ErrorHandlerTest.php 14 KB

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