forked from elastic/apm-agent-python
/
django_tests.py
1273 lines (1024 loc) · 49.2 KB
/
django_tests.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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import pytest # isort:skip
django = pytest.importorskip("django") # isort:skip
import json
import logging
import os
from copy import deepcopy
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.redirects.models import Redirect
from django.contrib.sites.models import Site
from django.core.handlers.wsgi import WSGIRequest
from django.core.management import call_command
from django.core.signals import got_request_exception
from django.db import DatabaseError
from django.http import QueryDict
from django.http.cookie import SimpleCookie
from django.test.client import Client as _TestClient
from django.test.client import ClientHandler as _TestClientHandler
from django.test.utils import override_settings
import mock
from elasticapm.base import Client
from elasticapm.contrib.django.client import client, get_client
from elasticapm.contrib.django.handlers import LoggingHandler
from elasticapm.contrib.django.middleware.wsgi import ElasticAPM
from elasticapm.utils import compat
from tests.contrib.django.testapp.views import IgnoredException, MyException
from tests.utils.compat import middleware_setting
try:
# Django 1.10+
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
try:
from celery.tests.utils import with_eager_tasks
has_with_eager_tasks = True
except ImportError:
from elasticapm.utils.compat import noop_decorator as with_eager_tasks
has_with_eager_tasks = False
class MockClientHandler(_TestClientHandler):
def __call__(self, environ, start_response=[]):
# this pretends doesnt require start_response
return super(MockClientHandler, self).__call__(environ)
class MockMiddleware(ElasticAPM):
def __call__(self, environ, start_response=[]):
# this pretends doesnt require start_response
return list(super(MockMiddleware, self).__call__(environ, start_response))
def test_proxy_responds_as_client():
assert get_client() == client
def test_basic(django_elasticapm_client):
config = {
'APP_ID': 'key',
'ORGANIZATION_ID': 'org',
'SECRET_TOKEN': '99'
}
event_count = len(django_elasticapm_client.events)
with override_settings(ELASTIC_APM=config):
django_elasticapm_client.capture('Message', message='foo')
assert len(django_elasticapm_client.events) == event_count + 1
django_elasticapm_client.events.pop(0)
def test_basic_django(django_elasticapm_client):
django_elasticapm_client.capture('Message', message='foo')
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
log = event['log']
assert 'message' in log
assert log['message'] == 'foo'
assert log['level'] == 'error'
assert log['param_message'] == 'foo'
def test_signal_integration(django_elasticapm_client):
try:
int('hello')
except ValueError:
got_request_exception.send(sender=None, request=None)
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'exception' in event
exc = event['exception']
assert exc['type'] == 'ValueError'
assert exc['message'] == u"ValueError: invalid literal for int() with base 10: 'hello'"
assert exc['handled'] is False
assert event['culprit'] == 'tests.contrib.django.django_tests.test_signal_integration'
def test_view_exception(django_elasticapm_client, client):
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'exception' in event
exc = event['exception']
assert exc['type'] == 'MyException'
assert exc['message'] == 'MyException: view exception'
assert exc['handled'] is False
assert event['culprit'] == 'tests.contrib.django.testapp.views.raise_exc'
def test_view_exception_debug(django_elasticapm_client, client):
django_elasticapm_client.config.debug = False
with override_settings(DEBUG=True):
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 0
def test_view_exception_elasticapm_debug(django_elasticapm_client, client):
django_elasticapm_client.config.debug = True
with override_settings(DEBUG=True):
with pytest.raises(Exception): client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
@pytest.mark.django_db
def test_user_info(django_elasticapm_client, client):
user = User(username='admin', email='admin@example.com')
user.set_password('admin')
user.save()
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'user' in event['context']
user_info = event['context']['user']
assert 'is_authenticated' in user_info
assert not user_info['is_authenticated']
assert user_info['username'] == ''
assert 'email' not in user_info
assert client.login(username='admin', password='admin')
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'user' in event['context']
user_info = event['context']['user']
assert 'is_authenticated' in user_info
assert user_info['is_authenticated']
assert 'username' in user_info
assert user_info['username'] == 'admin'
assert 'email' in user_info
assert user_info['email'] == 'admin@example.com'
@pytest.mark.django_db
def test_user_info_raises_database_error(django_elasticapm_client, client):
user = User(username='admin', email='admin@example.com')
user.set_password('admin')
user.save()
assert client.login(username='admin', password='admin')
with mock.patch("django.contrib.auth.models.User.is_authenticated") as is_authenticated:
is_authenticated.side_effect = DatabaseError("Test Exception")
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'user' in event['context']
user_info = event['context']['user']
assert user_info == {}
@pytest.mark.django_db
def test_user_info_with_custom_user(django_elasticapm_client, client):
with override_settings(AUTH_USER_MODEL='testapp.MyUser'):
from django.contrib.auth import get_user_model
MyUser = get_user_model()
user = MyUser(my_username='admin')
user.set_password('admin')
user.save()
assert client.login(username='admin', password='admin')
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'user' in event['context']
user_info = event['context']['user']
assert 'is_authenticated' in user_info
assert user_info['is_authenticated']
assert 'username' in user_info
assert user_info['username'] == 'admin'
assert 'email' not in user_info
@pytest.mark.skipif(django.VERSION > (1, 9),
reason='MIDDLEWARE_CLASSES removed in Django 2.0')
def test_user_info_with_non_django_auth(django_elasticapm_client, client):
with override_settings(INSTALLED_APPS=[
app for app in settings.INSTALLED_APPS
if app != 'django.contrib.auth'
]) and override_settings(MIDDLEWARE_CLASSES=[
m for m in settings.MIDDLEWARE_CLASSES
if m != 'django.contrib.auth.middleware.AuthenticationMiddleware'
]):
with pytest.raises(Exception):
resp = client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['context']['user'] == {}
@pytest.mark.skipif(django.VERSION < (1, 10),
reason='MIDDLEWARE new in Django 1.10')
def test_user_info_with_non_django_auth_django_2(django_elasticapm_client, client):
with override_settings(INSTALLED_APPS=[
app for app in settings.INSTALLED_APPS
if app != 'django.contrib.auth'
]) and override_settings(MIDDLEWARE_CLASSES=None, MIDDLEWARE=[
m for m in settings.MIDDLEWARE
if m != 'django.contrib.auth.middleware.AuthenticationMiddleware'
]):
with pytest.raises(Exception):
resp = client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['context']['user'] == {}
@pytest.mark.skipif(django.VERSION > (1, 9),
reason='MIDDLEWARE_CLASSES removed in Django 2.0')
def test_user_info_without_auth_middleware(django_elasticapm_client, client):
with override_settings(MIDDLEWARE_CLASSES=[
m for m in settings.MIDDLEWARE_CLASSES
if m != 'django.contrib.auth.middleware.AuthenticationMiddleware'
]):
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['context']['user'] == {}
@pytest.mark.skipif(django.VERSION < (1, 10),
reason='MIDDLEWARE new in Django 1.10')
def test_user_info_without_auth_middleware_django_2(django_elasticapm_client, client):
with override_settings(MIDDLEWARE_CLASSES=None, MIDDLEWARE=[
m for m in settings.MIDDLEWARE
if m != 'django.contrib.auth.middleware.AuthenticationMiddleware'
]):
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['context']['user'] == {}
def test_request_middleware_exception(django_elasticapm_client, client):
with override_settings(**middleware_setting(django.VERSION,
['tests.contrib.django.testapp.middleware.BrokenRequestMiddleware'])):
with pytest.raises(ImportError):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'exception' in event
exc = event['exception']
assert exc['type'] == 'ImportError'
assert exc['message'] == 'ImportError: request'
assert exc['handled'] is False
assert event['culprit'] == 'tests.contrib.django.testapp.middleware.process_request'
def test_response_middlware_exception(django_elasticapm_client, client):
if django.VERSION[:2] < (1, 3):
return
with override_settings(**middleware_setting(django.VERSION,
['tests.contrib.django.testapp.middleware.BrokenResponseMiddleware'])):
with pytest.raises(ImportError):
client.get(reverse('elasticapm-no-error'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'exception' in event
exc = event['exception']
assert exc['type'] == 'ImportError'
assert exc['message'] == 'ImportError: response'
assert exc['handled'] is False
assert event['culprit'] == 'tests.contrib.django.testapp.middleware.process_response'
def test_broken_500_handler_with_middleware(django_elasticapm_client, client):
with override_settings(BREAK_THAT_500=True):
client.handler = MockMiddleware(MockClientHandler())
with override_settings(**middleware_setting(django.VERSION, [])):
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 2
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'exception' in event
exc = event['exception']
assert exc['type'] == 'MyException'
assert exc['message'] == 'MyException: view exception'
assert event['culprit'] == 'tests.contrib.django.testapp.views.raise_exc'
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'exception' in event
exc = event['exception']
assert exc['type'] == 'ValueError'
assert exc['message'] == 'ValueError: handler500'
assert exc['handled'] is False
assert event['culprit'] == 'tests.contrib.django.testapp.urls.handler500'
def test_view_middleware_exception(django_elasticapm_client, client):
with override_settings(**middleware_setting(django.VERSION,
['tests.contrib.django.testapp.middleware.BrokenViewMiddleware'])):
with pytest.raises(ImportError):
client.get(reverse('elasticapm-raise-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'exception' in event
exc = event['exception']
assert exc['type'] == 'ImportError'
assert exc['message'] == 'ImportError: view'
assert exc['handled'] is False
assert event['culprit'] == 'tests.contrib.django.testapp.middleware.process_view'
def test_exclude_modules_view(django_elasticapm_client, client):
django_elasticapm_client.config.exclude_paths = ['tests.views.decorated_raise_exc']
with pytest.raises(Exception):
client.get(reverse('elasticapm-raise-exc-decor'))
assert len(django_elasticapm_client.events) == 1, django_elasticapm_client.events
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['culprit'] == 'tests.contrib.django.testapp.views.raise_exc'
def test_include_modules(django_elasticapm_client, client):
django_elasticapm_client.config.include_paths = ['django.shortcuts.get_object_or_404']
with pytest.raises(Exception):
client.get(reverse('elasticapm-django-exc'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['culprit'] == 'django.shortcuts.get_object_or_404'
def test_ignored_exception_is_ignored(django_elasticapm_client, client):
with pytest.raises(IgnoredException):
client.get(reverse('elasticapm-ignored-exception'))
assert len(django_elasticapm_client.events) == 0
@pytest.mark.skipif(compat.PY3, reason='see Python bug #10805')
def test_record_none_exc_info(django_elasticapm_client):
# sys.exc_info can return (None, None, None) if no exception is being
# handled anywhere on the stack. See:
# http://docs.python.org/library/sys.html#sys.exc_info
record = logging.LogRecord(
'foo',
logging.INFO,
pathname=None,
lineno=None,
msg='test',
args=(),
exc_info=(None, None, None),
)
handler = LoggingHandler()
handler.emit(record)
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['log']['param_message'] == 'test'
assert event['log']['logger_name'] == 'foo'
assert event['log']['level'] == 'info'
assert 'exception' not in event
def test_404_middleware(django_elasticapm_client, client):
with override_settings(**middleware_setting(django.VERSION,
['elasticapm.contrib.django.middleware.Catch404Middleware'])):
resp = client.get('/non-existant-page')
assert resp.status_code == 404
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['log']['level'] == 'info'
assert event['log']['logger_name'] == 'http404'
assert 'request' in event['context']
request = event['context']['request']
assert request['url']['full'] == u'http://testserver/non-existant-page'
assert request['method'] == 'GET'
assert 'body' not in request
def test_404_middleware_with_debug(django_elasticapm_client, client):
django_elasticapm_client.config.debug = False
with override_settings(
DEBUG=True,
**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.Catch404Middleware'
])
):
resp = client.get('/non-existant-page')
assert resp.status_code == 404
assert len(django_elasticapm_client.events) == 0
def test_response_error_id_middleware(django_elasticapm_client, client):
with override_settings(**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.ErrorIdMiddleware',
'elasticapm.contrib.django.middleware.Catch404Middleware'])):
resp = client.get('/non-existant-page')
assert resp.status_code == 404
headers = dict(resp.items())
assert 'X-ElasticAPM-ErrorId' in headers
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['id'] == headers['X-ElasticAPM-ErrorId']
def test_get_client(django_elasticapm_client):
assert get_client() == get_client()
assert get_client('elasticapm.base.Client').__class__ == Client
@pytest.mark.parametrize('django_elasticapm_client', [
{'capture_body': 'errors'},
], indirect=True)
def test_raw_post_data_partial_read(django_elasticapm_client):
v = compat.b('{"foo": "bar"}')
request = WSGIRequest(environ={
'wsgi.input': compat.BytesIO(v + compat.b('\r\n\r\n')),
'REQUEST_METHOD': 'POST',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'CONTENT_TYPE': 'application/json',
'CONTENT_LENGTH': len(v),
'ACCEPT': 'application/json',
})
request.read(1)
django_elasticapm_client.capture('Message', message='foo', request=request)
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'request' in event['context']
request = event['context']['request']
assert request['method'] == 'POST'
assert request['body'] == '<unavailable>'
@pytest.mark.parametrize('django_elasticapm_client', [
{'capture_body': 'errors'},
{'capture_body': 'all'},
{'capture_body': 'off'},
], indirect=True)
def test_post_data(django_elasticapm_client):
request = WSGIRequest(environ={
'wsgi.input': compat.BytesIO(),
'REQUEST_METHOD': 'POST',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
'ACCEPT': 'application/json',
})
request.POST = QueryDict("x=1&y=2&y=3")
django_elasticapm_client.capture('Message', message='foo', request=request)
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'request' in event['context']
request = event['context']['request']
assert request['method'] == 'POST'
if django_elasticapm_client.config.capture_body in ('errors', 'all'):
assert request['body'] == {'x': '1', 'y': ['2', '3']}
else:
assert request['body'] == '[REDACTED]'
@pytest.mark.parametrize('django_elasticapm_client', [
{'capture_body': 'errors'},
{'capture_body': 'all'},
{'capture_body': 'off'},
], indirect=True)
def test_post_raw_data(django_elasticapm_client):
request = WSGIRequest(environ={
'wsgi.input': compat.BytesIO(compat.b('foobar')),
'wsgi.url_scheme': 'http',
'REQUEST_METHOD': 'POST',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'CONTENT_TYPE': 'application/json',
'ACCEPT': 'application/json',
'CONTENT_LENGTH': '6',
})
django_elasticapm_client.capture('Message', message='foo', request=request)
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'request' in event['context']
request = event['context']['request']
assert request['method'] == 'POST'
if django_elasticapm_client.config.capture_body in ('errors', 'all'):
assert request['body'] == compat.b('foobar')
else:
assert request['body'] == '[REDACTED]'
@pytest.mark.skipif(django.VERSION < (1, 9),
reason='get-raw-uri-not-available')
def test_disallowed_hosts_error_django_19(django_elasticapm_client):
request = WSGIRequest(environ={
'wsgi.input': compat.BytesIO(),
'wsgi.url_scheme': 'http',
'REQUEST_METHOD': 'POST',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'CONTENT_TYPE': 'application/json',
'ACCEPT': 'application/json',
})
with override_settings(ALLOWED_HOSTS=['example.com']):
# this should not raise a DisallowedHost exception
django_elasticapm_client.capture('Message', message='foo', request=request)
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['context']['request']['url']['full'] == 'http://testserver/'
@pytest.mark.skipif(django.VERSION >= (1, 9),
reason='get-raw-uri-available')
def test_disallowed_hosts_error_django_18(django_elasticapm_client):
request = WSGIRequest(environ={
'wsgi.input': compat.BytesIO(),
'wsgi.url_scheme': 'http',
'REQUEST_METHOD': 'POST',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'CONTENT_TYPE': 'application/json',
'ACCEPT': 'application/json',
})
with override_settings(ALLOWED_HOSTS=['example.com']):
# this should not raise a DisallowedHost exception
django_elasticapm_client.capture('Message', message='foo', request=request)
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert event['context']['request']['url'] == {'full': 'DisallowedHost'}
@pytest.mark.parametrize('django_elasticapm_client', [
{'capture_body': 'errors'},
{'capture_body': 'all'},
{'capture_body': 'off'},
], indirect=True)
def test_request_capture(django_elasticapm_client):
request = WSGIRequest(environ={
'wsgi.input': compat.BytesIO(),
'REQUEST_METHOD': 'POST',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'CONTENT_TYPE': 'text/html',
'ACCEPT': 'text/html',
})
request.read(1)
django_elasticapm_client.capture('Message', message='foo', request=request)
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'request' in event['context']
request = event['context']['request']
assert request['method'] == 'POST'
if django_elasticapm_client.config.capture_body in ('errors', 'all'):
assert request['body'] == '<unavailable>'
else:
assert request['body'] == '[REDACTED]'
assert 'headers' in request
headers = request['headers']
assert 'content-type' in headers, headers.keys()
assert headers['content-type'] == 'text/html'
env = request['env']
assert 'SERVER_NAME' in env, env.keys()
assert env['SERVER_NAME'] == 'testserver'
assert 'SERVER_PORT' in env, env.keys()
assert env['SERVER_PORT'] == '80'
def test_transaction_request_response_data(django_elasticapm_client, client):
client.cookies = SimpleCookie({'foo': 'bar'})
django_elasticapm_client.instrumentation_store.get_all()
with override_settings(**middleware_setting(
django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware']
)):
client.get(reverse('elasticapm-no-error'))
assert len(django_elasticapm_client.instrumentation_store) == 1
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert len(transactions) == 1
transaction = transactions[0]
assert transaction['result'] == 'HTTP 2xx'
assert 'request' in transaction['context']
request = transaction['context']['request']
assert request['method'] == 'GET'
assert 'headers' in request
headers = request['headers']
assert headers['cookie'] == ' foo=bar'
env = request['env']
assert 'SERVER_NAME' in env, env.keys()
assert env['SERVER_NAME'] == 'testserver'
assert 'SERVER_PORT' in env, env.keys()
assert env['SERVER_PORT'] == '80'
assert 'response' in transaction['context']
response = transaction['context']['response']
assert response['status_code'] == 200
assert response['headers']['my-header'] == 'foo'
def test_transaction_metrics(django_elasticapm_client, client):
django_elasticapm_client.instrumentation_store.get_all() # clear the store
with override_settings(**middleware_setting(
django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware']
)):
assert len(django_elasticapm_client.instrumentation_store) == 0
client.get(reverse('elasticapm-no-error'))
assert len(django_elasticapm_client.instrumentation_store) == 1
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert len(transactions) == 1
transaction = transactions[0]
assert transaction['duration'] > 0
assert transaction['result'] == 'HTTP 2xx'
assert transaction['name'] == 'GET tests.contrib.django.testapp.views.no_error'
def test_transaction_metrics_debug(django_elasticapm_client, client):
with override_settings(DEBUG=True, **middleware_setting(
django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware']
)):
assert len(django_elasticapm_client.instrumentation_store) == 0
client.get(reverse('elasticapm-no-error'))
assert len(django_elasticapm_client.instrumentation_store) == 0
@pytest.mark.parametrize('django_elasticapm_client', [
{'debug': True}
], indirect=True)
def test_transaction_metrics_debug_and_client_debug(django_elasticapm_client, client):
assert django_elasticapm_client.config.debug is True
with override_settings(DEBUG=True, **middleware_setting(
django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware']
)):
assert len(django_elasticapm_client.instrumentation_store) == 0
client.get(reverse('elasticapm-no-error'))
assert len(django_elasticapm_client.instrumentation_store) == 1
def test_request_metrics_301_append_slash(django_elasticapm_client, client):
django_elasticapm_client.instrumentation_store.get_all() # clear the store
# enable middleware wrapping
django_elasticapm_client.config.instrument_django_middleware = True
from elasticapm.contrib.django.middleware import TracingMiddleware
TracingMiddleware._elasticapm_instrumented = False
with override_settings(
APPEND_SLASH=True,
**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.TracingMiddleware',
'django.middleware.common.CommonMiddleware',
])
):
client.get(reverse('elasticapm-no-error-slash')[:-1])
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert transactions[0]['name'] in (
# django <= 1.8
'GET django.middleware.common.CommonMiddleware.process_request',
# django 1.9+
'GET django.middleware.common.CommonMiddleware.process_response',
)
assert transactions[0]['result'] == 'HTTP 3xx'
def test_request_metrics_301_prepend_www(django_elasticapm_client, client):
django_elasticapm_client.instrumentation_store.get_all() # clear the store
# enable middleware wrapping
django_elasticapm_client.config.instrument_django_middleware = True
from elasticapm.contrib.django.middleware import TracingMiddleware
TracingMiddleware._elasticapm_instrumented = False
with override_settings(
PREPEND_WWW=True,
**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.TracingMiddleware',
'django.middleware.common.CommonMiddleware',
])
):
client.get(reverse('elasticapm-no-error'))
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert transactions[0]['name'] == 'GET django.middleware.common.CommonMiddleware.process_request'
assert transactions[0]['result'] == 'HTTP 3xx'
@pytest.mark.django_db
def test_request_metrics_contrib_redirect(django_elasticapm_client, client):
django_elasticapm_client.instrumentation_store.get_all() # clear the store
# enable middleware wrapping
django_elasticapm_client.config.instrument_django_middleware = True
from elasticapm.contrib.django.middleware import TracingMiddleware
TracingMiddleware._elasticapm_instrumented = False
s = Site.objects.get(pk=1)
Redirect.objects.create(site=s, old_path='/redirect/me/', new_path='/here/')
with override_settings(
**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.TracingMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
])
):
response = client.get('/redirect/me/')
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert transactions[0]['name'] == 'GET django.contrib.redirects.middleware.RedirectFallbackMiddleware.process_response'
assert transactions[0]['result'] == 'HTTP 3xx'
def test_request_metrics_name_override(django_elasticapm_client, client):
django_elasticapm_client.instrumentation_store.get_all() # clear the store
with override_settings(
**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.TracingMiddleware',
'tests.contrib.django.testapp.middleware.MetricsNameOverrideMiddleware',
])
):
client.get(reverse('elasticapm-no-error'))
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert transactions[0]['name'] == 'GET foobar'
def test_request_metrics_404_resolve_error(django_elasticapm_client, client):
django_elasticapm_client.instrumentation_store.get_all() # clear the store
with override_settings(
**middleware_setting(django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware'])
):
client.get('/i-dont-exist/')
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert transactions[0]['name'] == ''
def test_get_service_info(django_elasticapm_client):
app_info = django_elasticapm_client.get_service_info()
assert django.get_version() == app_info['framework']['version']
assert app_info['framework']['name'] == 'django'
assert django_elasticapm_client.config.framework_name == 'django'
@pytest.mark.parametrize('django_sending_elasticapm_client', [{'filter_exception_types': [
'KeyError', 'tests.contrib.django.fake1.FakeException'
]}], indirect=True)
def test_filter_no_match(django_sending_elasticapm_client):
try:
raise ValueError('foo')
except ValueError:
django_sending_elasticapm_client.capture('Exception')
assert len(django_sending_elasticapm_client.httpserver.requests) == 1
@pytest.mark.parametrize('django_sending_elasticapm_client', [{'filter_exception_types': [
'KeyError', 'tests.contrib.django.fake1.FakeException'
]}], indirect=True)
def test_filter_matches_type(django_sending_elasticapm_client):
try:
raise KeyError('foo')
except KeyError:
django_sending_elasticapm_client.capture('Exception')
assert len(django_sending_elasticapm_client.httpserver.requests) == 0
@pytest.mark.parametrize('django_sending_elasticapm_client', [{'filter_exception_types': [
'KeyError', 'tests.contrib.django.fake1.FakeException'
]}], indirect=True)
def test_filter_matches_type_but_not_module(django_sending_elasticapm_client):
from tests.contrib.django.fake2 import FakeException
try:
raise FakeException('foo')
except FakeException:
django_sending_elasticapm_client.capture('Exception')
assert len(django_sending_elasticapm_client.httpserver.requests) == 1
@pytest.mark.parametrize('django_sending_elasticapm_client', [{'filter_exception_types': [
'KeyError', 'tests.contrib.django.fake1.FakeException'
]}], indirect=True)
def test_filter_matches_type_and_module(django_sending_elasticapm_client):
from tests.contrib.django.fake1 import FakeException
try:
raise FakeException('foo')
except FakeException:
django_sending_elasticapm_client.capture('Exception')
assert len(django_sending_elasticapm_client.httpserver.requests) == 0
@pytest.mark.parametrize('django_sending_elasticapm_client', [{'filter_exception_types': [
'KeyError', 'tests.contrib.django.fake1.FakeException'
]}], indirect=True)
def test_filter_matches_module_only(django_sending_elasticapm_client):
from tests.contrib.django.fake1 import OtherFakeException
try:
raise OtherFakeException('foo')
except OtherFakeException:
django_sending_elasticapm_client.capture('Exception')
assert len(django_sending_elasticapm_client.httpserver.requests) == 1
def test_django_logging_request_kwarg(django_elasticapm_client):
handler = LoggingHandler()
logger = logging.getLogger(__name__)
logger.handlers = []
logger.addHandler(handler)
logger.error('This is a test error', extra={
'request': WSGIRequest(environ={
'wsgi.input': compat.StringIO(),
'REQUEST_METHOD': 'POST',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'CONTENT_TYPE': 'application/json',
'ACCEPT': 'application/json',
})
})
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'request' in event['context']
request = event['context']['request']
assert request['method'] == 'POST'
def test_django_logging_middleware(django_elasticapm_client, client):
handler = LoggingHandler()
logger = logging.getLogger('logmiddleware')
logger.handlers = []
logger.addHandler(handler)
with override_settings(**middleware_setting(django.VERSION,
['elasticapm.contrib.django.middleware.LogMiddleware'])):
client.get(reverse('elasticapm-logging'))
assert len(django_elasticapm_client.events) == 1
event = django_elasticapm_client.events.pop(0)['errors'][0]
assert 'request' in event['context']
assert event['context']['request']['url']['pathname'] == reverse('elasticapm-logging')
def client_get(client, url):
return client.get(url)
def test_stacktraces_have_templates(client, django_elasticapm_client):
# only Django 1.9+ have the necessary information stored on Node/Template
# instances when TEMPLATE_DEBUG = False
TEMPLATE_DEBUG = django.VERSION < (1, 9)
with mock.patch("elasticapm.traces.TransactionsStore.should_collect") as should_collect:
should_collect.return_value = False
TEMPLATES_copy = deepcopy(settings.TEMPLATES)
TEMPLATES_copy[0]['OPTIONS']['debug'] = TEMPLATE_DEBUG
with override_settings(
TEMPLATE_DEBUG=TEMPLATE_DEBUG,
TEMPLATES=TEMPLATES_copy,
**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.TracingMiddleware'
])
):
resp = client.get(reverse("render-heavy-template"))
assert resp.status_code == 200
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert len(transactions) == 1
transaction = transactions[0]
assert transaction['result'] == 'HTTP 2xx'
spans = transaction['spans']
assert len(spans) == 2, [t['name'] for t in spans]
expected_names = {'list_users.html', 'something_expensive'}
assert {t['name'] for t in spans} == expected_names
assert spans[0]['name'] == 'something_expensive'
# Find the template
for frame in spans[0]['stacktrace']:
if frame['lineno'] == 4 and frame['filename'].endswith(
os.path.join('django', 'testapp', 'templates', 'list_users.html')
):
break
else:
assert False is True, "Template was not found"
def test_stacktrace_filtered_for_elasticapm(client, django_elasticapm_client):
with mock.patch(
"elasticapm.traces.TransactionsStore.should_collect") as should_collect:
should_collect.return_value = False
with override_settings(**middleware_setting(django.VERSION,
['elasticapm.contrib.django.middleware.TracingMiddleware'])):
resp = client.get(reverse("render-heavy-template"))
assert resp.status_code == 200
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert transactions[0]['result'] == 'HTTP 2xx'
spans = transactions[0]['spans']
expected_signatures = ['transaction', 'list_users.html',
'something_expensive']
assert spans[1]['name'] == 'list_users.html'
# Top frame should be inside django rendering
assert spans[1]['stacktrace'][0]['module'].startswith('django.template'), spans[1]['stacktrace'][0]['function']
@pytest.mark.parametrize('django_elasticapm_client', [{'_wait_to_first_send': 100}], indirect=True)
def test_perf_template_render(benchmark, client, django_elasticapm_client):
responses = []
with mock.patch("elasticapm.traces.TransactionsStore.should_collect") as should_collect:
should_collect.return_value = False
with override_settings(**middleware_setting(django.VERSION,
['elasticapm.contrib.django.middleware.TracingMiddleware'])):
benchmark(lambda: responses.append(
client_get(client, reverse("render-heavy-template"))
))
for resp in responses:
assert resp.status_code == 200
transactions = django_elasticapm_client.instrumentation_store.get_all()
# If the test falls right at the change from one minute to another
# this will have two items.
assert len(transactions) == len(responses)
for transaction in transactions:
assert len(transaction['spans']) == 2
assert transaction['result'] == 'HTTP 2xx'
@pytest.mark.parametrize('django_elasticapm_client', [{'_wait_to_first_send': 100}], indirect=True)
def test_perf_template_render_no_middleware(benchmark, client, django_elasticapm_client):
responses = []
with mock.patch(
"elasticapm.traces.TransactionsStore.should_collect") as should_collect:
should_collect.return_value = False