ErrorHandlerMiddlewareTest.php 11 KB

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