ErrorHandlerTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Debug\Tests;
  11. use Psr\Log\LogLevel;
  12. use Symfony\Component\Debug\ErrorHandler;
  13. use Symfony\Component\Debug\BufferingLogger;
  14. use Symfony\Component\Debug\Exception\ContextErrorException;
  15. /**
  16. * ErrorHandlerTest.
  17. *
  18. * @author Robert Schönthal <seroscho@googlemail.com>
  19. * @author Nicolas Grekas <p@tchwork.com>
  20. */
  21. class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
  22. {
  23. public function testRegister()
  24. {
  25. $handler = ErrorHandler::register();
  26. try {
  27. $this->assertInstanceOf('Symfony\Component\Debug\ErrorHandler', $handler);
  28. $this->assertSame($handler, ErrorHandler::register());
  29. $newHandler = new ErrorHandler();
  30. $this->assertSame($newHandler, ErrorHandler::register($newHandler, false));
  31. $h = set_error_handler('var_dump');
  32. restore_error_handler();
  33. $this->assertSame(array($handler, 'handleError'), $h);
  34. try {
  35. $this->assertSame($newHandler, ErrorHandler::register($newHandler, true));
  36. $h = set_error_handler('var_dump');
  37. restore_error_handler();
  38. $this->assertSame(array($newHandler, 'handleError'), $h);
  39. } catch (\Exception $e) {
  40. }
  41. restore_error_handler();
  42. restore_exception_handler();
  43. if (isset($e)) {
  44. throw $e;
  45. }
  46. } catch (\Exception $e) {
  47. }
  48. restore_error_handler();
  49. restore_exception_handler();
  50. if (isset($e)) {
  51. throw $e;
  52. }
  53. }
  54. public function testNotice()
  55. {
  56. ErrorHandler::register();
  57. try {
  58. self::triggerNotice($this);
  59. $this->fail('ContextErrorException expected');
  60. } catch (ContextErrorException $exception) {
  61. // if an exception is thrown, the test passed
  62. $this->assertEquals(E_NOTICE, $exception->getSeverity());
  63. $this->assertEquals(__FILE__, $exception->getFile());
  64. $this->assertRegExp('/^Notice: Undefined variable: (foo|bar)/', $exception->getMessage());
  65. $this->assertArrayHasKey('foobar', $exception->getContext());
  66. $trace = $exception->getTrace();
  67. $this->assertEquals(__FILE__, $trace[0]['file']);
  68. $this->assertEquals('Symfony\Component\Debug\ErrorHandler', $trace[0]['class']);
  69. $this->assertEquals('handleError', $trace[0]['function']);
  70. $this->assertEquals('->', $trace[0]['type']);
  71. $this->assertEquals(__FILE__, $trace[1]['file']);
  72. $this->assertEquals(__CLASS__, $trace[1]['class']);
  73. $this->assertEquals('triggerNotice', $trace[1]['function']);
  74. $this->assertEquals('::', $trace[1]['type']);
  75. $this->assertEquals(__FILE__, $trace[1]['file']);
  76. $this->assertEquals(__CLASS__, $trace[2]['class']);
  77. $this->assertEquals(__FUNCTION__, $trace[2]['function']);
  78. $this->assertEquals('->', $trace[2]['type']);
  79. } finally {
  80. restore_error_handler();
  81. restore_exception_handler();
  82. }
  83. }
  84. // dummy function to test trace in error handler.
  85. private static function triggerNotice($that)
  86. {
  87. // dummy variable to check for in error handler.
  88. $foobar = 123;
  89. $that->assertSame('', $foo.$foo.$bar);
  90. }
  91. public function testConstruct()
  92. {
  93. try {
  94. $handler = ErrorHandler::register();
  95. $handler->throwAt(3, true);
  96. $this->assertEquals(3 | E_RECOVERABLE_ERROR | E_USER_ERROR, $handler->throwAt(0));
  97. } finally {
  98. restore_error_handler();
  99. restore_exception_handler();
  100. }
  101. }
  102. public function testDefaultLogger()
  103. {
  104. try {
  105. $handler = ErrorHandler::register();
  106. $logger = $this->getMock('Psr\Log\LoggerInterface');
  107. $handler->setDefaultLogger($logger, E_NOTICE);
  108. $handler->setDefaultLogger($logger, array(E_USER_NOTICE => LogLevel::CRITICAL));
  109. $loggers = array(
  110. E_DEPRECATED => array(null, LogLevel::INFO),
  111. E_USER_DEPRECATED => array(null, LogLevel::INFO),
  112. E_NOTICE => array($logger, LogLevel::WARNING),
  113. E_USER_NOTICE => array($logger, LogLevel::CRITICAL),
  114. E_STRICT => array(null, LogLevel::WARNING),
  115. E_WARNING => array(null, LogLevel::WARNING),
  116. E_USER_WARNING => array(null, LogLevel::WARNING),
  117. E_COMPILE_WARNING => array(null, LogLevel::WARNING),
  118. E_CORE_WARNING => array(null, LogLevel::WARNING),
  119. E_USER_ERROR => array(null, LogLevel::CRITICAL),
  120. E_RECOVERABLE_ERROR => array(null, LogLevel::CRITICAL),
  121. E_COMPILE_ERROR => array(null, LogLevel::CRITICAL),
  122. E_PARSE => array(null, LogLevel::CRITICAL),
  123. E_ERROR => array(null, LogLevel::CRITICAL),
  124. E_CORE_ERROR => array(null, LogLevel::CRITICAL),
  125. );
  126. $this->assertSame($loggers, $handler->setLoggers(array()));
  127. } finally {
  128. restore_error_handler();
  129. restore_exception_handler();
  130. }
  131. }
  132. public function testHandleError()
  133. {
  134. try {
  135. $handler = ErrorHandler::register();
  136. $handler->throwAt(0, true);
  137. $this->assertFalse($handler->handleError(0, 'foo', 'foo.php', 12, array()));
  138. restore_error_handler();
  139. restore_exception_handler();
  140. $handler = ErrorHandler::register();
  141. $handler->throwAt(3, true);
  142. $this->assertFalse($handler->handleError(4, 'foo', 'foo.php', 12, array()));
  143. restore_error_handler();
  144. restore_exception_handler();
  145. $handler = ErrorHandler::register();
  146. $handler->throwAt(3, true);
  147. try {
  148. $handler->handleError(4, 'foo', 'foo.php', 12, array());
  149. } catch (\ErrorException $e) {
  150. $this->assertSame('Parse Error: foo', $e->getMessage());
  151. $this->assertSame(4, $e->getSeverity());
  152. $this->assertSame('foo.php', $e->getFile());
  153. $this->assertSame(12, $e->getLine());
  154. }
  155. restore_error_handler();
  156. restore_exception_handler();
  157. $handler = ErrorHandler::register();
  158. $handler->throwAt(E_USER_DEPRECATED, true);
  159. $this->assertFalse($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, array()));
  160. restore_error_handler();
  161. restore_exception_handler();
  162. $handler = ErrorHandler::register();
  163. $handler->throwAt(E_DEPRECATED, true);
  164. $this->assertFalse($handler->handleError(E_DEPRECATED, 'foo', 'foo.php', 12, array()));
  165. restore_error_handler();
  166. restore_exception_handler();
  167. $logger = $this->getMock('Psr\Log\LoggerInterface');
  168. $warnArgCheck = function ($logLevel, $message, $context) {
  169. $this->assertEquals('info', $logLevel);
  170. $this->assertEquals('foo', $message);
  171. $this->assertArrayHasKey('type', $context);
  172. $this->assertEquals($context['type'], E_USER_DEPRECATED);
  173. $this->assertArrayHasKey('stack', $context);
  174. $this->assertInternalType('array', $context['stack']);
  175. };
  176. $logger
  177. ->expects($this->once())
  178. ->method('log')
  179. ->will($this->returnCallback($warnArgCheck))
  180. ;
  181. $handler = ErrorHandler::register();
  182. $handler->setDefaultLogger($logger, E_USER_DEPRECATED);
  183. $this->assertTrue($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, array()));
  184. restore_error_handler();
  185. restore_exception_handler();
  186. $logger = $this->getMock('Psr\Log\LoggerInterface');
  187. $logArgCheck = function ($level, $message, $context) {
  188. $this->assertEquals('Undefined variable: undefVar', $message);
  189. $this->assertArrayHasKey('type', $context);
  190. $this->assertEquals($context['type'], E_NOTICE);
  191. };
  192. $logger
  193. ->expects($this->once())
  194. ->method('log')
  195. ->will($this->returnCallback($logArgCheck))
  196. ;
  197. $handler = ErrorHandler::register();
  198. $handler->setDefaultLogger($logger, E_NOTICE);
  199. $handler->screamAt(E_NOTICE);
  200. unset($undefVar);
  201. @$undefVar++;
  202. restore_error_handler();
  203. restore_exception_handler();
  204. } catch (\Exception $e) {
  205. restore_error_handler();
  206. restore_exception_handler();
  207. throw $e;
  208. }
  209. }
  210. public function testHandleUserError()
  211. {
  212. try {
  213. $handler = ErrorHandler::register();
  214. $handler->throwAt(0, true);
  215. $e = null;
  216. $x = new \Exception('Foo');
  217. try {
  218. $f = new Fixtures\ToStringThrower($x);
  219. $f .= ''; // Trigger $f->__toString()
  220. } catch (\Exception $e) {
  221. }
  222. $this->assertSame($x, $e);
  223. } finally {
  224. restore_error_handler();
  225. restore_exception_handler();
  226. }
  227. }
  228. public function testHandleDeprecation()
  229. {
  230. $logArgCheck = function ($level, $message, $context) {
  231. $this->assertEquals(LogLevel::INFO, $level);
  232. $this->assertArrayHasKey('level', $context);
  233. $this->assertEquals(E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED, $context['level']);
  234. $this->assertArrayHasKey('stack', $context);
  235. };
  236. $logger = $this->getMock('Psr\Log\LoggerInterface');
  237. $logger
  238. ->expects($this->once())
  239. ->method('log')
  240. ->will($this->returnCallback($logArgCheck))
  241. ;
  242. $handler = new ErrorHandler();
  243. $handler->setDefaultLogger($logger);
  244. @$handler->handleError(E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, array());
  245. }
  246. public function testHandleException()
  247. {
  248. try {
  249. $handler = ErrorHandler::register();
  250. $exception = new \Exception('foo');
  251. $logger = $this->getMock('Psr\Log\LoggerInterface');
  252. $logArgCheck = function ($level, $message, $context) {
  253. $this->assertEquals('Uncaught Exception: foo', $message);
  254. $this->assertArrayHasKey('type', $context);
  255. $this->assertEquals($context['type'], E_ERROR);
  256. };
  257. $logger
  258. ->expects($this->exactly(2))
  259. ->method('log')
  260. ->will($this->returnCallback($logArgCheck))
  261. ;
  262. $handler->setDefaultLogger($logger, E_ERROR);
  263. try {
  264. $handler->handleException($exception);
  265. $this->fail('Exception expected');
  266. } catch (\Exception $e) {
  267. $this->assertSame($exception, $e);
  268. }
  269. $handler->setExceptionHandler(function ($e) use ($exception) {
  270. $this->assertSame($exception, $e);
  271. });
  272. $handler->handleException($exception);
  273. } finally {
  274. restore_error_handler();
  275. restore_exception_handler();
  276. }
  277. }
  278. public function testErrorStacking()
  279. {
  280. try {
  281. $handler = ErrorHandler::register();
  282. $handler->screamAt(E_USER_WARNING);
  283. $logger = $this->getMock('Psr\Log\LoggerInterface');
  284. $logger
  285. ->expects($this->exactly(2))
  286. ->method('log')
  287. ->withConsecutive(
  288. array($this->equalTo(LogLevel::WARNING), $this->equalTo('Dummy log')),
  289. array($this->equalTo(LogLevel::DEBUG), $this->equalTo('Silenced warning'))
  290. )
  291. ;
  292. $handler->setDefaultLogger($logger, array(E_USER_WARNING => LogLevel::WARNING));
  293. ErrorHandler::stackErrors();
  294. @trigger_error('Silenced warning', E_USER_WARNING);
  295. $logger->log(LogLevel::WARNING, 'Dummy log');
  296. ErrorHandler::unstackErrors();
  297. } finally {
  298. restore_error_handler();
  299. restore_exception_handler();
  300. }
  301. }
  302. public function testBootstrappingLogger()
  303. {
  304. $bootLogger = new BufferingLogger();
  305. $handler = new ErrorHandler($bootLogger);
  306. $loggers = array(
  307. E_DEPRECATED => array($bootLogger, LogLevel::INFO),
  308. E_USER_DEPRECATED => array($bootLogger, LogLevel::INFO),
  309. E_NOTICE => array($bootLogger, LogLevel::WARNING),
  310. E_USER_NOTICE => array($bootLogger, LogLevel::WARNING),
  311. E_STRICT => array($bootLogger, LogLevel::WARNING),
  312. E_WARNING => array($bootLogger, LogLevel::WARNING),
  313. E_USER_WARNING => array($bootLogger, LogLevel::WARNING),
  314. E_COMPILE_WARNING => array($bootLogger, LogLevel::WARNING),
  315. E_CORE_WARNING => array($bootLogger, LogLevel::WARNING),
  316. E_USER_ERROR => array($bootLogger, LogLevel::CRITICAL),
  317. E_RECOVERABLE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  318. E_COMPILE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  319. E_PARSE => array($bootLogger, LogLevel::CRITICAL),
  320. E_ERROR => array($bootLogger, LogLevel::CRITICAL),
  321. E_CORE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  322. );
  323. $this->assertSame($loggers, $handler->setLoggers(array()));
  324. $handler->handleError(E_DEPRECATED, 'Foo message', __FILE__, 123, array());
  325. $expectedLog = array(LogLevel::INFO, 'Foo message', array('type' => E_DEPRECATED, 'file' => __FILE__, 'line' => 123, 'level' => error_reporting()));
  326. $logs = $bootLogger->cleanLogs();
  327. unset($logs[0][2]['stack']);
  328. $this->assertSame(array($expectedLog), $logs);
  329. $bootLogger->log($expectedLog[0], $expectedLog[1], $expectedLog[2]);
  330. $mockLogger = $this->getMock('Psr\Log\LoggerInterface');
  331. $mockLogger->expects($this->once())
  332. ->method('log')
  333. ->with(LogLevel::WARNING, 'Foo message', $expectedLog[2]);
  334. $handler->setLoggers(array(E_DEPRECATED => array($mockLogger, LogLevel::WARNING)));
  335. }
  336. public function testHandleFatalError()
  337. {
  338. try {
  339. $handler = ErrorHandler::register();
  340. $error = array(
  341. 'type' => E_PARSE,
  342. 'message' => 'foo',
  343. 'file' => 'bar',
  344. 'line' => 123,
  345. );
  346. $logger = $this->getMock('Psr\Log\LoggerInterface');
  347. $logArgCheck = function ($level, $message, $context) {
  348. $this->assertEquals('Fatal Parse Error: foo', $message);
  349. $this->assertArrayHasKey('type', $context);
  350. $this->assertEquals($context['type'], E_PARSE);
  351. };
  352. $logger
  353. ->expects($this->once())
  354. ->method('log')
  355. ->will($this->returnCallback($logArgCheck))
  356. ;
  357. $handler->setDefaultLogger($logger, E_PARSE);
  358. $handler->handleFatalError($error);
  359. restore_error_handler();
  360. restore_exception_handler();
  361. } catch (\Exception $e) {
  362. restore_error_handler();
  363. restore_exception_handler();
  364. throw $e;
  365. }
  366. }
  367. /**
  368. * @requires PHP 7
  369. */
  370. public function testHandleErrorException()
  371. {
  372. $exception = new \Error("Class 'Foo' not found");
  373. $handler = new ErrorHandler();
  374. $handler->setExceptionHandler(function () use (&$args) {
  375. $args = func_get_args();
  376. });
  377. $handler->handleException($exception);
  378. $this->assertInstanceOf('Symfony\Component\Debug\Exception\ClassNotFoundException', $args[0]);
  379. $this->assertStringStartsWith("Attempted to load class \"Foo\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
  380. }
  381. public function testHandleFatalErrorOnHHVM()
  382. {
  383. try {
  384. $handler = ErrorHandler::register();
  385. $logger = $this->getMock('Psr\Log\LoggerInterface');
  386. $logger
  387. ->expects($this->once())
  388. ->method('log')
  389. ->with(
  390. $this->equalTo(LogLevel::CRITICAL),
  391. $this->equalTo('Fatal Error: foo'),
  392. $this->equalTo(array(
  393. 'type' => 1,
  394. 'file' => 'bar',
  395. 'line' => 123,
  396. 'level' => -1,
  397. 'stack' => array(456),
  398. ))
  399. )
  400. ;
  401. $handler->setDefaultLogger($logger, E_ERROR);
  402. $error = array(
  403. 'type' => E_ERROR + 0x1000000, // This error level is used by HHVM for fatal errors
  404. 'message' => 'foo',
  405. 'file' => 'bar',
  406. 'line' => 123,
  407. 'context' => array(123),
  408. 'backtrace' => array(456),
  409. );
  410. call_user_func_array(array($handler, 'handleError'), $error);
  411. $handler->handleFatalError($error);
  412. } finally {
  413. restore_error_handler();
  414. restore_exception_handler();
  415. }
  416. }
  417. }