ErrorHandlerTest.php 16 KB

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