ApplicationTest.php 56 KB

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