ErrorHandlerTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Error;
  17. use Cake\Core\Configure;
  18. use Cake\Datasource\Exception\RecordNotFoundException;
  19. use Cake\Error\ErrorHandler;
  20. use Cake\Http\Exception\ForbiddenException;
  21. use Cake\Http\Exception\NotFoundException;
  22. use Cake\Http\Exception\MissingControllerException;
  23. use Cake\Http\ServerRequest;
  24. use Cake\Log\Log;
  25. use Cake\Routing\Router;
  26. use Cake\TestSuite\TestCase;
  27. use Psr\Log\LoggerInterface;
  28. use TestApp\Error\TestErrorHandler;
  29. /**
  30. * ErrorHandlerTest class
  31. */
  32. class ErrorHandlerTest extends TestCase
  33. {
  34. protected $_restoreError = false;
  35. /**
  36. * @var \Psr\Log\LoggerInterface|\PHPUnit\Framework\MockObject\MockObject
  37. */
  38. protected $_logger;
  39. /**
  40. * error level property
  41. *
  42. */
  43. private static $errorLevel;
  44. /**
  45. * setup create a request object to get out of router later.
  46. *
  47. * @return void
  48. */
  49. public function setUp(): void
  50. {
  51. parent::setUp();
  52. Router::reload();
  53. $request = new ServerRequest([
  54. 'base' => '',
  55. 'environment' => [
  56. 'HTTP_REFERER' => '/referer',
  57. ],
  58. ]);
  59. Router::setRequest($request);
  60. Configure::write('debug', true);
  61. $this->_logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
  62. Log::reset();
  63. Log::setConfig('error_test', [
  64. 'engine' => $this->_logger,
  65. ]);
  66. }
  67. /**
  68. * tearDown
  69. *
  70. * @return void
  71. */
  72. public function tearDown(): void
  73. {
  74. parent::tearDown();
  75. Log::reset();
  76. $this->clearPlugins();
  77. if ($this->_restoreError) {
  78. restore_error_handler();
  79. restore_exception_handler();
  80. }
  81. error_reporting(self::$errorLevel);
  82. }
  83. /**
  84. * setUpBeforeClass
  85. *
  86. * @return void
  87. */
  88. public static function setUpBeforeClass(): void
  89. {
  90. parent::setUpBeforeClass();
  91. self::$errorLevel = error_reporting();
  92. }
  93. /**
  94. * Test an invalid rendering class.
  95. *
  96. * @return void
  97. */
  98. public function testInvalidRenderer()
  99. {
  100. $this->expectException(\Exception::class);
  101. $this->expectExceptionMessage('The \'TotallyInvalid\' renderer class could not be found');
  102. $errorHandler = new ErrorHandler(['exceptionRenderer' => 'TotallyInvalid']);
  103. $errorHandler->getRenderer(new \Exception('Something bad'));
  104. }
  105. /**
  106. * test error handling when debug is on, an error should be printed from Debugger.
  107. *
  108. * @return void
  109. */
  110. public function testHandleErrorDebugOn()
  111. {
  112. $errorHandler = new ErrorHandler();
  113. $errorHandler->register();
  114. $this->_restoreError = true;
  115. ob_start();
  116. $wrong = $wrong + 1;
  117. $result = ob_get_clean();
  118. $this->assertRegExp('/<pre class="cake-error">/', $result);
  119. $this->assertRegExp('/<b>Notice<\/b>/', $result);
  120. $this->assertRegExp('/variable:\s+wrong/', $result);
  121. }
  122. /**
  123. * provides errors for mapping tests.
  124. *
  125. * @return array
  126. */
  127. public static function errorProvider()
  128. {
  129. return [
  130. [E_USER_NOTICE, 'Notice'],
  131. [E_USER_WARNING, 'Warning'],
  132. ];
  133. }
  134. /**
  135. * test error mappings
  136. *
  137. * @dataProvider errorProvider
  138. * @return void
  139. */
  140. public function testErrorMapping($error, $expected)
  141. {
  142. $errorHandler = new ErrorHandler();
  143. $errorHandler->register();
  144. $this->_restoreError = true;
  145. ob_start();
  146. trigger_error('Test error', $error);
  147. $result = ob_get_clean();
  148. $this->assertStringContainsString('<b>' . $expected . '</b>', $result);
  149. }
  150. /**
  151. * test error prepended by @
  152. *
  153. * @return void
  154. */
  155. public function testErrorSuppressed()
  156. {
  157. $errorHandler = new ErrorHandler();
  158. $errorHandler->register();
  159. $this->_restoreError = true;
  160. ob_start();
  161. // phpcs:disable
  162. @include 'invalid.file';
  163. // phpcs:enable
  164. $result = ob_get_clean();
  165. $this->assertEmpty($result);
  166. }
  167. /**
  168. * Test that errors go into Cake Log when debug = 0.
  169. *
  170. * @return void
  171. */
  172. public function testHandleErrorDebugOff()
  173. {
  174. Configure::write('debug', false);
  175. $errorHandler = new ErrorHandler();
  176. $errorHandler->register();
  177. $this->_restoreError = true;
  178. $this->_logger->expects($this->once())
  179. ->method('log')
  180. ->with(
  181. $this->matchesRegularExpression('(notice|debug)'),
  182. 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ + 3) . ']' . "\n\n"
  183. );
  184. $out = $out + 1;
  185. }
  186. /**
  187. * Test that errors going into Cake Log include traces.
  188. *
  189. * @return void
  190. */
  191. public function testHandleErrorLoggingTrace()
  192. {
  193. Configure::write('debug', false);
  194. $errorHandler = new ErrorHandler(['trace' => true]);
  195. $errorHandler->register();
  196. $this->_restoreError = true;
  197. $this->_logger->expects($this->once())
  198. ->method('log')
  199. ->with(
  200. $this->matchesRegularExpression('(notice|debug)'),
  201. $this->logicalAnd(
  202. $this->stringContains('Notice (8): Undefined variable: out in '),
  203. $this->stringContains('Trace:'),
  204. $this->stringContains(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()'),
  205. $this->stringContains('Request URL:'),
  206. $this->stringContains('Referer URL:')
  207. )
  208. );
  209. $out = $out + 1;
  210. }
  211. /**
  212. * test handleException generating a page.
  213. *
  214. * @return void
  215. */
  216. public function testHandleException()
  217. {
  218. $error = new NotFoundException('Kaboom!');
  219. $errorHandler = new TestErrorHandler();
  220. $errorHandler->handleException($error);
  221. $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
  222. }
  223. /**
  224. * test handleException generating log.
  225. *
  226. * @return void
  227. */
  228. public function testHandleExceptionLog()
  229. {
  230. $errorHandler = new TestErrorHandler([
  231. 'log' => true,
  232. 'trace' => true,
  233. ]);
  234. $error = new NotFoundException('Kaboom!');
  235. $this->_logger->expects($this->at(0))
  236. ->method('log')
  237. ->with('error', $this->logicalAnd(
  238. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  239. $this->stringContains('ErrorHandlerTest->testHandleExceptionLog')
  240. ));
  241. $this->_logger->expects($this->at(1))
  242. ->method('log')
  243. ->with('error', $this->logicalAnd(
  244. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  245. $this->logicalNot($this->stringContains('ErrorHandlerTest->testHandleExceptionLog'))
  246. ));
  247. $errorHandler->handleException($error);
  248. $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
  249. $errorHandler = new TestErrorHandler([
  250. 'log' => true,
  251. 'trace' => false,
  252. ]);
  253. $errorHandler->handleException($error);
  254. }
  255. /**
  256. * test logging attributes with/without debug
  257. *
  258. * @return void
  259. */
  260. public function testHandleExceptionLogAttributes()
  261. {
  262. $errorHandler = new TestErrorHandler([
  263. 'log' => true,
  264. 'trace' => true,
  265. ]);
  266. $error = new MissingControllerException(['class' => 'Derp']);
  267. $this->_logger->expects($this->at(0))
  268. ->method('log')
  269. ->with('error', $this->logicalAnd(
  270. $this->stringContains(
  271. '[Cake\Http\Exception\MissingControllerException] ' .
  272. 'Controller class Derp could not be found.'
  273. ),
  274. $this->stringContains('Exception Attributes:'),
  275. $this->stringContains('Request URL:'),
  276. $this->stringContains('Referer URL:')
  277. ));
  278. $this->_logger->expects($this->at(1))
  279. ->method('log')
  280. ->with('error', $this->logicalAnd(
  281. $this->stringContains(
  282. '[Cake\Http\Exception\MissingControllerException] ' .
  283. 'Controller class Derp could not be found.'
  284. ),
  285. $this->logicalNot($this->stringContains('Exception Attributes:'))
  286. ));
  287. $errorHandler->handleException($error);
  288. Configure::write('debug', false);
  289. $errorHandler->handleException($error);
  290. }
  291. /**
  292. * test logging attributes with previous exception
  293. *
  294. * @return void
  295. */
  296. public function testHandleExceptionLogPrevious()
  297. {
  298. $errorHandler = new TestErrorHandler([
  299. 'log' => true,
  300. 'trace' => true,
  301. ]);
  302. $previous = new RecordNotFoundException('Previous logged');
  303. $error = new NotFoundException('Kaboom!', null, $previous);
  304. $this->_logger->expects($this->at(0))
  305. ->method('log')
  306. ->with('error', $this->logicalAnd(
  307. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  308. $this->stringContains('Caused by: [Cake\Datasource\Exception\RecordNotFoundException] Previous logged'),
  309. $this->stringContains('ErrorHandlerTest->testHandleExceptionLogPrevious')
  310. ));
  311. $errorHandler->handleException($error);
  312. }
  313. /**
  314. * test handleException generating log.
  315. *
  316. * @return void
  317. */
  318. public function testHandleExceptionLogSkipping()
  319. {
  320. $notFound = new NotFoundException('Kaboom!');
  321. $forbidden = new ForbiddenException('Fooled you!');
  322. $this->_logger->expects($this->once())
  323. ->method('log')
  324. ->with(
  325. 'error',
  326. $this->stringContains('[Cake\Http\Exception\ForbiddenException] Fooled you!')
  327. );
  328. $errorHandler = new TestErrorHandler([
  329. 'log' => true,
  330. 'skipLog' => ['Cake\Http\Exception\NotFoundException'],
  331. ]);
  332. $errorHandler->handleException($notFound);
  333. $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
  334. $errorHandler->handleException($forbidden);
  335. $this->assertStringContainsString('Fooled you!', (string)$errorHandler->response->getBody(), 'message missing.');
  336. }
  337. /**
  338. * tests it is possible to load a plugin exception renderer
  339. *
  340. * @return void
  341. */
  342. public function testLoadPluginHandler()
  343. {
  344. $this->loadPlugins(['TestPlugin']);
  345. $errorHandler = new TestErrorHandler([
  346. 'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer',
  347. ]);
  348. $error = new NotFoundException('Kaboom!');
  349. $errorHandler->handleException($error);
  350. $result = $errorHandler->response;
  351. $this->assertSame('Rendered by test plugin', (string)$result);
  352. }
  353. /**
  354. * test handleFatalError generating a page.
  355. *
  356. * These tests start two buffers as handleFatalError blows the outer one up.
  357. *
  358. * @return void
  359. */
  360. public function testHandleFatalErrorPage()
  361. {
  362. $line = __LINE__;
  363. $errorHandler = new TestErrorHandler();
  364. Configure::write('debug', true);
  365. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  366. $result = (string)$errorHandler->response->getBody();
  367. $this->assertStringContainsString('Something wrong', $result, 'message missing.');
  368. $this->assertStringContainsString(__FILE__, $result, 'filename missing.');
  369. $this->assertStringContainsString((string)$line, $result, 'line missing.');
  370. Configure::write('debug', false);
  371. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  372. $result = (string)$errorHandler->response->getBody();
  373. $this->assertStringNotContainsString('Something wrong', $result, 'message must not appear.');
  374. $this->assertStringNotContainsString(__FILE__, $result, 'filename must not appear.');
  375. $this->assertStringContainsString('An Internal Error Has Occurred.', $result);
  376. }
  377. /**
  378. * test handleFatalError generating log.
  379. *
  380. * @return void
  381. */
  382. public function testHandleFatalErrorLog()
  383. {
  384. $this->_logger->expects($this->at(0))
  385. ->method('log')
  386. ->with('error', $this->logicalAnd(
  387. $this->stringContains(__FILE__ . ', line ' . (__LINE__ + 9)),
  388. $this->stringContains('Fatal Error (1)'),
  389. $this->stringContains('Something wrong')
  390. ));
  391. $this->_logger->expects($this->at(1))
  392. ->method('log')
  393. ->with('error', $this->stringContains('[Cake\Error\FatalErrorException] Something wrong'));
  394. $errorHandler = new TestErrorHandler(['log' => true]);
  395. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
  396. }
  397. /**
  398. * Data provider for memory limit changing.
  399. *
  400. * @return array
  401. */
  402. public function memoryLimitProvider()
  403. {
  404. return [
  405. // start, adjust, expected
  406. ['256M', 4, '262148K'],
  407. ['262144K', 4, '262148K'],
  408. ['1G', 128, '1048704K'],
  409. ];
  410. }
  411. /**
  412. * Test increasing the memory limit.
  413. *
  414. * @dataProvider memoryLimitProvider
  415. * @return void
  416. */
  417. public function testIncreaseMemoryLimit($start, $adjust, $expected)
  418. {
  419. $initial = ini_get('memory_limit');
  420. $this->skipIf(strlen($initial) === 0, 'Cannot read memory limit, and cannot test increasing it.');
  421. // phpunit.xml often has -1 as memory limit
  422. ini_set('memory_limit', $start);
  423. $errorHandler = new TestErrorHandler();
  424. $this->assertNull($errorHandler->increaseMemoryLimit($adjust));
  425. $new = ini_get('memory_limit');
  426. $this->assertEquals($expected, $new, 'memory limit did not get increased.');
  427. ini_set('memory_limit', $initial);
  428. }
  429. }