ErrorHandlerTest.php 16 KB

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