This repository was archived by the owner on Sep 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathtest_django_middleware.py
More file actions
475 lines (368 loc) · 15.4 KB
/
test_django_middleware.py
File metadata and controls
475 lines (368 loc) · 15.4 KB
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# Copyright 2017, OpenCensus 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 sys
import traceback
import unittest
import mock
from django.test import RequestFactory, override_settings
from django.test.utils import teardown_test_environment
from opencensus.trace import execution_context, print_exporter, samplers
from opencensus.trace import span as span_module
from opencensus.trace import utils
from opencensus.trace.blank_span import BlankSpan
from opencensus.trace.propagation import trace_context_http_header_format
class TestOpencensusMiddleware(unittest.TestCase):
def setUp(self):
from django.conf import settings as django_settings
from django.test.utils import setup_test_environment
if not django_settings.configured:
django_settings.configure()
setup_test_environment()
def tearDown(self):
execution_context.clear()
teardown_test_environment()
def test_constructor_default(self):
from opencensus.ext.django import middleware
middleware = middleware.OpencensusMiddleware()
assert isinstance(middleware.sampler, samplers.ProbabilitySampler)
assert isinstance(middleware.exporter, print_exporter.PrintExporter)
assert isinstance(
middleware.propagator,
trace_context_http_header_format.TraceContextPropagator,
)
def test_configuration(self):
from opencensus.ext.django import middleware
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
'EXPORTER': 'opencensus.trace.print_exporter.PrintExporter()', # noqa
'PROPAGATOR': 'opencensus.trace.propagation.trace_context_http_header_format.TraceContextPropagator()', # noqa
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)
with patch_settings:
middleware = middleware.OpencensusMiddleware()
assert isinstance(middleware.sampler, samplers.AlwaysOnSampler)
assert isinstance(middleware.exporter, print_exporter.PrintExporter)
assert isinstance(
middleware.propagator,
trace_context_http_header_format.TraceContextPropagator,
)
def test_process_request(self):
from opencensus.ext.django import middleware
trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
span_id = '6e0c63257de34c92'
django_trace_id = '00-{}-{}-00'.format(trace_id, span_id)
django_request = RequestFactory().get('/wiki/Rabbit', **{
'HTTP_TRACEPARENT': django_trace_id})
# Force the test request to be sampled
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)
with patch_settings:
middleware_obj = middleware.OpencensusMiddleware()
# test process_request
middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
expected_attributes = {
'http.host': u'testserver',
'http.method': 'GET',
'http.path': u'/wiki/Rabbit',
'http.route': u'/wiki/Rabbit',
'http.url': u'http://testserver/wiki/Rabbit',
}
self.assertEqual(span.span_kind, span_module.SpanKind.SERVER)
self.assertEqual(span.attributes, expected_attributes)
self.assertEqual(span.parent_span.span_id, span_id)
span_context = tracer.span_context
self.assertEqual(span_context.trace_id, trace_id)
# test process_view
view_func = mock.Mock()
middleware_obj.process_view(django_request, view_func)
self.assertEqual(span.name, 'mock.mock.Mock')
@override_settings(ALLOWED_HOSTS=['allowedhost'])
def test_process_request_with_disallowed_host(self):
from opencensus.ext.django import middleware
trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
span_id = '6e0c63257de34c92'
django_trace_id = '00-{}-{}-00'.format(trace_id, span_id)
django_request = RequestFactory().get('/wiki/Rabbit', **{
'HTTP_HOST': 'notallowedhost',
'HTTP_TRACEPARENT': django_trace_id})
# Force the test request to be sampled
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)
with patch_settings:
middleware_obj = middleware.OpencensusMiddleware()
# test process_request
middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
expected_attributes = {
'http.host': u'notallowedhost',
'http.method': 'GET',
'http.path': u'/wiki/Rabbit',
'http.route': u'/wiki/Rabbit',
'http.url': u'http://notallowedhost/wiki/Rabbit',
}
self.assertEqual(span.span_kind, span_module.SpanKind.SERVER)
self.assertEqual(span.attributes, expected_attributes)
self.assertEqual(span.parent_span.span_id, span_id)
span_context = tracer.span_context
self.assertEqual(span_context.trace_id, trace_id)
# test process_view
view_func = mock.Mock()
middleware_obj.process_view(django_request, view_func)
self.assertEqual(span.name, 'mock.mock.Mock')
def test_excludelist_path(self):
from opencensus.ext.django import middleware
execution_context.clear()
excludelist_paths = ['test_excludelist_path']
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
'EXCLUDELIST_PATHS': excludelist_paths,
'EXPORTER': mock.Mock(),
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)
with patch_settings:
middleware_obj = middleware.OpencensusMiddleware()
django_request = RequestFactory().get('/test_excludelist_path')
disabled = utils.disable_tracing_url(django_request.path,
excludelist_paths)
self.assertTrue(disabled)
self.assertEqual(middleware_obj.excludelist_paths, excludelist_paths)
# test process_request
middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
# process view
view_func = mock.Mock()
middleware_obj.process_view(django_request, view_func)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
assert isinstance(span, BlankSpan)
# process response
django_response = mock.Mock()
django_response.status_code = 200
middleware_obj.process_response(django_request, django_response)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
assert isinstance(span, BlankSpan)
def test_process_response(self):
from opencensus.ext.django import middleware
trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
span_id = '6e0c63257de34c92'
django_trace_id = '00-{}-{}-00'.format(trace_id, span_id)
django_request = RequestFactory().get('/wiki/Rabbit', **{
'traceparent': django_trace_id,
})
# Force the test request to be sampled
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)
with patch_settings:
middleware_obj = middleware.OpencensusMiddleware()
middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
exporter_mock = mock.Mock()
tracer.exporter = exporter_mock
django_response = mock.Mock()
django_response.status_code = 200
expected_attributes = {
'http.host': u'testserver',
'http.method': 'GET',
'http.path': u'/wiki/Rabbit',
'http.route': u'/wiki/Rabbit',
'http.url': u'http://testserver/wiki/Rabbit',
'http.status_code': 200,
'django.user.id': '123',
'django.user.name': 'test_name'
}
mock_user = mock.Mock()
mock_user.pk = 123
mock_user.get_username.return_value = 'test_name'
django_request.user = mock_user
middleware_obj.process_response(django_request, django_response)
self.assertEqual(span.attributes, expected_attributes)
def test_process_response_unfinished_child_span(self):
from opencensus.ext.django import middleware
trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
span_id = '6e0c63257de34c92'
django_trace_id = '00-{}-{}-00'.format(trace_id, span_id)
django_request = RequestFactory().get('/wiki/Rabbit', **{
'traceparent': django_trace_id,
})
# Force the test request to be sampled
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)
with patch_settings:
middleware_obj = middleware.OpencensusMiddleware()
middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
exporter_mock = mock.Mock()
tracer.exporter = exporter_mock
django_response = mock.Mock()
django_response.status_code = 500
expected_attributes = {
'http.host': u'testserver',
'http.method': 'GET',
'http.path': u'/wiki/Rabbit',
'http.route': u'/wiki/Rabbit',
'http.url': u'http://testserver/wiki/Rabbit',
'http.status_code': 500,
'django.user.id': '123',
'django.user.name': 'test_name'
}
mock_user = mock.Mock()
mock_user.pk = 123
mock_user.get_username.return_value = 'test_name'
django_request.user = mock_user
tracer.start_span()
self.assertNotEqual(span, tracer.current_span())
middleware_obj.process_response(django_request, django_response)
self.assertEqual(span.attributes, expected_attributes)
def test_process_exception(self):
from opencensus.ext.django import middleware
trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
span_id = '6e0c63257de34c92'
django_trace_id = '00-{}-{}-00'.format(trace_id, span_id)
django_request = RequestFactory().get('/wiki/Rabbit', **{
'traceparent': django_trace_id,
})
# Force the test request to be sampled
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)
with patch_settings:
middleware_obj = middleware.OpencensusMiddleware()
tb = None
try:
raise RuntimeError("bork bork bork")
except Exception as exc:
test_exception = exc
if hasattr(exc, "__traceback__"):
tb = exc.__traceback__
else:
_, _, tb = sys.exc_info()
middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()
exporter_mock = mock.Mock()
tracer.exporter = exporter_mock
django_response = mock.Mock()
django_response.status_code = 200
expected_attributes = {
'http.host': u'testserver',
'http.method': 'GET',
'http.path': u'/wiki/Rabbit',
'http.route': u'/wiki/Rabbit',
'http.url': u'http://testserver/wiki/Rabbit',
'django.user.id': '123',
'django.user.name': 'test_name',
'error.name': "RuntimeError",
'error.message': 'bork bork bork',
'stacktrace': '\n'.join(traceback.format_tb(tb))
}
mock_user = mock.Mock()
mock_user.pk = 123
mock_user.get_username.return_value = 'test_name'
django_request.user = mock_user
middleware_obj.process_exception(django_request, test_exception)
self.assertEqual(span.attributes, expected_attributes)
class Test__set_django_attributes(unittest.TestCase):
class Span(object):
def __init__(self):
self.attributes = {}
def add_attribute(self, key, value):
self.attributes[key] = value
def test__set_django_attributes_no_user(self):
from opencensus.ext.django.middleware import \
_set_django_attributes
span = self.Span()
request = mock.Mock()
request.user = None
_set_django_attributes(span, request)
expected_attributes = {}
self.assertEqual(span.attributes, expected_attributes)
def test__set_django_attributes_no_user_info(self):
from opencensus.ext.django.middleware import \
_set_django_attributes
span = self.Span()
request = mock.Mock()
django_user = mock.Mock()
request.user = django_user
django_user.pk = None
django_user.get_username.return_value = None
_set_django_attributes(span, request)
expected_attributes = {}
self.assertEqual(span.attributes, expected_attributes)
def test__set_django_attributes_with_user_info(self):
from opencensus.ext.django.middleware import \
_set_django_attributes
span = self.Span()
request = mock.Mock()
django_user = mock.Mock()
request.user = django_user
test_id = 123
test_name = 'test_name'
django_user.pk = test_id
django_user.get_username.return_value = test_name
_set_django_attributes(span, request)
expected_attributes = {
'django.user.id': '123',
'django.user.name': test_name}
self.assertEqual(span.attributes, expected_attributes)