CommandRunnerTest.php 19 KB

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