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