| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340 |
- <?php
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @link https://cakephp.org CakePHP(tm) Project
- * @since 3.3.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Test\TestCase\Error\Middleware;
- use Cake\Error\Middleware\ErrorHandlerMiddleware;
- use Cake\Http\Response;
- use Cake\Http\ServerRequestFactory;
- use Cake\Log\Log;
- use Cake\TestSuite\TestCase;
- use Error;
- use LogicException;
- use Psr\Log\LoggerInterface;
- /**
- * Test for ErrorHandlerMiddleware
- */
- class ErrorHandlerMiddlewareTest extends TestCase
- {
- protected $logger;
- /**
- * setup
- *
- * @return void
- */
- public function setUp()
- {
- parent::setUp();
- static::setAppNamespace();
- $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
- Log::reset();
- Log::setConfig('error_test', [
- 'engine' => $this->logger
- ]);
- }
- /**
- * Teardown
- *
- * @return void
- */
- public function tearDown()
- {
- parent::tearDown();
- Log::drop('error_test');
- }
- /**
- * Test returning a response works ok.
- *
- * @return void
- */
- public function testNoErrorResponse()
- {
- $this->logger->expects($this->never())->method('log');
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware();
- $next = function ($req, $res) {
- return $res;
- };
- $result = $middleware($request, $response, $next);
- $this->assertSame($result, $response);
- }
- /**
- * Test an invalid rendering class.
- *
- */
- public function testInvalidRenderer()
- {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('The \'TotallyInvalid\' renderer class could not be found');
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware('TotallyInvalid');
- $next = function ($req, $res) {
- throw new \Exception('Something bad');
- };
- $middleware($request, $response, $next);
- }
- /**
- * Test using a factory method to make a renderer.
- *
- * @return void
- */
- public function testRendererFactory()
- {
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $factory = function ($exception) {
- $this->assertInstanceOf('LogicException', $exception);
- $response = new Response;
- $mock = $this->getMockBuilder('StdClass')
- ->setMethods(['render'])
- ->getMock();
- $mock->expects($this->once())
- ->method('render')
- ->will($this->returnValue($response));
- return $mock;
- };
- $middleware = new ErrorHandlerMiddleware($factory);
- $next = function ($req, $res) {
- throw new LogicException('Something bad');
- };
- $middleware($request, $response, $next);
- }
- /**
- * Test rendering an error page
- *
- * @return void
- */
- public function testHandleException()
- {
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware();
- $next = function ($req, $res) {
- throw new \Cake\Http\Exception\NotFoundException('whoops');
- };
- $result = $middleware($request, $response, $next);
- $this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $result);
- $this->assertInstanceOf('Cake\Http\Response', $result);
- $this->assertNotSame($result, $response);
- $this->assertEquals(404, $result->getStatusCode());
- $this->assertContains('was not found', '' . $result->getBody());
- }
- /**
- * Test rendering an error page holds onto the original request.
- *
- * @return void
- */
- public function testHandleExceptionPreserveRequest()
- {
- $request = ServerRequestFactory::fromGlobals();
- $request = $request->withHeader('Accept', 'application/json');
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware();
- $next = function ($req, $res) {
- throw new \Cake\Http\Exception\NotFoundException('whoops');
- };
- $result = $middleware($request, $response, $next);
- $this->assertInstanceOf('Cake\Http\Response', $result);
- $this->assertNotSame($result, $response);
- $this->assertEquals(404, $result->getStatusCode());
- $this->assertContains('"message": "whoops"', '' . $result->getBody());
- $this->assertEquals('application/json', $result->getHeaderLine('Content-type'));
- }
- /**
- * Test handling PHP 7's Error instance.
- *
- * @return void
- */
- public function testHandlePHP7Error()
- {
- $this->skipIf(version_compare(PHP_VERSION, '7.0.0', '<'), 'Error class only exists since PHP 7.');
- $middleware = new ErrorHandlerMiddleware();
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $error = new Error();
- $result = $middleware->handleException($error, $request, $response);
- $this->assertInstanceOf(Response::class, $result);
- }
- /**
- * Test rendering an error page logs errors
- *
- * @return void
- */
- public function testHandleExceptionLogAndTrace()
- {
- $this->logger->expects($this->at(0))
- ->method('log')
- ->with('error', $this->logicalAnd(
- $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
- $this->stringContains('ErrorHandlerMiddlewareTest->testHandleException'),
- $this->stringContains('Request URL: /target/url'),
- $this->stringContains('Referer URL: /other/path'),
- $this->logicalNot(
- $this->stringContains('Previous: ')
- )
- ));
- $request = ServerRequestFactory::fromGlobals([
- 'REQUEST_URI' => '/target/url',
- 'HTTP_REFERER' => '/other/path'
- ]);
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware(null, ['log' => true, 'trace' => true]);
- $next = function ($req, $res) {
- throw new \Cake\Http\Exception\NotFoundException('Kaboom!');
- };
- $result = $middleware($request, $response, $next);
- $this->assertNotSame($result, $response);
- $this->assertEquals(404, $result->getStatusCode());
- $this->assertContains('was not found', '' . $result->getBody());
- }
- /**
- * Test rendering an error page logs errors with previous
- *
- * @return void
- */
- public function testHandleExceptionLogAndTraceWithPrevious()
- {
- $this->logger->expects($this->at(0))
- ->method('log')
- ->with('error', $this->logicalAnd(
- $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
- $this->stringContains('Caused by: [Cake\Datasource\Exception\RecordNotFoundException] Previous logged'),
- $this->stringContains('ErrorHandlerMiddlewareTest->testHandleExceptionLogAndTraceWithPrevious'),
- $this->stringContains('Request URL: /target/url'),
- $this->stringContains('Referer URL: /other/path')
- ));
- $request = ServerRequestFactory::fromGlobals([
- 'REQUEST_URI' => '/target/url',
- 'HTTP_REFERER' => '/other/path'
- ]);
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware(null, ['log' => true, 'trace' => true]);
- $next = function ($req, $res) {
- $previous = new \Cake\Datasource\Exception\RecordNotFoundException('Previous logged');
- throw new \Cake\Http\Exception\NotFoundException('Kaboom!', null, $previous);
- };
- $result = $middleware($request, $response, $next);
- $this->assertNotSame($result, $response);
- $this->assertEquals(404, $result->getStatusCode());
- $this->assertContains('was not found', '' . $result->getBody());
- }
- /**
- * Test rendering an error page skips logging for specific classes
- *
- * @return void
- */
- public function testHandleExceptionSkipLog()
- {
- $this->logger->expects($this->never())->method('log');
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware(null, [
- 'log' => true,
- 'skipLog' => ['Cake\Http\Exception\NotFoundException']
- ]);
- $next = function ($req, $res) {
- throw new \Cake\Http\Exception\NotFoundException('Kaboom!');
- };
- $result = $middleware($request, $response, $next);
- $this->assertNotSame($result, $response);
- $this->assertEquals(404, $result->getStatusCode());
- $this->assertContains('was not found', '' . $result->getBody());
- }
- /**
- * Test rendering an error page logs exception attributes
- *
- * @return void
- */
- public function testHandleExceptionLogAttributes()
- {
- $this->logger->expects($this->at(0))
- ->method('log')
- ->with('error', $this->logicalAnd(
- $this->stringContains(
- '[Cake\Routing\Exception\MissingControllerException] ' .
- 'Controller class Articles could not be found.'
- ),
- $this->stringContains('Exception Attributes:'),
- $this->stringContains("'class' => 'Articles'"),
- $this->stringContains('Request URL:')
- ));
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $middleware = new ErrorHandlerMiddleware(null, ['log' => true]);
- $next = function ($req, $res) {
- throw new \Cake\Routing\Exception\MissingControllerException(['class' => 'Articles']);
- };
- $result = $middleware($request, $response, $next);
- $this->assertNotSame($result, $response);
- $this->assertEquals(404, $result->getStatusCode());
- }
- /**
- * Test handling an error and having rendering fail.
- *
- * @return void
- */
- public function testHandleExceptionRenderingFails()
- {
- $request = ServerRequestFactory::fromGlobals();
- $response = new Response();
- $factory = function ($exception) {
- $mock = $this->getMockBuilder('StdClass')
- ->setMethods(['render'])
- ->getMock();
- $mock->expects($this->once())
- ->method('render')
- ->will($this->throwException(new LogicException('Rendering failed')));
- return $mock;
- };
- $middleware = new ErrorHandlerMiddleware($factory);
- $next = function ($req, $res) {
- throw new \Cake\Http\Exception\ServiceUnavailableException('whoops');
- };
- $response = $middleware($request, $response, $next);
- $this->assertEquals(500, $response->getStatusCode());
- $this->assertEquals('An Internal Server Error Occurred', '' . $response->getBody());
- }
- }
|