ErrorHandlerMiddlewareTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. $this->logicalNot(
  164. $this->stringContains('Previous: ')
  165. )
  166. ));
  167. $request = ServerRequestFactory::fromGlobals([
  168. 'REQUEST_URI' => '/target/url',
  169. 'HTTP_REFERER' => '/other/path'
  170. ]);
  171. $response = new Response();
  172. $middleware = new ErrorHandlerMiddleware(null, ['log' => true, 'trace' => true]);
  173. $next = function ($req, $res) {
  174. throw new \Cake\Http\Exception\NotFoundException('Kaboom!');
  175. };
  176. $result = $middleware($request, $response, $next);
  177. $this->assertNotSame($result, $response);
  178. $this->assertEquals(404, $result->getStatusCode());
  179. $this->assertContains('was not found', '' . $result->getBody());
  180. }
  181. /**
  182. * Test rendering an error page logs errors with previous
  183. *
  184. * @return void
  185. */
  186. public function testHandleExceptionLogAndTraceWithPrevious()
  187. {
  188. $this->logger->expects($this->at(0))
  189. ->method('log')
  190. ->with('error', $this->logicalAnd(
  191. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  192. $this->stringContains('Previous: [Cake\Datasource\Exception\RecordNotFoundException] Previous logged'),
  193. $this->stringContains('ErrorHandlerMiddlewareTest->testHandleException'),
  194. $this->stringContains('Request URL: /target/url'),
  195. $this->stringContains('Referer URL: /other/path')
  196. ));
  197. $request = ServerRequestFactory::fromGlobals([
  198. 'REQUEST_URI' => '/target/url',
  199. 'HTTP_REFERER' => '/other/path'
  200. ]);
  201. $response = new Response();
  202. $middleware = new ErrorHandlerMiddleware(null, ['log' => true, 'trace' => true]);
  203. $next = function ($req, $res) {
  204. $previous = new \Cake\Datasource\Exception\RecordNotFoundException('Previous logged');
  205. throw new \Cake\Http\Exception\NotFoundException('Kaboom!', null, $previous);
  206. };
  207. $result = $middleware($request, $response, $next);
  208. $this->assertNotSame($result, $response);
  209. $this->assertEquals(404, $result->getStatusCode());
  210. $this->assertContains('was not found', '' . $result->getBody());
  211. }
  212. /**
  213. * Test rendering an error page skips logging for specific classes
  214. *
  215. * @return void
  216. */
  217. public function testHandleExceptionSkipLog()
  218. {
  219. $this->logger->expects($this->never())->method('log');
  220. $request = ServerRequestFactory::fromGlobals();
  221. $response = new Response();
  222. $middleware = new ErrorHandlerMiddleware(null, [
  223. 'log' => true,
  224. 'skipLog' => ['Cake\Http\Exception\NotFoundException']
  225. ]);
  226. $next = function ($req, $res) {
  227. throw new \Cake\Http\Exception\NotFoundException('Kaboom!');
  228. };
  229. $result = $middleware($request, $response, $next);
  230. $this->assertNotSame($result, $response);
  231. $this->assertEquals(404, $result->getStatusCode());
  232. $this->assertContains('was not found', '' . $result->getBody());
  233. }
  234. /**
  235. * Test rendering an error page logs exception attributes
  236. *
  237. * @return void
  238. */
  239. public function testHandleExceptionLogAttributes()
  240. {
  241. $this->logger->expects($this->at(0))
  242. ->method('log')
  243. ->with('error', $this->logicalAnd(
  244. $this->stringContains(
  245. '[Cake\Routing\Exception\MissingControllerException] ' .
  246. 'Controller class Articles could not be found.'
  247. ),
  248. $this->stringContains('Exception Attributes:'),
  249. $this->stringContains("'class' => 'Articles'"),
  250. $this->stringContains('Request URL:')
  251. ));
  252. $request = ServerRequestFactory::fromGlobals();
  253. $response = new Response();
  254. $middleware = new ErrorHandlerMiddleware(null, ['log' => true]);
  255. $next = function ($req, $res) {
  256. throw new \Cake\Routing\Exception\MissingControllerException(['class' => 'Articles']);
  257. };
  258. $result = $middleware($request, $response, $next);
  259. $this->assertNotSame($result, $response);
  260. $this->assertEquals(404, $result->getStatusCode());
  261. }
  262. /**
  263. * Test handling an error and having rendering fail.
  264. *
  265. * @return void
  266. */
  267. public function testHandleExceptionRenderingFails()
  268. {
  269. $request = ServerRequestFactory::fromGlobals();
  270. $response = new Response();
  271. $factory = function ($exception) {
  272. $mock = $this->getMockBuilder('StdClass')
  273. ->setMethods(['render'])
  274. ->getMock();
  275. $mock->expects($this->once())
  276. ->method('render')
  277. ->will($this->throwException(new LogicException('Rendering failed')));
  278. return $mock;
  279. };
  280. $middleware = new ErrorHandlerMiddleware($factory);
  281. $next = function ($req, $res) {
  282. throw new \Cake\Http\Exception\ServiceUnavailableException('whoops');
  283. };
  284. $response = $middleware($request, $response, $next);
  285. $this->assertEquals(500, $response->getStatusCode());
  286. $this->assertEquals('An Internal Server Error Occurred', '' . $response->getBody());
  287. }
  288. }