ApplicationTest.php 60 KB

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