ErrorHandlerTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 Psr\Log\LogLevel;
  12. use Symfony\Component\Debug\BufferingLogger;
  13. use Symfony\Component\Debug\ErrorHandler;
  14. use Symfony\Component\Debug\Exception\ContextErrorException;
  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 \PHPUnit_Framework_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('ContextErrorException expected');
  61. } catch (ContextErrorException $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. $this->assertArrayHasKey('foobar', $exception->getContext());
  67. $trace = $exception->getTrace();
  68. $this->assertEquals(__FILE__, $trace[0]['file']);
  69. $this->assertEquals(__CLASS__, $trace[0]['class']);
  70. $this->assertEquals('triggerNotice', $trace[0]['function']);
  71. $this->assertEquals('::', $trace[0]['type']);
  72. $this->assertEquals(__FILE__, $trace[0]['file']);
  73. $this->assertEquals(__CLASS__, $trace[1]['class']);
  74. $this->assertEquals(__FUNCTION__, $trace[1]['function']);
  75. $this->assertEquals('->', $trace[1]['type']);
  76. } finally {
  77. restore_error_handler();
  78. restore_exception_handler();
  79. }
  80. }
  81. // dummy function to test trace in error handler.
  82. private static function triggerNotice($that)
  83. {
  84. // dummy variable to check for in error handler.
  85. $foobar = 123;
  86. $that->assertSame('', $foo.$foo.$bar);
  87. }
  88. public function testConstruct()
  89. {
  90. try {
  91. $handler = ErrorHandler::register();
  92. $handler->throwAt(3, true);
  93. $this->assertEquals(3 | E_RECOVERABLE_ERROR | E_USER_ERROR, $handler->throwAt(0));
  94. } finally {
  95. restore_error_handler();
  96. restore_exception_handler();
  97. }
  98. }
  99. public function testDefaultLogger()
  100. {
  101. try {
  102. $handler = ErrorHandler::register();
  103. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  104. $handler->setDefaultLogger($logger, E_NOTICE);
  105. $handler->setDefaultLogger($logger, array(E_USER_NOTICE => LogLevel::CRITICAL));
  106. $loggers = array(
  107. E_DEPRECATED => array(null, LogLevel::INFO),
  108. E_USER_DEPRECATED => array(null, LogLevel::INFO),
  109. E_NOTICE => array($logger, LogLevel::WARNING),
  110. E_USER_NOTICE => array($logger, LogLevel::CRITICAL),
  111. E_STRICT => array(null, LogLevel::WARNING),
  112. E_WARNING => array(null, LogLevel::WARNING),
  113. E_USER_WARNING => array(null, LogLevel::WARNING),
  114. E_COMPILE_WARNING => array(null, LogLevel::WARNING),
  115. E_CORE_WARNING => array(null, LogLevel::WARNING),
  116. E_USER_ERROR => array(null, LogLevel::CRITICAL),
  117. E_RECOVERABLE_ERROR => array(null, LogLevel::CRITICAL),
  118. E_COMPILE_ERROR => array(null, LogLevel::CRITICAL),
  119. E_PARSE => array(null, LogLevel::CRITICAL),
  120. E_ERROR => array(null, LogLevel::CRITICAL),
  121. E_CORE_ERROR => array(null, LogLevel::CRITICAL),
  122. );
  123. $this->assertSame($loggers, $handler->setLoggers(array()));
  124. } finally {
  125. restore_error_handler();
  126. restore_exception_handler();
  127. }
  128. }
  129. public function testHandleError()
  130. {
  131. try {
  132. $handler = ErrorHandler::register();
  133. $handler->throwAt(0, true);
  134. $this->assertFalse($handler->handleError(0, 'foo', 'foo.php', 12, array()));
  135. restore_error_handler();
  136. restore_exception_handler();
  137. $handler = ErrorHandler::register();
  138. $handler->throwAt(3, true);
  139. $this->assertFalse($handler->handleError(4, 'foo', 'foo.php', 12, array()));
  140. restore_error_handler();
  141. restore_exception_handler();
  142. $handler = ErrorHandler::register();
  143. $handler->throwAt(3, true);
  144. try {
  145. $handler->handleError(4, 'foo', 'foo.php', 12, array());
  146. } catch (\ErrorException $e) {
  147. $this->assertSame('Parse Error: foo', $e->getMessage());
  148. $this->assertSame(4, $e->getSeverity());
  149. $this->assertSame('foo.php', $e->getFile());
  150. $this->assertSame(12, $e->getLine());
  151. }
  152. restore_error_handler();
  153. restore_exception_handler();
  154. $handler = ErrorHandler::register();
  155. $handler->throwAt(E_USER_DEPRECATED, true);
  156. $this->assertFalse($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, array()));
  157. restore_error_handler();
  158. restore_exception_handler();
  159. $handler = ErrorHandler::register();
  160. $handler->throwAt(E_DEPRECATED, true);
  161. $this->assertFalse($handler->handleError(E_DEPRECATED, 'foo', 'foo.php', 12, array()));
  162. restore_error_handler();
  163. restore_exception_handler();
  164. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  165. $warnArgCheck = function ($logLevel, $message, $context) {
  166. $this->assertEquals('info', $logLevel);
  167. $this->assertEquals('User Deprecated: foo', $message);
  168. $this->assertArrayHasKey('exception', $context);
  169. $exception = $context['exception'];
  170. $this->assertInstanceOf(\ErrorException::class, $exception);
  171. $this->assertSame('User Deprecated: foo', $exception->getMessage());
  172. $this->assertSame(E_USER_DEPRECATED, $exception->getSeverity());
  173. };
  174. $logger
  175. ->expects($this->once())
  176. ->method('log')
  177. ->will($this->returnCallback($warnArgCheck))
  178. ;
  179. $handler = ErrorHandler::register();
  180. $handler->setDefaultLogger($logger, E_USER_DEPRECATED);
  181. $this->assertTrue($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, array()));
  182. restore_error_handler();
  183. restore_exception_handler();
  184. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  185. $logArgCheck = function ($level, $message, $context) {
  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. };
  192. $logger
  193. ->expects($this->once())
  194. ->method('log')
  195. ->will($this->returnCallback($logArgCheck))
  196. ;
  197. $handler = ErrorHandler::register();
  198. $handler->setDefaultLogger($logger, E_NOTICE);
  199. $handler->screamAt(E_NOTICE);
  200. unset($undefVar);
  201. @$undefVar++;
  202. restore_error_handler();
  203. restore_exception_handler();
  204. } catch (\Exception $e) {
  205. restore_error_handler();
  206. restore_exception_handler();
  207. throw $e;
  208. }
  209. }
  210. public function testHandleUserError()
  211. {
  212. try {
  213. $handler = ErrorHandler::register();
  214. $handler->throwAt(0, true);
  215. $e = null;
  216. $x = new \Exception('Foo');
  217. try {
  218. $f = new Fixtures\ToStringThrower($x);
  219. $f .= ''; // Trigger $f->__toString()
  220. } catch (\Exception $e) {
  221. }
  222. $this->assertSame($x, $e);
  223. } finally {
  224. restore_error_handler();
  225. restore_exception_handler();
  226. }
  227. }
  228. public function testHandleDeprecation()
  229. {
  230. $logArgCheck = function ($level, $message, $context) {
  231. $this->assertEquals(LogLevel::INFO, $level);
  232. $this->assertArrayHasKey('exception', $context);
  233. $exception = $context['exception'];
  234. $this->assertInstanceOf(\ErrorException::class, $exception);
  235. $this->assertSame('User Deprecated: Foo deprecation', $exception->getMessage());
  236. };
  237. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  238. $logger
  239. ->expects($this->once())
  240. ->method('log')
  241. ->will($this->returnCallback($logArgCheck))
  242. ;
  243. $handler = new ErrorHandler();
  244. $handler->setDefaultLogger($logger);
  245. @$handler->handleError(E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, array());
  246. }
  247. public function testHandleException()
  248. {
  249. try {
  250. $handler = ErrorHandler::register();
  251. $exception = new \Exception('foo');
  252. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  253. $logArgCheck = function ($level, $message, $context) {
  254. $this->assertSame('Uncaught Exception: foo', $message);
  255. $this->assertArrayHasKey('exception', $context);
  256. $this->assertInstanceOf(\Exception::class, $context['exception']);
  257. };
  258. $logger
  259. ->expects($this->exactly(2))
  260. ->method('log')
  261. ->will($this->returnCallback($logArgCheck))
  262. ;
  263. $handler->setDefaultLogger($logger, E_ERROR);
  264. try {
  265. $handler->handleException($exception);
  266. $this->fail('Exception expected');
  267. } catch (\Exception $e) {
  268. $this->assertSame($exception, $e);
  269. }
  270. $handler->setExceptionHandler(function ($e) use ($exception) {
  271. $this->assertSame($exception, $e);
  272. });
  273. $handler->handleException($exception);
  274. } finally {
  275. restore_error_handler();
  276. restore_exception_handler();
  277. }
  278. }
  279. public function testErrorStacking()
  280. {
  281. try {
  282. $handler = ErrorHandler::register();
  283. $handler->screamAt(E_USER_WARNING);
  284. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  285. $logger
  286. ->expects($this->exactly(2))
  287. ->method('log')
  288. ->withConsecutive(
  289. array($this->equalTo(LogLevel::WARNING), $this->equalTo('Dummy log')),
  290. array($this->equalTo(LogLevel::DEBUG), $this->equalTo('User Warning: Silenced warning'))
  291. )
  292. ;
  293. $handler->setDefaultLogger($logger, array(E_USER_WARNING => LogLevel::WARNING));
  294. ErrorHandler::stackErrors();
  295. @trigger_error('Silenced warning', E_USER_WARNING);
  296. $logger->log(LogLevel::WARNING, 'Dummy log');
  297. ErrorHandler::unstackErrors();
  298. } finally {
  299. restore_error_handler();
  300. restore_exception_handler();
  301. }
  302. }
  303. public function testBootstrappingLogger()
  304. {
  305. $bootLogger = new BufferingLogger();
  306. $handler = new ErrorHandler($bootLogger);
  307. $loggers = array(
  308. E_DEPRECATED => array($bootLogger, LogLevel::INFO),
  309. E_USER_DEPRECATED => array($bootLogger, LogLevel::INFO),
  310. E_NOTICE => array($bootLogger, LogLevel::WARNING),
  311. E_USER_NOTICE => array($bootLogger, LogLevel::WARNING),
  312. E_STRICT => array($bootLogger, LogLevel::WARNING),
  313. E_WARNING => array($bootLogger, LogLevel::WARNING),
  314. E_USER_WARNING => array($bootLogger, LogLevel::WARNING),
  315. E_COMPILE_WARNING => array($bootLogger, LogLevel::WARNING),
  316. E_CORE_WARNING => array($bootLogger, LogLevel::WARNING),
  317. E_USER_ERROR => array($bootLogger, LogLevel::CRITICAL),
  318. E_RECOVERABLE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  319. E_COMPILE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  320. E_PARSE => array($bootLogger, LogLevel::CRITICAL),
  321. E_ERROR => array($bootLogger, LogLevel::CRITICAL),
  322. E_CORE_ERROR => array($bootLogger, LogLevel::CRITICAL),
  323. );
  324. $this->assertSame($loggers, $handler->setLoggers(array()));
  325. $handler->handleError(E_DEPRECATED, 'Foo message', __FILE__, 123, array());
  326. $logs = $bootLogger->cleanLogs();
  327. $this->assertCount(1, $logs);
  328. $log = $logs[0];
  329. $this->assertSame('info', $log[0]);
  330. $this->assertSame('Deprecated: Foo message', $log[1]);
  331. $this->assertArrayHasKey('exception', $log[2]);
  332. $exception = $log[2]['exception'];
  333. $this->assertInstanceOf(\ErrorException::class, $exception);
  334. $this->assertSame('Deprecated: Foo message', $exception->getMessage());
  335. $this->assertSame(__FILE__, $exception->getFile());
  336. $this->assertSame(123, $exception->getLine());
  337. $this->assertSame(E_DEPRECATED, $exception->getSeverity());
  338. $bootLogger->log(LogLevel::WARNING, 'Foo message', array('exception' => $exception));
  339. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  340. $mockLogger->expects($this->once())
  341. ->method('log')
  342. ->with(LogLevel::WARNING, 'Foo message', array('exception' => $exception));
  343. $handler->setLoggers(array(E_DEPRECATED => array($mockLogger, LogLevel::WARNING)));
  344. }
  345. public function testHandleFatalError()
  346. {
  347. try {
  348. $handler = ErrorHandler::register();
  349. $error = array(
  350. 'type' => E_PARSE,
  351. 'message' => 'foo',
  352. 'file' => 'bar',
  353. 'line' => 123,
  354. );
  355. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  356. $logArgCheck = function ($level, $message, $context) {
  357. $this->assertEquals('Fatal Parse Error: foo', $message);
  358. $this->assertArrayHasKey('exception', $context);
  359. $this->assertInstanceOf(\Exception::class, $context['exception']);
  360. };
  361. $logger
  362. ->expects($this->once())
  363. ->method('log')
  364. ->will($this->returnCallback($logArgCheck))
  365. ;
  366. $handler->setDefaultLogger($logger, E_PARSE);
  367. $handler->handleFatalError($error);
  368. restore_error_handler();
  369. restore_exception_handler();
  370. } catch (\Exception $e) {
  371. restore_error_handler();
  372. restore_exception_handler();
  373. throw $e;
  374. }
  375. }
  376. /**
  377. * @requires PHP 7
  378. */
  379. public function testHandleErrorException()
  380. {
  381. $exception = new \Error("Class 'Foo' not found");
  382. $handler = new ErrorHandler();
  383. $handler->setExceptionHandler(function () use (&$args) {
  384. $args = func_get_args();
  385. });
  386. $handler->handleException($exception);
  387. $this->assertInstanceOf('Symfony\Component\Debug\Exception\ClassNotFoundException', $args[0]);
  388. $this->assertStringStartsWith("Attempted to load class \"Foo\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
  389. }
  390. public function testHandleFatalErrorOnHHVM()
  391. {
  392. try {
  393. $handler = ErrorHandler::register();
  394. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  395. $logger
  396. ->expects($this->once())
  397. ->method('log')
  398. ->with(
  399. $this->equalTo(LogLevel::CRITICAL),
  400. $this->equalTo('Fatal Error: foo')
  401. )
  402. ;
  403. $handler->setDefaultLogger($logger, E_ERROR);
  404. $error = array(
  405. 'type' => E_ERROR + 0x1000000, // This error level is used by HHVM for fatal errors
  406. 'message' => 'foo',
  407. 'file' => 'bar',
  408. 'line' => 123,
  409. 'context' => array(123),
  410. 'backtrace' => array(456),
  411. );
  412. call_user_func_array(array($handler, 'handleError'), $error);
  413. $handler->handleFatalError($error);
  414. } finally {
  415. restore_error_handler();
  416. restore_exception_handler();
  417. }
  418. }
  419. }