ErrorHandlerTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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\LoggerInterface;
  13. use Psr\Log\LogLevel;
  14. use Psr\Log\NullLogger;
  15. use Symfony\Component\Debug\BufferingLogger;
  16. use Symfony\Component\Debug\ErrorHandler;
  17. use Symfony\Component\Debug\Exception\SilencedErrorContext;
  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. public function testHandleException()
  276. {
  277. try {
  278. $handler = ErrorHandler::register();
  279. $exception = new \Exception('foo');
  280. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  281. $logArgCheck = function ($level, $message, $context) {
  282. $this->assertSame('Uncaught Exception: foo', $message);
  283. $this->assertArrayHasKey('exception', $context);
  284. $this->assertInstanceOf(\Exception::class, $context['exception']);
  285. };
  286. $logger
  287. ->expects($this->exactly(2))
  288. ->method('log')
  289. ->will($this->returnCallback($logArgCheck))
  290. ;
  291. $handler->setDefaultLogger($logger, E_ERROR);
  292. try {
  293. $handler->handleException($exception);
  294. $this->fail('Exception expected');
  295. } catch (\Exception $e) {
  296. $this->assertSame($exception, $e);
  297. }
  298. $handler->setExceptionHandler(function ($e) use ($exception) {
  299. $this->assertSame($exception, $e);
  300. });
  301. $handler->handleException($exception);
  302. } finally {
  303. restore_error_handler();
  304. restore_exception_handler();
  305. }
  306. }
  307. public function testBootstrappingLogger()
  308. {
  309. $bootLogger = new BufferingLogger();
  310. $handler = new ErrorHandler($bootLogger);
  311. $loggers = [
  312. E_DEPRECATED => [$bootLogger, LogLevel::INFO],
  313. E_USER_DEPRECATED => [$bootLogger, LogLevel::INFO],
  314. E_NOTICE => [$bootLogger, LogLevel::WARNING],
  315. E_USER_NOTICE => [$bootLogger, LogLevel::WARNING],
  316. E_STRICT => [$bootLogger, LogLevel::WARNING],
  317. E_WARNING => [$bootLogger, LogLevel::WARNING],
  318. E_USER_WARNING => [$bootLogger, LogLevel::WARNING],
  319. E_COMPILE_WARNING => [$bootLogger, LogLevel::WARNING],
  320. E_CORE_WARNING => [$bootLogger, LogLevel::WARNING],
  321. E_USER_ERROR => [$bootLogger, LogLevel::CRITICAL],
  322. E_RECOVERABLE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  323. E_COMPILE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  324. E_PARSE => [$bootLogger, LogLevel::CRITICAL],
  325. E_ERROR => [$bootLogger, LogLevel::CRITICAL],
  326. E_CORE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  327. ];
  328. $this->assertSame($loggers, $handler->setLoggers([]));
  329. $handler->handleError(E_DEPRECATED, 'Foo message', __FILE__, 123, []);
  330. $logs = $bootLogger->cleanLogs();
  331. $this->assertCount(1, $logs);
  332. $log = $logs[0];
  333. $this->assertSame('info', $log[0]);
  334. $this->assertSame('Deprecated: Foo message', $log[1]);
  335. $this->assertArrayHasKey('exception', $log[2]);
  336. $exception = $log[2]['exception'];
  337. $this->assertInstanceOf(\ErrorException::class, $exception);
  338. $this->assertSame('Deprecated: Foo message', $exception->getMessage());
  339. $this->assertSame(__FILE__, $exception->getFile());
  340. $this->assertSame(123, $exception->getLine());
  341. $this->assertSame(E_DEPRECATED, $exception->getSeverity());
  342. $bootLogger->log(LogLevel::WARNING, 'Foo message', ['exception' => $exception]);
  343. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  344. $mockLogger->expects($this->once())
  345. ->method('log')
  346. ->with(LogLevel::WARNING, 'Foo message', ['exception' => $exception]);
  347. $handler->setLoggers([E_DEPRECATED => [$mockLogger, LogLevel::WARNING]]);
  348. }
  349. public function testSettingLoggerWhenExceptionIsBuffered()
  350. {
  351. $bootLogger = new BufferingLogger();
  352. $handler = new ErrorHandler($bootLogger);
  353. $exception = new \Exception('Foo message');
  354. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  355. $mockLogger->expects($this->once())
  356. ->method('log')
  357. ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', ['exception' => $exception]);
  358. $handler->setExceptionHandler(function () use ($handler, $mockLogger) {
  359. $handler->setDefaultLogger($mockLogger);
  360. });
  361. $handler->handleException($exception);
  362. }
  363. public function testHandleFatalError()
  364. {
  365. try {
  366. $handler = ErrorHandler::register();
  367. $error = [
  368. 'type' => E_PARSE,
  369. 'message' => 'foo',
  370. 'file' => 'bar',
  371. 'line' => 123,
  372. ];
  373. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  374. $logArgCheck = function ($level, $message, $context) {
  375. $this->assertEquals('Fatal Parse Error: foo', $message);
  376. $this->assertArrayHasKey('exception', $context);
  377. $this->assertInstanceOf(\Exception::class, $context['exception']);
  378. };
  379. $logger
  380. ->expects($this->once())
  381. ->method('log')
  382. ->will($this->returnCallback($logArgCheck))
  383. ;
  384. $handler->setDefaultLogger($logger, E_PARSE);
  385. $handler->handleFatalError($error);
  386. restore_error_handler();
  387. restore_exception_handler();
  388. } catch (\Exception $e) {
  389. restore_error_handler();
  390. restore_exception_handler();
  391. throw $e;
  392. }
  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. /**
  406. * @expectedException \Exception
  407. */
  408. public function testCustomExceptionHandler()
  409. {
  410. $handler = new ErrorHandler();
  411. $handler->setExceptionHandler(function ($e) use ($handler) {
  412. $handler->handleException($e);
  413. });
  414. $handler->handleException(new \Exception());
  415. }
  416. /**
  417. * @dataProvider errorHandlerIsNotLostWhenLoggingProvider
  418. */
  419. public function testErrorHandlerIsNotLostWhenLogging($customErrorHandlerHasBeenPreviouslyDefined, LoggerInterface $logger)
  420. {
  421. try {
  422. if ($customErrorHandlerHasBeenPreviouslyDefined) {
  423. set_error_handler('count');
  424. }
  425. $handler = ErrorHandler::register();
  426. $handler->setDefaultLogger($logger);
  427. @trigger_error('foo', E_USER_DEPRECATED);
  428. @trigger_error('bar', E_USER_DEPRECATED);
  429. $this->assertSame([$handler, 'handleError'], set_error_handler('var_dump'));
  430. restore_error_handler();
  431. if ($customErrorHandlerHasBeenPreviouslyDefined) {
  432. restore_error_handler();
  433. }
  434. } finally {
  435. restore_error_handler();
  436. restore_exception_handler();
  437. }
  438. }
  439. public function errorHandlerIsNotLostWhenLoggingProvider()
  440. {
  441. return [
  442. [false, new NullLogger()],
  443. [true, new NullLogger()],
  444. [false, new LoggerThatSetAnErrorHandler()],
  445. [true, new LoggerThatSetAnErrorHandler()],
  446. ];
  447. }
  448. }