ApplicationTest.php 75 KB

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