ErrorHandlerTest.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. public function testHandleException()
  272. {
  273. try {
  274. $handler = ErrorHandler::register();
  275. $exception = new \Exception('foo');
  276. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  277. $logArgCheck = function ($level, $message, $context) {
  278. $this->assertSame('Uncaught Exception: foo', $message);
  279. $this->assertArrayHasKey('exception', $context);
  280. $this->assertInstanceOf(\Exception::class, $context['exception']);
  281. };
  282. $logger
  283. ->expects($this->exactly(2))
  284. ->method('log')
  285. ->will($this->returnCallback($logArgCheck))
  286. ;
  287. $handler->setDefaultLogger($logger, E_ERROR);
  288. try {
  289. $handler->handleException($exception);
  290. $this->fail('Exception expected');
  291. } catch (\Exception $e) {
  292. $this->assertSame($exception, $e);
  293. }
  294. $handler->setExceptionHandler(function ($e) use ($exception) {
  295. $this->assertSame($exception, $e);
  296. });
  297. $handler->handleException($exception);
  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 testSettingLoggerWhenExceptionIsBuffered()
  346. {
  347. $bootLogger = new BufferingLogger();
  348. $handler = new ErrorHandler($bootLogger);
  349. $exception = new \Exception('Foo message');
  350. $mockLogger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  351. $mockLogger->expects($this->once())
  352. ->method('log')
  353. ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', array('exception' => $exception));
  354. $handler->setExceptionHandler(function () use ($handler, $mockLogger) {
  355. $handler->setDefaultLogger($mockLogger);
  356. });
  357. $handler->handleException($exception);
  358. }
  359. public function testHandleFatalError()
  360. {
  361. try {
  362. $handler = ErrorHandler::register();
  363. $error = array(
  364. 'type' => E_PARSE,
  365. 'message' => 'foo',
  366. 'file' => 'bar',
  367. 'line' => 123,
  368. );
  369. $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
  370. $logArgCheck = function ($level, $message, $context) {
  371. $this->assertEquals('Fatal Parse Error: foo', $message);
  372. $this->assertArrayHasKey('exception', $context);
  373. $this->assertInstanceOf(\Exception::class, $context['exception']);
  374. };
  375. $logger
  376. ->expects($this->once())
  377. ->method('log')
  378. ->will($this->returnCallback($logArgCheck))
  379. ;
  380. $handler->setDefaultLogger($logger, E_PARSE);
  381. $handler->handleFatalError($error);
  382. restore_error_handler();
  383. restore_exception_handler();
  384. } catch (\Exception $e) {
  385. restore_error_handler();
  386. restore_exception_handler();
  387. throw $e;
  388. }
  389. }
  390. public function testHandleErrorException()
  391. {
  392. $exception = new \Error("Class 'Foo' not found");
  393. $handler = new ErrorHandler();
  394. $handler->setExceptionHandler(function () use (&$args) {
  395. $args = func_get_args();
  396. });
  397. $handler->handleException($exception);
  398. $this->assertInstanceOf('Symfony\Component\Debug\Exception\ClassNotFoundException', $args[0]);
  399. $this->assertStringStartsWith("Attempted to load class \"Foo\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
  400. }
  401. /**
  402. * @expectedException \Exception
  403. */
  404. public function testCustomExceptionHandler()
  405. {
  406. $handler = new ErrorHandler();
  407. $handler->setExceptionHandler(function ($e) use ($handler) {
  408. $handler->handleException($e);
  409. });
  410. $handler->handleException(new \Exception());
  411. }
  412. }