PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Console/Tests/ApplicationTest.php

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