PHPConsoleHandlerTest.php 9.9 KB

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