ErrorHandlerTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. /**
  3. * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
  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://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
  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\Router;
  29. use Cake\TestSuite\TestCase;
  30. /**
  31. * Testing stub.
  32. */
  33. class TestErrorHandler extends ErrorHandler
  34. {
  35. /**
  36. * Access the response used.
  37. *
  38. * @var \Cake\Network\Response
  39. */
  40. public $response;
  41. /**
  42. * Stub output clearing in tests.
  43. *
  44. * @return void
  45. */
  46. protected function _clearOutput()
  47. {
  48. // noop
  49. }
  50. /**
  51. * Stub sending responses
  52. *
  53. * @return void
  54. */
  55. protected function _sendResponse($response)
  56. {
  57. $this->response = $response;
  58. }
  59. }
  60. /**
  61. * ErrorHandlerTest class
  62. */
  63. class ErrorHandlerTest extends TestCase
  64. {
  65. protected $_restoreError = false;
  66. /**
  67. * setup create a request object to get out of router later.
  68. *
  69. * @return void
  70. */
  71. public function setUp()
  72. {
  73. parent::setUp();
  74. Router::reload();
  75. $request = new Request();
  76. $request->base = '';
  77. Router::setRequestInfo($request);
  78. Configure::write('debug', true);
  79. $this->_logger = $this->getMock('Psr\Log\LoggerInterface');
  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->assertTrue(empty($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. )
  200. );
  201. $out = $out + 1;
  202. }
  203. /**
  204. * test handleException generating a page.
  205. *
  206. * @return void
  207. */
  208. public function testHandleException()
  209. {
  210. $error = new NotFoundException('Kaboom!');
  211. $errorHandler = new TestErrorHandler();
  212. $errorHandler->handleException($error);
  213. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  214. }
  215. /**
  216. * test handleException generating log.
  217. *
  218. * @return void
  219. */
  220. public function testHandleExceptionLog()
  221. {
  222. $errorHandler = new TestErrorHandler([
  223. 'log' => true,
  224. ]);
  225. $error = new NotFoundException('Kaboom!');
  226. $this->_logger->expects($this->once())
  227. ->method('log')
  228. ->with('error', $this->logicalAnd(
  229. $this->stringContains('[Cake\Network\Exception\NotFoundException] Kaboom!'),
  230. $this->stringContains('ErrorHandlerTest->testHandleExceptionLog')
  231. ));
  232. $errorHandler->handleException($error);
  233. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  234. }
  235. /**
  236. * test handleException generating log.
  237. *
  238. * @return void
  239. */
  240. public function testHandleExceptionLogSkipping()
  241. {
  242. $notFound = new NotFoundException('Kaboom!');
  243. $forbidden = new ForbiddenException('Fooled you!');
  244. $this->_logger->expects($this->once())
  245. ->method('log')
  246. ->with(
  247. 'error',
  248. $this->stringContains('[Cake\Network\Exception\ForbiddenException] Fooled you!')
  249. );
  250. $errorHandler = new TestErrorHandler([
  251. 'log' => true,
  252. 'skipLog' => ['Cake\Network\Exception\NotFoundException'],
  253. ]);
  254. $errorHandler->handleException($notFound);
  255. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  256. $errorHandler->handleException($forbidden);
  257. $this->assertContains('Fooled you!', $errorHandler->response->body(), 'message missing.');
  258. }
  259. /**
  260. * tests it is possible to load a plugin exception renderer
  261. *
  262. * @return void
  263. */
  264. public function testLoadPluginHandler()
  265. {
  266. Plugin::load('TestPlugin');
  267. $errorHandler = new TestErrorHandler([
  268. 'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer',
  269. ]);
  270. $error = new NotFoundException('Kaboom!');
  271. $errorHandler->handleException($error);
  272. $result = $errorHandler->response;
  273. $this->assertEquals('Rendered by test plugin', $result);
  274. }
  275. /**
  276. * test handleFatalError generating a page.
  277. *
  278. * These tests start two buffers as handleFatalError blows the outer one up.
  279. *
  280. * @return void
  281. */
  282. public function testHandleFatalErrorPage()
  283. {
  284. $line = __LINE__;
  285. $errorHandler = new TestErrorHandler();
  286. Configure::write('debug', true);
  287. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  288. $result = $errorHandler->response->body();
  289. $this->assertContains('Something wrong', $result, 'message missing.');
  290. $this->assertContains(__FILE__, $result, 'filename missing.');
  291. $this->assertContains((string)$line, $result, 'line missing.');
  292. Configure::write('debug', false);
  293. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  294. $result = $errorHandler->response->body();
  295. $this->assertNotContains('Something wrong', $result, 'message must not appear.');
  296. $this->assertNotContains(__FILE__, $result, 'filename must not appear.');
  297. $this->assertContains('An Internal Error Has Occurred', $result);
  298. }
  299. /**
  300. * test handleFatalError generating log.
  301. *
  302. * @return void
  303. */
  304. public function testHandleFatalErrorLog()
  305. {
  306. $this->_logger->expects($this->at(0))
  307. ->method('log')
  308. ->with('error', $this->logicalAnd(
  309. $this->stringContains(__FILE__ . ', line ' . (__LINE__ + 9)),
  310. $this->stringContains('Fatal Error (1)'),
  311. $this->stringContains('Something wrong')
  312. ));
  313. $this->_logger->expects($this->at(1))
  314. ->method('log')
  315. ->with('error', $this->stringContains('[Cake\Error\FatalErrorException] Something wrong'));
  316. $errorHandler = new TestErrorHandler(['log' => true]);
  317. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
  318. }
  319. }