ErrorHandlerMiddlewareTest.php 11 KB

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