ErrorHandlerTest.php 8.5 KB

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