CommandRunnerTest.php 19 KB

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