ErrorHandlerTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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\Log\Log;
  24. use Cake\Network\Exception\ForbiddenException;
  25. use Cake\Network\Exception\NotFoundException;
  26. use Cake\Network\Request;
  27. use Cake\Network\Response;
  28. use Cake\Routing\Exception\MissingControllerException;
  29. use Cake\Routing\Router;
  30. use Cake\TestSuite\TestCase;
  31. /**
  32. * Testing stub.
  33. */
  34. class TestErrorHandler extends ErrorHandler
  35. {
  36. /**
  37. * Access the response used.
  38. *
  39. * @var \Cake\Network\Response
  40. */
  41. public $response;
  42. /**
  43. * Stub output clearing in tests.
  44. *
  45. * @return void
  46. */
  47. protected function _clearOutput()
  48. {
  49. // noop
  50. }
  51. /**
  52. * Stub sending responses
  53. *
  54. * @return void
  55. */
  56. protected function _sendResponse($response)
  57. {
  58. $this->response = $response;
  59. }
  60. }
  61. /**
  62. * ErrorHandlerTest class
  63. */
  64. class ErrorHandlerTest extends TestCase
  65. {
  66. protected $_restoreError = false;
  67. /**
  68. * setup create a request object to get out of router later.
  69. *
  70. * @return void
  71. */
  72. public function setUp()
  73. {
  74. parent::setUp();
  75. Router::reload();
  76. $request = new Request();
  77. $request->base = '';
  78. Router::setRequestInfo($request);
  79. Configure::write('debug', true);
  80. $this->_logger = $this->getMock('Psr\Log\LoggerInterface');
  81. Log::reset();
  82. Log::config('error_test', [
  83. 'engine' => $this->_logger
  84. ]);
  85. }
  86. /**
  87. * tearDown
  88. *
  89. * @return void
  90. */
  91. public function tearDown()
  92. {
  93. parent::tearDown();
  94. Log::reset();
  95. if ($this->_restoreError) {
  96. restore_error_handler();
  97. restore_exception_handler();
  98. }
  99. }
  100. /**
  101. * test error handling when debug is on, an error should be printed from Debugger.
  102. *
  103. * @return void
  104. */
  105. public function testHandleErrorDebugOn()
  106. {
  107. $errorHandler = new ErrorHandler();
  108. $errorHandler->register();
  109. $this->_restoreError = true;
  110. ob_start();
  111. $wrong = $wrong + 1;
  112. $result = ob_get_clean();
  113. $this->assertRegExp('/<pre class="cake-error">/', $result);
  114. $this->assertRegExp('/<b>Notice<\/b>/', $result);
  115. $this->assertRegExp('/variable:\s+wrong/', $result);
  116. }
  117. /**
  118. * provides errors for mapping tests.
  119. *
  120. * @return void
  121. */
  122. public static function errorProvider()
  123. {
  124. return [
  125. [E_USER_NOTICE, 'Notice'],
  126. [E_USER_WARNING, 'Warning'],
  127. ];
  128. }
  129. /**
  130. * test error mappings
  131. *
  132. * @dataProvider errorProvider
  133. * @return void
  134. */
  135. public function testErrorMapping($error, $expected)
  136. {
  137. $errorHandler = new ErrorHandler();
  138. $errorHandler->register();
  139. $this->_restoreError = true;
  140. ob_start();
  141. trigger_error('Test error', $error);
  142. $result = ob_get_clean();
  143. $this->assertContains('<b>' . $expected . '</b>', $result);
  144. }
  145. /**
  146. * test error prepended by @
  147. *
  148. * @return void
  149. */
  150. public function testErrorSuppressed()
  151. {
  152. $errorHandler = new ErrorHandler();
  153. $errorHandler->register();
  154. $this->_restoreError = true;
  155. ob_start();
  156. //@codingStandardsIgnoreStart
  157. @include 'invalid.file';
  158. //@codingStandardsIgnoreEnd
  159. $result = ob_get_clean();
  160. $this->assertTrue(empty($result));
  161. }
  162. /**
  163. * Test that errors go into Cake Log when debug = 0.
  164. *
  165. * @return void
  166. */
  167. public function testHandleErrorDebugOff()
  168. {
  169. Configure::write('debug', false);
  170. $errorHandler = new ErrorHandler();
  171. $errorHandler->register();
  172. $this->_restoreError = true;
  173. $this->_logger->expects($this->once())
  174. ->method('log')
  175. ->with(
  176. $this->matchesRegularExpression('(notice|debug)'),
  177. 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ + 3) . ']' . "\n\n"
  178. );
  179. $out = $out + 1;
  180. }
  181. /**
  182. * Test that errors going into Cake Log include traces.
  183. *
  184. * @return void
  185. */
  186. public function testHandleErrorLoggingTrace()
  187. {
  188. Configure::write('debug', false);
  189. $errorHandler = new ErrorHandler(['trace' => true]);
  190. $errorHandler->register();
  191. $this->_restoreError = true;
  192. $this->_logger->expects($this->once())
  193. ->method('log')
  194. ->with(
  195. $this->matchesRegularExpression('(notice|debug)'),
  196. $this->logicalAnd(
  197. $this->stringContains('Notice (8): Undefined variable: out in '),
  198. $this->stringContains('Trace:'),
  199. $this->stringContains(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()')
  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. ));
  269. $this->_logger->expects($this->at(1))
  270. ->method('log')
  271. ->with('error', $this->logicalAnd(
  272. $this->stringContains(
  273. '[Cake\Routing\Exception\MissingControllerException] ' .
  274. 'Controller class Derp could not be found.'
  275. ),
  276. $this->logicalNot($this->stringContains('Exception Attributes:'))
  277. ));
  278. $errorHandler->handleException($error);
  279. Configure::write('debug', false);
  280. $errorHandler->handleException($error);
  281. }
  282. /**
  283. * test handleException generating log.
  284. *
  285. * @return void
  286. */
  287. public function testHandleExceptionLogSkipping()
  288. {
  289. $notFound = new NotFoundException('Kaboom!');
  290. $forbidden = new ForbiddenException('Fooled you!');
  291. $this->_logger->expects($this->once())
  292. ->method('log')
  293. ->with(
  294. 'error',
  295. $this->stringContains('[Cake\Network\Exception\ForbiddenException] Fooled you!')
  296. );
  297. $errorHandler = new TestErrorHandler([
  298. 'log' => true,
  299. 'skipLog' => ['Cake\Network\Exception\NotFoundException'],
  300. ]);
  301. $errorHandler->handleException($notFound);
  302. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  303. $errorHandler->handleException($forbidden);
  304. $this->assertContains('Fooled you!', $errorHandler->response->body(), 'message missing.');
  305. }
  306. /**
  307. * tests it is possible to load a plugin exception renderer
  308. *
  309. * @return void
  310. */
  311. public function testLoadPluginHandler()
  312. {
  313. Plugin::load('TestPlugin');
  314. $errorHandler = new TestErrorHandler([
  315. 'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer',
  316. ]);
  317. $error = new NotFoundException('Kaboom!');
  318. $errorHandler->handleException($error);
  319. $result = $errorHandler->response;
  320. $this->assertEquals('Rendered by test plugin', $result);
  321. }
  322. /**
  323. * test handleFatalError generating a page.
  324. *
  325. * These tests start two buffers as handleFatalError blows the outer one up.
  326. *
  327. * @return void
  328. */
  329. public function testHandleFatalErrorPage()
  330. {
  331. $line = __LINE__;
  332. $errorHandler = new TestErrorHandler();
  333. Configure::write('debug', true);
  334. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  335. $result = $errorHandler->response->body();
  336. $this->assertContains('Something wrong', $result, 'message missing.');
  337. $this->assertContains(__FILE__, $result, 'filename missing.');
  338. $this->assertContains((string)$line, $result, 'line missing.');
  339. Configure::write('debug', false);
  340. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  341. $result = $errorHandler->response->body();
  342. $this->assertNotContains('Something wrong', $result, 'message must not appear.');
  343. $this->assertNotContains(__FILE__, $result, 'filename must not appear.');
  344. $this->assertContains('An Internal Error Has Occurred.', $result);
  345. }
  346. /**
  347. * test handleFatalError generating log.
  348. *
  349. * @return void
  350. */
  351. public function testHandleFatalErrorLog()
  352. {
  353. $this->_logger->expects($this->at(0))
  354. ->method('log')
  355. ->with('error', $this->logicalAnd(
  356. $this->stringContains(__FILE__ . ', line ' . (__LINE__ + 9)),
  357. $this->stringContains('Fatal Error (1)'),
  358. $this->stringContains('Something wrong')
  359. ));
  360. $this->_logger->expects($this->at(1))
  361. ->method('log')
  362. ->with('error', $this->stringContains('[Cake\Error\FatalErrorException] Something wrong'));
  363. $errorHandler = new TestErrorHandler(['log' => true]);
  364. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
  365. }
  366. }