ConsoleOptionParserTest.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 2.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Console;
  17. use Cake\Console\ConsoleInputArgument;
  18. use Cake\Console\ConsoleInputOption;
  19. use Cake\Console\ConsoleInputSubcommand;
  20. use Cake\Console\ConsoleOptionParser;
  21. use Cake\Console\Exception\ConsoleException;
  22. use Cake\Console\Exception\MissingOptionException;
  23. use Cake\TestSuite\TestCase;
  24. use LogicException;
  25. /**
  26. * ConsoleOptionParserTest
  27. */
  28. class ConsoleOptionParserTest extends TestCase
  29. {
  30. /**
  31. * test setting the console description
  32. *
  33. * @return void
  34. */
  35. public function testDescription()
  36. {
  37. $parser = new ConsoleOptionParser('test', false);
  38. $result = $parser->setDescription('A test');
  39. $this->assertEquals($parser, $result, 'Setting description is not chainable');
  40. $this->assertSame('A test', $parser->getDescription(), 'getting value is wrong.');
  41. $result = $parser->setDescription(['A test', 'something']);
  42. $this->assertEquals("A test\nsomething", $parser->getDescription(), 'getting value is wrong.');
  43. }
  44. /**
  45. * test setting and getting the console epilog
  46. *
  47. * @return void
  48. */
  49. public function testEpilog()
  50. {
  51. $parser = new ConsoleOptionParser('test', false);
  52. $result = $parser->setEpilog('A test');
  53. $this->assertEquals($parser, $result, 'Setting epilog is not chainable');
  54. $this->assertSame('A test', $parser->getEpilog(), 'getting value is wrong.');
  55. $result = $parser->setEpilog(['A test', 'something']);
  56. $this->assertEquals("A test\nsomething", $parser->getEpilog(), 'getting value is wrong.');
  57. }
  58. /**
  59. * test adding an option returns self.
  60. *
  61. * @return void
  62. */
  63. public function testAddOptionReturnSelf()
  64. {
  65. $parser = new ConsoleOptionParser('test', false);
  66. $result = $parser->addOption('test');
  67. $this->assertEquals($parser, $result, 'Did not return $this from addOption');
  68. }
  69. /**
  70. * test removing an option
  71. *
  72. * @return void
  73. */
  74. public function testRemoveOption()
  75. {
  76. $parser = new ConsoleOptionParser('test', false);
  77. $result = $parser->addOption('test')
  78. ->removeOption('test')
  79. ->removeOption('help');
  80. $this->assertSame($parser, $result, 'Did not return $this from removeOption');
  81. $this->assertEquals([], $result->options());
  82. }
  83. /**
  84. * test adding an option and using the long value for parsing.
  85. *
  86. * @return void
  87. */
  88. public function testAddOptionLong()
  89. {
  90. $parser = new ConsoleOptionParser('test', false);
  91. $parser->addOption('test', [
  92. 'short' => 't',
  93. ]);
  94. $result = $parser->parse(['--test', 'value']);
  95. $this->assertEquals(['test' => 'value', 'help' => false], $result[0], 'Long parameter did not parse out');
  96. }
  97. /**
  98. * test adding an option with a zero value
  99. *
  100. * @return void
  101. */
  102. public function testAddOptionZero()
  103. {
  104. $parser = new ConsoleOptionParser('test', false);
  105. $parser->addOption('count', []);
  106. $result = $parser->parse(['--count', '0']);
  107. $this->assertEquals(['count' => '0', 'help' => false], $result[0], 'Zero parameter did not parse out');
  108. }
  109. /**
  110. * test addOption with an object.
  111. *
  112. * @return void
  113. */
  114. public function testAddOptionObject()
  115. {
  116. $parser = new ConsoleOptionParser('test', false);
  117. $parser->addOption(new ConsoleInputOption('test', 't'));
  118. $result = $parser->parse(['--test=value']);
  119. $this->assertEquals(['test' => 'value', 'help' => false], $result[0], 'Long parameter did not parse out');
  120. }
  121. /**
  122. * test adding an option and using the long value for parsing.
  123. *
  124. * @return void
  125. */
  126. public function testAddOptionLongEquals()
  127. {
  128. $parser = new ConsoleOptionParser('test', false);
  129. $parser->addOption('test', [
  130. 'short' => 't',
  131. ]);
  132. $result = $parser->parse(['--test=value']);
  133. $this->assertEquals(['test' => 'value', 'help' => false], $result[0], 'Long parameter did not parse out');
  134. }
  135. /**
  136. * test adding an option and using the default.
  137. *
  138. * @return void
  139. */
  140. public function testAddOptionDefault()
  141. {
  142. $parser = new ConsoleOptionParser('test', false);
  143. $parser
  144. ->addOption('test', [
  145. 'default' => 'default value',
  146. ])
  147. ->addOption('no-default', [
  148. ]);
  149. $result = $parser->parse(['--test']);
  150. $this->assertSame(
  151. ['test' => 'default value', 'help' => false],
  152. $result[0],
  153. 'Default value did not parse out'
  154. );
  155. $parser = new ConsoleOptionParser('test', false);
  156. $parser->addOption('test', [
  157. 'default' => 'default value',
  158. ]);
  159. $result = $parser->parse([]);
  160. $this->assertEquals(['test' => 'default value', 'help' => false], $result[0], 'Default value did not parse out');
  161. }
  162. /**
  163. * test adding an option and using the short value for parsing.
  164. *
  165. * @return void
  166. */
  167. public function testAddOptionShort()
  168. {
  169. $parser = new ConsoleOptionParser('test', false);
  170. $parser->addOption('test', [
  171. 'short' => 't',
  172. ]);
  173. $result = $parser->parse(['-t', 'value']);
  174. $this->assertEquals(['test' => 'value', 'help' => false], $result[0], 'Short parameter did not parse out');
  175. }
  176. /**
  177. * test adding an option and using the short value for parsing.
  178. *
  179. * @return void
  180. */
  181. public function testAddOptionWithMultipleShort()
  182. {
  183. $parser = new ConsoleOptionParser('test', false);
  184. $parser->addOption('source', [
  185. 'multiple' => true,
  186. 'short' => 's',
  187. ]);
  188. $result = $parser->parse(['-s', 'mysql', '-s', 'postgres']);
  189. $this->assertEquals(
  190. [
  191. 'source' => ['mysql', 'postgres'],
  192. 'help' => false,
  193. ],
  194. $result[0],
  195. 'Short parameter did not parse out'
  196. );
  197. }
  198. /**
  199. * Test that adding an option using a two letter short value causes an exception.
  200. * As they will not parse correctly.
  201. *
  202. * @return void
  203. */
  204. public function testAddOptionShortOneLetter()
  205. {
  206. $this->expectException(ConsoleException::class);
  207. $parser = new ConsoleOptionParser('test', false);
  208. $parser->addOption('test', ['short' => 'te']);
  209. }
  210. /**
  211. * test adding and using boolean options.
  212. *
  213. * @return void
  214. */
  215. public function testAddOptionBoolean()
  216. {
  217. $parser = new ConsoleOptionParser('test', false);
  218. $parser->addOption('test', [
  219. 'boolean' => true,
  220. ]);
  221. $result = $parser->parse(['--test', 'value']);
  222. $expected = [['test' => true, 'help' => false], ['value']];
  223. $this->assertEquals($expected, $result);
  224. $result = $parser->parse(['value']);
  225. $expected = [['test' => false, 'help' => false], ['value']];
  226. $this->assertEquals($expected, $result);
  227. }
  228. /**
  229. * test adding an multiple shorts.
  230. *
  231. * @return void
  232. */
  233. public function testAddOptionMultipleShort()
  234. {
  235. $parser = new ConsoleOptionParser('test', false);
  236. $parser->addOption('test', ['short' => 't', 'boolean' => true])
  237. ->addOption('file', ['short' => 'f', 'boolean' => true])
  238. ->addOption('output', ['short' => 'o', 'boolean' => true]);
  239. $result = $parser->parse(['-o', '-t', '-f']);
  240. $expected = ['file' => true, 'test' => true, 'output' => true, 'help' => false];
  241. $this->assertEquals($expected, $result[0], 'Short parameter did not parse out');
  242. $result = $parser->parse(['-otf']);
  243. $this->assertEquals($expected, $result[0], 'Short parameter did not parse out');
  244. }
  245. /**
  246. * test multiple options at once.
  247. *
  248. * @return void
  249. */
  250. public function testAddOptionMultipleOptions()
  251. {
  252. $parser = new ConsoleOptionParser('test', false);
  253. $parser->addOption('test')
  254. ->addOption('connection')
  255. ->addOption('table', ['short' => 't', 'default' => true]);
  256. $result = $parser->parse(['--test', 'value', '-t', '--connection', 'postgres']);
  257. $expected = ['test' => 'value', 'table' => true, 'connection' => 'postgres', 'help' => false];
  258. $this->assertEquals($expected, $result[0], 'multiple options did not parse');
  259. }
  260. /**
  261. * test adding an option that accepts multiple values.
  262. *
  263. * @return void
  264. */
  265. public function testAddOptionWithMultiple()
  266. {
  267. $parser = new ConsoleOptionParser('test', false);
  268. $parser->addOption('source', ['short' => 's', 'multiple' => true]);
  269. $result = $parser->parse(['--source', 'mysql', '-s', 'postgres']);
  270. $expected = [
  271. 'source' => [
  272. 'mysql',
  273. 'postgres',
  274. ],
  275. 'help' => false,
  276. ];
  277. $this->assertEquals($expected, $result[0], 'options with multiple values did not parse');
  278. }
  279. /**
  280. * test adding multiple options, including one that accepts multiple values.
  281. *
  282. * @return void
  283. */
  284. public function testAddOptionMultipleOptionsWithMultiple()
  285. {
  286. $parser = new ConsoleOptionParser('test', false);
  287. $parser
  288. ->addOption('source', ['multiple' => true])
  289. ->addOption('name')
  290. ->addOption('export', ['boolean' => true]);
  291. $result = $parser->parse(['--export', '--source', 'mysql', '--name', 'annual-report', '--source', 'postgres']);
  292. $expected = [
  293. 'export' => true,
  294. 'source' => [
  295. 'mysql',
  296. 'postgres',
  297. ],
  298. 'name' => 'annual-report',
  299. 'help' => false,
  300. ];
  301. $this->assertEquals($expected, $result[0], 'options with multiple values did not parse');
  302. }
  303. /**
  304. * test adding a required option with a default.
  305. *
  306. * @return void
  307. */
  308. public function testAddOptionRequiredDefaultValue()
  309. {
  310. $parser = new ConsoleOptionParser('test', false);
  311. $parser
  312. ->addOption('test', [
  313. 'default' => 'default value',
  314. 'required' => true,
  315. ])
  316. ->addOption('no-default', [
  317. 'required' => true,
  318. ]);
  319. $result = $parser->parse(['--test', '--no-default', 'value']);
  320. $this->assertSame(
  321. ['test' => 'default value', 'no-default' => 'value', 'help' => false],
  322. $result[0]
  323. );
  324. $result = $parser->parse(['--no-default', 'value']);
  325. $this->assertSame(
  326. ['no-default' => 'value', 'help' => false, 'test' => 'default value'],
  327. $result[0]
  328. );
  329. }
  330. /**
  331. * test adding a required option that is missing.
  332. *
  333. * @return void
  334. */
  335. public function testAddOptionRequiredMissing()
  336. {
  337. $parser = new ConsoleOptionParser('test', false);
  338. $parser
  339. ->addOption('test', [
  340. 'default' => 'default value',
  341. 'required' => true,
  342. ])
  343. ->addOption('no-default', [
  344. 'required' => true,
  345. ]);
  346. $this->expectException(ConsoleException::class);
  347. $parser->parse(['--test']);
  348. }
  349. /**
  350. * Test adding multiple options.
  351. *
  352. * @return void
  353. */
  354. public function testAddOptions()
  355. {
  356. $parser = new ConsoleOptionParser('something', false);
  357. $result = $parser->addOptions([
  358. 'name' => ['help' => 'The name'],
  359. 'other' => ['help' => 'The other arg'],
  360. ]);
  361. $this->assertEquals($parser, $result, 'addOptions is not chainable.');
  362. $result = $parser->options();
  363. $this->assertCount(3, $result, 'Not enough options');
  364. }
  365. /**
  366. * test that boolean options work
  367. *
  368. * @return void
  369. */
  370. public function testOptionWithBooleanParam()
  371. {
  372. $parser = new ConsoleOptionParser('test', false);
  373. $parser->addOption('no-commit', ['boolean' => true])
  374. ->addOption('table', ['short' => 't']);
  375. $result = $parser->parse(['--table', 'posts', '--no-commit', 'arg1', 'arg2']);
  376. $expected = [['table' => 'posts', 'no-commit' => true, 'help' => false], ['arg1', 'arg2']];
  377. $this->assertEquals($expected, $result, 'Boolean option did not parse correctly.');
  378. }
  379. /**
  380. * test parsing options that do not exist.
  381. *
  382. * @return void
  383. */
  384. public function testOptionThatDoesNotExist()
  385. {
  386. $parser = new ConsoleOptionParser('test', false);
  387. $parser->addOption('no-commit', ['boolean' => true]);
  388. try {
  389. $parser->parse(['--he', 'other']);
  390. } catch (MissingOptionException $e) {
  391. $this->assertStringContainsString(
  392. "Unknown option `he`.\n" .
  393. "Did you mean: `help`?\n" .
  394. "\n" .
  395. "Other valid choices:\n" .
  396. "\n" .
  397. "- help",
  398. $e->getFullMessage()
  399. );
  400. }
  401. }
  402. /**
  403. * test parsing short options that do not exist.
  404. *
  405. * @return void
  406. */
  407. public function testShortOptionThatDoesNotExist()
  408. {
  409. $parser = new ConsoleOptionParser('test', false);
  410. $parser->addOption('no-commit', ['boolean' => true, 'short' => 'n']);
  411. $parser->addOption('construct', ['boolean' => true]);
  412. $parser->addOption('clear', ['boolean' => true, 'short' => 'c']);
  413. try {
  414. $parser->parse(['-f']);
  415. } catch (MissingOptionException $e) {
  416. $this->assertStringContainsString("Unknown short option `f`.", $e->getFullMessage());
  417. }
  418. }
  419. /**
  420. * test that options with choices enforce them.
  421. *
  422. * @return void
  423. */
  424. public function testOptionWithChoices()
  425. {
  426. $this->expectException(ConsoleException::class);
  427. $parser = new ConsoleOptionParser('test', false);
  428. $parser->addOption('name', ['choices' => ['mark', 'jose']]);
  429. $result = $parser->parse(['--name', 'mark']);
  430. $expected = ['name' => 'mark', 'help' => false];
  431. $this->assertEquals($expected, $result[0], 'Got the correct value.');
  432. $result = $parser->parse(['--name', 'jimmy']);
  433. }
  434. /**
  435. * Ensure that option values can start with -
  436. *
  437. * @return void
  438. */
  439. public function testOptionWithValueStartingWithMinus()
  440. {
  441. $parser = new ConsoleOptionParser('test', false);
  442. $parser->addOption('name')
  443. ->addOption('age');
  444. $result = $parser->parse(['--name', '-foo', '--age', 'old']);
  445. $expected = ['name' => '-foo', 'age' => 'old', 'help' => false];
  446. $this->assertEquals($expected, $result[0], 'Option values starting with "-" are broken.');
  447. }
  448. /**
  449. * test positional argument parsing.
  450. *
  451. * @return void
  452. */
  453. public function testPositionalArgument()
  454. {
  455. $parser = new ConsoleOptionParser('test', false);
  456. $result = $parser->addArgument('name', ['help' => 'An argument']);
  457. $this->assertEquals($parser, $result, 'Should return this');
  458. }
  459. /**
  460. * test addOption with an object.
  461. *
  462. * @return void
  463. */
  464. public function testAddArgumentObject()
  465. {
  466. $parser = new ConsoleOptionParser('test', false);
  467. $parser->addArgument(new ConsoleInputArgument('test'));
  468. $result = $parser->arguments();
  469. $this->assertCount(1, $result);
  470. $this->assertSame('test', $result[0]->name());
  471. }
  472. /**
  473. * Test adding arguments out of order.
  474. *
  475. * @return void
  476. */
  477. public function testAddArgumentOutOfOrder()
  478. {
  479. $parser = new ConsoleOptionParser('test', false);
  480. $parser->addArgument('name', ['index' => 1, 'help' => 'first argument'])
  481. ->addArgument('bag', ['index' => 2, 'help' => 'second argument'])
  482. ->addArgument('other', ['index' => 0, 'help' => 'Zeroth argument']);
  483. $result = $parser->arguments();
  484. $this->assertCount(3, $result);
  485. $this->assertSame('other', $result[0]->name());
  486. $this->assertSame('name', $result[1]->name());
  487. $this->assertSame('bag', $result[2]->name());
  488. $this->assertSame([0, 1, 2], array_keys($result));
  489. $this->assertEquals(
  490. ['other', 'name', 'bag'],
  491. $parser->argumentNames()
  492. );
  493. }
  494. /**
  495. * test overwriting positional arguments.
  496. *
  497. * @return void
  498. */
  499. public function testPositionalArgOverwrite()
  500. {
  501. $parser = new ConsoleOptionParser('test', false);
  502. $parser->addArgument('name', ['help' => 'An argument'])
  503. ->addArgument('other', ['index' => 0]);
  504. $result = $parser->arguments();
  505. $this->assertCount(1, $result, 'Overwrite did not occur');
  506. }
  507. /**
  508. * test parsing arguments.
  509. *
  510. * @return void
  511. */
  512. public function testParseArgumentTooMany()
  513. {
  514. $this->expectException(ConsoleException::class);
  515. $parser = new ConsoleOptionParser('test', false);
  516. $parser->addArgument('name', ['help' => 'An argument'])
  517. ->addArgument('other');
  518. $expected = ['one', 'two'];
  519. $result = $parser->parse($expected);
  520. $this->assertEquals($expected, $result[1], 'Arguments are not as expected');
  521. $result = $parser->parse(['one', 'two', 'three']);
  522. }
  523. /**
  524. * test parsing arguments with 0 value.
  525. *
  526. * @return void
  527. */
  528. public function testParseArgumentZero()
  529. {
  530. $parser = new ConsoleOptionParser('test', false);
  531. $expected = ['one', 'two', 0, 'after', 'zero'];
  532. $result = $parser->parse($expected);
  533. $this->assertEquals($expected, $result[1], 'Arguments are not as expected');
  534. }
  535. /**
  536. * test that when there are not enough arguments an exception is raised
  537. *
  538. * @return void
  539. */
  540. public function testPositionalArgNotEnough()
  541. {
  542. $this->expectException(ConsoleException::class);
  543. $parser = new ConsoleOptionParser('test', false);
  544. $parser->addArgument('name', ['required' => true])
  545. ->addArgument('other', ['required' => true]);
  546. $parser->parse(['one']);
  547. }
  548. /**
  549. * test that when there are required arguments after optional ones an exception is raised
  550. *
  551. * @return void
  552. */
  553. public function testPositionalArgRequiredAfterOptional()
  554. {
  555. $this->expectException(LogicException::class);
  556. $parser = new ConsoleOptionParser('test');
  557. $parser->addArgument('name', ['required' => false])
  558. ->addArgument('other', ['required' => true]);
  559. }
  560. /**
  561. * test that arguments with choices enforce them.
  562. *
  563. * @return void
  564. */
  565. public function testPositionalArgWithChoices()
  566. {
  567. $this->expectException(ConsoleException::class);
  568. $parser = new ConsoleOptionParser('test', false);
  569. $parser->addArgument('name', ['choices' => ['mark', 'jose']])
  570. ->addArgument('alias', ['choices' => ['cowboy', 'samurai']])
  571. ->addArgument('weapon', ['choices' => ['gun', 'sword']]);
  572. $result = $parser->parse(['mark', 'samurai', 'sword']);
  573. $expected = ['mark', 'samurai', 'sword'];
  574. $this->assertEquals($expected, $result[1], 'Got the correct value.');
  575. $result = $parser->parse(['jose', 'coder']);
  576. }
  577. /**
  578. * Test adding multiple arguments.
  579. *
  580. * @return void
  581. */
  582. public function testAddArguments()
  583. {
  584. $parser = new ConsoleOptionParser('test', false);
  585. $result = $parser->addArguments([
  586. 'name' => ['help' => 'The name'],
  587. 'other' => ['help' => 'The other arg'],
  588. ]);
  589. $this->assertEquals($parser, $result, 'addArguments is not chainable.');
  590. $result = $parser->arguments();
  591. $this->assertCount(2, $result, 'Not enough arguments');
  592. }
  593. /**
  594. * test setting a subcommand up.
  595. *
  596. * @return void
  597. */
  598. public function testSubcommand()
  599. {
  600. $parser = new ConsoleOptionParser('test', false);
  601. $result = $parser->addSubcommand('initdb', [
  602. 'help' => 'Initialize the database',
  603. ]);
  604. $this->assertEquals($parser, $result, 'Adding a subcommand is not chainable');
  605. }
  606. /**
  607. * Tests setting a subcommand up for a Shell method `initMyDb`.
  608. *
  609. * @return void
  610. */
  611. public function testSubcommandCamelBacked()
  612. {
  613. $parser = new ConsoleOptionParser('test', false);
  614. $result = $parser->addSubcommand('initMyDb', [
  615. 'help' => 'Initialize the database',
  616. ]);
  617. $subcommands = array_keys($result->subcommands());
  618. $this->assertEquals(['init_my_db'], $subcommands, 'Adding a subcommand does not work with camel backed method names.');
  619. }
  620. /**
  621. * Test addSubcommand inherits options as no
  622. * parser is created.
  623. *
  624. * @return void
  625. */
  626. public function testAddSubcommandInheritOptions()
  627. {
  628. $parser = new ConsoleOptionParser('test', false);
  629. $parser->addSubcommand('build', [
  630. 'help' => 'Build things',
  631. ])->addOption('connection', [
  632. 'short' => 'c',
  633. 'default' => 'default',
  634. ])->addArgument('name', ['required' => false]);
  635. $result = $parser->parse(['build']);
  636. $this->assertSame('default', $result[0]['connection']);
  637. $result = $parser->subcommands();
  638. $this->assertArrayHasKey('build', $result);
  639. $this->assertNull($result['build']->parser(), 'No parser should be created');
  640. }
  641. /**
  642. * test addSubcommand with an object.
  643. *
  644. * @return void
  645. */
  646. public function testAddSubcommandObject()
  647. {
  648. $parser = new ConsoleOptionParser('test', false);
  649. $parser->addSubcommand(new ConsoleInputSubcommand('test'));
  650. $result = $parser->subcommands();
  651. $this->assertCount(1, $result);
  652. $this->assertSame('test', $result['test']->name());
  653. }
  654. /**
  655. * test addSubcommand without sorting applied.
  656. */
  657. public function testAddSubcommandSort()
  658. {
  659. $parser = new ConsoleOptionParser('test', false);
  660. $this->assertTrue($parser->isSubcommandSortEnabled());
  661. $parser->enableSubcommandSort(false);
  662. $this->assertFalse($parser->isSubcommandSortEnabled());
  663. $parser->addSubcommand(new ConsoleInputSubcommand('betaTest'), []);
  664. $parser->addSubcommand(new ConsoleInputSubcommand('alphaTest'), []);
  665. $result = $parser->subcommands();
  666. $this->assertCount(2, $result);
  667. $firstResult = key($result);
  668. $this->assertSame('betaTest', $firstResult);
  669. }
  670. /**
  671. * test removeSubcommand with an object.
  672. *
  673. * @return void
  674. */
  675. public function testRemoveSubcommand()
  676. {
  677. $parser = new ConsoleOptionParser('test', false);
  678. $parser->addSubcommand(new ConsoleInputSubcommand('test'));
  679. $result = $parser->subcommands();
  680. $this->assertCount(1, $result);
  681. $parser->removeSubcommand('test');
  682. $result = $parser->subcommands();
  683. $this->assertCount(0, $result, 'Remove a subcommand does not work');
  684. }
  685. /**
  686. * test adding multiple subcommands
  687. *
  688. * @return void
  689. */
  690. public function testAddSubcommands()
  691. {
  692. $parser = new ConsoleOptionParser('test', false);
  693. $result = $parser->addSubcommands([
  694. 'initdb' => ['help' => 'Initialize the database'],
  695. 'create' => ['help' => 'Create something'],
  696. ]);
  697. $this->assertEquals($parser, $result, 'Adding a subcommands is not chainable');
  698. $result = $parser->subcommands();
  699. $this->assertCount(2, $result, 'Not enough subcommands');
  700. }
  701. /**
  702. * test that no exception is triggered when help is being generated
  703. *
  704. * @return void
  705. */
  706. public function testHelpNoExceptionWhenGettingHelp()
  707. {
  708. $parser = new ConsoleOptionParser('mycommand', false);
  709. $parser->addOption('test', ['help' => 'A test option.'])
  710. ->addArgument('model', ['help' => 'The model to make.', 'required' => true]);
  711. $result = $parser->parse(['--help']);
  712. $this->assertTrue($result[0]['help']);
  713. }
  714. /**
  715. * test that help() with a command param shows the help for a subcommand
  716. *
  717. * @return void
  718. */
  719. public function testHelpSubcommandHelp()
  720. {
  721. $subParser = new ConsoleOptionParser('method', false);
  722. $subParser->addOption('connection', ['help' => 'Db connection.']);
  723. $subParser->addOption('zero', ['short' => '0', 'help' => 'Zero.']);
  724. $parser = new ConsoleOptionParser('mycommand', false);
  725. $parser->addSubcommand('method', [
  726. 'help' => 'This is another command',
  727. 'parser' => $subParser,
  728. ])
  729. ->addOption('test', ['help' => 'A test option.']);
  730. $result = $parser->help('method');
  731. $expected = <<<TEXT
  732. This is another command
  733. <info>Usage:</info>
  734. cake mycommand method [--connection] [-h] [-0]
  735. <info>Options:</info>
  736. --connection Db connection.
  737. --help, -h Display this help.
  738. --zero, -0 Zero.
  739. TEXT;
  740. $this->assertTextEquals($expected, $result, 'Help is not correct.');
  741. }
  742. /**
  743. * Test addSubcommand inherits options as no
  744. * parser is created.
  745. *
  746. * @return void
  747. */
  748. public function testHelpSubcommandInheritOptions()
  749. {
  750. $parser = new ConsoleOptionParser('mycommand', false);
  751. $parser->addSubcommand('build', [
  752. 'help' => 'Build things.',
  753. ])->addSubcommand('destroy', [
  754. 'help' => 'Destroy things.',
  755. ])->addOption('connection', [
  756. 'help' => 'Db connection.',
  757. 'short' => 'c',
  758. ])->addArgument('name', ['required' => false]);
  759. $result = $parser->help('build');
  760. $expected = <<<TEXT
  761. Build things.
  762. <info>Usage:</info>
  763. cake mycommand build [-c] [-h] [-q] [-v] [<name>]
  764. <info>Options:</info>
  765. --connection, -c Db connection.
  766. --help, -h Display this help.
  767. --quiet, -q Enable quiet output.
  768. --verbose, -v Enable verbose output.
  769. <info>Arguments:</info>
  770. name <comment>(optional)</comment>
  771. TEXT;
  772. $this->assertTextEquals($expected, $result, 'Help is not correct.');
  773. }
  774. /**
  775. * test that help() with a command param shows the help for a subcommand
  776. *
  777. * @return void
  778. */
  779. public function testHelpSubcommandHelpArray()
  780. {
  781. $subParser = [
  782. 'options' => [
  783. 'foo' => [
  784. 'short' => 'f',
  785. 'help' => 'Foo.',
  786. 'boolean' => true,
  787. ],
  788. ],
  789. ];
  790. $parser = new ConsoleOptionParser('mycommand', false);
  791. $parser->addSubcommand('method', [
  792. 'help' => 'This is a subcommand',
  793. 'parser' => $subParser,
  794. ])
  795. ->setRootName('tool')
  796. ->addOption('test', ['help' => 'A test option.']);
  797. $result = $parser->help('method');
  798. $expected = <<<TEXT
  799. This is a subcommand
  800. <info>Usage:</info>
  801. tool mycommand method [-f] [-h] [-q] [-v]
  802. <info>Options:</info>
  803. --foo, -f Foo.
  804. --help, -h Display this help.
  805. --quiet, -q Enable quiet output.
  806. --verbose, -v Enable verbose output.
  807. TEXT;
  808. $this->assertTextEquals($expected, $result, 'Help is not correct.');
  809. }
  810. /**
  811. * test that help() with a command param shows the help for a subcommand
  812. *
  813. * @return void
  814. */
  815. public function testHelpSubcommandInheritParser()
  816. {
  817. $subParser = new ConsoleOptionParser('method', false);
  818. $subParser->addOption('connection', ['help' => 'Db connection.']);
  819. $subParser->addOption('zero', ['short' => '0', 'help' => 'Zero.']);
  820. $parser = new ConsoleOptionParser('mycommand', false);
  821. $parser->addSubcommand('method', [
  822. 'help' => 'This is another command',
  823. 'parser' => $subParser,
  824. ])
  825. ->addOption('test', ['help' => 'A test option.']);
  826. $result = $parser->help('method');
  827. $expected = <<<TEXT
  828. This is another command
  829. <info>Usage:</info>
  830. cake mycommand method [--connection] [-h] [-0]
  831. <info>Options:</info>
  832. --connection Db connection.
  833. --help, -h Display this help.
  834. --zero, -0 Zero.
  835. TEXT;
  836. $this->assertTextEquals($expected, $result, 'Help is not correct.');
  837. }
  838. /**
  839. * test that help() with a custom rootName
  840. *
  841. * @return void
  842. */
  843. public function testHelpWithRootName()
  844. {
  845. $parser = new ConsoleOptionParser('sample', false);
  846. $parser->setDescription('A command!')
  847. ->setRootName('tool')
  848. ->addOption('test', ['help' => 'A test option.'])
  849. ->addOption('reqd', ['help' => 'A required option.', 'required' => true]);
  850. $result = $parser->help();
  851. $expected = <<<TEXT
  852. A command!
  853. <info>Usage:</info>
  854. tool sample [-h] --reqd [--test]
  855. <info>Options:</info>
  856. --help, -h Display this help.
  857. --reqd A required option. <comment>(required)</comment>
  858. --test A test option.
  859. TEXT;
  860. $this->assertTextEquals($expected, $result, 'Help is not correct.');
  861. }
  862. /**
  863. * test that getCommandError() with an unknown subcommand param shows a helpful message
  864. *
  865. * @return void
  866. */
  867. public function testHelpUnknownSubcommand()
  868. {
  869. $subParser = [
  870. 'options' => [
  871. 'foo' => [
  872. 'short' => 'f',
  873. 'help' => 'Foo.',
  874. 'boolean' => true,
  875. ],
  876. ],
  877. ];
  878. $parser = new ConsoleOptionParser('mycommand', false);
  879. $parser
  880. ->addSubcommand('method', [
  881. 'help' => 'This is a subcommand',
  882. 'parser' => $subParser,
  883. ])
  884. ->addOption('test', ['help' => 'A test option.'])
  885. ->addSubcommand('unstash');
  886. try {
  887. $result = $parser->help('unknown');
  888. } catch (MissingOptionException $e) {
  889. $result = $e->getFullMessage();
  890. $this->assertStringContainsString(
  891. "Unable to find the `mycommand unknown` subcommand. See `bin/cake mycommand --help`.\n" .
  892. "\n" .
  893. "Other valid choices:\n" .
  894. "\n" .
  895. "- method",
  896. $result
  897. );
  898. }
  899. }
  900. /**
  901. * test building a parser from an array.
  902. *
  903. * @return void
  904. */
  905. public function testBuildFromArray()
  906. {
  907. $spec = [
  908. 'command' => 'test',
  909. 'arguments' => [
  910. 'name' => ['help' => 'The name'],
  911. 'other' => ['help' => 'The other arg'],
  912. ],
  913. 'options' => [
  914. 'name' => ['help' => 'The name'],
  915. 'other' => ['help' => 'The other arg'],
  916. ],
  917. 'subcommands' => [
  918. 'initdb' => ['help' => 'make database'],
  919. ],
  920. 'description' => 'description text',
  921. 'epilog' => 'epilog text',
  922. ];
  923. $parser = ConsoleOptionParser::buildFromArray($spec);
  924. $this->assertEquals($spec['description'], $parser->getDescription());
  925. $this->assertEquals($spec['epilog'], $parser->getEpilog());
  926. $options = $parser->options();
  927. $this->assertArrayHasKey('name', $options);
  928. $this->assertArrayHasKey('other', $options);
  929. $args = $parser->arguments();
  930. $this->assertCount(2, $args);
  931. $commands = $parser->subcommands();
  932. $this->assertCount(1, $commands);
  933. }
  934. /**
  935. * test that create() returns instances
  936. *
  937. * @return void
  938. */
  939. public function testCreateFactory()
  940. {
  941. $parser = ConsoleOptionParser::create('factory', false);
  942. $this->assertInstanceOf('Cake\Console\ConsoleOptionParser', $parser);
  943. $this->assertSame('factory', $parser->getCommand());
  944. }
  945. /**
  946. * test that getCommand() inflects the command name.
  947. *
  948. * @return void
  949. */
  950. public function testCommandInflection()
  951. {
  952. $parser = new ConsoleOptionParser('CommandLine');
  953. $this->assertSame('command_line', $parser->getCommand());
  954. }
  955. /**
  956. * test that parse() takes a subcommand argument, and that the subcommand parser
  957. * is used.
  958. *
  959. * @return void
  960. */
  961. public function testParsingWithSubParser()
  962. {
  963. $parser = new ConsoleOptionParser('test', false);
  964. $parser->addOption('primary')
  965. ->addArgument('one', ['required' => true, 'choices' => ['a', 'b']])
  966. ->addArgument('two', ['required' => true])
  967. ->addSubcommand('sub', [
  968. 'parser' => [
  969. 'options' => [
  970. 'secondary' => ['boolean' => true],
  971. 'fourth' => ['help' => 'fourth option'],
  972. ],
  973. 'arguments' => [
  974. 'sub_arg' => ['choices' => ['c', 'd']],
  975. ],
  976. ],
  977. ]);
  978. $result = $parser->parse(['sub', '--secondary', '--fourth', '4', 'c']);
  979. $expected = [[
  980. 'secondary' => true,
  981. 'fourth' => '4',
  982. 'help' => false,
  983. 'verbose' => false,
  984. 'quiet' => false], ['c']];
  985. $this->assertEquals($expected, $result, 'Sub parser did not parse request.');
  986. }
  987. /**
  988. * Tests toArray()
  989. *
  990. * @return void
  991. */
  992. public function testToArray()
  993. {
  994. $spec = [
  995. 'command' => 'test',
  996. 'arguments' => [
  997. 'name' => ['help' => 'The name'],
  998. 'other' => ['help' => 'The other arg'],
  999. ],
  1000. 'options' => [
  1001. 'name' => ['help' => 'The name'],
  1002. 'other' => ['help' => 'The other arg'],
  1003. ],
  1004. 'subcommands' => [
  1005. 'initdb' => ['help' => 'make database'],
  1006. ],
  1007. 'description' => 'description text',
  1008. 'epilog' => 'epilog text',
  1009. ];
  1010. $parser = ConsoleOptionParser::buildFromArray($spec);
  1011. $result = $parser->toArray();
  1012. $this->assertEquals($spec['description'], $result['description']);
  1013. $this->assertEquals($spec['epilog'], $result['epilog']);
  1014. $options = $result['options'];
  1015. $this->assertArrayHasKey('name', $options);
  1016. $this->assertArrayHasKey('other', $options);
  1017. $this->assertCount(2, $result['arguments']);
  1018. $this->assertCount(1, $result['subcommands']);
  1019. }
  1020. /**
  1021. * Tests merge()
  1022. *
  1023. * @return void
  1024. */
  1025. public function testMerge()
  1026. {
  1027. $parser = new ConsoleOptionParser('test');
  1028. $parser->addOption('test', ['short' => 't', 'boolean' => true])
  1029. ->addArgument('one', ['required' => true, 'choices' => ['a', 'b']])
  1030. ->addArgument('two', ['required' => true]);
  1031. $parserTwo = new ConsoleOptionParser('test');
  1032. $parserTwo->addOption('file', ['short' => 'f', 'boolean' => true])
  1033. ->addOption('output', ['short' => 'o', 'boolean' => true])
  1034. ->addArgument('one', ['required' => true, 'choices' => ['a', 'b']]);
  1035. $parser->merge($parserTwo);
  1036. $result = $parser->toArray();
  1037. $options = $result['options'];
  1038. $this->assertArrayHasKey('quiet', $options);
  1039. $this->assertArrayHasKey('test', $options);
  1040. $this->assertArrayHasKey('file', $options);
  1041. $this->assertArrayHasKey('output', $options);
  1042. $this->assertCount(2, $result['arguments']);
  1043. $this->assertCount(6, $result['options']);
  1044. }
  1045. }