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