ErrorHandlerTest.php 22 KB

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