ApplicationTest.php 78 KB

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