ErrorHandlerTest.php 15 KB

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