forked from open-telemetry/opentelemetry-python-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_programmatic.py
425 lines (346 loc) · 14.6 KB
/
test_programmatic.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# 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.
from unittest.mock import Mock, patch
from flask import Flask, request
from opentelemetry import trace
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.propagators import (
TraceResponsePropagator,
get_global_response_propagator,
set_global_response_propagator,
)
from opentelemetry.sdk.resources import Resource
from opentelemetry.semconv.trace import SpanAttributes
from opentelemetry.test.test_base import TestBase
from opentelemetry.test.wsgitestutil import WsgiTestBase
from opentelemetry.util.http import get_excluded_urls
# pylint: disable=import-error
from .base_test import InstrumentationTest
def expected_attributes(override_attributes):
default_attributes = {
SpanAttributes.HTTP_METHOD: "GET",
SpanAttributes.HTTP_SERVER_NAME: "localhost",
SpanAttributes.HTTP_SCHEME: "http",
SpanAttributes.NET_HOST_PORT: 80,
SpanAttributes.HTTP_HOST: "localhost",
SpanAttributes.HTTP_TARGET: "/",
SpanAttributes.HTTP_FLAVOR: "1.1",
SpanAttributes.HTTP_STATUS_CODE: 200,
}
for key, val in override_attributes.items():
default_attributes[key] = val
return default_attributes
class TestProgrammatic(InstrumentationTest, TestBase, WsgiTestBase):
def setUp(self):
super().setUp()
self.env_patch = patch.dict(
"os.environ",
{
"OTEL_PYTHON_FLASK_EXCLUDED_URLS": "http://localhost/env_excluded_arg/123,env_excluded_noarg"
},
)
self.env_patch.start()
self.exclude_patch = patch(
"opentelemetry.instrumentation.flask._excluded_urls_from_env",
get_excluded_urls("FLASK"),
)
self.exclude_patch.start()
self.app = Flask(__name__)
FlaskInstrumentor().instrument_app(self.app)
self._common_initialization()
def tearDown(self):
super().tearDown()
self.env_patch.stop()
self.exclude_patch.stop()
with self.disable_logging():
FlaskInstrumentor().uninstrument_app(self.app)
def test_instrument_app_and_instrument(self):
FlaskInstrumentor().instrument()
resp = self.client.get("/hello/123")
self.assertEqual(200, resp.status_code)
self.assertEqual([b"Hello: 123"], list(resp.response))
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
FlaskInstrumentor().uninstrument()
def test_uninstrument_app(self):
resp = self.client.get("/hello/123")
self.assertEqual(200, resp.status_code)
self.assertEqual([b"Hello: 123"], list(resp.response))
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
FlaskInstrumentor().uninstrument_app(self.app)
resp = self.client.get("/hello/123")
self.assertEqual(200, resp.status_code)
self.assertEqual([b"Hello: 123"], list(resp.response))
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
def test_uninstrument_app_after_instrument(self):
FlaskInstrumentor().instrument()
FlaskInstrumentor().uninstrument_app(self.app)
resp = self.client.get("/hello/123")
self.assertEqual(200, resp.status_code)
self.assertEqual([b"Hello: 123"], list(resp.response))
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 0)
FlaskInstrumentor().uninstrument()
# pylint: disable=no-member
def test_only_strings_in_environ(self):
"""
Some WSGI servers (such as Gunicorn) expect keys in the environ object
to be strings
OpenTelemetry should adhere to this convention.
"""
nonstring_keys = set()
def assert_environ():
for key in request.environ:
if not isinstance(key, str):
nonstring_keys.add(key)
return "hi"
self.app.route("/assert_environ")(assert_environ)
self.client.get("/assert_environ")
self.assertEqual(nonstring_keys, set())
def test_simple(self):
expected_attrs = expected_attributes(
{
SpanAttributes.HTTP_TARGET: "/hello/123",
SpanAttributes.HTTP_ROUTE: "/hello/<int:helloid>",
}
)
self.client.get("/hello/123")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(span_list[0].name, "/hello/<int:helloid>")
self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER)
self.assertEqual(span_list[0].attributes, expected_attrs)
def test_trace_response(self):
orig = get_global_response_propagator()
set_global_response_propagator(TraceResponsePropagator())
response = self.client.get("/hello/123")
headers = response.headers
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
span = span_list[0]
self.assertIn("traceresponse", headers)
self.assertEqual(
headers["access-control-expose-headers"], "traceresponse",
)
self.assertEqual(
headers["traceresponse"],
"00-{0}-{1}-01".format(
trace.format_trace_id(span.get_span_context().trace_id),
trace.format_span_id(span.get_span_context().span_id),
),
)
set_global_response_propagator(orig)
def test_not_recording(self):
mock_tracer = Mock()
mock_span = Mock()
mock_span.is_recording.return_value = False
mock_tracer.start_span.return_value = mock_span
with patch("opentelemetry.trace.get_tracer") as tracer:
tracer.return_value = mock_tracer
self.client.get("/hello/123")
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_404(self):
expected_attrs = expected_attributes(
{
SpanAttributes.HTTP_METHOD: "POST",
SpanAttributes.HTTP_TARGET: "/bye",
SpanAttributes.HTTP_STATUS_CODE: 404,
}
)
resp = self.client.post("/bye")
self.assertEqual(404, resp.status_code)
resp.close()
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(span_list[0].name, "HTTP POST")
self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER)
self.assertEqual(span_list[0].attributes, expected_attrs)
def test_internal_error(self):
expected_attrs = expected_attributes(
{
SpanAttributes.HTTP_TARGET: "/hello/500",
SpanAttributes.HTTP_ROUTE: "/hello/<int:helloid>",
SpanAttributes.HTTP_STATUS_CODE: 500,
}
)
resp = self.client.get("/hello/500")
self.assertEqual(500, resp.status_code)
resp.close()
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(span_list[0].name, "/hello/<int:helloid>")
self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER)
self.assertEqual(span_list[0].attributes, expected_attrs)
def test_exclude_lists_from_env(self):
self.client.get("/env_excluded_arg/123")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 0)
self.client.get("/env_excluded_arg/125")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.client.get("/env_excluded_noarg")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.client.get("/env_excluded_noarg2")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
def test_exclude_lists_from_explicit(self):
excluded_urls = "http://localhost/explicit_excluded_arg/123,explicit_excluded_noarg"
app = Flask(__name__)
FlaskInstrumentor().instrument_app(app, excluded_urls=excluded_urls)
client = app.test_client()
client.get("/explicit_excluded_arg/123")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 0)
client.get("/explicit_excluded_arg/125")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
client.get("/explicit_excluded_noarg")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
client.get("/explicit_excluded_noarg2")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
class TestProgrammaticHooks(InstrumentationTest, TestBase, WsgiTestBase):
def setUp(self):
super().setUp()
hook_headers = (
"hook_attr",
"hello otel",
)
def request_hook_test(span, environ):
span.update_name("name from hook")
def response_hook_test(span, environ, response_headers):
span.set_attribute("hook_attr", "hello world")
response_headers.append(hook_headers)
self.app = Flask(__name__)
FlaskInstrumentor().instrument_app(
self.app,
request_hook=request_hook_test,
response_hook=response_hook_test,
)
self._common_initialization()
def tearDown(self):
super().tearDown()
with self.disable_logging():
FlaskInstrumentor().uninstrument_app(self.app)
def test_hooks(self):
expected_attrs = expected_attributes(
{
"http.target": "/hello/123",
"http.route": "/hello/<int:helloid>",
"hook_attr": "hello world",
}
)
resp = self.client.get("/hello/123")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(span_list[0].name, "name from hook")
self.assertEqual(span_list[0].attributes, expected_attrs)
self.assertEqual(resp.headers["hook_attr"], "hello otel")
class TestProgrammaticHooksWithoutApp(
InstrumentationTest, TestBase, WsgiTestBase
):
def setUp(self):
super().setUp()
hook_headers = (
"hook_attr",
"hello otel without app",
)
def request_hook_test(span, environ):
span.update_name("without app")
def response_hook_test(span, environ, response_headers):
span.set_attribute("hook_attr", "hello world without app")
response_headers.append(hook_headers)
FlaskInstrumentor().instrument(
request_hook=request_hook_test, response_hook=response_hook_test
)
# pylint: disable=import-outside-toplevel,reimported,redefined-outer-name
from flask import Flask
self.app = Flask(__name__)
self._common_initialization()
def tearDown(self):
super().tearDown()
with self.disable_logging():
FlaskInstrumentor().uninstrument()
def test_no_app_hooks(self):
expected_attrs = expected_attributes(
{
"http.target": "/hello/123",
"http.route": "/hello/<int:helloid>",
"hook_attr": "hello world without app",
}
)
resp = self.client.get("/hello/123")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(span_list[0].name, "without app")
self.assertEqual(span_list[0].attributes, expected_attrs)
self.assertEqual(resp.headers["hook_attr"], "hello otel without app")
class TestProgrammaticCustomTracerProvider(
InstrumentationTest, TestBase, WsgiTestBase
):
def setUp(self):
super().setUp()
resource = Resource.create({"service.name": "flask-api"})
result = self.create_tracer_provider(resource=resource)
tracer_provider, exporter = result
self.memory_exporter = exporter
self.app = Flask(__name__)
FlaskInstrumentor().instrument_app(
self.app, tracer_provider=tracer_provider
)
self._common_initialization()
def tearDown(self):
super().tearDown()
with self.disable_logging():
FlaskInstrumentor().uninstrument_app(self.app)
def test_custom_span_name(self):
self.client.get("/hello/123")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(
span_list[0].resource.attributes["service.name"], "flask-api"
)
class TestProgrammaticCustomTracerProviderWithoutApp(
InstrumentationTest, TestBase, WsgiTestBase
):
def setUp(self):
super().setUp()
resource = Resource.create({"service.name": "flask-api-no-app"})
result = self.create_tracer_provider(resource=resource)
tracer_provider, exporter = result
self.memory_exporter = exporter
FlaskInstrumentor().instrument(tracer_provider=tracer_provider)
# pylint: disable=import-outside-toplevel,reimported,redefined-outer-name
from flask import Flask
self.app = Flask(__name__)
self._common_initialization()
def tearDown(self):
super().tearDown()
with self.disable_logging():
FlaskInstrumentor().uninstrument()
def test_custom_span_name(self):
self.client.get("/hello/123")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(
span_list[0].resource.attributes["service.name"],
"flask-api-no-app",
)