CommandTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Tests\Command;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Console\Application;
  13. use Symfony\Component\Console\Attribute\AsCommand;
  14. use Symfony\Component\Console\Command\Command;
  15. use Symfony\Component\Console\Exception\InvalidOptionException;
  16. use Symfony\Component\Console\Helper\FormatterHelper;
  17. use Symfony\Component\Console\Input\InputArgument;
  18. use Symfony\Component\Console\Input\InputDefinition;
  19. use Symfony\Component\Console\Input\InputInterface;
  20. use Symfony\Component\Console\Input\InputOption;
  21. use Symfony\Component\Console\Input\StringInput;
  22. use Symfony\Component\Console\Output\NullOutput;
  23. use Symfony\Component\Console\Output\OutputInterface;
  24. use Symfony\Component\Console\Tester\CommandTester;
  25. class CommandTest extends TestCase
  26. {
  27. protected static $fixturesPath;
  28. public static function setUpBeforeClass(): void
  29. {
  30. self::$fixturesPath = __DIR__.'/../Fixtures/';
  31. require_once self::$fixturesPath.'/TestCommand.php';
  32. }
  33. public function testConstructor()
  34. {
  35. $command = new Command('foo:bar');
  36. $this->assertEquals('foo:bar', $command->getName(), '__construct() takes the command name as its first argument');
  37. }
  38. public function testCommandNameCannotBeEmpty()
  39. {
  40. $this->expectException(\LogicException::class);
  41. $this->expectExceptionMessage('The command defined in "Symfony\Component\Console\Command\Command" cannot have an empty name.');
  42. (new Application())->add(new Command());
  43. }
  44. public function testSetApplication()
  45. {
  46. $application = new Application();
  47. $command = new \TestCommand();
  48. $command->setApplication($application);
  49. $this->assertEquals($application, $command->getApplication(), '->setApplication() sets the current application');
  50. $this->assertEquals($application->getHelperSet(), $command->getHelperSet());
  51. }
  52. public function testSetApplicationNull()
  53. {
  54. $command = new \TestCommand();
  55. $command->setApplication(null);
  56. $this->assertNull($command->getHelperSet());
  57. }
  58. public function testSetGetDefinition()
  59. {
  60. $command = new \TestCommand();
  61. $ret = $command->setDefinition($definition = new InputDefinition());
  62. $this->assertEquals($command, $ret, '->setDefinition() implements a fluent interface');
  63. $this->assertEquals($definition, $command->getDefinition(), '->setDefinition() sets the current InputDefinition instance');
  64. $command->setDefinition([new InputArgument('foo'), new InputOption('bar')]);
  65. $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument');
  66. $this->assertTrue($command->getDefinition()->hasOption('bar'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument');
  67. $command->setDefinition(new InputDefinition());
  68. }
  69. public function testAddArgument()
  70. {
  71. $command = new \TestCommand();
  72. $ret = $command->addArgument('foo');
  73. $this->assertEquals($command, $ret, '->addArgument() implements a fluent interface');
  74. $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->addArgument() adds an argument to the command');
  75. }
  76. public function testAddOption()
  77. {
  78. $command = new \TestCommand();
  79. $ret = $command->addOption('foo');
  80. $this->assertEquals($command, $ret, '->addOption() implements a fluent interface');
  81. $this->assertTrue($command->getDefinition()->hasOption('foo'), '->addOption() adds an option to the command');
  82. }
  83. public function testSetHidden()
  84. {
  85. $command = new \TestCommand();
  86. $command->setHidden(true);
  87. $this->assertTrue($command->isHidden());
  88. }
  89. public function testGetNamespaceGetNameSetName()
  90. {
  91. $command = new \TestCommand();
  92. $this->assertEquals('namespace:name', $command->getName(), '->getName() returns the command name');
  93. $command->setName('foo');
  94. $this->assertEquals('foo', $command->getName(), '->setName() sets the command name');
  95. $ret = $command->setName('foobar:bar');
  96. $this->assertEquals($command, $ret, '->setName() implements a fluent interface');
  97. $this->assertEquals('foobar:bar', $command->getName(), '->setName() sets the command name');
  98. }
  99. /**
  100. * @dataProvider provideInvalidCommandNames
  101. */
  102. public function testInvalidCommandNames($name)
  103. {
  104. $this->expectException(\InvalidArgumentException::class);
  105. $this->expectExceptionMessage(sprintf('Command name "%s" is invalid.', $name));
  106. $command = new \TestCommand();
  107. $command->setName($name);
  108. }
  109. public static function provideInvalidCommandNames()
  110. {
  111. return [
  112. [''],
  113. ['foo:'],
  114. ];
  115. }
  116. public function testGetSetDescription()
  117. {
  118. $command = new \TestCommand();
  119. $this->assertEquals('description', $command->getDescription(), '->getDescription() returns the description');
  120. $ret = $command->setDescription('description1');
  121. $this->assertEquals($command, $ret, '->setDescription() implements a fluent interface');
  122. $this->assertEquals('description1', $command->getDescription(), '->setDescription() sets the description');
  123. }
  124. public function testGetSetHelp()
  125. {
  126. $command = new \TestCommand();
  127. $this->assertEquals('help', $command->getHelp(), '->getHelp() returns the help');
  128. $ret = $command->setHelp('help1');
  129. $this->assertEquals($command, $ret, '->setHelp() implements a fluent interface');
  130. $this->assertEquals('help1', $command->getHelp(), '->setHelp() sets the help');
  131. $command->setHelp('');
  132. $this->assertEquals('', $command->getHelp(), '->getHelp() does not fall back to the description');
  133. }
  134. public function testGetProcessedHelp()
  135. {
  136. $command = new \TestCommand();
  137. $command->setHelp('The %command.name% command does... Example: %command.full_name%.');
  138. $this->assertStringContainsString('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly');
  139. $this->assertStringNotContainsString('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name%');
  140. $command = new \TestCommand();
  141. $command->setHelp('');
  142. $this->assertStringContainsString('description', $command->getProcessedHelp(), '->getProcessedHelp() falls back to the description');
  143. $command = new \TestCommand();
  144. $command->setHelp('The %command.name% command does... Example: %command.full_name%.');
  145. $application = new Application();
  146. $application->add($command);
  147. $application->setDefaultCommand('namespace:name', true);
  148. $this->assertStringContainsString('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly in single command applications');
  149. $this->assertStringNotContainsString('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name% in single command applications');
  150. }
  151. public function testGetSetAliases()
  152. {
  153. $command = new \TestCommand();
  154. $this->assertEquals(['name'], $command->getAliases(), '->getAliases() returns the aliases');
  155. $ret = $command->setAliases(['name1']);
  156. $this->assertEquals($command, $ret, '->setAliases() implements a fluent interface');
  157. $this->assertEquals(['name1'], $command->getAliases(), '->setAliases() sets the aliases');
  158. }
  159. public function testGetSynopsis()
  160. {
  161. $command = new \TestCommand();
  162. $command->addOption('foo');
  163. $command->addArgument('bar');
  164. $command->addArgument('info');
  165. $this->assertEquals('namespace:name [--foo] [--] [<bar> [<info>]]', $command->getSynopsis(), '->getSynopsis() returns the synopsis');
  166. }
  167. public function testAddGetUsages()
  168. {
  169. $command = new \TestCommand();
  170. $command->addUsage('foo1');
  171. $command->addUsage('foo2');
  172. $this->assertContains('namespace:name foo1', $command->getUsages());
  173. $this->assertContains('namespace:name foo2', $command->getUsages());
  174. }
  175. public function testGetHelper()
  176. {
  177. $application = new Application();
  178. $command = new \TestCommand();
  179. $command->setApplication($application);
  180. $formatterHelper = new FormatterHelper();
  181. $this->assertEquals($formatterHelper->getName(), $command->getHelper('formatter')->getName(), '->getHelper() returns the correct helper');
  182. }
  183. public function testGetHelperWithoutHelperSet()
  184. {
  185. $this->expectException(\LogicException::class);
  186. $this->expectExceptionMessage('Cannot retrieve helper "formatter" because there is no HelperSet defined.');
  187. $command = new \TestCommand();
  188. $command->getHelper('formatter');
  189. }
  190. public function testMergeApplicationDefinition()
  191. {
  192. $application1 = new Application();
  193. $application1->getDefinition()->addArguments([new InputArgument('foo')]);
  194. $application1->getDefinition()->addOptions([new InputOption('bar')]);
  195. $command = new \TestCommand();
  196. $command->setApplication($application1);
  197. $command->setDefinition($definition = new InputDefinition([new InputArgument('bar'), new InputOption('foo')]));
  198. $r = new \ReflectionObject($command);
  199. $m = $r->getMethod('mergeApplicationDefinition');
  200. $m->setAccessible(true);
  201. $m->invoke($command);
  202. $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition() merges the application arguments and the command arguments');
  203. $this->assertTrue($command->getDefinition()->hasArgument('bar'), '->mergeApplicationDefinition() merges the application arguments and the command arguments');
  204. $this->assertTrue($command->getDefinition()->hasOption('foo'), '->mergeApplicationDefinition() merges the application options and the command options');
  205. $this->assertTrue($command->getDefinition()->hasOption('bar'), '->mergeApplicationDefinition() merges the application options and the command options');
  206. $m->invoke($command);
  207. $this->assertEquals(3, $command->getDefinition()->getArgumentCount(), '->mergeApplicationDefinition() does not try to merge twice the application arguments and options');
  208. }
  209. public function testMergeApplicationDefinitionWithoutArgsThenWithArgsAddsArgs()
  210. {
  211. $application1 = new Application();
  212. $application1->getDefinition()->addArguments([new InputArgument('foo')]);
  213. $application1->getDefinition()->addOptions([new InputOption('bar')]);
  214. $command = new \TestCommand();
  215. $command->setApplication($application1);
  216. $command->setDefinition($definition = new InputDefinition([]));
  217. $r = new \ReflectionObject($command);
  218. $m = $r->getMethod('mergeApplicationDefinition');
  219. $m->setAccessible(true);
  220. $m->invoke($command, false);
  221. $this->assertTrue($command->getDefinition()->hasOption('bar'), '->mergeApplicationDefinition(false) merges the application and the command options');
  222. $this->assertFalse($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition(false) does not merge the application arguments');
  223. $m->invoke($command, true);
  224. $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition(true) merges the application arguments and the command arguments');
  225. $m->invoke($command);
  226. $this->assertEquals(2, $command->getDefinition()->getArgumentCount(), '->mergeApplicationDefinition() does not try to merge twice the application arguments');
  227. }
  228. public function testRunInteractive()
  229. {
  230. $tester = new CommandTester(new \TestCommand());
  231. $tester->execute([], ['interactive' => true]);
  232. $this->assertEquals('interact called'.\PHP_EOL.'execute called'.\PHP_EOL, $tester->getDisplay(), '->run() calls the interact() method if the input is interactive');
  233. }
  234. public function testRunNonInteractive()
  235. {
  236. $tester = new CommandTester(new \TestCommand());
  237. $tester->execute([], ['interactive' => false]);
  238. $this->assertEquals('execute called'.\PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive');
  239. }
  240. public function testExecuteMethodNeedsToBeOverridden()
  241. {
  242. $this->expectException(\LogicException::class);
  243. $this->expectExceptionMessage('You must override the execute() method in the concrete command class.');
  244. $command = new Command('foo');
  245. $command->run(new StringInput(''), new NullOutput());
  246. }
  247. public function testRunWithInvalidOption()
  248. {
  249. $this->expectException(InvalidOptionException::class);
  250. $this->expectExceptionMessage('The "--bar" option does not exist.');
  251. $command = new \TestCommand();
  252. $tester = new CommandTester($command);
  253. $tester->execute(['--bar' => true]);
  254. }
  255. public function testRunWithApplication()
  256. {
  257. $command = new \TestCommand();
  258. $command->setApplication(new Application());
  259. $exitCode = $command->run(new StringInput(''), new NullOutput());
  260. $this->assertSame(0, $exitCode, '->run() returns an integer exit code');
  261. }
  262. public function testRunReturnsAlwaysInteger()
  263. {
  264. $command = new \TestCommand();
  265. $this->assertSame(0, $command->run(new StringInput(''), new NullOutput()));
  266. }
  267. public function testRunWithProcessTitle()
  268. {
  269. $command = new \TestCommand();
  270. $command->setApplication(new Application());
  271. $command->setProcessTitle('foo');
  272. $this->assertSame(0, $command->run(new StringInput(''), new NullOutput()));
  273. if (\function_exists('cli_set_process_title')) {
  274. if (null === @cli_get_process_title() && 'Darwin' === \PHP_OS) {
  275. $this->markTestSkipped('Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.');
  276. }
  277. $this->assertEquals('foo', cli_get_process_title());
  278. }
  279. }
  280. public function testSetCode()
  281. {
  282. $command = new \TestCommand();
  283. $ret = $command->setCode(function (InputInterface $input, OutputInterface $output) {
  284. $output->writeln('from the code...');
  285. });
  286. $this->assertEquals($command, $ret, '->setCode() implements a fluent interface');
  287. $tester = new CommandTester($command);
  288. $tester->execute([]);
  289. $this->assertEquals('interact called'.\PHP_EOL.'from the code...'.\PHP_EOL, $tester->getDisplay());
  290. }
  291. public static function getSetCodeBindToClosureTests()
  292. {
  293. return [
  294. [true, 'not bound to the command'],
  295. [false, 'bound to the command'],
  296. ];
  297. }
  298. /**
  299. * @dataProvider getSetCodeBindToClosureTests
  300. */
  301. public function testSetCodeBindToClosure($previouslyBound, $expected)
  302. {
  303. $code = createClosure();
  304. if ($previouslyBound) {
  305. $code = $code->bindTo($this);
  306. }
  307. $command = new \TestCommand();
  308. $command->setCode($code);
  309. $tester = new CommandTester($command);
  310. $tester->execute([]);
  311. $this->assertEquals('interact called'.\PHP_EOL.$expected.\PHP_EOL, $tester->getDisplay());
  312. }
  313. public function testSetCodeWithStaticClosure()
  314. {
  315. $command = new \TestCommand();
  316. $command->setCode(self::createClosure());
  317. $tester = new CommandTester($command);
  318. $tester->execute([]);
  319. $this->assertEquals('interact called'.\PHP_EOL.'bound'.\PHP_EOL, $tester->getDisplay());
  320. }
  321. private static function createClosure()
  322. {
  323. return function (InputInterface $input, OutputInterface $output) {
  324. $output->writeln(isset($this) ? 'bound' : 'not bound');
  325. };
  326. }
  327. public function testSetCodeWithNonClosureCallable()
  328. {
  329. $command = new \TestCommand();
  330. $ret = $command->setCode([$this, 'callableMethodCommand']);
  331. $this->assertEquals($command, $ret, '->setCode() implements a fluent interface');
  332. $tester = new CommandTester($command);
  333. $tester->execute([]);
  334. $this->assertEquals('interact called'.\PHP_EOL.'from the code...'.\PHP_EOL, $tester->getDisplay());
  335. }
  336. public function callableMethodCommand(InputInterface $input, OutputInterface $output)
  337. {
  338. $output->writeln('from the code...');
  339. }
  340. public function testSetCodeWithStaticAnonymousFunction()
  341. {
  342. $command = new \TestCommand();
  343. $command->setCode(static function (InputInterface $input, OutputInterface $output) {
  344. $output->writeln(isset($this) ? 'bound' : 'not bound');
  345. });
  346. $tester = new CommandTester($command);
  347. $tester->execute([]);
  348. $this->assertEquals('interact called'.\PHP_EOL.'not bound'.\PHP_EOL, $tester->getDisplay());
  349. }
  350. /**
  351. * @requires PHP 8
  352. */
  353. public function testCommandAttribute()
  354. {
  355. $this->assertSame('|foo|f', Php8Command::getDefaultName());
  356. $this->assertSame('desc', Php8Command::getDefaultDescription());
  357. $command = new Php8Command();
  358. $this->assertSame('foo', $command->getName());
  359. $this->assertSame('desc', $command->getDescription());
  360. $this->assertTrue($command->isHidden());
  361. $this->assertSame(['f'], $command->getAliases());
  362. }
  363. /**
  364. * @requires PHP 8
  365. */
  366. public function testDefaultCommand()
  367. {
  368. $apl = new Application();
  369. $apl->setDefaultCommand(Php8Command::getDefaultName());
  370. $property = new \ReflectionProperty($apl, 'defaultCommand');
  371. $property->setAccessible(true);
  372. $this->assertEquals('foo', $property->getValue($apl));
  373. $apl->setDefaultCommand(Php8Command2::getDefaultName());
  374. $property = new \ReflectionProperty($apl, 'defaultCommand');
  375. $property->setAccessible(true);
  376. $this->assertEquals('foo2', $property->getValue($apl));
  377. }
  378. }
  379. // In order to get an unbound closure, we should create it outside a class
  380. // scope.
  381. function createClosure()
  382. {
  383. return function (InputInterface $input, OutputInterface $output) {
  384. $output->writeln($this instanceof Command ? 'bound to the command' : 'not bound to the command');
  385. };
  386. }
  387. #[AsCommand(name: 'foo', description: 'desc', hidden: true, aliases: ['f'])]
  388. class Php8Command extends Command
  389. {
  390. }
  391. #[AsCommand(name: 'foo2', description: 'desc2', hidden: true)]
  392. class Php8Command2 extends Command
  393. {
  394. }