CommandRunnerTest.php 17 KB

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