PHPConsoleHandlerTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  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 Monolog\Handler;
  11. use Exception;
  12. use Monolog\ErrorHandler;
  13. use Monolog\Level;
  14. use Monolog\Logger;
  15. use Monolog\Test\TestCase;
  16. use PhpConsole\Connector;
  17. use PhpConsole\Dispatcher\Debug as DebugDispatcher;
  18. use PhpConsole\Dispatcher\Errors as ErrorDispatcher;
  19. use PhpConsole\Handler as VendorPhpConsoleHandler;
  20. use PHPUnit\Framework\MockObject\MockObject;
  21. /**
  22. * @covers Monolog\Handler\PHPConsoleHandler
  23. * @author Sergey Barbushin https://www.linkedin.com/in/barbushin
  24. */
  25. class PHPConsoleHandlerTest extends TestCase
  26. {
  27. protected Connector&MockObject $connector;
  28. protected DebugDispatcher&MockObject $debugDispatcher;
  29. protected ErrorDispatcher&MockObject $errorDispatcher;
  30. protected function setUp(): void
  31. {
  32. // suppress warnings until https://github.com/barbushin/php-console/pull/173 is merged
  33. $previous = error_reporting(0);
  34. if (!class_exists('PhpConsole\Connector')) {
  35. error_reporting($previous);
  36. $this->markTestSkipped('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
  37. }
  38. if (!class_exists('PhpConsole\Handler')) {
  39. error_reporting($previous);
  40. $this->markTestSkipped('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
  41. }
  42. error_reporting($previous);
  43. $this->connector = $this->initConnectorMock();
  44. $this->debugDispatcher = $this->initDebugDispatcherMock($this->connector);
  45. $this->connector->setDebugDispatcher($this->debugDispatcher);
  46. $this->errorDispatcher = $this->initErrorDispatcherMock($this->connector);
  47. $this->connector->setErrorsDispatcher($this->errorDispatcher);
  48. }
  49. public function tearDown(): void
  50. {
  51. parent::tearDown();
  52. unset($this->connector, $this->debugDispatcher, $this->errorDispatcher);
  53. }
  54. protected function initDebugDispatcherMock(Connector $connector)
  55. {
  56. return $this->getMockBuilder('PhpConsole\Dispatcher\Debug')
  57. ->disableOriginalConstructor()
  58. ->onlyMethods(['dispatchDebug'])
  59. ->setConstructorArgs([$connector, $connector->getDumper()])
  60. ->getMock();
  61. }
  62. protected function initErrorDispatcherMock(Connector $connector)
  63. {
  64. return $this->getMockBuilder('PhpConsole\Dispatcher\Errors')
  65. ->disableOriginalConstructor()
  66. ->onlyMethods(['dispatchError', 'dispatchException'])
  67. ->setConstructorArgs([$connector, $connector->getDumper()])
  68. ->getMock();
  69. }
  70. protected function initConnectorMock()
  71. {
  72. $connector = $this->getMockBuilder('PhpConsole\Connector')
  73. ->disableOriginalConstructor()
  74. ->onlyMethods([
  75. 'sendMessage',
  76. 'onShutDown',
  77. 'isActiveClient',
  78. 'setSourcesBasePath',
  79. 'setServerEncoding',
  80. 'setPassword',
  81. 'enableSslOnlyMode',
  82. 'setAllowedIpMasks',
  83. 'setHeadersLimit',
  84. 'startEvalRequestsListener',
  85. ])
  86. ->getMock();
  87. $connector->expects($this->any())
  88. ->method('isActiveClient')
  89. ->will($this->returnValue(true));
  90. return $connector;
  91. }
  92. protected function getHandlerDefaultOption($name)
  93. {
  94. $handler = new PHPConsoleHandler([], $this->connector);
  95. $options = $handler->getOptions();
  96. return $options[$name];
  97. }
  98. protected function initLogger($handlerOptions = [], $level = Level::Debug)
  99. {
  100. return new Logger('test', [
  101. new PHPConsoleHandler($handlerOptions, $this->connector, $level),
  102. ]);
  103. }
  104. public function testInitWithDefaultConnector()
  105. {
  106. $handler = new PHPConsoleHandler();
  107. $this->assertEquals(spl_object_hash(Connector::getInstance()), spl_object_hash($handler->getConnector()));
  108. }
  109. public function testInitWithCustomConnector()
  110. {
  111. $handler = new PHPConsoleHandler([], $this->connector);
  112. $this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector()));
  113. }
  114. public function testDebug()
  115. {
  116. $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with($this->equalTo('test'));
  117. $this->initLogger()->debug('test');
  118. }
  119. public function testDebugContextInMessage()
  120. {
  121. $message = 'test';
  122. $tag = 'tag';
  123. $context = [$tag, 'custom' => mt_rand()];
  124. $expectedMessage = $message . ' ' . json_encode(array_slice($context, 1));
  125. $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
  126. $this->equalTo($expectedMessage),
  127. $this->equalTo($tag)
  128. );
  129. $this->initLogger()->debug($message, $context);
  130. }
  131. public function testDebugTags($tagsContextKeys = null)
  132. {
  133. $expectedTags = mt_rand();
  134. $logger = $this->initLogger($tagsContextKeys ? ['debugTagsKeysInContext' => $tagsContextKeys] : []);
  135. if (!$tagsContextKeys) {
  136. $tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext');
  137. }
  138. foreach ($tagsContextKeys as $key) {
  139. $debugDispatcher = $this->initDebugDispatcherMock($this->connector);
  140. $debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
  141. $this->anything(),
  142. $this->equalTo($expectedTags)
  143. );
  144. $this->connector->setDebugDispatcher($debugDispatcher);
  145. $logger->debug('test', [$key => $expectedTags]);
  146. }
  147. }
  148. public function testError($classesPartialsTraceIgnore = null)
  149. {
  150. $code = E_USER_NOTICE;
  151. $message = 'message';
  152. $file = __FILE__;
  153. $line = __LINE__;
  154. $this->errorDispatcher->expects($this->once())->method('dispatchError')->with(
  155. $this->equalTo($code),
  156. $this->equalTo($message),
  157. $this->equalTo($file),
  158. $this->equalTo($line),
  159. $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore'))
  160. );
  161. $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false);
  162. $errorHandler->registerErrorHandler([], false, E_USER_WARNING);
  163. $reflMethod = new \ReflectionMethod($errorHandler, 'handleError');
  164. $reflMethod->invoke($errorHandler, $code, $message, $file, $line);
  165. }
  166. public function testException()
  167. {
  168. $e = new Exception();
  169. $this->errorDispatcher->expects($this->once())->method('dispatchException')->with(
  170. $this->equalTo($e)
  171. );
  172. $handler = $this->initLogger();
  173. $handler->log(
  174. \Psr\Log\LogLevel::ERROR,
  175. sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
  176. ['exception' => $e]
  177. );
  178. }
  179. public function testWrongOptionsThrowsException()
  180. {
  181. $this->expectException(\Exception::class);
  182. new PHPConsoleHandler(['xxx' => 1]);
  183. }
  184. public function testOptionEnabled()
  185. {
  186. $this->debugDispatcher->expects($this->never())->method('dispatchDebug');
  187. $this->initLogger(['enabled' => false])->debug('test');
  188. }
  189. public function testOptionClassesPartialsTraceIgnore()
  190. {
  191. $this->testError(['Class', 'Namespace\\']);
  192. }
  193. public function testOptionDebugTagsKeysInContext()
  194. {
  195. $this->testDebugTags(['key1', 'key2']);
  196. }
  197. public function testOptionUseOwnErrorsAndExceptionsHandler()
  198. {
  199. $this->initLogger(['useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true]);
  200. $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleError'], set_error_handler(function () {
  201. }));
  202. $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () {
  203. }));
  204. }
  205. public static function provideConnectorMethodsOptionsSets()
  206. {
  207. return [
  208. ['sourcesBasePath', 'setSourcesBasePath', __DIR__],
  209. ['serverEncoding', 'setServerEncoding', 'cp1251'],
  210. ['password', 'setPassword', '******'],
  211. ['enableSslOnlyMode', 'enableSslOnlyMode', true, false],
  212. ['ipMasks', 'setAllowedIpMasks', ['127.0.0.*']],
  213. ['headersLimit', 'setHeadersLimit', 2500],
  214. ['enableEvalListener', 'startEvalRequestsListener', true, false],
  215. ];
  216. }
  217. /**
  218. * @dataProvider provideConnectorMethodsOptionsSets
  219. */
  220. public function testOptionCallsConnectorMethod($option, $method, $value, $isArgument = true)
  221. {
  222. $expectCall = $this->connector->expects($this->once())->method($method);
  223. if ($isArgument) {
  224. $expectCall->with($value);
  225. }
  226. new PHPConsoleHandler([$option => $value], $this->connector);
  227. }
  228. public function testOptionDetectDumpTraceAndSource()
  229. {
  230. new PHPConsoleHandler(['detectDumpTraceAndSource' => true], $this->connector);
  231. $this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource);
  232. }
  233. public static function provideDumperOptionsValues()
  234. {
  235. return [
  236. ['dumperLevelLimit', 'levelLimit', 1001],
  237. ['dumperItemsCountLimit', 'itemsCountLimit', 1002],
  238. ['dumperItemSizeLimit', 'itemSizeLimit', 1003],
  239. ['dumperDumpSizeLimit', 'dumpSizeLimit', 1004],
  240. ['dumperDetectCallbacks', 'detectCallbacks', true],
  241. ];
  242. }
  243. /**
  244. * @dataProvider provideDumperOptionsValues
  245. */
  246. public function testDumperOptions($option, $dumperProperty, $value)
  247. {
  248. new PHPConsoleHandler([$option => $value], $this->connector);
  249. $this->assertEquals($value, $this->connector->getDumper()->$dumperProperty);
  250. }
  251. }