ErrorHandlerTest.php 14 KB

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