ErrorHandlerTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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($newHandler, 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 testNotice()
  56. {
  57. ErrorHandler::register();
  58. try {
  59. self::triggerNotice($this);
  60. $this->fail('ErrorException expected');
  61. } catch (\ErrorException $exception) {
  62. // if an exception is thrown, the test passed
  63. $this->assertEquals(E_NOTICE, $exception->getSeverity());
  64. $this->assertEquals(__FILE__, $exception->getFile());
  65. $this->assertRegExp('/^Notice: Undefined variable: (foo|bar)/', $exception->getMessage());
  66. $trace = $exception->getTrace();
  67. $this->assertEquals(__FILE__, $trace[0]['file']);
  68. $this->assertEquals(__CLASS__, $trace[0]['class']);
  69. $this->assertEquals('triggerNotice', $trace[0]['function']);
  70. $this->assertEquals('::', $trace[0]['type']);
  71. $this->assertEquals(__FILE__, $trace[0]['file']);
  72. $this->assertEquals(__CLASS__, $trace[1]['class']);
  73. $this->assertEquals(__FUNCTION__, $trace[1]['function']);
  74. $this->assertEquals('->', $trace[1]['type']);
  75. } finally {
  76. restore_error_handler();
  77. restore_exception_handler();
  78. }
  79. }
  80. // dummy function to test trace in error handler.
  81. private static function triggerNotice($that)
  82. {
  83. // dummy variable to check for in error handler.
  84. $foobar = 123;
  85. $that->assertSame('', $foo.$foo.$bar);
  86. }
  87. public function testConstruct()
  88. {
  89. try {
  90. $handler = ErrorHandler::register();
  91. $handler->throwAt(3, true);
  92. $this->assertEquals(3 | E_RECOVERABLE_ERROR | E_USER_ERROR, $handler->throwAt(0));
  93. } finally {
  94. restore_error_handler();
  95. restore_exception_handler();
  96. }
  97. }
  98. public function testDefaultLogger()
  99. {
  100. try {
  101. $handler = ErrorHandler::register();
  102. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  103. $handler->setDefaultLogger($logger, E_NOTICE);
  104. $handler->setDefaultLogger($logger, array(E_USER_NOTICE => LogLevel::CRITICAL));
  105. $loggers = array(
  106. E_DEPRECATED => array(null, LogLevel::INFO),
  107. E_USER_DEPRECATED => array(null, LogLevel::INFO),
  108. E_NOTICE => array($logger, LogLevel::WARNING),
  109. E_USER_NOTICE => array($logger, LogLevel::CRITICAL),
  110. E_STRICT => array(null, LogLevel::WARNING),
  111. E_WARNING => array(null, LogLevel::WARNING),
  112. E_USER_WARNING => array(null, LogLevel::WARNING),
  113. E_COMPILE_WARNING => array(null, LogLevel::WARNING),
  114. E_CORE_WARNING => array(null, LogLevel::WARNING),
  115. E_USER_ERROR => array(null, LogLevel::CRITICAL),
  116. E_RECOVERABLE_ERROR => array(null, LogLevel::CRITICAL),
  117. E_COMPILE_ERROR => array(null, LogLevel::CRITICAL),
  118. E_PARSE => array(null, LogLevel::CRITICAL),
  119. E_ERROR => array(null, LogLevel::CRITICAL),
  120. E_CORE_ERROR => array(null, LogLevel::CRITICAL),
  121. );
  122. $this->assertSame($loggers, $handler->setLoggers(array()));
  123. } finally {
  124. restore_error_handler();
  125. restore_exception_handler();
  126. }
  127. }
  128. public function testHandleError()
  129. {
  130. try {
  131. $handler = ErrorHandler::register();
  132. $handler->throwAt(0, true);
  133. $this->assertFalse($handler->handleError(0, 'foo', 'foo.php', 12, array()));
  134. restore_error_handler();
  135. restore_exception_handler();
  136. $handler = ErrorHandler::register();
  137. $handler->throwAt(3, true);
  138. $this->assertFalse($handler->handleError(4, 'foo', 'foo.php', 12, array()));
  139. restore_error_handler();
  140. restore_exception_handler();
  141. $handler = ErrorHandler::register();
  142. $handler->throwAt(3, true);
  143. try {
  144. $handler->handleError(4, 'foo', 'foo.php', 12, array());
  145. } catch (\ErrorException $e) {
  146. $this->assertSame('Parse Error: foo', $e->getMessage());
  147. $this->assertSame(4, $e->getSeverity());
  148. $this->assertSame('foo.php', $e->getFile());
  149. $this->assertSame(12, $e->getLine());
  150. }
  151. restore_error_handler();
  152. restore_exception_handler();
  153. $handler = ErrorHandler::register();
  154. $handler->throwAt(E_USER_DEPRECATED, true);
  155. $this->assertFalse($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, array()));
  156. restore_error_handler();
  157. restore_exception_handler();
  158. $handler = ErrorHandler::register();
  159. $handler->throwAt(E_DEPRECATED, true);
  160. $this->assertFalse($handler->handleError(E_DEPRECATED, 'foo', 'foo.php', 12, array()));
  161. restore_error_handler();
  162. restore_exception_handler();
  163. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  164. $warnArgCheck = function ($logLevel, $message, $context) {
  165. $this->assertEquals('info', $logLevel);
  166. $this->assertEquals('User Deprecated: foo', $message);
  167. $this->assertArrayHasKey('exception', $context);
  168. $exception = $context['exception'];
  169. $this->assertInstanceOf(\ErrorException::class, $exception);
  170. $this->assertSame('User Deprecated: foo', $exception->getMessage());
  171. $this->assertSame(E_USER_DEPRECATED, $exception->getSeverity());
  172. };
  173. $logger
  174. ->expects($this->once())
  175. ->method('log')
  176. ->will($this->returnCallback($warnArgCheck))
  177. ;
  178. $handler = ErrorHandler::register();
  179. $handler->setDefaultLogger($logger, E_USER_DEPRECATED);
  180. $this->assertTrue($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, array()));
  181. restore_error_handler();
  182. restore_exception_handler();
  183. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  184. $logArgCheck = function ($level, $message, $context) {
  185. $this->assertEquals('Notice: Undefined variable: undefVar', $message);
  186. $this->assertArrayHasKey('exception', $context);
  187. $exception = $context['exception'];
  188. $this->assertInstanceOf(SilencedErrorContext::class, $exception);
  189. $this->assertSame(E_NOTICE, $exception->getSeverity());
  190. };
  191. $logger
  192. ->expects($this->once())
  193. ->method('log')
  194. ->will($this->returnCallback($logArgCheck))
  195. ;
  196. $handler = ErrorHandler::register();
  197. $handler->setDefaultLogger($logger, E_NOTICE);
  198. $handler->screamAt(E_NOTICE);
  199. unset($undefVar);
  200. @$undefVar++;
  201. restore_error_handler();
  202. restore_exception_handler();
  203. } catch (\Exception $e) {
  204. restore_error_handler();
  205. restore_exception_handler();
  206. throw $e;
  207. }
  208. }
  209. public function testHandleUserError()
  210. {
  211. try {
  212. $handler = ErrorHandler::register();
  213. $handler->throwAt(0, true);
  214. $e = null;
  215. $x = new \Exception('Foo');
  216. try {
  217. $f = new Fixtures\ToStringThrower($x);
  218. $f .= ''; // Trigger $f->__toString()
  219. } catch (\Exception $e) {
  220. }
  221. $this->assertSame($x, $e);
  222. } finally {
  223. restore_error_handler();
  224. restore_exception_handler();
  225. }
  226. }
  227. public function testHandleDeprecation()
  228. {
  229. $logArgCheck = function ($level, $message, $context) {
  230. $this->assertEquals(LogLevel::INFO, $level);
  231. $this->assertArrayHasKey('exception', $context);
  232. $exception = $context['exception'];
  233. $this->assertInstanceOf(\ErrorException::class, $exception);
  234. $this->assertSame('User Deprecated: Foo deprecation', $exception->getMessage());
  235. };
  236. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  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->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  252. $logArgCheck = function ($level, $message, $context) {
  253. $this->assertSame('Uncaught Exception: foo', $message);
  254. $this->assertArrayHasKey('exception', $context);
  255. $this->assertInstanceOf(\Exception::class, $context['exception']);
  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->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  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('User Warning: 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. $logs = $bootLogger->cleanLogs();
  326. $this->assertCount(1, $logs);
  327. $log = $logs[0];
  328. $this->assertSame('info', $log[0]);
  329. $this->assertSame('Deprecated: Foo message', $log[1]);
  330. $this->assertArrayHasKey('exception', $log[2]);
  331. $exception = $log[2]['exception'];
  332. $this->assertInstanceOf(\ErrorException::class, $exception);
  333. $this->assertSame('Deprecated: Foo message', $exception->getMessage());
  334. $this->assertSame(__FILE__, $exception->getFile());
  335. $this->assertSame(123, $exception->getLine());
  336. $this->assertSame(E_DEPRECATED, $exception->getSeverity());
  337. $bootLogger->log(LogLevel::WARNING, 'Foo message', array('exception' => $exception));
  338. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  339. $mockLogger->expects($this->once())
  340. ->method('log')
  341. ->with(LogLevel::WARNING, 'Foo message', array('exception' => $exception));
  342. $handler->setLoggers(array(E_DEPRECATED => array($mockLogger, LogLevel::WARNING)));
  343. }
  344. public function testSettingLoggerWhenExceptionIsBuffered()
  345. {
  346. $bootLogger = new BufferingLogger();
  347. $handler = new ErrorHandler($bootLogger);
  348. $exception = new \Exception('Foo message');
  349. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  350. $mockLogger->expects($this->once())
  351. ->method('log')
  352. ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', array('exception' => $exception));
  353. $handler->setExceptionHandler(function () use ($handler, $mockLogger) {
  354. $handler->setDefaultLogger($mockLogger);
  355. });
  356. $handler->handleException($exception);
  357. }
  358. public function testHandleFatalError()
  359. {
  360. try {
  361. $handler = ErrorHandler::register();
  362. $error = array(
  363. 'type' => E_PARSE,
  364. 'message' => 'foo',
  365. 'file' => 'bar',
  366. 'line' => 123,
  367. );
  368. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  369. $logArgCheck = function ($level, $message, $context) {
  370. $this->assertEquals('Fatal Parse Error: foo', $message);
  371. $this->assertArrayHasKey('exception', $context);
  372. $this->assertInstanceOf(\Exception::class, $context['exception']);
  373. };
  374. $logger
  375. ->expects($this->once())
  376. ->method('log')
  377. ->will($this->returnCallback($logArgCheck))
  378. ;
  379. $handler->setDefaultLogger($logger, E_PARSE);
  380. $handler->handleFatalError($error);
  381. restore_error_handler();
  382. restore_exception_handler();
  383. } catch (\Exception $e) {
  384. restore_error_handler();
  385. restore_exception_handler();
  386. throw $e;
  387. }
  388. }
  389. /**
  390. * @requires PHP 7
  391. */
  392. public function testHandleErrorException()
  393. {
  394. $exception = new \Error("Class 'Foo' not found");
  395. $handler = new ErrorHandler();
  396. $handler->setExceptionHandler(function () use (&$args) {
  397. $args = func_get_args();
  398. });
  399. $handler->handleException($exception);
  400. $this->assertInstanceOf('Symfony\Component\Debug\Exception\ClassNotFoundException', $args[0]);
  401. $this->assertStringStartsWith("Attempted to load class \"Foo\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
  402. }
  403. public function testHandleFatalErrorOnHHVM()
  404. {
  405. try {
  406. $handler = ErrorHandler::register();
  407. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  408. $logger
  409. ->expects($this->once())
  410. ->method('log')
  411. ->with(
  412. $this->equalTo(LogLevel::CRITICAL),
  413. $this->equalTo('Fatal Error: foo')
  414. )
  415. ;
  416. $handler->setDefaultLogger($logger, E_ERROR);
  417. $error = array(
  418. 'type' => E_ERROR + 0x1000000, // This error level is used by HHVM for fatal errors
  419. 'message' => 'foo',
  420. 'file' => 'bar',
  421. 'line' => 123,
  422. 'context' => array(123),
  423. 'backtrace' => array(456),
  424. );
  425. call_user_func_array(array($handler, 'handleError'), $error);
  426. $handler->handleFatalError($error);
  427. } finally {
  428. restore_error_handler();
  429. restore_exception_handler();
  430. }
  431. }
  432. }