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