Skip to content

Commit 29f570b

Browse files
committed
WIP elasticsearch: tests against elasticsearch 8
1 parent 3291f38 commit 29f570b

File tree

7 files changed

+116
-39
lines changed

7 files changed

+116
-39
lines changed

instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,8 @@ def _instrument(self, **kwargs):
173173

174174
def _uninstrument(self, **kwargs):
175175
# pylint: disable=no-member
176-
unwrap(elasticsearch.Transport, "perform_request")
176+
transport_class = elastic_transport.Transport if es_transport_split else elasticsearch.Transport
177+
unwrap(transport_class, "perform_request")
177178

178179

179180
_regex_doc_url = re.compile(r"/_doc/([^/]+)")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
asgiref==3.7.2
2+
attrs==23.2.0
3+
Deprecated==1.2.14
4+
elasticsearch==8.12.1
5+
elasticsearch-dsl==8.12.0
6+
elastic-transport==8.12.0
7+
importlib-metadata==7.1.0
8+
iniconfig==2.0.0
9+
packaging==23.2
10+
pluggy==1.4.0
11+
py==1.11.0
12+
py-cpuinfo==9.0.0
13+
pytest==7.1.3
14+
pytest-benchmark==4.0.0
15+
python-dateutil==2.8.2
16+
six==1.16.0
17+
tomli==2.0.1
18+
typing_extensions==4.10.0
19+
urllib3==2.2.1
20+
wrapt==1.16.0
21+
zipp==3.17.0
22+
-e opentelemetry-instrumentation
23+
-e instrumentation/opentelemetry-instrumentation-elasticsearch

instrumentation/opentelemetry-instrumentation-elasticsearch/tests/helpers_es6.py

+6
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,9 @@ class Index:
3131
dsl_index_span_name = "Elasticsearch/test-index/doc/2"
3232
dsl_index_url = "/test-index/doc/2"
3333
dsl_search_method = "GET"
34+
35+
perform_request_mock_path = "elasticsearch.connection.http_urllib3.Urllib3HttpConnection.perform_request"
36+
37+
38+
def mock_response(body: str):
39+
return (1, {}, body)

instrumentation/opentelemetry-instrumentation-elasticsearch/tests/helpers_es7.py

+6
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,9 @@ class Index:
2929
dsl_index_span_name = "Elasticsearch/test-index/_doc/:id"
3030
dsl_index_url = "/test-index/_doc/2"
3131
dsl_search_method = "POST"
32+
33+
perform_request_mock_path = "elasticsearch.connection.http_urllib3.Urllib3HttpConnection.perform_request"
34+
35+
36+
def mock_response(body: str):
37+
return (1, {}, body)

instrumentation/opentelemetry-instrumentation-elasticsearch/tests/helpers_es8.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
# limitations under the License.
1414

1515
from elasticsearch_dsl import Document, Keyword, Text
16+
from elastic_transport._node import NodeApiResponse
17+
from elastic_transport import ApiResponseMeta, HttpHeaders
1618

1719

1820
class Article(Document):
@@ -36,6 +38,23 @@ class Index:
3638
}
3739
}
3840
dsl_index_result = (1, {}, '{"result": "created"}')
39-
dsl_index_span_name = "Elasticsearch/test-index/_doc/2"
41+
dsl_index_span_name = "Elasticsearch/test-index/_doc/:id"
4042
dsl_index_url = "/test-index/_doc/2"
4143
dsl_search_method = "POST"
44+
45+
perform_request_mock_path = (
46+
"elastic_transport._node._http_urllib3.Urllib3HttpNode.perform_request"
47+
)
48+
49+
50+
def mock_response(body: str):
51+
return NodeApiResponse(
52+
ApiResponseMeta(
53+
status=200,
54+
headers=HttpHeaders({}),
55+
duration=100,
56+
http_version="1.1",
57+
node="node",
58+
),
59+
body.encode(),
60+
)

instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py

+55-35
Original file line numberDiff line numberDiff line change
@@ -51,25 +51,25 @@
5151

5252

5353
def normalize_arguments(doc_type, body=None):
54-
if major_version == 7:
55-
return {"document": body} if body else {}
56-
return (
57-
{"body": body, "doc_type": doc_type}
58-
if body
59-
else {"doc_type": doc_type}
60-
)
54+
if major_version < 7:
55+
return (
56+
{"body": body, "doc_type": doc_type}
57+
if body
58+
else {"doc_type": doc_type}
59+
)
60+
return {"document": body} if body else {}
6161

6262

6363
def get_elasticsearch_client(*args, **kwargs):
6464
client = Elasticsearch(*args, **kwargs)
65-
if major_version == 7:
65+
if major_version == 8:
66+
client._verified_elasticsearch = True
67+
elif major_version == 7:
6668
client.transport._verified_elasticsearch = True
6769
return client
6870

6971

70-
@mock.patch(
71-
"elasticsearch.connection.http_urllib3.Urllib3HttpConnection.perform_request"
72-
)
72+
@mock.patch(helpers.perform_request_mock_path)
7373
class TestElasticsearchIntegration(TestBase):
7474
search_attributes = {
7575
SpanAttributes.DB_SYSTEM: "elasticsearch",
@@ -96,7 +96,7 @@ def tearDown(self):
9696
ElasticsearchInstrumentor().uninstrument()
9797

9898
def test_instrumentor(self, request_mock):
99-
request_mock.return_value = (1, {}, "{}")
99+
request_mock.return_value = helpers.mock_response("{}")
100100

101101
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
102102
es.index(
@@ -147,7 +147,7 @@ def test_prefix_arg(self, request_mock):
147147
prefix = "prefix-from-env"
148148
ElasticsearchInstrumentor().uninstrument()
149149
ElasticsearchInstrumentor(span_name_prefix=prefix).instrument()
150-
request_mock.return_value = (1, {}, "{}")
150+
request_mock.return_value = helpers.mock_response("{}")
151151
self._test_prefix(prefix)
152152

153153
def test_prefix_env(self, request_mock):
@@ -156,7 +156,7 @@ def test_prefix_env(self, request_mock):
156156
os.environ[env_var] = prefix
157157
ElasticsearchInstrumentor().uninstrument()
158158
ElasticsearchInstrumentor().instrument()
159-
request_mock.return_value = (1, {}, "{}")
159+
request_mock.return_value = helpers.mock_response("{}")
160160
del os.environ[env_var]
161161
self._test_prefix(prefix)
162162

@@ -174,10 +174,8 @@ def _test_prefix(self, prefix):
174174
self.assertTrue(span.name.startswith(prefix))
175175

176176
def test_result_values(self, request_mock):
177-
request_mock.return_value = (
178-
1,
179-
{},
180-
'{"found": false, "timed_out": true, "took": 7}',
177+
request_mock.return_value = helpers.mock_response(
178+
'{"found": false, "timed_out": true, "took": 7}'
181179
)
182180
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
183181
es.get(
@@ -201,8 +199,11 @@ def test_trace_error_unknown(self, request_mock):
201199

202200
def test_trace_error_not_found(self, request_mock):
203201
msg = "record not found"
204-
exc = elasticsearch.exceptions.NotFoundError(404, msg)
205-
request_mock.return_value = (1, {}, "{}")
202+
if major_version == 8:
203+
exc = elasticsearch.exceptions.NotFoundError(404, msg, body=None)
204+
else:
205+
exc = elasticsearch.exceptions.NotFoundError(404, msg)
206+
request_mock.return_value = helpers.mock_response("{}")
206207
request_mock.side_effect = exc
207208
self._test_trace_error(StatusCode.ERROR, exc)
208209

@@ -227,7 +228,7 @@ def _test_trace_error(self, code, exc):
227228
)
228229

229230
def test_parent(self, request_mock):
230-
request_mock.return_value = (1, {}, "{}")
231+
request_mock.return_value = helpers.mock_response("{}")
231232
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
232233
with self.tracer.start_as_current_span("parent"):
233234
es.index(
@@ -245,7 +246,7 @@ def test_parent(self, request_mock):
245246
self.assertEqual(child.parent.span_id, parent.context.span_id)
246247

247248
def test_multithread(self, request_mock):
248-
request_mock.return_value = (1, {}, "{}")
249+
request_mock.return_value = helpers.mock_response("{}")
249250
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
250251
ev = threading.Event()
251252

@@ -292,7 +293,9 @@ def target2():
292293
self.assertIsNone(s3.parent)
293294

294295
def test_dsl_search(self, request_mock):
295-
request_mock.return_value = (1, {}, '{"hits": {"hits": []}}')
296+
request_mock.return_value = helpers.mock_response(
297+
'{"hits": {"hits": []}}'
298+
)
296299

297300
client = get_elasticsearch_client(hosts=["http://localhost:9200"])
298301
search = Search(using=client, index="test-index").filter(
@@ -310,7 +313,9 @@ def test_dsl_search(self, request_mock):
310313
)
311314

312315
def test_dsl_search_sanitized(self, request_mock):
313-
request_mock.return_value = (1, {}, '{"hits": {"hits": []}}')
316+
request_mock.return_value = helpers.mock_response(
317+
'{"hits": {"hits": []}}'
318+
)
314319
client = get_elasticsearch_client(hosts=["http://localhost:9200"])
315320
search = Search(using=client, index="test-index").filter(
316321
"term", author="testing"
@@ -327,7 +332,7 @@ def test_dsl_search_sanitized(self, request_mock):
327332
)
328333

329334
def test_dsl_create(self, request_mock):
330-
request_mock.return_value = (1, {}, "{}")
335+
request_mock.return_value = helpers.mock_response("{}")
331336
client = get_elasticsearch_client(hosts=["http://localhost:9200"])
332337
Article.init(using=client)
333338

@@ -354,7 +359,7 @@ def test_dsl_create(self, request_mock):
354359
)
355360

356361
def test_dsl_create_sanitized(self, request_mock):
357-
request_mock.return_value = (1, {}, "{}")
362+
request_mock.return_value = helpers.mock_response("{}")
358363
client = get_elasticsearch_client(hosts=["http://localhost:9200"])
359364
Article.init(using=client)
360365

@@ -370,7 +375,9 @@ def test_dsl_create_sanitized(self, request_mock):
370375
)
371376

372377
def test_dsl_index(self, request_mock):
373-
request_mock.return_value = (1, {}, helpers.dsl_index_result[2])
378+
request_mock.return_value = helpers.mock_response(
379+
helpers.dsl_index_result[2]
380+
)
374381

375382
client = get_elasticsearch_client(hosts=["http://localhost:9200"])
376383
article = Article(
@@ -404,6 +411,9 @@ def test_request_hook(self, request_mock):
404411
request_hook_kwargs_attribute = "request_hook.kwargs"
405412

406413
def request_hook(span, method, url, kwargs):
414+
# FIXME: this is done only to get tests passing, need a more clueful solution
415+
if major_version == 8:
416+
kwargs = dict(kwargs["headers"])
407417
attributes = {
408418
request_hook_method_attribute: method,
409419
request_hook_url_attribute: url,
@@ -416,10 +426,8 @@ def request_hook(span, method, url, kwargs):
416426
ElasticsearchInstrumentor().uninstrument()
417427
ElasticsearchInstrumentor().instrument(request_hook=request_hook)
418428

419-
request_mock.return_value = (
420-
1,
421-
{},
422-
'{"found": false, "timed_out": true, "took": 7}',
429+
request_mock.return_value = helpers.mock_response(
430+
'{"found": false, "timed_out": true, "took": 7}'
423431
)
424432
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
425433
index = "test-index"
@@ -439,12 +447,19 @@ def request_hook(span, method, url, kwargs):
439447
"GET", spans[0].attributes[request_hook_method_attribute]
440448
)
441449
expected_url = f"/{index}/_doc/{doc_id}"
450+
if major_version == 8:
451+
expected_url += "?realtime=true&refresh=true"
442452
self.assertEqual(
443453
expected_url,
444454
spans[0].attributes[request_hook_url_attribute],
445455
)
446456

447-
if major_version == 7:
457+
if major_version == 8:
458+
# FIXME: kwargs passed to request_hook on 8 are completely different
459+
expected_kwargs = {
460+
"accept": "application/vnd.elasticsearch+json; compatible-with=8"
461+
}
462+
elif major_version == 7:
448463
expected_kwargs = {
449464
**kwargs,
450465
"headers": {"accept": "application/json"},
@@ -461,6 +476,9 @@ def test_response_hook(self, request_mock):
461476

462477
def response_hook(span, response):
463478
if span and span.is_recording():
479+
# FIXME: something more clean
480+
if major_version == 8:
481+
response = response.body
464482
span.set_attribute(
465483
response_attribute_name, json.dumps(response)
466484
)
@@ -492,7 +510,9 @@ def response_hook(span, response):
492510
},
493511
}
494512

495-
request_mock.return_value = (1, {}, json.dumps(response_payload))
513+
request_mock.return_value = helpers.mock_response(
514+
json.dumps(response_payload)
515+
)
496516
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
497517
es.get(
498518
index="test-index", **normalize_arguments(doc_type="_doc"), id=1
@@ -512,7 +532,7 @@ def test_no_op_tracer_provider(self, request_mock):
512532
tracer_provider=trace.NoOpTracerProvider()
513533
)
514534
response_payload = '{"found": false, "timed_out": true, "took": 7}'
515-
request_mock.return_value = (1, {}, response_payload)
535+
request_mock.return_value = helpers.mock_response(response_payload)
516536
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
517537
res = es.get(
518538
index="test-index", **normalize_arguments(doc_type="_doc"), id=1
@@ -543,7 +563,7 @@ def test_body_sanitization(self, _):
543563
)
544564

545565
def test_bulk(self, request_mock):
546-
request_mock.return_value = (1, {}, "{}")
566+
request_mock.return_value = helpers.mock_response("{}")
547567

548568
es = get_elasticsearch_client(hosts=["http://localhost:9200"])
549569
es.bulk(

tox.ini

+4-2
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,9 @@ envlist =
7979
; below mean these dependencies are being used:
8080
; 0: elasticsearch-dsl==6.4.0 elasticsearch==6.8.2
8181
; 1: elasticsearch-dsl==7.4.1 elasticsearch==7.17.9
82-
py3{8,9,10,11}-test-instrumentation-elasticsearch-{0,1}
83-
pypy3-test-instrumentation-elasticsearch-{0,1}
82+
; 2: elasticsearch-dsl>=8.0,<8.13 elasticsearch>=8.0,<8.13
83+
py3{8,9,10,11}-test-instrumentation-elasticsearch-{0,1,2}
84+
pypy3-test-instrumentation-elasticsearch-{0,1,2}
8485

8586
; opentelemetry-instrumentation-falcon
8687
; py310 does not work with falcon 1
@@ -645,6 +646,7 @@ commands_pre =
645646
elasticsearch: pip install opentelemetry-test-utils@{env:CORE_REPO}\#egg=opentelemetry-test-utils&subdirectory=tests/opentelemetry-test-utils
646647
elasticsearch-0: pip install -r {toxinidir}/instrumentation/opentelemetry-instrumentation-elasticsearch/test-requirements-0.txt
647648
elasticsearch-1: pip install -r {toxinidir}/instrumentation/opentelemetry-instrumentation-elasticsearch/test-requirements-1.txt
649+
elasticsearch-2: pip install -r {toxinidir}/instrumentation/opentelemetry-instrumentation-elasticsearch/test-requirements-2.txt
648650

649651
asyncio: pip install opentelemetry-api@{env:CORE_REPO}\#egg=opentelemetry-api&subdirectory=opentelemetry-api
650652
asyncio: pip install opentelemetry-semantic-conventions@{env:CORE_REPO}\#egg=opentelemetry-semantic-conventions&subdirectory=opentelemetry-semantic-conventions

0 commit comments

Comments
 (0)