ConsoleOptionParserTest.php 34 KB

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