ErrorHandlerMiddlewareTest.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.3.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Error\Middleware;
  17. use Cake\Error\Middleware\ErrorHandlerMiddleware;
  18. use Cake\Http\Response;
  19. use Cake\Http\ServerRequestFactory;
  20. use Cake\Log\Log;
  21. use Cake\TestSuite\TestCase;
  22. use Error;
  23. use LogicException;
  24. use Psr\Log\LoggerInterface;
  25. /**
  26. * Test for ErrorHandlerMiddleware
  27. */
  28. class ErrorHandlerMiddlewareTest extends TestCase
  29. {
  30. protected $logger;
  31. /**
  32. * setup
  33. *
  34. * @return void
  35. */
  36. public function setUp()
  37. {
  38. parent::setUp();
  39. static::setAppNamespace();
  40. $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
  41. Log::reset();
  42. Log::setConfig('error_test', [
  43. 'engine' => $this->logger
  44. ]);
  45. }
  46. /**
  47. * Teardown
  48. *
  49. * @return void
  50. */
  51. public function tearDown()
  52. {
  53. parent::tearDown();
  54. Log::drop('error_test');
  55. }
  56. /**
  57. * Test returning a response works ok.
  58. *
  59. * @return void
  60. */
  61. public function testNoErrorResponse()
  62. {
  63. $this->logger->expects($this->never())->method('log');
  64. $request = ServerRequestFactory::fromGlobals();
  65. $response = new Response();
  66. $middleware = new ErrorHandlerMiddleware();
  67. $next = function ($req, $res) {
  68. return $res;
  69. };
  70. $result = $middleware($request, $response, $next);
  71. $this->assertSame($result, $response);
  72. }
  73. /**
  74. * Test an invalid rendering class.
  75. *
  76. */
  77. public function testInvalidRenderer()
  78. {
  79. $this->expectException(\Exception::class);
  80. $this->expectExceptionMessage('The \'TotallyInvalid\' renderer class could not be found');
  81. $request = ServerRequestFactory::fromGlobals();
  82. $response = new Response();
  83. $middleware = new ErrorHandlerMiddleware('TotallyInvalid');
  84. $next = function ($req, $res) {
  85. throw new \Exception('Something bad');
  86. };
  87. $middleware($request, $response, $next);
  88. }
  89. /**
  90. * Test using a factory method to make a renderer.
  91. *
  92. * @return void
  93. */
  94. public function testRendererFactory()
  95. {
  96. $request = ServerRequestFactory::fromGlobals();
  97. $response = new Response();
  98. $factory = function ($exception) {
  99. $this->assertInstanceOf('LogicException', $exception);
  100. $response = new Response;
  101. $mock = $this->getMockBuilder('StdClass')
  102. ->setMethods(['render'])
  103. ->getMock();
  104. $mock->expects($this->once())
  105. ->method('render')
  106. ->will($this->returnValue($response));
  107. return $mock;
  108. };
  109. $middleware = new ErrorHandlerMiddleware($factory);
  110. $next = function ($req, $res) {
  111. throw new LogicException('Something bad');
  112. };
  113. $middleware($request, $response, $next);
  114. }
  115. /**
  116. * Test rendering an error page
  117. *
  118. * @return void
  119. */
  120. public function testHandleException()
  121. {
  122. $request = ServerRequestFactory::fromGlobals();
  123. $response = new Response();
  124. $middleware = new ErrorHandlerMiddleware();
  125. $next = function ($req, $res) {
  126. throw new \Cake\Http\Exception\NotFoundException('whoops');
  127. };
  128. $result = $middleware($request, $response, $next);
  129. $this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $result);
  130. $this->assertInstanceOf('Cake\Http\Response', $result);
  131. $this->assertNotSame($result, $response);
  132. $this->assertEquals(404, $result->getStatusCode());
  133. $this->assertContains('was not found', '' . $result->getBody());
  134. }
  135. /**
  136. * Test rendering an error page holds onto the original request.
  137. *
  138. * @return void
  139. */
  140. public function testHandleExceptionPreserveRequest()
  141. {
  142. $request = ServerRequestFactory::fromGlobals();
  143. $request = $request->withHeader('Accept', 'application/json');
  144. $response = new Response();
  145. $middleware = new ErrorHandlerMiddleware();
  146. $next = function ($req, $res) {
  147. throw new \Cake\Http\Exception\NotFoundException('whoops');
  148. };
  149. $result = $middleware($request, $response, $next);
  150. $this->assertInstanceOf('Cake\Http\Response', $result);
  151. $this->assertNotSame($result, $response);
  152. $this->assertEquals(404, $result->getStatusCode());
  153. $this->assertContains('"message": "whoops"', '' . $result->getBody());
  154. $this->assertEquals('application/json; charset=UTF-8', $result->getHeaderLine('Content-type'));
  155. }
  156. /**
  157. * Test handling PHP 7's Error instance.
  158. *
  159. * @return void
  160. */
  161. public function testHandlePHP7Error()
  162. {
  163. $this->skipIf(version_compare(PHP_VERSION, '7.0.0', '<'), 'Error class only exists since PHP 7.');
  164. $middleware = new ErrorHandlerMiddleware();
  165. $request = ServerRequestFactory::fromGlobals();
  166. $response = new Response();
  167. $error = new Error();
  168. $result = $middleware->handleException($error, $request, $response);
  169. $this->assertInstanceOf(Response::class, $result);
  170. }
  171. /**
  172. * Test rendering an error page logs errors
  173. *
  174. * @return void
  175. */
  176. public function testHandleExceptionLogAndTrace()
  177. {
  178. $this->logger->expects($this->at(0))
  179. ->method('log')
  180. ->with('error', $this->logicalAnd(
  181. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  182. $this->stringContains('ErrorHandlerMiddlewareTest->testHandleException'),
  183. $this->stringContains('Request URL: /target/url'),
  184. $this->stringContains('Referer URL: /other/path')
  185. ));
  186. $request = ServerRequestFactory::fromGlobals([
  187. 'REQUEST_URI' => '/target/url',
  188. 'HTTP_REFERER' => '/other/path'
  189. ]);
  190. $response = new Response();
  191. $middleware = new ErrorHandlerMiddleware(null, ['log' => true, 'trace' => true]);
  192. $next = function ($req, $res) {
  193. throw new \Cake\Http\Exception\NotFoundException('Kaboom!');
  194. };
  195. $result = $middleware($request, $response, $next);
  196. $this->assertNotSame($result, $response);
  197. $this->assertEquals(404, $result->getStatusCode());
  198. $this->assertContains('was not found', '' . $result->getBody());
  199. }
  200. /**
  201. * Test rendering an error page skips logging for specific classes
  202. *
  203. * @return void
  204. */
  205. public function testHandleExceptionSkipLog()
  206. {
  207. $this->logger->expects($this->never())->method('log');
  208. $request = ServerRequestFactory::fromGlobals();
  209. $response = new Response();
  210. $middleware = new ErrorHandlerMiddleware(null, [
  211. 'log' => true,
  212. 'skipLog' => ['Cake\Http\Exception\NotFoundException']
  213. ]);
  214. $next = function ($req, $res) {
  215. throw new \Cake\Http\Exception\NotFoundException('Kaboom!');
  216. };
  217. $result = $middleware($request, $response, $next);
  218. $this->assertNotSame($result, $response);
  219. $this->assertEquals(404, $result->getStatusCode());
  220. $this->assertContains('was not found', '' . $result->getBody());
  221. }
  222. /**
  223. * Test rendering an error page logs exception attributes
  224. *
  225. * @return void
  226. */
  227. public function testHandleExceptionLogAttributes()
  228. {
  229. $this->logger->expects($this->at(0))
  230. ->method('log')
  231. ->with('error', $this->logicalAnd(
  232. $this->stringContains(
  233. '[Cake\Routing\Exception\MissingControllerException] ' .
  234. 'Controller class Articles could not be found.'
  235. ),
  236. $this->stringContains('Exception Attributes:'),
  237. $this->stringContains("'class' => 'Articles'"),
  238. $this->stringContains('Request URL:')
  239. ));
  240. $request = ServerRequestFactory::fromGlobals();
  241. $response = new Response();
  242. $middleware = new ErrorHandlerMiddleware(null, ['log' => true]);
  243. $next = function ($req, $res) {
  244. throw new \Cake\Routing\Exception\MissingControllerException(['class' => 'Articles']);
  245. };
  246. $result = $middleware($request, $response, $next);
  247. $this->assertNotSame($result, $response);
  248. $this->assertEquals(404, $result->getStatusCode());
  249. }
  250. /**
  251. * Test handling an error and having rendering fail.
  252. *
  253. * @return void
  254. */
  255. public function testHandleExceptionRenderingFails()
  256. {
  257. $request = ServerRequestFactory::fromGlobals();
  258. $response = new Response();
  259. $factory = function ($exception) {
  260. $mock = $this->getMockBuilder('StdClass')
  261. ->setMethods(['render'])
  262. ->getMock();
  263. $mock->expects($this->once())
  264. ->method('render')
  265. ->will($this->throwException(new LogicException('Rendering failed')));
  266. return $mock;
  267. };
  268. $middleware = new ErrorHandlerMiddleware($factory);
  269. $next = function ($req, $res) {
  270. throw new \Cake\Http\Exception\ServiceUnavailableException('whoops');
  271. };
  272. $response = $middleware($request, $response, $next);
  273. $this->assertEquals(500, $response->getStatusCode());
  274. $this->assertEquals('An Internal Server Error Occurred', '' . $response->getBody());
  275. }
  276. }