ErrorHandlerMiddlewareTest.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 handling PHP 7's Error instance.
  136. *
  137. * @return void
  138. */
  139. public function testHandlePHP7Error()
  140. {
  141. $this->skipIf(version_compare(PHP_VERSION, '7.0.0', '<'), 'Error class only exists since PHP 7.');
  142. $middleware = new ErrorHandlerMiddleware();
  143. $request = ServerRequestFactory::fromGlobals();
  144. $response = new Response();
  145. $error = new Error();
  146. $result = $middleware->handleException($error, $request, $response);
  147. $this->assertInstanceOf(Response::class, $result);
  148. }
  149. /**
  150. * Test rendering an error page logs errors
  151. *
  152. * @return void
  153. */
  154. public function testHandleExceptionLogAndTrace()
  155. {
  156. $this->logger->expects($this->at(0))
  157. ->method('log')
  158. ->with('error', $this->logicalAnd(
  159. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  160. $this->stringContains('ErrorHandlerMiddlewareTest->testHandleException'),
  161. $this->stringContains('Request URL: /target/url'),
  162. $this->stringContains('Referer URL: /other/path')
  163. ));
  164. $request = ServerRequestFactory::fromGlobals([
  165. 'REQUEST_URI' => '/target/url',
  166. 'HTTP_REFERER' => '/other/path'
  167. ]);
  168. $response = new Response();
  169. $middleware = new ErrorHandlerMiddleware(null, ['log' => true, 'trace' => true]);
  170. $next = function ($req, $res) {
  171. throw new \Cake\Http\Exception\NotFoundException('Kaboom!');
  172. };
  173. $result = $middleware($request, $response, $next);
  174. $this->assertNotSame($result, $response);
  175. $this->assertEquals(404, $result->getStatusCode());
  176. $this->assertContains('was not found', '' . $result->getBody());
  177. }
  178. /**
  179. * Test rendering an error page skips logging for specific classes
  180. *
  181. * @return void
  182. */
  183. public function testHandleExceptionSkipLog()
  184. {
  185. $this->logger->expects($this->never())->method('log');
  186. $request = ServerRequestFactory::fromGlobals();
  187. $response = new Response();
  188. $middleware = new ErrorHandlerMiddleware(null, [
  189. 'log' => true,
  190. 'skipLog' => ['Cake\Http\Exception\NotFoundException']
  191. ]);
  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 logs exception attributes
  202. *
  203. * @return void
  204. */
  205. public function testHandleExceptionLogAttributes()
  206. {
  207. $this->logger->expects($this->at(0))
  208. ->method('log')
  209. ->with('error', $this->logicalAnd(
  210. $this->stringContains(
  211. '[Cake\Routing\Exception\MissingControllerException] ' .
  212. 'Controller class Articles could not be found.'
  213. ),
  214. $this->stringContains('Exception Attributes:'),
  215. $this->stringContains("'class' => 'Articles'"),
  216. $this->stringContains('Request URL:')
  217. ));
  218. $request = ServerRequestFactory::fromGlobals();
  219. $response = new Response();
  220. $middleware = new ErrorHandlerMiddleware(null, ['log' => true]);
  221. $next = function ($req, $res) {
  222. throw new \Cake\Routing\Exception\MissingControllerException(['class' => 'Articles']);
  223. };
  224. $result = $middleware($request, $response, $next);
  225. $this->assertNotSame($result, $response);
  226. $this->assertEquals(404, $result->getStatusCode());
  227. }
  228. /**
  229. * Test handling an error and having rendering fail.
  230. *
  231. * @return void
  232. */
  233. public function testHandleExceptionRenderingFails()
  234. {
  235. $request = ServerRequestFactory::fromGlobals();
  236. $response = new Response();
  237. $factory = function ($exception) {
  238. $mock = $this->getMockBuilder('StdClass')
  239. ->setMethods(['render'])
  240. ->getMock();
  241. $mock->expects($this->once())
  242. ->method('render')
  243. ->will($this->throwException(new LogicException('Rendering failed')));
  244. return $mock;
  245. };
  246. $middleware = new ErrorHandlerMiddleware($factory);
  247. $next = function ($req, $res) {
  248. throw new \Cake\Http\Exception\ServiceUnavailableException('whoops');
  249. };
  250. $response = $middleware($request, $response, $next);
  251. $this->assertEquals(500, $response->getStatusCode());
  252. $this->assertEquals('An Internal Server Error Occurred', '' . $response->getBody());
  253. }
  254. }