ErrorHandlerTest.php 14 KB

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