ErrorHandlerTest.php 19 KB

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