ApplicationTest.php 63 KB

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