ApplicationTest.php 62 KB

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