ElasticSearchHandlerTest.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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\Logger;
  15. use Elastica\Client;
  16. use Elastica\Request;
  17. use Elastica\Response;
  18. class ElasticSearchHandlerTest extends TestCase
  19. {
  20. /**
  21. * @var Client mock
  22. */
  23. protected $client;
  24. /**
  25. * @var array Default handler options
  26. */
  27. protected $options = [
  28. 'index' => 'my_index',
  29. 'type' => 'doc_type',
  30. ];
  31. public function setUp()
  32. {
  33. // Elastica lib required
  34. if (!class_exists("Elastica\Client")) {
  35. $this->markTestSkipped("ruflin/elastica not installed");
  36. }
  37. // base mock Elastica Client object
  38. $this->client = $this->getMockBuilder('Elastica\Client')
  39. ->setMethods(['addDocuments'])
  40. ->disableOriginalConstructor()
  41. ->getMock();
  42. }
  43. /**
  44. * @covers Monolog\Handler\ElasticSearchHandler::write
  45. * @covers Monolog\Handler\ElasticSearchHandler::handleBatch
  46. * @covers Monolog\Handler\ElasticSearchHandler::bulkSend
  47. * @covers Monolog\Handler\ElasticSearchHandler::getDefaultFormatter
  48. */
  49. public function testHandle()
  50. {
  51. // log message
  52. $msg = [
  53. 'level' => Logger::ERROR,
  54. 'level_name' => 'ERROR',
  55. 'channel' => 'meh',
  56. 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
  57. 'datetime' => new \DateTimeImmutable("@0"),
  58. 'extra' => [],
  59. 'message' => 'log',
  60. ];
  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 ElasticSearchHandler($this->client, $this->options);
  70. $handler->handle($msg);
  71. $handler->handleBatch([$msg]);
  72. }
  73. /**
  74. * @covers Monolog\Handler\ElasticSearchHandler::setFormatter
  75. */
  76. public function testSetFormatter()
  77. {
  78. $handler = new ElasticSearchHandler($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\ElasticSearchHandler::setFormatter
  87. * @expectedException InvalidArgumentException
  88. * @expectedExceptionMessage ElasticSearchHandler is only compatible with ElasticaFormatter
  89. */
  90. public function testSetFormatterInvalid()
  91. {
  92. $handler = new ElasticSearchHandler($this->client);
  93. $formatter = new NormalizerFormatter();
  94. $handler->setFormatter($formatter);
  95. }
  96. /**
  97. * @covers Monolog\Handler\ElasticSearchHandler::__construct
  98. * @covers Monolog\Handler\ElasticSearchHandler::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 ElasticSearchHandler($this->client, $this->options);
  108. $this->assertEquals($expected, $handler->getOptions());
  109. }
  110. /**
  111. * @covers Monolog\Handler\ElasticSearchHandler::bulkSend
  112. * @dataProvider providerTestConnectionErrors
  113. */
  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 ElasticSearchHandler($client, $handlerOpts);
  120. if ($expectedError) {
  121. $this->setExpectedException($expectedError[0], $expectedError[1]);
  122. $handler->handle($this->getRecord());
  123. } else {
  124. $this->assertFalse($handler->handle($this->getRecord()));
  125. }
  126. }
  127. /**
  128. * @return array
  129. */
  130. public function providerTestConnectionErrors()
  131. {
  132. return [
  133. [false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
  134. [true, false],
  135. ];
  136. }
  137. /**
  138. * Integration test using localhost Elastic Search server
  139. *
  140. * @covers Monolog\Handler\ElasticSearchHandler::__construct
  141. * @covers Monolog\Handler\ElasticSearchHandler::handleBatch
  142. * @covers Monolog\Handler\ElasticSearchHandler::bulkSend
  143. * @covers Monolog\Handler\ElasticSearchHandler::getDefaultFormatter
  144. */
  145. public function testHandleIntegration()
  146. {
  147. $msg = [
  148. 'level' => Logger::ERROR,
  149. 'level_name' => 'ERROR',
  150. 'channel' => 'meh',
  151. 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
  152. 'datetime' => new \DateTimeImmutable("@0"),
  153. 'extra' => [],
  154. 'message' => 'log',
  155. ];
  156. $expected = $msg;
  157. $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
  158. $expected['context'] = [
  159. 'class' => '[object] (stdClass: {})',
  160. 'foo' => 7,
  161. 0 => 'bar',
  162. ];
  163. $client = new Client();
  164. $handler = new ElasticSearchHandler($client, $this->options);
  165. try {
  166. $handler->handleBatch([$msg]);
  167. } catch (\RuntimeException $e) {
  168. $this->markTestSkipped("Cannot connect to Elastic Search server on localhost");
  169. }
  170. // check document id from ES server response
  171. $documentId = $this->getCreatedDocId($client->getLastResponse());
  172. $this->assertNotEmpty($documentId, 'No elastic document id received');
  173. // retrieve document source from ES and validate
  174. $document = $this->getDocSourceFromElastic(
  175. $client,
  176. $this->options['index'],
  177. $this->options['type'],
  178. $documentId
  179. );
  180. $this->assertEquals($expected, $document);
  181. // remove test index from ES
  182. $client->request("/{$this->options['index']}", Request::DELETE);
  183. }
  184. /**
  185. * Return last created document id from ES response
  186. * @param Response $response Elastica Response object
  187. * @return string|null
  188. */
  189. protected function getCreatedDocId(Response $response)
  190. {
  191. $data = $response->getData();
  192. if (!empty($data['items'][0]['create']['_id'])) {
  193. return $data['items'][0]['create']['_id'];
  194. }
  195. }
  196. /**
  197. * Retrieve document by id from Elasticsearch
  198. * @param Client $client Elastica client
  199. * @param string $index
  200. * @param string $type
  201. * @param string $documentId
  202. * @return array
  203. */
  204. protected function getDocSourceFromElastic(Client $client, $index, $type, $documentId)
  205. {
  206. $resp = $client->request("/{$index}/{$type}/{$documentId}", Request::GET);
  207. $data = $resp->getData();
  208. if (!empty($data['_source'])) {
  209. return $data['_source'];
  210. }
  211. return [];
  212. }
  213. }