ApplicationTest.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  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;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Console\Application;
  13. use Symfony\Component\Console\Command\Command;
  14. use Symfony\Component\Console\CommandLoader\FactoryCommandLoader;
  15. use Symfony\Component\Console\DependencyInjection\AddConsoleCommandPass;
  16. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  17. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  18. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  19. use Symfony\Component\Console\Exception\CommandNotFoundException;
  20. use Symfony\Component\Console\Exception\NamespaceNotFoundException;
  21. use Symfony\Component\Console\Helper\FormatterHelper;
  22. use Symfony\Component\Console\Helper\HelperSet;
  23. use Symfony\Component\Console\Input\ArgvInput;
  24. use Symfony\Component\Console\Input\ArrayInput;
  25. use Symfony\Component\Console\Input\InputArgument;
  26. use Symfony\Component\Console\Input\InputDefinition;
  27. use Symfony\Component\Console\Input\InputInterface;
  28. use Symfony\Component\Console\Input\InputOption;
  29. use Symfony\Component\Console\Output\NullOutput;
  30. use Symfony\Component\Console\Output\Output;
  31. use Symfony\Component\Console\Output\OutputInterface;
  32. use Symfony\Component\Console\Output\StreamOutput;
  33. use Symfony\Component\Console\Tester\ApplicationTester;
  34. use Symfony\Component\DependencyInjection\ContainerBuilder;
  35. use Symfony\Component\EventDispatcher\EventDispatcher;
  36. class ApplicationTest extends TestCase
  37. {
  38. protected static $fixturesPath;
  39. private $colSize;
  40. protected function setUp()
  41. {
  42. $this->colSize = getenv('COLUMNS');
  43. }
  44. protected function tearDown()
  45. {
  46. putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS');
  47. putenv('SHELL_VERBOSITY');
  48. unset($_ENV['SHELL_VERBOSITY']);
  49. unset($_SERVER['SHELL_VERBOSITY']);
  50. }
  51. public static function setUpBeforeClass()
  52. {
  53. self::$fixturesPath = realpath(__DIR__.'/Fixtures/');
  54. require_once self::$fixturesPath.'/FooCommand.php';
  55. require_once self::$fixturesPath.'/FooOptCommand.php';
  56. require_once self::$fixturesPath.'/Foo1Command.php';
  57. require_once self::$fixturesPath.'/Foo2Command.php';
  58. require_once self::$fixturesPath.'/Foo3Command.php';
  59. require_once self::$fixturesPath.'/Foo4Command.php';
  60. require_once self::$fixturesPath.'/Foo5Command.php';
  61. require_once self::$fixturesPath.'/FooSameCaseUppercaseCommand.php';
  62. require_once self::$fixturesPath.'/FooSameCaseLowercaseCommand.php';
  63. require_once self::$fixturesPath.'/FoobarCommand.php';
  64. require_once self::$fixturesPath.'/BarBucCommand.php';
  65. require_once self::$fixturesPath.'/FooSubnamespaced1Command.php';
  66. require_once self::$fixturesPath.'/FooSubnamespaced2Command.php';
  67. require_once self::$fixturesPath.'/FooWithoutAliasCommand.php';
  68. require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering.php';
  69. require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering2.php';
  70. }
  71. protected function normalizeLineBreaks($text)
  72. {
  73. return str_replace(PHP_EOL, "\n", $text);
  74. }
  75. /**
  76. * Replaces the dynamic placeholders of the command help text with a static version.
  77. * The placeholder %command.full_name% includes the script path that is not predictable
  78. * and can not be tested against.
  79. */
  80. protected function ensureStaticCommandHelp(Application $application)
  81. {
  82. foreach ($application->all() as $command) {
  83. $command->setHelp(str_replace('%command.full_name%', 'app/console %command.name%', $command->getHelp()));
  84. }
  85. }
  86. public function testConstructor()
  87. {
  88. $application = new Application('foo', 'bar');
  89. $this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument');
  90. $this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its second argument');
  91. $this->assertEquals(['help', 'list'], array_keys($application->all()), '__construct() registered the help and list commands by default');
  92. }
  93. public function testSetGetName()
  94. {
  95. $application = new Application();
  96. $application->setName('foo');
  97. $this->assertEquals('foo', $application->getName(), '->setName() sets the name of the application');
  98. }
  99. public function testSetGetVersion()
  100. {
  101. $application = new Application();
  102. $application->setVersion('bar');
  103. $this->assertEquals('bar', $application->getVersion(), '->setVersion() sets the version of the application');
  104. }
  105. public function testGetLongVersion()
  106. {
  107. $application = new Application('foo', 'bar');
  108. $this->assertEquals('foo <info>bar</info>', $application->getLongVersion(), '->getLongVersion() returns the long version of the application');
  109. }
  110. public function testHelp()
  111. {
  112. $application = new Application();
  113. $this->assertStringEqualsFile(self::$fixturesPath.'/application_gethelp.txt', $this->normalizeLineBreaks($application->getHelp()), '->getHelp() returns a help message');
  114. }
  115. public function testAll()
  116. {
  117. $application = new Application();
  118. $commands = $application->all();
  119. $this->assertInstanceOf('Symfony\\Component\\Console\\Command\\HelpCommand', $commands['help'], '->all() returns the registered commands');
  120. $application->add(new \FooCommand());
  121. $commands = $application->all('foo');
  122. $this->assertCount(1, $commands, '->all() takes a namespace as its first argument');
  123. }
  124. public function testAllWithCommandLoader()
  125. {
  126. $application = new Application();
  127. $commands = $application->all();
  128. $this->assertInstanceOf('Symfony\\Component\\Console\\Command\\HelpCommand', $commands['help'], '->all() returns the registered commands');
  129. $application->add(new \FooCommand());
  130. $commands = $application->all('foo');
  131. $this->assertCount(1, $commands, '->all() takes a namespace as its first argument');
  132. $application->setCommandLoader(new FactoryCommandLoader([
  133. 'foo:bar1' => function () { return new \Foo1Command(); },
  134. ]));
  135. $commands = $application->all('foo');
  136. $this->assertCount(2, $commands, '->all() takes a namespace as its first argument');
  137. $this->assertInstanceOf(\FooCommand::class, $commands['foo:bar'], '->all() returns the registered commands');
  138. $this->assertInstanceOf(\Foo1Command::class, $commands['foo:bar1'], '->all() returns the registered commands');
  139. }
  140. public function testRegister()
  141. {
  142. $application = new Application();
  143. $command = $application->register('foo');
  144. $this->assertEquals('foo', $command->getName(), '->register() registers a new command');
  145. }
  146. public function testRegisterAmbiguous()
  147. {
  148. $code = function (InputInterface $input, OutputInterface $output) {
  149. $output->writeln('It works!');
  150. };
  151. $application = new Application();
  152. $application->setAutoExit(false);
  153. $application
  154. ->register('test-foo')
  155. ->setAliases(['test'])
  156. ->setCode($code);
  157. $application
  158. ->register('test-bar')
  159. ->setCode($code);
  160. $tester = new ApplicationTester($application);
  161. $tester->run(['test']);
  162. $this->assertContains('It works!', $tester->getDisplay(true));
  163. }
  164. public function testAdd()
  165. {
  166. $application = new Application();
  167. $application->add($foo = new \FooCommand());
  168. $commands = $application->all();
  169. $this->assertEquals($foo, $commands['foo:bar'], '->add() registers a command');
  170. $application = new Application();
  171. $application->addCommands([$foo = new \FooCommand(), $foo1 = new \Foo1Command()]);
  172. $commands = $application->all();
  173. $this->assertEquals([$foo, $foo1], [$commands['foo:bar'], $commands['foo:bar1']], '->addCommands() registers an array of commands');
  174. }
  175. /**
  176. * @expectedException \LogicException
  177. * @expectedExceptionMessage Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor.
  178. */
  179. public function testAddCommandWithEmptyConstructor()
  180. {
  181. $application = new Application();
  182. $application->add(new \Foo5Command());
  183. }
  184. public function testHasGet()
  185. {
  186. $application = new Application();
  187. $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered');
  188. $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered');
  189. $application->add($foo = new \FooCommand());
  190. $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered');
  191. $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name');
  192. $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias');
  193. $application = new Application();
  194. $application->add($foo = new \FooCommand());
  195. // simulate --help
  196. $r = new \ReflectionObject($application);
  197. $p = $r->getProperty('wantHelps');
  198. $p->setAccessible(true);
  199. $p->setValue($application, true);
  200. $command = $application->get('foo:bar');
  201. $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $command, '->get() returns the help command if --help is provided as the input');
  202. }
  203. public function testHasGetWithCommandLoader()
  204. {
  205. $application = new Application();
  206. $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered');
  207. $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered');
  208. $application->add($foo = new \FooCommand());
  209. $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered');
  210. $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name');
  211. $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias');
  212. $application->setCommandLoader(new FactoryCommandLoader([
  213. 'foo:bar1' => function () { return new \Foo1Command(); },
  214. ]));
  215. $this->assertTrue($application->has('afoobar'), '->has() returns true if an instance is registered for an alias even with command loader');
  216. $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns an instance by name even with command loader');
  217. $this->assertEquals($foo, $application->get('afoobar'), '->get() returns an instance by alias even with command loader');
  218. $this->assertTrue($application->has('foo:bar1'), '->has() returns true for commands registered in the loader');
  219. $this->assertInstanceOf(\Foo1Command::class, $foo1 = $application->get('foo:bar1'), '->get() returns a command by name from the command loader');
  220. $this->assertTrue($application->has('afoobar1'), '->has() returns true for commands registered in the loader');
  221. $this->assertEquals($foo1, $application->get('afoobar1'), '->get() returns a command by name from the command loader');
  222. }
  223. public function testSilentHelp()
  224. {
  225. $application = new Application();
  226. $application->setAutoExit(false);
  227. $application->setCatchExceptions(false);
  228. $tester = new ApplicationTester($application);
  229. $tester->run(['-h' => true, '-q' => true], ['decorated' => false]);
  230. $this->assertEmpty($tester->getDisplay(true));
  231. }
  232. /**
  233. * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
  234. * @expectedExceptionMessage The command "foofoo" does not exist.
  235. */
  236. public function testGetInvalidCommand()
  237. {
  238. $application = new Application();
  239. $application->get('foofoo');
  240. }
  241. public function testGetNamespaces()
  242. {
  243. $application = new Application();
  244. $application->add(new \FooCommand());
  245. $application->add(new \Foo1Command());
  246. $this->assertEquals(['foo'], $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces');
  247. }
  248. public function testFindNamespace()
  249. {
  250. $application = new Application();
  251. $application->add(new \FooCommand());
  252. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
  253. $this->assertEquals('foo', $application->findNamespace('f'), '->findNamespace() finds a namespace given an abbreviation');
  254. $application->add(new \Foo2Command());
  255. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
  256. }
  257. public function testFindNamespaceWithSubnamespaces()
  258. {
  259. $application = new Application();
  260. $application->add(new \FooSubnamespaced1Command());
  261. $application->add(new \FooSubnamespaced2Command());
  262. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns commands even if the commands are only contained in subnamespaces');
  263. }
  264. public function testFindAmbiguousNamespace()
  265. {
  266. $application = new Application();
  267. $application->add(new \BarBucCommand());
  268. $application->add(new \FooCommand());
  269. $application->add(new \Foo2Command());
  270. $expectedMsg = "The namespace \"f\" is ambiguous.\nDid you mean one of these?\n foo\n foo1";
  271. if (method_exists($this, 'expectException')) {
  272. $this->expectException(NamespaceNotFoundException::class);
  273. $this->expectExceptionMessage($expectedMsg);
  274. } else {
  275. $this->setExpectedException(NamespaceNotFoundException::class, $expectedMsg);
  276. }
  277. $application->findNamespace('f');
  278. }
  279. public function testFindNonAmbiguous()
  280. {
  281. $application = new Application();
  282. $application->add(new \TestAmbiguousCommandRegistering());
  283. $application->add(new \TestAmbiguousCommandRegistering2());
  284. $this->assertEquals('test-ambiguous', $application->find('test')->getName());
  285. }
  286. /**
  287. * @expectedException \Symfony\Component\Console\Exception\NamespaceNotFoundException
  288. * @expectedExceptionMessage There are no commands defined in the "bar" namespace.
  289. */
  290. public function testFindInvalidNamespace()
  291. {
  292. $application = new Application();
  293. $application->findNamespace('bar');
  294. }
  295. /**
  296. * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
  297. * @expectedExceptionMessage Command "foo1" is not defined
  298. */
  299. public function testFindUniqueNameButNamespaceName()
  300. {
  301. $application = new Application();
  302. $application->add(new \FooCommand());
  303. $application->add(new \Foo1Command());
  304. $application->add(new \Foo2Command());
  305. $application->find($commandName = 'foo1');
  306. }
  307. public function testFind()
  308. {
  309. $application = new Application();
  310. $application->add(new \FooCommand());
  311. $this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists');
  312. $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists');
  313. $this->assertInstanceOf('FooCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists');
  314. $this->assertInstanceOf('FooCommand', $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist');
  315. $this->assertInstanceOf('FooCommand', $application->find('a'), '->find() returns a command if the abbreviation exists for an alias');
  316. }
  317. public function testFindCaseSensitiveFirst()
  318. {
  319. $application = new Application();
  320. $application->add(new \FooSameCaseUppercaseCommand());
  321. $application->add(new \FooSameCaseLowercaseCommand());
  322. $this->assertInstanceOf('FooSameCaseUppercaseCommand', $application->find('f:B'), '->find() returns a command if the abbreviation is the correct case');
  323. $this->assertInstanceOf('FooSameCaseUppercaseCommand', $application->find('f:BAR'), '->find() returns a command if the abbreviation is the correct case');
  324. $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:b'), '->find() returns a command if the abbreviation is the correct case');
  325. $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation is the correct case');
  326. }
  327. public function testFindCaseInsensitiveAsFallback()
  328. {
  329. $application = new Application();
  330. $application->add(new \FooSameCaseLowercaseCommand());
  331. $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:b'), '->find() returns a command if the abbreviation is the correct case');
  332. $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:B'), '->find() will fallback to case insensitivity');
  333. $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('FoO:BaR'), '->find() will fallback to case insensitivity');
  334. }
  335. /**
  336. * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
  337. * @expectedExceptionMessage Command "FoO:BaR" is ambiguous
  338. */
  339. public function testFindCaseInsensitiveSuggestions()
  340. {
  341. $application = new Application();
  342. $application->add(new \FooSameCaseLowercaseCommand());
  343. $application->add(new \FooSameCaseUppercaseCommand());
  344. $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('FoO:BaR'), '->find() will find two suggestions with case insensitivity');
  345. }
  346. public function testFindWithCommandLoader()
  347. {
  348. $application = new Application();
  349. $application->setCommandLoader(new FactoryCommandLoader([
  350. 'foo:bar' => $f = function () { return new \FooCommand(); },
  351. ]));
  352. $this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists');
  353. $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists');
  354. $this->assertInstanceOf('FooCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists');
  355. $this->assertInstanceOf('FooCommand', $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist');
  356. $this->assertInstanceOf('FooCommand', $application->find('a'), '->find() returns a command if the abbreviation exists for an alias');
  357. }
  358. /**
  359. * @dataProvider provideAmbiguousAbbreviations
  360. */
  361. public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage)
  362. {
  363. putenv('COLUMNS=120');
  364. if (method_exists($this, 'expectException')) {
  365. $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException');
  366. $this->expectExceptionMessage($expectedExceptionMessage);
  367. } else {
  368. $this->setExpectedException('Symfony\Component\Console\Exception\CommandNotFoundException', $expectedExceptionMessage);
  369. }
  370. $application = new Application();
  371. $application->add(new \FooCommand());
  372. $application->add(new \Foo1Command());
  373. $application->add(new \Foo2Command());
  374. $application->find($abbreviation);
  375. }
  376. public function provideAmbiguousAbbreviations()
  377. {
  378. return [
  379. ['f', 'Command "f" is not defined.'],
  380. [
  381. 'a',
  382. "Command \"a\" is ambiguous.\nDid you mean one of these?\n".
  383. " afoobar The foo:bar command\n".
  384. " afoobar1 The foo:bar1 command\n".
  385. ' afoobar2 The foo1:bar command',
  386. ],
  387. [
  388. 'foo:b',
  389. "Command \"foo:b\" is ambiguous.\nDid you mean one of these?\n".
  390. " foo:bar The foo:bar command\n".
  391. " foo:bar1 The foo:bar1 command\n".
  392. ' foo1:bar The foo1:bar command',
  393. ],
  394. ];
  395. }
  396. public function testFindCommandEqualNamespace()
  397. {
  398. $application = new Application();
  399. $application->add(new \Foo3Command());
  400. $application->add(new \Foo4Command());
  401. $this->assertInstanceOf('Foo3Command', $application->find('foo3:bar'), '->find() returns the good command even if a namespace has same name');
  402. $this->assertInstanceOf('Foo4Command', $application->find('foo3:bar:toh'), '->find() returns a command even if its namespace equals another command name');
  403. }
  404. public function testFindCommandWithAmbiguousNamespacesButUniqueName()
  405. {
  406. $application = new Application();
  407. $application->add(new \FooCommand());
  408. $application->add(new \FoobarCommand());
  409. $this->assertInstanceOf('FoobarCommand', $application->find('f:f'));
  410. }
  411. public function testFindCommandWithMissingNamespace()
  412. {
  413. $application = new Application();
  414. $application->add(new \Foo4Command());
  415. $this->assertInstanceOf('Foo4Command', $application->find('f::t'));
  416. }
  417. /**
  418. * @dataProvider provideInvalidCommandNamesSingle
  419. * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
  420. * @expectedExceptionMessage Did you mean this
  421. */
  422. public function testFindAlternativeExceptionMessageSingle($name)
  423. {
  424. $application = new Application();
  425. $application->add(new \Foo3Command());
  426. $application->find($name);
  427. }
  428. public function testDontRunAlternativeNamespaceName()
  429. {
  430. $application = new Application();
  431. $application->add(new \Foo1Command());
  432. $application->setAutoExit(false);
  433. $tester = new ApplicationTester($application);
  434. $tester->run(['command' => 'foos:bar1'], ['decorated' => false]);
  435. $this->assertSame('
  436. There are no commands defined in the "foos" namespace.
  437. Did you mean this?
  438. foo
  439. ', $tester->getDisplay(true));
  440. }
  441. public function testCanRunAlternativeCommandName()
  442. {
  443. $application = new Application();
  444. $application->add(new \FooWithoutAliasCommand());
  445. $application->setAutoExit(false);
  446. $tester = new ApplicationTester($application);
  447. $tester->setInputs(['y']);
  448. $tester->run(['command' => 'foos'], ['decorated' => false]);
  449. $display = trim($tester->getDisplay(true));
  450. $this->assertContains('Command "foos" is not defined', $display);
  451. $this->assertContains('Do you want to run "foo" instead? (yes/no) [no]:', $display);
  452. $this->assertContains('called', $display);
  453. }
  454. public function testDontRunAlternativeCommandName()
  455. {
  456. $application = new Application();
  457. $application->add(new \FooWithoutAliasCommand());
  458. $application->setAutoExit(false);
  459. $tester = new ApplicationTester($application);
  460. $tester->setInputs(['n']);
  461. $exitCode = $tester->run(['command' => 'foos'], ['decorated' => false]);
  462. $this->assertSame(1, $exitCode);
  463. $display = trim($tester->getDisplay(true));
  464. $this->assertContains('Command "foos" is not defined', $display);
  465. $this->assertContains('Do you want to run "foo" instead? (yes/no) [no]:', $display);
  466. }
  467. public function provideInvalidCommandNamesSingle()
  468. {
  469. return [
  470. ['foo3:barr'],
  471. ['fooo3:bar'],
  472. ];
  473. }
  474. public function testFindAlternativeExceptionMessageMultiple()
  475. {
  476. putenv('COLUMNS=120');
  477. $application = new Application();
  478. $application->add(new \FooCommand());
  479. $application->add(new \Foo1Command());
  480. $application->add(new \Foo2Command());
  481. // Command + plural
  482. try {
  483. $application->find('foo:baR');
  484. $this->fail('->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  485. } catch (\Exception $e) {
  486. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  487. $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  488. $this->assertRegExp('/foo1:bar/', $e->getMessage());
  489. $this->assertRegExp('/foo:bar/', $e->getMessage());
  490. }
  491. // Namespace + plural
  492. try {
  493. $application->find('foo2:bar');
  494. $this->fail('->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  495. } catch (\Exception $e) {
  496. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  497. $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  498. $this->assertRegExp('/foo1/', $e->getMessage());
  499. }
  500. $application->add(new \Foo3Command());
  501. $application->add(new \Foo4Command());
  502. // Subnamespace + plural
  503. try {
  504. $a = $application->find('foo3:');
  505. $this->fail('->find() should throw an Symfony\Component\Console\Exception\CommandNotFoundException if a command is ambiguous because of a subnamespace, with alternatives');
  506. } catch (\Exception $e) {
  507. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e);
  508. $this->assertRegExp('/foo3:bar/', $e->getMessage());
  509. $this->assertRegExp('/foo3:bar:toh/', $e->getMessage());
  510. }
  511. }
  512. public function testFindAlternativeCommands()
  513. {
  514. $application = new Application();
  515. $application->add(new \FooCommand());
  516. $application->add(new \Foo1Command());
  517. $application->add(new \Foo2Command());
  518. try {
  519. $application->find($commandName = 'Unknown command');
  520. $this->fail('->find() throws a CommandNotFoundException if command does not exist');
  521. } catch (\Exception $e) {
  522. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist');
  523. $this->assertSame([], $e->getAlternatives());
  524. $this->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without alternatives');
  525. }
  526. // Test if "bar1" command throw a "CommandNotFoundException" and does not contain
  527. // "foo:bar" as alternative because "bar1" is too far from "foo:bar"
  528. try {
  529. $application->find($commandName = 'bar1');
  530. $this->fail('->find() throws a CommandNotFoundException if command does not exist');
  531. } catch (\Exception $e) {
  532. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist');
  533. $this->assertSame(['afoobar1', 'foo:bar1'], $e->getAlternatives());
  534. $this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  535. $this->assertRegExp('/afoobar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "afoobar1"');
  536. $this->assertRegExp('/foo:bar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "foo:bar1"');
  537. $this->assertNotRegExp('/foo:bar(?>!1)/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without "foo:bar" alternative');
  538. }
  539. }
  540. public function testFindAlternativeCommandsWithAnAlias()
  541. {
  542. $fooCommand = new \FooCommand();
  543. $fooCommand->setAliases(['foo2']);
  544. $application = new Application();
  545. $application->add($fooCommand);
  546. $result = $application->find('foo');
  547. $this->assertSame($fooCommand, $result);
  548. }
  549. public function testFindAlternativeNamespace()
  550. {
  551. $application = new Application();
  552. $application->add(new \FooCommand());
  553. $application->add(new \Foo1Command());
  554. $application->add(new \Foo2Command());
  555. $application->add(new \Foo3Command());
  556. try {
  557. $application->find('Unknown-namespace:Unknown-command');
  558. $this->fail('->find() throws a CommandNotFoundException if namespace does not exist');
  559. } catch (\Exception $e) {
  560. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if namespace does not exist');
  561. $this->assertSame([], $e->getAlternatives());
  562. $this->assertEquals('There are no commands defined in the "Unknown-namespace" namespace.', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, without alternatives');
  563. }
  564. try {
  565. $application->find('foo2:command');
  566. $this->fail('->find() throws a CommandNotFoundException if namespace does not exist');
  567. } catch (\Exception $e) {
  568. $this->assertInstanceOf('Symfony\Component\Console\Exception\NamespaceNotFoundException', $e, '->find() throws a NamespaceNotFoundException if namespace does not exist');
  569. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, 'NamespaceNotFoundException extends from CommandNotFoundException');
  570. $this->assertCount(3, $e->getAlternatives());
  571. $this->assertContains('foo', $e->getAlternatives());
  572. $this->assertContains('foo1', $e->getAlternatives());
  573. $this->assertContains('foo3', $e->getAlternatives());
  574. $this->assertRegExp('/There are no commands defined in the "foo2" namespace./', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative');
  575. $this->assertRegExp('/foo/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo"');
  576. $this->assertRegExp('/foo1/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo1"');
  577. $this->assertRegExp('/foo3/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo3"');
  578. }
  579. }
  580. public function testFindAlternativesOutput()
  581. {
  582. $application = new Application();
  583. $application->add(new \FooCommand());
  584. $application->add(new \Foo1Command());
  585. $application->add(new \Foo2Command());
  586. $application->add(new \Foo3Command());
  587. $expectedAlternatives = [
  588. 'afoobar',
  589. 'afoobar1',
  590. 'afoobar2',
  591. 'foo1:bar',
  592. 'foo3:bar',
  593. 'foo:bar',
  594. 'foo:bar1',
  595. ];
  596. try {
  597. $application->find('foo');
  598. $this->fail('->find() throws a CommandNotFoundException if command is not defined');
  599. } catch (\Exception $e) {
  600. $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command is not defined');
  601. $this->assertSame($expectedAlternatives, $e->getAlternatives());
  602. $this->assertRegExp('/Command "foo" is not defined\..*Did you mean one of these\?.*/Ums', $e->getMessage());
  603. }
  604. }
  605. public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces()
  606. {
  607. $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getNamespaces'])->getMock();
  608. $application->expects($this->once())
  609. ->method('getNamespaces')
  610. ->willReturn(['foo:sublong', 'bar:sub']);
  611. $this->assertEquals('foo:sublong', $application->findNamespace('f:sub'));
  612. }
  613. /**
  614. * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
  615. * @expectedExceptionMessage Command "foo::bar" is not defined.
  616. */
  617. public function testFindWithDoubleColonInNameThrowsException()
  618. {
  619. $application = new Application();
  620. $application->add(new \FooCommand());
  621. $application->add(new \Foo4Command());
  622. $application->find('foo::bar');
  623. }
  624. public function testSetCatchExceptions()
  625. {
  626. $application = new Application();
  627. $application->setAutoExit(false);
  628. putenv('COLUMNS=120');
  629. $tester = new ApplicationTester($application);
  630. $application->setCatchExceptions(true);
  631. $this->assertTrue($application->areExceptionsCaught());
  632. $tester->run(['command' => 'foo'], ['decorated' => false]);
  633. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag');
  634. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  635. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->setCatchExceptions() sets the catch exception flag');
  636. $this->assertSame('', $tester->getDisplay(true));
  637. $application->setCatchExceptions(false);
  638. try {
  639. $tester->run(['command' => 'foo'], ['decorated' => false]);
  640. $this->fail('->setCatchExceptions() sets the catch exception flag');
  641. } catch (\Exception $e) {
  642. $this->assertInstanceOf('\Exception', $e, '->setCatchExceptions() sets the catch exception flag');
  643. $this->assertEquals('Command "foo" is not defined.', $e->getMessage(), '->setCatchExceptions() sets the catch exception flag');
  644. }
  645. }
  646. public function testAutoExitSetting()
  647. {
  648. $application = new Application();
  649. $this->assertTrue($application->isAutoExitEnabled());
  650. $application->setAutoExit(false);
  651. $this->assertFalse($application->isAutoExitEnabled());
  652. }
  653. public function testRenderException()
  654. {
  655. $application = new Application();
  656. $application->setAutoExit(false);
  657. putenv('COLUMNS=120');
  658. $tester = new ApplicationTester($application);
  659. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  660. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exception');
  661. $tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true]);
  662. $this->assertContains('Exception trace', $tester->getErrorOutput(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose');
  663. $tester->run(['command' => 'list', '--foo' => true], ['decorated' => false, 'capture_stderr_separately' => true]);
  664. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception2.txt', $tester->getErrorOutput(true), '->renderException() renders the command synopsis when an exception occurs in the context of a command');
  665. $application->add(new \Foo3Command());
  666. $tester = new ApplicationTester($application);
  667. $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'capture_stderr_separately' => true]);
  668. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  669. $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]);
  670. $this->assertRegExp('/\[Exception\]\s*First exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is default and verbosity is verbose');
  671. $this->assertRegExp('/\[Exception\]\s*Second exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is 0 and verbosity is verbose');
  672. $this->assertRegExp('/\[Exception \(404\)\]\s*Third exception/', $tester->getDisplay(), '->renderException() renders a pretty exception with code exception when code exception is 404 and verbosity is verbose');
  673. $tester->run(['command' => 'foo3:bar'], ['decorated' => true]);
  674. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  675. $tester->run(['command' => 'foo3:bar'], ['decorated' => true, 'capture_stderr_separately' => true]);
  676. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  677. $application = new Application();
  678. $application->setAutoExit(false);
  679. putenv('COLUMNS=32');
  680. $tester = new ApplicationTester($application);
  681. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  682. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal');
  683. putenv('COLUMNS=120');
  684. }
  685. public function testRenderExceptionWithDoubleWidthCharacters()
  686. {
  687. $application = new Application();
  688. $application->setAutoExit(false);
  689. putenv('COLUMNS=120');
  690. $application->register('foo')->setCode(function () {
  691. throw new \Exception('エラーメッセージ');
  692. });
  693. $tester = new ApplicationTester($application);
  694. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  695. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  696. $tester->run(['command' => 'foo'], ['decorated' => true, 'capture_stderr_separately' => true]);
  697. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  698. $application = new Application();
  699. $application->setAutoExit(false);
  700. putenv('COLUMNS=32');
  701. $application->register('foo')->setCode(function () {
  702. throw new \Exception('コマンドの実行中にエラーが発生しました。');
  703. });
  704. $tester = new ApplicationTester($application);
  705. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  706. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth2.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal');
  707. putenv('COLUMNS=120');
  708. }
  709. public function testRenderExceptionEscapesLines()
  710. {
  711. $application = new Application();
  712. $application->setAutoExit(false);
  713. putenv('COLUMNS=22');
  714. $application->register('foo')->setCode(function () {
  715. throw new \Exception('dont break here <info>!</info>');
  716. });
  717. $tester = new ApplicationTester($application);
  718. $tester->run(['command' => 'foo'], ['decorated' => false]);
  719. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_escapeslines.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting');
  720. putenv('COLUMNS=120');
  721. }
  722. public function testRenderExceptionLineBreaks()
  723. {
  724. $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getTerminalWidth'])->getMock();
  725. $application->setAutoExit(false);
  726. $application->expects($this->any())
  727. ->method('getTerminalWidth')
  728. ->willReturn(120);
  729. $application->register('foo')->setCode(function () {
  730. throw new \InvalidArgumentException("\n\nline 1 with extra spaces \nline 2\n\nline 4\n");
  731. });
  732. $tester = new ApplicationTester($application);
  733. $tester->run(['command' => 'foo'], ['decorated' => false]);
  734. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks');
  735. }
  736. public function testRenderAnonymousException()
  737. {
  738. $application = new Application();
  739. $application->setAutoExit(false);
  740. $application->register('foo')->setCode(function () {
  741. throw new class('') extends \InvalidArgumentException {
  742. };
  743. });
  744. $tester = new ApplicationTester($application);
  745. $tester->run(['command' => 'foo'], ['decorated' => false]);
  746. $this->assertContains('[InvalidArgumentException@anonymous]', $tester->getDisplay(true));
  747. $application = new Application();
  748. $application->setAutoExit(false);
  749. $application->register('foo')->setCode(function () {
  750. throw new \InvalidArgumentException(sprintf('Dummy type "%s" is invalid.', \get_class(new class() {
  751. })));
  752. });
  753. $tester = new ApplicationTester($application);
  754. $tester->run(['command' => 'foo'], ['decorated' => false]);
  755. $this->assertContains('Dummy type "@anonymous" is invalid.', $tester->getDisplay(true));
  756. }
  757. public function testRenderExceptionStackTraceContainsRootException()
  758. {
  759. $application = new Application();
  760. $application->setAutoExit(false);
  761. $application->register('foo')->setCode(function () {
  762. throw new class('') extends \InvalidArgumentException {
  763. };
  764. });
  765. $tester = new ApplicationTester($application);
  766. $tester->run(['command' => 'foo'], ['decorated' => false]);
  767. $this->assertContains('[InvalidArgumentException@anonymous]', $tester->getDisplay(true));
  768. $application = new Application();
  769. $application->setAutoExit(false);
  770. $application->register('foo')->setCode(function () {
  771. throw new \InvalidArgumentException(sprintf('Dummy type "%s" is invalid.', \get_class(new class() {
  772. })));
  773. });
  774. $tester = new ApplicationTester($application);
  775. $tester->run(['command' => 'foo'], ['decorated' => false]);
  776. $this->assertContains('Dummy type "@anonymous" is invalid.', $tester->getDisplay(true));
  777. }
  778. public function testRun()
  779. {
  780. $application = new Application();
  781. $application->setAutoExit(false);
  782. $application->setCatchExceptions(false);
  783. $application->add($command = new \Foo1Command());
  784. $_SERVER['argv'] = ['cli.php', 'foo:bar1'];
  785. ob_start();
  786. $application->run();
  787. ob_end_clean();
  788. $this->assertInstanceOf('Symfony\Component\Console\Input\ArgvInput', $command->input, '->run() creates an ArgvInput by default if none is given');
  789. $this->assertInstanceOf('Symfony\Component\Console\Output\ConsoleOutput', $command->output, '->run() creates a ConsoleOutput by default if none is given');
  790. $application = new Application();
  791. $application->setAutoExit(false);
  792. $application->setCatchExceptions(false);
  793. $this->ensureStaticCommandHelp($application);
  794. $tester = new ApplicationTester($application);
  795. $tester->run([], ['decorated' => false]);
  796. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed');
  797. $tester->run(['--help' => true], ['decorated' => false]);
  798. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed');
  799. $tester->run(['-h' => true], ['decorated' => false]);
  800. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed');
  801. $tester->run(['command' => 'list', '--help' => true], ['decorated' => false]);
  802. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');
  803. $tester->run(['command' => 'list', '-h' => true], ['decorated' => false]);
  804. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');
  805. $tester->run(['--ansi' => true]);
  806. $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed');
  807. $tester->run(['--no-ansi' => true]);
  808. $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed');
  809. $tester->run(['--version' => true], ['decorated' => false]);
  810. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed');
  811. $tester->run(['-V' => true], ['decorated' => false]);
  812. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed');
  813. $tester->run(['command' => 'list', '--quiet' => true]);
  814. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed');
  815. $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if --quiet is passed');
  816. $tester->run(['command' => 'list', '-q' => true]);
  817. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed');
  818. $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if -q is passed');
  819. $tester->run(['command' => 'list', '--verbose' => true]);
  820. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed');
  821. $tester->run(['command' => 'list', '--verbose' => 1]);
  822. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed');
  823. $tester->run(['command' => 'list', '--verbose' => 2]);
  824. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed');
  825. $tester->run(['command' => 'list', '--verbose' => 3]);
  826. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed');
  827. $tester->run(['command' => 'list', '--verbose' => 4]);
  828. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed');
  829. $tester->run(['command' => 'list', '-v' => true]);
  830. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  831. $tester->run(['command' => 'list', '-vv' => true]);
  832. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  833. $tester->run(['command' => 'list', '-vvv' => true]);
  834. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  835. $application = new Application();
  836. $application->setAutoExit(false);
  837. $application->setCatchExceptions(false);
  838. $application->add(new \FooCommand());
  839. $tester = new ApplicationTester($application);
  840. $tester->run(['command' => 'foo:bar', '--no-interaction' => true], ['decorated' => false]);
  841. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed');
  842. $tester->run(['command' => 'foo:bar', '-n' => true], ['decorated' => false]);
  843. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed');
  844. }
  845. public function testRunWithGlobalOptionAndNoCommand()
  846. {
  847. $application = new Application();
  848. $application->setAutoExit(false);
  849. $application->setCatchExceptions(false);
  850. $application->getDefinition()->addOption(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL));
  851. $output = new StreamOutput(fopen('php://memory', 'w', false));
  852. $input = new ArgvInput(['cli.php', '--foo', 'bar']);
  853. $this->assertSame(0, $application->run($input, $output));
  854. }
  855. /**
  856. * Issue #9285.
  857. *
  858. * If the "verbose" option is just before an argument in ArgvInput,
  859. * an argument value should not be treated as verbosity value.
  860. * This test will fail with "Not enough arguments." if broken
  861. */
  862. public function testVerboseValueNotBreakArguments()
  863. {
  864. $application = new Application();
  865. $application->setAutoExit(false);
  866. $application->setCatchExceptions(false);
  867. $application->add(new \FooCommand());
  868. $output = new StreamOutput(fopen('php://memory', 'w', false));
  869. $input = new ArgvInput(['cli.php', '-v', 'foo:bar']);
  870. $application->run($input, $output);
  871. $this->addToAssertionCount(1);
  872. $input = new ArgvInput(['cli.php', '--verbose', 'foo:bar']);
  873. $application->run($input, $output);
  874. $this->addToAssertionCount(1);
  875. }
  876. public function testRunReturnsIntegerExitCode()
  877. {
  878. $exception = new \Exception('', 4);
  879. $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock();
  880. $application->setAutoExit(false);
  881. $application->expects($this->once())
  882. ->method('doRun')
  883. ->willThrowException($exception);
  884. $exitCode = $application->run(new ArrayInput([]), new NullOutput());
  885. $this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception');
  886. }
  887. public function testRunDispatchesIntegerExitCode()
  888. {
  889. $passedRightValue = false;
  890. // We can assume here that some other test asserts that the event is dispatched at all
  891. $dispatcher = new EventDispatcher();
  892. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) {
  893. $passedRightValue = (4 === $event->getExitCode());
  894. });
  895. $application = new Application();
  896. $application->setDispatcher($dispatcher);
  897. $application->setAutoExit(false);
  898. $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) {
  899. throw new \Exception('', 4);
  900. });
  901. $tester = new ApplicationTester($application);
  902. $tester->run(['command' => 'test']);
  903. $this->assertTrue($passedRightValue, '-> exit code 4 was passed in the console.terminate event');
  904. }
  905. public function testRunReturnsExitCodeOneForExceptionCodeZero()
  906. {
  907. $exception = new \Exception('', 0);
  908. $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock();
  909. $application->setAutoExit(false);
  910. $application->expects($this->once())
  911. ->method('doRun')
  912. ->willThrowException($exception);
  913. $exitCode = $application->run(new ArrayInput([]), new NullOutput());
  914. $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0');
  915. }
  916. public function testRunDispatchesExitCodeOneForExceptionCodeZero()
  917. {
  918. $passedRightValue = false;
  919. // We can assume here that some other test asserts that the event is dispatched at all
  920. $dispatcher = new EventDispatcher();
  921. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) {
  922. $passedRightValue = (1 === $event->getExitCode());
  923. });
  924. $application = new Application();
  925. $application->setDispatcher($dispatcher);
  926. $application->setAutoExit(false);
  927. $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) {
  928. throw new \Exception();
  929. });
  930. $tester = new ApplicationTester($application);
  931. $tester->run(['command' => 'test']);
  932. $this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event');
  933. }
  934. /**
  935. * @expectedException \LogicException
  936. * @expectedExceptionMessage An option with shortcut "e" already exists.
  937. */
  938. public function testAddingOptionWithDuplicateShortcut()
  939. {
  940. $dispatcher = new EventDispatcher();
  941. $application = new Application();
  942. $application->setAutoExit(false);
  943. $application->setCatchExceptions(false);
  944. $application->setDispatcher($dispatcher);
  945. $application->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'Environment'));
  946. $application
  947. ->register('foo')
  948. ->setAliases(['f'])
  949. ->setDefinition([new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.')])
  950. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  951. ;
  952. $input = new ArrayInput(['command' => 'foo']);
  953. $output = new NullOutput();
  954. $application->run($input, $output);
  955. }
  956. /**
  957. * @expectedException \LogicException
  958. * @dataProvider getAddingAlreadySetDefinitionElementData
  959. */
  960. public function testAddingAlreadySetDefinitionElementData($def)
  961. {
  962. $application = new Application();
  963. $application->setAutoExit(false);
  964. $application->setCatchExceptions(false);
  965. $application
  966. ->register('foo')
  967. ->setDefinition([$def])
  968. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  969. ;
  970. $input = new ArrayInput(['command' => 'foo']);
  971. $output = new NullOutput();
  972. $application->run($input, $output);
  973. }
  974. public function getAddingAlreadySetDefinitionElementData()
  975. {
  976. return [
  977. [new InputArgument('command', InputArgument::REQUIRED)],
  978. [new InputOption('quiet', '', InputOption::VALUE_NONE)],
  979. [new InputOption('query', 'q', InputOption::VALUE_NONE)],
  980. ];
  981. }
  982. public function testGetDefaultHelperSetReturnsDefaultValues()
  983. {
  984. $application = new Application();
  985. $application->setAutoExit(false);
  986. $application->setCatchExceptions(false);
  987. $helperSet = $application->getHelperSet();
  988. $this->assertTrue($helperSet->has('formatter'));
  989. }
  990. public function testAddingSingleHelperSetOverwritesDefaultValues()
  991. {
  992. $application = new Application();
  993. $application->setAutoExit(false);
  994. $application->setCatchExceptions(false);
  995. $application->setHelperSet(new HelperSet([new FormatterHelper()]));
  996. $helperSet = $application->getHelperSet();
  997. $this->assertTrue($helperSet->has('formatter'));
  998. // no other default helper set should be returned
  999. $this->assertFalse($helperSet->has('dialog'));
  1000. $this->assertFalse($helperSet->has('progress'));
  1001. }
  1002. public function testOverwritingDefaultHelperSetOverwritesDefaultValues()
  1003. {
  1004. $application = new CustomApplication();
  1005. $application->setAutoExit(false);
  1006. $application->setCatchExceptions(false);
  1007. $application->setHelperSet(new HelperSet([new FormatterHelper()]));
  1008. $helperSet = $application->getHelperSet();
  1009. $this->assertTrue($helperSet->has('formatter'));
  1010. // no other default helper set should be returned
  1011. $this->assertFalse($helperSet->has('dialog'));
  1012. $this->assertFalse($helperSet->has('progress'));
  1013. }
  1014. public function testGetDefaultInputDefinitionReturnsDefaultValues()
  1015. {
  1016. $application = new Application();
  1017. $application->setAutoExit(false);
  1018. $application->setCatchExceptions(false);
  1019. $inputDefinition = $application->getDefinition();
  1020. $this->assertTrue($inputDefinition->hasArgument('command'));
  1021. $this->assertTrue($inputDefinition->hasOption('help'));
  1022. $this->assertTrue($inputDefinition->hasOption('quiet'));
  1023. $this->assertTrue($inputDefinition->hasOption('verbose'));
  1024. $this->assertTrue($inputDefinition->hasOption('version'));
  1025. $this->assertTrue($inputDefinition->hasOption('ansi'));
  1026. $this->assertTrue($inputDefinition->hasOption('no-ansi'));
  1027. $this->assertTrue($inputDefinition->hasOption('no-interaction'));
  1028. }
  1029. public function testOverwritingDefaultInputDefinitionOverwritesDefaultValues()
  1030. {
  1031. $application = new CustomApplication();
  1032. $application->setAutoExit(false);
  1033. $application->setCatchExceptions(false);
  1034. $inputDefinition = $application->getDefinition();
  1035. // check whether the default arguments and options are not returned any more
  1036. $this->assertFalse($inputDefinition->hasArgument('command'));
  1037. $this->assertFalse($inputDefinition->hasOption('help'));
  1038. $this->assertFalse($inputDefinition->hasOption('quiet'));
  1039. $this->assertFalse($inputDefinition->hasOption('verbose'));
  1040. $this->assertFalse($inputDefinition->hasOption('version'));
  1041. $this->assertFalse($inputDefinition->hasOption('ansi'));
  1042. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  1043. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  1044. $this->assertTrue($inputDefinition->hasOption('custom'));
  1045. }
  1046. public function testSettingCustomInputDefinitionOverwritesDefaultValues()
  1047. {
  1048. $application = new Application();
  1049. $application->setAutoExit(false);
  1050. $application->setCatchExceptions(false);
  1051. $application->setDefinition(new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]));
  1052. $inputDefinition = $application->getDefinition();
  1053. // check whether the default arguments and options are not returned any more
  1054. $this->assertFalse($inputDefinition->hasArgument('command'));
  1055. $this->assertFalse($inputDefinition->hasOption('help'));
  1056. $this->assertFalse($inputDefinition->hasOption('quiet'));
  1057. $this->assertFalse($inputDefinition->hasOption('verbose'));
  1058. $this->assertFalse($inputDefinition->hasOption('version'));
  1059. $this->assertFalse($inputDefinition->hasOption('ansi'));
  1060. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  1061. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  1062. $this->assertTrue($inputDefinition->hasOption('custom'));
  1063. }
  1064. public function testRunWithDispatcher()
  1065. {
  1066. $application = new Application();
  1067. $application->setAutoExit(false);
  1068. $application->setDispatcher($this->getDispatcher());
  1069. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1070. $output->write('foo.');
  1071. });
  1072. $tester = new ApplicationTester($application);
  1073. $tester->run(['command' => 'foo']);
  1074. $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay());
  1075. }
  1076. /**
  1077. * @expectedException \LogicException
  1078. * @expectedExceptionMessage error
  1079. */
  1080. public function testRunWithExceptionAndDispatcher()
  1081. {
  1082. $application = new Application();
  1083. $application->setDispatcher($this->getDispatcher());
  1084. $application->setAutoExit(false);
  1085. $application->setCatchExceptions(false);
  1086. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1087. throw new \RuntimeException('foo');
  1088. });
  1089. $tester = new ApplicationTester($application);
  1090. $tester->run(['command' => 'foo']);
  1091. }
  1092. public function testRunDispatchesAllEventsWithException()
  1093. {
  1094. $application = new Application();
  1095. $application->setDispatcher($this->getDispatcher());
  1096. $application->setAutoExit(false);
  1097. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1098. $output->write('foo.');
  1099. throw new \RuntimeException('foo');
  1100. });
  1101. $tester = new ApplicationTester($application);
  1102. $tester->run(['command' => 'foo']);
  1103. $this->assertContains('before.foo.error.after.', $tester->getDisplay());
  1104. }
  1105. public function testRunDispatchesAllEventsWithExceptionInListener()
  1106. {
  1107. $dispatcher = $this->getDispatcher();
  1108. $dispatcher->addListener('console.command', function () {
  1109. throw new \RuntimeException('foo');
  1110. });
  1111. $application = new Application();
  1112. $application->setDispatcher($dispatcher);
  1113. $application->setAutoExit(false);
  1114. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1115. $output->write('foo.');
  1116. });
  1117. $tester = new ApplicationTester($application);
  1118. $tester->run(['command' => 'foo']);
  1119. $this->assertContains('before.error.after.', $tester->getDisplay());
  1120. }
  1121. public function testRunWithError()
  1122. {
  1123. $application = new Application();
  1124. $application->setAutoExit(false);
  1125. $application->setCatchExceptions(false);
  1126. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1127. $output->write('dym.');
  1128. throw new \Error('dymerr');
  1129. });
  1130. $tester = new ApplicationTester($application);
  1131. try {
  1132. $tester->run(['command' => 'dym']);
  1133. $this->fail('Error expected.');
  1134. } catch (\Error $e) {
  1135. $this->assertSame('dymerr', $e->getMessage());
  1136. }
  1137. }
  1138. public function testRunAllowsErrorListenersToSilenceTheException()
  1139. {
  1140. $dispatcher = $this->getDispatcher();
  1141. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1142. $event->getOutput()->write('silenced.');
  1143. $event->setExitCode(0);
  1144. });
  1145. $dispatcher->addListener('console.command', function () {
  1146. throw new \RuntimeException('foo');
  1147. });
  1148. $application = new Application();
  1149. $application->setDispatcher($dispatcher);
  1150. $application->setAutoExit(false);
  1151. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1152. $output->write('foo.');
  1153. });
  1154. $tester = new ApplicationTester($application);
  1155. $tester->run(['command' => 'foo']);
  1156. $this->assertContains('before.error.silenced.after.', $tester->getDisplay());
  1157. $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $tester->getStatusCode());
  1158. }
  1159. public function testConsoleErrorEventIsTriggeredOnCommandNotFound()
  1160. {
  1161. $dispatcher = new EventDispatcher();
  1162. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1163. $this->assertNull($event->getCommand());
  1164. $this->assertInstanceOf(CommandNotFoundException::class, $event->getError());
  1165. $event->getOutput()->write('silenced command not found');
  1166. });
  1167. $application = new Application();
  1168. $application->setDispatcher($dispatcher);
  1169. $application->setAutoExit(false);
  1170. $tester = new ApplicationTester($application);
  1171. $tester->run(['command' => 'unknown']);
  1172. $this->assertContains('silenced command not found', $tester->getDisplay());
  1173. $this->assertEquals(1, $tester->getStatusCode());
  1174. }
  1175. public function testErrorIsRethrownIfNotHandledByConsoleErrorEvent()
  1176. {
  1177. $application = new Application();
  1178. $application->setAutoExit(false);
  1179. $application->setCatchExceptions(false);
  1180. $application->setDispatcher(new EventDispatcher());
  1181. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1182. new \UnknownClass();
  1183. });
  1184. $tester = new ApplicationTester($application);
  1185. try {
  1186. $tester->run(['command' => 'dym']);
  1187. $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
  1188. } catch (\Error $e) {
  1189. $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found');
  1190. }
  1191. }
  1192. /**
  1193. * @expectedException \LogicException
  1194. * @expectedExceptionMessage error
  1195. */
  1196. public function testRunWithErrorAndDispatcher()
  1197. {
  1198. $application = new Application();
  1199. $application->setDispatcher($this->getDispatcher());
  1200. $application->setAutoExit(false);
  1201. $application->setCatchExceptions(false);
  1202. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1203. $output->write('dym.');
  1204. throw new \Error('dymerr');
  1205. });
  1206. $tester = new ApplicationTester($application);
  1207. $tester->run(['command' => 'dym']);
  1208. $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events');
  1209. }
  1210. public function testRunDispatchesAllEventsWithError()
  1211. {
  1212. $application = new Application();
  1213. $application->setDispatcher($this->getDispatcher());
  1214. $application->setAutoExit(false);
  1215. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1216. $output->write('dym.');
  1217. throw new \Error('dymerr');
  1218. });
  1219. $tester = new ApplicationTester($application);
  1220. $tester->run(['command' => 'dym']);
  1221. $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events');
  1222. }
  1223. public function testRunWithErrorFailingStatusCode()
  1224. {
  1225. $application = new Application();
  1226. $application->setDispatcher($this->getDispatcher());
  1227. $application->setAutoExit(false);
  1228. $application->register('dus')->setCode(function (InputInterface $input, OutputInterface $output) {
  1229. $output->write('dus.');
  1230. throw new \Error('duserr');
  1231. });
  1232. $tester = new ApplicationTester($application);
  1233. $tester->run(['command' => 'dus']);
  1234. $this->assertSame(1, $tester->getStatusCode(), 'Status code should be 1');
  1235. }
  1236. public function testRunWithDispatcherSkippingCommand()
  1237. {
  1238. $application = new Application();
  1239. $application->setDispatcher($this->getDispatcher(true));
  1240. $application->setAutoExit(false);
  1241. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1242. $output->write('foo.');
  1243. });
  1244. $tester = new ApplicationTester($application);
  1245. $exitCode = $tester->run(['command' => 'foo']);
  1246. $this->assertContains('before.after.', $tester->getDisplay());
  1247. $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode);
  1248. }
  1249. public function testRunWithDispatcherAccessingInputOptions()
  1250. {
  1251. $noInteractionValue = null;
  1252. $quietValue = null;
  1253. $dispatcher = $this->getDispatcher();
  1254. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$noInteractionValue, &$quietValue) {
  1255. $input = $event->getInput();
  1256. $noInteractionValue = $input->getOption('no-interaction');
  1257. $quietValue = $input->getOption('quiet');
  1258. });
  1259. $application = new Application();
  1260. $application->setDispatcher($dispatcher);
  1261. $application->setAutoExit(false);
  1262. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1263. $output->write('foo.');
  1264. });
  1265. $tester = new ApplicationTester($application);
  1266. $tester->run(['command' => 'foo', '--no-interaction' => true]);
  1267. $this->assertTrue($noInteractionValue);
  1268. $this->assertFalse($quietValue);
  1269. }
  1270. public function testRunWithDispatcherAddingInputOptions()
  1271. {
  1272. $extraValue = null;
  1273. $dispatcher = $this->getDispatcher();
  1274. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$extraValue) {
  1275. $definition = $event->getCommand()->getDefinition();
  1276. $input = $event->getInput();
  1277. $definition->addOption(new InputOption('extra', null, InputOption::VALUE_REQUIRED));
  1278. $input->bind($definition);
  1279. $extraValue = $input->getOption('extra');
  1280. });
  1281. $application = new Application();
  1282. $application->setDispatcher($dispatcher);
  1283. $application->setAutoExit(false);
  1284. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1285. $output->write('foo.');
  1286. });
  1287. $tester = new ApplicationTester($application);
  1288. $tester->run(['command' => 'foo', '--extra' => 'some test value']);
  1289. $this->assertEquals('some test value', $extraValue);
  1290. }
  1291. public function testSetRunCustomDefaultCommand()
  1292. {
  1293. $command = new \FooCommand();
  1294. $application = new Application();
  1295. $application->setAutoExit(false);
  1296. $application->add($command);
  1297. $application->setDefaultCommand($command->getName());
  1298. $tester = new ApplicationTester($application);
  1299. $tester->run([], ['interactive' => false]);
  1300. $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1301. $application = new CustomDefaultCommandApplication();
  1302. $application->setAutoExit(false);
  1303. $tester = new ApplicationTester($application);
  1304. $tester->run([], ['interactive' => false]);
  1305. $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1306. }
  1307. public function testSetRunCustomDefaultCommandWithOption()
  1308. {
  1309. $command = new \FooOptCommand();
  1310. $application = new Application();
  1311. $application->setAutoExit(false);
  1312. $application->add($command);
  1313. $application->setDefaultCommand($command->getName());
  1314. $tester = new ApplicationTester($application);
  1315. $tester->run(['--fooopt' => 'opt'], ['interactive' => false]);
  1316. $this->assertEquals('called'.PHP_EOL.'opt'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1317. }
  1318. public function testSetRunCustomSingleCommand()
  1319. {
  1320. $command = new \FooCommand();
  1321. $application = new Application();
  1322. $application->setAutoExit(false);
  1323. $application->add($command);
  1324. $application->setDefaultCommand($command->getName(), true);
  1325. $tester = new ApplicationTester($application);
  1326. $tester->run([]);
  1327. $this->assertContains('called', $tester->getDisplay());
  1328. $tester->run(['--help' => true]);
  1329. $this->assertContains('The foo:bar command', $tester->getDisplay());
  1330. }
  1331. /**
  1332. * @requires function posix_isatty
  1333. */
  1334. public function testCanCheckIfTerminalIsInteractive()
  1335. {
  1336. $application = new CustomDefaultCommandApplication();
  1337. $application->setAutoExit(false);
  1338. $tester = new ApplicationTester($application);
  1339. $tester->run(['command' => 'help']);
  1340. $this->assertFalse($tester->getInput()->hasParameterOption(['--no-interaction', '-n']));
  1341. $inputStream = $tester->getInput()->getStream();
  1342. $this->assertEquals($tester->getInput()->isInteractive(), @posix_isatty($inputStream));
  1343. }
  1344. public function testRunLazyCommandService()
  1345. {
  1346. $container = new ContainerBuilder();
  1347. $container->addCompilerPass(new AddConsoleCommandPass());
  1348. $container
  1349. ->register('lazy-command', LazyCommand::class)
  1350. ->addTag('console.command', ['command' => 'lazy:command'])
  1351. ->addTag('console.command', ['command' => 'lazy:alias'])
  1352. ->addTag('console.command', ['command' => 'lazy:alias2']);
  1353. $container->compile();
  1354. $application = new Application();
  1355. $application->setCommandLoader($container->get('console.command_loader'));
  1356. $application->setAutoExit(false);
  1357. $tester = new ApplicationTester($application);
  1358. $tester->run(['command' => 'lazy:command']);
  1359. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1360. $tester->run(['command' => 'lazy:alias']);
  1361. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1362. $tester->run(['command' => 'lazy:alias2']);
  1363. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1364. $command = $application->get('lazy:command');
  1365. $this->assertSame(['lazy:alias', 'lazy:alias2'], $command->getAliases());
  1366. }
  1367. /**
  1368. * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
  1369. */
  1370. public function testGetDisabledLazyCommand()
  1371. {
  1372. $application = new Application();
  1373. $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
  1374. $application->get('disabled');
  1375. }
  1376. public function testHasReturnsFalseForDisabledLazyCommand()
  1377. {
  1378. $application = new Application();
  1379. $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
  1380. $this->assertFalse($application->has('disabled'));
  1381. }
  1382. public function testAllExcludesDisabledLazyCommand()
  1383. {
  1384. $application = new Application();
  1385. $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
  1386. $this->assertArrayNotHasKey('disabled', $application->all());
  1387. }
  1388. protected function getDispatcher($skipCommand = false)
  1389. {
  1390. $dispatcher = new EventDispatcher();
  1391. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use ($skipCommand) {
  1392. $event->getOutput()->write('before.');
  1393. if ($skipCommand) {
  1394. $event->disableCommand();
  1395. }
  1396. });
  1397. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use ($skipCommand) {
  1398. $event->getOutput()->writeln('after.');
  1399. if (!$skipCommand) {
  1400. $event->setExitCode(ConsoleCommandEvent::RETURN_CODE_DISABLED);
  1401. }
  1402. });
  1403. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1404. $event->getOutput()->write('error.');
  1405. $event->setError(new \LogicException('error.', $event->getExitCode(), $event->getError()));
  1406. });
  1407. return $dispatcher;
  1408. }
  1409. public function testErrorIsRethrownIfNotHandledByConsoleErrorEventWithCatchingEnabled()
  1410. {
  1411. $application = new Application();
  1412. $application->setAutoExit(false);
  1413. $application->setDispatcher(new EventDispatcher());
  1414. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1415. new \UnknownClass();
  1416. });
  1417. $tester = new ApplicationTester($application);
  1418. try {
  1419. $tester->run(['command' => 'dym']);
  1420. $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
  1421. } catch (\Error $e) {
  1422. $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found');
  1423. }
  1424. }
  1425. /**
  1426. * @expectedException \RuntimeException
  1427. * @expectedExceptionMessage foo
  1428. */
  1429. public function testThrowingErrorListener()
  1430. {
  1431. $dispatcher = $this->getDispatcher();
  1432. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1433. throw new \RuntimeException('foo');
  1434. });
  1435. $dispatcher->addListener('console.command', function () {
  1436. throw new \RuntimeException('bar');
  1437. });
  1438. $application = new Application();
  1439. $application->setDispatcher($dispatcher);
  1440. $application->setAutoExit(false);
  1441. $application->setCatchExceptions(false);
  1442. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1443. $output->write('foo.');
  1444. });
  1445. $tester = new ApplicationTester($application);
  1446. $tester->run(['command' => 'foo']);
  1447. }
  1448. }
  1449. class CustomApplication extends Application
  1450. {
  1451. /**
  1452. * Overwrites the default input definition.
  1453. *
  1454. * @return InputDefinition An InputDefinition instance
  1455. */
  1456. protected function getDefaultInputDefinition()
  1457. {
  1458. return new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]);
  1459. }
  1460. /**
  1461. * Gets the default helper set with the helpers that should always be available.
  1462. *
  1463. * @return HelperSet A HelperSet instance
  1464. */
  1465. protected function getDefaultHelperSet()
  1466. {
  1467. return new HelperSet([new FormatterHelper()]);
  1468. }
  1469. }
  1470. class CustomDefaultCommandApplication extends Application
  1471. {
  1472. /**
  1473. * Overwrites the constructor in order to set a different default command.
  1474. */
  1475. public function __construct()
  1476. {
  1477. parent::__construct();
  1478. $command = new \FooCommand();
  1479. $this->add($command);
  1480. $this->setDefaultCommand($command->getName());
  1481. }
  1482. }
  1483. class LazyCommand extends Command
  1484. {
  1485. public function execute(InputInterface $input, OutputInterface $output)
  1486. {
  1487. $output->writeln('lazy-command called');
  1488. }
  1489. }
  1490. class DisabledCommand extends Command
  1491. {
  1492. public function isEnabled()
  1493. {
  1494. return false;
  1495. }
  1496. }