ApplicationTest.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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 \InvalidArgumentException
  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 \InvalidArgumentException
  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 \InvalidArgumentException
  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 \InvalidArgumentException
  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('InvalidArgumentException', $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 \InvalidArgumentException
  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 an \InvalidArgumentException if command does not exist, with alternatives');
  297. } catch (\Exception $e) {
  298. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  299. $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws an \InvalidArgumentException 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 an \InvalidArgumentException if command does not exist, with alternatives');
  307. } catch (\Exception $e) {
  308. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  309. $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws an \InvalidArgumentException 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 \InvalidArgumentException if a command is ambiguous because of a subnamespace, with alternatives');
  318. } catch (\Exception $e) {
  319. $this->assertInstanceOf('\InvalidArgumentException', $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 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->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, without alternatives');
  336. }
  337. // Test if "bar1" command throw an "\InvalidArgumentException" and does not contain
  338. // "foo:bar" as alternative because "bar1" is too far from "foo:bar"
  339. try {
  340. $application->find($commandName = 'bar1');
  341. $this->fail('->find() throws an \InvalidArgumentException if command does not exist');
  342. } catch (\Exception $e) {
  343. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist');
  344. $this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
  345. $this->assertRegExp('/afoobar1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternative : "afoobar1"');
  346. $this->assertRegExp('/foo:bar1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternative : "foo:bar1"');
  347. $this->assertNotRegExp('/foo:bar(?>!1)/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, without "foo:bar" alternative');
  348. }
  349. }
  350. public function testFindAlternativeCommandsWithAnAlias()
  351. {
  352. $fooCommand = new \FooCommand();
  353. $fooCommand->setAliases(array('foo2'));
  354. $application = new Application();
  355. $application->add($fooCommand);
  356. $result = $application->find('foo');
  357. $this->assertSame($fooCommand, $result);
  358. }
  359. public function testFindAlternativeNamespace()
  360. {
  361. $application = new Application();
  362. $application->add(new \FooCommand());
  363. $application->add(new \Foo1Command());
  364. $application->add(new \Foo2Command());
  365. $application->add(new \foo3Command());
  366. try {
  367. $application->find('Unknown-namespace:Unknown-command');
  368. $this->fail('->find() throws an \InvalidArgumentException if namespace does not exist');
  369. } catch (\Exception $e) {
  370. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if namespace does not exist');
  371. $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');
  372. }
  373. try {
  374. $application->find('foo2:command');
  375. $this->fail('->find() throws an \InvalidArgumentException if namespace does not exist');
  376. } catch (\Exception $e) {
  377. $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if namespace does not exist');
  378. $this->assertRegExp('/There are no commands defined in the "foo2" namespace./', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative');
  379. $this->assertRegExp('/foo/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo"');
  380. $this->assertRegExp('/foo1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo1"');
  381. $this->assertRegExp('/foo3/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo3"');
  382. }
  383. }
  384. public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces()
  385. {
  386. $application = $this->getMock('Symfony\Component\Console\Application', array('getNamespaces'));
  387. $application->expects($this->once())
  388. ->method('getNamespaces')
  389. ->will($this->returnValue(array('foo:sublong', 'bar:sub')));
  390. $this->assertEquals('foo:sublong', $application->findNamespace('f:sub'));
  391. }
  392. /**
  393. * @expectedException \InvalidArgumentException
  394. * @expectedExceptionMessage Command "foo::bar" is not defined.
  395. */
  396. public function testFindWithDoubleColonInNameThrowsException()
  397. {
  398. $application = new Application();
  399. $application->add(new \FooCommand());
  400. $application->add(new \Foo4Command());
  401. $application->find('foo::bar');
  402. }
  403. public function testSetCatchExceptions()
  404. {
  405. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  406. $application->setAutoExit(false);
  407. $application->expects($this->any())
  408. ->method('getTerminalWidth')
  409. ->will($this->returnValue(120));
  410. $tester = new ApplicationTester($application);
  411. $application->setCatchExceptions(true);
  412. $tester->run(array('command' => 'foo'), array('decorated' => false));
  413. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag');
  414. $application->setCatchExceptions(false);
  415. try {
  416. $tester->run(array('command' => 'foo'), array('decorated' => false));
  417. $this->fail('->setCatchExceptions() sets the catch exception flag');
  418. } catch (\Exception $e) {
  419. $this->assertInstanceOf('\Exception', $e, '->setCatchExceptions() sets the catch exception flag');
  420. $this->assertEquals('Command "foo" is not defined.', $e->getMessage(), '->setCatchExceptions() sets the catch exception flag');
  421. }
  422. }
  423. /**
  424. * @group legacy
  425. */
  426. public function testLegacyAsText()
  427. {
  428. $application = new Application();
  429. $application->add(new \FooCommand());
  430. $this->ensureStaticCommandHelp($application);
  431. $this->assertStringEqualsFile(self::$fixturesPath.'/application_astext1.txt', $this->normalizeLineBreaks($application->asText()), '->asText() returns a text representation of the application');
  432. $this->assertStringEqualsFile(self::$fixturesPath.'/application_astext2.txt', $this->normalizeLineBreaks($application->asText('foo')), '->asText() returns a text representation of the application');
  433. }
  434. /**
  435. * @group legacy
  436. */
  437. public function testLegacyAsXml()
  438. {
  439. $application = new Application();
  440. $application->add(new \FooCommand());
  441. $this->ensureStaticCommandHelp($application);
  442. $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/application_asxml1.txt', $application->asXml(), '->asXml() returns an XML representation of the application');
  443. $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/application_asxml2.txt', $application->asXml('foo'), '->asXml() returns an XML representation of the application');
  444. }
  445. public function testRenderException()
  446. {
  447. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  448. $application->setAutoExit(false);
  449. $application->expects($this->any())
  450. ->method('getTerminalWidth')
  451. ->will($this->returnValue(120));
  452. $tester = new ApplicationTester($application);
  453. $tester->run(array('command' => 'foo'), array('decorated' => false));
  454. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->renderException() renders a pretty exception');
  455. $tester->run(array('command' => 'foo'), array('decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE));
  456. $this->assertContains('Exception trace', $tester->getDisplay(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose');
  457. $tester->run(array('command' => 'list', '--foo' => true), array('decorated' => false));
  458. $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');
  459. $application->add(new \Foo3Command());
  460. $tester = new ApplicationTester($application);
  461. $tester->run(array('command' => 'foo3:bar'), array('decorated' => false));
  462. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  463. $tester->run(array('command' => 'foo3:bar'), array('decorated' => true));
  464. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  465. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  466. $application->setAutoExit(false);
  467. $application->expects($this->any())
  468. ->method('getTerminalWidth')
  469. ->will($this->returnValue(32));
  470. $tester = new ApplicationTester($application);
  471. $tester->run(array('command' => 'foo'), array('decorated' => false));
  472. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getDisplay(true), '->renderException() wraps messages when they are bigger than the terminal');
  473. }
  474. public function testRenderExceptionWithDoubleWidthCharacters()
  475. {
  476. if (!function_exists('mb_strwidth')) {
  477. $this->markTestSkipped('The "mb_strwidth" function is not available');
  478. }
  479. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  480. $application->setAutoExit(false);
  481. $application->expects($this->any())
  482. ->method('getTerminalWidth')
  483. ->will($this->returnValue(120));
  484. $application->register('foo')->setCode(function () {
  485. throw new \Exception('エラーメッセージ');
  486. });
  487. $tester = new ApplicationTester($application);
  488. $tester->run(array('command' => 'foo'), array('decorated' => false));
  489. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception_doublewidth1.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  490. $tester->run(array('command' => 'foo'), array('decorated' => true));
  491. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception_doublewidth1decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  492. $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
  493. $application->setAutoExit(false);
  494. $application->expects($this->any())
  495. ->method('getTerminalWidth')
  496. ->will($this->returnValue(32));
  497. $application->register('foo')->setCode(function () {
  498. throw new \Exception('コマンドの実行中にエラーが発生しました。');
  499. });
  500. $tester = new ApplicationTester($application);
  501. $tester->run(array('command' => 'foo'), array('decorated' => false));
  502. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception_doublewidth2.txt', $tester->getDisplay(true), '->renderException() wraps messages when they are bigger than the terminal');
  503. }
  504. public function testRun()
  505. {
  506. $application = new Application();
  507. $application->setAutoExit(false);
  508. $application->setCatchExceptions(false);
  509. $application->add($command = new \Foo1Command());
  510. $_SERVER['argv'] = array('cli.php', 'foo:bar1');
  511. ob_start();
  512. $application->run();
  513. ob_end_clean();
  514. $this->assertInstanceOf('Symfony\Component\Console\Input\ArgvInput', $command->input, '->run() creates an ArgvInput by default if none is given');
  515. $this->assertInstanceOf('Symfony\Component\Console\Output\ConsoleOutput', $command->output, '->run() creates a ConsoleOutput by default if none is given');
  516. $application = new Application();
  517. $application->setAutoExit(false);
  518. $application->setCatchExceptions(false);
  519. $this->ensureStaticCommandHelp($application);
  520. $tester = new ApplicationTester($application);
  521. $tester->run(array(), array('decorated' => false));
  522. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed');
  523. $tester->run(array('--help' => true), array('decorated' => false));
  524. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed');
  525. $tester->run(array('-h' => true), array('decorated' => false));
  526. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed');
  527. $tester->run(array('command' => 'list', '--help' => true), array('decorated' => false));
  528. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');
  529. $tester->run(array('command' => 'list', '-h' => true), array('decorated' => false));
  530. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');
  531. $tester->run(array('--ansi' => true));
  532. $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed');
  533. $tester->run(array('--no-ansi' => true));
  534. $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed');
  535. $tester->run(array('--version' => true), array('decorated' => false));
  536. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed');
  537. $tester->run(array('-V' => true), array('decorated' => false));
  538. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed');
  539. $tester->run(array('command' => 'list', '--quiet' => true));
  540. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed');
  541. $tester->run(array('command' => 'list', '-q' => true));
  542. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed');
  543. $tester->run(array('command' => 'list', '--verbose' => true));
  544. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed');
  545. $tester->run(array('command' => 'list', '--verbose' => 1));
  546. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed');
  547. $tester->run(array('command' => 'list', '--verbose' => 2));
  548. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed');
  549. $tester->run(array('command' => 'list', '--verbose' => 3));
  550. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed');
  551. $tester->run(array('command' => 'list', '--verbose' => 4));
  552. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed');
  553. $tester->run(array('command' => 'list', '-v' => true));
  554. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  555. $tester->run(array('command' => 'list', '-vv' => true));
  556. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  557. $tester->run(array('command' => 'list', '-vvv' => true));
  558. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  559. $application = new Application();
  560. $application->setAutoExit(false);
  561. $application->setCatchExceptions(false);
  562. $application->add(new \FooCommand());
  563. $tester = new ApplicationTester($application);
  564. $tester->run(array('command' => 'foo:bar', '--no-interaction' => true), array('decorated' => false));
  565. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed');
  566. $tester->run(array('command' => 'foo:bar', '-n' => true), array('decorated' => false));
  567. $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed');
  568. }
  569. /**
  570. * Issue #9285.
  571. *
  572. * If the "verbose" option is just before an argument in ArgvInput,
  573. * an argument value should not be treated as verbosity value.
  574. * This test will fail with "Not enough arguments." if broken
  575. */
  576. public function testVerboseValueNotBreakArguments()
  577. {
  578. $application = new Application();
  579. $application->setAutoExit(false);
  580. $application->setCatchExceptions(false);
  581. $application->add(new \FooCommand());
  582. $output = new StreamOutput(fopen('php://memory', 'w', false));
  583. $input = new ArgvInput(array('cli.php', '-v', 'foo:bar'));
  584. $application->run($input, $output);
  585. $input = new ArgvInput(array('cli.php', '--verbose', 'foo:bar'));
  586. $application->run($input, $output);
  587. }
  588. public function testRunReturnsIntegerExitCode()
  589. {
  590. $exception = new \Exception('', 4);
  591. $application = $this->getMock('Symfony\Component\Console\Application', array('doRun'));
  592. $application->setAutoExit(false);
  593. $application->expects($this->once())
  594. ->method('doRun')
  595. ->will($this->throwException($exception));
  596. $exitCode = $application->run(new ArrayInput(array()), new NullOutput());
  597. $this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception');
  598. }
  599. public function testRunReturnsExitCodeOneForExceptionCodeZero()
  600. {
  601. $exception = new \Exception('', 0);
  602. $application = $this->getMock('Symfony\Component\Console\Application', array('doRun'));
  603. $application->setAutoExit(false);
  604. $application->expects($this->once())
  605. ->method('doRun')
  606. ->will($this->throwException($exception));
  607. $exitCode = $application->run(new ArrayInput(array()), new NullOutput());
  608. $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0');
  609. }
  610. /**
  611. * @expectedException \LogicException
  612. * @dataProvider getAddingAlreadySetDefinitionElementData
  613. */
  614. public function testAddingAlreadySetDefinitionElementData($def)
  615. {
  616. $application = new Application();
  617. $application->setAutoExit(false);
  618. $application->setCatchExceptions(false);
  619. $application
  620. ->register('foo')
  621. ->setDefinition(array($def))
  622. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  623. ;
  624. $input = new ArrayInput(array('command' => 'foo'));
  625. $output = new NullOutput();
  626. $application->run($input, $output);
  627. }
  628. public function getAddingAlreadySetDefinitionElementData()
  629. {
  630. return array(
  631. array(new InputArgument('command', InputArgument::REQUIRED)),
  632. array(new InputOption('quiet', '', InputOption::VALUE_NONE)),
  633. array(new InputOption('query', 'q', InputOption::VALUE_NONE)),
  634. );
  635. }
  636. public function testGetDefaultHelperSetReturnsDefaultValues()
  637. {
  638. $application = new Application();
  639. $application->setAutoExit(false);
  640. $application->setCatchExceptions(false);
  641. $helperSet = $application->getHelperSet();
  642. $this->assertTrue($helperSet->has('formatter'));
  643. $this->assertTrue($helperSet->has('dialog'));
  644. $this->assertTrue($helperSet->has('progress'));
  645. }
  646. public function testAddingSingleHelperSetOverwritesDefaultValues()
  647. {
  648. $application = new Application();
  649. $application->setAutoExit(false);
  650. $application->setCatchExceptions(false);
  651. $application->setHelperSet(new HelperSet(array(new FormatterHelper())));
  652. $helperSet = $application->getHelperSet();
  653. $this->assertTrue($helperSet->has('formatter'));
  654. // no other default helper set should be returned
  655. $this->assertFalse($helperSet->has('dialog'));
  656. $this->assertFalse($helperSet->has('progress'));
  657. }
  658. public function testOverwritingDefaultHelperSetOverwritesDefaultValues()
  659. {
  660. $application = new CustomApplication();
  661. $application->setAutoExit(false);
  662. $application->setCatchExceptions(false);
  663. $application->setHelperSet(new HelperSet(array(new FormatterHelper())));
  664. $helperSet = $application->getHelperSet();
  665. $this->assertTrue($helperSet->has('formatter'));
  666. // no other default helper set should be returned
  667. $this->assertFalse($helperSet->has('dialog'));
  668. $this->assertFalse($helperSet->has('progress'));
  669. }
  670. public function testGetDefaultInputDefinitionReturnsDefaultValues()
  671. {
  672. $application = new Application();
  673. $application->setAutoExit(false);
  674. $application->setCatchExceptions(false);
  675. $inputDefinition = $application->getDefinition();
  676. $this->assertTrue($inputDefinition->hasArgument('command'));
  677. $this->assertTrue($inputDefinition->hasOption('help'));
  678. $this->assertTrue($inputDefinition->hasOption('quiet'));
  679. $this->assertTrue($inputDefinition->hasOption('verbose'));
  680. $this->assertTrue($inputDefinition->hasOption('version'));
  681. $this->assertTrue($inputDefinition->hasOption('ansi'));
  682. $this->assertTrue($inputDefinition->hasOption('no-ansi'));
  683. $this->assertTrue($inputDefinition->hasOption('no-interaction'));
  684. }
  685. public function testOverwritingDefaultInputDefinitionOverwritesDefaultValues()
  686. {
  687. $application = new CustomApplication();
  688. $application->setAutoExit(false);
  689. $application->setCatchExceptions(false);
  690. $inputDefinition = $application->getDefinition();
  691. // check whether the default arguments and options are not returned any more
  692. $this->assertFalse($inputDefinition->hasArgument('command'));
  693. $this->assertFalse($inputDefinition->hasOption('help'));
  694. $this->assertFalse($inputDefinition->hasOption('quiet'));
  695. $this->assertFalse($inputDefinition->hasOption('verbose'));
  696. $this->assertFalse($inputDefinition->hasOption('version'));
  697. $this->assertFalse($inputDefinition->hasOption('ansi'));
  698. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  699. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  700. $this->assertTrue($inputDefinition->hasOption('custom'));
  701. }
  702. public function testSettingCustomInputDefinitionOverwritesDefaultValues()
  703. {
  704. $application = new Application();
  705. $application->setAutoExit(false);
  706. $application->setCatchExceptions(false);
  707. $application->setDefinition(new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.'))));
  708. $inputDefinition = $application->getDefinition();
  709. // check whether the default arguments and options are not returned any more
  710. $this->assertFalse($inputDefinition->hasArgument('command'));
  711. $this->assertFalse($inputDefinition->hasOption('help'));
  712. $this->assertFalse($inputDefinition->hasOption('quiet'));
  713. $this->assertFalse($inputDefinition->hasOption('verbose'));
  714. $this->assertFalse($inputDefinition->hasOption('version'));
  715. $this->assertFalse($inputDefinition->hasOption('ansi'));
  716. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  717. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  718. $this->assertTrue($inputDefinition->hasOption('custom'));
  719. }
  720. public function testRunWithDispatcher()
  721. {
  722. $application = new Application();
  723. $application->setAutoExit(false);
  724. $application->setDispatcher($this->getDispatcher());
  725. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  726. $output->write('foo.');
  727. });
  728. $tester = new ApplicationTester($application);
  729. $tester->run(array('command' => 'foo'));
  730. $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay());
  731. }
  732. /**
  733. * @expectedException \LogicException
  734. * @expectedExceptionMessage caught
  735. */
  736. public function testRunWithExceptionAndDispatcher()
  737. {
  738. $application = new Application();
  739. $application->setDispatcher($this->getDispatcher());
  740. $application->setAutoExit(false);
  741. $application->setCatchExceptions(false);
  742. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  743. throw new \RuntimeException('foo');
  744. });
  745. $tester = new ApplicationTester($application);
  746. $tester->run(array('command' => 'foo'));
  747. }
  748. public function testRunDispatchesAllEventsWithException()
  749. {
  750. $application = new Application();
  751. $application->setDispatcher($this->getDispatcher());
  752. $application->setAutoExit(false);
  753. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  754. $output->write('foo.');
  755. throw new \RuntimeException('foo');
  756. });
  757. $tester = new ApplicationTester($application);
  758. $tester->run(array('command' => 'foo'));
  759. $this->assertContains('before.foo.caught.after.', $tester->getDisplay());
  760. }
  761. public function testRunWithDispatcherSkippingCommand()
  762. {
  763. $application = new Application();
  764. $application->setDispatcher($this->getDispatcher(true));
  765. $application->setAutoExit(false);
  766. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  767. $output->write('foo.');
  768. });
  769. $tester = new ApplicationTester($application);
  770. $exitCode = $tester->run(array('command' => 'foo'));
  771. $this->assertContains('before.after.', $tester->getDisplay());
  772. $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode);
  773. }
  774. public function testTerminalDimensions()
  775. {
  776. $application = new Application();
  777. $originalDimensions = $application->getTerminalDimensions();
  778. $this->assertCount(2, $originalDimensions);
  779. $width = 80;
  780. if ($originalDimensions[0] == $width) {
  781. $width = 100;
  782. }
  783. $application->setTerminalDimensions($width, 80);
  784. $this->assertSame(array($width, 80), $application->getTerminalDimensions());
  785. }
  786. protected function getDispatcher($skipCommand = false)
  787. {
  788. $dispatcher = new EventDispatcher();
  789. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use ($skipCommand) {
  790. $event->getOutput()->write('before.');
  791. if ($skipCommand) {
  792. $event->disableCommand();
  793. }
  794. });
  795. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use ($skipCommand) {
  796. $event->getOutput()->writeln('after.');
  797. if (!$skipCommand) {
  798. $event->setExitCode(113);
  799. }
  800. });
  801. $dispatcher->addListener('console.exception', function (ConsoleExceptionEvent $event) {
  802. $event->getOutput()->write('caught.');
  803. $event->setException(new \LogicException('caught.', $event->getExitCode(), $event->getException()));
  804. });
  805. return $dispatcher;
  806. }
  807. public function testSetRunCustomDefaultCommand()
  808. {
  809. $command = new \FooCommand();
  810. $application = new Application();
  811. $application->setAutoExit(false);
  812. $application->add($command);
  813. $application->setDefaultCommand($command->getName());
  814. $tester = new ApplicationTester($application);
  815. $tester->run(array());
  816. $this->assertEquals('interact called'.PHP_EOL.'called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  817. $application = new CustomDefaultCommandApplication();
  818. $application->setAutoExit(false);
  819. $tester = new ApplicationTester($application);
  820. $tester->run(array());
  821. $this->assertEquals('interact called'.PHP_EOL.'called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  822. }
  823. public function testCanCheckIfTerminalIsInteractive()
  824. {
  825. if (!function_exists('posix_isatty')) {
  826. $this->markTestSkipped('posix_isatty function is required');
  827. }
  828. $application = new CustomDefaultCommandApplication();
  829. $application->setAutoExit(false);
  830. $tester = new ApplicationTester($application);
  831. $tester->run(array('command' => 'help'));
  832. $this->assertFalse($tester->getInput()->hasParameterOption(array('--no-interaction', '-n')));
  833. $inputStream = $application->getHelperSet()->get('question')->getInputStream();
  834. $this->assertEquals($tester->getInput()->isInteractive(), @posix_isatty($inputStream));
  835. }
  836. }
  837. class CustomApplication extends Application
  838. {
  839. /**
  840. * Overwrites the default input definition.
  841. *
  842. * @return InputDefinition An InputDefinition instance
  843. */
  844. protected function getDefaultInputDefinition()
  845. {
  846. return new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')));
  847. }
  848. /**
  849. * Gets the default helper set with the helpers that should always be available.
  850. *
  851. * @return HelperSet A HelperSet instance
  852. */
  853. protected function getDefaultHelperSet()
  854. {
  855. return new HelperSet(array(new FormatterHelper()));
  856. }
  857. }
  858. class CustomDefaultCommandApplication extends Application
  859. {
  860. /**
  861. * Overwrites the constructor in order to set a different default command.
  862. */
  863. public function __construct()
  864. {
  865. parent::__construct();
  866. $command = new \FooCommand();
  867. $this->add($command);
  868. $this->setDefaultCommand($command->getName());
  869. }
  870. }