ErrorHandlerTest.php 14 KB

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