-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtest_nameko_sentry.py
1017 lines (743 loc) · 28.2 KB
/
test_nameko_sentry.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
import gc
import json
import logging
import socket
import eventlet
import objgraph
import pytest
from eventlet.event import Event
from mock import ANY, Mock, patch, PropertyMock
from nameko.extensions import DependencyProvider
from nameko.exceptions import RemoteError
from nameko.rpc import rpc
from nameko.standalone.rpc import ServiceRpcProxy
from nameko.testing.services import (
entrypoint_hook, entrypoint_waiter, get_extension)
from nameko.web.handlers import HttpRequestHandler, http
from raven import breadcrumbs, Client
from raven.transport.eventlet import EventletHTTPTransport
from werkzeug.exceptions import ClientDisconnected
from nameko_sentry import SentryReporter
from six.moves.urllib import parse
class CustomException(Exception):
pass
@pytest.fixture
def config(rabbit_config):
config = rabbit_config.copy()
config.update({
'SENTRY': {
'DSN': 'http://user:pass@localhost:9000/1',
'CLIENT_CONFIG': {
'site': 'site name'
}
}
})
return config
@pytest.fixture
def service_cls():
class Service(object):
name = "service"
sentry = SentryReporter()
@rpc(expected_exceptions=CustomException)
def broken(self):
raise CustomException("Error!")
@rpc
def fine(self):
return "OK"
return Service
@pytest.yield_fixture
def patched_sentry():
with patch.object(Client, 'send'):
yield
@pytest.mark.parametrize("dsn", [
'http://user:pass@localhost:9000/1',
'eventlet+http://user:pass@localhost:9000/1',
])
def test_eventlet_transport(
dsn, rabbit_config, container_factory, service_cls
):
config = rabbit_config.copy()
config.update({
'SENTRY': {
'DSN': dsn
}
})
container = container_factory(service_cls, config)
container.start()
sentry = get_extension(container, SentryReporter)
# transport set correctly
transport = sentry.client.remote.get_transport()
assert isinstance(transport, EventletHTTPTransport)
@pytest.mark.usefixtures('patched_sentry')
def test_setup(container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
sentry = get_extension(container, SentryReporter)
# client config and DSN applied correctly
assert sentry.client.site == "site name"
assert sentry.client.get_public_dsn() == "//user@localhost:9000/1"
assert sentry.client.is_enabled()
# transport set correctly
transport = sentry.client.remote.get_transport()
assert isinstance(transport, EventletHTTPTransport)
@pytest.mark.usefixtures('patched_sentry')
def test_setup_without_optional_config(container_factory, service_cls, config):
del config['SENTRY']['CLIENT_CONFIG']
container = container_factory(service_cls, config)
container.start()
sentry = get_extension(container, SentryReporter)
# DSN applied correctly
assert sentry.client.get_public_dsn() == "//user@localhost:9000/1"
assert sentry.client.is_enabled()
# transport set correctly
transport = sentry.client.remote.get_transport()
assert isinstance(transport, EventletHTTPTransport)
@pytest.mark.usefixtures('patched_sentry')
def test_setup_without_sentry_section_in_config(
container_factory, service_cls, config
):
del config['SENTRY']
container = container_factory(service_cls, config)
container.start()
sentry = get_extension(container, SentryReporter)
# DSN applied correctly
assert sentry.client.get_public_dsn() is None
assert not sentry.client.is_enabled()
@pytest.mark.usefixtures('patched_sentry')
def test_disabled(container_factory, service_cls, config):
config['SENTRY']['DSN'] = None
container = container_factory(service_cls, config)
container.start()
sentry = get_extension(container, SentryReporter)
# DSN applied correctly
assert sentry.client.get_public_dsn() is None
assert not sentry.client.is_enabled()
@pytest.mark.usefixtures('patched_sentry')
def test_worker_result(container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
with entrypoint_hook(container, 'fine') as fine:
with entrypoint_waiter(container, 'fine'):
assert fine() == "OK"
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 0
@pytest.mark.usefixtures('patched_sentry', 'predictable_call_ids')
@pytest.mark.parametrize("exception_cls,expected_level", [
(CustomException, logging.WARNING),
(KeyError, logging.ERROR)
])
def test_worker_exception(
exception_cls, expected_level, container_factory, config
):
class Service(object):
name = "service"
sentry = SentryReporter()
@rpc(expected_exceptions=CustomException)
def broken(self):
raise exception_cls("Error!")
container = container_factory(Service, config)
container.start()
with entrypoint_waiter(container, 'broken') as result:
with ServiceRpcProxy('service', config) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken()
with pytest.raises(exception_cls) as raised:
result.get()
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
# generate expected call args
expected_logger = "service.broken"
expected_message = "Unhandled exception in call {}: {} {!r}".format(
'service.broken.1', exception_cls.__name__, str(raised.value)
)
_, kwargs = sentry.client.send.call_args
assert kwargs['message'] == expected_message
assert kwargs['logger'] == expected_logger
assert kwargs['level'] == expected_level
assert kwargs['extra'] == ANY
assert kwargs['tags'] == ANY
assert kwargs['user'] == {}
@pytest.mark.usefixtures('patched_sentry')
@pytest.mark.parametrize("exception_cls,expected_count", [
(CustomException, 0),
(KeyError, 1)
])
def test_expected_exception_not_reported(
exception_cls, expected_count, container_factory, config
):
class Service(object):
name = "service"
sentry = SentryReporter()
@rpc(expected_exceptions=CustomException)
def broken(self):
raise exception_cls("Error!")
config['SENTRY']['REPORT_EXPECTED_EXCEPTIONS'] = False
container = container_factory(Service, config)
container.start()
with entrypoint_waiter(container, 'broken') as result:
with ServiceRpcProxy('service', config) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken()
with pytest.raises(exception_cls):
result.get()
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == expected_count
@pytest.mark.usefixtures('patched_sentry')
class TestUserContext(object):
def test_user_defaults(self, container_factory, service_cls, config):
user_data = {
'user': 'matt',
'username': 'matt',
'user_id': 1,
'email': '[email protected]',
'email_address': '[email protected]',
'session_id': 1
}
container = container_factory(service_cls, config)
container.start()
context_data = {
'language': 'en-gb'
}
context_data.update(user_data)
with ServiceRpcProxy(
'service', config, context_data=context_data
) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken()
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
assert kwargs['user'] == user_data
def test_user_custom(self, container_factory, service_cls, config):
config['SENTRY']['USER_TYPE_CONTEXT_KEYS'] = (
'user|email', # excludes session
'other_pattern'
)
container = container_factory(service_cls, config)
container.start()
user_data = {
'user': 'matt',
'username': 'matt',
'user_id': 1,
'email': '[email protected]',
'email_address': '[email protected]',
}
context_data = {
'session_id': 1, # excluded from user data
'language': 'en-gb'
}
context_data.update(user_data)
with ServiceRpcProxy(
'service', config, context_data=context_data
) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken()
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
assert kwargs['user'] == user_data
assert "session_id" not in kwargs['user']
@pytest.mark.usefixtures('predictable_call_ids')
@pytest.mark.usefixtures('patched_sentry')
class TestExtraContext(object):
def test_extra(self, container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
context_data = {
'language': 'en-gb'
}
with ServiceRpcProxy(
'service', config, context_data=context_data
) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken()
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
expected_extra = {
'call_id_stack': (
repr(u"standalone_rpc_proxy.call.0"), repr(u"service.broken.1")
),
'language': repr(u"en-gb"),
'sys.argv': ANY
}
_, kwargs = sentry.client.send.call_args
assert kwargs['extra'] == expected_extra
@pytest.mark.usefixtures('predictable_call_ids')
@pytest.mark.usefixtures('patched_sentry')
class TestTagContext(object):
def test_tags_defaults(self, container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
with ServiceRpcProxy('service', config) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken()
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
expected_tags = {
'site': config['SENTRY']['CLIENT_CONFIG']['site'],
'call_id': 'service.broken.1',
'parent_call_id': 'standalone_rpc_proxy.call.0',
'service_name': 'service',
'method_name': 'broken'
}
_, kwargs = sentry.client.send.call_args
assert expected_tags == kwargs['tags']
def test_tags_custom(self, container_factory, service_cls, config):
config['SENTRY']['TAG_TYPE_CONTEXT_KEYS'] = (
'session',
'other_pattern'
)
container = container_factory(service_cls, config)
container.start()
context_data = {
'call_id_stack': ["standalone_rpc_proxy.call.0"],
'session_id': 1,
'email_address': '[email protected]',
}
with ServiceRpcProxy(
'service', config, context_data=context_data
) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken()
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
expected_tags = {
'site': config['SENTRY']['CLIENT_CONFIG']['site'],
'call_id': 'service.broken.1',
'parent_call_id': 'standalone_rpc_proxy.call.0',
'service_name': 'service',
'method_name': 'broken',
'session_id': '1', # extra
}
_, kwargs = sentry.client.send.call_args
assert expected_tags == kwargs['tags']
@pytest.mark.usefixtures('patched_sentry')
class TestHttpContext(object):
@pytest.fixture
def config(self, config, web_config):
config.update(web_config)
return config
def test_normal_http_entrypoint(
self, container_factory, config, web_session
):
class Service(object):
name = "service"
sentry = SentryReporter()
@http('GET', '/resource')
def resource(self, request):
raise CustomException()
container = container_factory(Service, config)
container.start()
with entrypoint_waiter(container, 'resource'):
web_session.get('/resource')
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
expected_http = {
'url': ANY,
'query_string': "",
'method': 'GET',
'data': {},
'headers': ANY,
'env': ANY
}
assert kwargs['request'] == expected_http
def test_json_payload(
self, container_factory, config, web_session
):
class Service(object):
name = "service"
sentry = SentryReporter()
@http('POST', '/resource')
def resource(self, request):
raise CustomException()
container = container_factory(Service, config)
container.start()
submitted_data = {
'foo': 'bar'
}
with entrypoint_waiter(container, 'resource'):
rv = web_session.post('/resource', json=submitted_data)
assert rv.status_code == 500
assert "CustomException" in rv.text
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
received_data = kwargs['request']['data']
assert received_data == json.dumps(submitted_data).encode('utf-8')
def test_form_submission(
self, container_factory, config, web_session
):
class Service(object):
name = "service"
sentry = SentryReporter()
@http('POST', '/resource')
def resource(self, request):
raise CustomException()
container = container_factory(Service, config)
container.start()
submitted_data = {
'foo': 'bar'
}
with entrypoint_waiter(container, 'resource'):
web_session.post('/resource', data=submitted_data)
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
assert kwargs['request']['data'] == submitted_data
def test_client_disconnect(
self, container_factory, config, web_session
):
class Service(object):
name = "service"
sentry = SentryReporter()
@http('POST', '/resource')
def resource(self, request):
raise CustomException()
container = container_factory(Service, config)
container.start()
request = Mock(
method="GET",
url="http://example.com",
mimetype='application/json',
environ={}
)
type(request).data = PropertyMock(side_effect=ClientDisconnected)
with entrypoint_hook(container, 'resource') as hook:
with pytest.raises(CustomException):
hook(request)
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
assert kwargs['request']['data'] == {}
def test_unsupported_http_entrypoint(
self, container_factory, config, web_session
):
bogus = object()
class CustomHttpEntrypoint(HttpRequestHandler):
def get_entrypoint_parameters(self, request):
args = (bogus, request)
kwargs = request.path_values
return args, kwargs
custom_http = CustomHttpEntrypoint.decorator
class Service(object):
name = "service"
sentry = SentryReporter()
@custom_http('GET', '/resource')
def resource(self, bogus_arg, request):
raise CustomException()
container = container_factory(Service, config)
container.start()
with entrypoint_waiter(container, 'resource'):
web_session.get('/resource')
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
expected_http = {}
assert kwargs['request'] == expected_http
@patch.object(EventletHTTPTransport, '_send_payload')
def test_raven_transport_does_not_affect_container(
send_mock, container_factory, service_cls, config
):
""" Allowing raven to use the eventlet transport should not affect the
nameko container, even if raven blocks trying to make calls.
"""
def block(*args):
Event().wait()
send_mock.side_effect = block
container = container_factory(service_cls, config)
container.start()
with entrypoint_hook(container, 'broken') as broken:
with entrypoint_waiter(container, 'broken'):
with pytest.raises(CustomException):
broken()
container.stop()
@pytest.mark.usefixtures('patched_sentry')
class TestConcurrency(object):
@pytest.fixture
def config(self, config, web_config):
config.update(web_config)
return config
def test_concurrent_workers(
self, container_factory, config, web_session
):
class Service(object):
name = "service"
sentry = SentryReporter()
@http('GET', '/resource')
def resource(self, request):
raise CustomException()
container = container_factory(Service, config)
container.start()
called = Mock()
def called_twice(worker_ctx, res, exc_info):
called()
return called.call_count == 2
with entrypoint_waiter(container, 'resource', callback=called_twice):
eventlet.spawn(web_session.get, '/resource?q1')
eventlet.spawn(web_session.get, '/resource?q2')
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 2
query_strings = {
kwargs['request']['query_string']
for (_, kwargs) in sentry.client.send.call_args_list
}
assert query_strings == {"q1", "q2"}
@pytest.mark.usefixtures('patched_sentry')
class TestWorkerUsage(object):
@pytest.fixture
def service_cls(self):
class Service(object):
name = "service"
sentry = SentryReporter()
@rpc
def broken(self, data):
self.sentry.context.merge({
"arbitrary": data
})
raise CustomException("Error!")
@rpc
def get_dsn(self):
return self.sentry.get_public_dsn()
return Service
def test_context_merge(self, container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
user_data = {
'user': 'matt'
}
context_data = {
'language': 'en-gb'
}
context_data.update(user_data)
data = {'foo': 'bar'}
with ServiceRpcProxy(
'service', config, context_data=context_data
) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.broken(data)
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
assert kwargs['user'] == user_data
assert kwargs['arbitrary'] == data
def test_access_client(self, container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
with ServiceRpcProxy('service', config) as rpc_proxy:
res = rpc_proxy.get_dsn()
sentry = get_extension(container, SentryReporter)
assert res == sentry.client.get_public_dsn()
@pytest.mark.usefixtures('patched_sentry')
class TestBreadcrumbs(object):
@pytest.fixture
def config(self, config, web_config):
config.update(web_config)
return config
@pytest.fixture
def service_cls(self):
class Service(object):
name = "service"
sentry = SentryReporter()
@rpc
def record_with_helper(self, data):
breadcrumbs.record(
category="worker",
message='breadcrumb message',
level='warning',
data=data
)
raise CustomException("Error!")
@rpc
def record_directly(self, data):
self.sentry.captureBreadcrumb(
category="worker",
message='breadcrumb message',
level='warning',
data=data
)
raise CustomException("Error!")
@rpc
def activate_deactivate(self, a, b, c):
breadcrumbs.record(category="worker", message=a)
self.sentry.context.deactivate()
breadcrumbs.record(category="worker", message=b)
self.sentry.context.activate()
breadcrumbs.record(category="worker", message=c)
raise CustomException("Error!")
return Service
@pytest.mark.parametrize(
"method", ["record_directly", "record_with_helper"]
)
def test_breadcrumbs(self, method, container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
data = {'foo': 'bar'}
with ServiceRpcProxy('service', config) as rpc_proxy:
with pytest.raises(RemoteError):
getattr(rpc_proxy, method)(data)
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
breadcrumbs = [
crumb for crumb in kwargs['breadcrumbs']['values']
if crumb['category'] == "worker"
]
assert breadcrumbs == [{
'category': 'worker',
'data': data,
'level': 'warning',
'message': 'breadcrumb message',
'timestamp': ANY,
'type': 'default'
}]
def test_activate_deactivate(self, container_factory, service_cls, config):
container = container_factory(service_cls, config)
container.start()
with ServiceRpcProxy('service', config) as rpc_proxy:
with pytest.raises(RemoteError):
rpc_proxy.activate_deactivate("a", "b", "c")
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 1
_, kwargs = sentry.client.send.call_args
breadcrumbs = [
crumb for crumb in kwargs['breadcrumbs']['values']
if crumb['category'] == "worker"
]
assert breadcrumbs == [{
'category': "worker",
'data': None,
'level': ANY,
'message': 'a',
'timestamp': ANY,
'type': 'default'
}, {
'category': "worker",
'data': None,
'level': ANY,
'message': 'c',
'timestamp': ANY,
'type': 'default'
}]
def test_concurrency(
self, container_factory, config, web_session
):
class Service(object):
name = "service"
sentry = SentryReporter()
@http('GET', '/resource')
def resource(self, request):
breadcrumbs.record(message=request.query_string)
raise CustomException()
container = container_factory(Service, config)
container.start()
called = Mock()
def called_twice(worker_ctx, res, exc_info):
called()
return called.call_count == 2
with entrypoint_waiter(container, 'resource', callback=called_twice):
eventlet.spawn(web_session.get, '/resource?q1')
eventlet.spawn(web_session.get, '/resource?q2')
sentry = get_extension(container, SentryReporter)
assert sentry.client.send.call_count == 2
breadcrumbs_map = {
kwargs['request']['query_string']: kwargs['breadcrumbs']['values']
for (_, kwargs) in sentry.client.send.call_args_list
}
expected_crumb_q1 = {
'category': None,
'data': None,
'level': ANY,
'message': 'q1'.encode('utf-8'),
'timestamp': ANY,
'type': 'default'
}
assert expected_crumb_q1 in breadcrumbs_map['q1']
assert expected_crumb_q1 not in breadcrumbs_map['q2']
expected_crumb_q2 = {
'category': None,
'data': None,
'level': ANY,
'message': 'q2'.encode('utf-8'),
'timestamp': ANY,
'type': 'default'
}
assert expected_crumb_q2 in breadcrumbs_map['q2']
assert expected_crumb_q2 not in breadcrumbs_map['q1']
@pytest.mark.usefixtures('patched_sentry')
class TestReleaseMemory(object):
@pytest.fixture
def log(self):
return logging.getLogger("test")
@pytest.fixture
def service_cls(self, log):
class Unsafe(DependencyProvider):
def get_dependency(self, worker_ctx):
return worker_ctx.container._worker_threads[worker_ctx]
class Service(object):
name = "service"
sentry = SentryReporter()
unsafe = Unsafe()
@rpc
def broken(self):
log.info("breadcrumb %s", self.unsafe)
raise CustomException("Error!")
return Service
def test_leak(self, container_factory, service_cls, config):
# regression test for
# https://github.com/mattbennett/nameko-sentry/issues/12
container = container_factory(service_cls, config)
container.start()
gc.collect()
count_before = objgraph.count('raven.breadcrumbs.BreadcrumbBuffer')
with entrypoint_hook(container, 'broken') as hook:
for _ in range(5):
with pytest.raises(CustomException):
hook()
gc.collect()
count_after = objgraph.count('raven.breadcrumbs.BreadcrumbBuffer')
assert count_before == count_after
class TestEndToEnd(object):
@pytest.fixture
def tracker(self):
return Mock()
@pytest.fixture
def free_port(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
sock.close()
return port
@pytest.fixture
def sentry_dsn(self, free_port):
return 'eventlet+http://user:[email protected]:{}/1'.format(free_port)
@pytest.fixture
def sentry_stub(self, container_factory, sentry_dsn, tracker):
""" Start a container to imitate a sentry server
"""
class SentryStub(object):
name = "sentry"
@http('POST', "/api/1/store/")
def report(self, request):
tracker(request.get_data())
return 200, "OK"
address = parse.urlparse(sentry_dsn).netloc.split("@")[-1]
config = {
'WEB_SERVER_ADDRESS': address
}
container = container_factory(SentryStub, config)
container.start()
return container