菜谱项目

ErrorHandlerTest.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. $line = null;
  185. $logArgCheck = function ($level, $message, $context) use (&$line) {
  186. $this->assertEquals('Notice: Undefined variable: undefVar', $message);
  187. $this->assertArrayHasKey('exception', $context);
  188. $exception = $context['exception'];
  189. $this->assertInstanceOf(SilencedErrorContext::class, $exception);
  190. $this->assertSame(E_NOTICE, $exception->getSeverity());
  191. $this->assertSame(__FILE__, $exception->getFile());
  192. $this->assertSame($line, $exception->getLine());
  193. $this->assertNotEmpty($exception->getTrace());
  194. $this->assertSame(1, $exception->count);
  195. };
  196. $logger
  197. ->expects($this->once())
  198. ->method('log')
  199. ->will($this->returnCallback($logArgCheck))
  200. ;
  201. $handler = ErrorHandler::register();
  202. $handler->setDefaultLogger($logger, E_NOTICE);
  203. $handler->screamAt(E_NOTICE);
  204. unset($undefVar);
  205. $line = __LINE__ + 1;
  206. @$undefVar++;
  207. restore_error_handler();
  208. restore_exception_handler();
  209. } catch (\Exception $e) {
  210. restore_error_handler();
  211. restore_exception_handler();
  212. throw $e;
  213. }
  214. }
  215. public function testHandleUserError()
  216. {
  217. try {
  218. $handler = ErrorHandler::register();
  219. $handler->throwAt(0, true);
  220. $e = null;
  221. $x = new \Exception('Foo');
  222. try {
  223. $f = new Fixtures\ToStringThrower($x);
  224. $f .= ''; // Trigger $f->__toString()
  225. } catch (\Exception $e) {
  226. }
  227. $this->assertSame($x, $e);
  228. } finally {
  229. restore_error_handler();
  230. restore_exception_handler();
  231. }
  232. }
  233. public function testHandleDeprecation()
  234. {
  235. $logArgCheck = function ($level, $message, $context) {
  236. $this->assertEquals(LogLevel::INFO, $level);
  237. $this->assertArrayHasKey('exception', $context);
  238. $exception = $context['exception'];
  239. $this->assertInstanceOf(\ErrorException::class, $exception);
  240. $this->assertSame('User Deprecated: Foo deprecation', $exception->getMessage());
  241. };
  242. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  243. $logger
  244. ->expects($this->once())
  245. ->method('log')
  246. ->will($this->returnCallback($logArgCheck))
  247. ;
  248. $handler = new ErrorHandler();
  249. $handler->setDefaultLogger($logger);
  250. @$handler->handleError(E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, array());
  251. }
  252. public function testHandleException()
  253. {
  254. try {
  255. $handler = ErrorHandler::register();
  256. $exception = new \Exception('foo');
  257. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  258. $logArgCheck = function ($level, $message, $context) {
  259. $this->assertSame('Uncaught Exception: foo', $message);
  260. $this->assertArrayHasKey('exception', $context);
  261. $this->assertInstanceOf(\Exception::class, $context['exception']);
  262. };
  263. $logger
  264. ->expects($this->exactly(2))
  265. ->method('log')
  266. ->will($this->returnCallback($logArgCheck))
  267. ;
  268. $handler->setDefaultLogger($logger, E_ERROR);
  269. try {
  270. $handler->handleException($exception);
  271. $this->fail('Exception expected');
  272. } catch (\Exception $e) {
  273. $this->assertSame($exception, $e);
  274. }
  275. $handler->setExceptionHandler(function ($e) use ($exception) {
  276. $this->assertSame($exception, $e);
  277. });
  278. $handler->handleException($exception);
  279. } finally {
  280. restore_error_handler();
  281. restore_exception_handler();
  282. }
  283. }
  284. public function testErrorStacking()
  285. {
  286. try {
  287. $handler = ErrorHandler::register();
  288. $handler->screamAt(E_USER_WARNING);
  289. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  290. $logger
  291. ->expects($this->exactly(2))
  292. ->method('log')
  293. ->withConsecutive(
  294. array($this->equalTo(LogLevel::WARNING), $this->equalTo('Dummy log')),
  295. array($this->equalTo(LogLevel::DEBUG), $this->equalTo('User Warning: Silenced warning'))
  296. )
  297. ;
  298. $handler->setDefaultLogger($logger, array(E_USER_WARNING => LogLevel::WARNING));
  299. ErrorHandler::stackErrors();
  300. @trigger_error('Silenced warning', E_USER_WARNING);
  301. $logger->log(LogLevel::WARNING, 'Dummy log');
  302. ErrorHandler::unstackErrors();
  303. } finally {
  304. restore_error_handler();
  305. restore_exception_handler();
  306. }
  307. }
  308. public function testBootstrappingLogger()
  309. {
  310. $bootLogger = new BufferingLogger();
  311. $handler = new ErrorHandler($bootLogger);
  312. $loggers = array(
  313. E_DEPRECATED => array($bootLogger, LogLevel::INFO),
  314. E_USER_DEPRECATED => array($bootLogger, LogLevel::INFO),
  315. E_NOTICE => array($bootLogger, LogLevel::WARNING),
  316. E_USER_NOTICE => array($bootLogger, LogLevel::WARNING),
  317. E_STRICT => array($bootLogger, LogLevel::WARNING),
  318. E_WARNING => array($bootLogger, LogLevel::WARNING),
  319. E_USER_WARNING => array($bootLogger, LogLevel::WARNING),
  320. E_COMPILE_WARNING => array($bootLogger, LogLevel::WARNING),
  321. E_CORE_WARNING => array($bootLogger, LogLevel::WARNING),
  322. E_USER_ERROR => array($bootLogger, LogLevel::CRITICAL),
  323. E_RECOVERABLE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  324. E_COMPILE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  325. E_PARSE => array($bootLogger, LogLevel::CRITICAL),
  326. E_ERROR => array($bootLogger, LogLevel::CRITICAL),
  327. E_CORE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  328. );
  329. $this->assertSame($loggers, $handler->setLoggers(array()));
  330. $handler->handleError(E_DEPRECATED, 'Foo message', __FILE__, 123, array());
  331. $logs = $bootLogger->cleanLogs();
  332. $this->assertCount(1, $logs);
  333. $log = $logs[0];
  334. $this->assertSame('info', $log[0]);
  335. $this->assertSame('Deprecated: Foo message', $log[1]);
  336. $this->assertArrayHasKey('exception', $log[2]);
  337. $exception = $log[2]['exception'];
  338. $this->assertInstanceOf(\ErrorException::class, $exception);
  339. $this->assertSame('Deprecated: Foo message', $exception->getMessage());
  340. $this->assertSame(__FILE__, $exception->getFile());
  341. $this->assertSame(123, $exception->getLine());
  342. $this->assertSame(E_DEPRECATED, $exception->getSeverity());
  343. $bootLogger->log(LogLevel::WARNING, 'Foo message', array('exception' => $exception));
  344. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  345. $mockLogger->expects($this->once())
  346. ->method('log')
  347. ->with(LogLevel::WARNING, 'Foo message', array('exception' => $exception));
  348. $handler->setLoggers(array(E_DEPRECATED => array($mockLogger, LogLevel::WARNING)));
  349. }
  350. public function testSettingLoggerWhenExceptionIsBuffered()
  351. {
  352. $bootLogger = new BufferingLogger();
  353. $handler = new ErrorHandler($bootLogger);
  354. $exception = new \Exception('Foo message');
  355. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  356. $mockLogger->expects($this->once())
  357. ->method('log')
  358. ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', array('exception' => $exception));
  359. $handler->setExceptionHandler(function () use ($handler, $mockLogger) {
  360. $handler->setDefaultLogger($mockLogger);
  361. });
  362. $handler->handleException($exception);
  363. }
  364. public function testHandleFatalError()
  365. {
  366. try {
  367. $handler = ErrorHandler::register();
  368. $error = array(
  369. 'type' => E_PARSE,
  370. 'message' => 'foo',
  371. 'file' => 'bar',
  372. 'line' => 123,
  373. );
  374. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  375. $logArgCheck = function ($level, $message, $context) {
  376. $this->assertEquals('Fatal Parse Error: foo', $message);
  377. $this->assertArrayHasKey('exception', $context);
  378. $this->assertInstanceOf(\Exception::class, $context['exception']);
  379. };
  380. $logger
  381. ->expects($this->once())
  382. ->method('log')
  383. ->will($this->returnCallback($logArgCheck))
  384. ;
  385. $handler->setDefaultLogger($logger, E_PARSE);
  386. $handler->handleFatalError($error);
  387. restore_error_handler();
  388. restore_exception_handler();
  389. } catch (\Exception $e) {
  390. restore_error_handler();
  391. restore_exception_handler();
  392. throw $e;
  393. }
  394. }
  395. /**
  396. * @requires PHP 7
  397. */
  398. public function testHandleErrorException()
  399. {
  400. $exception = new \Error("Class 'Foo' not found");
  401. $handler = new ErrorHandler();
  402. $handler->setExceptionHandler(function () use (&$args) {
  403. $args = func_get_args();
  404. });
  405. $handler->handleException($exception);
  406. $this->assertInstanceOf('Symfony\Component\Debug\Exception\ClassNotFoundException', $args[0]);
  407. $this->assertStringStartsWith("Attempted to load class \"Foo\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
  408. }
  409. public function testHandleFatalErrorOnHHVM()
  410. {
  411. try {
  412. $handler = ErrorHandler::register();
  413. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  414. $logger
  415. ->expects($this->once())
  416. ->method('log')
  417. ->with(
  418. $this->equalTo(LogLevel::CRITICAL),
  419. $this->equalTo('Fatal Error: foo')
  420. )
  421. ;
  422. $handler->setDefaultLogger($logger, E_ERROR);
  423. $error = array(
  424. 'type' => E_ERROR + 0x1000000, // This error level is used by HHVM for fatal errors
  425. 'message' => 'foo',
  426. 'file' => 'bar',
  427. 'line' => 123,
  428. 'context' => array(123),
  429. 'backtrace' => array(456),
  430. );
  431. call_user_func_array(array($handler, 'handleError'), $error);
  432. $handler->handleFatalError($error);
  433. } finally {
  434. restore_error_handler();
  435. restore_exception_handler();
  436. }
  437. }
  438. }