ErrorHandlerMiddlewareTest.php 12 KB

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