php-framework-benchmark /slim/tests/SlimTest.php

Language PHP Lines 1759
MD5 Hash 6eee421e580c9e23f982da04e181d1bc Estimated Cost $21,598 (why?)
Repository git://github.com/eryx/php-framework-benchmark.git View Raw File
   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
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
<?php
/**
 * Slim - a micro PHP 5 framework
 *
 * @author      Josh Lockhart <info@joshlockhart.com>
 * @copyright   2011 Josh Lockhart
 * @link        http://www.slimframework.com
 * @license     http://www.slimframework.com/license
 * @version     1.5.0
 *
 * MIT LICENSE
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

set_include_path(dirname(__FILE__) . '/../' . PATH_SEPARATOR . get_include_path());

//Start session before PHPUnit sends output. This only prevents us from using
//the default Slim Session cookie store.
session_start();

require_once 'Slim/Slim.php';

//Prepare mock HTTP request
$_SERVER['REDIRECT_STATUS'] = "200";
$_SERVER['HTTP_HOST'] = "slim";
$_SERVER['HTTP_CONNECTION'] = "keep-alive";
$_SERVER['HTTP_CACHE_CONTROL'] = "max-age=0";
$_SERVER['HTTP_ACCEPT'] = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$_SERVER['HTTP_USER_AGENT'] = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3";
$_SERVER['HTTP_ACCEPT_ENCODING'] = "gzip,deflate,sdch";
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = "en-US,en;q=0.8";
$_SERVER['HTTP_ACCEPT_CHARSET'] = "ISO-8859-1,utf-8;q=0.7,*;q=0.3";
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = "Sun, 03 Oct 2010 17:00:52 -0400";
$_SERVER['HTTP_IF_NONE_MATCH'] = '"abc123"';
$_SERVER['HTTP_COOKIE'] = 'foo=bar; foo2=bar2';
$_SERVER['PATH'] = "/usr/bin:/bin:/usr/sbin:/sbin";
$_SERVER['SERVER_SIGNATURE'] = "";
$_SERVER['SERVER_SOFTWARE'] = "Apache";
$_SERVER['SERVER_NAME'] = "slim";
$_SERVER['SERVER_ADDR'] = "127.0.0.1";
$_SERVER['SERVER_PORT'] = "80";
$_SERVER['REMOTE_ADDR'] = "127.0.0.1";
$_SERVER['DOCUMENT_ROOT'] = '/home/account/public';
$_SERVER['SERVER_ADMIN'] = "you@example.com";
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
$_SERVER['REMOTE_PORT'] = "55426";
$_SERVER['REDIRECT_URL'] = "/";
$_SERVER['GATEWAY_INTERFACE'] = "CGI/1.1";
$_SERVER['SERVER_PROTOCOL'] = "HTTP/1.1";
$_SERVER['REQUEST_METHOD'] = "GET";
$_SERVER['QUERY_STRING'] = "";
$_SERVER['REQUEST_URI'] = "/";
$_SERVER['SCRIPT_NAME'] = '/bootstrap.php';
$_SERVER['PHP_SELF'] = '/bootstrap.php';
$_SERVER['REQUEST_TIME'] = "1285647051";
$_SERVER['argv'] = array();
$_SERVER['argc'] = 0;

//Register non-Slim autoloader
function customAutoLoader( $class ) {
    $file = rtrim(dirname(__FILE__), '/') . '/' . $class . '.php';
    if ( file_exists($file) ) {
        require $file;
    } else {
        return;
    }
}
spl_autoload_register('customAutoLoader');

//Mock custom view
class CustomView extends Slim_View {
    function render($template) { echo "Custom view"; }
}

//Mock custom Logger
class CustomLogger{
    public function debug( $var ) {
        print_r($var);
    }
    public function info( $var ) {
        print_r($var);
    }
    public function warn( $var ) {
        print_r($var);
    }
    public function error( $var ) {
        print_r($var);
    }
    public function fatal( $var ) {
        print_r($var);
    }
}

class SlimTest extends PHPUnit_Extensions_OutputTestCase {

    public function setUp() {
        $_SERVER['REQUEST_METHOD'] = "GET";
        $_ENV['SLIM_MODE'] = null;
        $_COOKIE['foo'] = 'bar';
        $_COOKIE['foo2'] = 'bar2';
        $_SERVER['REQUEST_URI'] = "/";
    }

    /************************************************
     * SLIM INITIALIZATION
     ************************************************/

    /**
     * Test Slim default View
     *
     * Pre-conditions:
     * Slim app instantiated with default View;
     *
     * Post-conditions:
     * Slim app has default View of class Slim_View;
     */
    public function testSlimDefaultView() {
        $app = new Slim();
        $this->assertTrue($app->view() instanceof Slim_View);
    }

    /**
     * Test Slim custom View
     *
     * Pre-conditions:
     * Case A: Slim app instantiated with View setting as string;
     * Case B: Slim app instantiated with View as instance;
     *
     * Post-conditions:
     * Case A: View is instance of CustomView
     * Case B: View is instance of CustomView
     */
    public function testSlimInitWithCustomView(){
        //Case A
        $app1 = new Slim(array('view' => 'CustomView'));
        $this->assertTrue($app1->view() instanceof CustomView);
        //Case B
        $app2 = new Slim(array('view' => new CustomView()));
        $this->assertTrue($app2->view() instanceOf CustomView);
    }

    /**
     * Test Slim default Logger
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Logging enabled;
     * Default Logger used;
     *
     * Post-conditions:
     * Slim app has default Logger of class Slim_Logger;
     */
    public function testSlimInitWithDefaultLogger() {
        $app = new Slim(array(
            'log.path' => dirname(__FILE__) . '/logs',
            'log.enable' => true
        ));
        $this->assertTrue($app->getLog()->getLogger() instanceof Slim_Logger);
    }

    /**
     * Test Slim custom Logger
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Logging enabled;
     * Custom Logger used;
     *
     * Post-conditions:
     * Slim app has custom Logger of class CustomLogger;
     */
    public function testSlimInitWithCustomLogger() {
        $app = new Slim(array(
            'log.enable' => true,
            'log.logger' => new CustomLogger()
        ));
        $this->assertTrue($app->getLog()->getLogger() instanceof CustomLogger);
    }

    /**
     * Test Slim autoloader ignores non-Slim classes
     *
     * Pre-conditions:
     * Instantiate a non-Slim class;
     *
     * Post-conditions:
     * Slim autoloader returns without requiring a class file;
     */
    public function testSlimAutoloaderIgnoresNonSlimClass() {
        $foo = new Foo();
    }

    /**
     * Test Slim get instance
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Set app name;
     *
     * Post-conditions:
     * A default app exists;
     * The instantiated app is returned by the name assigned to it;
     */
    public function testGetInstance() {
        $app = new Slim();
        $app->setName('foo');
        $this->assertTrue(Slim::getInstance() instanceof Slim);
        $this->assertEquals('foo', $app->getName());
        $this->assertSame($app, Slim::getInstance('foo'));
    }

    /**
     * Test Slim does not affect default Response HTTP status
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Case A: Use default settings;
     * Case B: Set to "1.0";
     *
     * Post-conditions:
     * Case A: Response HTTP version is "1.1";
     * Case B: Response HTTP version is "1.0";
     */
    public function testSlimSetsResponseHttpVersion() {
        $app1 = new Slim();
        $app2 = new Slim(array(
            'http.version' => '1.0'
        ));
        $this->assertEquals('1.1', $app1->response()->httpVersion());
        $this->assertEquals('1.0', $app2->response()->httpVersion());
    }

    /************************************************
     * SLIM SETTINGS
     ************************************************/

    /**
     * Test Slim mode with ENV[SLIM_MODE]
     *
     * Pre-conditions:
     * SLIM_MODE environment variable set;
     * Slim app instantiated with config mode;
     *
     * Post-conditions:
     * Only the production configuration is called;
     */
    public function testSlimModeEnvironment() {
        $this->expectOutputString('production mode');
        $_ENV['SLIM_MODE'] = 'production';
        $app = new Slim(array(
            'mode' => 'test'
        ));
        $app->configureMode('test', function () {
            echo "test mode";
        });
        $app->configureMode('production', function () {
            echo "production mode";
        });
    }

    /**
     * Test Slim mode with Config
     *
     * Pre-conditions:
     * ENV[SLIM_MODE] not set;
     * Slim app instantiated with config mode;
     *
     * Post-conditions:
     * Only the test configuration is called;
     */
    public function testSlimModeConfig() {
        $this->expectOutputString('test mode');
        $app = new Slim(array(
            'mode' => 'test'
        ));
        $app->configureMode('test', function () {
            echo "test mode";
        });
        $app->configureMode('production', function () {
            echo "production mode";
        });
    }

    /**
     * Test Slim mode with default
     *
     * Pre-conditions:
     * ENV[SLIM_MODE] not set;
     * Slim app instantiated without config mode;
     *
     * Post-conditions:
     * Only the development configuration is called;
     */
    public function testSlimModeDefault() {
        $this->expectOutputString('dev mode');
        $app = new Slim();
        $app->configureMode('development', function () {
            echo "dev mode";
        });
        $app->configureMode('production', function () {
            echo "production mode";
        });
    }

    /**
     * Test Slim Logging for given mode
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Set custom Logger for current app mode;
     *
     * Post-conditions:
     * Slim app Logger correct based on mode;
     */
    public function testSlimLoggerInMode() {
        $app = new Slim(array(
            'mode' => 'test'
        ));
        $app->configureMode('test', function () use ($app) {
            $app->config(array(
                'log.enable' => true,
                'log.logger' => new CustomLogger()
            ));
        });
        $app->configureMode('development', function () use ($app) {
            $app->config(array(
                'log.enable' => true
            ));
        });
        $this->assertTrue($app->getLog()->getLogger() instanceof CustomLogger);
    }

    /**
     * Test Slim defines one application setting
     *
     * Pre-conditions:
     * Slim app instantiated;
     * One configuration setting is set;
     *
     * Post-conditions:
     * Configuration setting `foo` === `bar`;
     */
    public function testSlimConfigSetsOneSetting(){
        $app = new Slim();
        $app->config('foo', 'bar');
        $this->assertEquals('bar', $app->config('foo'));
    }

    /**
     * Test Slim setting is NULL if non-existant
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Fetch non-existing configuration setting;
     *
     * Post-conditions:
     * NULL is returned for the value of the setting;
     */
    public function testSlimConfigIfSettingDoesNotExist(){
        $app = new Slim();
        $this->assertNull($app->config('foo'));
    }

    /**
     * Test Slim defines multiple settings with array
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Batch-define multiple configuration settings with associative array;
     *
     * Post-conditions:
     * Multiple settings are set correctly;
     */
    public function testSlimCongfigurationWithArray(){
        $app = new Slim();
        $app->config(array(
            'one' => 'A',
            'two' => 'B',
            'three' => 'C'
        ));
        $this->assertEquals('A', $app->config('one'));
        $this->assertEquals('B', $app->config('two'));
        $this->assertEquals('C', $app->config('three'));
    }

    /************************************************
     * SLIM ROUTING
     ************************************************/

    /**
     * Test Slim GET route
     *
     * Pre-conditions:
     * Slim app instantiated;
     * One GET route defined;
     *
     * Post-conditions:
     * The GET route is returned;
     * The GET route's pattern and callable are set correctly;
     */
    public function testSlimGetRoute(){
        $app = new Slim();
        $callable = function () { echo "foo"; };
        $route = $app->get('/foo/bar', $callable);
        $this->assertEquals('/foo/bar', $route->getPattern());
        $this->assertSame($callable, $route->getCallable());
    }

    /**
     * Test Slim GET route with middleware
     *
     * Pre-conditions:
     * Slim app instantiated and run;
     * One GET route defined with middleware;
     *
     * Post-conditions:
     * The GET route and its middleware are invoked in sequence;
     */
    public function testSlimGetRouteWithMiddleware(){ 
        $app = new Slim();
        $mw1 = function () { echo "foo"; };
        $mw2 = function () { echo "bar"; };
        $callable = function () { echo "foo"; };
        $app->get('/', $mw1, $mw2, $callable);
        $this->expectOutputString('foobarfoo');
        $app->run();
    }

    /**
     * Test Slim sets POST route
     *
     * Pre-conditions:
     * Slim app instantiated;
     * One POST route defined;
     *
     * Post-conditions:
     * The POST route is returned;
     * The POST route's pattern and callable are set correctly;
     */
    public function testSlimPostRoute(){
        $app = new Slim();
        $callable = function () { echo "foo"; };
        $route = $app->post('/foo/bar', $callable);
        $this->assertEquals('/foo/bar', $route->getPattern());
        $this->assertSame($callable, $route->getCallable());
    }

    /**
     * Test Slim POST route with middleware
     *
     * Pre-conditions:
     * Slim app instantiated and run;
     * One POST route defined with middleware;
     *
     * Post-conditions:
     * The POST route and its middleware are invoked in sequence;
     */
    public function testSlimPostRouteWithMiddleware(){ 
        $_SERVER['REQUEST_METHOD'] = 'POST';
        $app = new Slim();
        $mw1 = function () { echo "foo"; };
        $mw2 = function () { echo "bar"; };
        $callable = function () { echo "foo"; };
        $route = $app->post('/', $mw1, $mw2, $callable);
        $this->expectOutputString('foobarfoo');
        $app->run();
    }

    /**
     * Test Slim sets PUT route
     *
     * Pre-conditions:
     * Slim app instantiated;
     * One PUT request defined;
     *
     * Post-conditions:
     * The PUT route is returned;
     * The PUT route's pattern and callable are set correctly;
     */
    public function testSlimPutRoute(){
        $app = new Slim();
        $callable = function () { echo "foo"; };
        $route = $app->put('/foo/bar', $callable);
        $this->assertEquals('/foo/bar', $route->getPattern());
        $this->assertSame($callable, $route->getCallable());
    }

    /**
     * Test Slim PUT route with middleware
     *
     * Pre-conditions:
     * Slim app instantiated and run;
     * One PUT request defined with middleware;
     *
     * Post-conditions:
     * The PUT route and its middleware are invoked in sequence;
     */
    public function testSlimPutRouteWithMiddleware(){ 
        $_SERVER['REQUEST_METHOD'] = 'PUT';
        $app = new Slim();
        $mw1 = function () { echo "foo"; };
        $mw2 = function () { echo "bar"; };
        $callable = function () { echo "foo"; };
        $route = $app->put('/', $mw1, $mw2, $callable);
        $this->expectOutputString('foobarfoo');
        $app->run();
    }

    /**
     * Test Slim sets DELETE route
     *
     * Pre-conditions:
     * Slim app instantiated;
     * One DELETE route defined;
     *
     * Post-conditions:
     * The DELETE route is returned;
     * The DELETE route's pattern and callable are set correctly;
     */
    public function testSlimDeleteRoute(){
        $app = new Slim();
        $callable = function () { echo "foo"; };
        $route = $app->delete('/foo/bar', $callable);
        $this->assertEquals('/foo/bar', $route->getPattern());
        $this->assertSame($callable, $route->getCallable());
    }

    /**
     * Test Slim DELETE route with middleware
     *
     * Pre-conditions:
     * Slim app instatiated and run;
     * One DELETE route defined with middleware;
     *
     * Post-conditions:
     * The DELETE route and its middleware are invoked in sequence;
     */
    public function testSlimDeleteRouteWithMiddleware(){ 
        $_SERVER['REQUEST_METHOD'] = 'DELETE';
        $app = new Slim();
        $mw1 = function () { echo "foo"; };
        $mw2 = function () { echo "bar"; };
        $callable = function () { echo "foo"; };
        $route = $app->delete('/', $mw1, $mw2, $callable);
        $this->expectOutputString('foobarfoo');
        $app->run();
    }
    
    /**
     * Test Slim sets DELETE route
     *
     * Pre-conditions:
     * Slim app instantiated;
     * One OPTIONS route defined;
     *
     * Post-conditions:
     * The OPTIONS route is returned;
     * The OPTIONS route's pattern and callable are set correctly;
     */
    public function testSlimOptionsRoute(){
        $app = new Slim();
        $callable = function () { echo "foo"; };
        $route = $app->options('/foo/bar', $callable);
        $this->assertEquals('/foo/bar', $route->getPattern());
        $this->assertSame($callable, $route->getCallable());
    }

    /**
     * Test Slim DELETE route with middleware
     *
     * Pre-conditions:
     * Slim app instatiated and run;
     * One OPTIONS route defined with middleware;
     *
     * Post-conditions:
     * The OPTIONS route and its middleware are invoked in sequence;
     */
    public function testSlimOptionsRouteWithMiddleware(){ 
        $_SERVER['REQUEST_METHOD'] = 'OPTIONS';
        $app = new Slim();
        $mw1 = function () { echo "foo"; };
        $mw2 = function () { echo "bar"; };
        $callable = function () { echo "foo"; };
        $route = $app->options('/', $mw1, $mw2, $callable);
        $this->expectOutputString('foobarfoo');
        $app->run();
    }

    /**
     * Test Slim routing and trailing slashes
     *
     * Pre-conditions:
     * A route is defined that expects a trailing slash, but
     * the resource URI does not have a trailing slash - but
     * otherwise matches the route pattern.
     *
     * Post-conditions:
     * Slim will send a 301 redirect response to the same
     * resource URI but with a trailing slash.
     */
    public function testRouteWithSlashAndUrlWithout() {
        $_SERVER['REQUEST_URI'] = '/foo/bar/bob';
        $app = new Slim();
        $app->get('/foo/bar/:name/', function ($name) {});
        $app->run();
        $this->assertEquals(301, $app->response()->status());
        $this->assertEquals('/foo/bar/bob/', $app->response()->header('Location'));
    }

    /**
     * Test Slim routing and trailing slashes
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Route defined that matches current HTTP request;
     * Route does NOT expect trailing slash;
     * HTTP request DOES have trailing slash;
     *
     * Post-conditions:
     * Slim response status is 404;
     */
    public function testRouteWithoutSlashAndUrlWith() {
        $_SERVER['REQUEST_URI'] = '/foo/bar/bob/';
        $app = new Slim();
        $app->get('/foo/bar/:name', function ($name) {});
        $app->run();
        $this->assertEquals(404, $app->response()->status());
    }

    /**
     * Test Slim routing with URL encoded characters
     *
     * Pre-conditions:
     * Slim initialized;
     * Route defined and matches current request;
     * URL encoded spaces in URL;
     *
     * Post-conditions:
     * Route matched;
     * Route callable invoked;
     * Route callable arguments are URL decoded;
     */
    public function testRouteWithUrlEncodedParameters() {
        $_SERVER['REQUEST_URI'] = '/foo/jo%20hn/smi%20th';
        $app = new Slim();
        $app->get('/foo/:one/:two', function ($one, $two) {
            echo "$one and $two";
        });
        $app->run();
        $this->expectOutputString('jo hn and smi th');
    }

    /************************************************
     * SLIM ACCESSORS
     ************************************************/

    public function testSlimAccessors() {
        $app = new Slim();
        $this->assertTrue($app->request() instanceof Slim_Http_Request);
        $this->assertTrue($app->response() instanceof Slim_Http_Response);
        $this->assertTrue($app->router() instanceof Slim_Router);
    }

    /************************************************
     * SLIM VIEW
     ************************************************/

    /**
     * Test Slim copies data from old View to new View
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Data set in default View;
     * New View is defined;
     *
     * Post-conditions:
     * The data from the original View is accessible in the new View;
     */
    public function testSlimCopiesViewData(){
        $data = array('foo' => 'bar');
        $app = new Slim();
        $app->view()->setData($data);
        $this->assertTrue($app->view() instanceof Slim_View);
        $this->assertEquals($data, $app->view()->getData());
        $app->view('CustomView');
        $this->assertTrue($app->view() instanceof CustomView);
        $this->assertEquals($data, $app->view()->getData());
    }

    /************************************************
     * SLIM RENDERING
     ************************************************/

    /**
     * Test Slim rendering with custom status
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Render an existing template with custom data and status;
     *
     * Post-conditions:
     * The response status is 404;
     * The response body is correct;
     */
    public function testSlimRenderSetsResponseStatusOk(){
        $this->expectOutputString('test output bar');
        $app = new Slim(array(
            'templates.path' => null,
            'templates_dir' => dirname(__FILE__) . '/templates'
        ));
        $app->render('test.php', array('foo' => 'bar'), 404);
        $this->assertEquals(404, $app->response()->status());
    }

    /**
     * Test Slim rendering
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Render an existing template with custom data;
     *
     * Post-conditions:
     * The response body is correct;
     */
    public function testSlimRender(){
        $this->expectOutputString('test output bar');
        $app = new Slim(array(
            'templates.path' => dirname(__FILE__) . '/templates'
        ));
        $app->render('test.php', array('foo' => 'bar'));
    }

    /************************************************
     * SLIM HTTP CACHING
     ************************************************/

    /**
     * Test Slim HTTP caching if ETag match
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Define route that matches current HTTP request;
     * Route sets ETag header, matches request's `If-None-Match` header;
     *
     * Post-conditions:
     * Slim app response status is 304;
     */
    public function testSlimEtagMatches(){
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->etag('abc123');
        });
        $app->run();
        $this->assertEquals(304, $app->response()->status());
    }

    /**
     * Test Slim HTTP caching if ETag does not match
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Define route that matches current HTTP request;
     * Route sets ETag header, does not match request's `If-None-Match` header;
     *
     * Post-conditions:
     * Slim app response status is 200;
     */
    public function testSlimEtagDoesNotMatch(){
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->etag('xyz789');
        });
        $app->run();
        $this->assertEquals(200, $app->response()->status());
    }

    /**
     * Test Slim::etag only accepts 'strong' or 'weak' types
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Define route that matches current HTTP request;
     * Route sets ETag header with an invalid argument;
     *
     * Post-conditions:
     * Slim app response status is 500;
     */
    public function testSlimETagThrowsExceptionForInvalidType(){
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->etag('123','foo');
        });
        $app->run();
        $this->assertEquals(500, $app->response()->status());
    }

    /**
     * Test Slim HTTP caching with Last Modified match
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Define route that matches current HTTP request;
     * Route correctly sets a Last-Modified header;
     *
     * Post-conditions:
     * Slim app response status is 304 Not Modified;
     */
    public function testSlimLastModifiedDateMatches(){
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->lastModified(1286139652);
        });
        $app->run();
        $this->assertEquals(304, $app->response()->status());
    }

    /**
     * Test Slim HTTP caching if Last Modified does not match
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Define route that matches current HTTP request;
     * Route sets `Last-Modified` header;
     * The HTTP `If-Modified-Since` header does not match the `Last-Modified` date;
     *
     * Post-conditions:
     * Slim app response status is 200;
     */
    public function testSlimLastModifiedDateDoesNotMatch(){
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->lastModified(1286139250);
        });
        $app->run();
        $this->assertEquals(200, $app->response()->status());
    }

    /**
     * Test Slim Last Modified only accepts integer values
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Define route that matches current HTTP request;
     * Route sets LastModified header value incorrectly;
     *
     * Post-conditions:
     * Slim app response status is 500;
     */
    public function testSlimLastModifiedOnlyAcceptsIntegers(){
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->lastModified('Test');
        });
        $app->run();
        $this->assertEquals(500, $app->response()->status());
    }

    /************************************************
     * SLIM COOKIES
     ************************************************/

    /**
     * Test Slim gets cookie
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Case A: Cookie `foo` exists, available in HTTP request;
     * Case B: Cookie `bad` does not exist;
     *
     * Post-conditions:
     * Case A: Cookie `foo` value is "bar";
     * Case B: Cooke `bad` value is NULL;
     */
    public function testSlimGetsCookie() {
        $app = new Slim();
        //Case A
        $this->assertEquals('bar', $app->getCookie('foo'));
        //Case B
        $this->assertNull($app->getCookie('doesNotExist'));
    }

    /**
     * Test Slim sets cookie with default time
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Case A: Cookie time not set;
     * Case B: Cookie time set as seconds from now (integer);
     * Case C: Cookie time set as string;
     * Case D: Cookie time is set to 0;
     *
     * Post-conditions:
     * Cookie available in response;
     * Case A: Cookie time set using default value;
     * Case C: Cookie time set using `strtotime()`;
     * Case D: Cookie time is 0;
     */
    public function testSlimSetsCookie() {
        $app = new Slim();
        $cj = $app->response()->getCookieJar();
        //Case A
        $timeA = time();
        $app->setCookie('myCookie1', 'myValue1');
        $cookieA = $cj->getResponseCookie('myCookie1');
        $this->assertEquals('myCookie1', $cookieA->getName());
        $this->assertEquals('myValue1', $cookieA->getValue());
        $this->assertEquals($timeA + 1200, $cookieA->getExpires()); //default duration is 20 minutes
        $this->assertEquals('/', $cookieA->getPath());
        $this->assertEquals('', $cookieA->getDomain());
        $this->assertFalse($cookieA->getSecure());
        $this->assertFalse($cookieA->getHttpOnly());
        //Case C
        $timeC = time();
        $app->setCookie('myCookie3', 'myValue3', '1 hour');
        $cookieC = $cj->getResponseCookie('myCookie3');
        $this->assertEquals($timeC + 3600, $cookieC->getExpires());
        //Case D
        $timeD = time();
        $app->setCookie('myCookie4', 'myValue4', 0);
        $cookieD = $cj->getResponseCookie('myCookie4');
        $this->assertEquals(0, $cookieD->getExpires());
    }

    /**
     * Test Slim sets encrypted cookie
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Case A: Cookie time not set;
     * Case B: Cookie time set as seconds from now (integer);
     * Case C: Cookie time set as string;
     * Case D: Cookie time is set to 0;
     *
     * Post-conditions:
     * Cookie available in response;
     * Case A: Cookie time set using default value;
     * Case C: Cookie time set using `strtotime()`;
     * Case D: Cookie time is 0;
     */
    public function testSlimSetsEncryptedCookie() {
        $app = new Slim();
        $cj = $app->response()->getCookieJar();
        //Case A
        $timeA = time();
        $app->setEncryptedCookie('myCookie1', 'myValue1');
        $cookieA = $cj->getResponseCookie('myCookie1');
        $this->assertEquals('myCookie1', $cookieA->getName());
        $this->assertEquals($timeA + 1200, $cookieA->getExpires()); //default duration is 20 minutes
        $this->assertEquals('/', $cookieA->getPath());
        $this->assertEquals('', $cookieA->getDomain());
        $this->assertFalse($cookieA->getSecure());
        $this->assertFalse($cookieA->getHttpOnly());
        //Case C
        $timeC = time();
        $app->setEncryptedCookie('myCookie3', 'myValue3', '1 hour');
        $cookieC = $cj->getResponseCookie('myCookie3');
        $this->assertEquals($timeC + 3600, $cookieC->getExpires());
        //Case D
        $timeD = time();
        $app->setEncryptedCookie('myCookie4', 'myValue4', 0);
        $cookieD = $cj->getResponseCookie('myCookie4');
        $this->assertEquals(0, $cookieD->getExpires());
    }

    /**
     * Test Slim deletes cookies
     *
     * Pre-conditions:
     * Case A: Classic cookie
     * Case B: Encrypted cookie
     *
     * Post-conditions:
     * Response Cookies replaced with empty, auto-expiring Cookies
     */
    public function testSlimDeletesCookies() {
        $app = new Slim();
        $cj = $app->response()->getCookieJar();
        //Case A
        $app->setCookie('foo1', 'bar1');
        $this->assertEquals('bar1', $cj->getResponseCookie('foo1')->getValue());
        $this->assertTrue($cj->getResponseCookie('foo1')->getExpires() > time());
        $app->deleteCookie('foo1');
        $this->assertEquals('', $app->getCookie('foo1'));
        $this->assertTrue($cj->getResponseCookie('foo1')->getExpires() < time());
        //Case B
        $app->setEncryptedCookie('foo2', 'bar2');
        $this->assertTrue(strlen($cj->getResponseCookie('foo2')->getValue()) > 0);
        $this->assertTrue($cj->getResponseCookie('foo2')->getExpires() > time());
        $app->deleteCookie('foo2');
        $this->assertEquals('', $cj->getResponseCookie('foo2')->getValue());
        $this->assertTrue($cj->getResponseCookie('foo2')->getExpires() < time());
    }

    /************************************************
     * SLIM HELPERS
     ************************************************/

    /**
     * Test Slim Root
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Slim app installed in document root directory;
     *
     * Post-conditions:
     * Slim correctly reports root path;
     */
    public function testRootPathInBaseDirectory() {
        $rootPath = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/';
        $app = new Slim();
        $this->assertEquals($rootPath, $app->root());
    }

    /**
     * Test Slim Root From Subdirectory
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Slim app installed in a physical, public subdirectory of document root;
     *
     * Post-conditions:
     * Slim correctly reports root path;
     */
    public function testRootPathInSubDirectory() {
        $_SERVER['REQUEST_URI'] = '/foo/bar';
        $_SERVER['SCRIPT_NAME'] = '/foo/bootstrap.php';
        $_SERVER['PHP_SELF'] = '/foo/bootstrap.php';
        $rootPath = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/foo/';
        $app = new Slim();
        $this->assertEquals($rootPath, $app->root());
    }

    /**
     * Test Slim Stop
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Slim app stopped while route invocation in process;
     *
     * Post-conditions:
     * Slim ignores output after `stop()` is invoked;
     */
    public function testSlimStop() {
        $app = new Slim();
        $app->get('/', function () use ($app) {
            try {
                echo "foo";
                $app->stop();
                echo "bar";
            } catch ( Slim_Exception_Stop $e ) {}
        });
        $app->run();
        $this->assertEquals('foo', $app->response()->body());
    }

    /**
     * Test Slim Halt inside route callback
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Define route that matches current HTTP request;
     * Halt app from within invoked route;
     *
     * Post-conditions:
     * Slim app response status is 404;
     * Slim app response body is 'Halt not found';
     */
    public function testSlimHaltInsideCallback() {
        $app = new Slim();
        $app->get('/', function () use ($app) {
            echo 'foo';
            $app->halt(404, 'Halt not found');
            echo 'bar';
        });
        $app->run();
        $this->assertEquals(404, $app->response()->status());
        $this->assertEquals('Halt not found', $app->response()->body());
    }

    /**
     * Test Slim Halt outside route callback
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Slim::halt is invoked outside of a route callback;
     *
     * Post-conditions:
     * The new response should be returned with the expected
     * status code and body, regardless of the current route
     * callback's expected output.
     */
    public function testSlimHaltOutsideCallback() {
        $this->setExpectedException('Slim_Exception_Stop');
        $app = new Slim();
        $app->halt(500, 'External error');
        $app->get('/', function () {
            echo "foo";
        });
        $app->run();
        $this->assertEquals(500, $app->response()->status());
        $this->assertEquals('External error', $app->response()->body());
    }

    /**
     * Test Slim Pass continues to next matching route
     *
     * Pre-conditions:
     * Slim app instantiated with two routes;
     * First route is most specific, invokes `pass()`;
     * Second route is next matching route;
     *
     * Post-conditions:
     * The response body is set by the second matching route;
     */
    public function testSlimPassWithFallbackRoute() {
        $_SERVER['REQUEST_URI'] = "/name/Frank";
        $app = new Slim();
        $app->get('/name/Frank', function () use ($app) {
            echo "Your name is Frank";
            $app->pass();
        });
        $app->get('/name/:name', function ($name) {
            echo "I think your name is $name";
        });
        $app->run();
        $this->assertEquals('I think your name is Frank', $app->response()->body());
    }

    /**
     * Test Slim Pass continues, but next matching route not found
     *
     * Pre-conditions:
     * Slim app initiated;
     * Define route that matches current HTTP request;
     * Route passes;
     * No subsequent routes available;
     *
     * Post-conditions:
     * Slim app response status is 404;
     */
    public function testSlimPassWithoutFallbackRoute() {
        $_SERVER['REQUEST_URI'] = '/name/Frank';
        $app = new Slim();
        $app->get('/name/Frank', function () use ($app) {
            echo 'Your name is Frank';
            $app->pass();
        });
        $app->run();
        $this->assertEquals(404, $app->response()->status());
    }

    /**
     * Test Slim::contentType
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Content-Type header is set using helper method;
     *
     * Post-conditions:
     * The Response content type header is set correctly;
     */
    public function testSlimContentType(){
        $app = new Slim();
        $app->contentType('image/jpeg');
        $this->assertEquals('image/jpeg', $app->response()->header('Content-Type'));
    }

    /**
     * Test Slim::status
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Case A: Valid HTTP status is set using helper method;
     * Case B: Invalid HTTP status is set using helper method;
     *
     * Post-conditions:
     * Case A: The Response status code is set correctly;
     * Case B: InvalidArgumentException is thrown;
     */
    public function testSlimStatus(){
        $app1 = new Slim();
        //Case A
        $app1->status(302);
        $this->assertSame($app1->response()->status(), 302);
        //Case B
        $this->setExpectedException('InvalidArgumentException');
        $app2 = new Slim();
        $app2->status(900);
    }

    /**
     * Test Slim URL For
     *
     * Pre-conditions:
     * Slim app instantiatd with named route;
     *
     * Post-conditions:
     * Slim returns an accurate URL for the named route;
     */
    public function testSlimUrlFor(){
        $app = new Slim();
        $app->get('/hello/:name', function () {})->name('hello');
        $this->assertEquals('/hello/Josh', $app->urlFor('hello', array('name' => 'Josh')));
    }

    /**
     * Test Slim::redirect
     *
     * Pre-conditions:
     * Case A: Status code is less than 300
     * Case B: Status code is greater than 307
     * Case C: Status code is 300
     * Case D: Status code is 302 (between 300 and 307)
     * Case E: Status code is 307
     *
     * Post-conditions:
     * Case A: Response code is 500 (due to invalid redirect status)
     * Case B: Response code is 500 (due to invalid redirect status)
     * Case C: Response code is 300
     * Case D: Response code is 302
     * Case E: Response code is 307
     */
    public function testSlimRedirect() {
        //Case A
        $app1 = new Slim();
        $app1->get('/', function () use ($app1) {
            $app1->redirect('/foo', 200);
        });
        ob_start();
        $app1->run();
        $app1Out = ob_get_clean();
        $this->assertEquals(500, $app1->response()->status());

        //Case B
        $app2 = new Slim();
        $app2->get('/', function () use ($app2) {
            $app2->redirect('/foo', 308);
        });
        ob_start();
        $app2->run();
        $app2Out = ob_get_clean();
        $this->assertEquals(500, $app2->response()->status());

        //Case C
        $app3 = new Slim();
        $app3->get('/', function () use ($app3) {
            $app3->redirect('/foo', 300);
        });
        $app3->run();
        $this->assertEquals(300, $app3->response()->status());

        //Case D
        $app4 = new Slim();
        $app4->get('/', function () use ($app4) {
            $app4->redirect('/foo', 302);
        });
        $app4->run();
        $this->assertEquals(302, $app4->response()->status());

        //Case E
        $app5 = new Slim();
        $app5->get('/', function () use ($app5) {
            $app5->redirect('/foo', 307);
        });
        $app5->run();
        $this->assertEquals(307, $app5->response()->status());
    }

    /************************************************
     * SLIM FLASH MESSAGING
     ************************************************/

    /**
     * Slim Flash
     *
     * Pre-conditions:
     * Slim app sets Flash message for next request;
     *
     * Post-conditions:
     * Message is persisted to $_SESSION after app is run;
     */
    public function testSlimFlash() {
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->flash('info', 'Foo');
        });
        $app->run();
        $this->assertArrayHasKey('info', $_SESSION['flash']);
        $this->assertEquals('Foo', $_SESSION['flash']['info']);
    }

    /**
     * Slim Flash with Redirect
     *
     * Pre-conditions:
     * Slim app sets Flash message for next request;
     * Slim app halts with 302 redirect
     *
     * Post-conditions:
     * Message is persisted to $_SESSION after app is run;
     */
    public function testSlimFlashWithRedirect() {
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->flash('info', 'Foo redirect');
            $app->redirect('/foo');
        });
        $app->run();
        $this->assertArrayHasKey('info', $_SESSION['flash']);
        $this->assertEquals('Foo redirect', $_SESSION['flash']['info']);
    }

    /**
     * Slim Flash Now
     *
     * Pre-conditions:
     * Slim app sets Flash message for current request;
     *
     * Post-conditions:
     * Message is persisted to View data;
     */
    public function testSlimFlashNow() {
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->flashNow('info', 'Foo');
        });
        $app->run();
        $flash = $app->view()->getData('flash');
        $this->assertEquals('Foo', $flash['info']);
    }

    /**
     * Slim Keep Flash
     *
     * Pre-conditions:
     * Slim app receives existing Flash message from $_SESSION;
     *
     * Post-conditions:
     * Message is re-persisted to $_SESSION after app is run;
     */
    public function testSlimFlashKeep() {
        $_SESSION['flash'] = array('info' => 'Foo');
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->flashKeep();
        });
        $app->run();
        $this->assertArrayHasKey('info', $_SESSION['flash']);
        $this->assertEquals('Foo', $_SESSION['flash']['info']);
    }

    /************************************************
     * SLIM ERROR AND EXCEPTION HANDLING
     ************************************************/

    /**
     * Test default and custom error handlers
     *
     * Pre-conditions:
     * Invoked app route calls default error handler;
     *
     * Post-conditions:
     * Response status code is 500;
     */
    public function testSlimError() {
        $app = new Slim();
        $app->get('/', function () use ($app) {
            $app->error();
        });
        $app->run();
        $this->assertEquals(500, $app->response()->status());
    }

    /**
     * Test triggered errors are converted to ErrorExceptions
     *
     * Pre-conditions:
     * Custom error handler defined;
     * Invoked app route triggers error;
     *
     * Post-conditions:
     * Response status is 500;
     * Response body is equal to triggered error message;
     * Error handler's argument is ErrorException instance;
     */
    public function testTriggeredErrorsAreConvertedToErrorExceptions() {
        $app = new Slim(array(
            'debug' => false
        ));
        $app->error(function ( $e ) {
            if ( $e instanceof ErrorException ) {
                echo $e->getMessage();
            }
        });
        $app->get('/', function () {
            trigger_error('Foo I say!');
        });
        $app->run();
        $this->assertEquals('Foo I say!', $app->response()->body());
        $this->assertEquals(500, $app->response()->status());
    }

    /**
     * Test error handler receives Exception as argument
     *
     * Pre-conditions:
     * Custom error handler defined;
     * Invoked app route throws Exception;
     *
     * Post-conditions:
     * Response status is 500;
     * Error handler's argument is the thrown Exception
     */
    public function testErrorHandlerReceivesException() {
        $this->expectOutputString('ErrorException');
        $app = new Slim(array(
            'debug' => false
        ));
        $app->error(function ( $e ) {
            if ( $e instanceof Exception ) {
                echo get_class($e);
            }
        });
        $app->get('/', function () {
            $result = 1 / 0;
        });
        $app->run();
        $this->assertEquals(500, $app->response()->status());
    }

    /**
     * Test error triggered with multiple applications
     *
     * Pre-conditions:
     * Multiple Slim apps are instantiated;
     * Both apps are run;
     * One app returns 200 OK;
     * One app triggers an error;
     *
     * Post-conditions:
     * One app returns 200 OK with no Exceptions;
     * One app returns 500 Error;
     * Error triggered does not affect other app;
     */
    public function testErrorWithMultipleApps() {
        $app1 = new Slim();
        $app2 = new Slim();
        $app1->get('/', function () {
            trigger_error('error');
        });
        $app2->get('/', function () {
            echo 'success';
        });
        $app1->run();
        $app2->run();
        $this->assertEquals(500, $app1->response()->status());
        $this->assertEquals(200, $app2->response()->status());
    }

    /**
     * Test Slim Not Found handler
     *
     * Pre-conditions:
     * Initialize one Slim app without custom Not Found handler;
     * Initialize one Slim app with custom Not Found Handler;
     * Both app's routes do not match HTTP request;
     *
     * Post-conditions:
     * Both Slim apps' response status is 404;
     * Custom Not Found handler is invoked if specified;
     */
    public function testSlimRouteNotFound() {
        $app1 = new Slim();
        $app1->get('/foo', function () {});
        ob_start();
        $app1->run();
        $app1Out = ob_get_clean();
        $app2 = new Slim();
        $app2->notFound(function () {
            echo 'Not Found';
        });
        $app2->get('/bar', function () {});
        ob_start();
        $app2->run();
        $app2Out = ob_get_clean();
        $this->assertEquals(404, $app1->response()->status());
        $this->assertEquals(404, $app2->response()->status());
        $this->assertEquals('Not Found', $app2->response()->body());
    }

    /**
     * Test Slim app without errors
     *
     * Pre-conditions:
     * Slim app does not have Errors and Exceptions;
     *
     * Post-conditions:
     * Slim app response status is 200;
     */
    public function testSlimOkResponse() {
        $app = new Slim();
        $app->get('/', function () {
            echo 'Ok';
        });
        $app->run();
        $this->assertEquals(200, $app->response()->status());
        $this->assertEquals('Ok', $app->response()->body());
    }

    /************************************************
     * SLIM HOOKS
     ************************************************/

    /**
     * Test hook listener
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Hook name does not exist;
     * Listeners are callable objects;
     *
     * Post-conditions:
     * Callables are invoked in expected order;
     */
    public function testRegistersAndCallsHooksByPriority() {
        $this->expectOutputString('barfoo');
        $app = new Slim();
        $callable1 = function () { echo "foo"; };
        $callable2 = function () { echo "bar"; };
        $app->hook('test.hook.one', $callable1); //default is 10
        $app->hook('test.hook.one', $callable2, 8);
        $hooks = $app->getHooks();
        $this->assertEquals(7, count($hooks)); //6 default, 1 custom
        $app->applyHook('test.hook.one');
    }

    /**
     * Test hook listener if listener is not callable
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Hook name does not exist;
     * Listener is NOT a callable object;
     *
     * Post-conditions:
     * Hook is created;
     * Callable is NOT assigned to hook;
     */
    public function testHookInvalidCallable() {
        $app = new Slim();
        $callable = 'test'; //NOT callable
        $app->hook('test.hook.one', $callable);
        $this->assertEquals(array(array()), $app->getHooks('test.hook.one'));
    }

    /**
     * Test hook invocation if hook does not exist
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Hook name does not exist;
     *
     * Post-conditions:
     * Hook is created;
     * Hook initialized with empty array;
     */
    public function testHookInvocationIfNotExists() {
        $app = new Slim();
        $app->applyHook('test.hook.one');
        $this->assertEquals(array(array()), $app->getHooks('test.hook.one'));
    }

    /**
     * Test clear hooks
     *
     * Pre-conditions:
     * Slim app instantiated;
     * Two hooks exist, each with one listener;
     *
     * Post-conditions:
     * Case A: Listeners for 'test.hook.one' are cleared;
     * Case B: Listeners for all hooks are cleared;
     */
    public function testHookClear() {
        $app = new Slim();
        $app->hook('test.hook.one', function () {});
        $app->hook('test.hook.two', function () {});
        $app->clearHooks('test.hook.two');
        $this->assertEquals(array(array()), $app->getHooks('test.hook.two'));
        $hookOne = $app->getHooks('test.hook.one');
        $this->assertTrue(count($hookOne[10]) === 1);
        $app->clearHooks();
        $this->assertEquals(array(array()), $app->getHooks('test.hook.one'));
    }

    /**
     * Test hook filter behavior
     */
    public function testHookFilterBehavior() {
        $app = new Slim();
        $app->hook('test.hook', function ($arg) { return $arg . 'foo'; });
        $this->assertEquals('barfoo', $app->applyHook('test.hook', 'bar'));
    }

    /************************************************
     * SLIM RUN LOOP
     ************************************************/

    /**
     * Test that a route returns 200 OK response when the route is
     * manually assigned multiple HTTP methods
     */
    public function testMatchingRouteWithMultipleMethods() {
        $_SERVER['REQUEST_URI'] = "/foo";
        $_SERVER['REQUEST_METHOD'] = 'POST';
        $app = new Slim();
        $app->map('/foo', function () {
            echo "Foo!";
        })->via('GET', 'POST');
        $app->run();
        $this->assertEquals(200, $app->response()->status());
        $this->assertEquals('Foo!', $app->response()->body());
    }

    /**
     * Test that a route returns 200 OK response when a prior matching
     * route was not invoked because it did not support HTTP request method.
     */
    public function testMatchingRoutesThatSupportDifferentMethods() {
        $_SERVER['REQUEST_URI'] = "/foo";
        $_SERVER['REQUEST_METHOD'] = 'POST';
        $app = new Slim();
        //GET route
        $app->map('/foo', function () {
            echo "Foo GET";
        })->via('GET');
        //POST route
        $app->map('/foo', function () {
            echo "Foo POST";
        })->via('POST');
        $app->run();
        $this->assertEquals(200, $app->response()->status());
        $this->assertEquals('Foo POST', $app->response()->body());
    }
    
    /**
     * Test that app returns 405 response when matching routes
     * are round but do not support the HTTP request method. Ensure the 
     * response's Allow header is also set and aggregates all matching
     * routes' supported methods into the response header.
     */
    public function testMatchingRoutesThatDoNotSupportRequestMethod() {
        $_SERVER['REQUEST_URI'] = "/foo";
        $_SERVER['REQUEST_METHOD'] = 'DELETE';
        $app = new Slim();
        //GET route
        $app->map('/foo', function () {
            echo "Foo GET";
        })->via('GET');
        //POST and PUT route
        $app->map('/foo', function () {
            echo "Foo POST and PUT";
        })->via('POST', 'PUT');
        $app->run();
        $this->assertEquals(405, $app->response()->status());
        $this->assertEquals('GET POST PUT', $app->response()->header('Allow'));
    }

    /**
     * Test that app returns 405 response when matched, invoked route calls
     * $app->pass(); the subsequent matching route does not support the current
     * HTTP request method.
     */
    public function testInvokedRoutePassesToAnotherRouteThatDoesNotSupportMethod() {
        $_SERVER['REQUEST_URI'] = "/foo";
        $_SERVER['REQUEST_METHOD'] = 'GET';
        $app = new Slim();
        //GET route
        $app->map('/foo', function () use ($app) {
            $app->pass();
            echo "Foo GET";
        })->via('GET');
        //POST and PUT route
        $app->map('/foo', function () {
            echo "Foo POST";
        })->via('POST');
        $app->run();
        $this->assertEquals(405, $app->response()->status());
        $this->assertEquals('POST', $app->response()->header('Allow'));
    }

    /**
     * Test that app returns 404 response when matched, invoked route calls
     * $app->pass(); there are no subsequent matching routes.
     */
    public function testInvokedRoutePassesWithoutSubsequentRoutes() {
        $_SERVER['REQUEST_URI'] = "/foo";
        $_SERVER['REQUEST_METHOD'] = 'GET';
        $app = new Slim();
        $app->map('/foo', function () use ($app) {
            $app->pass();
            echo "Foo GET";
        })->via('GET');
        $app->run();
        $this->assertEquals(404, $app->response()->status());
    }

    /**
     * Test that app returns 404 response when there are no matching routes
     */
    public function testNotFoundIfNoMatchingRoutes() {
        $_SERVER['REQUEST_URI'] = "/foo";
        $_SERVER['REQUEST_METHOD'] = 'GET';
        $app = new Slim();
        $app->map('/foo/bar', function () {
            echo "Foo bar!";
        })->via('GET');
        $app->run();
        $this->assertEquals(404, $app->response()->status());
    }

    /**
     * Test that app sends response with default HTTP version
     */
    public function testAppSendsResponseWithDefaultHttpVersion() {
        $app = new Slim();
        $app->get('/', function () {});
        $app->run();
        $this->assertEquals('1.1', $app->response()->httpVersion());
    }

    /**
     * Test that app sends response with custom HTTP version
     */
    public function testAppSendsResponseWithCustomHttpVersion() {
        $app = new Slim(array('http.version' => '1.0'));
        $app->get('/', function () {});
        $app->run();
        $this->assertEquals('1.0', $app->response()->httpVersion());
    }
}
Back to Top