ElasticaHandlerTest.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 Monolog\Formatter\ElasticaFormatter;
  12. use Monolog\Formatter\NormalizerFormatter;
  13. use Monolog\Test\TestCase;
  14. use Monolog\Level;
  15. use Elastica\Client;
  16. use Elastica\Request;
  17. use Elastica\Response;
  18. use PHPUnit\Framework\Attributes\DataProvider;
  19. use PHPUnit\Framework\Attributes\Group;
  20. #[Group('Elastica')]
  21. class ElasticaHandlerTest extends TestCase
  22. {
  23. /**
  24. * @var Client mock
  25. */
  26. protected Client $client;
  27. /**
  28. * @var array Default handler options
  29. */
  30. protected array $options = [
  31. 'index' => 'my_index',
  32. 'type' => 'doc_type',
  33. ];
  34. public function setUp(): void
  35. {
  36. // Elastica lib required
  37. if (!class_exists("Elastica\Client")) {
  38. $this->markTestSkipped("ruflin/elastica not installed");
  39. }
  40. // base mock Elastica Client object
  41. $this->client = $this->getMockBuilder('Elastica\Client')
  42. ->onlyMethods(['addDocuments'])
  43. ->disableOriginalConstructor()
  44. ->getMock();
  45. }
  46. public function tearDown(): void
  47. {
  48. parent::tearDown();
  49. unset($this->client);
  50. }
  51. /**
  52. * @covers Monolog\Handler\ElasticaHandler::write
  53. * @covers Monolog\Handler\ElasticaHandler::handleBatch
  54. * @covers Monolog\Handler\ElasticaHandler::bulkSend
  55. * @covers Monolog\Handler\ElasticaHandler::getDefaultFormatter
  56. */
  57. public function testHandle()
  58. {
  59. // log message
  60. $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
  61. // format expected result
  62. $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']);
  63. $expected = [$formatter->format($msg)];
  64. // setup ES client mock
  65. $this->client->expects($this->any())
  66. ->method('addDocuments')
  67. ->with($expected);
  68. // perform tests
  69. $handler = new ElasticaHandler($this->client, $this->options);
  70. $handler->handle($msg);
  71. $handler->handleBatch([$msg]);
  72. }
  73. /**
  74. * @covers Monolog\Handler\ElasticaHandler::setFormatter
  75. */
  76. public function testSetFormatter()
  77. {
  78. $handler = new ElasticaHandler($this->client);
  79. $formatter = new ElasticaFormatter('index_new', 'type_new');
  80. $handler->setFormatter($formatter);
  81. $this->assertInstanceOf('Monolog\Formatter\ElasticaFormatter', $handler->getFormatter());
  82. $this->assertEquals('index_new', $handler->getFormatter()->getIndex());
  83. $this->assertEquals('type_new', $handler->getFormatter()->getType());
  84. }
  85. /**
  86. * @covers Monolog\Handler\ElasticaHandler::setFormatter
  87. */
  88. public function testSetFormatterInvalid()
  89. {
  90. $handler = new ElasticaHandler($this->client);
  91. $formatter = new NormalizerFormatter();
  92. $this->expectException(\InvalidArgumentException::class);
  93. $this->expectExceptionMessage('ElasticaHandler is only compatible with ElasticaFormatter');
  94. $handler->setFormatter($formatter);
  95. }
  96. /**
  97. * @covers Monolog\Handler\ElasticaHandler::__construct
  98. * @covers Monolog\Handler\ElasticaHandler::getOptions
  99. */
  100. public function testOptions()
  101. {
  102. $expected = [
  103. 'index' => $this->options['index'],
  104. 'type' => $this->options['type'],
  105. 'ignore_error' => false,
  106. ];
  107. $handler = new ElasticaHandler($this->client, $this->options);
  108. $this->assertEquals($expected, $handler->getOptions());
  109. }
  110. /**
  111. * @covers Monolog\Handler\ElasticaHandler::bulkSend
  112. */
  113. #[DataProvider('providerTestConnectionErrors')]
  114. public function testConnectionErrors($ignore, $expectedError)
  115. {
  116. $clientOpts = ['host' => '127.0.0.1', 'port' => 1];
  117. $client = new Client($clientOpts);
  118. $handlerOpts = ['ignore_error' => $ignore];
  119. $handler = new ElasticaHandler($client, $handlerOpts);
  120. if ($expectedError) {
  121. $this->expectException($expectedError[0]);
  122. $this->expectExceptionMessage($expectedError[1]);
  123. $handler->handle($this->getRecord());
  124. } else {
  125. $this->assertFalse($handler->handle($this->getRecord()));
  126. }
  127. }
  128. public static function providerTestConnectionErrors(): array
  129. {
  130. return [
  131. [false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
  132. [true, false],
  133. ];
  134. }
  135. /**
  136. * Integration test using localhost Elastic Search server version 7+
  137. *
  138. * @covers Monolog\Handler\ElasticaHandler::__construct
  139. * @covers Monolog\Handler\ElasticaHandler::handleBatch
  140. * @covers Monolog\Handler\ElasticaHandler::bulkSend
  141. * @covers Monolog\Handler\ElasticaHandler::getDefaultFormatter
  142. */
  143. public function testHandleIntegrationNewESVersion()
  144. {
  145. $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
  146. $expected = (array) $msg;
  147. $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
  148. $expected['context'] = [
  149. 'class' => '[object] (stdClass: {})',
  150. 'foo' => 7,
  151. 0 => 'bar',
  152. ];
  153. $clientOpts = ['url' => 'http://elastic:changeme@127.0.0.1:9200'];
  154. $client = new Client($clientOpts);
  155. $handler = new ElasticaHandler($client, $this->options);
  156. try {
  157. $handler->handleBatch([$msg]);
  158. } catch (\RuntimeException $e) {
  159. $this->markTestSkipped("Cannot connect to Elastic Search server on localhost");
  160. }
  161. // check document id from ES server response
  162. $documentId = $this->getCreatedDocId($client->getLastResponse());
  163. $this->assertNotEmpty($documentId, 'No elastic document id received');
  164. // retrieve document source from ES and validate
  165. $document = $this->getDocSourceFromElastic(
  166. $client,
  167. $this->options['index'],
  168. null,
  169. $documentId
  170. );
  171. $this->assertEquals($expected, $document);
  172. // remove test index from ES
  173. $client->request("/{$this->options['index']}", Request::DELETE);
  174. }
  175. /**
  176. * Return last created document id from ES response
  177. * @param Response $response Elastica Response object
  178. */
  179. protected function getCreatedDocId(Response $response): ?string
  180. {
  181. $data = $response->getData();
  182. if (!empty($data['items'][0]['index']['_id'])) {
  183. return $data['items'][0]['index']['_id'];
  184. }
  185. var_dump('Unexpected response: ', $data);
  186. return null;
  187. }
  188. /**
  189. * Retrieve document by id from Elasticsearch
  190. * @param Client $client Elastica client
  191. * @param ?string $type
  192. */
  193. protected function getDocSourceFromElastic(Client $client, string $index, $type, string $documentId): array
  194. {
  195. if ($type === null) {
  196. $path = "/{$index}/_doc/{$documentId}";
  197. } else {
  198. $path = "/{$index}/{$type}/{$documentId}";
  199. }
  200. $resp = $client->request($path, Request::GET);
  201. $data = $resp->getData();
  202. if (!empty($data['_source'])) {
  203. return $data['_source'];
  204. }
  205. return [];
  206. }
  207. }