No Description

ApplicationTest.php 47KB

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