PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/symfony/console/Tests/ApplicationTest.php

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