ApplicationTest.php 74KB

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