ApplicationTest.php 64 KB

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