ApplicationTest.php 79 KB

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