This commit is contained in:
2022-10-23 01:39:27 +02:00
parent 8c17aab483
commit 1929b84685
4130 changed files with 479334 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
<?php
/*
* This file is part of the {{ }} package.
*
* (c) Yo-An Lin <cornelius.howl@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
use GetOptionKit\Argument;
class ArgumentTest extends \PHPUnit\Framework\TestCase
{
function test()
{
$arg = new Argument( '--option' );
$this->assertTrue( $arg->isLongOption() );
$this->assertFalse( $arg->isShortOption() );
$this->assertEquals('option' , $arg->getOptionName());
$this->assertEquals(null, $arg->getOptionValue());
}
function test2()
{
$arg = new Argument('--option=value');
$this->assertNotNull( $arg->containsOptionValue() );
$this->assertEquals('value' , $arg->getOptionValue());
$this->assertEquals('option' , $arg->getOptionName());
}
function test3()
{
$arg = new Argument( '-abc' );
$this->assertNotNull( $arg->withExtraFlagOptions() );
$args = $arg->extractExtraFlagOptions();
$this->assertNotNull( $args );
$this->assertCount( 2, $args );
$this->assertEquals( '-b', $args[0] );
$this->assertEquals( '-c', $args[1] );
$this->assertEquals( '-a', $arg->arg);
}
function testZeroValue()
{
$arg = new Argument( '0' );
$this->assertFalse( $arg->isShortOption() );
$this->assertFalse( $arg->isLongOption() );
$this->assertFalse( $arg->isEmpty() );
}
}

View File

@@ -0,0 +1,335 @@
<?php
/*
* This file is part of the {{ }} package.
*
* (c) Yo-An Lin <cornelius.howl@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace tests\GetOptionKit;
use GetOptionKit\ContinuousOptionParser;
use GetOptionKit\OptionCollection;
class ContinuousOptionParserTest extends \PHPUnit\Framework\TestCase
{
public function testOptionCollection()
{
$specs = new OptionCollection;
$specVerbose = $specs->add('v|verbose');
$specColor = $specs->add('c|color');
$specDebug = $specs->add('d|debug');
}
public function argumentProvider()
{
return [
[
['program','subcommand1', 'arg1', 'arg2', 'arg3', 'subcommand2', '-b', 1, 'subcommand3', '-b', 2],
[
'args' => ['arg1', 'arg2', 'arg3']
],
],
[
['program','-v', '-c', 'subcommand1', '--as', 99, 'arg1', 'arg2', 'arg3'],
[
'app' => ['verbose' => true ],
'args' => ['arg1', 'arg2', 'arg3']
],
],
[
['program','-v', '-c', 'subcommand1', '--as', 99, 'arg1', 'arg2', 'arg3', '--','zz','xx','vv'],
[
'app' => ['verbose' => true],
'args' => ['arg1', 'arg2', 'arg3']
],
],
];
}
/**
* @dataProvider argumentProvider
*/
public function testParseSubCommandOptions($argv, $expected)
{
$appspecs = new OptionCollection;
$appspecs->add('v|verbose');
$appspecs->add('c|color');
$appspecs->add('d|debug');
$cmdspecs = new OptionCollection;
$cmdspecs->add('as:');
$cmdspecs->add('b:');
$cmdspecs->add('c:');
$cmdspecs->add('def:')->isa('number')->defaultValue(3);
$parser = new ContinuousOptionParser( $appspecs );
$subcommands = array('subcommand1','subcommand2','subcommand3');
$subcommand_specs = array(
'subcommand1' => clone $cmdspecs,
'subcommand2' => clone $cmdspecs,
'subcommand3' => clone $cmdspecs,
);
$subcommand_options = array();
// $argv = explode(' ','program -v -c subcommand1 --as 99 arg1 arg2 arg3 -- zz xx vv');
// $argv = explode(' ','program subcommand1 -a 1 subcommand2 -a 2 subcommand3 -a 3 arg1 arg2 arg3');
$app_options = $parser->parse( $argv );
$arguments = array();
while (! $parser->isEnd()) {
if (!empty($subcommands) && $parser->getCurrentArgument() == $subcommands[0]) {
$parser->advance();
$subcommand = array_shift($subcommands);
$parser->setSpecs($subcommand_specs[$subcommand]);
$subcommand_options[$subcommand] = $parser->continueParse();
} else {
$arguments[] = $parser->advance();
}
}
$this->assertSame($expected['args'], $arguments);
if (isset($expected['app'])) {
foreach ($expected['app'] as $k => $v) {
$this->assertEquals($v, $app_options->get($k));
}
}
// $this->assertEquals(99, $subcommand_options['subcommand1']->as);
}
public function testParser3()
{
$appspecs = new OptionCollection;
$appspecs->add('v|verbose');
$appspecs->add('c|color');
$appspecs->add('d|debug');
$cmdspecs = new OptionCollection;
$cmdspecs->add('n|name:=string');
$cmdspecs->add('p|phone:=string');
$cmdspecs->add('a|address:=string');
$subcommands = array('subcommand1','subcommand2','subcommand3');
$subcommand_specs = array(
'subcommand1' => $cmdspecs,
'subcommand2' => $cmdspecs,
'subcommand3' => $cmdspecs,
);
$subcommand_options = array();
$arguments = array();
$argv = explode(' ','program -v -d -c subcommand1 --name=c9s --phone=123123123 --address=somewhere arg1 arg2 arg3');
$parser = new ContinuousOptionParser( $appspecs );
$app_options = $parser->parse( $argv );
while (! $parser->isEnd()) {
if (@$subcommands[0] && $parser->getCurrentArgument() == $subcommands[0]) {
$parser->advance();
$subcommand = array_shift( $subcommands );
$parser->setSpecs( $subcommand_specs[$subcommand] );
$subcommand_options[ $subcommand ] = $parser->continueParse();
} else {
$arguments[] = $parser->advance();
}
}
$this->assertCount(3, $arguments);
$this->assertEquals('arg1', $arguments[0]);
$this->assertEquals('arg2', $arguments[1]);
$this->assertEquals('arg3', $arguments[2]);
$this->assertNotNull($subcommand_options['subcommand1']);
$this->assertEquals('c9s', $subcommand_options['subcommand1']->name );
$this->assertEquals('123123123', $subcommand_options['subcommand1']->phone );
$this->assertEquals('somewhere', $subcommand_options['subcommand1']->address );
}
/* test parser without options */
function testParser4()
{
$appspecs = new OptionCollection;
$appspecs->add('v|verbose');
$appspecs->add('c|color');
$appspecs->add('d|debug');
$cmdspecs = new OptionCollection;
$cmdspecs->add('a:'); // required
$cmdspecs->add('b?'); // optional
$cmdspecs->add('c+'); // multiple (required)
$parser = new ContinuousOptionParser( $appspecs );
$this->assertNotNull( $parser );
$subcommands = array('subcommand1','subcommand2','subcommand3');
$subcommand_specs = array(
'subcommand1' => clone $cmdspecs,
'subcommand2' => clone $cmdspecs,
'subcommand3' => clone $cmdspecs,
);
$subcommand_options = array();
$argv = explode(' ','program subcommand1 subcommand2 subcommand3 -a a -b b -c c');
$app_options = $parser->parse( $argv );
$arguments = array();
while( ! $parser->isEnd() ) {
if( @$subcommands[0] && $parser->getCurrentArgument() == $subcommands[0] ) {
$parser->advance();
$subcommand = array_shift( $subcommands );
$parser->setSpecs( $subcommand_specs[$subcommand] );
$subcommand_options[ $subcommand ] = $parser->continueParse();
} else {
$arguments[] = $parser->advance();
}
}
$this->assertNotNull( $subcommand_options );
$this->assertNotNull( $subcommand_options['subcommand1'] );
$this->assertNotNull( $subcommand_options['subcommand2'] );
$this->assertNotNull( $subcommand_options['subcommand3'] );
$r = $subcommand_options['subcommand3'];
$this->assertNotNull( $r );
$this->assertNotNull( $r->a , 'option a' );
$this->assertNotNull( $r->b , 'option b' );
$this->assertNotNull( $r->c , 'option c' );
$this->assertEquals( 'a', $r->a );
$this->assertEquals( 'b', $r->b );
$this->assertEquals( 'c', $r->c[0] );
}
/* test parser without options */
function testParser5()
{
$appspecs = new OptionCollection;
$appspecs->add('v|verbose');
$appspecs->add('c|color');
$appspecs->add('d|debug');
$cmdspecs = new OptionCollection;
$cmdspecs->add('a:');
$cmdspecs->add('b');
$cmdspecs->add('c');
$parser = new ContinuousOptionParser( $appspecs );
$this->assertNotNull( $parser );
$subcommands = array('subcommand1','subcommand2','subcommand3');
$subcommand_specs = array(
'subcommand1' => clone $cmdspecs,
'subcommand2' => clone $cmdspecs,
'subcommand3' => clone $cmdspecs,
);
$subcommand_options = array();
$argv = explode(' ','program subcommand1 -a 1 subcommand2 -a 2 subcommand3 -a 3 arg1 arg2 arg3');
$app_options = $parser->parse( $argv );
$arguments = array();
while (! $parser->isEnd()) {
if (!empty($subcommands) && $parser->getCurrentArgument() == $subcommands[0] ) {
$parser->advance();
$subcommand = array_shift( $subcommands );
$parser->setSpecs($subcommand_specs[$subcommand]);
$subcommand_options[ $subcommand ] = $parser->continueParse();
} else {
$arguments[] = $parser->advance();
}
}
$this->assertEquals( 'arg1', $arguments[0] );
$this->assertEquals( 'arg2', $arguments[1] );
$this->assertEquals( 'arg3', $arguments[2] );
$this->assertNotNull( $subcommand_options );
$this->assertEquals(1, $subcommand_options['subcommand1']->a);
$this->assertNotNull( 2, $subcommand_options['subcommand2']->a );
$this->assertNotNull( 3, $subcommand_options['subcommand3']->a );
}
/**
* @expectedException GetOptionKit\Exception\InvalidOptionException
*/
public function testParseInvalidOptionException()
{
$parser = new ContinuousOptionParser(new OptionCollection);
$parser->parse(array('app','--foo'));
$arguments = array();
while (!$parser->isEnd())
{
$arguments[] = $parser->getCurrentArgument();
$parser->advance();
}
}
public function testMultipleShortOption()
{
$options = new OptionCollection;
$options->add("a");
$options->add("b");
$options->add("c");
$parser = new ContinuousOptionParser($options);
$result = $parser->parse(array('app', '-ab', 'foo', 'bar'));
while (!$parser->isEnd())
{
$arguments[] = $parser->getCurrentArgument();
$parser->advance();
}
$this->assertTrue($result->keys["a"]->value);
$this->assertTrue($result->keys["b"]->value);
}
public function testIncrementalValue()
{
$options = new OptionCollection;
$options->add("v|verbose")->incremental();
$parser = new ContinuousOptionParser($options);
$result = $parser->parse(array('app', '-vvv'));
$this->assertEquals(3, $result->keys["verbose"]->value);
}
/**
* @expectedException GetOptionKit\Exception\InvalidOptionException
*/
public function testUnknownOption()
{
$options = new OptionCollection;
$options->add("v|verbose");
$parser = new ContinuousOptionParser($options);
$result = $parser->parse(array('app', '-b'));
}
/**
* @expectedException LogicException
*/
public function testAdvancedOutOfBounds()
{
$options = new OptionCollection;
$options->add("v|verbose");
$parser = new ContinuousOptionParser($options);
$result = $parser->parse(array('app', '-v'));
$parser->advance();
}
}

View File

@@ -0,0 +1,46 @@
<?php
use GetOptionKit\Option;
use GetOptionKit\OptionCollection;
class OptionCollectionTest extends \PHPUnit\Framework\TestCase
{
public function testAddOption()
{
$opts = new OptionCollection;
$opts->add($o = new Option('v|verbose'));
$this->assertSame($o, $opts->getLongOption('verbose'));
$this->assertSame($o, $opts->getShortOption('v'));
}
/**
* @expectedException LogicException
*/
public function testAddInvalidOption()
{
$opts = new OptionCollection;
$opts->add(123);
}
/**
* @expectedException GetOptionKit\Exception\OptionConflictException
*/
public function testOptionConflictShort()
{
$opts = new OptionCollection;
$opts->add('r|repeat');
$opts->add('t|time');
$opts->add('r|regex');
}
/**
* @expectedException GetOptionKit\Exception\OptionConflictException
*/
public function testOptionConflictLong()
{
$opts = new OptionCollection;
$opts->add('r|repeat');
$opts->add('t|time');
$opts->add('c|repeat');
}
}

View File

@@ -0,0 +1,477 @@
<?php
/*
* This file is part of the GetOptionKit package.
*
* (c) Yo-An Lin <cornelius.howl@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
use GetOptionKit\InvalidOptionValue;
use GetOptionKit\OptionCollection;
use GetOptionKit\OptionParser;
use GetOptionKit\Option;
class OptionParserTest extends \PHPUnit\Framework\TestCase
{
public $parser;
public $specs;
public function setUp()
{
$this->specs = new OptionCollection;
$this->parser = new OptionParser($this->specs);
}
/**
* @expectedException Exception
*/
public function testInvalidOption()
{
$options = new OptionCollection;
$options->addOption(new Option(0));
}
public function testResultArrayAccessor()
{
$options = new OptionCollection;
$options->add('n|nice:' , 'I take negative value');
$parser = new OptionParser($options);
$result = $parser->parse(array('a', '-n', '-1', '--', '......'));
$this->assertTrue(isset($result->nice));
$this->assertTrue($result->has('nice'));
$this->assertTrue(isset($result['nice']));
$this->assertEquals(-1, $result['nice']->value);
$res = clone $result['nice'];
$res->value = 10;
$result['nice'] = $res;
$this->assertEquals(10, $result['nice']->value);
unset($result['nice']);
}
public function testCamelCaseOptionName()
{
$this->specs->add('base-dir:=dir' , 'I take path');
$result = $this->parser->parse(array('a', '--base-dir', 'src'));
$this->assertInstanceOf('SplFileInfo', $result->baseDir);
}
public function testOptionWithNegativeValue()
{
$this->specs->add('n|nice:' , 'I take negative value');
$result = $this->parser->parse(array('a', '-n', '-1'));
$this->assertEquals(-1, $result->nice);
}
public function testShortOptionName()
{
$this->specs->add('f:' , 'file');
$result = $this->parser->parse(array('a', '-f', 'aaa'));
$this->assertEquals('aaa',$result['f']->getValue());
}
public function testOptionWithShortNameAndLongName()
{
$this->specs->add( 'f|foo' , 'flag' );
$result = $this->parser->parse(array('a', '-f'));
$this->assertTrue($result->foo);
$result = $this->parser->parse(array('a', '--foo'));
$this->assertTrue($result->foo);
}
public function testSpec()
{
$options = new OptionCollection;
$options->add( 'f|foo:' , 'option require value' );
$options->add( 'b|bar+' , 'option with multiple value' );
$options->add( 'z|zoo?' , 'option with optional value' );
$options->add( 'v|verbose' , 'verbose message' );
$options->add( 'd|debug' , 'debug message' );
$this->assertEquals(5, $options->size());
$this->assertEquals(5, count($options));
$opt = $options->get('foo');
$this->assertTrue($opt->isRequired());
$opt = $options->get('bar');
$this->assertTrue( $opt->isMultiple() );
$opt = $options->get('zoo');
$this->assertTrue( $opt->isOptional() );
$opt = $options->get( 'debug' );
$this->assertNotNull( $opt );
$this->assertInstanceOf('GetOptionKit\\Option', $opt);
$this->assertEquals('debug', $opt->long);
$this->assertEquals('d', $opt->short);
$this->assertTrue($opt->isFlag());
return $options;
}
/**
* @depends testSpec
*/
public function testOptionFinder($options)
{
$this->assertNotNull($options->find('f'));
$this->assertNotNull($options->find('foo'));
$this->assertNull($options->find('xyz'));
}
public function testRequire()
{
$this->specs->add( 'f|foo:' , 'option require value' );
$this->specs->add( 'b|bar+' , 'option with multiple value' );
$this->specs->add( 'z|zoo?' , 'option with optional value' );
$this->specs->add( 'v|verbose' , 'verbose message' );
$this->specs->add( 'd|debug' , 'debug message' );
$firstExceptionRaised = false;
$secondExceptionRaised = false;
// option required a value should throw an exception
try {
$result = $this->parser->parse( array('a', '-f' , '-v' , '-d' ) );
}
catch (Exception $e) {
$firstExceptionRaised = true;
}
// even if only one option presented in args array
try {
$result = $this->parser->parse(array('a','-f'));
} catch (Exception $e) {
$secondExceptionRaised = true;
}
if ($firstExceptionRaised && $secondExceptionRaised) {
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testMultiple()
{
$opt = new OptionCollection;
$opt->add( 'b|bar+' , 'option with multiple value' );
$parser = new OptionParser($opt);
$result = $parser->parse(explode(' ','app -b 1 -b 2 --bar 3'));
$this->assertNotNull($result->bar);
$this->assertCount(3,$result->bar);
}
public function testMultipleNumber()
{
$opt = new OptionCollection;
$opt->add('b|bar+=number' , 'option with multiple value');
$parser = new OptionParser($opt);
$result = $parser->parse(explode(' ','app --bar 1 --bar 2 --bar 3'));
$this->assertNotNull($result->bar);
$this->assertCount(3,$result->bar);
$this->assertSame(array(1,2,3),$result->bar);
}
public function testSimpleOptionWithDefaultValue()
{
$opts = new OptionCollection;
$opts->add('p|proc=number' , 'option with required value')
->defaultValue(10)
;
$parser = new OptionParser($opts);
$result = $parser->parse(explode(' ','app'));
$this->assertEquals(10, $result['proc']->value);
}
public function testOptionalOptionWithDefaultValue()
{
$opts = new OptionCollection;
$opts->add('p|proc?=number' , 'option with required value')
->defaultValue(10)
;
$parser = new OptionParser($opts);
$result = $parser->parse(explode(' ','app --proc'));
$this->assertEquals(10, $result['proc']->value);
}
public function testMultipleString()
{
$opts = new OptionCollection;
$opts->add('b|bar+=string' , 'option with multiple value');
$bar = $opts->get('bar');
$this->assertNotNull($bar);
$this->assertTrue($bar->isMultiple());
$this->assertTrue($bar->isType('string'));
$this->assertFalse($bar->isType('number'));
$parser = new OptionParser($opts);
$result = $parser->parse(explode(' ','app --bar lisa --bar mary --bar john a b c'));
$this->assertNotNull($result->bar);
$this->assertCount(3,$result->bar);
$this->assertSame(array('lisa', 'mary', 'john'),$result->bar);
$this->assertSame(array('a','b','c'), $result->getArguments());
}
public function testParseIncrementalOption()
{
$opts = new OptionCollection;
$opts->add('v|verbose' , 'verbose')
->isa("number")
->incremental();
$parser = new OptionParser($opts);
$result = $parser->parse(explode(' ','app -vvv arg1 arg2'));
$this->assertInstanceOf('GetOptionKit\Option',$result['verbose']);
$this->assertNotNull($result['verbose']);
$this->assertEquals(3, $result['verbose']->value);
}
/**
* @expectedException Exception
*/
public function testIntegerTypeNonNumeric()
{
$opt = new OptionCollection;
$opt->add( 'b|bar:=number' , 'option with integer type' );
$parser = new OptionParser($opt);
$spec = $opt->get('bar');
$this->assertTrue($spec->isTypeNumber());
// test non numeric
$result = $parser->parse(explode(' ','app -b test'));
$this->assertNotNull($result->bar);
}
public function testIntegerTypeNumericWithoutEqualSign()
{
$opt = new OptionCollection;
$opt->add('b|bar:=number', 'option with integer type');
$spec = $opt->get('bar');
$this->assertTrue($spec->isTypeNumber());
$parser = new OptionParser($opt);
$result = $parser->parse(explode(' ','app -b 123123'));
$this->assertNotNull($result);
$this->assertEquals(123123, $result->bar);
}
public function testIntegerTypeNumericWithEqualSign()
{
$opt = new OptionCollection;
$opt->add('b|bar:=number' , 'option with integer type');
$spec = $opt->get('bar');
$this->assertTrue($spec->isTypeNumber());
$parser = new OptionParser($opt);
$result = $parser->parse(explode(' ','app -b=123123'));
$this->assertNotNull($result);
$this->assertNotNull($result->bar);
$this->assertEquals(123123, $result->bar);
}
public function testStringType()
{
$this->specs->add( 'b|bar:=string' , 'option with type' );
$spec = $this->specs->get('bar');
$result = $this->parser->parse(explode(' ','app -b text arg1 arg2 arg3'));
$this->assertNotNull($result->bar);
$result = $this->parser->parse(explode(' ','app -b=text arg1 arg2 arg3'));
$this->assertNotNull($result->bar);
$args = $result->getArguments();
$this->assertNotEmpty($args);
$this->assertCount(3,$args);
$this->assertEquals('arg1', $args[0]);
$this->assertEquals('arg2', $args[1]);
$this->assertEquals('arg3', $args[2]);
}
public function testStringQuoteOptionValue()
{
$opts = new OptionCollection();
$opts->add('f|foo:' , 'option requires a value.');
$parser = new OptionParser($opts);
$res = $parser->parse(['app','--foo=aa bb cc']);
$this->assertEquals('aa bb cc', $res->get('foo'));
}
public function testSpec2()
{
$this->specs->add('long' , 'long option name only.');
$this->specs->add('a' , 'short option name only.');
$this->specs->add('b' , 'short option name only.');
$this->assertNotNull($this->specs->all());
$this->assertNotNull($this->specs);
$this->assertNotNull($result = $this->parser->parse(explode(' ','app -a -b --long')) );
$this->assertNotNull($result->a);
$this->assertNotNull($result->b);
}
public function testSpecCollection()
{
$this->specs->add( 'f|foo:' , 'option requires a value.' );
$this->specs->add( 'b|bar+' , 'option with multiple value.' );
$this->specs->add( 'z|zoo?' , 'option with optional value.' );
$this->specs->add( 'v|verbose' , 'verbose message.' );
$this->specs->add( 'd|debug' , 'debug message.' );
$this->specs->add( 'long' , 'long option name only.' );
$this->specs->add( 's' , 'short option name only.' );
$this->assertNotNull( $this->specs->all() );
$this->assertNotNull( $this->specs );
$this->assertCount( 7 , $array = $this->specs->toArray() );
$this->assertNotEmpty( isset($array[0]['long'] ));
$this->assertNotEmpty( isset($array[0]['short'] ));
$this->assertNotEmpty( isset($array[0]['desc'] ));
}
public function optionTestProvider()
{
return array(
array( 'foo', 'simple boolean option', 'foo', true,
[['a','--foo','a', 'b', 'c']]
),
array( 'f|foo', 'simple boolean option', 'foo', true,
[['a','--foo'], ['a','-f']]
),
array( 'f|foo:=string', 'string option', 'foo', 'xxx',
[['a','--foo','xxx'], ['a','-f', 'xxx']]
),
array( 'f|foo:=string', 'string option', 'foo', 'xxx',
[['a','b', 'c', '--foo','xxx'], ['a', 'a', 'b', 'c', '-f', 'xxx']]
),
);
}
/**
* @dataProvider optionTestProvider
*/
public function test($specString, $desc, $key, $expectedValue, array $argvList)
{
$opts = new OptionCollection();
$opts->add($specString, $desc);
$parser = new OptionParser($opts);
foreach ($argvList as $argv) {
$res = $parser->parse($argv);
$this->assertSame($expectedValue, $res->get($key));
}
}
/**
* @expectedException Exception
*/
public function testParseWithoutProgramName()
{
$parser = new OptionParser(new OptionCollection);
$parser->parse(array('--foo'));
}
/**
* @expectedException GetOptionKit\Exception\InvalidOptionException
*/
public function testParseInvalidOptionException()
{
$parser = new OptionParser(new OptionCollection);
$parser->parse(array('app','--foo'));
}
/**
* @expectedException GetOptionKit\Exception\RequireValueException
*/
public function testParseOptionRequireValueException()
{
$options = new OptionCollection;
$options->add('name:=string', 'name');
$parser = new OptionParser($options);
$parser->parse(array('app','--name'));
}
public function testMore()
{
$this->specs->add('f|foo:' , 'option require value' );
$this->specs->add('b|bar+' , 'option with multiple value' );
$this->specs->add('z|zoo?' , 'option with optional value' );
$this->specs->add('v|verbose' , 'verbose message' );
$this->specs->add('d|debug' , 'debug message' );
$result = $this->parser->parse( array('a', '-f' , 'foo value' , '-v' , '-d' ) );
$this->assertNotNull($result->foo);
$this->assertNotNull($result->verbose);
$this->assertNotNull($result->debug);
$this->assertEquals( 'foo value', $result->foo );
$this->assertNotNull( $result->verbose );
$this->assertNotNull( $result->debug );
foreach ($result as $k => $v) {
$this->assertTrue(in_array($k, ['foo','bar','zoo','verbose', 'debug']));
$this->assertInstanceOf('GetOptionKit\\Option', $v);
}
$this->assertSame([
'foo' => 'foo value',
'verbose' => true,
'debug' => true
], $result->toArray());
$result = $this->parser->parse( array('a', '-f=foo value' , '-v' , '-d' ) );
$this->assertNotNull( $result );
$this->assertNotNull( $result->foo );
$this->assertNotNull( $result->verbose );
$this->assertNotNull( $result->debug );
$this->assertEquals( 'foo value', $result->foo );
$this->assertNotNull( $result->verbose );
$this->assertNotNull( $result->debug );
$result = $this->parser->parse( array('a', '-vd' ) );
$this->assertNotNull( $result->verbose );
$this->assertNotNull( $result->debug );
}
public function testParseAcceptsValidOption()
{
$this->specs
->add('f:foo', 'test option')
->validator(function($value) {
return $value === 'valid-option';
});
$result = $this->parser->parse(array('a', '-f' , 'valid-option'));
$this->assertArrayHasKey('f', $result);
}
/**
* @expectedException GetOptionKit\Exception\InvalidOptionValueException
*/
public function testParseThrowsExceptionOnInvalidOption()
{
$this->specs
->add('f:foo', 'test option')
->validator(function($value) {
return $value === 'valid-option';
});
$this->parser->parse(array('a', '-f' , 'not-a-valid-option'));
}
}

View File

@@ -0,0 +1,32 @@
<?php
use GetOptionKit\OptionPrinter\ConsoleOptionPrinter;
use GetOptionKit\OptionCollection;
class ConsoleOptionPrinterTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
$options = new OptionCollection;
$options->add('f|foo:', 'option requires a value.' )
->isa('String');
$options->add('b|bar+', 'option with multiple value.' )
->isa('Number');
$options->add('z|zoo?', 'option with optional value.' )
->isa('Boolean')
;
$options->add('n', 'n flag' );
$options->add('verbose', 'verbose');
$options->add('o|output?', 'option with optional value.' )
->isa('File')
->defaultValue('output.txt')
;
$printer = new ConsoleOptionPrinter;
$output = $printer->render($options);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the GetOptionKit package.
*
* (c) Yo-An Lin <cornelius.howl@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
class OptionResultTest extends \PHPUnit\Framework\TestCase
{
function testOption()
{
$option = new \GetOptionKit\OptionResult;
$this->assertNotNull( $option );
$specs = new \GetOptionKit\OptionCollection;
$specs->add('name:','name');
$result = \GetOptionKit\OptionResult::create($specs,array( 'name' => 'c9s' ),array( 'arg1' ));
$this->assertNotNull( $result );
$this->assertNotNull( $result->arguments );
$this->assertNotNull( $result->name );
$this->assertEquals( 'c9s', $result->name );
$this->assertEquals( $result->arguments[0] , 'arg1' );
}
}

View File

@@ -0,0 +1,227 @@
<?php
use GetOptionKit\Option;
class OptionTest extends \PHPUnit\Framework\TestCase
{
public function optionSpecDataProvider() {
return [
['i'],
['f'],
['a=number'],
// long options
['n|name'],
['e|email'],
];
}
/**
* @dataProvider optionSpecDataProvider
*/
public function testOptionSpec($spec)
{
$opt = new Option($spec);
$this->assertNotNull($opt);
}
/**
* @expectedException Exception
*/
public function testInvalidOptionSpec()
{
new Option('....');
}
public function testValueName()
{
$opt = new Option('z');
$opt->defaultValue(10);
$opt->valueName('priority');
$this->assertEquals('[=priority]', $opt->renderValueHint());
$this->assertEquals('-z[=priority]', $opt->renderReadableSpec());
}
public function testDefaultValue()
{
$opt = new Option('z');
$opt->defaultValue(10);
$this->assertEquals(10, $opt->getValue());
$this->assertEquals('-z[=10]',$opt->renderReadableSpec(true));
}
public function testBackwardCompatibleBoolean()
{
$opt = new Option('scope');
$opt->isa('bool');
$this->assertEquals('boolean', $opt->isa);
$this->assertEquals('--scope=<boolean>',$opt->renderReadableSpec(true));
}
public function validatorProvider()
{
return [
[function($a) { return in_array($a, ['public', 'private']); }],
[function($a) { return [in_array($a, ['public', 'private']), "message"]; }]
];
}
/**
* @dataProvider validatorProvider
*/
public function testValidator($cb)
{
$opt = new Option('scope');
$opt->validator($cb);
$ret = $opt->validate('public');
$this->assertTrue($ret[0]);
$ret = $opt->validate('private');
$this->assertTrue($ret[0]);
$ret = $opt->validate('foo');
$this->assertFalse($ret[0]);
$this->assertEquals('--scope', $opt->renderReadableSpec(true));
}
/**
* @expectedException Exception
*/
public function testInvalidTypeClass()
{
$opt = new Option('scope');
$opt->isa('SomethingElse');
$class = $opt->getTypeClass();
}
/**
* @expectedException InvalidArgumentException
*/
public function testValidatorReturnValue()
{
$opt = new Option('scope');
$opt->validator(function($val) {
return 123454;
});
$ret = $opt->validate('public');
}
public function testOptionWithoutValidator()
{
$opt = new Option('scope');
$ret = $opt->validate('public');
$this->assertTrue($ret[0]);
$ret = $opt->validate('private');
$this->assertTrue($ret[0]);
$ret = $opt->validate('foo');
$this->assertTrue($ret[0]);
$this->assertEquals('--scope',$opt->renderReadableSpec(true));
}
public function testSuggestionsCallback()
{
$opt = new Option('scope');
$this->assertEmpty($opt->getSuggestions());
$opt->suggestions(function() {
return ['public', 'private'];
});
$this->assertNotEmpty($opt->getSuggestions());
$this->assertSame(['public', 'private'],$opt->getSuggestions());
$opt->setValue('public');
$opt->setValue('private');
$this->assertEquals('private',$opt->value);
$this->assertEquals('--scope=[public,private]',$opt->renderReadableSpec(true));
}
public function testSuggestions()
{
$opt = new Option('scope');
$opt->suggestions(['public', 'private']);
$this->assertNotEmpty($opt->getSuggestions());
$this->assertSame(['public', 'private'],$opt->getSuggestions());
$opt->setValue('public');
$opt->setValue('private');
$this->assertEquals('private',$opt->value);
$this->assertEquals('--scope=[public,private]',$opt->renderReadableSpec(true));
}
public function testValidValuesCallback() {
$opt = new Option('scope');
$opt->validValues(function() {
return ['public', 'private'];
});
$this->assertNotNull($opt->getValidValues());
$this->assertNotEmpty($opt->getValidValues());
$opt->setValue('public');
$opt->setValue('private');
$this->assertEquals('private',$opt->value);
$this->assertEquals('--scope=(public,private)',$opt->renderReadableSpec(true));
}
public function testTrigger()
{
$opt = new Option('scope');
$opt->validValues([ 'public', 'private' ]);
$state = 0;
$opt->trigger(function($val) use(& $state) {
$state++;
});
$this->assertNotEmpty($opt->getValidValues());
$opt->setValue('public');
$this->assertEquals(1, $state);
$opt->setValue('private');
$this->assertEquals(2, $state);
}
public function testArrayValueToString()
{
$opt = new Option('uid');
$opt->setValue([1,2,3,4]);
$toString = '* key:uid spec:--uid desc:
value => 1,2,3,4
';
$this->assertEquals($toString,$opt->__toString());
}
public function testValidValues()
{
$opt = new Option('scope');
$opt->validValues([ 'public', 'private' ])
;
$this->assertNotEmpty($opt->getValidValues());
$this->assertTrue(is_array($opt->getValidValues()));
$opt->setValue('public');
$opt->setValue('private');
$this->assertEquals('private',$opt->value);
$this->assertEquals('--scope=(public,private)',$opt->renderReadableSpec(true));
$this->assertNotEmpty($opt->__toString());
}
public function testFilter() {
$opt = new Option('scope');
$opt->filter(function($val) {
return preg_replace('#a#', 'x', $val);
})
;
$opt->setValue('aa');
$this->assertEquals('xx', $opt->value);
}
}

View File

@@ -0,0 +1,26 @@
<?php
use GetOptionKit\ValueType\RegexType;
class RegexValueTypeTest extends \PHPUnit\Framework\TestCase
{
public function testOption()
{
$regex = new RegexType('#^Test$#');
$this->assertEquals($regex->option, '#^Test$#');
}
public function testValidation()
{
$regex = new RegexType('#^Test$#');
$this->assertTrue($regex->test('Test'));
$this->assertFalse($regex->test('test'));
$regex->option = '/^([a-z]+)$/';
$this->assertTrue($regex->test('barfoo'));
$this->assertFalse($regex->test('foobar234'));
$ret = $regex->parse('foobar234');
$this->assertNotNull($ret);
}
}

View File

@@ -0,0 +1,200 @@
<?php
use GetOptionKit\ValueType\BooleanType;
use GetOptionKit\ValueType\StringType;
use GetOptionKit\ValueType\FileType;
use GetOptionKit\ValueType\DirType;
use GetOptionKit\ValueType\NumberType;
use GetOptionKit\ValueType\UrlType;
use GetOptionKit\ValueType\IpType;
use GetOptionKit\ValueType\Ipv4Type;
use GetOptionKit\ValueType\Ipv6Type;
use GetOptionKit\ValueType\EmailType;
use GetOptionKit\ValueType\PathType;
use GetOptionKit\ValueType\DateType;
use GetOptionKit\ValueType\DateTimeType;
use GetOptionKit\ValueType\RegexType;
class ValueTypeTest extends \PHPUnit\Framework\TestCase
{
public function testTypeClass()
{
$this->assertNotNull( new BooleanType );
$this->assertNotNull( new StringType );
$this->assertNotNull( new FileType );
$this->assertNotNull( new DateType );
$this->assertNotNull( new DateTimeType );
$this->assertNotNull( new NumberType );
$this->assertNotNull( new UrlType );
$this->assertNotNull( new IpType );
$this->assertNotNull( new Ipv4Type );
$this->assertNotNull( new Ipv6Type );
$this->assertNotNull( new EmailType );
$this->assertNotNull( new PathType );
$this->assertNotNull( new RegexType("/[a-z]/"));
}
public function testDateTimeType()
{
$type = new DateTimeType([ 'format' => 'Y-m-d' ]);
$this->assertTrue($type->test('2016-12-30'));
$a = $type->parse('2016-12-30');
$this->assertEquals(2016, $a->format('Y'));
$this->assertEquals(12, $a->format('m'));
$this->assertEquals(30, $a->format('d'));
$this->assertFalse($type->test('foo'));
}
public function testDateType()
{
$type = new DateType;
$this->assertTrue($type->test('2016-12-30'));
$a = $type->parse('2016-12-30');
$this->assertEquals(2016, $a['year']);
$this->assertEquals(12, $a['month']);
$this->assertEquals(30, $a['day']);
$this->assertFalse($type->test('foo'));
}
public function booleanTestProvider()
{
return [
[true , true, true],
[false , true, false],
['true' , true, true],
['false' , true, false],
['0' , true, false],
['1' , true, true],
['foo' , false, null],
['123' , false, null],
];
}
/**
* @dataProvider booleanTestProvider
*/
public function testBooleanType($a, $test, $expected)
{
$bool = new BooleanType;
$this->assertEquals($test, $bool->test($a));
if ($bool->test($a)) {
$this->assertEquals($expected, $bool->parse($a));
}
}
public function testDirType()
{
$type = new DirType;
$this->assertTrue($type->test('tests'));
$this->assertFalse($type->test('composer.json'));
$this->assertFalse($type->test('foo/bar'));
$this->assertInstanceOf('SplFileInfo',$type->parse('tests'));
}
public function testFileType()
{
$type = new FileType;
$this->assertFalse($type->test('tests'));
$this->assertTrue($type->test('composer.json'));
$this->assertFalse($type->test('foo/bar'));
$this->assertInstanceOf('SplFileInfo', $type->parse('composer.json'));
}
public function testPathType()
{
$type = new PathType;
$this->assertTrue($type->test('tests'));
$this->assertTrue($type->test('composer.json'));
$this->assertFalse($type->test('foo/bar'));
$this->assertInstanceOf('SplFileInfo', $type->parse('composer.json'));
}
public function testUrlType()
{
$url = new UrlType;
$this->assertTrue($url->test('http://t'));
$this->assertTrue($url->test('http://t.c'));
$this->assertFalse($url->test('t.c'));
$this->assertEquals('http://t.c', $url->parse('http://t.c'));
}
public function ipV4Provider()
{
return [
['192.168.25.58', true],
['8.8.8.8', true],
['github.com', false],
];
}
public function ipV6Provider()
{
return [
['192.168.25.58', false],
['2607:f0d0:1002:51::4', true],
['2607:f0d0:1002:0051:0000:0000:0000:0004', true],
['::1', true],
['10.10.15.10/16', false],
['github.com', false],
];
}
public function ipProvider()
{
return [
['192.168.25.58', true],
['2607:f0d0:1002:51::4', true],
['::1', true],
['10.10.15.10/16', false],
['github.com', false],
];
}
/**
* @dataProvider ipProvider
*/
public function testIpType($ipstr, $pass = true)
{
$ip = new IpType;
$this->assertEquals($pass, $ip->test($ipstr));
if ($pass) {
$this->assertNotNull($ip->parse($ipstr));
}
}
/**
* @dataProvider ipV4Provider
*/
public function testIpv4Type($ipstr, $pass = true)
{
$ipv4 = new Ipv4Type;
$this->assertEquals($pass, $ipv4->test($ipstr));
if ($pass) {
$this->assertNotNull($ipv4->parse($ipstr));
}
}
/**
* @dataProvider ipV6Provider
*/
public function testIpv6Type($ipstr, $pass = true)
{
$ipv6 = new Ipv6Type;
$this->assertEquals($pass, $ipv6->test($ipstr));
if ($pass) {
$this->assertNotNull($ipv6->parse($ipstr));
}
}
public function testEmailType()
{
$email = new EmailType;
$this->assertTrue($email->test('test@gmail.com'));
$this->assertFalse($email->test('test@test'));
$email->parse('test@gmail.com');
}
}