ErrorHandlerMiddlewareTest.php 11 KB

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