ErrorHandlerTest.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. * Access the response used.
  36. *
  37. * @var \Cake\Network\Response
  38. */
  39. public $response;
  40. /**
  41. * Stub output clearing in tests.
  42. *
  43. * @return void
  44. */
  45. protected function _clearOutput() {
  46. // noop
  47. }
  48. /**
  49. * Stub sending responses
  50. *
  51. * @return void
  52. */
  53. protected function _sendResponse($response) {
  54. $this->response = $response;
  55. }
  56. }
  57. /**
  58. * ErrorHandlerTest class
  59. */
  60. class ErrorHandlerTest extends TestCase {
  61. protected $_restoreError = false;
  62. /**
  63. * setup create a request object to get out of router later.
  64. *
  65. * @return void
  66. */
  67. public function setUp() {
  68. parent::setUp();
  69. Router::reload();
  70. $request = new Request();
  71. $request->base = '';
  72. Router::setRequestInfo($request);
  73. Configure::write('debug', true);
  74. $this->_logger = $this->getMock('Psr\Log\LoggerInterface');
  75. Log::reset();
  76. Log::config('error_test', [
  77. 'engine' => $this->_logger
  78. ]);
  79. }
  80. /**
  81. * tearDown
  82. *
  83. * @return void
  84. */
  85. public function tearDown() {
  86. parent::tearDown();
  87. Log::reset();
  88. if ($this->_restoreError) {
  89. restore_error_handler();
  90. restore_exception_handler();
  91. }
  92. }
  93. /**
  94. * test error handling when debug is on, an error should be printed from Debugger.
  95. *
  96. * @return void
  97. */
  98. public function testHandleErrorDebugOn() {
  99. $errorHandler = new ErrorHandler();
  100. $errorHandler->register();
  101. $this->_restoreError = true;
  102. ob_start();
  103. $wrong .= '';
  104. $result = ob_get_clean();
  105. $this->assertRegExp('/<pre class="cake-error">/', $result);
  106. $this->assertRegExp('/<b>Notice<\/b>/', $result);
  107. $this->assertRegExp('/variable:\s+wrong/', $result);
  108. }
  109. /**
  110. * provides errors for mapping tests.
  111. *
  112. * @return void
  113. */
  114. public static function errorProvider() {
  115. return array(
  116. array(E_USER_NOTICE, 'Notice'),
  117. array(E_USER_WARNING, 'Warning'),
  118. );
  119. }
  120. /**
  121. * test error mappings
  122. *
  123. * @dataProvider errorProvider
  124. * @return void
  125. */
  126. public function testErrorMapping($error, $expected) {
  127. $errorHandler = new ErrorHandler();
  128. $errorHandler->register();
  129. $this->_restoreError = true;
  130. ob_start();
  131. trigger_error('Test error', $error);
  132. $result = ob_get_clean();
  133. $this->assertContains('<b>' . $expected . '</b>', $result);
  134. }
  135. /**
  136. * test error prepended by @
  137. *
  138. * @return void
  139. */
  140. public function testErrorSuppressed() {
  141. $errorHandler = new ErrorHandler();
  142. $errorHandler->register();
  143. $this->_restoreError = true;
  144. ob_start();
  145. //@codingStandardsIgnoreStart
  146. @include 'invalid.file';
  147. //@codingStandardsIgnoreEnd
  148. $result = ob_get_clean();
  149. $this->assertTrue(empty($result));
  150. }
  151. /**
  152. * Test that errors go into Cake Log when debug = 0.
  153. *
  154. * @return void
  155. */
  156. public function testHandleErrorDebugOff() {
  157. Configure::write('debug', false);
  158. $errorHandler = new ErrorHandler();
  159. $errorHandler->register();
  160. $this->_restoreError = true;
  161. $this->_logger->expects($this->once())
  162. ->method('log')
  163. ->with(
  164. $this->matchesRegularExpression('(notice|debug)'),
  165. 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ + 3) . ']' . "\n\n"
  166. );
  167. $out .= '';
  168. }
  169. /**
  170. * Test that errors going into Cake Log include traces.
  171. *
  172. * @return void
  173. */
  174. public function testHandleErrorLoggingTrace() {
  175. Configure::write('debug', false);
  176. $errorHandler = new ErrorHandler(['trace' => true]);
  177. $errorHandler->register();
  178. $this->_restoreError = true;
  179. $this->_logger->expects($this->once())
  180. ->method('log')
  181. ->with(
  182. $this->matchesRegularExpression('(notice|debug)'),
  183. $this->logicalAnd(
  184. $this->stringContains('Notice (8): Undefined variable: out in '),
  185. $this->stringContains('Trace:'),
  186. $this->stringContains(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()')
  187. )
  188. );
  189. $out .= '';
  190. }
  191. /**
  192. * test handleException generating a page.
  193. *
  194. * @return void
  195. */
  196. public function testHandleException() {
  197. $error = new NotFoundException('Kaboom!');
  198. $errorHandler = new TestErrorHandler();
  199. $errorHandler->handleException($error);
  200. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  201. }
  202. /**
  203. * test handleException generating log.
  204. *
  205. * @return void
  206. */
  207. public function testHandleExceptionLog() {
  208. $errorHandler = new TestErrorHandler([
  209. 'log' => true,
  210. ]);
  211. $error = new NotFoundException('Kaboom!');
  212. $this->_logger->expects($this->once())
  213. ->method('log')
  214. ->with('error', $this->logicalAnd(
  215. $this->stringContains('[Cake\Network\Exception\NotFoundException] Kaboom!'),
  216. $this->stringContains('ErrorHandlerTest->testHandleExceptionLog')
  217. ));
  218. $errorHandler->handleException($error);
  219. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  220. }
  221. /**
  222. * test handleException generating log.
  223. *
  224. * @return void
  225. */
  226. public function testHandleExceptionLogSkipping() {
  227. $notFound = new NotFoundException('Kaboom!');
  228. $forbidden = new ForbiddenException('Fooled you!');
  229. $this->_logger->expects($this->once())
  230. ->method('log')
  231. ->with(
  232. 'error',
  233. $this->stringContains('[Cake\Network\Exception\ForbiddenException] Fooled you!')
  234. );
  235. $errorHandler = new TestErrorHandler([
  236. 'log' => true,
  237. 'skipLog' => ['Cake\Network\Exception\NotFoundException'],
  238. ]);
  239. $errorHandler->handleException($notFound);
  240. $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
  241. $errorHandler->handleException($forbidden);
  242. $this->assertContains('Fooled you!', $errorHandler->response->body(), 'message missing.');
  243. }
  244. /**
  245. * tests it is possible to load a plugin exception renderer
  246. *
  247. * @return void
  248. */
  249. public function testLoadPluginHandler() {
  250. Plugin::load('TestPlugin');
  251. $errorHandler = new TestErrorHandler([
  252. 'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer',
  253. ]);
  254. $error = new NotFoundException('Kaboom!');
  255. $errorHandler->handleException($error);
  256. $result = $errorHandler->response;
  257. $this->assertEquals('Rendered by test plugin', $result);
  258. }
  259. /**
  260. * test handleFatalError generating a page.
  261. *
  262. * These tests start two buffers as handleFatalError blows the outer one up.
  263. *
  264. * @return void
  265. */
  266. public function testHandleFatalErrorPage() {
  267. $line = __LINE__;
  268. $errorHandler = new TestErrorHandler();
  269. Configure::write('debug', true);
  270. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  271. $result = $errorHandler->response->body();
  272. $this->assertContains('Something wrong', $result, 'message missing.');
  273. $this->assertContains(__FILE__, $result, 'filename missing.');
  274. $this->assertContains((string)$line, $result, 'line missing.');
  275. Configure::write('debug', false);
  276. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
  277. $result = $errorHandler->response->body();
  278. $this->assertNotContains('Something wrong', $result, 'message must not appear.');
  279. $this->assertNotContains(__FILE__, $result, 'filename must not appear.');
  280. $this->assertContains('An Internal Error Has Occurred', $result);
  281. }
  282. /**
  283. * test handleFatalError generating log.
  284. *
  285. * @return void
  286. */
  287. public function testHandleFatalErrorLog() {
  288. $this->_logger->expects($this->at(0))
  289. ->method('log')
  290. ->with('error', $this->logicalAnd(
  291. $this->stringContains(__FILE__ . ', line ' . (__LINE__ + 9)),
  292. $this->stringContains('Fatal Error (1)'),
  293. $this->stringContains('Something wrong')
  294. ));
  295. $this->_logger->expects($this->at(1))
  296. ->method('log')
  297. ->with('error', $this->stringContains('[Cake\Error\FatalErrorException] Something wrong'));
  298. $errorHandler = new TestErrorHandler(['log' => true]);
  299. $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
  300. }
  301. }