ErrorHandlerTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Error;
  16. use Cake\Controller\Controller;
  17. use Cake\Core\App;
  18. use Cake\Core\Configure;
  19. use Cake\Core\Plugin;
  20. use Cake\Error;
  21. use Cake\Error\ErrorHandler;
  22. use Cake\Error\ExceptionRenderer;
  23. use Cake\Error\PHP7ErrorException;
  24. use Cake\Log\Log;
  25. use Cake\Network\Exception\ForbiddenException;
  26. use Cake\Network\Exception\NotFoundException;
  27. use Cake\Network\Request;
  28. use Cake\Network\Response;
  29. use Cake\Routing\Exception\MissingControllerException;
  30. use Cake\Routing\Router;
  31. use Cake\TestSuite\TestCase;
  32. use ParseError;
  33. /**
  34. * Testing stub.
  35. */
  36. class TestErrorHandler extends ErrorHandler
  37. {
  38. /**
  39. * Access the response used.
  40. *
  41. * @var \Cake\Network\Response
  42. */
  43. public $response;
  44. /**
  45. * Stub output clearing in tests.
  46. *
  47. * @return void
  48. */
  49. protected function _clearOutput()
  50. {
  51. // noop
  52. }
  53. /**
  54. * Stub sending responses
  55. *
  56. * @return void
  57. */
  58. protected function _sendResponse($response)
  59. {
  60. $this->response = $response;
  61. }
  62. }
  63. /**
  64. * ErrorHandlerTest class
  65. */
  66. class ErrorHandlerTest extends TestCase
  67. {
  68. protected $_restoreError = false;
  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 Request();
  79. $request->base = '';
  80. Router::setRequestInfo($request);
  81. Configure::write('debug', true);
  82. $this->_logger = $this->getMock('Psr\Log\LoggerInterface');
  83. Log::reset();
  84. Log::config('error_test', [
  85. 'engine' => $this->_logger
  86. ]);
  87. }
  88. /**
  89. * tearDown
  90. *
  91. * @return void
  92. */
  93. public function tearDown()
  94. {
  95. parent::tearDown();
  96. Log::reset();
  97. if ($this->_restoreError) {
  98. restore_error_handler();
  99. restore_exception_handler();
  100. }
  101. }
  102. /**
  103. * test error handling when debug is on, an error should be printed from Debugger.
  104. *
  105. * @return void
  106. */
  107. public function testHandleErrorDebugOn()
  108. {
  109. $errorHandler = new ErrorHandler();
  110. $errorHandler->register();
  111. $this->_restoreError = true;
  112. ob_start();
  113. $wrong = $wrong + 1;
  114. $result = ob_get_clean();
  115. $this->assertRegExp('/<pre class="cake-error">/', $result);
  116. $this->assertRegExp('/<b>Notice<\/b>/', $result);
  117. $this->assertRegExp('/variable:\s+wrong/', $result);
  118. }
  119. /**
  120. * provides errors for mapping tests.
  121. *
  122. * @return void
  123. */
  124. public static function errorProvider()
  125. {
  126. return [
  127. [E_USER_NOTICE, 'Notice'],
  128. [E_USER_WARNING, 'Warning'],
  129. ];
  130. }
  131. /**
  132. * test error mappings
  133. *
  134. * @dataProvider errorProvider
  135. * @return void
  136. */
  137. public function testErrorMapping($error, $expected)
  138. {
  139. $errorHandler = new ErrorHandler();
  140. $errorHandler->register();
  141. $this->_restoreError = true;
  142. ob_start();
  143. trigger_error('Test error', $error);
  144. $result = ob_get_clean();
  145. $this->assertContains('<b>' . $expected . '</b>', $result);
  146. }
  147. /**
  148. * test error prepended by @
  149. *
  150. * @return void
  151. */
  152. public function testErrorSuppressed()
  153. {
  154. $errorHandler = new ErrorHandler();
  155. $errorHandler->register();
  156. $this->_restoreError = true;
  157. ob_start();
  158. //@codingStandardsIgnoreStart
  159. @include 'invalid.file';
  160. //@codingStandardsIgnoreEnd
  161. $result = ob_get_clean();
  162. $this->assertTrue(empty($result));
  163. }
  164. /**
  165. * Test that errors go into Cake Log when debug = 0.
  166. *
  167. * @return void
  168. */
  169. public function testHandleErrorDebugOff()
  170. {
  171. Configure::write('debug', false);
  172. $errorHandler = new ErrorHandler();
  173. $errorHandler->register();
  174. $this->_restoreError = true;
  175. $this->_logger->expects($this->once())
  176. ->method('log')
  177. ->with(
  178. $this->matchesRegularExpression('(notice|debug)'),
  179. 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ + 3) . ']' . "\n\n"
  180. );
  181. $out = $out + 1;
  182. }
  183. /**
  184. * Test that errors going into Cake Log include traces.
  185. *
  186. * @return void
  187. */
  188. public function testHandleErrorLoggingTrace()
  189. {
  190. Configure::write('debug', false);
  191. $errorHandler = new ErrorHandler(['trace' => true]);
  192. $errorHandler->register();
  193. $this->_restoreError = true;
  194. $this->_logger->expects($this->once())
  195. ->method('log')
  196. ->with(
  197. $this->matchesRegularExpression('(notice|debug)'),
  198. $this->logicalAnd(
  199. $this->stringContains('Notice (8): Undefined variable: out in '),
  200. $this->stringContains('Trace:'),
  201. $this->stringContains(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()')
  202. )
  203. );
  204. $out = $out + 1;
  205. }
  206. /**
  207. * test handleException generating a page.
  208. *
  209. * @return void
  210. */
  211. public function testHandleException()
  212. {
  213. $error = new NotFoundException('Kaboom!');
  214. $errorHandler = new TestErrorHandler();
  215. $errorHandler->handleException($error);
  216. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  217. }
  218. /**
  219. * test handleException generating log.
  220. *
  221. * @return void
  222. */
  223. public function testHandleExceptionLog()
  224. {
  225. $errorHandler = new TestErrorHandler([
  226. 'log' => true,
  227. 'trace' => true,
  228. ]);
  229. $error = new NotFoundException('Kaboom!');
  230. $this->_logger->expects($this->at(0))
  231. ->method('log')
  232. ->with('error', $this->logicalAnd(
  233. $this->stringContains('[Cake\Network\Exception\NotFoundException] Kaboom!'),
  234. $this->stringContains('ErrorHandlerTest->testHandleExceptionLog')
  235. ));
  236. $this->_logger->expects($this->at(1))
  237. ->method('log')
  238. ->with('error', $this->logicalAnd(
  239. $this->stringContains('[Cake\Network\Exception\NotFoundException] Kaboom!'),
  240. $this->logicalNot($this->stringContains('ErrorHandlerTest->testHandleExceptionLog'))
  241. ));
  242. $errorHandler->handleException($error);
  243. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  244. $errorHandler = new TestErrorHandler([
  245. 'log' => true,
  246. 'trace' => false,
  247. ]);
  248. $errorHandler->handleException($error);
  249. }
  250. /**
  251. * test logging attributes with/without debug
  252. *
  253. * @return void
  254. */
  255. public function testHandleExceptionLogAttributes()
  256. {
  257. $errorHandler = new TestErrorHandler([
  258. 'log' => true,
  259. 'trace' => true,
  260. ]);
  261. $error = new MissingControllerException(['class' => 'Derp']);
  262. $this->_logger->expects($this->at(0))
  263. ->method('log')
  264. ->with('error', $this->logicalAnd(
  265. $this->stringContains(
  266. '[Cake\Routing\Exception\MissingControllerException] ' .
  267. 'Controller class Derp could not be found.'
  268. ),
  269. $this->stringContains('Exception Attributes:')
  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. }