-
Notifications
You must be signed in to change notification settings - Fork 651
/
test_requests_integration.py
393 lines (333 loc) · 13.7 KB
/
test_requests_integration.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
from unittest import mock
import httpretty
import requests
import opentelemetry.instrumentation.requests
from opentelemetry import context, propagators, trace
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.sdk import resources
from opentelemetry.sdk.util import get_dict_as_key
from opentelemetry.test.mock_textmap import MockTextMapPropagator
from opentelemetry.test.test_base import TestBase
from opentelemetry.trace.status import StatusCanonicalCode
class RequestsIntegrationTestBase(abc.ABC):
# pylint: disable=no-member
URL = "http://httpbin.org/status/200"
# pylint: disable=invalid-name
def setUp(self):
super().setUp()
RequestsInstrumentor().instrument()
httpretty.enable()
httpretty.register_uri(httpretty.GET, self.URL, body="Hello!")
# pylint: disable=invalid-name
def tearDown(self):
super().tearDown()
RequestsInstrumentor().uninstrument()
httpretty.disable()
def assert_span(self, exporter=None, num_spans=1):
if exporter is None:
exporter = self.memory_exporter
span_list = exporter.get_finished_spans()
self.assertEqual(num_spans, len(span_list))
if num_spans == 0:
return None
if num_spans == 1:
return span_list[0]
return span_list
@staticmethod
@abc.abstractmethod
def perform_request(url: str, session: requests.Session = None):
pass
def test_basic(self):
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
span = self.assert_span()
self.assertIs(span.kind, trace.SpanKind.CLIENT)
self.assertEqual(span.name, "HTTP GET")
self.assertEqual(
span.attributes,
{
"component": "http",
"http.method": "GET",
"http.url": self.URL,
"http.status_code": 200,
"http.status_text": "OK",
},
)
self.assertIs(
span.status.canonical_code, trace.status.StatusCanonicalCode.OK
)
self.check_span_instrumentation_info(
span, opentelemetry.instrumentation.requests
)
self.assertIsNotNone(RequestsInstrumentor().meter)
self.assertEqual(len(RequestsInstrumentor().meter.metrics), 1)
recorder = RequestsInstrumentor().meter.metrics.pop()
match_key = get_dict_as_key(
{
"http.flavor": "1.1",
"http.method": "GET",
"http.status_code": "200",
"http.url": "http://httpbin.org/status/200",
}
)
for key in recorder.bound_instruments.keys():
self.assertEqual(key, match_key)
# pylint: disable=protected-access
bound = recorder.bound_instruments.get(key)
for view_data in bound.view_datas:
self.assertEqual(view_data.labels, key)
self.assertEqual(view_data.aggregator.current.count, 1)
self.assertGreaterEqual(view_data.aggregator.current.sum, 0)
def test_not_foundbasic(self):
url_404 = "http://httpbin.org/status/404"
httpretty.register_uri(
httpretty.GET, url_404, status=404,
)
result = self.perform_request(url_404)
self.assertEqual(result.status_code, 404)
span = self.assert_span()
self.assertEqual(span.attributes.get("http.status_code"), 404)
self.assertEqual(span.attributes.get("http.status_text"), "Not Found")
self.assertIs(
span.status.canonical_code,
trace.status.StatusCanonicalCode.NOT_FOUND,
)
def test_uninstrument(self):
RequestsInstrumentor().uninstrument()
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
self.assert_span(num_spans=0)
# instrument again to avoid annoying warning message
RequestsInstrumentor().instrument()
def test_uninstrument_session(self):
session1 = requests.Session()
RequestsInstrumentor().uninstrument_session(session1)
result = self.perform_request(self.URL, session1)
self.assertEqual(result.text, "Hello!")
self.assert_span(num_spans=0)
# Test that other sessions as well as global requests is still
# instrumented
session2 = requests.Session()
result = self.perform_request(self.URL, session2)
self.assertEqual(result.text, "Hello!")
self.assert_span()
self.memory_exporter.clear()
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
self.assert_span()
def test_suppress_instrumentation(self):
token = context.attach(
context.set_value("suppress_instrumentation", True)
)
try:
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
finally:
context.detach(token)
self.assert_span(num_spans=0)
def test_not_recording(self):
with mock.patch("opentelemetry.trace.INVALID_SPAN") as mock_span:
RequestsInstrumentor().uninstrument()
# original_tracer_provider returns a default tracer provider, which
# in turn will return an INVALID_SPAN, which is always not recording
RequestsInstrumentor().instrument(
tracer_provider=self.original_tracer_provider
)
mock_span.is_recording.return_value = False
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
self.assert_span(None, 0)
self.assertFalse(mock_span.is_recording())
self.assertTrue(mock_span.is_recording.called)
self.assertFalse(mock_span.set_attribute.called)
self.assertFalse(mock_span.set_status.called)
def test_distributed_context(self):
previous_propagator = propagators.get_global_textmap()
try:
propagators.set_global_textmap(MockTextMapPropagator())
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
span = self.assert_span()
headers = dict(httpretty.last_request().headers)
self.assertIn(MockTextMapPropagator.TRACE_ID_KEY, headers)
self.assertEqual(
str(span.get_span_context().trace_id),
headers[MockTextMapPropagator.TRACE_ID_KEY],
)
self.assertIn(MockTextMapPropagator.SPAN_ID_KEY, headers)
self.assertEqual(
str(span.get_span_context().span_id),
headers[MockTextMapPropagator.SPAN_ID_KEY],
)
finally:
propagators.set_global_textmap(previous_propagator)
def test_span_callback(self):
RequestsInstrumentor().uninstrument()
def span_callback(span, result: requests.Response):
span.set_attribute(
"http.response.body", result.content.decode("utf-8")
)
RequestsInstrumentor().instrument(
tracer_provider=self.tracer_provider, span_callback=span_callback,
)
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
span = self.assert_span()
self.assertEqual(
span.attributes,
{
"component": "http",
"http.method": "GET",
"http.url": self.URL,
"http.status_code": 200,
"http.status_text": "OK",
"http.response.body": "Hello!",
},
)
def test_custom_tracer_provider(self):
resource = resources.Resource.create({})
result = self.create_tracer_provider(resource=resource)
tracer_provider, exporter = result
RequestsInstrumentor().uninstrument()
RequestsInstrumentor().instrument(tracer_provider=tracer_provider)
result = self.perform_request(self.URL)
self.assertEqual(result.text, "Hello!")
span = self.assert_span(exporter=exporter)
self.assertIs(span.resource, resource)
@mock.patch(
"requests.adapters.HTTPAdapter.send",
side_effect=requests.RequestException,
)
def test_requests_exception_without_response(self, *_, **__):
with self.assertRaises(requests.RequestException):
self.perform_request(self.URL)
span = self.assert_span()
self.assertEqual(
span.attributes,
{"component": "http", "http.method": "GET", "http.url": self.URL},
)
self.assertEqual(
span.status.canonical_code, StatusCanonicalCode.UNKNOWN
)
self.assertIsNotNone(RequestsInstrumentor().meter)
self.assertEqual(len(RequestsInstrumentor().meter.metrics), 1)
recorder = RequestsInstrumentor().meter.metrics.pop()
match_key = get_dict_as_key(
{
"http.method": "GET",
"http.url": "http://httpbin.org/status/200",
}
)
for key in recorder.bound_instruments.keys():
self.assertEqual(key, match_key)
# pylint: disable=protected-access
bound = recorder.bound_instruments.get(key)
for view_data in bound.view_datas:
self.assertEqual(view_data.labels, key)
self.assertEqual(view_data.aggregator.current.count, 1)
mocked_response = requests.Response()
mocked_response.status_code = 500
mocked_response.reason = "Internal Server Error"
@mock.patch(
"requests.adapters.HTTPAdapter.send",
side_effect=requests.RequestException(response=mocked_response),
)
def test_requests_exception_with_response(self, *_, **__):
with self.assertRaises(requests.RequestException):
self.perform_request(self.URL)
span = self.assert_span()
self.assertEqual(
span.attributes,
{
"component": "http",
"http.method": "GET",
"http.url": self.URL,
"http.status_code": 500,
"http.status_text": "Internal Server Error",
},
)
self.assertEqual(
span.status.canonical_code, StatusCanonicalCode.INTERNAL
)
self.assertIsNotNone(RequestsInstrumentor().meter)
self.assertEqual(len(RequestsInstrumentor().meter.metrics), 1)
recorder = RequestsInstrumentor().meter.metrics.pop()
match_key = get_dict_as_key(
{
"http.method": "GET",
"http.status_code": "500",
"http.url": "http://httpbin.org/status/200",
}
)
for key in recorder.bound_instruments.keys():
self.assertEqual(key, match_key)
# pylint: disable=protected-access
bound = recorder.bound_instruments.get(key)
for view_data in bound.view_datas:
self.assertEqual(view_data.labels, key)
self.assertEqual(view_data.aggregator.current.count, 1)
@mock.patch("requests.adapters.HTTPAdapter.send", side_effect=Exception)
def test_requests_basic_exception(self, *_, **__):
with self.assertRaises(Exception):
self.perform_request(self.URL)
span = self.assert_span()
self.assertEqual(
span.status.canonical_code, StatusCanonicalCode.UNKNOWN
)
@mock.patch(
"requests.adapters.HTTPAdapter.send", side_effect=requests.Timeout
)
def test_requests_timeout_exception(self, *_, **__):
with self.assertRaises(Exception):
self.perform_request(self.URL)
span = self.assert_span()
self.assertEqual(
span.status.canonical_code, StatusCanonicalCode.DEADLINE_EXCEEDED
)
class TestRequestsIntegration(RequestsIntegrationTestBase, TestBase):
@staticmethod
def perform_request(url: str, session: requests.Session = None):
if session is None:
return requests.get(url)
return session.get(url)
def test_invalid_url(self):
url = "http://[::1/nope"
with self.assertRaises(ValueError):
requests.post(url)
span = self.assert_span()
self.assertEqual(span.name, "HTTP POST")
self.assertEqual(
span.attributes,
{"component": "http", "http.method": "POST", "http.url": url},
)
self.assertEqual(
span.status.canonical_code, StatusCanonicalCode.INVALID_ARGUMENT
)
def test_if_headers_equals_none(self):
result = requests.get(self.URL, headers=None)
self.assertEqual(result.text, "Hello!")
self.assert_span()
class TestRequestsIntegrationPreparedRequest(
RequestsIntegrationTestBase, TestBase
):
@staticmethod
def perform_request(url: str, session: requests.Session = None):
if session is None:
session = requests.Session()
request = requests.Request("GET", url)
prepared_request = session.prepare_request(request)
return session.send(prepared_request)