ApplicationTest.php 77 KB

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