ErrorHandlerTest.php 13 KB

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