ApplicationTest.php 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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(array('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(array(
  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(array($foo = new \FooCommand(), $foo1 = new \Foo1Command()));
  141. $commands = $application->all();
  142. $this->assertEquals(array($foo, $foo1), array($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(array(
  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(array('-h' => true, '-q' => true), array('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(array('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(array(
  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 array(
  347. array('f', 'Command "f" is not defined.'),
  348. array(
  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. array(
  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 array(
  399. array('foo3:barr'),
  400. array('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(array(), $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(array('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(array('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(array(), $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 = array(
  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(array('getNamespaces'))->getMock();
  535. $application->expects($this->once())
  536. ->method('getNamespaces')
  537. ->will($this->returnValue(array('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(array('command' => 'foo'), array('decorated' => false));
  560. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag');
  561. $tester->run(array('command' => 'foo'), array('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(array('command' => 'foo'), array('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(array('command' => 'foo'), array('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(array('command' => 'foo'), array('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(array('command' => 'list', '--foo' => true), array('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(array('command' => 'foo3:bar'), array('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(array('command' => 'foo3:bar'), array('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(array('command' => 'foo3:bar'), array('decorated' => true));
  601. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  602. $tester->run(array('command' => 'foo3:bar'), array('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(array('command' => 'foo'), array('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(array('command' => 'foo'), array('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(array('command' => 'foo'), array('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(array('command' => 'foo'), array('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(array('command' => 'foo'), array('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(array('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(array('command' => 'foo'), array('decorated' => false));
  661. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks');
  662. }
  663. public function testRun()
  664. {
  665. $application = new Application();
  666. $application->setAutoExit(false);
  667. $application->setCatchExceptions(false);
  668. $application->add($command = new \Foo1Command());
  669. $_SERVER['argv'] = array('cli.php', 'foo:bar1');
  670. ob_start();
  671. $application->run();
  672. ob_end_clean();
  673. $this->assertInstanceOf('Symfony\Component\Console\Input\ArgvInput', $command->input, '->run() creates an ArgvInput by default if none is given');
  674. $this->assertInstanceOf('Symfony\Component\Console\Output\ConsoleOutput', $command->output, '->run() creates a ConsoleOutput by default if none is given');
  675. $application = new Application();
  676. $application->setAutoExit(false);
  677. $application->setCatchExceptions(false);
  678. $this->ensureStaticCommandHelp($application);
  679. $tester = new ApplicationTester($application);
  680. $tester->run(array(), array('decorated' => false));
  681. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed');
  682. $tester->run(array('--help' => true), array('decorated' => false));
  683. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed');
  684. $tester->run(array('-h' => true), array('decorated' => false));
  685. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed');
  686. $tester->run(array('command' => 'list', '--help' => true), array('decorated' => false));
  687. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');
  688. $tester->run(array('command' => 'list', '-h' => true), array('decorated' => false));
  689. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');
  690. $tester->run(array('--ansi' => true));
  691. $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed');
  692. $tester->run(array('--no-ansi' => true));
  693. $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed');
  694. $tester->run(array('--version' => true), array('decorated' => false));
  695. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed');
  696. $tester->run(array('-V' => true), array('decorated' => false));
  697. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed');
  698. $tester->run(array('command' => 'list', '--quiet' => true));
  699. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed');
  700. $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if --quiet is passed');
  701. $tester->run(array('command' => 'list', '-q' => true));
  702. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed');
  703. $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if -q is passed');
  704. $tester->run(array('command' => 'list', '--verbose' => true));
  705. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed');
  706. $tester->run(array('command' => 'list', '--verbose' => 1));
  707. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed');
  708. $tester->run(array('command' => 'list', '--verbose' => 2));
  709. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed');
  710. $tester->run(array('command' => 'list', '--verbose' => 3));
  711. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed');
  712. $tester->run(array('command' => 'list', '--verbose' => 4));
  713. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed');
  714. $tester->run(array('command' => 'list', '-v' => true));
  715. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  716. $tester->run(array('command' => 'list', '-vv' => true));
  717. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  718. $tester->run(array('command' => 'list', '-vvv' => true));
  719. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  720. $application = new Application();
  721. $application->setAutoExit(false);
  722. $application->setCatchExceptions(false);
  723. $application->add(new \FooCommand());
  724. $tester = new ApplicationTester($application);
  725. $tester->run(array('command' => 'foo:bar', '--no-interaction' => true), array('decorated' => false));
  726. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed');
  727. $tester->run(array('command' => 'foo:bar', '-n' => true), array('decorated' => false));
  728. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed');
  729. }
  730. /**
  731. * Issue #9285.
  732. *
  733. * If the "verbose" option is just before an argument in ArgvInput,
  734. * an argument value should not be treated as verbosity value.
  735. * This test will fail with "Not enough arguments." if broken
  736. */
  737. public function testVerboseValueNotBreakArguments()
  738. {
  739. $application = new Application();
  740. $application->setAutoExit(false);
  741. $application->setCatchExceptions(false);
  742. $application->add(new \FooCommand());
  743. $output = new StreamOutput(fopen('php://memory', 'w', false));
  744. $input = new ArgvInput(array('cli.php', '-v', 'foo:bar'));
  745. $application->run($input, $output);
  746. $this->addToAssertionCount(1);
  747. $input = new ArgvInput(array('cli.php', '--verbose', 'foo:bar'));
  748. $application->run($input, $output);
  749. $this->addToAssertionCount(1);
  750. }
  751. public function testRunReturnsIntegerExitCode()
  752. {
  753. $exception = new \Exception('', 4);
  754. $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('doRun'))->getMock();
  755. $application->setAutoExit(false);
  756. $application->expects($this->once())
  757. ->method('doRun')
  758. ->will($this->throwException($exception));
  759. $exitCode = $application->run(new ArrayInput(array()), new NullOutput());
  760. $this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception');
  761. }
  762. public function testRunDispatchesIntegerExitCode()
  763. {
  764. $passedRightValue = false;
  765. // We can assume here that some other test asserts that the event is dispatched at all
  766. $dispatcher = new EventDispatcher();
  767. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) {
  768. $passedRightValue = (4 === $event->getExitCode());
  769. });
  770. $application = new Application();
  771. $application->setDispatcher($dispatcher);
  772. $application->setAutoExit(false);
  773. $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) {
  774. throw new \Exception('', 4);
  775. });
  776. $tester = new ApplicationTester($application);
  777. $tester->run(array('command' => 'test'));
  778. $this->assertTrue($passedRightValue, '-> exit code 4 was passed in the console.terminate event');
  779. }
  780. public function testRunReturnsExitCodeOneForExceptionCodeZero()
  781. {
  782. $exception = new \Exception('', 0);
  783. $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('doRun'))->getMock();
  784. $application->setAutoExit(false);
  785. $application->expects($this->once())
  786. ->method('doRun')
  787. ->will($this->throwException($exception));
  788. $exitCode = $application->run(new ArrayInput(array()), new NullOutput());
  789. $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0');
  790. }
  791. public function testRunDispatchesExitCodeOneForExceptionCodeZero()
  792. {
  793. $passedRightValue = false;
  794. // We can assume here that some other test asserts that the event is dispatched at all
  795. $dispatcher = new EventDispatcher();
  796. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) {
  797. $passedRightValue = (1 === $event->getExitCode());
  798. });
  799. $application = new Application();
  800. $application->setDispatcher($dispatcher);
  801. $application->setAutoExit(false);
  802. $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) {
  803. throw new \Exception();
  804. });
  805. $tester = new ApplicationTester($application);
  806. $tester->run(array('command' => 'test'));
  807. $this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event');
  808. }
  809. /**
  810. * @expectedException \LogicException
  811. * @expectedExceptionMessage An option with shortcut "e" already exists.
  812. */
  813. public function testAddingOptionWithDuplicateShortcut()
  814. {
  815. $dispatcher = new EventDispatcher();
  816. $application = new Application();
  817. $application->setAutoExit(false);
  818. $application->setCatchExceptions(false);
  819. $application->setDispatcher($dispatcher);
  820. $application->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'Environment'));
  821. $application
  822. ->register('foo')
  823. ->setAliases(array('f'))
  824. ->setDefinition(array(new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.')))
  825. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  826. ;
  827. $input = new ArrayInput(array('command' => 'foo'));
  828. $output = new NullOutput();
  829. $application->run($input, $output);
  830. }
  831. /**
  832. * @expectedException \LogicException
  833. * @dataProvider getAddingAlreadySetDefinitionElementData
  834. */
  835. public function testAddingAlreadySetDefinitionElementData($def)
  836. {
  837. $application = new Application();
  838. $application->setAutoExit(false);
  839. $application->setCatchExceptions(false);
  840. $application
  841. ->register('foo')
  842. ->setDefinition(array($def))
  843. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  844. ;
  845. $input = new ArrayInput(array('command' => 'foo'));
  846. $output = new NullOutput();
  847. $application->run($input, $output);
  848. }
  849. public function getAddingAlreadySetDefinitionElementData()
  850. {
  851. return array(
  852. array(new InputArgument('command', InputArgument::REQUIRED)),
  853. array(new InputOption('quiet', '', InputOption::VALUE_NONE)),
  854. array(new InputOption('query', 'q', InputOption::VALUE_NONE)),
  855. );
  856. }
  857. public function testGetDefaultHelperSetReturnsDefaultValues()
  858. {
  859. $application = new Application();
  860. $application->setAutoExit(false);
  861. $application->setCatchExceptions(false);
  862. $helperSet = $application->getHelperSet();
  863. $this->assertTrue($helperSet->has('formatter'));
  864. }
  865. public function testAddingSingleHelperSetOverwritesDefaultValues()
  866. {
  867. $application = new Application();
  868. $application->setAutoExit(false);
  869. $application->setCatchExceptions(false);
  870. $application->setHelperSet(new HelperSet(array(new FormatterHelper())));
  871. $helperSet = $application->getHelperSet();
  872. $this->assertTrue($helperSet->has('formatter'));
  873. // no other default helper set should be returned
  874. $this->assertFalse($helperSet->has('dialog'));
  875. $this->assertFalse($helperSet->has('progress'));
  876. }
  877. public function testOverwritingDefaultHelperSetOverwritesDefaultValues()
  878. {
  879. $application = new CustomApplication();
  880. $application->setAutoExit(false);
  881. $application->setCatchExceptions(false);
  882. $application->setHelperSet(new HelperSet(array(new FormatterHelper())));
  883. $helperSet = $application->getHelperSet();
  884. $this->assertTrue($helperSet->has('formatter'));
  885. // no other default helper set should be returned
  886. $this->assertFalse($helperSet->has('dialog'));
  887. $this->assertFalse($helperSet->has('progress'));
  888. }
  889. public function testGetDefaultInputDefinitionReturnsDefaultValues()
  890. {
  891. $application = new Application();
  892. $application->setAutoExit(false);
  893. $application->setCatchExceptions(false);
  894. $inputDefinition = $application->getDefinition();
  895. $this->assertTrue($inputDefinition->hasArgument('command'));
  896. $this->assertTrue($inputDefinition->hasOption('help'));
  897. $this->assertTrue($inputDefinition->hasOption('quiet'));
  898. $this->assertTrue($inputDefinition->hasOption('verbose'));
  899. $this->assertTrue($inputDefinition->hasOption('version'));
  900. $this->assertTrue($inputDefinition->hasOption('ansi'));
  901. $this->assertTrue($inputDefinition->hasOption('no-ansi'));
  902. $this->assertTrue($inputDefinition->hasOption('no-interaction'));
  903. }
  904. public function testOverwritingDefaultInputDefinitionOverwritesDefaultValues()
  905. {
  906. $application = new CustomApplication();
  907. $application->setAutoExit(false);
  908. $application->setCatchExceptions(false);
  909. $inputDefinition = $application->getDefinition();
  910. // check whether the default arguments and options are not returned any more
  911. $this->assertFalse($inputDefinition->hasArgument('command'));
  912. $this->assertFalse($inputDefinition->hasOption('help'));
  913. $this->assertFalse($inputDefinition->hasOption('quiet'));
  914. $this->assertFalse($inputDefinition->hasOption('verbose'));
  915. $this->assertFalse($inputDefinition->hasOption('version'));
  916. $this->assertFalse($inputDefinition->hasOption('ansi'));
  917. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  918. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  919. $this->assertTrue($inputDefinition->hasOption('custom'));
  920. }
  921. public function testSettingCustomInputDefinitionOverwritesDefaultValues()
  922. {
  923. $application = new Application();
  924. $application->setAutoExit(false);
  925. $application->setCatchExceptions(false);
  926. $application->setDefinition(new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.'))));
  927. $inputDefinition = $application->getDefinition();
  928. // check whether the default arguments and options are not returned any more
  929. $this->assertFalse($inputDefinition->hasArgument('command'));
  930. $this->assertFalse($inputDefinition->hasOption('help'));
  931. $this->assertFalse($inputDefinition->hasOption('quiet'));
  932. $this->assertFalse($inputDefinition->hasOption('verbose'));
  933. $this->assertFalse($inputDefinition->hasOption('version'));
  934. $this->assertFalse($inputDefinition->hasOption('ansi'));
  935. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  936. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  937. $this->assertTrue($inputDefinition->hasOption('custom'));
  938. }
  939. public function testRunWithDispatcher()
  940. {
  941. $application = new Application();
  942. $application->setAutoExit(false);
  943. $application->setDispatcher($this->getDispatcher());
  944. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  945. $output->write('foo.');
  946. });
  947. $tester = new ApplicationTester($application);
  948. $tester->run(array('command' => 'foo'));
  949. $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay());
  950. }
  951. /**
  952. * @expectedException \LogicException
  953. * @expectedExceptionMessage error
  954. */
  955. public function testRunWithExceptionAndDispatcher()
  956. {
  957. $application = new Application();
  958. $application->setDispatcher($this->getDispatcher());
  959. $application->setAutoExit(false);
  960. $application->setCatchExceptions(false);
  961. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  962. throw new \RuntimeException('foo');
  963. });
  964. $tester = new ApplicationTester($application);
  965. $tester->run(array('command' => 'foo'));
  966. }
  967. public function testRunDispatchesAllEventsWithException()
  968. {
  969. $application = new Application();
  970. $application->setDispatcher($this->getDispatcher());
  971. $application->setAutoExit(false);
  972. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  973. $output->write('foo.');
  974. throw new \RuntimeException('foo');
  975. });
  976. $tester = new ApplicationTester($application);
  977. $tester->run(array('command' => 'foo'));
  978. $this->assertContains('before.foo.error.after.', $tester->getDisplay());
  979. }
  980. public function testRunDispatchesAllEventsWithExceptionInListener()
  981. {
  982. $dispatcher = $this->getDispatcher();
  983. $dispatcher->addListener('console.command', function () {
  984. throw new \RuntimeException('foo');
  985. });
  986. $application = new Application();
  987. $application->setDispatcher($dispatcher);
  988. $application->setAutoExit(false);
  989. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  990. $output->write('foo.');
  991. });
  992. $tester = new ApplicationTester($application);
  993. $tester->run(array('command' => 'foo'));
  994. $this->assertContains('before.error.after.', $tester->getDisplay());
  995. }
  996. /**
  997. * @requires PHP 7
  998. */
  999. public function testRunWithError()
  1000. {
  1001. $application = new Application();
  1002. $application->setAutoExit(false);
  1003. $application->setCatchExceptions(false);
  1004. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1005. $output->write('dym.');
  1006. throw new \Error('dymerr');
  1007. });
  1008. $tester = new ApplicationTester($application);
  1009. try {
  1010. $tester->run(array('command' => 'dym'));
  1011. $this->fail('Error expected.');
  1012. } catch (\Error $e) {
  1013. $this->assertSame('dymerr', $e->getMessage());
  1014. }
  1015. }
  1016. public function testRunAllowsErrorListenersToSilenceTheException()
  1017. {
  1018. $dispatcher = $this->getDispatcher();
  1019. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1020. $event->getOutput()->write('silenced.');
  1021. $event->setExitCode(0);
  1022. });
  1023. $dispatcher->addListener('console.command', function () {
  1024. throw new \RuntimeException('foo');
  1025. });
  1026. $application = new Application();
  1027. $application->setDispatcher($dispatcher);
  1028. $application->setAutoExit(false);
  1029. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1030. $output->write('foo.');
  1031. });
  1032. $tester = new ApplicationTester($application);
  1033. $tester->run(array('command' => 'foo'));
  1034. $this->assertContains('before.error.silenced.after.', $tester->getDisplay());
  1035. $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $tester->getStatusCode());
  1036. }
  1037. public function testConsoleErrorEventIsTriggeredOnCommandNotFound()
  1038. {
  1039. $dispatcher = new EventDispatcher();
  1040. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1041. $this->assertNull($event->getCommand());
  1042. $this->assertInstanceOf(CommandNotFoundException::class, $event->getError());
  1043. $event->getOutput()->write('silenced command not found');
  1044. });
  1045. $application = new Application();
  1046. $application->setDispatcher($dispatcher);
  1047. $application->setAutoExit(false);
  1048. $tester = new ApplicationTester($application);
  1049. $tester->run(array('command' => 'unknown'));
  1050. $this->assertContains('silenced command not found', $tester->getDisplay());
  1051. $this->assertEquals(1, $tester->getStatusCode());
  1052. }
  1053. /**
  1054. * @group legacy
  1055. * @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.
  1056. */
  1057. public function testLegacyExceptionListenersAreStillTriggered()
  1058. {
  1059. $dispatcher = $this->getDispatcher();
  1060. $dispatcher->addListener('console.exception', function (ConsoleExceptionEvent $event) {
  1061. $event->getOutput()->write('caught.');
  1062. $event->setException(new \RuntimeException('replaced in caught.'));
  1063. });
  1064. $application = new Application();
  1065. $application->setDispatcher($dispatcher);
  1066. $application->setAutoExit(false);
  1067. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1068. throw new \RuntimeException('foo');
  1069. });
  1070. $tester = new ApplicationTester($application);
  1071. $tester->run(array('command' => 'foo'));
  1072. $this->assertContains('before.caught.error.after.', $tester->getDisplay());
  1073. $this->assertContains('replaced in caught.', $tester->getDisplay());
  1074. }
  1075. /**
  1076. * @requires PHP 7
  1077. */
  1078. public function testErrorIsRethrownIfNotHandledByConsoleErrorEvent()
  1079. {
  1080. $application = new Application();
  1081. $application->setAutoExit(false);
  1082. $application->setCatchExceptions(false);
  1083. $application->setDispatcher(new EventDispatcher());
  1084. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1085. new \UnknownClass();
  1086. });
  1087. $tester = new ApplicationTester($application);
  1088. try {
  1089. $tester->run(array('command' => 'dym'));
  1090. $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
  1091. } catch (\Error $e) {
  1092. $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found');
  1093. }
  1094. }
  1095. /**
  1096. * @requires PHP 7
  1097. * @expectedException \LogicException
  1098. * @expectedExceptionMessage error
  1099. */
  1100. public function testRunWithErrorAndDispatcher()
  1101. {
  1102. $application = new Application();
  1103. $application->setDispatcher($this->getDispatcher());
  1104. $application->setAutoExit(false);
  1105. $application->setCatchExceptions(false);
  1106. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1107. $output->write('dym.');
  1108. throw new \Error('dymerr');
  1109. });
  1110. $tester = new ApplicationTester($application);
  1111. $tester->run(array('command' => 'dym'));
  1112. $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events');
  1113. }
  1114. /**
  1115. * @requires PHP 7
  1116. */
  1117. public function testRunDispatchesAllEventsWithError()
  1118. {
  1119. $application = new Application();
  1120. $application->setDispatcher($this->getDispatcher());
  1121. $application->setAutoExit(false);
  1122. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1123. $output->write('dym.');
  1124. throw new \Error('dymerr');
  1125. });
  1126. $tester = new ApplicationTester($application);
  1127. $tester->run(array('command' => 'dym'));
  1128. $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events');
  1129. }
  1130. /**
  1131. * @requires PHP 7
  1132. */
  1133. public function testRunWithErrorFailingStatusCode()
  1134. {
  1135. $application = new Application();
  1136. $application->setDispatcher($this->getDispatcher());
  1137. $application->setAutoExit(false);
  1138. $application->register('dus')->setCode(function (InputInterface $input, OutputInterface $output) {
  1139. $output->write('dus.');
  1140. throw new \Error('duserr');
  1141. });
  1142. $tester = new ApplicationTester($application);
  1143. $tester->run(array('command' => 'dus'));
  1144. $this->assertSame(1, $tester->getStatusCode(), 'Status code should be 1');
  1145. }
  1146. public function testRunWithDispatcherSkippingCommand()
  1147. {
  1148. $application = new Application();
  1149. $application->setDispatcher($this->getDispatcher(true));
  1150. $application->setAutoExit(false);
  1151. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1152. $output->write('foo.');
  1153. });
  1154. $tester = new ApplicationTester($application);
  1155. $exitCode = $tester->run(array('command' => 'foo'));
  1156. $this->assertContains('before.after.', $tester->getDisplay());
  1157. $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode);
  1158. }
  1159. public function testRunWithDispatcherAccessingInputOptions()
  1160. {
  1161. $noInteractionValue = null;
  1162. $quietValue = null;
  1163. $dispatcher = $this->getDispatcher();
  1164. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$noInteractionValue, &$quietValue) {
  1165. $input = $event->getInput();
  1166. $noInteractionValue = $input->getOption('no-interaction');
  1167. $quietValue = $input->getOption('quiet');
  1168. });
  1169. $application = new Application();
  1170. $application->setDispatcher($dispatcher);
  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. $tester->run(array('command' => 'foo', '--no-interaction' => true));
  1177. $this->assertTrue($noInteractionValue);
  1178. $this->assertFalse($quietValue);
  1179. }
  1180. public function testRunWithDispatcherAddingInputOptions()
  1181. {
  1182. $extraValue = null;
  1183. $dispatcher = $this->getDispatcher();
  1184. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$extraValue) {
  1185. $definition = $event->getCommand()->getDefinition();
  1186. $input = $event->getInput();
  1187. $definition->addOption(new InputOption('extra', null, InputOption::VALUE_REQUIRED));
  1188. $input->bind($definition);
  1189. $extraValue = $input->getOption('extra');
  1190. });
  1191. $application = new Application();
  1192. $application->setDispatcher($dispatcher);
  1193. $application->setAutoExit(false);
  1194. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1195. $output->write('foo.');
  1196. });
  1197. $tester = new ApplicationTester($application);
  1198. $tester->run(array('command' => 'foo', '--extra' => 'some test value'));
  1199. $this->assertEquals('some test value', $extraValue);
  1200. }
  1201. /**
  1202. * @group legacy
  1203. */
  1204. public function testTerminalDimensions()
  1205. {
  1206. $application = new Application();
  1207. $originalDimensions = $application->getTerminalDimensions();
  1208. $this->assertCount(2, $originalDimensions);
  1209. $width = 80;
  1210. if ($originalDimensions[0] == $width) {
  1211. $width = 100;
  1212. }
  1213. $application->setTerminalDimensions($width, 80);
  1214. $this->assertSame(array($width, 80), $application->getTerminalDimensions());
  1215. }
  1216. public function testSetRunCustomDefaultCommand()
  1217. {
  1218. $command = new \FooCommand();
  1219. $application = new Application();
  1220. $application->setAutoExit(false);
  1221. $application->add($command);
  1222. $application->setDefaultCommand($command->getName());
  1223. $tester = new ApplicationTester($application);
  1224. $tester->run(array(), array('interactive' => false));
  1225. $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1226. $application = new CustomDefaultCommandApplication();
  1227. $application->setAutoExit(false);
  1228. $tester = new ApplicationTester($application);
  1229. $tester->run(array(), array('interactive' => false));
  1230. $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1231. }
  1232. public function testSetRunCustomDefaultCommandWithOption()
  1233. {
  1234. $command = new \FooOptCommand();
  1235. $application = new Application();
  1236. $application->setAutoExit(false);
  1237. $application->add($command);
  1238. $application->setDefaultCommand($command->getName());
  1239. $tester = new ApplicationTester($application);
  1240. $tester->run(array('--fooopt' => 'opt'), array('interactive' => false));
  1241. $this->assertEquals('called'.PHP_EOL.'opt'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1242. }
  1243. public function testSetRunCustomSingleCommand()
  1244. {
  1245. $command = new \FooCommand();
  1246. $application = new Application();
  1247. $application->setAutoExit(false);
  1248. $application->add($command);
  1249. $application->setDefaultCommand($command->getName(), true);
  1250. $tester = new ApplicationTester($application);
  1251. $tester->run(array());
  1252. $this->assertContains('called', $tester->getDisplay());
  1253. $tester->run(array('--help' => true));
  1254. $this->assertContains('The foo:bar command', $tester->getDisplay());
  1255. }
  1256. /**
  1257. * @requires function posix_isatty
  1258. */
  1259. public function testCanCheckIfTerminalIsInteractive()
  1260. {
  1261. $application = new CustomDefaultCommandApplication();
  1262. $application->setAutoExit(false);
  1263. $tester = new ApplicationTester($application);
  1264. $tester->run(array('command' => 'help'));
  1265. $this->assertFalse($tester->getInput()->hasParameterOption(array('--no-interaction', '-n')));
  1266. $inputStream = $tester->getInput()->getStream();
  1267. $this->assertEquals($tester->getInput()->isInteractive(), @posix_isatty($inputStream));
  1268. }
  1269. public function testRunLazyCommandService()
  1270. {
  1271. $container = new ContainerBuilder();
  1272. $container->addCompilerPass(new AddConsoleCommandPass());
  1273. $container
  1274. ->register('lazy-command', LazyCommand::class)
  1275. ->addTag('console.command', array('command' => 'lazy:command'))
  1276. ->addTag('console.command', array('command' => 'lazy:alias'))
  1277. ->addTag('console.command', array('command' => 'lazy:alias2'));
  1278. $container->compile();
  1279. $application = new Application();
  1280. $application->setCommandLoader($container->get('console.command_loader'));
  1281. $application->setAutoExit(false);
  1282. $tester = new ApplicationTester($application);
  1283. $tester->run(array('command' => 'lazy:command'));
  1284. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1285. $tester->run(array('command' => 'lazy:alias'));
  1286. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1287. $tester->run(array('command' => 'lazy:alias2'));
  1288. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1289. $command = $application->get('lazy:command');
  1290. $this->assertSame(array('lazy:alias', 'lazy:alias2'), $command->getAliases());
  1291. }
  1292. /**
  1293. * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
  1294. */
  1295. public function testGetDisabledLazyCommand()
  1296. {
  1297. $application = new Application();
  1298. $application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); })));
  1299. $application->get('disabled');
  1300. }
  1301. public function testHasReturnsFalseForDisabledLazyCommand()
  1302. {
  1303. $application = new Application();
  1304. $application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); })));
  1305. $this->assertFalse($application->has('disabled'));
  1306. }
  1307. public function testAllExcludesDisabledLazyCommand()
  1308. {
  1309. $application = new Application();
  1310. $application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); })));
  1311. $this->assertArrayNotHasKey('disabled', $application->all());
  1312. }
  1313. protected function getDispatcher($skipCommand = false)
  1314. {
  1315. $dispatcher = new EventDispatcher();
  1316. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use ($skipCommand) {
  1317. $event->getOutput()->write('before.');
  1318. if ($skipCommand) {
  1319. $event->disableCommand();
  1320. }
  1321. });
  1322. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use ($skipCommand) {
  1323. $event->getOutput()->writeln('after.');
  1324. if (!$skipCommand) {
  1325. $event->setExitCode(ConsoleCommandEvent::RETURN_CODE_DISABLED);
  1326. }
  1327. });
  1328. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1329. $event->getOutput()->write('error.');
  1330. $event->setError(new \LogicException('error.', $event->getExitCode(), $event->getError()));
  1331. });
  1332. return $dispatcher;
  1333. }
  1334. /**
  1335. * @requires PHP 7
  1336. */
  1337. public function testErrorIsRethrownIfNotHandledByConsoleErrorEventWithCatchingEnabled()
  1338. {
  1339. $application = new Application();
  1340. $application->setAutoExit(false);
  1341. $application->setDispatcher(new EventDispatcher());
  1342. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1343. new \UnknownClass();
  1344. });
  1345. $tester = new ApplicationTester($application);
  1346. try {
  1347. $tester->run(array('command' => 'dym'));
  1348. $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
  1349. } catch (\Error $e) {
  1350. $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found');
  1351. }
  1352. }
  1353. protected function tearDown()
  1354. {
  1355. putenv('SHELL_VERBOSITY');
  1356. unset($_ENV['SHELL_VERBOSITY']);
  1357. unset($_SERVER['SHELL_VERBOSITY']);
  1358. }
  1359. }
  1360. class CustomApplication extends Application
  1361. {
  1362. /**
  1363. * Overwrites the default input definition.
  1364. *
  1365. * @return InputDefinition An InputDefinition instance
  1366. */
  1367. protected function getDefaultInputDefinition()
  1368. {
  1369. return new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')));
  1370. }
  1371. /**
  1372. * Gets the default helper set with the helpers that should always be available.
  1373. *
  1374. * @return HelperSet A HelperSet instance
  1375. */
  1376. protected function getDefaultHelperSet()
  1377. {
  1378. return new HelperSet(array(new FormatterHelper()));
  1379. }
  1380. }
  1381. class CustomDefaultCommandApplication extends Application
  1382. {
  1383. /**
  1384. * Overwrites the constructor in order to set a different default command.
  1385. */
  1386. public function __construct()
  1387. {
  1388. parent::__construct();
  1389. $command = new \FooCommand();
  1390. $this->add($command);
  1391. $this->setDefaultCommand($command->getName());
  1392. }
  1393. }
  1394. class LazyCommand extends Command
  1395. {
  1396. public function execute(InputInterface $input, OutputInterface $output)
  1397. {
  1398. $output->writeln('lazy-command called');
  1399. }
  1400. }
  1401. class DisabledCommand extends Command
  1402. {
  1403. public function isEnabled()
  1404. {
  1405. return false;
  1406. }
  1407. }