ErrorHandlerTest.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. $handler = ErrorHandler::register();
  61. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  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. $handler = ErrorHandler::register();
  124. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  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. ->will($this->returnCallback($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. ->will($this->returnCallback($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. try {
  240. $handler = ErrorHandler::register();
  241. $handler->throwAt(0, true);
  242. $e = null;
  243. $x = new \Exception('Foo');
  244. try {
  245. $f = new Fixtures\ToStringThrower($x);
  246. $f .= ''; // Trigger $f->__toString()
  247. } catch (\Exception $e) {
  248. }
  249. $this->assertSame($x, $e);
  250. } finally {
  251. restore_error_handler();
  252. restore_exception_handler();
  253. }
  254. }
  255. public function testHandleDeprecation()
  256. {
  257. $logArgCheck = function ($level, $message, $context) {
  258. $this->assertEquals(LogLevel::INFO, $level);
  259. $this->assertArrayHasKey('exception', $context);
  260. $exception = $context['exception'];
  261. $this->assertInstanceOf(\ErrorException::class, $exception);
  262. $this->assertSame('User Deprecated: Foo deprecation', $exception->getMessage());
  263. };
  264. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  265. $logger
  266. ->expects($this->once())
  267. ->method('log')
  268. ->will($this->returnCallback($logArgCheck))
  269. ;
  270. $handler = new ErrorHandler();
  271. $handler->setDefaultLogger($logger);
  272. @$handler->handleError(E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, []);
  273. restore_error_handler();
  274. }
  275. /**
  276. * @group no-hhvm
  277. */
  278. public function testHandleException()
  279. {
  280. try {
  281. $handler = ErrorHandler::register();
  282. $exception = new \Exception('foo');
  283. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  284. $logArgCheck = function ($level, $message, $context) {
  285. $this->assertSame('Uncaught Exception: foo', $message);
  286. $this->assertArrayHasKey('exception', $context);
  287. $this->assertInstanceOf(\Exception::class, $context['exception']);
  288. };
  289. $logger
  290. ->expects($this->exactly(2))
  291. ->method('log')
  292. ->will($this->returnCallback($logArgCheck))
  293. ;
  294. $handler->setDefaultLogger($logger, E_ERROR);
  295. try {
  296. $handler->handleException($exception);
  297. $this->fail('Exception expected');
  298. } catch (\Exception $e) {
  299. $this->assertSame($exception, $e);
  300. }
  301. $handler->setExceptionHandler(function ($e) use ($exception) {
  302. $this->assertSame($exception, $e);
  303. });
  304. $handler->handleException($exception);
  305. } finally {
  306. restore_error_handler();
  307. restore_exception_handler();
  308. }
  309. }
  310. /**
  311. * @group legacy
  312. */
  313. public function testErrorStacking()
  314. {
  315. try {
  316. $handler = ErrorHandler::register();
  317. $handler->screamAt(E_USER_WARNING);
  318. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  319. $logger
  320. ->expects($this->exactly(2))
  321. ->method('log')
  322. ->withConsecutive(
  323. [$this->equalTo(LogLevel::WARNING), $this->equalTo('Dummy log')],
  324. [$this->equalTo(LogLevel::DEBUG), $this->equalTo('User Warning: Silenced warning')]
  325. )
  326. ;
  327. $handler->setDefaultLogger($logger, [E_USER_WARNING => LogLevel::WARNING]);
  328. ErrorHandler::stackErrors();
  329. @trigger_error('Silenced warning', E_USER_WARNING);
  330. $logger->log(LogLevel::WARNING, 'Dummy log');
  331. ErrorHandler::unstackErrors();
  332. } finally {
  333. restore_error_handler();
  334. restore_exception_handler();
  335. }
  336. }
  337. public function testBootstrappingLogger()
  338. {
  339. $bootLogger = new BufferingLogger();
  340. $handler = new ErrorHandler($bootLogger);
  341. $loggers = [
  342. E_DEPRECATED => [$bootLogger, LogLevel::INFO],
  343. E_USER_DEPRECATED => [$bootLogger, LogLevel::INFO],
  344. E_NOTICE => [$bootLogger, LogLevel::WARNING],
  345. E_USER_NOTICE => [$bootLogger, LogLevel::WARNING],
  346. E_STRICT => [$bootLogger, LogLevel::WARNING],
  347. E_WARNING => [$bootLogger, LogLevel::WARNING],
  348. E_USER_WARNING => [$bootLogger, LogLevel::WARNING],
  349. E_COMPILE_WARNING => [$bootLogger, LogLevel::WARNING],
  350. E_CORE_WARNING => [$bootLogger, LogLevel::WARNING],
  351. E_USER_ERROR => [$bootLogger, LogLevel::CRITICAL],
  352. E_RECOVERABLE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  353. E_COMPILE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  354. E_PARSE => [$bootLogger, LogLevel::CRITICAL],
  355. E_ERROR => [$bootLogger, LogLevel::CRITICAL],
  356. E_CORE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  357. ];
  358. $this->assertSame($loggers, $handler->setLoggers([]));
  359. $handler->handleError(E_DEPRECATED, 'Foo message', __FILE__, 123, []);
  360. $logs = $bootLogger->cleanLogs();
  361. $this->assertCount(1, $logs);
  362. $log = $logs[0];
  363. $this->assertSame('info', $log[0]);
  364. $this->assertSame('Deprecated: Foo message', $log[1]);
  365. $this->assertArrayHasKey('exception', $log[2]);
  366. $exception = $log[2]['exception'];
  367. $this->assertInstanceOf(\ErrorException::class, $exception);
  368. $this->assertSame('Deprecated: Foo message', $exception->getMessage());
  369. $this->assertSame(__FILE__, $exception->getFile());
  370. $this->assertSame(123, $exception->getLine());
  371. $this->assertSame(E_DEPRECATED, $exception->getSeverity());
  372. $bootLogger->log(LogLevel::WARNING, 'Foo message', ['exception' => $exception]);
  373. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  374. $mockLogger->expects($this->once())
  375. ->method('log')
  376. ->with(LogLevel::WARNING, 'Foo message', ['exception' => $exception]);
  377. $handler->setLoggers([E_DEPRECATED => [$mockLogger, LogLevel::WARNING]]);
  378. }
  379. /**
  380. * @group no-hhvm
  381. */
  382. public function testSettingLoggerWhenExceptionIsBuffered()
  383. {
  384. $bootLogger = new BufferingLogger();
  385. $handler = new ErrorHandler($bootLogger);
  386. $exception = new \Exception('Foo message');
  387. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  388. $mockLogger->expects($this->once())
  389. ->method('log')
  390. ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', ['exception' => $exception]);
  391. $handler->setExceptionHandler(function () use ($handler, $mockLogger) {
  392. $handler->setDefaultLogger($mockLogger);
  393. });
  394. $handler->handleException($exception);
  395. }
  396. /**
  397. * @group no-hhvm
  398. */
  399. public function testHandleFatalError()
  400. {
  401. try {
  402. $handler = ErrorHandler::register();
  403. $error = [
  404. 'type' => E_PARSE,
  405. 'message' => 'foo',
  406. 'file' => 'bar',
  407. 'line' => 123,
  408. ];
  409. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  410. $logArgCheck = function ($level, $message, $context) {
  411. $this->assertEquals('Fatal Parse Error: foo', $message);
  412. $this->assertArrayHasKey('exception', $context);
  413. $this->assertInstanceOf(\Exception::class, $context['exception']);
  414. };
  415. $logger
  416. ->expects($this->once())
  417. ->method('log')
  418. ->will($this->returnCallback($logArgCheck))
  419. ;
  420. $handler->setDefaultLogger($logger, E_PARSE);
  421. $handler->handleFatalError($error);
  422. restore_error_handler();
  423. restore_exception_handler();
  424. } catch (\Exception $e) {
  425. restore_error_handler();
  426. restore_exception_handler();
  427. throw $e;
  428. }
  429. }
  430. /**
  431. * @requires PHP 7
  432. */
  433. public function testHandleErrorException()
  434. {
  435. $exception = new \Error("Class 'Foo' not found");
  436. $handler = new ErrorHandler();
  437. $handler->setExceptionHandler(function () use (&$args) {
  438. $args = \func_get_args();
  439. });
  440. $handler->handleException($exception);
  441. $this->assertInstanceOf('Symfony\Component\Debug\Exception\ClassNotFoundException', $args[0]);
  442. $this->assertStringStartsWith("Attempted to load class \"Foo\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
  443. }
  444. /**
  445. * @group no-hhvm
  446. */
  447. public function testHandleFatalErrorOnHHVM()
  448. {
  449. try {
  450. $handler = ErrorHandler::register();
  451. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  452. $logger
  453. ->expects($this->once())
  454. ->method('log')
  455. ->with(
  456. $this->equalTo(LogLevel::CRITICAL),
  457. $this->equalTo('Fatal Error: foo')
  458. )
  459. ;
  460. $handler->setDefaultLogger($logger, E_ERROR);
  461. $error = [
  462. 'type' => E_ERROR + 0x1000000, // This error level is used by HHVM for fatal errors
  463. 'message' => 'foo',
  464. 'file' => 'bar',
  465. 'line' => 123,
  466. 'context' => [123],
  467. 'backtrace' => [456],
  468. ];
  469. \call_user_func_array([$handler, 'handleError'], $error);
  470. $handler->handleFatalError($error);
  471. } finally {
  472. restore_error_handler();
  473. restore_exception_handler();
  474. }
  475. }
  476. /**
  477. * @expectedException \Exception
  478. * @group no-hhvm
  479. */
  480. public function testCustomExceptionHandler()
  481. {
  482. $handler = new ErrorHandler();
  483. $handler->setExceptionHandler(function ($e) use ($handler) {
  484. $handler->handleException($e);
  485. });
  486. $handler->handleException(new \Exception());
  487. }
  488. /**
  489. * @dataProvider errorHandlerWhenLoggingProvider
  490. */
  491. public function testErrorHandlerWhenLogging($previousHandlerWasDefined, $loggerSetsAnotherHandler, $nextHandlerIsDefined)
  492. {
  493. try {
  494. if ($previousHandlerWasDefined) {
  495. set_error_handler('count');
  496. }
  497. $logger = $loggerSetsAnotherHandler ? new LoggerThatSetAnErrorHandler() : new NullLogger();
  498. $handler = ErrorHandler::register();
  499. $handler->setDefaultLogger($logger);
  500. if ($nextHandlerIsDefined) {
  501. $handler = ErrorHandlerThatUsesThePreviousOne::register();
  502. }
  503. @trigger_error('foo', E_USER_DEPRECATED);
  504. @trigger_error('bar', E_USER_DEPRECATED);
  505. $this->assertSame([$handler, 'handleError'], set_error_handler('var_dump'));
  506. if ($logger instanceof LoggerThatSetAnErrorHandler) {
  507. $this->assertCount(2, $logger->cleanLogs());
  508. }
  509. restore_error_handler();
  510. if ($previousHandlerWasDefined) {
  511. restore_error_handler();
  512. }
  513. if ($nextHandlerIsDefined) {
  514. restore_error_handler();
  515. }
  516. } finally {
  517. restore_error_handler();
  518. restore_exception_handler();
  519. }
  520. }
  521. public function errorHandlerWhenLoggingProvider()
  522. {
  523. foreach ([false, true] as $previousHandlerWasDefined) {
  524. foreach ([false, true] as $loggerSetsAnotherHandler) {
  525. foreach ([false, true] as $nextHandlerIsDefined) {
  526. yield [$previousHandlerWasDefined, $loggerSetsAnotherHandler, $nextHandlerIsDefined];
  527. }
  528. }
  529. }
  530. }
  531. }