PHPConsoleHandlerTest.php 9.9 KB

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