PHPConsoleHandlerTest.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. protected function initDebugDispatcherMock(Connector $connector)
  50. {
  51. return $this->getMockBuilder('PhpConsole\Dispatcher\Debug')
  52. ->disableOriginalConstructor()
  53. ->onlyMethods(['dispatchDebug'])
  54. ->setConstructorArgs([$connector, $connector->getDumper()])
  55. ->getMock();
  56. }
  57. protected function initErrorDispatcherMock(Connector $connector)
  58. {
  59. return $this->getMockBuilder('PhpConsole\Dispatcher\Errors')
  60. ->disableOriginalConstructor()
  61. ->onlyMethods(['dispatchError', 'dispatchException'])
  62. ->setConstructorArgs([$connector, $connector->getDumper()])
  63. ->getMock();
  64. }
  65. protected function initConnectorMock()
  66. {
  67. $connector = $this->getMockBuilder('PhpConsole\Connector')
  68. ->disableOriginalConstructor()
  69. ->onlyMethods([
  70. 'sendMessage',
  71. 'onShutDown',
  72. 'isActiveClient',
  73. 'setSourcesBasePath',
  74. 'setServerEncoding',
  75. 'setPassword',
  76. 'enableSslOnlyMode',
  77. 'setAllowedIpMasks',
  78. 'setHeadersLimit',
  79. 'startEvalRequestsListener',
  80. ])
  81. ->getMock();
  82. $connector->expects($this->any())
  83. ->method('isActiveClient')
  84. ->will($this->returnValue(true));
  85. return $connector;
  86. }
  87. protected function getHandlerDefaultOption($name)
  88. {
  89. $handler = new PHPConsoleHandler([], $this->connector);
  90. $options = $handler->getOptions();
  91. return $options[$name];
  92. }
  93. protected function initLogger($handlerOptions = [], $level = Level::Debug)
  94. {
  95. return new Logger('test', [
  96. new PHPConsoleHandler($handlerOptions, $this->connector, $level),
  97. ]);
  98. }
  99. public function testInitWithDefaultConnector()
  100. {
  101. $handler = new PHPConsoleHandler();
  102. $this->assertEquals(spl_object_hash(Connector::getInstance()), spl_object_hash($handler->getConnector()));
  103. }
  104. public function testInitWithCustomConnector()
  105. {
  106. $handler = new PHPConsoleHandler([], $this->connector);
  107. $this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector()));
  108. }
  109. public function testDebug()
  110. {
  111. $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with($this->equalTo('test'));
  112. $this->initLogger()->debug('test');
  113. }
  114. public function testDebugContextInMessage()
  115. {
  116. $message = 'test';
  117. $tag = 'tag';
  118. $context = [$tag, 'custom' => mt_rand()];
  119. $expectedMessage = $message . ' ' . json_encode(array_slice($context, 1));
  120. $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
  121. $this->equalTo($expectedMessage),
  122. $this->equalTo($tag)
  123. );
  124. $this->initLogger()->debug($message, $context);
  125. }
  126. public function testDebugTags($tagsContextKeys = null)
  127. {
  128. $expectedTags = mt_rand();
  129. $logger = $this->initLogger($tagsContextKeys ? ['debugTagsKeysInContext' => $tagsContextKeys] : []);
  130. if (!$tagsContextKeys) {
  131. $tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext');
  132. }
  133. foreach ($tagsContextKeys as $key) {
  134. $debugDispatcher = $this->initDebugDispatcherMock($this->connector);
  135. $debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
  136. $this->anything(),
  137. $this->equalTo($expectedTags)
  138. );
  139. $this->connector->setDebugDispatcher($debugDispatcher);
  140. $logger->debug('test', [$key => $expectedTags]);
  141. }
  142. }
  143. public function testError($classesPartialsTraceIgnore = null)
  144. {
  145. $code = E_USER_NOTICE;
  146. $message = 'message';
  147. $file = __FILE__;
  148. $line = __LINE__;
  149. $this->errorDispatcher->expects($this->once())->method('dispatchError')->with(
  150. $this->equalTo($code),
  151. $this->equalTo($message),
  152. $this->equalTo($file),
  153. $this->equalTo($line),
  154. $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore'))
  155. );
  156. $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false);
  157. $errorHandler->registerErrorHandler([], false, E_USER_WARNING);
  158. $errorHandler->handleError($code, $message, $file, $line);
  159. }
  160. public function testException()
  161. {
  162. $e = new Exception();
  163. $this->errorDispatcher->expects($this->once())->method('dispatchException')->with(
  164. $this->equalTo($e)
  165. );
  166. $handler = $this->initLogger();
  167. $handler->log(
  168. \Psr\Log\LogLevel::ERROR,
  169. sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
  170. ['exception' => $e]
  171. );
  172. }
  173. public function testWrongOptionsThrowsException()
  174. {
  175. $this->expectException(\Exception::class);
  176. new PHPConsoleHandler(['xxx' => 1]);
  177. }
  178. public function testOptionEnabled()
  179. {
  180. $this->debugDispatcher->expects($this->never())->method('dispatchDebug');
  181. $this->initLogger(['enabled' => false])->debug('test');
  182. }
  183. public function testOptionClassesPartialsTraceIgnore()
  184. {
  185. $this->testError(['Class', 'Namespace\\']);
  186. }
  187. public function testOptionDebugTagsKeysInContext()
  188. {
  189. $this->testDebugTags(['key1', 'key2']);
  190. }
  191. public function testOptionUseOwnErrorsAndExceptionsHandler()
  192. {
  193. $this->initLogger(['useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true]);
  194. $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleError'], set_error_handler(function () {
  195. }));
  196. $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () {
  197. }));
  198. }
  199. public static function provideConnectorMethodsOptionsSets()
  200. {
  201. return [
  202. ['sourcesBasePath', 'setSourcesBasePath', __DIR__],
  203. ['serverEncoding', 'setServerEncoding', 'cp1251'],
  204. ['password', 'setPassword', '******'],
  205. ['enableSslOnlyMode', 'enableSslOnlyMode', true, false],
  206. ['ipMasks', 'setAllowedIpMasks', ['127.0.0.*']],
  207. ['headersLimit', 'setHeadersLimit', 2500],
  208. ['enableEvalListener', 'startEvalRequestsListener', true, false],
  209. ];
  210. }
  211. /**
  212. * @dataProvider provideConnectorMethodsOptionsSets
  213. */
  214. public function testOptionCallsConnectorMethod($option, $method, $value, $isArgument = true)
  215. {
  216. $expectCall = $this->connector->expects($this->once())->method($method);
  217. if ($isArgument) {
  218. $expectCall->with($value);
  219. }
  220. new PHPConsoleHandler([$option => $value], $this->connector);
  221. }
  222. public function testOptionDetectDumpTraceAndSource()
  223. {
  224. new PHPConsoleHandler(['detectDumpTraceAndSource' => true], $this->connector);
  225. $this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource);
  226. }
  227. public static function provideDumperOptionsValues()
  228. {
  229. return [
  230. ['dumperLevelLimit', 'levelLimit', 1001],
  231. ['dumperItemsCountLimit', 'itemsCountLimit', 1002],
  232. ['dumperItemSizeLimit', 'itemSizeLimit', 1003],
  233. ['dumperDumpSizeLimit', 'dumpSizeLimit', 1004],
  234. ['dumperDetectCallbacks', 'detectCallbacks', true],
  235. ];
  236. }
  237. /**
  238. * @dataProvider provideDumperOptionsValues
  239. */
  240. public function testDumperOptions($option, $dumperProperty, $value)
  241. {
  242. new PHPConsoleHandler([$option => $value], $this->connector);
  243. $this->assertEquals($value, $this->connector->getDumper()->$dumperProperty);
  244. }
  245. }