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