PHPConsoleHandlerTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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\Attributes\DataProvider;
  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 TestCase
  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. public function testError($classesPartialsTraceIgnore = null)
  150. {
  151. $code = E_USER_NOTICE;
  152. $message = 'message';
  153. $file = __FILE__;
  154. $line = __LINE__;
  155. $this->errorDispatcher->expects($this->once())->method('dispatchError')->with(
  156. $this->equalTo($code),
  157. $this->equalTo($message),
  158. $this->equalTo($file),
  159. $this->equalTo($line),
  160. $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore'))
  161. );
  162. $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false);
  163. $errorHandler->registerErrorHandler([], false, E_USER_WARNING);
  164. $reflMethod = new \ReflectionMethod($errorHandler, 'handleError');
  165. $reflMethod->invoke($errorHandler, $code, $message, $file, $line);
  166. }
  167. public function testException()
  168. {
  169. $e = new Exception();
  170. $this->errorDispatcher->expects($this->once())->method('dispatchException')->with(
  171. $this->equalTo($e)
  172. );
  173. $handler = $this->initLogger();
  174. $handler->log(
  175. \Psr\Log\LogLevel::ERROR,
  176. sprintf('Uncaught Exception %s: "%s" at %s line %s', \get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
  177. ['exception' => $e]
  178. );
  179. }
  180. public function testWrongOptionsThrowsException()
  181. {
  182. $this->expectException(\Exception::class);
  183. new PHPConsoleHandler(['xxx' => 1]);
  184. }
  185. public function testOptionEnabled()
  186. {
  187. $this->debugDispatcher->expects($this->never())->method('dispatchDebug');
  188. $this->initLogger(['enabled' => false])->debug('test');
  189. }
  190. public function testOptionClassesPartialsTraceIgnore()
  191. {
  192. $this->testError(['Class', 'Namespace\\']);
  193. }
  194. public function testOptionDebugTagsKeysInContext()
  195. {
  196. $this->testDebugTags(['key1', 'key2']);
  197. }
  198. public function testOptionUseOwnErrorsAndExceptionsHandler()
  199. {
  200. $this->initLogger(['useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true]);
  201. $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleError'], set_error_handler(function () {
  202. }));
  203. $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () {
  204. }));
  205. }
  206. public static function provideConnectorMethodsOptionsSets()
  207. {
  208. return [
  209. ['sourcesBasePath', 'setSourcesBasePath', __DIR__],
  210. ['serverEncoding', 'setServerEncoding', 'cp1251'],
  211. ['password', 'setPassword', '******'],
  212. ['enableSslOnlyMode', 'enableSslOnlyMode', true, false],
  213. ['ipMasks', 'setAllowedIpMasks', ['127.0.0.*']],
  214. ['headersLimit', 'setHeadersLimit', 2500],
  215. ['enableEvalListener', 'startEvalRequestsListener', true, false],
  216. ];
  217. }
  218. #[DataProvider('provideConnectorMethodsOptionsSets')]
  219. public function testOptionCallsConnectorMethod($option, $method, $value, $isArgument = true)
  220. {
  221. $expectCall = $this->connector->expects($this->once())->method($method);
  222. if ($isArgument) {
  223. $expectCall->with($value);
  224. }
  225. new PHPConsoleHandler([$option => $value], $this->connector);
  226. }
  227. public function testOptionDetectDumpTraceAndSource()
  228. {
  229. new PHPConsoleHandler(['detectDumpTraceAndSource' => true], $this->connector);
  230. $this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource);
  231. }
  232. public static function provideDumperOptionsValues()
  233. {
  234. return [
  235. ['dumperLevelLimit', 'levelLimit', 1001],
  236. ['dumperItemsCountLimit', 'itemsCountLimit', 1002],
  237. ['dumperItemSizeLimit', 'itemSizeLimit', 1003],
  238. ['dumperDumpSizeLimit', 'dumpSizeLimit', 1004],
  239. ['dumperDetectCallbacks', 'detectCallbacks', true],
  240. ];
  241. }
  242. #[DataProvider('provideDumperOptionsValues')]
  243. public function testDumperOptions($option, $dumperProperty, $value)
  244. {
  245. new PHPConsoleHandler([$option => $value], $this->connector);
  246. $this->assertEquals($value, $this->connector->getDumper()->$dumperProperty);
  247. }
  248. }