ErrorHandlerTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. }
  136. /**
  137. * provides errors for mapping tests.
  138. *
  139. * @return array
  140. */
  141. public static function errorProvider()
  142. {
  143. return [
  144. [E_USER_NOTICE, 'Notice'],
  145. [E_USER_WARNING, 'Warning'],
  146. ];
  147. }
  148. /**
  149. * test error mappings
  150. *
  151. * @dataProvider errorProvider
  152. * @return void
  153. */
  154. public function testErrorMapping($error, $expected)
  155. {
  156. $errorHandler = new ErrorHandler();
  157. $errorHandler->register();
  158. $this->_restoreError = true;
  159. ob_start();
  160. trigger_error('Test error', $error);
  161. $result = ob_get_clean();
  162. $this->assertContains('<b>' . $expected . '</b>', $result);
  163. }
  164. /**
  165. * test error prepended by @
  166. *
  167. * @return void
  168. */
  169. public function testErrorSuppressed()
  170. {
  171. $errorHandler = new ErrorHandler();
  172. $errorHandler->register();
  173. $this->_restoreError = true;
  174. ob_start();
  175. //@codingStandardsIgnoreStart
  176. @include 'invalid.file';
  177. //@codingStandardsIgnoreEnd
  178. $result = ob_get_clean();
  179. $this->assertEmpty($result);
  180. }
  181. /**
  182. * Test that errors go into Cake Log when debug = 0.
  183. *
  184. * @return void
  185. */
  186. public function testHandleErrorDebugOff()
  187. {
  188. Configure::write('debug', false);
  189. $errorHandler = new ErrorHandler();
  190. $errorHandler->register();
  191. $this->_restoreError = true;
  192. $this->_logger->expects($this->once())
  193. ->method('log')
  194. ->with(
  195. $this->matchesRegularExpression('(notice|debug)'),
  196. 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ + 3) . ']' . "\n\n"
  197. );
  198. $out = $out + 1;
  199. }
  200. /**
  201. * Test that errors going into Cake Log include traces.
  202. *
  203. * @return void
  204. */
  205. public function testHandleErrorLoggingTrace()
  206. {
  207. Configure::write('debug', false);
  208. $errorHandler = new ErrorHandler(['trace' => true]);
  209. $errorHandler->register();
  210. $this->_restoreError = true;
  211. $this->_logger->expects($this->once())
  212. ->method('log')
  213. ->with(
  214. $this->matchesRegularExpression('(notice|debug)'),
  215. $this->logicalAnd(
  216. $this->stringContains('Notice (8): Undefined variable: out in '),
  217. $this->stringContains('Trace:'),
  218. $this->stringContains(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()'),
  219. $this->stringContains('Request URL:'),
  220. $this->stringContains('Referer URL:')
  221. )
  222. );
  223. $out = $out + 1;
  224. }
  225. /**
  226. * test handleException generating a page.
  227. *
  228. * @return void
  229. */
  230. public function testHandleException()
  231. {
  232. $error = new NotFoundException('Kaboom!');
  233. $errorHandler = new TestErrorHandler();
  234. $errorHandler->handleException($error);
  235. $this->assertContains('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
  236. }
  237. /**
  238. * test handleException generating log.
  239. *
  240. * @return void
  241. */
  242. public function testHandleExceptionLog()
  243. {
  244. $errorHandler = new TestErrorHandler([
  245. 'log' => true,
  246. 'trace' => true,
  247. ]);
  248. $error = new NotFoundException('Kaboom!');
  249. $this->_logger->expects($this->at(0))
  250. ->method('log')
  251. ->with('error', $this->logicalAnd(
  252. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  253. $this->stringContains('ErrorHandlerTest->testHandleExceptionLog')
  254. ));
  255. $this->_logger->expects($this->at(1))
  256. ->method('log')
  257. ->with('error', $this->logicalAnd(
  258. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  259. $this->logicalNot($this->stringContains('ErrorHandlerTest->testHandleExceptionLog'))
  260. ));
  261. $errorHandler->handleException($error);
  262. $this->assertContains('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
  263. $errorHandler = new TestErrorHandler([
  264. 'log' => true,
  265. 'trace' => false,
  266. ]);
  267. $errorHandler->handleException($error);
  268. }
  269. /**
  270. * test logging attributes with/without debug
  271. *
  272. * @return void
  273. */
  274. public function testHandleExceptionLogAttributes()
  275. {
  276. $errorHandler = new TestErrorHandler([
  277. 'log' => true,
  278. 'trace' => true,
  279. ]);
  280. $error = new MissingControllerException(['class' => 'Derp']);
  281. $this->_logger->expects($this->at(0))
  282. ->method('log')
  283. ->with('error', $this->logicalAnd(
  284. $this->stringContains(
  285. '[Cake\Routing\Exception\MissingControllerException] ' .
  286. 'Controller class Derp could not be found.'
  287. ),
  288. $this->stringContains('Exception Attributes:'),
  289. $this->stringContains('Request URL:'),
  290. $this->stringContains('Referer URL:')
  291. ));
  292. $this->_logger->expects($this->at(1))
  293. ->method('log')
  294. ->with('error', $this->logicalAnd(
  295. $this->stringContains(
  296. '[Cake\Routing\Exception\MissingControllerException] ' .
  297. 'Controller class Derp could not be found.'
  298. ),
  299. $this->logicalNot($this->stringContains('Exception Attributes:'))
  300. ));
  301. $errorHandler->handleException($error);
  302. Configure::write('debug', false);
  303. $errorHandler->handleException($error);
  304. }
  305. /**
  306. * test logging attributes with previous exception
  307. *
  308. * @return void
  309. */
  310. public function testHandleExceptionLogPrevious()
  311. {
  312. $errorHandler = new TestErrorHandler([
  313. 'log' => true,
  314. 'trace' => true,
  315. ]);
  316. $previous = new RecordNotFoundException('Previous logged');
  317. $error = new NotFoundException('Kaboom!', null, $previous);
  318. $this->_logger->expects($this->at(0))
  319. ->method('log')
  320. ->with('error', $this->logicalAnd(
  321. $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'),
  322. $this->stringContains('Caused by: [Cake\Datasource\Exception\RecordNotFoundException] Previous logged'),
  323. $this->stringContains('ErrorHandlerTest->testHandleExceptionLogPrevious')
  324. ));
  325. $errorHandler->handleException($error);
  326. }
  327. /**
  328. * test handleException generating log.
  329. *
  330. * @return void
  331. */
  332. public function testHandleExceptionLogSkipping()
  333. {
  334. $notFound = new NotFoundException('Kaboom!');
  335. $forbidden = new ForbiddenException('Fooled you!');
  336. $this->_logger->expects($this->once())
  337. ->method('log')
  338. ->with(
  339. 'error',
  340. $this->stringContains('[Cake\Http\Exception\ForbiddenException] Fooled you!')
  341. );
  342. $errorHandler = new TestErrorHandler([
  343. 'log' => true,
  344. 'skipLog' => ['Cake\Http\Exception\NotFoundException'],
  345. ]);
  346. $errorHandler->handleException($notFound);
  347. $this->assertContains('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
  348. $errorHandler->handleException($forbidden);
  349. $this->assertContains('Fooled you!', (string)$errorHandler->response->getBody(), 'message missing.');
  350. }
  351. /**
  352. * tests it is possible to load a plugin exception renderer
  353. *
  354. * @return void
  355. */
  356. public function testLoadPluginHandler()
  357. {
  358. $this->loadPlugins(['TestPlugin']);
  359. $errorHandler = new TestErrorHandler([
  360. 'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer',
  361. ]);
  362. $error = new NotFoundException('Kaboom!');
  363. $errorHandler->handleException($error);
  364. $result = $errorHandler->response;
  365. $this->assertEquals('Rendered by test plugin', $result);
  366. }
  367. /**
  368. * test handleFatalError generating a page.
  369. *
  370. * These tests start two buffers as handleFatalError blows the outer one up.
  371. *
  372. * @return void
  373. */
  374. public function testHandleFatalErrorPage()
  375. {
  376. $line = __LINE__;
  377. $errorHandler = new TestErrorHandler();
  378. Configure::write('debug', true);
  379. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  380. $result = (string)$errorHandler->response->getBody();
  381. $this->assertContains('Something wrong', $result, 'message missing.');
  382. $this->assertContains(__FILE__, $result, 'filename missing.');
  383. $this->assertContains((string)$line, $result, 'line missing.');
  384. Configure::write('debug', false);
  385. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  386. $result = (string)$errorHandler->response->getBody();
  387. $this->assertNotContains('Something wrong', $result, 'message must not appear.');
  388. $this->assertNotContains(__FILE__, $result, 'filename must not appear.');
  389. $this->assertContains('An Internal Error Has Occurred.', $result);
  390. }
  391. /**
  392. * test handleFatalError generating log.
  393. *
  394. * @return void
  395. */
  396. public function testHandleFatalErrorLog()
  397. {
  398. $this->_logger->expects($this->at(0))
  399. ->method('log')
  400. ->with('error', $this->logicalAnd(
  401. $this->stringContains(__FILE__ . ', line ' . (__LINE__ + 9)),
  402. $this->stringContains('Fatal Error (1)'),
  403. $this->stringContains('Something wrong')
  404. ));
  405. $this->_logger->expects($this->at(1))
  406. ->method('log')
  407. ->with('error', $this->stringContains('[Cake\Error\FatalErrorException] Something wrong'));
  408. $errorHandler = new TestErrorHandler(['log' => true]);
  409. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
  410. }
  411. /**
  412. * Tests Handling a PHP7 error
  413. *
  414. * @return void
  415. */
  416. public function testHandlePHP7Error()
  417. {
  418. $this->skipIf(!class_exists('Error'), 'Requires PHP7');
  419. $error = new PHP7ErrorException(new ParseError('Unexpected variable foo'));
  420. $errorHandler = new TestErrorHandler();
  421. $errorHandler->handleException($error);
  422. $this->assertContains('Unexpected variable foo', (string)$errorHandler->response->getBody(), 'message missing.');
  423. }
  424. /**
  425. * Data provider for memory limit changing.
  426. *
  427. * @return array
  428. */
  429. public function memoryLimitProvider()
  430. {
  431. return [
  432. // start, adjust, expected
  433. ['256M', 4, '262148K'],
  434. ['262144K', 4, '262148K'],
  435. ['1G', 128, '1048704K'],
  436. ];
  437. }
  438. /**
  439. * Test increasing the memory limit.
  440. *
  441. * @dataProvider memoryLimitProvider
  442. * @return void
  443. */
  444. public function testIncreaseMemoryLimit($start, $adjust, $expected)
  445. {
  446. $initial = ini_get('memory_limit');
  447. $this->skipIf(strlen($initial) === 0, 'Cannot read memory limit, and cannot test increasing it.');
  448. // phpunit.xml often has -1 as memory limit
  449. ini_set('memory_limit', $start);
  450. $errorHandler = new TestErrorHandler();
  451. $this->assertNull($errorHandler->increaseMemoryLimit($adjust));
  452. $new = ini_get('memory_limit');
  453. $this->assertEquals($expected, $new, 'memory limit did not get increased.');
  454. ini_set('memory_limit', $initial);
  455. }
  456. }