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