CommandRunnerTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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\CommandInterface;
  20. use Cake\Console\CommandRunner;
  21. use Cake\Console\ConsoleIo;
  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 RuntimeException;
  31. use stdClass;
  32. use TestApp\Command\AbortCommand;
  33. use TestApp\Command\DemoCommand;
  34. use TestApp\Command\DependencyCommand;
  35. use TestApp\Command\SampleCommand;
  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 ConsoleOutput();
  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 ConsoleOutput();
  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 ConsoleOutput();
  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 ConsoleOutput();
  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 ConsoleOutput();
  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 ConsoleOutput();
  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 ConsoleOutput();
  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 ConsoleOutput();
  242. $runner = new CommandRunner($app, 'cake');
  243. $result = $runner->run(['cake', 'routes'], $this->getMockIo($output));
  244. $this->assertSame(CommandInterface::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 ConsoleOutput();
  259. $runner = new CommandRunner($app, 'cake');
  260. $result = $runner->run(['cake', 'schema_cache', 'build'], $this->getMockIo($output));
  261. $this->assertSame(CommandInterface::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' => AbortCommand::class]);
  271. $output = new ConsoleOutput();
  272. $runner = new CommandRunner($app, 'cake');
  273. $result = $runner->run(['cake', 'failure'], $this->getMockIo($output));
  274. $this->assertSame(127, $result);
  275. }
  276. /**
  277. * Ensure that the root command name propagates to shell help
  278. */
  279. public function testRunRootNamePropagates(): void
  280. {
  281. $app = $this->makeAppWithCommands(['sample' => SampleCommand::class]);
  282. $output = new ConsoleOutput();
  283. $runner = new CommandRunner($app, 'widget');
  284. $runner->run(['widget', 'sample', '-h'], $this->getMockIo($output));
  285. $result = implode("\n", $output->messages());
  286. $this->assertStringContainsString('widget sample [-h]', $result);
  287. $this->assertStringNotContainsString('cake sample [-h]', $result);
  288. }
  289. /**
  290. * Test running a valid command
  291. */
  292. public function testRunValidCommandClass(): void
  293. {
  294. $app = $this->makeAppWithCommands(['ex' => DemoCommand::class]);
  295. $output = new ConsoleOutput();
  296. $runner = new CommandRunner($app, 'cake');
  297. $result = $runner->run(['cake', 'ex'], $this->getMockIo($output));
  298. $this->assertSame(CommandInterface::CODE_SUCCESS, $result);
  299. $messages = implode("\n", $output->messages());
  300. $this->assertStringContainsString('Demo Command!', $messages);
  301. }
  302. /**
  303. * Test running a valid command with spaces in the name
  304. */
  305. public function testRunValidCommandSubcommandName(): void
  306. {
  307. $app = $this->makeAppWithCommands([
  308. 'tool build' => DemoCommand::class,
  309. 'tool' => AbortCommand::class,
  310. ]);
  311. $output = new ConsoleOutput();
  312. $runner = new CommandRunner($app, 'cake');
  313. $result = $runner->run(['cake', 'tool', 'build'], $this->getMockIo($output));
  314. $this->assertSame(CommandInterface::CODE_SUCCESS, $result);
  315. $messages = implode("\n", $output->messages());
  316. $this->assertStringContainsString('Demo Command!', $messages);
  317. }
  318. /**
  319. * Test running a valid command with spaces in the name
  320. */
  321. public function testRunValidCommandNestedName(): void
  322. {
  323. $app = $this->makeAppWithCommands([
  324. 'tool build assets' => DemoCommand::class,
  325. 'tool' => AbortCommand::class,
  326. ]);
  327. $output = new ConsoleOutput();
  328. $runner = new CommandRunner($app, 'cake');
  329. $result = $runner->run(['cake', 'tool', 'build', 'assets'], $this->getMockIo($output));
  330. $this->assertSame(CommandInterface::CODE_SUCCESS, $result);
  331. $messages = implode("\n", $output->messages());
  332. $this->assertStringContainsString('Demo Command!', $messages);
  333. }
  334. /**
  335. * Test using a custom factory
  336. */
  337. public function testRunWithCustomFactory(): void
  338. {
  339. $output = new ConsoleOutput();
  340. $io = $this->getMockIo($output);
  341. $factory = $this->createMock(CommandFactoryInterface::class);
  342. $factory->expects($this->once())
  343. ->method('create')
  344. ->with(DemoCommand::class)
  345. ->willReturn(new DemoCommand());
  346. $app = $this->makeAppWithCommands(['ex' => DemoCommand::class]);
  347. $runner = new CommandRunner($app, 'cake', $factory);
  348. $result = $runner->run(['cake', 'ex'], $io);
  349. $this->assertSame(CommandInterface::CODE_SUCCESS, $result);
  350. $messages = implode("\n", $output->messages());
  351. $this->assertStringContainsString('Demo Command!', $messages);
  352. }
  353. public function testRunWithContainerDependencies(): void
  354. {
  355. $app = $this->makeAppWithCommands([
  356. 'dependency' => DependencyCommand::class,
  357. ]);
  358. $container = $app->getContainer();
  359. $container->add(stdClass::class, json_decode('{"key":"value"}'));
  360. $container->add(DependencyCommand::class)
  361. ->addArgument(stdClass::class);
  362. $output = new ConsoleOutput();
  363. $runner = new CommandRunner($app, 'cake');
  364. $result = $runner->run(['cake', 'dependency'], $this->getMockIo($output));
  365. $this->assertSame(CommandInterface::CODE_SUCCESS, $result);
  366. $messages = implode("\n", $output->messages());
  367. $this->assertStringContainsString('Dependency Command', $messages);
  368. $this->assertStringContainsString('constructor inject: {"key":"value"}', $messages);
  369. }
  370. /**
  371. * Test running a command class' help
  372. */
  373. public function testRunValidCommandClassHelp(): void
  374. {
  375. $app = $this->makeAppWithCommands(['ex' => DemoCommand::class]);
  376. $output = new ConsoleOutput();
  377. $runner = new CommandRunner($app, 'cake');
  378. $result = $runner->run(['cake', 'ex', '-h'], $this->getMockIo($output));
  379. $this->assertSame(CommandInterface::CODE_SUCCESS, $result);
  380. $messages = implode("\n", $output->messages());
  381. $this->assertStringContainsString("\ncake ex [-h]", $messages);
  382. $this->assertStringNotContainsString('Demo Command!', $messages);
  383. }
  384. /**
  385. * Test that run() fires off the buildCommands event.
  386. */
  387. public function testRunTriggersBuildCommandsEvent(): void
  388. {
  389. $app = $this->getMockBuilder(BaseApplication::class)
  390. ->onlyMethods(['middleware', 'bootstrap', 'routes'])
  391. ->setConstructorArgs([$this->config])
  392. ->getMock();
  393. $output = new ConsoleOutput();
  394. $runner = new CommandRunner($app, 'cake');
  395. $runner->getEventManager()->on('Console.buildCommands', function ($event, $commands): void {
  396. $this->assertInstanceOf(CommandCollection::class, $commands);
  397. $this->eventTriggered = true;
  398. });
  399. $result = $runner->run(['cake', '--version'], $this->getMockIo($output));
  400. $this->assertTrue($this->eventTriggered, 'Should have triggered event.');
  401. }
  402. /**
  403. * Test that run calls plugin hook methods
  404. */
  405. public function testRunCallsPluginHookMethods(): void
  406. {
  407. $app = $this->getMockBuilder(BaseApplication::class)
  408. ->onlyMethods([
  409. 'middleware', 'bootstrap', 'routes',
  410. 'pluginBootstrap', 'pluginConsole', 'pluginRoutes',
  411. ])
  412. ->setConstructorArgs([$this->config])
  413. ->getMock();
  414. $app->expects($this->once())->method('bootstrap');
  415. $app->expects($this->once())->method('pluginBootstrap');
  416. $commands = new CommandCollection();
  417. $app->expects($this->once())
  418. ->method('pluginConsole')
  419. ->with($this->isinstanceOf(CommandCollection::class))
  420. ->will($this->returnCallback(function ($commands) {
  421. return $commands;
  422. }));
  423. $app->expects($this->once())->method('routes');
  424. $app->expects($this->once())->method('pluginRoutes');
  425. $output = new ConsoleOutput();
  426. $runner = new CommandRunner($app, 'cake');
  427. $result = $runner->run(['cake', '--version'], $this->getMockIo($output));
  428. $this->assertStringContainsString(Configure::version(), $output->messages()[0]);
  429. }
  430. /**
  431. * Test that run() loads routing.
  432. */
  433. public function testRunLoadsRoutes(): void
  434. {
  435. $app = $this->getMockBuilder(BaseApplication::class)
  436. ->onlyMethods(['middleware', 'bootstrap'])
  437. ->setConstructorArgs([TEST_APP . 'config' . DS])
  438. ->getMock();
  439. $output = new ConsoleOutput();
  440. $runner = new CommandRunner($app, 'cake');
  441. $runner->run(['cake', '--version'], $this->getMockIo($output));
  442. $this->assertGreaterThan(2, count(Router::getRouteCollection()->routes()));
  443. }
  444. protected function makeAppWithCommands(array $commands): BaseApplication
  445. {
  446. $app = $this->getMockBuilder(BaseApplication::class)
  447. ->onlyMethods(['middleware', 'bootstrap', 'console', 'routes'])
  448. ->setConstructorArgs([$this->config])
  449. ->getMock();
  450. $collection = new CommandCollection($commands);
  451. $app->method('console')->will($this->returnValue($collection));
  452. return $app;
  453. }
  454. protected function getMockIo(ConsoleOutput $output): ConsoleIo
  455. {
  456. $io = $this->getMockBuilder(ConsoleIo::class)
  457. ->setConstructorArgs([$output, $output, null, null])
  458. ->addMethods(['in'])
  459. ->getMock();
  460. return $io;
  461. }
  462. }