diff --git a/tests/php/Control/DirectorTest.php b/tests/php/Control/DirectorTest.php index cb2e94b62..a7095cf1a 100644 --- a/tests/php/Control/DirectorTest.php +++ b/tests/php/Control/DirectorTest.php @@ -1,5 +1,4 @@ assertEquals(2, $filter->postCalls); } + + public function testGlobalMiddleware() + { + $middleware = new DirectorTest\TestMiddleware; + + Injector::inst()->registerService($middleware, 'Middleware1'); + Config::modify()->set(Director::class, 'middlewares', [ 'Middleware1' ]); + + $response = Director::test('some-dummy-url'); + $this->assertEquals(404, $response->getStatusCode()); + + // Both triggered + $this->assertEquals(1, $middleware->preCalls); + $this->assertEquals(1, $middleware->postCalls); + + $middleware->failPost = true; + + $response = Director::test('some-dummy-url'); + $this->assertEquals(500, $response->getStatusCode()); + + // Both triggered + $this->assertEquals(2, $middleware->preCalls); + $this->assertEquals(2, $middleware->postCalls); + + $middleware->failPre = true; + + $response = Director::test('some-dummy-url'); + $this->assertEquals(400, $response->getStatusCode()); + + // Pre triggered, post not + $this->assertEquals(3, $middleware->preCalls); + $this->assertEquals(2, $middleware->postCalls); + } + + public function testRouteSpecificMiddleware() + { + $middleware = new DirectorTest\TestMiddleware; + $specificMiddleware = new DirectorTest\TestMiddleware; + + Injector::inst()->registerService($middleware, 'Middleware1'); + Injector::inst()->registerService($specificMiddleware, 'Middleware2'); + + // Global middleware + Config::modify()->set(Director::class, 'middlewares', [ 'Middleware1' ]); + + // URL rules, one of which has a specific middleware + Config::modify()->set( + Director::class, + 'rules', + [ + 'url-one' => TestController::class, + 'url-two' => [ + 'Controller' => TestController::class, + 'Middlewares' => [ 'Middleware2' ] + ] + ] + ); + + // URL without a route-specific middleware + $response = Director::test('url-one'); + + // Only the global middleware triggered + $this->assertEquals(1, $middleware->preCalls); + $this->assertEquals(0, $specificMiddleware->postCalls); + + $response = Director::test('url-two'); + + // Both triggered on the url with the specific middleware applied + $this->assertEquals(2, $middleware->preCalls); + $this->assertEquals(1, $specificMiddleware->postCalls); + + } } diff --git a/tests/php/Control/DirectorTest/TestMiddleware.php b/tests/php/Control/DirectorTest/TestMiddleware.php new file mode 100644 index 000000000..d26e4a727 --- /dev/null +++ b/tests/php/Control/DirectorTest/TestMiddleware.php @@ -0,0 +1,40 @@ +preCalls++; + if ($this->failPre) { + return new HTTPResponse('Fail pre', 400); + } + + $response = $delegate($request); + + $this->postCalls++; + if ($this->failPost) { + return new HTTPResponse('Fail post', 500); + } + + return $response; + } + + public function reset() + { + $this->preCalls = 0; + $this->postCalls = 0; + } +}