add more tests for getopts

This commit is contained in:
Luke Sampson
2013-09-02 23:45:54 +10:00
parent dea0d9f409
commit b28eca4efd
3 changed files with 33 additions and 4 deletions
+18 -1
View File
@@ -33,7 +33,10 @@ function getopt($argv, $shortopts, $longopts) {
$opts, $rem, $msg
}
# ensure these are arrays
$argv = @($argv)
$longopts = @($longopts)
for($i = 0; $i -lt $argv.length; $i++) {
$arg = $argv[$i]
@@ -56,7 +59,21 @@ function getopt($argv, $shortopts, $longopts) {
}
} elseif($arg.startswith('-') -and $arg -ne '-') {
for($j = 1; $j -lt $arg.length; $j++) {
$letter = $arg[$j]
$letter = $arg[$j].tostring()
if($shortopts -match "$letter`:?") {
$shortopt = $matches[0]
if($shortopt[1] -eq ':') {
if($j -ne $arg.length -1 -or $i -eq $argv.length) {
return err "option -$letter requires an argument"
}
$opts.$letter = $argv[++$i]
} else {
$opts.$letter = $true
}
} else {
return err "option -$letter not recognized"
}
}
}
}
+7
View File
@@ -5,6 +5,7 @@ $a = "--global -a 32bit test" -split ' '
$opt, $rem, $err = getopt $a "ga:" "global", "arch="
assert $err -eq $null
assert $opt.global -eq $true
assert $opt.a -eq "32bit"
@@ -13,4 +14,10 @@ $null, $null, $err = getopt "--non-exist", "", ""
assert $err -ne $null
assert $err -eq "option --non-exist not recognized"
$null, $null, $err = getopt "--arb" "" "arb="
assert $err -eq "option --arb requires an argument"
$null, $null, $err = getopt "-az" "a" ""
assert $err -eq "option -z not recognized"
test_results
+8 -3
View File
@@ -7,10 +7,15 @@ function fail($msg) {
$script = split-path $invoked.scriptname -leaf
$line = $invoked.scriptlinenumber
write-host "FAIL: $msg ($script line $line)" -f red
write-host "FAIL: $msg" -f red
write-host $invoked.positionmessage
}
function fmt($var) {
if($var -is [string]) { return "'$var'" }
return $var
}
function assert(
$x,$eq='__undefined',$ne='__undefined') {
$script:run++
@@ -20,11 +25,11 @@ function assert(
}
if($eq -ne "__undefined") {
if($x -ne $eq) { fail "$x != $eq" }
if($x -ne $eq) { fail "$(fmt($x)) != $(fmt($eq))" }
}
if($ne -ne "__undefined") {
if($x -eq $ne) { fail "$x == $ne" }
if($x -eq $ne) { fail "$(fmt($x)) == $(fmt($ne))" }
}
}