CommandTest.php 18 KB

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