CommandRunnerTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  12. * @link http://cakephp.org CakePHP(tm) Project
  13. * @since 3.5.0
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Console;
  17. use Cake\Console\CommandCollection;
  18. use Cake\Console\CommandFactoryInterface;
  19. use Cake\Console\CommandRunner;
  20. use Cake\Console\ConsoleIo;
  21. use Cake\Console\Shell;
  22. use Cake\Core\Configure;
  23. use Cake\Core\ConsoleApplicationInterface;
  24. use Cake\Event\EventManager;
  25. use Cake\Http\BaseApplication;
  26. use Cake\Routing\Router;
  27. use Cake\TestSuite\Stub\ConsoleOutput;
  28. use Cake\TestSuite\TestCase;
  29. use InvalidArgumentException;
  30. use TestApp\Command\AbortCommand;
  31. use TestApp\Command\DemoCommand;
  32. use TestApp\Command\DependencyCommand;
  33. use TestApp\Shell\SampleShell;
  34. /**
  35. * Test case for the CommandCollection
  36. */
  37. class CommandRunnerTest extends TestCase
  38. {
  39. /**
  40. * @var string
  41. */
  42. protected $config;
  43. /**
  44. * Tracking property for event triggering
  45. *
  46. * @var bool
  47. */
  48. protected $eventTriggered = false;
  49. /**
  50. * setup
  51. *
  52. * @return void
  53. */
  54. public function setUp(): void
  55. {
  56. parent::setUp();
  57. Configure::write('App.namespace', 'TestApp');
  58. $this->config = dirname(dirname(__DIR__));
  59. }
  60. /**
  61. * test event manager proxies to the application.
  62. *
  63. * @return void
  64. */
  65. public function testEventManagerProxies()
  66. {
  67. $app = $this->getMockForAbstractClass(
  68. BaseApplication::class,
  69. [$this->config]
  70. );
  71. $runner = new CommandRunner($app);
  72. $this->assertSame($app->getEventManager(), $runner->getEventManager());
  73. }
  74. /**
  75. * test event manager cannot be set on applications without events.
  76. *
  77. * @return void
  78. */
  79. public function testGetEventManagerNonEventedApplication()
  80. {
  81. $app = $this->createMock(ConsoleApplicationInterface::class);
  82. $runner = new CommandRunner($app);
  83. $this->assertSame(EventManager::instance(), $runner->getEventManager());
  84. }
  85. /**
  86. * test event manager cannot be set on applications without events.
  87. *
  88. * @return void
  89. */
  90. public function testSetEventManagerNonEventedApplication()
  91. {
  92. $this->expectException(InvalidArgumentException::class);
  93. $app = $this->createMock(ConsoleApplicationInterface::class);
  94. $events = new EventManager();
  95. $runner = new CommandRunner($app);
  96. $runner->setEventManager($events);
  97. }
  98. /**
  99. * Test that running with empty argv fails
  100. *
  101. * @return void
  102. */
  103. public function testRunMissingRootCommand()
  104. {
  105. $this->expectException(\RuntimeException::class);
  106. $this->expectExceptionMessage('Cannot run any commands. No arguments received.');
  107. $app = $this->getMockBuilder(BaseApplication::class)
  108. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  109. ->setConstructorArgs([$this->config])
  110. ->getMock();
  111. $runner = new CommandRunner($app);
  112. $runner->run([]);
  113. }
  114. /**
  115. * Test that running an unknown command raises an error.
  116. *
  117. * @return void
  118. */
  119. public function testRunInvalidCommand()
  120. {
  121. $app = $this->getMockBuilder(BaseApplication::class)
  122. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  123. ->setConstructorArgs([$this->config])
  124. ->getMock();
  125. $output = new ConsoleOutput();
  126. $runner = new CommandRunner($app);
  127. $runner->run(['cake', 'nope', 'nope', 'nope'], $this->getMockIo($output));
  128. $messages = implode("\n", $output->messages());
  129. $this->assertStringContainsString(
  130. 'Unknown command `cake nope`. Run `cake --help` to get the list of commands.',
  131. $messages
  132. );
  133. }
  134. /**
  135. * Test that running an unknown command gives suggestions.
  136. *
  137. * @return void
  138. */
  139. public function testRunInvalidCommandSuggestion()
  140. {
  141. $app = $this->getMockBuilder(BaseApplication::class)
  142. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  143. ->setConstructorArgs([$this->config])
  144. ->getMock();
  145. $output = new ConsoleOutput();
  146. $runner = new CommandRunner($app);
  147. $runner->run(['cake', 'cache'], $this->getMockIo($output));
  148. $messages = implode("\n", $output->messages());
  149. $this->assertStringContainsString(
  150. "Did you mean: `cache clear`?\n" .
  151. "\n" .
  152. "Other valid choices:\n" .
  153. "\n" .
  154. '- help',
  155. $messages
  156. );
  157. }
  158. /**
  159. * Test using `cake --help` invokes the help command
  160. *
  161. * @return void
  162. */
  163. public function testRunHelpLongOption()
  164. {
  165. $app = $this->getMockBuilder(BaseApplication::class)
  166. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  167. ->setConstructorArgs([$this->config])
  168. ->getMock();
  169. $output = new ConsoleOutput();
  170. $runner = new CommandRunner($app, 'cake');
  171. $result = $runner->run(['cake', '--help'], $this->getMockIo($output));
  172. $this->assertSame(0, $result);
  173. $messages = implode("\n", $output->messages());
  174. $this->assertStringContainsString('Current Paths', $messages);
  175. $this->assertStringContainsString('- i18n', $messages);
  176. $this->assertStringContainsString('Available Commands', $messages);
  177. }
  178. /**
  179. * Test using `cake -h` invokes the help command
  180. *
  181. * @return void
  182. */
  183. public function testRunHelpShortOption()
  184. {
  185. $app = $this->getMockBuilder(BaseApplication::class)
  186. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  187. ->setConstructorArgs([$this->config])
  188. ->getMock();
  189. $output = new ConsoleOutput();
  190. $runner = new CommandRunner($app, 'cake');
  191. $result = $runner->run(['cake', '-h'], $this->getMockIo($output));
  192. $this->assertSame(0, $result);
  193. $messages = implode("\n", $output->messages());
  194. $this->assertStringContainsString('- i18n', $messages);
  195. $this->assertStringContainsString('Available Commands', $messages);
  196. }
  197. /**
  198. * Test that no command outputs the command list
  199. *
  200. * @return void
  201. */
  202. public function testRunNoCommand()
  203. {
  204. $app = $this->getMockBuilder(BaseApplication::class)
  205. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  206. ->setConstructorArgs([$this->config])
  207. ->getMock();
  208. $output = new ConsoleOutput();
  209. $runner = new CommandRunner($app);
  210. $result = $runner->run(['cake'], $this->getMockIo($output));
  211. $this->assertSame(0, $result, 'help output is success.');
  212. $messages = implode("\n", $output->messages());
  213. $this->assertStringContainsString('No command provided. Choose one of the available commands', $messages);
  214. $this->assertStringContainsString('- i18n', $messages);
  215. $this->assertStringContainsString('Available Commands', $messages);
  216. }
  217. /**
  218. * Test using `cake --version` invokes the version command
  219. *
  220. * @return void
  221. */
  222. public function testRunVersionAlias()
  223. {
  224. $app = $this->getMockBuilder(BaseApplication::class)
  225. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  226. ->setConstructorArgs([$this->config])
  227. ->getMock();
  228. $output = new ConsoleOutput();
  229. $runner = new CommandRunner($app, 'cake');
  230. $result = $runner->run(['cake', '--version'], $this->getMockIo($output));
  231. $this->assertStringContainsString(Configure::version(), $output->messages()[0]);
  232. }
  233. /**
  234. * Test running a valid command
  235. *
  236. * @return void
  237. */
  238. public function testRunValidCommand()
  239. {
  240. $app = $this->getMockBuilder(BaseApplication::class)
  241. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  242. ->setConstructorArgs([$this->config])
  243. ->getMock();
  244. $output = new ConsoleOutput();
  245. $runner = new CommandRunner($app, 'cake');
  246. $result = $runner->run(['cake', 'routes'], $this->getMockIo($output));
  247. $this->assertSame(Shell::CODE_SUCCESS, $result);
  248. $contents = implode("\n", $output->messages());
  249. $this->assertStringContainsString('URI template', $contents);
  250. }
  251. /**
  252. * Test running a valid command and that backwards compatible
  253. * inflection is hooked up.
  254. *
  255. * @return void
  256. */
  257. public function testRunValidCommandInflection()
  258. {
  259. $app = $this->getMockBuilder(BaseApplication::class)
  260. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  261. ->setConstructorArgs([$this->config])
  262. ->getMock();
  263. $output = new ConsoleOutput();
  264. $runner = new CommandRunner($app, 'cake');
  265. $result = $runner->run(['cake', 'schema_cache', 'build'], $this->getMockIo($output));
  266. $this->assertSame(Shell::CODE_SUCCESS, $result);
  267. $contents = implode("\n", $output->messages());
  268. $this->assertStringContainsString('Cache', $contents);
  269. }
  270. /**
  271. * Test running a valid raising an error
  272. *
  273. * @return void
  274. */
  275. public function testRunValidCommandWithAbort()
  276. {
  277. $app = $this->makeAppWithCommands(['failure' => SampleShell::class]);
  278. $output = new ConsoleOutput();
  279. $runner = new CommandRunner($app, 'cake');
  280. $result = $runner->run(['cake', 'failure', 'with_abort'], $this->getMockIo($output));
  281. $this->assertSame(Shell::CODE_ERROR, $result);
  282. }
  283. /**
  284. * Test returning a non-zero value
  285. *
  286. * @return void
  287. */
  288. public function testRunValidCommandReturnInteger()
  289. {
  290. $app = $this->makeAppWithCommands(['failure' => SampleShell::class]);
  291. $output = new ConsoleOutput();
  292. $runner = new CommandRunner($app, 'cake');
  293. $result = $runner->run(['cake', 'failure', 'returnValue'], $this->getMockIo($output));
  294. $this->assertSame(99, $result);
  295. }
  296. /**
  297. * Ensure that the root command name propagates to shell help
  298. *
  299. * @return void
  300. */
  301. public function testRunRootNamePropagates()
  302. {
  303. $app = $this->makeAppWithCommands(['sample' => SampleShell::class]);
  304. $output = new ConsoleOutput();
  305. $runner = new CommandRunner($app, 'widget');
  306. $runner->run(['widget', 'sample', '-h'], $this->getMockIo($output));
  307. $result = implode("\n", $output->messages());
  308. $this->assertStringContainsString('widget sample [-h]', $result);
  309. $this->assertStringNotContainsString('cake sample [-h]', $result);
  310. }
  311. /**
  312. * Test running a valid command
  313. *
  314. * @return void
  315. */
  316. public function testRunValidCommandClass()
  317. {
  318. $app = $this->makeAppWithCommands(['ex' => DemoCommand::class]);
  319. $output = new ConsoleOutput();
  320. $runner = new CommandRunner($app, 'cake');
  321. $result = $runner->run(['cake', 'ex'], $this->getMockIo($output));
  322. $this->assertSame(Shell::CODE_SUCCESS, $result);
  323. $messages = implode("\n", $output->messages());
  324. $this->assertStringContainsString('Demo Command!', $messages);
  325. }
  326. /**
  327. * Test running a valid command with spaces in the name
  328. *
  329. * @return void
  330. */
  331. public function testRunValidCommandSubcommandName()
  332. {
  333. $app = $this->makeAppWithCommands([
  334. 'tool build' => DemoCommand::class,
  335. 'tool' => AbortCommand::class,
  336. ]);
  337. $output = new ConsoleOutput();
  338. $runner = new CommandRunner($app, 'cake');
  339. $result = $runner->run(['cake', 'tool', 'build'], $this->getMockIo($output));
  340. $this->assertSame(Shell::CODE_SUCCESS, $result);
  341. $messages = implode("\n", $output->messages());
  342. $this->assertStringContainsString('Demo Command!', $messages);
  343. }
  344. /**
  345. * Test running a valid command with spaces in the name
  346. *
  347. * @return void
  348. */
  349. public function testRunValidCommandNestedName()
  350. {
  351. $app = $this->makeAppWithCommands([
  352. 'tool build assets' => DemoCommand::class,
  353. 'tool' => AbortCommand::class,
  354. ]);
  355. $output = new ConsoleOutput();
  356. $runner = new CommandRunner($app, 'cake');
  357. $result = $runner->run(['cake', 'tool', 'build', 'assets'], $this->getMockIo($output));
  358. $this->assertSame(Shell::CODE_SUCCESS, $result);
  359. $messages = implode("\n", $output->messages());
  360. $this->assertStringContainsString('Demo Command!', $messages);
  361. }
  362. /**
  363. * Test using a custom factory
  364. *
  365. * @return void
  366. */
  367. public function testRunWithCustomFactory()
  368. {
  369. $output = new ConsoleOutput();
  370. $io = $this->getMockIo($output);
  371. $factory = $this->createMock(CommandFactoryInterface::class);
  372. $factory->expects($this->once())
  373. ->method('create')
  374. ->with(DemoCommand::class)
  375. ->willReturn(new DemoCommand());
  376. $app = $this->makeAppWithCommands(['ex' => DemoCommand::class]);
  377. $runner = new CommandRunner($app, 'cake', $factory);
  378. $result = $runner->run(['cake', 'ex'], $io);
  379. $this->assertSame(Shell::CODE_SUCCESS, $result);
  380. $messages = implode("\n", $output->messages());
  381. $this->assertStringContainsString('Demo Command!', $messages);
  382. }
  383. public function testRunWithContainerDependencies()
  384. {
  385. $app = $this->makeAppWithCommands([
  386. 'dependency' => DependencyCommand::class,
  387. ]);
  388. $container = $app->getContainer();
  389. $container->add(stdClass::class, json_decode('{"key":"value"}'));
  390. $container->add(DependencyCommand::class)
  391. ->addArgument(stdClass::class);
  392. $output = new ConsoleOutput();
  393. $runner = new CommandRunner($app, 'cake');
  394. $result = $runner->run(['cake', 'dependency'], $this->getMockIo($output));
  395. $this->assertSame(Shell::CODE_SUCCESS, $result);
  396. $messages = implode("\n", $output->messages());
  397. $this->assertStringContainsString('Dependency Command', $messages);
  398. $this->assertStringContainsString('constructor inject: {"key":"value"}', $messages);
  399. }
  400. /**
  401. * Test running a command class' help
  402. *
  403. * @return void
  404. */
  405. public function testRunValidCommandClassHelp()
  406. {
  407. $app = $this->makeAppWithCommands(['ex' => DemoCommand::class]);
  408. $output = new ConsoleOutput();
  409. $runner = new CommandRunner($app, 'cake');
  410. $result = $runner->run(['cake', 'ex', '-h'], $this->getMockIo($output));
  411. $this->assertSame(Shell::CODE_SUCCESS, $result);
  412. $messages = implode("\n", $output->messages());
  413. $this->assertStringContainsString("\ncake ex [-h]", $messages);
  414. $this->assertStringNotContainsString('Demo Command!', $messages);
  415. }
  416. /**
  417. * Test that run() fires off the buildCommands event.
  418. *
  419. * @return void
  420. */
  421. public function testRunTriggersBuildCommandsEvent()
  422. {
  423. $app = $this->getMockBuilder(BaseApplication::class)
  424. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  425. ->setConstructorArgs([$this->config])
  426. ->getMock();
  427. $output = new ConsoleOutput();
  428. $runner = new CommandRunner($app, 'cake');
  429. $runner->getEventManager()->on('Console.buildCommands', function ($event, $commands) {
  430. $this->assertInstanceOf(CommandCollection::class, $commands);
  431. $this->eventTriggered = true;
  432. });
  433. $result = $runner->run(['cake', '--version'], $this->getMockIo($output));
  434. $this->assertTrue($this->eventTriggered, 'Should have triggered event.');
  435. }
  436. /**
  437. * Test that run calls plugin hook methods
  438. *
  439. * @return void
  440. */
  441. public function testRunCallsPluginHookMethods()
  442. {
  443. $app = $this->getMockBuilder(BaseApplication::class)
  444. ->onlyMethods([
  445. 'middleware', 'bootstrap', 'routes',
  446. 'pluginBootstrap', 'pluginConsole', 'pluginRoutes',
  447. ])
  448. ->setConstructorArgs([$this->config])
  449. ->getMock();
  450. $app->expects($this->once())->method('bootstrap');
  451. $app->expects($this->once())->method('pluginBootstrap');
  452. $commands = new CommandCollection();
  453. $app->expects($this->once())
  454. ->method('pluginConsole')
  455. ->with($this->isinstanceOf(CommandCollection::class))
  456. ->will($this->returnCallback(function ($commands) {
  457. return $commands;
  458. }));
  459. $app->expects($this->once())->method('routes');
  460. $app->expects($this->once())->method('pluginRoutes');
  461. $output = new ConsoleOutput();
  462. $runner = new CommandRunner($app, 'cake');
  463. $result = $runner->run(['cake', '--version'], $this->getMockIo($output));
  464. $this->assertStringContainsString(Configure::version(), $output->messages()[0]);
  465. }
  466. /**
  467. * Test that run() loads routing.
  468. *
  469. * @return void
  470. */
  471. public function testRunLoadsRoutes()
  472. {
  473. $app = $this->getMockBuilder(BaseApplication::class)
  474. ->onlyMethods(['middleware', 'bootstrap'])
  475. ->setConstructorArgs([TEST_APP . 'config' . DS])
  476. ->getMock();
  477. $output = new ConsoleOutput();
  478. $runner = new CommandRunner($app, 'cake');
  479. $runner->run(['cake', '--version'], $this->getMockIo($output));
  480. $this->assertGreaterThan(2, count(Router::getRouteCollection()->routes()));
  481. }
  482. protected function makeAppWithCommands(array $commands)
  483. {
  484. $app = $this->getMockBuilder(BaseApplication::class)
  485. ->onlyMethods(['middleware', 'bootstrap', 'console', 'routes'])
  486. ->setConstructorArgs([$this->config])
  487. ->getMock();
  488. $collection = new CommandCollection($commands);
  489. $app->method('console')->will($this->returnValue($collection));
  490. return $app;
  491. }
  492. protected function getMockIo(ConsoleOutput $output)
  493. {
  494. $io = $this->getMockBuilder(ConsoleIo::class)
  495. ->setConstructorArgs([$output, $output, null, null])
  496. ->addMethods(['in'])
  497. ->getMock();
  498. return $io;
  499. }
  500. }