ApplicationTest.php 54 KB

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