ErrorHandlerTest.php 14 KB

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