ApplicationTest.php 55 KB

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