PHPConsoleHandlerTest.php 10 KB

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