PHPConsoleHandlerTest.php 9.5 KB

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