ApplicationTest.php 75 KB

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