RouteTest.php 19.1 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
<?php
/**
 * Slim - a micro PHP 5 framework
 *
 * @author      Josh Lockhart <info@slimframework.com>
 * @copyright   2011 Josh Lockhart
 * @link        http://www.slimframework.com
 * @license     http://www.slimframework.com/license
 * @version     2.6.1
 *
 * 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.
 */

class LazyInitializeTestClass {
    public static $initialized = false;

    public function __construct() {
        self::$initialized = true;
    }

    public function foo() {
    }
}

class FooTestClass {
    public static $foo_invoked = false;
    public static $foo_invoked_args = array();

    public function foo() {
        self::$foo_invoked = true;
        self::$foo_invoked_args = func_get_args();
    }
}

class RouteTest extends PHPUnit_Framework_TestCase
{
    public function testGetPattern()
    {
        $route = new \Slim\Route('/foo', function () {});

        $this->assertEquals('/foo', $route->getPattern());
    }

    public function testGetName()
    {
        $route = new \Slim\Route('/foo', function () {});

        $property = new \ReflectionProperty($route, 'name');
        $property->setAccessible(true);
        $property->setValue($route, 'foo');

        $this->assertEquals('foo', $route->getName());
    }

    public function testSetName()
    {
        $route = new \Slim\Route('/foo', function () {});
        $route->name('foo'); // <-- Alias for `setName()`

        $this->assertAttributeEquals('foo', 'name', $route);
    }

    public function testGetCallable()
    {
        $callable = function () {
            echo 'Foo';
        };
        $route = new \Slim\Route('/foo', $callable);

        $this->assertSame($callable, $route->getCallable());
    }

    public function testGetCallableAsClass()
    {
        FooTestClass::$foo_invoked = false;
        FooTestClass::$foo_invoked_args = array();
        $route = new \Slim\Route('/foo', '\FooTestClass:foo');
        $route->setParams(array('bar' => '1234'));

        $this->assertFalse(FooTestClass::$foo_invoked);
        $this->assertTrue($route->dispatch());
        $this->assertTrue(FooTestClass::$foo_invoked);
        $this->assertEquals(array('1234'), FooTestClass::$foo_invoked_args);
    }

    public function testGetCallableAsClassLazyInitialize()
    {
        LazyInitializeTestClass::$initialized = false;

        $route = new \Slim\Route('/foo', '\LazyInitializeTestClass:foo');
        $this->assertFalse(LazyInitializeTestClass::$initialized);

        $route->dispatch();
        $this->assertTrue(LazyInitializeTestClass::$initialized);
    }

    public function testGetCallableAsStaticMethod()
    {
        $route = new \Slim\Route('/bar', '\Slim\Slim::getInstance');

        $callable = $route->getCallable();
        $this->assertEquals('\Slim\Slim::getInstance', $callable);
    }

    public function example_cร llรขble_wรฏth_wรฉird_chars()
    {
        return 'test';
    }

    public function testGetCallableWithOddCharsAsClass()
    {
        $route = new \Slim\Route('/foo', '\RouteTest:example_cร llรขble_wรฏth_wรฉird_chars');
        $callable = $route->getCallable();

        $this->assertEquals('test', $callable());
    }

    public function testSetCallable()
    {
        $callable = function () {
            echo 'Foo';
        };
        $route = new \Slim\Route('/foo', $callable); // <-- Called inside __construct()

        $this->assertAttributeSame($callable, 'callable', $route);
    }

    public function testSetCallableWithInvalidArgument()
    {
        $this->setExpectedException('\InvalidArgumentException');
        $route = new \Slim\Route('/foo', 'doesNotExist'); // <-- Called inside __construct()
    }

    public function testGetParams()
    {
        $route = new \Slim\Route('/hello/:first/:last', function () {});
        $route->matches('/hello/mr/anderson'); // <-- Parses params from argument

        $this->assertEquals(array(
            'first' => 'mr',
            'last' => 'anderson'
        ), $route->getParams());
    }

    public function testSetParams()
    {
        $route = new \Slim\Route('/hello/:first/:last', function () {});
        $route->matches('/hello/mr/anderson'); // <-- Parses params from argument
        $route->setParams(array(
            'first' => 'agent',
            'last' => 'smith'
        ));

        $this->assertAttributeEquals(array(
            'first' => 'agent',
            'last' => 'smith'
        ), 'params', $route);
    }

    public function testGetParam()
    {
        $route = new \Slim\Route('/hello/:first/:last', function () {});

        $property = new \ReflectionProperty($route, 'params');
        $property->setAccessible(true);
        $property->setValue($route, array(
            'first' => 'foo',
            'last' => 'bar'
        ));

        $this->assertEquals('foo', $route->getParam('first'));
    }

    public function testGetParamThatDoesNotExist()
    {
        $this->setExpectedException('InvalidArgumentException');

        $route = new \Slim\Route('/hello/:first/:last', function () {});

        $property = new \ReflectionProperty($route, 'params');
        $property->setAccessible(true);
        $property->setValue($route, array(
            'first' => 'foo',
            'last' => 'bar'
        ));

        $route->getParam('middle');
    }

    public function testSetParam()
    {
        $route = new \Slim\Route('/hello/:first/:last', function () {});
        $route->matches('/hello/mr/anderson'); // <-- Parses params from argument
        $route->setParam('last', 'smith');

        $this->assertAttributeEquals(array(
            'first' => 'mr',
            'last' => 'smith'
        ), 'params', $route);
    }

    public function testSetParamThatDoesNotExist()
    {
        $this->setExpectedException('InvalidArgumentException');

        $route = new \Slim\Route('/hello/:first/:last', function () {});
        $route->matches('/hello/mr/anderson'); // <-- Parses params from argument
        $route->setParam('middle', 'smith'); // <-- Should trigger InvalidArgumentException
    }

    public function testMatches()
    {
        $route = new \Slim\Route('/hello/:name', function () {});

        $this->assertTrue($route->matches('/hello/josh'));
    }

    public function testMatchesIsFalse()
    {
        $route = new \Slim\Route('/foo', function () {});

        $this->assertFalse($route->matches('/bar'));
    }

    public function testMatchesPatternWithTrailingSlash()
    {
        $route = new \Slim\Route('/foo/', function () {});

        $this->assertTrue($route->matches('/foo/'));
        $this->assertTrue($route->matches('/foo'));
    }

    public function testMatchesPatternWithoutTrailingSlash()
    {
        $route = new \Slim\Route('/foo', function () {});

        $this->assertFalse($route->matches('/foo/'));
        $this->assertTrue($route->matches('/foo'));
    }

    public function testMatchesWithConditions()
    {
        $route = new \Slim\Route('/hello/:first/and/:second', function () {});
        $route->conditions(array(
            'first' => '[a-zA-Z]{3,}'
        ));

        $this->assertTrue($route->matches('/hello/Josh/and/John'));
    }

    public function testMatchesWithConditionsIsFalse()
    {
        $route = new \Slim\Route('/hello/:first/and/:second', function () {});
        $route->conditions(array(
            'first' => '[a-z]{3,}'
        ));

        $this->assertFalse($route->matches('/hello/Josh/and/John'));
    }

    /*
     * Route should match URI with valid path component according to rfc2396
     *
     * "Uniform Resource Identifiers (URI): Generic Syntax" http://www.ietf.org/rfc/rfc2396.txt
     *
     * Excludes "+" which is valid but decodes into a space character
     */
    public function testMatchesWithValidRfc2396PathComponent()
    {
        $symbols = ':@&=$,';
        $route = new \Slim\Route('/rfc2386/:symbols', function () {});

        $this->assertTrue($route->matches('/rfc2386/' . $symbols));
    }

    /*
     * Route should match URI including unreserved punctuation marks from rfc2396
     *
     * "Uniform Resource Identifiers (URI): Generic Syntax" http://www.ietf.org/rfc/rfc2396.txt
     */
    public function testMatchesWithUnreservedMarks()
    {
        $marks = "-_.!~*'()";
        $route = new \Slim\Route('/marks/:marks', function () {});

        $this->assertTrue($route->matches('/marks/' . $marks));
    }

    public function testMatchesOptionalParameters()
    {
        $pattern = '/archive/:year(/:month(/:day))';

        $route1 = new \Slim\Route($pattern, function () {});
        $this->assertTrue($route1->matches('/archive/2010'));
        $this->assertEquals(array('year' => '2010'), $route1->getParams());

        $route2 = new \Slim\Route($pattern, function () {});
        $this->assertTrue($route2->matches('/archive/2010/05'));
        $this->assertEquals(array('year' => '2010', 'month' => '05'), $route2->getParams());

        $route3 = new \Slim\Route($pattern, function () {});
        $this->assertTrue($route3->matches('/archive/2010/05/13'));
        $this->assertEquals(array('year' => '2010', 'month' => '05', 'day' => '13'), $route3->getParams());
    }

    public function testMatchesIsCaseSensitiveByDefault()
    {
        $route = new \Slim\Route('/case/sensitive', function () {});
        $this->assertTrue($route->matches('/case/sensitive'));
        $this->assertFalse($route->matches('/CaSe/SensItiVe'));
    }

    public function testMatchesCanBeCaseInsensitive()
    {
        $route = new \Slim\Route('/Case/Insensitive', function () {}, false);
        $this->assertTrue($route->matches('/Case/Insensitive'));
        $this->assertTrue($route->matches('/CaSe/iNSensItiVe'));
    }

    public function testGetConditions()
    {
        $route = new \Slim\Route('/foo', function () {});

        $property = new \ReflectionProperty($route, 'conditions');
        $property->setAccessible(true);
        $property->setValue($route, array('foo' => '\d{3}'));

        $this->assertEquals(array('foo' => '\d{3}'), $route->getConditions());
    }

    public function testSetDefaultConditions()
    {
        \Slim\Route::setDefaultConditions(array(
            'id' => '\d+'
        ));

        $property = new \ReflectionProperty('\Slim\Route', 'defaultConditions');
        $property->setAccessible(true);

        $this->assertEquals(array(
            'id' => '\d+'
        ), $property->getValue());
    }

    public function testGetDefaultConditions()
    {
        $property = new \ReflectionProperty('\Slim\Route', 'defaultConditions');
        $property->setAccessible(true);
        $property->setValue(array(
            'id' => '\d+'
        ));

        $this->assertEquals(array(
            'id' => '\d+'
        ), \Slim\Route::getDefaultConditions());
    }

    public function testDefaultConditionsAssignedToInstance()
    {
        $staticProperty = new \ReflectionProperty('\Slim\Route', 'defaultConditions');
        $staticProperty->setAccessible(true);
        $staticProperty->setValue(array(
            'id' => '\d+'
        ));
        $route = new \Slim\Route('/foo', function () {});

        $this->assertAttributeEquals(array(
            'id' => '\d+'
        ), 'conditions', $route);
    }

    public function testMatchesWildcard()
    {
        $route = new \Slim\Route('/hello/:path+/world', function () {});

        $this->assertTrue($route->matches('/hello/foo/bar/world'));
        $this->assertAttributeEquals(array(
            'path' => array('foo', 'bar')
        ), 'params', $route);
    }

    public function testMatchesMultipleWildcards()
    {
        $route = new \Slim\Route('/hello/:path+/world/:date+', function () {});

        $this->assertTrue($route->matches('/hello/foo/bar/world/2012/03/10'));
        $this->assertAttributeEquals(array(
            'path' => array('foo', 'bar'),
            'date' => array('2012', '03', '10')
        ), 'params', $route);
    }

    public function testMatchesParamsAndWildcards()
    {
        $route = new \Slim\Route('/hello/:path+/world/:year/:month/:day/:path2+', function () {});

        $this->assertTrue($route->matches('/hello/foo/bar/world/2012/03/10/first/second'));
        $this->assertAttributeEquals(array(
            'path' => array('foo', 'bar'),
            'year' => '2012',
            'month' => '03',
            'day' => '10',
            'path2' => array('first', 'second')
        ), 'params', $route);
    }

    public function testMatchesParamsWithOptionalWildcard()
    {
        $route = new \Slim\Route('/hello(/:foo(/:bar+))', function () {});

        $this->assertTrue($route->matches('/hello'));
        $this->assertTrue($route->matches('/hello/world'));
        $this->assertTrue($route->matches('/hello/world/foo'));
        $this->assertTrue($route->matches('/hello/world/foo/bar'));
    }

    public function testSetMiddleware()
    {
        $route = new \Slim\Route('/foo', function () {});
        $mw = function () {
            echo 'Foo';
        };
        $route->setMiddleware($mw);

        $this->assertAttributeContains($mw, 'middleware', $route);
    }

    public function testSetMiddlewareMultipleTimes()
    {
        $route = new \Slim\Route('/foo', function () {});
        $mw1 = function () {
            echo 'Foo';
        };
        $mw2 = function () {
            echo 'Bar';
        };
        $route->setMiddleware($mw1);
        $route->setMiddleware($mw2);

        $this->assertAttributeContains($mw1, 'middleware', $route);
        $this->assertAttributeContains($mw2, 'middleware', $route);
    }

    public function testSetMiddlewareWithArray()
    {
        $route = new \Slim\Route('/foo', function () {});
        $mw1 = function () {
            echo 'Foo';
        };
        $mw2 = function () {
            echo 'Bar';
        };
        $route->setMiddleware(array($mw1, $mw2));

        $this->assertAttributeContains($mw1, 'middleware', $route);
        $this->assertAttributeContains($mw2, 'middleware', $route);
    }

    public function testSetMiddlewareWithInvalidArgument()
    {
        $this->setExpectedException('InvalidArgumentException');

        $route = new \Slim\Route('/foo', function () {});
        $route->setMiddleware('doesNotExist'); // <-- Should throw InvalidArgumentException
    }

    public function testSetMiddlewareWithArrayWithInvalidArgument()
    {
        $this->setExpectedException('InvalidArgumentException');

        $route = new \Slim\Route('/foo', function () {});
        $route->setMiddleware(array('doesNotExist'));
    }

    public function testGetMiddleware()
    {
        $route = new \Slim\Route('/foo', function () {});

        $property = new \ReflectionProperty($route, 'middleware');
        $property->setAccessible(true);
        $property->setValue($route, array('foo' => 'bar'));

        $this->assertEquals(array('foo' => 'bar'), $route->getMiddleware());
    }

    public function testSetHttpMethods()
    {
        $route = new \Slim\Route('/foo', function () {});
        $route->setHttpMethods('GET', 'POST');

        $this->assertAttributeEquals(array('GET', 'POST'), 'methods', $route);
    }

    public function testGetHttpMethods()
    {
        $route = new \Slim\Route('/foo', function () {});

        $property = new \ReflectionProperty($route, 'methods');
        $property->setAccessible(true);
        $property->setValue($route, array('GET', 'POST'));

        $this->assertEquals(array('GET', 'POST'), $route->getHttpMethods());
    }

    public function testAppendHttpMethods()
    {
        $route = new \Slim\Route('/foo', function () {});

        $property = new \ReflectionProperty($route, 'methods');
        $property->setAccessible(true);
        $property->setValue($route, array('GET', 'POST'));

        $route->appendHttpMethods('PUT');

        $this->assertAttributeEquals(array('GET', 'POST', 'PUT'), 'methods', $route);
    }

    public function testAppendArrayOfHttpMethods()
    {
        $arrayOfMethods = array('GET','POST','PUT');
        $route = new \Slim\Route('/foo', function () {});
        $route->appendHttpMethods($arrayOfMethods);

        $this->assertAttributeEquals($arrayOfMethods,'methods',$route);
    }

    public function testAppendHttpMethodsWithVia()
    {
        $route = new \Slim\Route('/foo', function () {});
        $route->via('PUT');

        $this->assertAttributeContains('PUT', 'methods', $route);
    }

    public function testAppendArrayOfHttpMethodsWithVia()
    {
        $arrayOfMethods = array('GET','POST','PUT');
        $route = new \Slim\Route('/foo', function () {});
        $route->via($arrayOfMethods);

        $this->assertAttributeEquals($arrayOfMethods,'methods',$route);
    }

    public function testSupportsHttpMethod()
    {
        $route = new \Slim\Route('/foo', function () {});

        $property = new \ReflectionProperty($route, 'methods');
        $property->setAccessible(true);
        $property->setValue($route, array('POST'));

        $this->assertTrue($route->supportsHttpMethod('POST'));
        $this->assertFalse($route->supportsHttpMethod('PUT'));
    }

    /**
     * Test dispatch with params
     */
    public function testDispatch()
    {
        $this->expectOutputString('Hello josh');
        $route = new \Slim\Route('/hello/:name', function ($name) { echo "Hello $name"; });
        $route->matches('/hello/josh'); //<-- Extracts params from resource URI
        $route->dispatch();
    }

    /**
     * Test dispatch with middleware
     */
    public function testDispatchWithMiddleware()
    {
        $this->expectOutputString('First! Second! Hello josh');
        $route = new \Slim\Route('/hello/:name', function ($name) { echo "Hello $name"; });
        $route->setMiddleware(function () {
            echo "First! ";
        });
        $route->setMiddleware(function () {
            echo "Second! ";
        });
        $route->matches('/hello/josh'); //<-- Extracts params from resource URI
        $route->dispatch();
    }

    /**
     * Test middleware with arguments
     */
    public function testRouteMiddlwareArguments()
    {
        $this->expectOutputString('foobar');
        $route = new \Slim\Route('/foo', function () { echo "bar"; });
        $route->setName('foo');
        $route->setMiddleware(function ($route) {
            echo $route->getName();
        });
        $route->matches('/foo'); //<-- Extracts params from resource URI
        $route->dispatch();
    }
}