ErrorHandlerTest.php 20 KB

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