PageRenderTime 60ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/Zend/Console/GetoptTest.php

https://bitbucket.org/aboozar/zf2
PHP | 626 lines | 500 code | 88 blank | 38 comment | 2 complexity | ae316d85d428e3f156acf67e54865562 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. * @package Zend_Console
  9. */
  10. namespace ZendTest\Console;
  11. use Zend\Console\Getopt;
  12. use Zend\Console\GetoptException;
  13. /**
  14. * @category Zend
  15. * @package Zend_Console
  16. * @subpackage UnitTests
  17. * @group Zend_Console
  18. */
  19. class GetoptTest extends \PHPUnit_Framework_TestCase
  20. {
  21. public function setUp()
  22. {
  23. if(ini_get('register_argc_argv') == false) {
  24. $this->markTestSkipped("Cannot Test Zend\\Console\\Getopt without 'register_argc_argv' ini option true.");
  25. }
  26. $_SERVER['argv'] = array('getopttest');
  27. }
  28. public function testGetoptShortOptionsGnuMode()
  29. {
  30. $opts = new Getopt('abp:', array('-a', '-p', 'p_arg'));
  31. $this->assertEquals(true, $opts->a);
  32. $this->assertNull(@$opts->b);
  33. $this->assertEquals($opts->p, 'p_arg');
  34. }
  35. public function testGetoptLongOptionsZendMode()
  36. {
  37. $opts = new Getopt(array(
  38. 'apple|a' => 'Apple option',
  39. 'banana|b' => 'Banana option',
  40. 'pear|p=s' => 'Pear option'
  41. ),
  42. array('-a', '-p', 'p_arg'));
  43. $this->assertTrue($opts->apple);
  44. $this->assertNull(@$opts->banana);
  45. $this->assertEquals($opts->pear, 'p_arg');
  46. }
  47. public function testGetoptZendModeEqualsParam()
  48. {
  49. $opts = new Getopt(array(
  50. 'apple|a' => 'Apple option',
  51. 'banana|b' => 'Banana option',
  52. 'pear|p=s' => 'Pear option'
  53. ),
  54. array('--pear=pear.phpunit.de'));
  55. $this->assertEquals($opts->pear, 'pear.phpunit.de');
  56. }
  57. public function testGetoptToString()
  58. {
  59. $opts = new Getopt('abp:', array('-a', '-p', 'p_arg'));
  60. $this->assertEquals($opts->__toString(), 'a=true p=p_arg');
  61. }
  62. public function testGetoptDumpString()
  63. {
  64. $opts = new Getopt('abp:', array('-a', '-p', 'p_arg'));
  65. $this->assertEquals($opts->toString(), 'a=true p=p_arg');
  66. }
  67. public function testGetoptDumpArray()
  68. {
  69. $opts = new Getopt('abp:', array('-a', '-p', 'p_arg'));
  70. $this->assertEquals(implode(',', $opts->toArray()), 'a,p,p_arg');
  71. }
  72. public function testGetoptDumpJson()
  73. {
  74. $opts = new Getopt('abp:', array('-a', '-p', 'p_arg'));
  75. $this->assertEquals($opts->toJson(),
  76. '{"options":[{"option":{"flag":"a","parameter":true}},{"option":{"flag":"p","parameter":"p_arg"}}]}');
  77. }
  78. public function testGetoptDumpXml()
  79. {
  80. $opts = new Getopt('abp:', array('-a', '-p', 'p_arg'));
  81. $this->assertEquals($opts->toXml(),
  82. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<options><option flag=\"a\"/><option flag=\"p\" parameter=\"p_arg\"/></options>\n");
  83. }
  84. public function testGetoptExceptionForMissingFlag()
  85. {
  86. $this->setExpectedException('\Zend\Console\Exception\InvalidArgumentException', 'Blank flag not allowed in rule');
  87. $opts = new Getopt(array('|a'=>'Apple option'));
  88. }
  89. public function testGetoptExceptionForKeyWithDuplicateFlagsViaOrOperator()
  90. {
  91. $this->setExpectedException('\Zend\Console\Exception\InvalidArgumentException', 'defined more than once');
  92. $opts = new Getopt(
  93. array('apple|apple'=>'apple-option'));
  94. }
  95. public function testGetoptExceptionForKeysThatDuplicateFlags()
  96. {
  97. $this->setExpectedException('\Zend\Console\Exception\InvalidArgumentException', 'defined more than once');
  98. $opts = new Getopt(
  99. array('a'=>'Apple option', 'apple|a'=>'Apple option'));
  100. }
  101. public function testGetoptAddRules()
  102. {
  103. $opts = new Getopt(
  104. array(
  105. 'apple|a' => 'Apple option',
  106. 'banana|b' => 'Banana option'
  107. ),
  108. array('--pear', 'pear_param'));
  109. try {
  110. $opts->parse();
  111. $this->fail('Expected to catch Zend\Console\Exception\RuntimeException');
  112. } catch (\Zend\Console\Exception\RuntimeException $e) {
  113. $this->assertEquals($e->getMessage(), 'Option "pear" is not recognized.');
  114. }
  115. $opts->addRules(array('pear|p=s' => 'Pear option'));
  116. $this->assertEquals($opts->pear, 'pear_param');
  117. }
  118. public function testGetoptExceptionMissingParameter()
  119. {
  120. $opts = new Getopt(
  121. array(
  122. 'apple|a=s' => 'Apple with required parameter',
  123. 'banana|b' => 'Banana'
  124. ),
  125. array('--apple'));
  126. $this->setExpectedException('\Zend\Console\Exception\RuntimeException', 'requires a parameter');
  127. $opts->parse();
  128. }
  129. public function testGetoptOptionalParameter()
  130. {
  131. $opts = new Getopt(
  132. array(
  133. 'apple|a-s' => 'Apple with optional parameter',
  134. 'banana|b' => 'Banana'
  135. ),
  136. array('--apple', '--banana'));
  137. $this->assertTrue($opts->apple);
  138. $this->assertTrue($opts->banana);
  139. }
  140. public function testGetoptIgnoreCaseGnuMode()
  141. {
  142. $opts = new Getopt('aB', array('-A', '-b'),
  143. array(Getopt::CONFIG_IGNORECASE => true));
  144. $this->assertEquals(true, $opts->a);
  145. $this->assertEquals(true, $opts->B);
  146. }
  147. public function testGetoptIgnoreCaseZendMode()
  148. {
  149. $opts = new Getopt(
  150. array(
  151. 'apple|a' => 'Apple-option',
  152. 'Banana|B' => 'Banana-option'
  153. ),
  154. array('--Apple', '--bAnaNa'),
  155. array(Getopt::CONFIG_IGNORECASE => true));
  156. $this->assertEquals(true, $opts->apple);
  157. $this->assertEquals(true, $opts->BANANA);
  158. }
  159. public function testGetoptIsSet()
  160. {
  161. $opts = new Getopt('ab', array('-a'));
  162. $this->assertTrue(isset($opts->a));
  163. $this->assertFalse(isset($opts->b));
  164. }
  165. public function testGetoptIsSetAlias()
  166. {
  167. $opts = new Getopt('ab', array('-a'));
  168. $opts->setAliases(array('a' => 'apple', 'b' => 'banana'));
  169. $this->assertTrue(isset($opts->apple));
  170. $this->assertFalse(isset($opts->banana));
  171. }
  172. public function testGetoptIsSetInvalid()
  173. {
  174. $opts = new Getopt('ab', array('-a'));
  175. $opts->setAliases(array('a' => 'apple', 'b' => 'banana'));
  176. $this->assertFalse(isset($opts->cumquat));
  177. }
  178. public function testGetoptSet()
  179. {
  180. $opts = new Getopt('ab', array('-a'));
  181. $this->assertFalse(isset($opts->b));
  182. $opts->b = true;
  183. $this->assertTrue(isset($opts->b));
  184. }
  185. public function testGetoptSetBeforeParse()
  186. {
  187. $opts = new Getopt('ab', array('-a'));
  188. $opts->b = true;
  189. $this->assertTrue(isset($opts->b));
  190. }
  191. public function testGetoptUnSet()
  192. {
  193. $opts = new Getopt('ab', array('-a'));
  194. $this->assertTrue(isset($opts->a));
  195. unset($opts->a);
  196. $this->assertFalse(isset($opts->a));
  197. }
  198. public function testGetoptUnSetBeforeParse()
  199. {
  200. $opts = new Getopt('ab', array('-a'));
  201. unset($opts->a);
  202. $this->assertFalse(isset($opts->a));
  203. }
  204. /**
  205. * @group ZF-5948
  206. */
  207. public function testGetoptAddSetNonArrayArguments()
  208. {
  209. $opts = new Getopt('abp:', array('-foo'));
  210. $this->setExpectedException('\Zend\Console\Exception\InvalidArgumentException', 'should be an array');
  211. $opts->setArguments('-a');
  212. }
  213. public function testGetoptAddArguments()
  214. {
  215. $opts = new Getopt('abp:', array('-a'));
  216. $this->assertNull(@$opts->p);
  217. $opts->addArguments(array('-p', 'p_arg'));
  218. $this->assertEquals($opts->p, 'p_arg');
  219. }
  220. public function testGetoptRemainingArgs()
  221. {
  222. $opts = new Getopt('abp:', array('-a', '--', 'file1', 'file2'));
  223. $this->assertEquals(implode(',', $opts->getRemainingArgs()), 'file1,file2');
  224. $opts = new Getopt('abp:', array('-a', 'file1', 'file2'));
  225. $this->assertEquals(implode(',', $opts->getRemainingArgs()), 'file1,file2');
  226. }
  227. public function testGetoptDashDashFalse()
  228. {
  229. $opts = new Getopt('abp:', array('-a', '--', '--fakeflag'),
  230. array(Getopt::CONFIG_DASHDASH => false));
  231. $this->setExpectedException('\Zend\Console\Exception\RuntimeException', 'not recognized');
  232. $opts->parse();
  233. }
  234. public function testGetoptGetOptions()
  235. {
  236. $opts = new Getopt('abp:', array('-a', '-p', 'p_arg'));
  237. $this->assertEquals(implode(',', $opts->getOptions()), 'a,p');
  238. }
  239. public function testGetoptGetUsageMessage()
  240. {
  241. $opts = new Getopt('abp:', array('-x'));
  242. $message = preg_replace('/Usage: .* \[ options \]/',
  243. 'Usage: <progname> [ options ]',
  244. $opts->getUsageMessage());
  245. $message = preg_replace('/ /', '_', $message);
  246. $this->assertEquals($message,
  247. "Usage:_<progname>_[_options_]\n-a___________________\n-b___________________\n-p_<string>__________\n");
  248. }
  249. public function testGetoptUsageMessageFromException()
  250. {
  251. try {
  252. $opts = new Getopt(array(
  253. 'apple|a-s' => 'apple',
  254. 'banana1|banana2|banana3|banana4' => 'banana',
  255. 'pear=s' => 'pear'),
  256. array('-x'));
  257. $opts->parse();
  258. $this->fail('Expected to catch \Zend\Console\Exception\RuntimeException');
  259. } catch (\Zend\Console\Exception\RuntimeException $e) {
  260. $message = preg_replace('/Usage: .* \[ options \]/',
  261. 'Usage: <progname> [ options ]',
  262. $e->getUsageMessage());
  263. $message = preg_replace('/ /', '_', $message);
  264. $this->assertEquals($message,
  265. "Usage:_<progname>_[_options_]\n--apple|-a_[_<string>_]_________________apple\n--banana1|--banana2|--banana3|--banana4_banana\n--pear_<string>_________________________pear\n");
  266. }
  267. }
  268. public function testGetoptSetAliases()
  269. {
  270. $opts = new Getopt('abp:', array('--apple'));
  271. $opts->setAliases(array('a' => 'apple'));
  272. $this->assertTrue($opts->a);
  273. }
  274. public function testGetoptSetAliasesIgnoreCase()
  275. {
  276. $opts = new Getopt('abp:', array('--apple'),
  277. array(Getopt::CONFIG_IGNORECASE => true));
  278. $opts->setAliases(array('a' => 'APPLE'));
  279. $this->assertTrue($opts->apple);
  280. }
  281. public function testGetoptSetAliasesWithNamingConflict()
  282. {
  283. $opts = new Getopt('abp:', array('--apple'));
  284. $opts->setAliases(array('a' => 'apple'));
  285. $this->setExpectedException('\Zend\Console\Exception\InvalidArgumentException', 'defined more than once');
  286. $opts->setAliases(array('b' => 'apple'));
  287. }
  288. public function testGetoptSetAliasesInvalid()
  289. {
  290. $opts = new Getopt('abp:', array('--apple'));
  291. $opts->setAliases(array('c' => 'cumquat'));
  292. $opts->setArguments(array('-c'));
  293. $this->setExpectedException('\Zend\Console\Exception\RuntimeException', 'not recognized');
  294. $opts->parse();
  295. }
  296. public function testGetoptSetHelp()
  297. {
  298. $opts = new Getopt('abp:', array('-a'));
  299. $opts->setHelp(array(
  300. 'a' => 'apple',
  301. 'b' => 'banana',
  302. 'p' => 'pear'));
  303. $message = preg_replace('/Usage: .* \[ options \]/',
  304. 'Usage: <progname> [ options ]',
  305. $opts->getUsageMessage());
  306. $message = preg_replace('/ /', '_', $message);
  307. $this->assertEquals($message,
  308. "Usage:_<progname>_[_options_]\n-a___________________apple\n-b___________________banana\n-p_<string>__________pear\n");
  309. }
  310. public function testGetoptSetHelpInvalid()
  311. {
  312. $opts = new Getopt('abp:', array('-a'));
  313. $opts->setHelp(array(
  314. 'a' => 'apple',
  315. 'b' => 'banana',
  316. 'p' => 'pear',
  317. 'c' => 'cumquat'));
  318. $message = preg_replace('/Usage: .* \[ options \]/',
  319. 'Usage: <progname> [ options ]',
  320. $opts->getUsageMessage());
  321. $message = preg_replace('/ /', '_', $message);
  322. $this->assertEquals($message,
  323. "Usage:_<progname>_[_options_]\n-a___________________apple\n-b___________________banana\n-p_<string>__________pear\n");
  324. }
  325. public function testGetoptCheckParameterType()
  326. {
  327. $opts = new Getopt(array(
  328. 'apple|a=i' => 'apple with integer',
  329. 'banana|b=w' => 'banana with word',
  330. 'pear|p=s' => 'pear with string',
  331. 'orange|o-i' => 'orange with optional integer',
  332. 'lemon|l-w' => 'lemon with optional word',
  333. 'kumquat|k-s' => 'kumquat with optional string'));
  334. $opts->setArguments(array('-a', 327));
  335. $opts->parse();
  336. $this->assertEquals(327, $opts->a);
  337. $opts->setArguments(array('-a', 'noninteger'));
  338. try {
  339. $opts->parse();
  340. $this->fail('Expected to catch \Zend\Console\Exception\RuntimeException');
  341. } catch (\Zend\Console\Exception\RuntimeException $e) {
  342. $this->assertEquals($e->getMessage(), 'Option "apple" requires an integer parameter, but was given "noninteger".');
  343. }
  344. $opts->setArguments(array('-b', 'word'));
  345. $this->assertEquals('word', $opts->b);
  346. $opts->setArguments(array('-b', 'two words'));
  347. try {
  348. $opts->parse();
  349. $this->fail('Expected to catch \Zend\Console\Exception\RuntimeException');
  350. } catch (\Zend\Console\Exception\RuntimeException $e) {
  351. $this->assertEquals($e->getMessage(), 'Option "banana" requires a single-word parameter, but was given "two words".');
  352. }
  353. $opts->setArguments(array('-p', 'string'));
  354. $this->assertEquals('string', $opts->p);
  355. $opts->setArguments(array('-o', 327));
  356. $this->assertEquals(327, $opts->o);
  357. $opts->setArguments(array('-o'));
  358. $this->assertTrue($opts->o);
  359. $opts->setArguments(array('-l', 'word'));
  360. $this->assertEquals('word', $opts->l);
  361. $opts->setArguments(array('-k', 'string'));
  362. $this->assertEquals('string', $opts->k);
  363. }
  364. /**
  365. * @group ZF-2295
  366. */
  367. public function testRegisterArgcArgvOffThrowsException()
  368. {
  369. $argv = $_SERVER['argv'];
  370. unset($_SERVER['argv']);
  371. try {
  372. $opts = new GetOpt('abp:');
  373. $this->fail();
  374. } catch(\Zend\Console\Exception\InvalidArgumentException $e) {
  375. $this->assertContains('$_SERVER["argv"]', $e->getMessage());
  376. }
  377. $_SERVER['argv'] = $argv;
  378. }
  379. /**
  380. * Test to ensure that dashed long names will parse correctly
  381. *
  382. * @group ZF-4763
  383. */
  384. public function testDashWithinLongOptionGetsParsed()
  385. {
  386. $opts = new Getopt(
  387. array( // rules
  388. 'man-bear|m-s' => 'ManBear with dash',
  389. 'man-bear-pig|b=s' => 'ManBearPid with dash',
  390. ),
  391. array( // arguments
  392. '--man-bear-pig=mbp',
  393. '--man-bear',
  394. 'foobar'
  395. )
  396. );
  397. $opts->parse();
  398. $this->assertEquals('foobar', $opts->getOption('man-bear'));
  399. $this->assertEquals('mbp', $opts->getOption('man-bear-pig'));
  400. }
  401. /**
  402. * @group ZF-2064
  403. */
  404. public function testAddRulesDoesNotThrowWarnings()
  405. {
  406. // Fails if warning is thrown: Should not happen!
  407. $opts = new Getopt('abp:');
  408. $opts->addRules(
  409. array(
  410. 'verbose|v' => 'Print verbose output'
  411. )
  412. );
  413. }
  414. /**
  415. * @group ZF-5345
  416. */
  417. public function testUsingDashWithoutOptionNameAsLastArgumentIsRecognizedAsRemainingArgument()
  418. {
  419. $opts = new Getopt("abp:", array("-"));
  420. $opts->parse();
  421. $this->assertEquals(1, count($opts->getRemainingArgs()));
  422. $this->assertEquals(array("-"), $opts->getRemainingArgs());
  423. }
  424. /**
  425. * @group ZF-5345
  426. */
  427. public function testUsingDashWithoutOptionNotAsLastArgumentThrowsException()
  428. {
  429. $opts = new Getopt("abp:", array("-", "file1"));
  430. $this->setExpectedException('\Zend\Console\Exception\RuntimeException');
  431. $opts->parse();
  432. }
  433. /**
  434. * @group ZF-5624
  435. */
  436. public function testEqualsCharacterInLongOptionsValue()
  437. {
  438. $fooValue = 'some text containing an = sign which breaks';
  439. $opts = new Getopt(
  440. array('foo=s' => 'Option One (string)'),
  441. array('--foo='.$fooValue)
  442. );
  443. $this->assertEquals($fooValue, $opts->foo);
  444. }
  445. public function testGetoptIgnoreCumulativeParamsByDefault()
  446. {
  447. $opts = new Getopt(
  448. array('colors=s' => 'Colors-option'),
  449. array('--colors=red', '--colors=green', '--colors=blue')
  450. );
  451. $this->assertInternalType('string', $opts->colors);
  452. $this->assertEquals('blue', $opts->colors, 'Should be equal to last variable');
  453. }
  454. public function testGetoptWithCumulativeParamsOptionHandleArrayValues()
  455. {
  456. $opts = new Getopt(
  457. array('colors=s' => 'Colors-option'),
  458. array('--colors=red', '--colors=green', '--colors=blue'),
  459. array(Getopt::CONFIG_CUMULATIVE_PARAMETERS => true)
  460. );
  461. $this->assertInternalType('array', $opts->colors, 'Colors value should be an array');
  462. $this->assertEquals('red,green,blue', implode(',', $opts->colors));
  463. }
  464. public function testGetoptIgnoreCumulativeFlagsByDefault()
  465. {
  466. $opts = new Getopt('v', array('-v', '-v', '-v'));
  467. $this->assertEquals(true, $opts->v);
  468. }
  469. public function testGetoptWithCumulativeFlagsOptionHandleCountOfEqualFlags()
  470. {
  471. $opts = new Getopt('v', array('-v', '-v', '-v'),
  472. array(Getopt::CONFIG_CUMULATIVE_FLAGS => true));
  473. $this->assertEquals(3, $opts->v);
  474. }
  475. public function testGetoptIgnoreParamsWithMultipleValuesByDefault()
  476. {
  477. $opts = new Getopt(
  478. array('colors=s' => 'Colors-option'),
  479. array('--colors=red,green,blue')
  480. );
  481. $this->assertEquals('red,green,blue', $opts->colors);
  482. }
  483. public function testGetoptWithNotEmptyParameterSeparatorSplitMultipleValues()
  484. {
  485. $opts = new Getopt(
  486. array('colors=s' => 'Colors-option'),
  487. array('--colors=red,green,blue'),
  488. array(Getopt::CONFIG_PARAMETER_SEPARATOR => ',')
  489. );
  490. $this->assertEquals('red:green:blue', implode(':', $opts->colors));
  491. }
  492. public function testGetoptWithFreeformFlagOptionRecognizeAllFlags()
  493. {
  494. $opts = new Getopt(
  495. array('colors' => 'Colors-option'),
  496. array('--freeform'),
  497. array(Getopt::CONFIG_FREEFORM_FLAGS => true)
  498. );
  499. $this->assertEquals(true, $opts->freeform);
  500. }
  501. public function testGetoptWithFreeformFlagOptionRecognizeFlagsWithValue()
  502. {
  503. $opts = new Getopt(
  504. array('colors' => 'Colors-option'),
  505. array('color', '--freeform', 'test', 'zend'),
  506. array(Getopt::CONFIG_FREEFORM_FLAGS => true)
  507. );
  508. $this->assertEquals('test', $opts->freeform);
  509. }
  510. public function testGetoptRaiseExceptionForNumericOptionsByDefault()
  511. {
  512. $opts = new Getopt(
  513. array('colors=s' => 'Colors-option'),
  514. array('red', 'green', '-3')
  515. );
  516. $this->setExpectedException('\Zend\Console\Exception\RuntimeException');
  517. $opts->parse();
  518. }
  519. public function testGetoptCanRecognizeNumericOprions()
  520. {
  521. $opts = new Getopt(
  522. array('lines=#' => 'Lines-option'),
  523. array('other', 'arguments', '-5'),
  524. array(Getopt::CONFIG_NUMERIC_FLAGS => true)
  525. );
  526. $this->assertEquals(5, $opts->lines);
  527. }
  528. public function testGetoptRaiseExceptionForNumericOptionsIfAneHandlerIsSpecified()
  529. {
  530. $opts = new Getopt(
  531. array('lines=s' => 'Lines-option'),
  532. array('other', 'arguments', '-5'),
  533. array(Getopt::CONFIG_NUMERIC_FLAGS => true)
  534. );
  535. $this->setExpectedException('\Zend\Console\Exception\RuntimeException');
  536. $opts->parse();
  537. }
  538. }