ErrorHandlerTest.php 14 KB

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