ApplicationTest.php 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Console\Application;
  13. use Symfony\Component\Console\Command\Command;
  14. use Symfony\Component\Console\Command\HelpCommand;
  15. use Symfony\Component\Console\Command\LazyCommand;
  16. use Symfony\Component\Console\Command\SignalableCommandInterface;
  17. use Symfony\Component\Console\CommandLoader\FactoryCommandLoader;
  18. use Symfony\Component\Console\DependencyInjection\AddConsoleCommandPass;
  19. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  20. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  21. use Symfony\Component\Console\Event\ConsoleSignalEvent;
  22. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  23. use Symfony\Component\Console\Exception\CommandNotFoundException;
  24. use Symfony\Component\Console\Exception\NamespaceNotFoundException;
  25. use Symfony\Component\Console\Helper\FormatterHelper;
  26. use Symfony\Component\Console\Helper\HelperSet;
  27. use Symfony\Component\Console\Input\ArgvInput;
  28. use Symfony\Component\Console\Input\ArrayInput;
  29. use Symfony\Component\Console\Input\InputArgument;
  30. use Symfony\Component\Console\Input\InputDefinition;
  31. use Symfony\Component\Console\Input\InputInterface;
  32. use Symfony\Component\Console\Input\InputOption;
  33. use Symfony\Component\Console\Output\ConsoleOutput;
  34. use Symfony\Component\Console\Output\NullOutput;
  35. use Symfony\Component\Console\Output\Output;
  36. use Symfony\Component\Console\Output\OutputInterface;
  37. use Symfony\Component\Console\Output\StreamOutput;
  38. use Symfony\Component\Console\SignalRegistry\SignalRegistry;
  39. use Symfony\Component\Console\Terminal;
  40. use Symfony\Component\Console\Tester\ApplicationTester;
  41. use Symfony\Component\DependencyInjection\ContainerBuilder;
  42. use Symfony\Component\EventDispatcher\EventDispatcher;
  43. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  44. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  45. use Symfony\Component\Process\Process;
  46. class ApplicationTest extends TestCase
  47. {
  48. protected static $fixturesPath;
  49. private $colSize;
  50. protected function setUp(): void
  51. {
  52. $this->colSize = getenv('COLUMNS');
  53. }
  54. protected function tearDown(): void
  55. {
  56. putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS');
  57. putenv('SHELL_VERBOSITY');
  58. unset($_ENV['SHELL_VERBOSITY']);
  59. unset($_SERVER['SHELL_VERBOSITY']);
  60. if (\function_exists('pcntl_signal')) {
  61. // We reset all signals to their default value to avoid side effects
  62. for ($i = 1; $i <= 15; ++$i) {
  63. if (9 === $i) {
  64. continue;
  65. }
  66. pcntl_signal($i, SIG_DFL);
  67. }
  68. }
  69. }
  70. public static function setUpBeforeClass(): void
  71. {
  72. self::$fixturesPath = realpath(__DIR__.'/Fixtures/');
  73. require_once self::$fixturesPath.'/FooCommand.php';
  74. require_once self::$fixturesPath.'/FooOptCommand.php';
  75. require_once self::$fixturesPath.'/Foo1Command.php';
  76. require_once self::$fixturesPath.'/Foo2Command.php';
  77. require_once self::$fixturesPath.'/Foo3Command.php';
  78. require_once self::$fixturesPath.'/Foo4Command.php';
  79. require_once self::$fixturesPath.'/Foo5Command.php';
  80. require_once self::$fixturesPath.'/FooSameCaseUppercaseCommand.php';
  81. require_once self::$fixturesPath.'/FooSameCaseLowercaseCommand.php';
  82. require_once self::$fixturesPath.'/FoobarCommand.php';
  83. require_once self::$fixturesPath.'/BarBucCommand.php';
  84. require_once self::$fixturesPath.'/FooSubnamespaced1Command.php';
  85. require_once self::$fixturesPath.'/FooSubnamespaced2Command.php';
  86. require_once self::$fixturesPath.'/FooWithoutAliasCommand.php';
  87. require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering.php';
  88. require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering2.php';
  89. require_once self::$fixturesPath.'/FooHiddenCommand.php';
  90. require_once self::$fixturesPath.'/BarHiddenCommand.php';
  91. }
  92. protected function normalizeLineBreaks($text)
  93. {
  94. return str_replace(\PHP_EOL, "\n", $text);
  95. }
  96. /**
  97. * Replaces the dynamic placeholders of the command help text with a static version.
  98. * The placeholder %command.full_name% includes the script path that is not predictable
  99. * and cannot be tested against.
  100. */
  101. protected function ensureStaticCommandHelp(Application $application)
  102. {
  103. foreach ($application->all() as $command) {
  104. $command->setHelp(str_replace('%command.full_name%', 'app/console %command.name%', $command->getHelp()));
  105. }
  106. }
  107. public function testConstructor()
  108. {
  109. $application = new Application('foo', 'bar');
  110. $this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument');
  111. $this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its second argument');
  112. $this->assertEquals(['help', 'list', '_complete', 'completion'], array_keys($application->all()), '__construct() registered the help and list commands by default');
  113. }
  114. public function testSetGetName()
  115. {
  116. $application = new Application();
  117. $application->setName('foo');
  118. $this->assertEquals('foo', $application->getName(), '->setName() sets the name of the application');
  119. }
  120. public function testSetGetVersion()
  121. {
  122. $application = new Application();
  123. $application->setVersion('bar');
  124. $this->assertEquals('bar', $application->getVersion(), '->setVersion() sets the version of the application');
  125. }
  126. public function testGetLongVersion()
  127. {
  128. $application = new Application('foo', 'bar');
  129. $this->assertEquals('foo <info>bar</info>', $application->getLongVersion(), '->getLongVersion() returns the long version of the application');
  130. }
  131. public function testHelp()
  132. {
  133. $application = new Application();
  134. $this->assertStringEqualsFile(self::$fixturesPath.'/application_gethelp.txt', $this->normalizeLineBreaks($application->getHelp()), '->getHelp() returns a help message');
  135. }
  136. public function testAll()
  137. {
  138. $application = new Application();
  139. $commands = $application->all();
  140. $this->assertInstanceOf(HelpCommand::class, $commands['help'], '->all() returns the registered commands');
  141. $application->add(new \FooCommand());
  142. $commands = $application->all('foo');
  143. $this->assertCount(1, $commands, '->all() takes a namespace as its first argument');
  144. }
  145. public function testAllWithCommandLoader()
  146. {
  147. $application = new Application();
  148. $commands = $application->all();
  149. $this->assertInstanceOf(HelpCommand::class, $commands['help'], '->all() returns the registered commands');
  150. $application->add(new \FooCommand());
  151. $commands = $application->all('foo');
  152. $this->assertCount(1, $commands, '->all() takes a namespace as its first argument');
  153. $application->setCommandLoader(new FactoryCommandLoader([
  154. 'foo:bar1' => function () { return new \Foo1Command(); },
  155. ]));
  156. $commands = $application->all('foo');
  157. $this->assertCount(2, $commands, '->all() takes a namespace as its first argument');
  158. $this->assertInstanceOf(\FooCommand::class, $commands['foo:bar'], '->all() returns the registered commands');
  159. $this->assertInstanceOf(\Foo1Command::class, $commands['foo:bar1'], '->all() returns the registered commands');
  160. }
  161. public function testRegister()
  162. {
  163. $application = new Application();
  164. $command = $application->register('foo');
  165. $this->assertEquals('foo', $command->getName(), '->register() registers a new command');
  166. }
  167. public function testRegisterAmbiguous()
  168. {
  169. $code = function (InputInterface $input, OutputInterface $output) {
  170. $output->writeln('It works!');
  171. };
  172. $application = new Application();
  173. $application->setAutoExit(false);
  174. $application
  175. ->register('test-foo')
  176. ->setAliases(['test'])
  177. ->setCode($code);
  178. $application
  179. ->register('test-bar')
  180. ->setCode($code);
  181. $tester = new ApplicationTester($application);
  182. $tester->run(['test']);
  183. $this->assertStringContainsString('It works!', $tester->getDisplay(true));
  184. }
  185. public function testAdd()
  186. {
  187. $application = new Application();
  188. $application->add($foo = new \FooCommand());
  189. $commands = $application->all();
  190. $this->assertEquals($foo, $commands['foo:bar'], '->add() registers a command');
  191. $application = new Application();
  192. $application->addCommands([$foo = new \FooCommand(), $foo1 = new \Foo1Command()]);
  193. $commands = $application->all();
  194. $this->assertEquals([$foo, $foo1], [$commands['foo:bar'], $commands['foo:bar1']], '->addCommands() registers an array of commands');
  195. }
  196. public function testAddCommandWithEmptyConstructor()
  197. {
  198. $this->expectException(\LogicException::class);
  199. $this->expectExceptionMessage('Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor.');
  200. $application = new Application();
  201. $application->add(new \Foo5Command());
  202. }
  203. public function testHasGet()
  204. {
  205. $application = new Application();
  206. $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered');
  207. $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered');
  208. $application->add($foo = new \FooCommand());
  209. $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered');
  210. $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name');
  211. $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias');
  212. $application = new Application();
  213. $application->add($foo = new \FooCommand());
  214. // simulate --help
  215. $r = new \ReflectionObject($application);
  216. $p = $r->getProperty('wantHelps');
  217. $p->setAccessible(true);
  218. $p->setValue($application, true);
  219. $command = $application->get('foo:bar');
  220. $this->assertInstanceOf(HelpCommand::class, $command, '->get() returns the help command if --help is provided as the input');
  221. }
  222. public function testHasGetWithCommandLoader()
  223. {
  224. $application = new Application();
  225. $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered');
  226. $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered');
  227. $application->add($foo = new \FooCommand());
  228. $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered');
  229. $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name');
  230. $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias');
  231. $application->setCommandLoader(new FactoryCommandLoader([
  232. 'foo:bar1' => function () { return new \Foo1Command(); },
  233. ]));
  234. $this->assertTrue($application->has('afoobar'), '->has() returns true if an instance is registered for an alias even with command loader');
  235. $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns an instance by name even with command loader');
  236. $this->assertEquals($foo, $application->get('afoobar'), '->get() returns an instance by alias even with command loader');
  237. $this->assertTrue($application->has('foo:bar1'), '->has() returns true for commands registered in the loader');
  238. $this->assertInstanceOf(\Foo1Command::class, $foo1 = $application->get('foo:bar1'), '->get() returns a command by name from the command loader');
  239. $this->assertTrue($application->has('afoobar1'), '->has() returns true for commands registered in the loader');
  240. $this->assertEquals($foo1, $application->get('afoobar1'), '->get() returns a command by name from the command loader');
  241. }
  242. public function testSilentHelp()
  243. {
  244. $application = new Application();
  245. $application->setAutoExit(false);
  246. $application->setCatchExceptions(false);
  247. $tester = new ApplicationTester($application);
  248. $tester->run(['-h' => true, '-q' => true], ['decorated' => false]);
  249. $this->assertEmpty($tester->getDisplay(true));
  250. }
  251. public function testGetInvalidCommand()
  252. {
  253. $this->expectException(CommandNotFoundException::class);
  254. $this->expectExceptionMessage('The command "foofoo" does not exist.');
  255. $application = new Application();
  256. $application->get('foofoo');
  257. }
  258. public function testGetNamespaces()
  259. {
  260. $application = new Application();
  261. $application->add(new \FooCommand());
  262. $application->add(new \Foo1Command());
  263. $this->assertEquals(['foo'], $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces');
  264. }
  265. public function testFindNamespace()
  266. {
  267. $application = new Application();
  268. $application->add(new \FooCommand());
  269. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
  270. $this->assertEquals('foo', $application->findNamespace('f'), '->findNamespace() finds a namespace given an abbreviation');
  271. $application->add(new \Foo2Command());
  272. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
  273. }
  274. public function testFindNamespaceWithSubnamespaces()
  275. {
  276. $application = new Application();
  277. $application->add(new \FooSubnamespaced1Command());
  278. $application->add(new \FooSubnamespaced2Command());
  279. $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns commands even if the commands are only contained in subnamespaces');
  280. }
  281. public function testFindAmbiguousNamespace()
  282. {
  283. $application = new Application();
  284. $application->add(new \BarBucCommand());
  285. $application->add(new \FooCommand());
  286. $application->add(new \Foo2Command());
  287. $expectedMsg = "The namespace \"f\" is ambiguous.\nDid you mean one of these?\n foo\n foo1";
  288. $this->expectException(NamespaceNotFoundException::class);
  289. $this->expectExceptionMessage($expectedMsg);
  290. $application->findNamespace('f');
  291. }
  292. public function testFindNonAmbiguous()
  293. {
  294. $application = new Application();
  295. $application->add(new \TestAmbiguousCommandRegistering());
  296. $application->add(new \TestAmbiguousCommandRegistering2());
  297. $this->assertEquals('test-ambiguous', $application->find('test')->getName());
  298. }
  299. public function testFindInvalidNamespace()
  300. {
  301. $this->expectException(NamespaceNotFoundException::class);
  302. $this->expectExceptionMessage('There are no commands defined in the "bar" namespace.');
  303. $application = new Application();
  304. $application->findNamespace('bar');
  305. }
  306. public function testFindUniqueNameButNamespaceName()
  307. {
  308. $this->expectException(CommandNotFoundException::class);
  309. $this->expectExceptionMessage('Command "foo1" is not defined');
  310. $application = new Application();
  311. $application->add(new \FooCommand());
  312. $application->add(new \Foo1Command());
  313. $application->add(new \Foo2Command());
  314. $application->find($commandName = 'foo1');
  315. }
  316. public function testFind()
  317. {
  318. $application = new Application();
  319. $application->add(new \FooCommand());
  320. $this->assertInstanceOf(\FooCommand::class, $application->find('foo:bar'), '->find() returns a command if its name exists');
  321. $this->assertInstanceOf(HelpCommand::class, $application->find('h'), '->find() returns a command if its name exists');
  322. $this->assertInstanceOf(\FooCommand::class, $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists');
  323. $this->assertInstanceOf(\FooCommand::class, $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist');
  324. $this->assertInstanceOf(\FooCommand::class, $application->find('a'), '->find() returns a command if the abbreviation exists for an alias');
  325. }
  326. public function testFindCaseSensitiveFirst()
  327. {
  328. $application = new Application();
  329. $application->add(new \FooSameCaseUppercaseCommand());
  330. $application->add(new \FooSameCaseLowercaseCommand());
  331. $this->assertInstanceOf(\FooSameCaseUppercaseCommand::class, $application->find('f:B'), '->find() returns a command if the abbreviation is the correct case');
  332. $this->assertInstanceOf(\FooSameCaseUppercaseCommand::class, $application->find('f:BAR'), '->find() returns a command if the abbreviation is the correct case');
  333. $this->assertInstanceOf(\FooSameCaseLowercaseCommand::class, $application->find('f:b'), '->find() returns a command if the abbreviation is the correct case');
  334. $this->assertInstanceOf(\FooSameCaseLowercaseCommand::class, $application->find('f:bar'), '->find() returns a command if the abbreviation is the correct case');
  335. }
  336. public function testFindCaseInsensitiveAsFallback()
  337. {
  338. $application = new Application();
  339. $application->add(new \FooSameCaseLowercaseCommand());
  340. $this->assertInstanceOf(\FooSameCaseLowercaseCommand::class, $application->find('f:b'), '->find() returns a command if the abbreviation is the correct case');
  341. $this->assertInstanceOf(\FooSameCaseLowercaseCommand::class, $application->find('f:B'), '->find() will fallback to case insensitivity');
  342. $this->assertInstanceOf(\FooSameCaseLowercaseCommand::class, $application->find('FoO:BaR'), '->find() will fallback to case insensitivity');
  343. }
  344. public function testFindCaseInsensitiveSuggestions()
  345. {
  346. $this->expectException(CommandNotFoundException::class);
  347. $this->expectExceptionMessage('Command "FoO:BaR" is ambiguous');
  348. $application = new Application();
  349. $application->add(new \FooSameCaseLowercaseCommand());
  350. $application->add(new \FooSameCaseUppercaseCommand());
  351. $this->assertInstanceOf(\FooSameCaseLowercaseCommand::class, $application->find('FoO:BaR'), '->find() will find two suggestions with case insensitivity');
  352. }
  353. public function testFindWithCommandLoader()
  354. {
  355. $application = new Application();
  356. $application->setCommandLoader(new FactoryCommandLoader([
  357. 'foo:bar' => $f = function () { return new \FooCommand(); },
  358. ]));
  359. $this->assertInstanceOf(\FooCommand::class, $application->find('foo:bar'), '->find() returns a command if its name exists');
  360. $this->assertInstanceOf(HelpCommand::class, $application->find('h'), '->find() returns a command if its name exists');
  361. $this->assertInstanceOf(\FooCommand::class, $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists');
  362. $this->assertInstanceOf(\FooCommand::class, $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist');
  363. $this->assertInstanceOf(\FooCommand::class, $application->find('a'), '->find() returns a command if the abbreviation exists for an alias');
  364. }
  365. /**
  366. * @dataProvider provideAmbiguousAbbreviations
  367. */
  368. public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage)
  369. {
  370. putenv('COLUMNS=120');
  371. $this->expectException(CommandNotFoundException::class);
  372. $this->expectExceptionMessage($expectedExceptionMessage);
  373. $application = new Application();
  374. $application->add(new \FooCommand());
  375. $application->add(new \Foo1Command());
  376. $application->add(new \Foo2Command());
  377. $application->find($abbreviation);
  378. }
  379. public static function provideAmbiguousAbbreviations()
  380. {
  381. return [
  382. ['f', 'Command "f" is not defined.'],
  383. [
  384. 'a',
  385. "Command \"a\" is ambiguous.\nDid you mean one of these?\n".
  386. " afoobar The foo:bar command\n".
  387. " afoobar1 The foo:bar1 command\n".
  388. ' afoobar2 The foo1:bar command',
  389. ],
  390. [
  391. 'foo:b',
  392. "Command \"foo:b\" is ambiguous.\nDid you mean one of these?\n".
  393. " foo:bar The foo:bar command\n".
  394. " foo:bar1 The foo:bar1 command\n".
  395. ' foo1:bar The foo1:bar command',
  396. ],
  397. ];
  398. }
  399. public function testFindWithAmbiguousAbbreviationsFindsCommandIfAlternativesAreHidden()
  400. {
  401. $application = new Application();
  402. $application->add(new \FooCommand());
  403. $application->add(new \FooHiddenCommand());
  404. $this->assertInstanceOf(\FooCommand::class, $application->find('foo:'));
  405. }
  406. public function testFindCommandEqualNamespace()
  407. {
  408. $application = new Application();
  409. $application->add(new \Foo3Command());
  410. $application->add(new \Foo4Command());
  411. $this->assertInstanceOf(\Foo3Command::class, $application->find('foo3:bar'), '->find() returns the good command even if a namespace has same name');
  412. $this->assertInstanceOf(\Foo4Command::class, $application->find('foo3:bar:toh'), '->find() returns a command even if its namespace equals another command name');
  413. }
  414. public function testFindCommandWithAmbiguousNamespacesButUniqueName()
  415. {
  416. $application = new Application();
  417. $application->add(new \FooCommand());
  418. $application->add(new \FoobarCommand());
  419. $this->assertInstanceOf(\FoobarCommand::class, $application->find('f:f'));
  420. }
  421. public function testFindCommandWithMissingNamespace()
  422. {
  423. $application = new Application();
  424. $application->add(new \Foo4Command());
  425. $this->assertInstanceOf(\Foo4Command::class, $application->find('f::t'));
  426. }
  427. /**
  428. * @dataProvider provideInvalidCommandNamesSingle
  429. */
  430. public function testFindAlternativeExceptionMessageSingle($name)
  431. {
  432. $this->expectException(CommandNotFoundException::class);
  433. $this->expectExceptionMessage('Did you mean this');
  434. $application = new Application();
  435. $application->add(new \Foo3Command());
  436. $application->find($name);
  437. }
  438. public function testDontRunAlternativeNamespaceName()
  439. {
  440. $application = new Application();
  441. $application->add(new \Foo1Command());
  442. $application->setAutoExit(false);
  443. $tester = new ApplicationTester($application);
  444. $tester->run(['command' => 'foos:bar1'], ['decorated' => false]);
  445. $this->assertStringEqualsFile(self::$fixturesPath.'/application.dont_run_alternative_namespace_name.txt', $tester->getDisplay(true));
  446. }
  447. public function testCanRunAlternativeCommandName()
  448. {
  449. $application = new Application();
  450. $application->add(new \FooWithoutAliasCommand());
  451. $application->setAutoExit(false);
  452. $tester = new ApplicationTester($application);
  453. $tester->setInputs(['y']);
  454. $tester->run(['command' => 'foos'], ['decorated' => false]);
  455. $display = trim($tester->getDisplay(true));
  456. $this->assertStringContainsString('Command "foos" is not defined', $display);
  457. $this->assertStringContainsString('Do you want to run "foo" instead? (yes/no) [no]:', $display);
  458. $this->assertStringContainsString('called', $display);
  459. }
  460. public function testDontRunAlternativeCommandName()
  461. {
  462. $application = new Application();
  463. $application->add(new \FooWithoutAliasCommand());
  464. $application->setAutoExit(false);
  465. $tester = new ApplicationTester($application);
  466. $tester->setInputs(['n']);
  467. $exitCode = $tester->run(['command' => 'foos'], ['decorated' => false]);
  468. $this->assertSame(1, $exitCode);
  469. $display = trim($tester->getDisplay(true));
  470. $this->assertStringContainsString('Command "foos" is not defined', $display);
  471. $this->assertStringContainsString('Do you want to run "foo" instead? (yes/no) [no]:', $display);
  472. }
  473. public static function provideInvalidCommandNamesSingle()
  474. {
  475. return [
  476. ['foo3:barr'],
  477. ['fooo3:bar'],
  478. ];
  479. }
  480. public function testFindAlternativeExceptionMessageMultiple()
  481. {
  482. putenv('COLUMNS=120');
  483. $application = new Application();
  484. $application->add(new \FooCommand());
  485. $application->add(new \Foo1Command());
  486. $application->add(new \Foo2Command());
  487. // Command + plural
  488. try {
  489. $application->find('foo:baR');
  490. $this->fail('->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  491. } catch (\Exception $e) {
  492. $this->assertInstanceOf(CommandNotFoundException::class, $e, '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  493. $this->assertMatchesRegularExpression('/Did you mean one of these/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  494. $this->assertMatchesRegularExpression('/foo1:bar/', $e->getMessage());
  495. $this->assertMatchesRegularExpression('/foo:bar/', $e->getMessage());
  496. }
  497. // Namespace + plural
  498. try {
  499. $application->find('foo2:bar');
  500. $this->fail('->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  501. } catch (\Exception $e) {
  502. $this->assertInstanceOf(CommandNotFoundException::class, $e, '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  503. $this->assertMatchesRegularExpression('/Did you mean one of these/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  504. $this->assertMatchesRegularExpression('/foo1/', $e->getMessage());
  505. }
  506. $application->add(new \Foo3Command());
  507. $application->add(new \Foo4Command());
  508. // Subnamespace + plural
  509. try {
  510. $application->find('foo3:');
  511. $this->fail('->find() should throw an Symfony\Component\Console\Exception\CommandNotFoundException if a command is ambiguous because of a subnamespace, with alternatives');
  512. } catch (\Exception $e) {
  513. $this->assertInstanceOf(CommandNotFoundException::class, $e);
  514. $this->assertMatchesRegularExpression('/foo3:bar/', $e->getMessage());
  515. $this->assertMatchesRegularExpression('/foo3:bar:toh/', $e->getMessage());
  516. }
  517. }
  518. public function testFindAlternativeCommands()
  519. {
  520. $application = new Application();
  521. $application->add(new \FooCommand());
  522. $application->add(new \Foo1Command());
  523. $application->add(new \Foo2Command());
  524. try {
  525. $application->find($commandName = 'Unknown command');
  526. $this->fail('->find() throws a CommandNotFoundException if command does not exist');
  527. } catch (\Exception $e) {
  528. $this->assertInstanceOf(CommandNotFoundException::class, $e, '->find() throws a CommandNotFoundException if command does not exist');
  529. $this->assertSame([], $e->getAlternatives());
  530. $this->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without alternatives');
  531. }
  532. // Test if "bar1" command throw a "CommandNotFoundException" and does not contain
  533. // "foo:bar" as alternative because "bar1" is too far from "foo:bar"
  534. try {
  535. $application->find($commandName = 'bar1');
  536. $this->fail('->find() throws a CommandNotFoundException if command does not exist');
  537. } catch (\Exception $e) {
  538. $this->assertInstanceOf(CommandNotFoundException::class, $e, '->find() throws a CommandNotFoundException if command does not exist');
  539. $this->assertSame(['afoobar1', 'foo:bar1'], $e->getAlternatives());
  540. $this->assertMatchesRegularExpression(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
  541. $this->assertMatchesRegularExpression('/afoobar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "afoobar1"');
  542. $this->assertMatchesRegularExpression('/foo:bar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "foo:bar1"');
  543. $this->assertDoesNotMatchRegularExpression('/foo:bar(?!1)/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without "foo:bar" alternative');
  544. }
  545. }
  546. public function testFindAlternativeCommandsWithAnAlias()
  547. {
  548. $fooCommand = new \FooCommand();
  549. $fooCommand->setAliases(['foo2']);
  550. $application = new Application();
  551. $application->setCommandLoader(new FactoryCommandLoader([
  552. 'foo3' => static function () use ($fooCommand) { return $fooCommand; },
  553. ]));
  554. $application->add($fooCommand);
  555. $result = $application->find('foo');
  556. $this->assertSame($fooCommand, $result);
  557. }
  558. public function testFindAlternativeNamespace()
  559. {
  560. $application = new Application();
  561. $application->add(new \FooCommand());
  562. $application->add(new \Foo1Command());
  563. $application->add(new \Foo2Command());
  564. $application->add(new \Foo3Command());
  565. try {
  566. $application->find('Unknown-namespace:Unknown-command');
  567. $this->fail('->find() throws a CommandNotFoundException if namespace does not exist');
  568. } catch (\Exception $e) {
  569. $this->assertInstanceOf(CommandNotFoundException::class, $e, '->find() throws a CommandNotFoundException if namespace does not exist');
  570. $this->assertSame([], $e->getAlternatives());
  571. $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');
  572. }
  573. try {
  574. $application->find('foo2:command');
  575. $this->fail('->find() throws a CommandNotFoundException if namespace does not exist');
  576. } catch (\Exception $e) {
  577. $this->assertInstanceOf(NamespaceNotFoundException::class, $e, '->find() throws a NamespaceNotFoundException if namespace does not exist');
  578. $this->assertInstanceOf(CommandNotFoundException::class, $e, 'NamespaceNotFoundException extends from CommandNotFoundException');
  579. $this->assertCount(3, $e->getAlternatives());
  580. $this->assertContains('foo', $e->getAlternatives());
  581. $this->assertContains('foo1', $e->getAlternatives());
  582. $this->assertContains('foo3', $e->getAlternatives());
  583. $this->assertMatchesRegularExpression('/There are no commands defined in the "foo2" namespace./', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative');
  584. $this->assertMatchesRegularExpression('/foo/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo"');
  585. $this->assertMatchesRegularExpression('/foo1/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo1"');
  586. $this->assertMatchesRegularExpression('/foo3/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo3"');
  587. }
  588. }
  589. public function testFindAlternativesOutput()
  590. {
  591. $application = new Application();
  592. $application->add(new \FooCommand());
  593. $application->add(new \Foo1Command());
  594. $application->add(new \Foo2Command());
  595. $application->add(new \Foo3Command());
  596. $application->add(new \FooHiddenCommand());
  597. $expectedAlternatives = [
  598. 'afoobar',
  599. 'afoobar1',
  600. 'afoobar2',
  601. 'foo1:bar',
  602. 'foo3:bar',
  603. 'foo:bar',
  604. 'foo:bar1',
  605. ];
  606. try {
  607. $application->find('foo');
  608. $this->fail('->find() throws a CommandNotFoundException if command is not defined');
  609. } catch (\Exception $e) {
  610. $this->assertInstanceOf(CommandNotFoundException::class, $e, '->find() throws a CommandNotFoundException if command is not defined');
  611. $this->assertSame($expectedAlternatives, $e->getAlternatives());
  612. $this->assertMatchesRegularExpression('/Command "foo" is not defined\..*Did you mean one of these\?.*/Ums', $e->getMessage());
  613. }
  614. }
  615. public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces()
  616. {
  617. $application = $this->getMockBuilder(Application::class)->onlyMethods(['getNamespaces'])->getMock();
  618. $application->expects($this->once())
  619. ->method('getNamespaces')
  620. ->willReturn(['foo:sublong', 'bar:sub']);
  621. $this->assertEquals('foo:sublong', $application->findNamespace('f:sub'));
  622. }
  623. public function testFindWithDoubleColonInNameThrowsException()
  624. {
  625. $this->expectException(CommandNotFoundException::class);
  626. $this->expectExceptionMessage('Command "foo::bar" is not defined.');
  627. $application = new Application();
  628. $application->add(new \FooCommand());
  629. $application->add(new \Foo4Command());
  630. $application->find('foo::bar');
  631. }
  632. public function testFindHiddenWithExactName()
  633. {
  634. $application = new Application();
  635. $application->add(new \FooHiddenCommand());
  636. $this->assertInstanceOf(\FooHiddenCommand::class, $application->find('foo:hidden'));
  637. $this->assertInstanceOf(\FooHiddenCommand::class, $application->find('afoohidden'));
  638. }
  639. public function testFindAmbiguousCommandsIfAllAlternativesAreHidden()
  640. {
  641. $application = new Application();
  642. $application->add(new \FooCommand());
  643. $application->add(new \FooHiddenCommand());
  644. $this->assertInstanceOf(\FooCommand::class, $application->find('foo:'));
  645. }
  646. public function testSetCatchExceptions()
  647. {
  648. $application = new Application();
  649. $application->setAutoExit(false);
  650. putenv('COLUMNS=120');
  651. $tester = new ApplicationTester($application);
  652. $application->setCatchExceptions(true);
  653. $this->assertTrue($application->areExceptionsCaught());
  654. $tester->run(['command' => 'foo'], ['decorated' => false]);
  655. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag');
  656. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  657. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->setCatchExceptions() sets the catch exception flag');
  658. $this->assertSame('', $tester->getDisplay(true));
  659. $application->setCatchExceptions(false);
  660. try {
  661. $tester->run(['command' => 'foo'], ['decorated' => false]);
  662. $this->fail('->setCatchExceptions() sets the catch exception flag');
  663. } catch (\Exception $e) {
  664. $this->assertInstanceOf(\Exception::class, $e, '->setCatchExceptions() sets the catch exception flag');
  665. $this->assertEquals('Command "foo" is not defined.', $e->getMessage(), '->setCatchExceptions() sets the catch exception flag');
  666. }
  667. }
  668. public function testAutoExitSetting()
  669. {
  670. $application = new Application();
  671. $this->assertTrue($application->isAutoExitEnabled());
  672. $application->setAutoExit(false);
  673. $this->assertFalse($application->isAutoExitEnabled());
  674. }
  675. public function testRenderException()
  676. {
  677. $application = new Application();
  678. $application->setAutoExit(false);
  679. putenv('COLUMNS=120');
  680. $tester = new ApplicationTester($application);
  681. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  682. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exception');
  683. $tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true]);
  684. $this->assertStringContainsString('Exception trace', $tester->getErrorOutput(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose');
  685. $tester->run(['command' => 'list', '--foo' => true], ['decorated' => false, 'capture_stderr_separately' => true]);
  686. $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');
  687. $application->add(new \Foo3Command());
  688. $tester = new ApplicationTester($application);
  689. $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'capture_stderr_separately' => true]);
  690. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  691. $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]);
  692. $this->assertMatchesRegularExpression('/\[Exception\]\s*First exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is default and verbosity is verbose');
  693. $this->assertMatchesRegularExpression('/\[Exception\]\s*Second exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is 0 and verbosity is verbose');
  694. $this->assertMatchesRegularExpression('/\[Exception \(404\)\]\s*Third exception/', $tester->getDisplay(), '->renderException() renders a pretty exception with code exception when code exception is 404 and verbosity is verbose');
  695. $tester->run(['command' => 'foo3:bar'], ['decorated' => true]);
  696. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
  697. $tester->run(['command' => 'foo3:bar'], ['decorated' => true, 'capture_stderr_separately' => true]);
  698. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  699. $application = new Application();
  700. $application->setAutoExit(false);
  701. putenv('COLUMNS=32');
  702. $tester = new ApplicationTester($application);
  703. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  704. $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal');
  705. putenv('COLUMNS=120');
  706. }
  707. public function testRenderExceptionWithDoubleWidthCharacters()
  708. {
  709. $application = new Application();
  710. $application->setAutoExit(false);
  711. putenv('COLUMNS=120');
  712. $application->register('foo')->setCode(function () {
  713. throw new \Exception('エラーメッセージ');
  714. });
  715. $tester = new ApplicationTester($application);
  716. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  717. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  718. $tester->run(['command' => 'foo'], ['decorated' => true, 'capture_stderr_separately' => true]);
  719. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
  720. $application = new Application();
  721. $application->setAutoExit(false);
  722. putenv('COLUMNS=32');
  723. $application->register('foo')->setCode(function () {
  724. throw new \Exception('コマンドの実行中にエラーが発生しました。');
  725. });
  726. $tester = new ApplicationTester($application);
  727. $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
  728. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth2.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal');
  729. putenv('COLUMNS=120');
  730. }
  731. public function testRenderExceptionEscapesLines()
  732. {
  733. $application = new Application();
  734. $application->setAutoExit(false);
  735. putenv('COLUMNS=22');
  736. $application->register('foo')->setCode(function () {
  737. throw new \Exception('dont break here <info>!</info>');
  738. });
  739. $tester = new ApplicationTester($application);
  740. $tester->run(['command' => 'foo'], ['decorated' => false]);
  741. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_escapeslines.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting');
  742. putenv('COLUMNS=120');
  743. }
  744. public function testRenderExceptionLineBreaks()
  745. {
  746. $application = $this->getMockBuilder(Application::class)->addMethods(['getTerminalWidth'])->getMock();
  747. $application->setAutoExit(false);
  748. $application->expects($this->any())
  749. ->method('getTerminalWidth')
  750. ->willReturn(120);
  751. $application->register('foo')->setCode(function () {
  752. throw new \InvalidArgumentException("\n\nline 1 with extra spaces \nline 2\n\nline 4\n");
  753. });
  754. $tester = new ApplicationTester($application);
  755. $tester->run(['command' => 'foo'], ['decorated' => false]);
  756. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks');
  757. }
  758. /**
  759. * @group transient-on-windows
  760. */
  761. public function testRenderAnonymousException()
  762. {
  763. $application = new Application();
  764. $application->setAutoExit(false);
  765. $application->register('foo')->setCode(function () {
  766. throw new class('') extends \InvalidArgumentException { };
  767. });
  768. $tester = new ApplicationTester($application);
  769. $tester->run(['command' => 'foo'], ['decorated' => false]);
  770. $this->assertStringContainsString('[InvalidArgumentException@anonymous]', $tester->getDisplay(true));
  771. $application = new Application();
  772. $application->setAutoExit(false);
  773. $application->register('foo')->setCode(function () {
  774. throw new \InvalidArgumentException(sprintf('Dummy type "%s" is invalid.', \get_class(new class() { })));
  775. });
  776. $tester = new ApplicationTester($application);
  777. $tester->run(['command' => 'foo'], ['decorated' => false]);
  778. $this->assertStringContainsString('Dummy type "class@anonymous" is invalid.', $tester->getDisplay(true));
  779. }
  780. /**
  781. * @group transient-on-windows
  782. */
  783. public function testRenderExceptionStackTraceContainsRootException()
  784. {
  785. $application = new Application();
  786. $application->setAutoExit(false);
  787. $application->register('foo')->setCode(function () {
  788. throw new class('') extends \InvalidArgumentException { };
  789. });
  790. $tester = new ApplicationTester($application);
  791. $tester->run(['command' => 'foo'], ['decorated' => false]);
  792. $this->assertStringContainsString('[InvalidArgumentException@anonymous]', $tester->getDisplay(true));
  793. $application = new Application();
  794. $application->setAutoExit(false);
  795. $application->register('foo')->setCode(function () {
  796. throw new \InvalidArgumentException(sprintf('Dummy type "%s" is invalid.', \get_class(new class() { })));
  797. });
  798. $tester = new ApplicationTester($application);
  799. $tester->run(['command' => 'foo'], ['decorated' => false]);
  800. $this->assertStringContainsString('Dummy type "class@anonymous" is invalid.', $tester->getDisplay(true));
  801. }
  802. public function testRenderExceptionEscapesLinesOfSynopsis()
  803. {
  804. $application = new Application();
  805. $application->setAutoExit(false);
  806. $application
  807. ->register('foo')
  808. ->setCode(function () {
  809. throw new \Exception('some exception');
  810. })
  811. ->addArgument('info')
  812. ;
  813. $tester = new ApplicationTester($application);
  814. $tester->run(['command' => 'foo'], ['decorated' => false]);
  815. $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_rendersynopsis_escapesline.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting of synopsis');
  816. }
  817. public function testRun()
  818. {
  819. $application = new Application();
  820. $application->setAutoExit(false);
  821. $application->setCatchExceptions(false);
  822. $application->add($command = new \Foo1Command());
  823. $_SERVER['argv'] = ['cli.php', 'foo:bar1'];
  824. ob_start();
  825. $application->run();
  826. ob_end_clean();
  827. $this->assertInstanceOf(ArgvInput::class, $command->input, '->run() creates an ArgvInput by default if none is given');
  828. $this->assertInstanceOf(ConsoleOutput::class, $command->output, '->run() creates a ConsoleOutput by default if none is given');
  829. $application = new Application();
  830. $application->setAutoExit(false);
  831. $application->setCatchExceptions(false);
  832. $this->ensureStaticCommandHelp($application);
  833. $tester = new ApplicationTester($application);
  834. $tester->run([], ['decorated' => false]);
  835. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed');
  836. $tester->run(['--help' => true], ['decorated' => false]);
  837. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed');
  838. $tester->run(['-h' => true], ['decorated' => false]);
  839. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed');
  840. $tester->run(['command' => 'list', '--help' => true], ['decorated' => false]);
  841. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');
  842. $tester->run(['command' => 'list', '-h' => true], ['decorated' => false]);
  843. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');
  844. $tester->run(['--ansi' => true]);
  845. $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed');
  846. $tester->run(['--no-ansi' => true]);
  847. $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed');
  848. $tester->run(['--version' => true], ['decorated' => false]);
  849. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed');
  850. $tester->run(['-V' => true], ['decorated' => false]);
  851. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed');
  852. $tester->run(['command' => 'list', '--quiet' => true]);
  853. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed');
  854. $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if --quiet is passed');
  855. $tester->run(['command' => 'list', '-q' => true]);
  856. $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed');
  857. $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if -q is passed');
  858. $tester->run(['command' => 'list', '--verbose' => true]);
  859. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed');
  860. $tester->run(['command' => 'list', '--verbose' => 1]);
  861. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed');
  862. $tester->run(['command' => 'list', '--verbose' => 2]);
  863. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed');
  864. $tester->run(['command' => 'list', '--verbose' => 3]);
  865. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed');
  866. $tester->run(['command' => 'list', '--verbose' => 4]);
  867. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed');
  868. $tester->run(['command' => 'list', '-v' => true]);
  869. $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  870. $tester->run(['command' => 'list', '-vv' => true]);
  871. $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  872. $tester->run(['command' => 'list', '-vvv' => true]);
  873. $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
  874. $tester->run(['command' => 'help', '--help' => true], ['decorated' => false]);
  875. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run5.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');
  876. $tester->run(['command' => 'help', '-h' => true], ['decorated' => false]);
  877. $this->assertStringEqualsFile(self::$fixturesPath.'/application_run5.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');
  878. $application = new Application();
  879. $application->setAutoExit(false);
  880. $application->setCatchExceptions(false);
  881. $application->add(new \FooCommand());
  882. $tester = new ApplicationTester($application);
  883. $tester->run(['command' => 'foo:bar', '--no-interaction' => true], ['decorated' => false]);
  884. $this->assertSame('called'.\PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed');
  885. $tester->run(['command' => 'foo:bar', '-n' => true], ['decorated' => false]);
  886. $this->assertSame('called'.\PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed');
  887. }
  888. public function testRunWithGlobalOptionAndNoCommand()
  889. {
  890. $application = new Application();
  891. $application->setAutoExit(false);
  892. $application->setCatchExceptions(false);
  893. $application->getDefinition()->addOption(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL));
  894. $output = new StreamOutput(fopen('php://memory', 'w', false));
  895. $input = new ArgvInput(['cli.php', '--foo', 'bar']);
  896. $this->assertSame(0, $application->run($input, $output));
  897. }
  898. /**
  899. * Issue #9285.
  900. *
  901. * If the "verbose" option is just before an argument in ArgvInput,
  902. * an argument value should not be treated as verbosity value.
  903. * This test will fail with "Not enough arguments." if broken
  904. */
  905. public function testVerboseValueNotBreakArguments()
  906. {
  907. $application = new Application();
  908. $application->setAutoExit(false);
  909. $application->setCatchExceptions(false);
  910. $application->add(new \FooCommand());
  911. $output = new StreamOutput(fopen('php://memory', 'w', false));
  912. $input = new ArgvInput(['cli.php', '-v', 'foo:bar']);
  913. $application->run($input, $output);
  914. $this->addToAssertionCount(1);
  915. $input = new ArgvInput(['cli.php', '--verbose', 'foo:bar']);
  916. $application->run($input, $output);
  917. $this->addToAssertionCount(1);
  918. }
  919. public function testRunReturnsIntegerExitCode()
  920. {
  921. $exception = new \Exception('', 4);
  922. $application = $this->getMockBuilder(Application::class)->onlyMethods(['doRun'])->getMock();
  923. $application->setAutoExit(false);
  924. $application->expects($this->once())
  925. ->method('doRun')
  926. ->willThrowException($exception);
  927. $exitCode = $application->run(new ArrayInput([]), new NullOutput());
  928. $this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception');
  929. }
  930. public function testRunDispatchesIntegerExitCode()
  931. {
  932. $passedRightValue = false;
  933. // We can assume here that some other test asserts that the event is dispatched at all
  934. $dispatcher = new EventDispatcher();
  935. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) {
  936. $passedRightValue = (4 === $event->getExitCode());
  937. });
  938. $application = new Application();
  939. $application->setDispatcher($dispatcher);
  940. $application->setAutoExit(false);
  941. $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) {
  942. throw new \Exception('', 4);
  943. });
  944. $tester = new ApplicationTester($application);
  945. $tester->run(['command' => 'test']);
  946. $this->assertTrue($passedRightValue, '-> exit code 4 was passed in the console.terminate event');
  947. }
  948. public function testRunReturnsExitCodeOneForExceptionCodeZero()
  949. {
  950. $exception = new \Exception('', 0);
  951. $application = $this->getMockBuilder(Application::class)->onlyMethods(['doRun'])->getMock();
  952. $application->setAutoExit(false);
  953. $application->expects($this->once())
  954. ->method('doRun')
  955. ->willThrowException($exception);
  956. $exitCode = $application->run(new ArrayInput([]), new NullOutput());
  957. $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0');
  958. }
  959. public function testRunDispatchesExitCodeOneForExceptionCodeZero()
  960. {
  961. $passedRightValue = false;
  962. // We can assume here that some other test asserts that the event is dispatched at all
  963. $dispatcher = new EventDispatcher();
  964. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) {
  965. $passedRightValue = (1 === $event->getExitCode());
  966. });
  967. $application = new Application();
  968. $application->setDispatcher($dispatcher);
  969. $application->setAutoExit(false);
  970. $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) {
  971. throw new \Exception();
  972. });
  973. $tester = new ApplicationTester($application);
  974. $tester->run(['command' => 'test']);
  975. $this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event');
  976. }
  977. /**
  978. * @testWith [-1]
  979. * [-32000]
  980. */
  981. public function testRunReturnsExitCodeOneForNegativeExceptionCode($exceptionCode)
  982. {
  983. $exception = new \Exception('', $exceptionCode);
  984. $application = $this->getMockBuilder(Application::class)->onlyMethods(['doRun'])->getMock();
  985. $application->setAutoExit(false);
  986. $application->expects($this->once())
  987. ->method('doRun')
  988. ->willThrowException($exception);
  989. $exitCode = $application->run(new ArrayInput([]), new NullOutput());
  990. $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is '.$exceptionCode);
  991. }
  992. public function testAddingOptionWithDuplicateShortcut()
  993. {
  994. $this->expectException(\LogicException::class);
  995. $this->expectExceptionMessage('An option with shortcut "e" already exists.');
  996. $dispatcher = new EventDispatcher();
  997. $application = new Application();
  998. $application->setAutoExit(false);
  999. $application->setCatchExceptions(false);
  1000. $application->setDispatcher($dispatcher);
  1001. $application->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'Environment'));
  1002. $application
  1003. ->register('foo')
  1004. ->setAliases(['f'])
  1005. ->setDefinition([new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.')])
  1006. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  1007. ;
  1008. $input = new ArrayInput(['command' => 'foo']);
  1009. $output = new NullOutput();
  1010. $application->run($input, $output);
  1011. }
  1012. /**
  1013. * @dataProvider getAddingAlreadySetDefinitionElementData
  1014. */
  1015. public function testAddingAlreadySetDefinitionElementData($def)
  1016. {
  1017. $this->expectException(\LogicException::class);
  1018. $application = new Application();
  1019. $application->setAutoExit(false);
  1020. $application->setCatchExceptions(false);
  1021. $application
  1022. ->register('foo')
  1023. ->setDefinition([$def])
  1024. ->setCode(function (InputInterface $input, OutputInterface $output) {})
  1025. ;
  1026. $input = new ArrayInput(['command' => 'foo']);
  1027. $output = new NullOutput();
  1028. $application->run($input, $output);
  1029. }
  1030. public static function getAddingAlreadySetDefinitionElementData()
  1031. {
  1032. return [
  1033. [new InputArgument('command', InputArgument::REQUIRED)],
  1034. [new InputOption('quiet', '', InputOption::VALUE_NONE)],
  1035. [new InputOption('query', 'q', InputOption::VALUE_NONE)],
  1036. ];
  1037. }
  1038. public function testGetDefaultHelperSetReturnsDefaultValues()
  1039. {
  1040. $application = new Application();
  1041. $application->setAutoExit(false);
  1042. $application->setCatchExceptions(false);
  1043. $helperSet = $application->getHelperSet();
  1044. $this->assertTrue($helperSet->has('formatter'));
  1045. }
  1046. public function testAddingSingleHelperSetOverwritesDefaultValues()
  1047. {
  1048. $application = new Application();
  1049. $application->setAutoExit(false);
  1050. $application->setCatchExceptions(false);
  1051. $application->setHelperSet(new HelperSet([new FormatterHelper()]));
  1052. $helperSet = $application->getHelperSet();
  1053. $this->assertTrue($helperSet->has('formatter'));
  1054. // no other default helper set should be returned
  1055. $this->assertFalse($helperSet->has('dialog'));
  1056. $this->assertFalse($helperSet->has('progress'));
  1057. }
  1058. public function testOverwritingDefaultHelperSetOverwritesDefaultValues()
  1059. {
  1060. $application = new CustomApplication();
  1061. $application->setAutoExit(false);
  1062. $application->setCatchExceptions(false);
  1063. $application->setHelperSet(new HelperSet([new FormatterHelper()]));
  1064. $helperSet = $application->getHelperSet();
  1065. $this->assertTrue($helperSet->has('formatter'));
  1066. // no other default helper set should be returned
  1067. $this->assertFalse($helperSet->has('dialog'));
  1068. $this->assertFalse($helperSet->has('progress'));
  1069. }
  1070. public function testGetDefaultInputDefinitionReturnsDefaultValues()
  1071. {
  1072. $application = new Application();
  1073. $application->setAutoExit(false);
  1074. $application->setCatchExceptions(false);
  1075. $inputDefinition = $application->getDefinition();
  1076. $this->assertTrue($inputDefinition->hasArgument('command'));
  1077. $this->assertTrue($inputDefinition->hasOption('help'));
  1078. $this->assertTrue($inputDefinition->hasOption('quiet'));
  1079. $this->assertTrue($inputDefinition->hasOption('verbose'));
  1080. $this->assertTrue($inputDefinition->hasOption('version'));
  1081. $this->assertTrue($inputDefinition->hasOption('ansi'));
  1082. $this->assertTrue($inputDefinition->hasNegation('no-ansi'));
  1083. $this->assertFalse($inputDefinition->hasOption('no-ansi'));
  1084. $this->assertTrue($inputDefinition->hasOption('no-interaction'));
  1085. }
  1086. public function testOverwritingDefaultInputDefinitionOverwritesDefaultValues()
  1087. {
  1088. $application = new CustomApplication();
  1089. $application->setAutoExit(false);
  1090. $application->setCatchExceptions(false);
  1091. $inputDefinition = $application->getDefinition();
  1092. // check whether the default arguments and options are not returned any more
  1093. $this->assertFalse($inputDefinition->hasArgument('command'));
  1094. $this->assertFalse($inputDefinition->hasOption('help'));
  1095. $this->assertFalse($inputDefinition->hasOption('quiet'));
  1096. $this->assertFalse($inputDefinition->hasOption('verbose'));
  1097. $this->assertFalse($inputDefinition->hasOption('version'));
  1098. $this->assertFalse($inputDefinition->hasOption('ansi'));
  1099. $this->assertFalse($inputDefinition->hasNegation('no-ansi'));
  1100. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  1101. $this->assertTrue($inputDefinition->hasOption('custom'));
  1102. }
  1103. public function testSettingCustomInputDefinitionOverwritesDefaultValues()
  1104. {
  1105. $application = new Application();
  1106. $application->setAutoExit(false);
  1107. $application->setCatchExceptions(false);
  1108. $application->setDefinition(new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]));
  1109. $inputDefinition = $application->getDefinition();
  1110. // check whether the default arguments and options are not returned any more
  1111. $this->assertFalse($inputDefinition->hasArgument('command'));
  1112. $this->assertFalse($inputDefinition->hasOption('help'));
  1113. $this->assertFalse($inputDefinition->hasOption('quiet'));
  1114. $this->assertFalse($inputDefinition->hasOption('verbose'));
  1115. $this->assertFalse($inputDefinition->hasOption('version'));
  1116. $this->assertFalse($inputDefinition->hasOption('ansi'));
  1117. $this->assertFalse($inputDefinition->hasNegation('no-ansi'));
  1118. $this->assertFalse($inputDefinition->hasOption('no-interaction'));
  1119. $this->assertTrue($inputDefinition->hasOption('custom'));
  1120. }
  1121. public function testRunWithDispatcher()
  1122. {
  1123. $application = new Application();
  1124. $application->setAutoExit(false);
  1125. $application->setDispatcher($this->getDispatcher());
  1126. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1127. $output->write('foo.');
  1128. });
  1129. $tester = new ApplicationTester($application);
  1130. $tester->run(['command' => 'foo']);
  1131. $this->assertEquals('before.foo.after.'.\PHP_EOL, $tester->getDisplay());
  1132. }
  1133. public function testRunWithExceptionAndDispatcher()
  1134. {
  1135. $this->expectException(\LogicException::class);
  1136. $this->expectExceptionMessage('error');
  1137. $application = new Application();
  1138. $application->setDispatcher($this->getDispatcher());
  1139. $application->setAutoExit(false);
  1140. $application->setCatchExceptions(false);
  1141. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1142. throw new \RuntimeException('foo');
  1143. });
  1144. $tester = new ApplicationTester($application);
  1145. $tester->run(['command' => 'foo']);
  1146. }
  1147. public function testRunDispatchesAllEventsWithException()
  1148. {
  1149. $application = new Application();
  1150. $application->setDispatcher($this->getDispatcher());
  1151. $application->setAutoExit(false);
  1152. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1153. $output->write('foo.');
  1154. throw new \RuntimeException('foo');
  1155. });
  1156. $tester = new ApplicationTester($application);
  1157. $tester->run(['command' => 'foo']);
  1158. $this->assertStringContainsString('before.foo.error.after.', $tester->getDisplay());
  1159. }
  1160. public function testRunDispatchesAllEventsWithExceptionInListener()
  1161. {
  1162. $dispatcher = $this->getDispatcher();
  1163. $dispatcher->addListener('console.command', function () {
  1164. throw new \RuntimeException('foo');
  1165. });
  1166. $application = new Application();
  1167. $application->setDispatcher($dispatcher);
  1168. $application->setAutoExit(false);
  1169. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1170. $output->write('foo.');
  1171. });
  1172. $tester = new ApplicationTester($application);
  1173. $tester->run(['command' => 'foo']);
  1174. $this->assertStringContainsString('before.error.after.', $tester->getDisplay());
  1175. }
  1176. public function testRunWithError()
  1177. {
  1178. $application = new Application();
  1179. $application->setAutoExit(false);
  1180. $application->setCatchExceptions(false);
  1181. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1182. $output->write('dym.');
  1183. throw new \Error('dymerr');
  1184. });
  1185. $tester = new ApplicationTester($application);
  1186. try {
  1187. $tester->run(['command' => 'dym']);
  1188. $this->fail('Error expected.');
  1189. } catch (\Error $e) {
  1190. $this->assertSame('dymerr', $e->getMessage());
  1191. }
  1192. }
  1193. public function testRunAllowsErrorListenersToSilenceTheException()
  1194. {
  1195. $dispatcher = $this->getDispatcher();
  1196. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1197. $event->getOutput()->write('silenced.');
  1198. $event->setExitCode(0);
  1199. });
  1200. $dispatcher->addListener('console.command', function () {
  1201. throw new \RuntimeException('foo');
  1202. });
  1203. $application = new Application();
  1204. $application->setDispatcher($dispatcher);
  1205. $application->setAutoExit(false);
  1206. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1207. $output->write('foo.');
  1208. });
  1209. $tester = new ApplicationTester($application);
  1210. $tester->run(['command' => 'foo']);
  1211. $this->assertStringContainsString('before.error.silenced.after.', $tester->getDisplay());
  1212. $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $tester->getStatusCode());
  1213. }
  1214. public function testConsoleErrorEventIsTriggeredOnCommandNotFound()
  1215. {
  1216. $dispatcher = new EventDispatcher();
  1217. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1218. $this->assertNull($event->getCommand());
  1219. $this->assertInstanceOf(CommandNotFoundException::class, $event->getError());
  1220. $event->getOutput()->write('silenced command not found');
  1221. });
  1222. $application = new Application();
  1223. $application->setDispatcher($dispatcher);
  1224. $application->setAutoExit(false);
  1225. $tester = new ApplicationTester($application);
  1226. $tester->run(['command' => 'unknown']);
  1227. $this->assertStringContainsString('silenced command not found', $tester->getDisplay());
  1228. $this->assertEquals(1, $tester->getStatusCode());
  1229. }
  1230. public function testErrorIsRethrownIfNotHandledByConsoleErrorEvent()
  1231. {
  1232. $application = new Application();
  1233. $application->setAutoExit(false);
  1234. $application->setCatchExceptions(false);
  1235. $application->setDispatcher(new EventDispatcher());
  1236. $application->register('dym')->setCode(function () {
  1237. throw new \Error('Something went wrong.');
  1238. });
  1239. $tester = new ApplicationTester($application);
  1240. try {
  1241. $tester->run(['command' => 'dym']);
  1242. $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
  1243. } catch (\Error $e) {
  1244. $this->assertSame('Something went wrong.', $e->getMessage());
  1245. }
  1246. }
  1247. public function testRunWithErrorAndDispatcher()
  1248. {
  1249. $this->expectException(\LogicException::class);
  1250. $this->expectExceptionMessage('error');
  1251. $application = new Application();
  1252. $application->setDispatcher($this->getDispatcher());
  1253. $application->setAutoExit(false);
  1254. $application->setCatchExceptions(false);
  1255. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1256. $output->write('dym.');
  1257. throw new \Error('dymerr');
  1258. });
  1259. $tester = new ApplicationTester($application);
  1260. $tester->run(['command' => 'dym']);
  1261. $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP error did not dispatch events');
  1262. }
  1263. public function testRunDispatchesAllEventsWithError()
  1264. {
  1265. $application = new Application();
  1266. $application->setDispatcher($this->getDispatcher());
  1267. $application->setAutoExit(false);
  1268. $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) {
  1269. $output->write('dym.');
  1270. throw new \Error('dymerr');
  1271. });
  1272. $tester = new ApplicationTester($application);
  1273. $tester->run(['command' => 'dym']);
  1274. $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP error did not dispatch events');
  1275. }
  1276. public function testRunWithErrorFailingStatusCode()
  1277. {
  1278. $application = new Application();
  1279. $application->setDispatcher($this->getDispatcher());
  1280. $application->setAutoExit(false);
  1281. $application->register('dus')->setCode(function (InputInterface $input, OutputInterface $output) {
  1282. $output->write('dus.');
  1283. throw new \Error('duserr');
  1284. });
  1285. $tester = new ApplicationTester($application);
  1286. $tester->run(['command' => 'dus']);
  1287. $this->assertSame(1, $tester->getStatusCode(), 'Status code should be 1');
  1288. }
  1289. public function testRunWithDispatcherSkippingCommand()
  1290. {
  1291. $application = new Application();
  1292. $application->setDispatcher($this->getDispatcher(true));
  1293. $application->setAutoExit(false);
  1294. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1295. $output->write('foo.');
  1296. });
  1297. $tester = new ApplicationTester($application);
  1298. $exitCode = $tester->run(['command' => 'foo']);
  1299. $this->assertStringContainsString('before.after.', $tester->getDisplay());
  1300. $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode);
  1301. }
  1302. public function testRunWithDispatcherAccessingInputOptions()
  1303. {
  1304. $noInteractionValue = null;
  1305. $quietValue = null;
  1306. $dispatcher = $this->getDispatcher();
  1307. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$noInteractionValue, &$quietValue) {
  1308. $input = $event->getInput();
  1309. $noInteractionValue = $input->getOption('no-interaction');
  1310. $quietValue = $input->getOption('quiet');
  1311. });
  1312. $application = new Application();
  1313. $application->setDispatcher($dispatcher);
  1314. $application->setAutoExit(false);
  1315. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1316. $output->write('foo.');
  1317. });
  1318. $tester = new ApplicationTester($application);
  1319. $tester->run(['command' => 'foo', '--no-interaction' => true]);
  1320. $this->assertTrue($noInteractionValue);
  1321. $this->assertFalse($quietValue);
  1322. }
  1323. public function testRunWithDispatcherAddingInputOptions()
  1324. {
  1325. $extraValue = null;
  1326. $dispatcher = $this->getDispatcher();
  1327. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$extraValue) {
  1328. $definition = $event->getCommand()->getDefinition();
  1329. $input = $event->getInput();
  1330. $definition->addOption(new InputOption('extra', null, InputOption::VALUE_REQUIRED));
  1331. $input->bind($definition);
  1332. $extraValue = $input->getOption('extra');
  1333. });
  1334. $application = new Application();
  1335. $application->setDispatcher($dispatcher);
  1336. $application->setAutoExit(false);
  1337. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1338. $output->write('foo.');
  1339. });
  1340. $tester = new ApplicationTester($application);
  1341. $tester->run(['command' => 'foo', '--extra' => 'some test value']);
  1342. $this->assertEquals('some test value', $extraValue);
  1343. }
  1344. public function testSetRunCustomDefaultCommand()
  1345. {
  1346. $command = new \FooCommand();
  1347. $application = new Application();
  1348. $application->setAutoExit(false);
  1349. $application->add($command);
  1350. $application->setDefaultCommand($command->getName());
  1351. $tester = new ApplicationTester($application);
  1352. $tester->run([], ['interactive' => false]);
  1353. $this->assertEquals('called'.\PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1354. $application = new CustomDefaultCommandApplication();
  1355. $application->setAutoExit(false);
  1356. $tester = new ApplicationTester($application);
  1357. $tester->run([], ['interactive' => false]);
  1358. $this->assertEquals('called'.\PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1359. }
  1360. public function testSetRunCustomDefaultCommandWithOption()
  1361. {
  1362. $command = new \FooOptCommand();
  1363. $application = new Application();
  1364. $application->setAutoExit(false);
  1365. $application->add($command);
  1366. $application->setDefaultCommand($command->getName());
  1367. $tester = new ApplicationTester($application);
  1368. $tester->run(['--fooopt' => 'opt'], ['interactive' => false]);
  1369. $this->assertEquals('called'.\PHP_EOL.'opt'.\PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
  1370. }
  1371. public function testSetRunCustomSingleCommand()
  1372. {
  1373. $command = new \FooCommand();
  1374. $application = new Application();
  1375. $application->setAutoExit(false);
  1376. $application->add($command);
  1377. $application->setDefaultCommand($command->getName(), true);
  1378. $tester = new ApplicationTester($application);
  1379. $tester->run([]);
  1380. $this->assertStringContainsString('called', $tester->getDisplay());
  1381. $tester->run(['--help' => true]);
  1382. $this->assertStringContainsString('The foo:bar command', $tester->getDisplay());
  1383. }
  1384. public function testRunLazyCommandService()
  1385. {
  1386. $container = new ContainerBuilder();
  1387. $container->addCompilerPass(new AddConsoleCommandPass());
  1388. $container
  1389. ->register('lazy-command', LazyTestCommand::class)
  1390. ->addTag('console.command', ['command' => 'lazy:command'])
  1391. ->addTag('console.command', ['command' => 'lazy:alias'])
  1392. ->addTag('console.command', ['command' => 'lazy:alias2']);
  1393. $container->compile();
  1394. $application = new Application();
  1395. $application->setCommandLoader($container->get('console.command_loader'));
  1396. $application->setAutoExit(false);
  1397. $tester = new ApplicationTester($application);
  1398. $tester->run(['command' => 'lazy:command']);
  1399. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1400. $tester->run(['command' => 'lazy:alias']);
  1401. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1402. $tester->run(['command' => 'lazy:alias2']);
  1403. $this->assertSame("lazy-command called\n", $tester->getDisplay(true));
  1404. $command = $application->get('lazy:command');
  1405. $this->assertSame(['lazy:alias', 'lazy:alias2'], $command->getAliases());
  1406. }
  1407. public function testGetDisabledLazyCommand()
  1408. {
  1409. $this->expectException(CommandNotFoundException::class);
  1410. $application = new Application();
  1411. $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
  1412. $application->get('disabled');
  1413. }
  1414. public function testHasReturnsFalseForDisabledLazyCommand()
  1415. {
  1416. $application = new Application();
  1417. $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
  1418. $this->assertFalse($application->has('disabled'));
  1419. }
  1420. public function testAllExcludesDisabledLazyCommand()
  1421. {
  1422. $application = new Application();
  1423. $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
  1424. $this->assertArrayNotHasKey('disabled', $application->all());
  1425. }
  1426. public function testFindAlternativesDoesNotLoadSameNamespaceCommandsOnExactMatch()
  1427. {
  1428. $application = new Application();
  1429. $application->setAutoExit(false);
  1430. $loaded = [];
  1431. $application->setCommandLoader(new FactoryCommandLoader([
  1432. 'foo:bar' => function () use (&$loaded) {
  1433. $loaded['foo:bar'] = true;
  1434. return (new Command('foo:bar'))->setCode(function () {});
  1435. },
  1436. 'foo' => function () use (&$loaded) {
  1437. $loaded['foo'] = true;
  1438. return (new Command('foo'))->setCode(function () {});
  1439. },
  1440. ]));
  1441. $application->run(new ArrayInput(['command' => 'foo']), new NullOutput());
  1442. $this->assertSame(['foo' => true], $loaded);
  1443. }
  1444. protected function getDispatcher($skipCommand = false)
  1445. {
  1446. $dispatcher = new EventDispatcher();
  1447. $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use ($skipCommand) {
  1448. $event->getOutput()->write('before.');
  1449. if ($skipCommand) {
  1450. $event->disableCommand();
  1451. }
  1452. });
  1453. $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use ($skipCommand) {
  1454. $event->getOutput()->writeln('after.');
  1455. if (!$skipCommand) {
  1456. $event->setExitCode(ConsoleCommandEvent::RETURN_CODE_DISABLED);
  1457. }
  1458. });
  1459. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1460. $event->getOutput()->write('error.');
  1461. $event->setError(new \LogicException('error.', $event->getExitCode(), $event->getError()));
  1462. });
  1463. return $dispatcher;
  1464. }
  1465. public function testErrorIsRethrownIfNotHandledByConsoleErrorEventWithCatchingEnabled()
  1466. {
  1467. $application = new Application();
  1468. $application->setAutoExit(false);
  1469. $application->setDispatcher(new EventDispatcher());
  1470. $application->register('dym')->setCode(function () {
  1471. throw new \Error('Something went wrong.');
  1472. });
  1473. $tester = new ApplicationTester($application);
  1474. try {
  1475. $tester->run(['command' => 'dym']);
  1476. $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
  1477. } catch (\Error $e) {
  1478. $this->assertSame('Something went wrong.', $e->getMessage());
  1479. }
  1480. }
  1481. public function testThrowingErrorListener()
  1482. {
  1483. $this->expectException(\RuntimeException::class);
  1484. $this->expectExceptionMessage('foo');
  1485. $dispatcher = $this->getDispatcher();
  1486. $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) {
  1487. throw new \RuntimeException('foo');
  1488. });
  1489. $dispatcher->addListener('console.command', function () {
  1490. throw new \RuntimeException('bar');
  1491. });
  1492. $application = new Application();
  1493. $application->setDispatcher($dispatcher);
  1494. $application->setAutoExit(false);
  1495. $application->setCatchExceptions(false);
  1496. $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
  1497. $output->write('foo.');
  1498. });
  1499. $tester = new ApplicationTester($application);
  1500. $tester->run(['command' => 'foo']);
  1501. }
  1502. public function testCommandNameMismatchWithCommandLoaderKeyThrows()
  1503. {
  1504. $this->expectException(CommandNotFoundException::class);
  1505. $this->expectExceptionMessage('The "test" command cannot be found because it is registered under multiple names. Make sure you don\'t set a different name via constructor or "setName()".');
  1506. $app = new Application();
  1507. $loader = new FactoryCommandLoader([
  1508. 'test' => static function () { return new Command('test-command'); },
  1509. ]);
  1510. $app->setCommandLoader($loader);
  1511. $app->get('test');
  1512. }
  1513. /**
  1514. * @requires extension pcntl
  1515. */
  1516. public function testSignalListenerNotCalledByDefault()
  1517. {
  1518. $command = new SignableCommand(false);
  1519. $dispatcherCalled = false;
  1520. $dispatcher = new EventDispatcher();
  1521. $dispatcher->addListener('console.signal', function () use (&$dispatcherCalled) {
  1522. $dispatcherCalled = true;
  1523. });
  1524. $application = $this->createSignalableApplication($command, $dispatcher);
  1525. $this->assertSame(0, $application->run(new ArrayInput(['signal'])));
  1526. $this->assertFalse($command->signaled);
  1527. $this->assertFalse($dispatcherCalled);
  1528. }
  1529. /**
  1530. * @requires extension pcntl
  1531. */
  1532. public function testSignalListener()
  1533. {
  1534. $command = new SignableCommand();
  1535. $dispatcherCalled = false;
  1536. $dispatcher = new EventDispatcher();
  1537. $dispatcher->addListener('console.signal', function () use (&$dispatcherCalled) {
  1538. $dispatcherCalled = true;
  1539. });
  1540. $application = $this->createSignalableApplication($command, $dispatcher);
  1541. $this->assertSame(1, $application->run(new ArrayInput(['signal'])));
  1542. $this->assertTrue($dispatcherCalled);
  1543. $this->assertTrue($command->signaled);
  1544. }
  1545. /**
  1546. * @requires extension pcntl
  1547. */
  1548. public function testSignalSubscriberNotCalledByDefault()
  1549. {
  1550. $command = new BaseSignableCommand(false);
  1551. $subscriber = new SignalEventSubscriber();
  1552. $dispatcher = new EventDispatcher();
  1553. $dispatcher->addSubscriber($subscriber);
  1554. $application = $this->createSignalableApplication($command, $dispatcher);
  1555. $this->assertSame(0, $application->run(new ArrayInput(['signal'])));
  1556. $this->assertFalse($subscriber->signaled);
  1557. }
  1558. /**
  1559. * @requires extension pcntl
  1560. */
  1561. public function testSignalSubscriber()
  1562. {
  1563. $command = new BaseSignableCommand();
  1564. $subscriber1 = new SignalEventSubscriber();
  1565. $subscriber2 = new SignalEventSubscriber();
  1566. $dispatcher = new EventDispatcher();
  1567. $dispatcher->addSubscriber($subscriber1);
  1568. $dispatcher->addSubscriber($subscriber2);
  1569. $application = $this->createSignalableApplication($command, $dispatcher);
  1570. $this->assertSame(1, $application->run(new ArrayInput(['signal'])));
  1571. $this->assertTrue($subscriber1->signaled);
  1572. $this->assertTrue($subscriber2->signaled);
  1573. }
  1574. /**
  1575. * @requires extension pcntl
  1576. */
  1577. public function testSetSignalsToDispatchEvent()
  1578. {
  1579. if (!\defined('SIGUSR1')) {
  1580. $this->markTestSkipped('SIGUSR1 not available');
  1581. }
  1582. $command = new BaseSignableCommand();
  1583. $subscriber = new SignalEventSubscriber();
  1584. $dispatcher = new EventDispatcher();
  1585. $dispatcher->addSubscriber($subscriber);
  1586. // Since there is no signal handler, and by default PHP will stop even
  1587. // on SIGUSR1, we need to register a blank handler to avoid the process
  1588. // being stopped.
  1589. $blankHandlerSignaled = false;
  1590. pcntl_signal(\SIGUSR1, function () use (&$blankHandlerSignaled) {
  1591. $blankHandlerSignaled = true;
  1592. });
  1593. $application = $this->createSignalableApplication($command, $dispatcher);
  1594. $application->setSignalsToDispatchEvent(\SIGUSR2);
  1595. $this->assertSame(0, $application->run(new ArrayInput(['signal'])));
  1596. $this->assertFalse($subscriber->signaled);
  1597. $this->assertTrue($blankHandlerSignaled);
  1598. // We reset the blank handler to false to make sure it is called again
  1599. $blankHandlerSignaled = false;
  1600. $application = $this->createSignalableApplication($command, $dispatcher);
  1601. $application->setSignalsToDispatchEvent(\SIGUSR1);
  1602. $this->assertSame(1, $application->run(new ArrayInput(['signal'])));
  1603. $this->assertTrue($subscriber->signaled);
  1604. $this->assertTrue($blankHandlerSignaled);
  1605. // And now we test without the blank handler
  1606. $blankHandlerSignaled = false;
  1607. pcntl_signal(\SIGUSR1, SIG_DFL);
  1608. $application = $this->createSignalableApplication($command, $dispatcher);
  1609. $application->setSignalsToDispatchEvent(\SIGUSR1);
  1610. $this->assertSame(1, $application->run(new ArrayInput(['signal'])));
  1611. $this->assertTrue($subscriber->signaled);
  1612. $this->assertFalse($blankHandlerSignaled);
  1613. }
  1614. public function testSignalableCommandInterfaceWithoutSignals()
  1615. {
  1616. if (!\defined('SIGUSR1')) {
  1617. $this->markTestSkipped('SIGUSR1 not available');
  1618. }
  1619. $command = new SignableCommand(false);
  1620. $dispatcher = new EventDispatcher();
  1621. $application = new Application();
  1622. $application->setAutoExit(false);
  1623. $application->setDispatcher($dispatcher);
  1624. $application->add($command);
  1625. $this->assertSame(0, $application->run(new ArrayInput(['signal'])));
  1626. }
  1627. public function testSignalableCommandHandlerCalledAfterEventListener()
  1628. {
  1629. if (!\defined('SIGUSR1')) {
  1630. $this->markTestSkipped('SIGUSR1 not available');
  1631. }
  1632. $command = new SignableCommand();
  1633. $subscriber = new SignalEventSubscriber();
  1634. $dispatcher = new EventDispatcher();
  1635. $dispatcher->addSubscriber($subscriber);
  1636. $application = $this->createSignalableApplication($command, $dispatcher);
  1637. $application->setSignalsToDispatchEvent(\SIGUSR1);
  1638. $this->assertSame(1, $application->run(new ArrayInput(['signal'])));
  1639. $this->assertSame([SignalEventSubscriber::class, SignableCommand::class], $command->signalHandlers);
  1640. }
  1641. /**
  1642. * @group tty
  1643. */
  1644. public function testSignalableRestoresStty()
  1645. {
  1646. if (!Terminal::hasSttyAvailable()) {
  1647. $this->markTestSkipped('stty not available');
  1648. }
  1649. if (!SignalRegistry::isSupported()) {
  1650. $this->markTestSkipped('pcntl signals not available');
  1651. }
  1652. $previousSttyMode = shell_exec('stty -g');
  1653. $p = new Process(['php', __DIR__.'/Fixtures/application_signalable.php']);
  1654. $p->setTty(true);
  1655. $p->start();
  1656. for ($i = 0; $i < 10 && shell_exec('stty -g') === $previousSttyMode; ++$i) {
  1657. usleep(100000);
  1658. }
  1659. $this->assertNotSame($previousSttyMode, shell_exec('stty -g'));
  1660. $p->signal(\SIGINT);
  1661. $p->wait();
  1662. $sttyMode = shell_exec('stty -g');
  1663. shell_exec('stty '.$previousSttyMode);
  1664. $this->assertSame($previousSttyMode, $sttyMode);
  1665. }
  1666. private function createSignalableApplication(Command $command, ?EventDispatcherInterface $dispatcher): Application
  1667. {
  1668. $application = new Application();
  1669. $application->setAutoExit(false);
  1670. if ($dispatcher) {
  1671. $application->setDispatcher($dispatcher);
  1672. }
  1673. $application->add(new LazyCommand('signal', [], '', false, function () use ($command) { return $command; }, true));
  1674. return $application;
  1675. }
  1676. }
  1677. class CustomApplication extends Application
  1678. {
  1679. /**
  1680. * Overwrites the default input definition.
  1681. */
  1682. protected function getDefaultInputDefinition(): InputDefinition
  1683. {
  1684. return new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]);
  1685. }
  1686. /**
  1687. * Gets the default helper set with the helpers that should always be available.
  1688. */
  1689. protected function getDefaultHelperSet(): HelperSet
  1690. {
  1691. return new HelperSet([new FormatterHelper()]);
  1692. }
  1693. }
  1694. class CustomDefaultCommandApplication extends Application
  1695. {
  1696. /**
  1697. * Overwrites the constructor in order to set a different default command.
  1698. */
  1699. public function __construct()
  1700. {
  1701. parent::__construct();
  1702. $command = new \FooCommand();
  1703. $this->add($command);
  1704. $this->setDefaultCommand($command->getName());
  1705. }
  1706. }
  1707. class LazyTestCommand extends Command
  1708. {
  1709. public function execute(InputInterface $input, OutputInterface $output): int
  1710. {
  1711. $output->writeln('lazy-command called');
  1712. return 0;
  1713. }
  1714. }
  1715. class DisabledCommand extends Command
  1716. {
  1717. public function isEnabled(): bool
  1718. {
  1719. return false;
  1720. }
  1721. }
  1722. class BaseSignableCommand extends Command
  1723. {
  1724. public $signaled = false;
  1725. public $signalHandlers = [];
  1726. public $loop = 1000;
  1727. private $emitsSignal;
  1728. protected static $defaultName = 'signal';
  1729. public function __construct(bool $emitsSignal = true)
  1730. {
  1731. parent::__construct();
  1732. $this->emitsSignal = $emitsSignal;
  1733. }
  1734. protected function execute(InputInterface $input, OutputInterface $output): int
  1735. {
  1736. if ($this->emitsSignal) {
  1737. posix_kill(posix_getpid(), \SIGUSR1);
  1738. }
  1739. for ($i = 0; $i < $this->loop; ++$i) {
  1740. usleep(100);
  1741. if ($this->signaled) {
  1742. return 1;
  1743. }
  1744. }
  1745. return 0;
  1746. }
  1747. }
  1748. class SignableCommand extends BaseSignableCommand implements SignalableCommandInterface
  1749. {
  1750. protected static $defaultName = 'signal';
  1751. public function getSubscribedSignals(): array
  1752. {
  1753. return SignalRegistry::isSupported() ? [\SIGUSR1] : [];
  1754. }
  1755. public function handleSignal(int $signal): void
  1756. {
  1757. $this->signaled = true;
  1758. $this->signalHandlers[] = __CLASS__;
  1759. }
  1760. }
  1761. class SignalEventSubscriber implements EventSubscriberInterface
  1762. {
  1763. public $signaled = false;
  1764. public function onSignal(ConsoleSignalEvent $event): void
  1765. {
  1766. $this->signaled = true;
  1767. $event->getCommand()->signaled = true;
  1768. $event->getCommand()->signalHandlers[] = __CLASS__;
  1769. }
  1770. public static function getSubscribedEvents(): array
  1771. {
  1772. return ['console.signal' => 'onSignal'];
  1773. }
  1774. }