summaryrefslogtreecommitdiff
path: root/test/getopt.t
blob: 48f7d9d93c3293a34be83c39a3fad83829405936 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/www/server/bin/php -qC
<?php

# Tests for getopt in it.class

$GLOBALS['usage'] = "Usage: doesnotexist.php [OPTIONS] POSITIONAL [VARARGS]
	Some help to a not existing program
	  -h,--help          the help argument
	  -a,--argument=ARG  the arg argument
	  -d,--default=ARG   an argument with default [defäult]
	  -0,--zero          testworthy shortarg
";

function getopt_ok($argv, $exp, $name)
{
	$_SERVER['argv'] = array_merge(['doesnotexist.php'], $argv);
	$got = it::getopt($GLOBALS['usage'], ['noexit' => true]);
	return is($got, $exp, $name);
}

foreach (["" => "blah gnaber", " (umlaute)" => "pre üäpost"] as $variant => $testarg) {
	$exp = ['args' => [], 'positional' => $testarg, 'argument' => $testarg, 'default' => 'defäult'];
	getopt_ok([$testarg, '-a', $testarg], $exp, "Short version" . $variant);
	getopt_ok([$testarg, '--argument', $testarg], $exp, "Long version with space" . $variant);
	getopt_ok([$testarg, "--argument=$testarg"], $exp, "Long version with equal" . $variant);
}

$exp = ['args' => [], 'positional' => 'posarg', 'zero' => true, 'default' => 'defäult'];
getopt_ok(['posarg', '-0'], $exp, 'short argument -0 without value');
getopt_ok(['posarg', '--zero'], $exp, 'long argument --zero without value');
getopt_ok(['posarg', '-0', 'vararg'], ['args' => ['vararg']] + $exp, "additional value after short argument -0");
getopt_ok(['posarg', '--zero', 'vararg'], ['args' => ['vararg']] + $exp, "additional value after long argument --zero");

fclose(STDERR);
getopt_ok(['posarg', '--unknown'], false, "Unknown long named argument fails");
getopt_ok(['posarg', '-u'], false, "Unknown short named argument fails");
getopt_ok([], false, "Missing positional argument fails");
getopt_ok(['posarg', '--argument'], false, "Missing long named argument fails");
getopt_ok(['posarg', '-a'], false, "Missing short named argument fails");

$GLOBALS['usage'] = it::replace(['\s*\[VARARGS\]' => ''], $GLOBALS['usage']);
getopt_ok(['posargs', 'vararg'], false, "Extra positional argument fails");
getopt_ok(['posargs', '--zero', 'vararg'], false, "Extra positional argument fails after long argument");
getopt_ok(['posargs', '-0', 'vararg'], false, "Extra positional argument fails after short argument");
getopt_ok(['posargs', '--argument', 'value', 'vararg'], false, "Extra positional argument fails after long argument with value");
getopt_ok(['posargs', '-a', 'value', 'vararg'], false, "Extra positional argument fails after short argument with value");