ApplicationTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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 Symfony\Component\Console\Application;
  12. use Symfony\Component\Console\Helper\HelperSet;
  13. use Symfony\Component\Console\Helper\FormatterHelper;
  14. use Symfony\Component\Console\Input\ArrayInput;
  15. use Symfony\Component\Console\Input\InputInterface;
  16. use Symfony\Component\Console\Input\InputArgument;
  17. use Symfony\Component\Console\Input\InputDefinition;
  18. use Symfony\Component\Console\Input\InputOption;
  19. use Symfony\Component\Console\Output\NullOutput;
  20. use Symfony\Component\Console\Output\Output;
  21. use Symfony\Component\Console\Output\OutputInterface;
  22. use Symfony\Component\Console\Tester\ApplicationTester;
  23. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  24. use Symfony\Component\Console\Event\ConsoleForExceptionEvent;
  25. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  26. use Symfony\Component\EventDispatcher\EventDispatcher;
  27. class ApplicationTest extends \PHPUnit_Framework_TestCase
  28. {
  29. protected static $fixturesPath;
  30. public static function setUpBeforeClass()
  31. {
  32. self::$fixturesPath = realpath(__DIR__.'/Fixtures/');
  33. require_once self::$fixturesPath.'/FooCommand.php';
  34. require_once self::$fixturesPath.'/Foo1Command.php';
  35. require_once self::$fixturesPath.'/Foo2Command.php';
  36. require_once self::$fixturesPath.'/Foo3Command.php';
  37. require_once self::$fixturesPath.'/Foo4Command.php';
  38. }
  39. protected function normalizeLineBreaks($text)
  40. {
  41. return str_replace(PHP_EOL, "\n", $text);
  42. }
  43. /**
  44. * Replaces the dynamic placeholders of the command help text with a static version.
  45. * The placeholder %command.full_name% includes the script path that is not predictable
  46. * and can not be tested against.
  47. */
  48. protected function ensureStaticCommandHelp(Application $application)
  49. {
  50. foreach ($application->all() as $command) {
  51. $command->setHelp(str_replace('%command.full_name%', 'app/console %command.name%', $command->getHelp()));
  52. }
  53. }
  54. public function testConstructor()
  55. {
  56. $application = new Application('foo', 'bar');
  57. $this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument');
  58. $this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its first argument');
  59. $this->assertEquals(array('help', 'list'), array_keys($application->all()), '__construct() registered the help and list commands by default');
  60. }
  61. public function testSetGetName()
  62. {
  63. $application = new Application();
  64. $application->setName('foo');
  65. $this->assertEquals('foo', $application->getName(), '->setName() sets the name of the application');
  66. }
  67. public function testSetGetVersion()
  68. {
  69. $application = new Application();
  70. $application->setVersion('bar');
  71. $this->assertEquals('bar', $application->getVersion(), '->setVersion() sets the version of the application');
  72. }
  73. public function testGetLongVersion()
  74. {
  75. $application = new Application('foo', 'bar');
  76. $this->assertEquals('<info>foo</info> version <comment>bar</comment>', $application->getLongVersion(), '->getLongVersion() returns the long version of the application');
  77. }
  78. public function testHelp()
  79. {
  80. $application = new Application();
  81. $this->assertStringEqualsFile(self::$fixturesPath.'/application_gethelp.txt', $this->normalizeLineBreaks($application->getHelp()), '->setHelp() returns a help message');
  82. }
  83. public function testAll()
  84. {
  85. $application = new Application();
  86. $commands = $application->all();
  87. $this->assertEquals('Symfony\\Component\\Console\\Command\\HelpCommand', get_class($commands['help']), '->all() returns the registered commands');
  88. $application->add(new \FooCommand());
  89. $commands = $application->all('foo');
  90. $this->assertEquals(1, count($commands), '->all() takes a namespace as its first argument');
  91. }
  92. public function testRegister()
  93. {
  94. $application = new Application();
  95. $command = $application->register('foo');
  96. $this->assertEquals('foo', $command->getName(), '->register() registers a new command');
  97. }
  98. public function testAdd()
  99. {
  100. $application = new Application();
  101. $application->add($foo = new \FooCommand());
  102. $commands = $application->all();
  103. $this->assertEquals($foo, $commands['foo:bar'], '->add() registers a command');
  104. $application = new Application();
  105. $application->addCommands(array($foo = new \FooCommand(), $foo1 = new \Foo1Command()));
  106. $commands = $application->all();
  107. $this->assertEquals(array($foo, $foo1), array($commands['foo:bar'], $commands['foo:bar1']), '->addCommands() registers an array of commands');
  108. }
  109. public function testHasGet()
  110. {
  111. $application = new Application();
  112. $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered');
  113. $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered');
  114. $application->add($foo = new \FooCommand());
  115. $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered');
  116. $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name');
  117. $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias');
  118. $application = new Application();
  119. $application->add($foo = new \FooCommand());
  120. // simulate --help
  121. $r = new \ReflectionObject($application);
  122. $p = $r->getProperty('wantHelps');
  123. $p->setAccessible(true);
  124. $p->setValue($application, true);
  125. $command = $application->get('foo:bar');
  126. $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $command, '->get() returns the help command if --help is provided as the input');
  127. }
  128. /**
  129. * @expectedException \InvalidArgumentException
  130. * @expectedExceptionMessage The command "foofoo" does not exist.
  131. */
  132. public function testGetInvalidCommand()
  133. {
  134. $application = new Application();
  135. $application->get('foofoo');
  136. }
  137. public function testGetNamespaces()
  138. {
  139. $application = new Application();
  140. $application->add(new \FooCommand());
  141. $application->add(new \Foo1Command());
  142. $this->assertEquals(array('foo'), $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces');
  143. }
  144. public function testFindNamespace()
  145. {
  146. $application = new Application();
  147. $application->add(new \FooCommand());
  148. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
  149. $this->assertEquals('foo', $application->findNamespace('f'), '->findNamespace() finds a namespace given an abbreviation');
  150. $application->add(new \Foo2Command());
  151. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
  152. }
  153. /**
  154. * @expectedException \InvalidArgumentException
  155. * @expectedExceptionMessage The namespace "f" is ambiguous (foo, foo1).
  156. */
  157. public function testFindAmbiguousNamespace()
  158. {
  159. $application = new Application();
  160. $application->add(new \FooCommand());
  161. $application->add(new \Foo2Command());
  162. $application->findNamespace('f');
  163. }
  164. /**
  165. * @expectedException \InvalidArgumentException
  166. * @expectedExceptionMessage There are no commands defined in the "bar" namespace.
  167. */
  168. public function testFindInvalidNamespace()
  169. {
  170. $application = new Application();
  171. $application->findNamespace('bar');
  172. }
  173. public function testFind()
  174. {
  175. $application = new Application();
  176. $application->add(new \FooCommand());
  177. $this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists');
  178. $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists');
  179. $this->assertInstanceOf('FooCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists');
  180. $this->assertInstanceOf('FooCommand', $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist');
  181. $this->assertInstanceOf('FooCommand', $application->find('a'), '->find() returns a command if the abbreviation exists for an alias');
  182. }
  183. /**
  184. * @dataProvider provideAmbiguousAbbreviations
  185. */
  186. public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage)
  187. {
  188. $this->setExpectedException('InvalidArgumentException', $expectedExceptionMessage);
  189. $application = new Application();
  190. $application->add(new \FooCommand());
  191. $application->add(new \Foo1Command());
  192. $application->add(new \Foo2Command());
  193. $application->find($abbreviation);
  194. }
  195. public function provideAmbiguousAbbreviations()
  196. {
  197. return array(
  198. array('f', 'Command "f" is not defined.'),
  199. array('a', 'Command "a" is ambiguous (afoobar, afoobar1 and 1 more).'),
  200. array('foo:b', 'Command "foo:b" is ambiguous (foo:bar, foo:bar1).')
  201. );
  202. }
  203. /**
  204. * @dataProvider provideInvalidCommandNamesSingle
  205. * @expectedException \InvalidArgumentException
  206. * @expectedExceptionMessage Did you mean this
  207. */
  208. public function testFindAlternativeExceptionMessageSingle($name)
  209. {
  210. $application = new Application();
  211. $application->add(new \FooCommand());
  212. $application->find($name);
  213. }
  214. public function provideInvalidCommandNamesSingle()
  215. {
  216. return array(
  217. array('foo:baR'),
  218. array('foO:bar')
  219. );
  220. }
  221. public function testFindAlternativeExceptionMessageMultiple()
  222. {
  223. $application = new Application();
  224. $application->add(new \FooCommand());
  225. $application->add(new \Foo1Command());
  226. $application->add(new \Foo2Command());
  227. // Command + plural
  228. try {
  229. $application->find('foo:baR');
  230. $this->fail('->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  231. } catch (\Exception $e) {
  232. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  233. $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  234. }
  235. // Namespace + plural
  236. try {
  237. $application->find('foo2:bar');
  238. $this->fail('->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  239. } catch (\Exception $e) {
  240. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  241. $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  242. }
  243. $application->add(new \Foo3Command());
  244. $application->add(new \Foo4Command());
  245. // Subnamespace + plural
  246. try {
  247. $a = $application->find('foo3:');
  248. $this->fail('->find() should throw an \InvalidArgumentException if a command is ambiguous because of a subnamespace, with alternatives');
  249. } catch (\Exception $e) {
  250. $this->assertInstanceOf('\InvalidArgumentException', $e);
  251. $this->assertRegExp('/foo3:bar/', $e->getMessage());
  252. $this->assertRegExp('/foo3:bar:toh/', $e->getMessage());
  253. }
  254. }
  255. public function testFindAlternativeCommands()
  256. {
  257. $application = new Application();
  258. $application->add(new \FooCommand());
  259. $application->add(new \Foo1Command());
  260. $application->add(new \Foo2Command());
  261. try {
  262. $application->find($commandName = 'Unknown command');
  263. $this->fail('->find() throws an \InvalidArgumentException if command does not exist');
  264. } catch (\Exception $e) {
  265. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist');
  266. $this->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, without alternatives');
  267. }
  268. try {
  269. $application->find($commandName = 'foo');
  270. $this->fail('->find() throws an \InvalidArgumentException if command does not exist');
  271. } catch (\Exception $e) {
  272. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist');
  273. $this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  274. $this->assertRegExp('/foo:bar/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternative : "foo:bar"');
  275. $this->assertRegExp('/foo1:bar/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternative : "foo1:bar"');
  276. $this->assertRegExp('/foo:bar1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternative : "foo:bar1"');
  277. }
  278. // Test if "foo1" command throw an "\InvalidArgumentException" and does not contain
  279. // "foo:bar" as alternative because "foo1" is too far from "foo:bar"
  280. try {
  281. $application->find($commandName = 'foo1');
  282. $this->fail('->find() throws an \InvalidArgumentException if command does not exist');
  283. } catch (\Exception $e) {
  284. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist');
  285. $this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  286. $this->assertFalse(strpos($e->getMessage(), 'foo:bar'), '->find() throws an \InvalidArgumentException if command does not exist, without "foo:bar" alternative');
  287. }
  288. }
  289. public function testFindAlternativeNamespace()
  290. {
  291. $application = new Application();
  292. $application->add(new \FooCommand());
  293. $application->add(new \Foo1Command());
  294. $application->add(new \Foo2Command());
  295. $application->add(new \foo3Command());
  296. try {
  297. $application->find('Unknown-namespace:Unknown-command');
  298. $this->fail('->find() throws an \InvalidArgumentException if namespace does not exist');
  299. } catch (\Exception $e) {
  300. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if namespace does not exist');
  301. $this->assertEquals('There are no commands defined in the "Unknown-namespace" namespace.', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, without alternatives');
  302. }
  303. try {
  304. $application->find('foo2:command');
  305. $this->fail('->find() throws an \InvalidArgumentException if namespace does not exist');
  306. } catch (\Exception $e) {
  307. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if namespace does not exist');
  308. $this->assertRegExp('/There are no commands defined in the "foo2" namespace./', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative');
  309. $this->assertRegExp('/foo/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo"');
  310. $this->assertRegExp('/foo1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo1"');
  311. $this->assertRegExp('/foo3/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo3"');
  312. }
  313. }
  314. public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces()
  315. {
  316. $application = $this->getMock('Symfony\Component\Console\Application', array('getNamespaces'));
  317. $application->expects($this->once())
  318. ->method('getNamespaces')
  319. ->will($this->returnValue(array('foo:sublong', 'bar:sub')));
  320. $this->assertEquals('foo:sublong', $application->findNamespace('f:sub'));
  321. }
  322. public function testSetCatchExceptions()
  323. {
  324. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  325. $application->setAutoExit(false);
  326. $application->expects($this->any())
  327. ->method('getTerminalWidth')
  328. ->will($this->returnValue(120));
  329. $tester = new ApplicationTester($application);
  330. $application->setCatchExceptions(true);
  331. $tester->run(array('command' => 'foo'), array('decorated' => false));
  332. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag');
  333. $application->setCatchExceptions(false);
  334. try {
  335. $tester->run(array('command' => 'foo'), array('decorated' => false));
  336. $this->fail('->setCatchExceptions() sets the catch exception flag');
  337. } catch (\Exception $e) {
  338. $this->assertInstanceOf('\Exception', $e, '->setCatchExceptions() sets the catch exception flag');
  339. $this->assertEquals('Command "foo" is not defined.', $e->getMessage(), '->setCatchExceptions() sets the catch exception flag');
  340. }
  341. }
  342. public function testAsText()
  343. {
  344. $application = new Application();
  345. $application->add(new \FooCommand);
  346. $this->ensureStaticCommandHelp($application);
  347. $this->assertStringEqualsFile(self::$fixturesPath.'/application_astext1.txt', $this->normalizeLineBreaks($application->asText()), '->asText() returns a text representation of the application');
  348. $this->assertStringEqualsFile(self::$fixturesPath.'/application_astext2.txt', $this->normalizeLineBreaks($application->asText('foo')), '->asText() returns a text representation of the application');
  349. }
  350. public function testAsXml()
  351. {
  352. $application = new Application();
  353. $application->add(new \FooCommand);
  354. $this->ensureStaticCommandHelp($application);
  355. $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/application_asxml1.txt', $application->asXml(), '->asXml() returns an XML representation of the application');
  356. $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/application_asxml2.txt', $application->asXml('foo'), '->asXml() returns an XML representation of the application');
  357. }
  358. public function testRenderException()
  359. {
  360. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  361. $application->setAutoExit(false);
  362. $application->expects($this->any())
  363. ->method('getTerminalWidth')
  364. ->will($this->returnValue(120));
  365. $tester = new ApplicationTester($application);
  366. $tester->run(array('command' => 'foo'), array('decorated' => false));
  367. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->renderException() renders a pretty exception');
  368. $tester->run(array('command' => 'foo'), array('decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE));
  369. $this->assertContains('Exception trace', $tester->getDisplay(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose');
  370. $tester->run(array('command' => 'list', '--foo' => true), array('decorated' => false));
  371. $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');
  372. $application->add(new \Foo3Command);
  373. $tester = new ApplicationTester($application);
  374. $tester->run(array('command' => 'foo3:bar'), array('decorated' => false));
  375. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  376. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  377. $application->setAutoExit(false);
  378. $application->expects($this->any())
  379. ->method('getTerminalWidth')
  380. ->will($this->returnValue(32));
  381. $tester = new ApplicationTester($application);
  382. $tester->run(array('command' => 'foo'), array('decorated' => false));
  383. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getDisplay(true), '->renderException() wraps messages when they are bigger than the terminal');
  384. }
  385. public function testRun()
  386. {
  387. $application = new Application();
  388. $application->setAutoExit(false);
  389. $application->setCatchExceptions(false);
  390. $application->add($command = new \Foo1Command());
  391. $_SERVER['argv'] = array('cli.php', 'foo:bar1');
  392. ob_start();
  393. $application->run();
  394. ob_end_clean();
  395. $this->assertSame('Symfony\Component\Console\Input\ArgvInput', get_class($command->input), '->run() creates an ArgvInput by default if none is given');
  396. $this->assertSame('Symfony\Component\Console\Output\ConsoleOutput', get_class($command->output), '->run() creates a ConsoleOutput by default if none is given');
  397. $application = new Application();
  398. $application->setAutoExit(false);
  399. $application->setCatchExceptions(false);
  400. $this->ensureStaticCommandHelp($application);
  401. $tester = new ApplicationTester($application);
  402. $tester->run(array(), array('decorated' => false));
  403. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed');
  404. $tester->run(array('--help' => true), array('decorated' => false));
  405. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed');
  406. $tester->run(array('-h' => true), array('decorated' => false));
  407. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed');
  408. $tester->run(array('command' => 'list', '--help' => true), array('decorated' => false));
  409. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');
  410. $tester->run(array('command' => 'list', '-h' => true), array('decorated' => false));
  411. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');
  412. $tester->run(array('--ansi' => true));
  413. $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed');
  414. $tester->run(array('--no-ansi' => true));
  415. $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed');
  416. $tester->run(array('--version' => true), array('decorated' => false));
  417. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed');
  418. $tester->run(array('-V' => true), array('decorated' => false));
  419. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed');
  420. $tester->run(array('command' => 'list', '--quiet' => true));
  421. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed');
  422. $tester->run(array('command' => 'list', '-q' => true));
  423. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed');
  424. $tester->run(array('command' => 'list', '--verbose' => true));
  425. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed');
  426. $tester->run(array('command' => 'list', '-v' => true));
  427. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  428. $application = new Application();
  429. $application->setAutoExit(false);
  430. $application->setCatchExceptions(false);
  431. $application->add(new \FooCommand());
  432. $tester = new ApplicationTester($application);
  433. $tester->run(array('command' => 'foo:bar', '--no-interaction' => true), array('decorated' => false));
  434. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed');
  435. $tester->run(array('command' => 'foo:bar', '-n' => true), array('decorated' => false));
  436. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed');
  437. }
  438. /**
  439. * @expectedException \LogicException
  440. * @dataProvider getAddingAlreadySetDefinitionElementData
  441. */
  442. public function testAddingAlreadySetDefinitionElementData($def)
  443. {
  444. $application = new Application();
  445. $application->setAutoExit(false);
  446. $application->setCatchExceptions(false);
  447. $application
  448. ->register('foo')
  449. ->setDefinition(array($def))
  450. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  451. ;
  452. $input = new ArrayInput(array('command' => 'foo'));
  453. $output = new NullOutput();
  454. $application->run($input, $output);
  455. }
  456. public function getAddingAlreadySetDefinitionElementData()
  457. {
  458. return array(
  459. array(new InputArgument('command', InputArgument::REQUIRED)),
  460. array(new InputOption('quiet', '', InputOption::VALUE_NONE)),
  461. array(new InputOption('query', 'q', InputOption::VALUE_NONE)),
  462. );
  463. }
  464. public function testGetDefaultHelperSetReturnsDefaultValues()
  465. {
  466. $application = new Application();
  467. $application->setAutoExit(false);
  468. $application->setCatchExceptions(false);
  469. $helperSet = $application->getHelperSet();
  470. $this->assertTrue($helperSet->has('formatter'));
  471. $this->assertTrue($helperSet->has('dialog'));
  472. $this->assertTrue($helperSet->has('progress'));
  473. }
  474. public function testAddingSingleHelperSetOverwritesDefaultValues()
  475. {
  476. $application = new Application();
  477. $application->setAutoExit(false);
  478. $application->setCatchExceptions(false);
  479. $application->setHelperSet(new HelperSet(array(new FormatterHelper())));
  480. $helperSet = $application->getHelperSet();
  481. $this->assertTrue($helperSet->has('formatter'));
  482. // no other default helper set should be returned
  483. $this->assertFalse($helperSet->has('dialog'));
  484. $this->assertFalse($helperSet->has('progress'));
  485. }
  486. public function testOverwritingDefaultHelperSetOverwritesDefaultValues()
  487. {
  488. $application = new CustomApplication();
  489. $application->setAutoExit(false);
  490. $application->setCatchExceptions(false);
  491. $application->setHelperSet(new HelperSet(array(new FormatterHelper())));
  492. $helperSet = $application->getHelperSet();
  493. $this->assertTrue($helperSet->has('formatter'));
  494. // no other default helper set should be returned
  495. $this->assertFalse($helperSet->has('dialog'));
  496. $this->assertFalse($helperSet->has('progress'));
  497. }
  498. public function testGetDefaultInputDefinitionReturnsDefaultValues()
  499. {
  500. $application = new Application();
  501. $application->setAutoExit(false);
  502. $application->setCatchExceptions(false);
  503. $inputDefinition = $application->getDefinition();
  504. $this->assertTrue($inputDefinition->hasArgument('command'));
  505. $this->assertTrue($inputDefinition->hasOption('help'));
  506. $this->assertTrue($inputDefinition->hasOption('quiet'));
  507. $this->assertTrue($inputDefinition->hasOption('verbose'));
  508. $this->assertTrue($inputDefinition->hasOption('version'));
  509. $this->assertTrue($inputDefinition->hasOption('ansi'));
  510. $this->assertTrue($inputDefinition->hasOption('no-ansi'));
  511. $this->assertTrue($inputDefinition->hasOption('no-interaction'));
  512. }
  513. public function testOverwritingDefaultInputDefinitionOverwritesDefaultValues()
  514. {
  515. $application = new CustomApplication();
  516. $application->setAutoExit(false);
  517. $application->setCatchExceptions(false);
  518. $inputDefinition = $application->getDefinition();
  519. // check whether the default arguments and options are not returned any more
  520. $this->assertFalse($inputDefinition->hasArgument('command'));
  521. $this->assertFalse($inputDefinition->hasOption('help'));
  522. $this->assertFalse($inputDefinition->hasOption('quiet'));
  523. $this->assertFalse($inputDefinition->hasOption('verbose'));
  524. $this->assertFalse($inputDefinition->hasOption('version'));
  525. $this->assertFalse($inputDefinition->hasOption('ansi'));
  526. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  527. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  528. $this->assertTrue($inputDefinition->hasOption('custom'));
  529. }
  530. public function testSettingCustomInputDefinitionOverwritesDefaultValues()
  531. {
  532. $application = new Application();
  533. $application->setAutoExit(false);
  534. $application->setCatchExceptions(false);
  535. $application->setDefinition(new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.'))));
  536. $inputDefinition = $application->getDefinition();
  537. // check whether the default arguments and options are not returned any more
  538. $this->assertFalse($inputDefinition->hasArgument('command'));
  539. $this->assertFalse($inputDefinition->hasOption('help'));
  540. $this->assertFalse($inputDefinition->hasOption('quiet'));
  541. $this->assertFalse($inputDefinition->hasOption('verbose'));
  542. $this->assertFalse($inputDefinition->hasOption('version'));
  543. $this->assertFalse($inputDefinition->hasOption('ansi'));
  544. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  545. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  546. $this->assertTrue($inputDefinition->hasOption('custom'));
  547. }
  548. public function testRunWithDispatcher()
  549. {
  550. if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
  551. $this->markTestSkipped('The "EventDispatcher" component is not available');
  552. }
  553. $application = new Application();
  554. $application->setAutoExit(false);
  555. $application->setDispatcher($this->getDispatcher());
  556. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  557. $output->write('foo.');
  558. });
  559. $tester = new ApplicationTester($application);
  560. $tester->run(array('command' => 'foo'));
  561. $this->assertEquals('before.foo.after.', $tester->getDisplay());
  562. }
  563. /**
  564. * @expectedException \LogicException
  565. * @expectedExceptionMessage caught
  566. */
  567. public function testRunWithExceptionAndDispatcher()
  568. {
  569. if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
  570. $this->markTestSkipped('The "EventDispatcher" component is not available');
  571. }
  572. $application = new Application();
  573. $application->setDispatcher($this->getDispatcher());
  574. $application->setAutoExit(false);
  575. $application->setCatchExceptions(false);
  576. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  577. throw new \RuntimeException('foo');
  578. });
  579. $tester = new ApplicationTester($application);
  580. $tester->run(array('command' => 'foo'));
  581. }
  582. public function testRunDispatchesAllEventsWithException()
  583. {
  584. if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
  585. $this->markTestSkipped('The "EventDispatcher" component is not available');
  586. }
  587. $application = new Application();
  588. $application->setDispatcher($this->getDispatcher());
  589. $application->setAutoExit(false);
  590. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  591. $output->write('foo.');
  592. throw new \RuntimeException('foo');
  593. });
  594. $tester = new ApplicationTester($application);
  595. $tester->run(array('command' => 'foo'));
  596. $this->assertContains('before.foo.after.caught.', $tester->getDisplay());
  597. }
  598. protected function getDispatcher()
  599. {
  600. $dispatcher = new EventDispatcher;
  601. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) {
  602. $event->getOutput()->write('before.');
  603. });
  604. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) {
  605. $event->getOutput()->write('after.');
  606. $event->setExitCode(128);
  607. });
  608. $dispatcher->addListener('console.exception', function (ConsoleForExceptionEvent $event) {
  609. $event->getOutput()->writeln('caught.');
  610. $event->setException(new \LogicException('caught.', $event->getExitCode(), $event->getException()));
  611. });
  612. return $dispatcher;
  613. }
  614. }
  615. class CustomApplication extends Application
  616. {
  617. /**
  618. * Overwrites the default input definition.
  619. *
  620. * @return InputDefinition An InputDefinition instance
  621. */
  622. protected function getDefaultInputDefinition()
  623. {
  624. return new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')));
  625. }
  626. /**
  627. * Gets the default helper set with the helpers that should always be available.
  628. *
  629. * @return HelperSet A HelperSet instance
  630. */
  631. protected function getDefaultHelperSet()
  632. {
  633. return new HelperSet(array(new FormatterHelper()));
  634. }
  635. }