-
Notifications
You must be signed in to change notification settings - Fork 536
/
Copy pathtest_client.py
951 lines (753 loc) · 26.5 KB
/
test_client.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
# coding: utf-8
import os
import json
import mock
import pytest
import subprocess
import sys
import time
from textwrap import dedent
from sentry_sdk import (
Hub,
Client,
add_breadcrumb,
configure_scope,
capture_message,
capture_exception,
capture_event,
start_transaction,
set_tag,
)
from sentry_sdk.integrations.executing import ExecutingIntegration
from sentry_sdk.transport import Transport
from sentry_sdk._compat import reraise, text_type, PY2
from sentry_sdk.utils import HAS_CHAINED_EXCEPTIONS
from sentry_sdk.utils import logger
from sentry_sdk.serializer import MAX_DATABAG_BREADTH
from sentry_sdk.consts import DEFAULT_MAX_BREADCRUMBS
if PY2:
# Importing ABCs from collections is deprecated, and will stop working in 3.8
# https://github.com/python/cpython/blob/master/Lib/collections/__init__.py#L49
from collections import Mapping
else:
# New in 3.3
# https://docs.python.org/3/library/collections.abc.html
from collections.abc import Mapping
class EventCapturedError(Exception):
pass
class _TestTransport(Transport):
def capture_event(self, event):
raise EventCapturedError(event)
def test_transport_option(monkeypatch):
if "SENTRY_DSN" in os.environ:
monkeypatch.delenv("SENTRY_DSN")
dsn = "https://[email protected]/123"
dsn2 = "https://[email protected]/124"
assert str(Client(dsn=dsn).dsn) == dsn
assert Client().dsn is None
monkeypatch.setenv("SENTRY_DSN", dsn)
transport = Transport({"dsn": dsn2})
assert text_type(transport.parsed_dsn) == dsn2
assert str(Client(transport=transport).dsn) == dsn
@pytest.mark.parametrize(
"testcase",
[
{
"dsn": "http://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"arg_http_proxy": "http://localhost/123",
"arg_https_proxy": None,
"expected_proxy_scheme": "http",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"arg_http_proxy": "https://localhost/123",
"arg_https_proxy": None,
"expected_proxy_scheme": "https",
},
{
"dsn": "http://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"arg_http_proxy": "http://localhost/123",
"arg_https_proxy": "https://localhost/123",
"expected_proxy_scheme": "http",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"arg_http_proxy": "http://localhost/123",
"arg_https_proxy": "https://localhost/123",
"expected_proxy_scheme": "https",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"arg_http_proxy": "http://localhost/123",
"arg_https_proxy": None,
"expected_proxy_scheme": "http",
},
{
"dsn": "http://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": None,
},
{
"dsn": "http://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": None,
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": "http",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": "https://localhost/123",
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": "https",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": None,
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": "http",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": "https://localhost/123",
"arg_http_proxy": "",
"arg_https_proxy": "",
"expected_proxy_scheme": None,
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": "https://localhost/123",
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": "https",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": None,
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": "http",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": "https://localhost/123",
"arg_http_proxy": None,
"arg_https_proxy": "",
"expected_proxy_scheme": "http",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": "https://localhost/123",
"arg_http_proxy": "",
"arg_https_proxy": None,
"expected_proxy_scheme": "https",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": "https://localhost/123",
"arg_http_proxy": None,
"arg_https_proxy": "",
"expected_proxy_scheme": None,
},
{
"dsn": "http://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": "https://localhost/123",
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": "http",
},
# NO_PROXY testcases
{
"dsn": "http://[email protected]/123",
"env_http_proxy": "http://localhost/123",
"env_https_proxy": None,
"env_no_proxy": "sentry.io,example.com",
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": None,
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": "https://localhost/123",
"env_no_proxy": "example.com,sentry.io",
"arg_http_proxy": None,
"arg_https_proxy": None,
"expected_proxy_scheme": None,
},
{
"dsn": "http://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"env_no_proxy": "sentry.io,example.com",
"arg_http_proxy": "http://localhost/123",
"arg_https_proxy": None,
"expected_proxy_scheme": "http",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"env_no_proxy": "sentry.io,example.com",
"arg_http_proxy": None,
"arg_https_proxy": "https://localhost/123",
"expected_proxy_scheme": "https",
},
{
"dsn": "https://[email protected]/123",
"env_http_proxy": None,
"env_https_proxy": None,
"env_no_proxy": "sentry.io,example.com",
"arg_http_proxy": None,
"arg_https_proxy": "https://localhost/123",
"expected_proxy_scheme": "https",
"arg_proxy_headers": {"Test-Header": "foo-bar"},
},
],
)
def test_proxy(monkeypatch, testcase):
if testcase["env_http_proxy"] is not None:
monkeypatch.setenv("HTTP_PROXY", testcase["env_http_proxy"])
if testcase["env_https_proxy"] is not None:
monkeypatch.setenv("HTTPS_PROXY", testcase["env_https_proxy"])
if testcase.get("env_no_proxy") is not None:
monkeypatch.setenv("NO_PROXY", testcase["env_no_proxy"])
kwargs = {}
if testcase["arg_http_proxy"] is not None:
kwargs["http_proxy"] = testcase["arg_http_proxy"]
if testcase["arg_https_proxy"] is not None:
kwargs["https_proxy"] = testcase["arg_https_proxy"]
if testcase.get("arg_proxy_headers") is not None:
kwargs["proxy_headers"] = testcase["arg_proxy_headers"]
client = Client(testcase["dsn"], **kwargs)
if testcase["expected_proxy_scheme"] is None:
assert client.transport._pool.proxy is None
else:
assert client.transport._pool.proxy.scheme == testcase["expected_proxy_scheme"]
if testcase.get("arg_proxy_headers") is not None:
assert client.transport._pool.proxy_headers == testcase["arg_proxy_headers"]
def test_simple_transport(sentry_init):
events = []
sentry_init(transport=events.append)
capture_message("Hello World!")
assert events[0]["message"] == "Hello World!"
def test_ignore_errors(sentry_init, capture_events):
class MyDivisionError(ZeroDivisionError):
pass
def raise_it(exc_info):
reraise(*exc_info)
sentry_init(ignore_errors=[ZeroDivisionError], transport=_TestTransport())
Hub.current._capture_internal_exception = raise_it
def e(exc):
try:
raise exc
except Exception:
capture_exception()
e(ZeroDivisionError())
e(MyDivisionError())
pytest.raises(EventCapturedError, lambda: e(ValueError()))
def test_with_locals_deprecation_enabled(sentry_init):
with mock.patch.object(logger, "warning", mock.Mock()) as fake_warning:
sentry_init(with_locals=True)
client = Hub.current.client
assert "with_locals" not in client.options
assert "include_local_variables" in client.options
assert client.options["include_local_variables"]
fake_warning.assert_called_once_with(
"Deprecated: The option 'with_locals' was renamed to 'include_local_variables'. Please use 'include_local_variables'. The option 'with_locals' will be removed in the future."
)
def test_with_locals_deprecation_disabled(sentry_init):
with mock.patch.object(logger, "warning", mock.Mock()) as fake_warning:
sentry_init(with_locals=False)
client = Hub.current.client
assert "with_locals" not in client.options
assert "include_local_variables" in client.options
assert not client.options["include_local_variables"]
fake_warning.assert_called_once_with(
"Deprecated: The option 'with_locals' was renamed to 'include_local_variables'. Please use 'include_local_variables'. The option 'with_locals' will be removed in the future."
)
def test_include_local_variables_deprecation(sentry_init):
with mock.patch.object(logger, "warning", mock.Mock()) as fake_warning:
sentry_init(include_local_variables=False)
client = Hub.current.client
assert "with_locals" not in client.options
assert "include_local_variables" in client.options
assert not client.options["include_local_variables"]
fake_warning.assert_not_called()
def test_include_local_variables_enabled(sentry_init, capture_events):
sentry_init(include_local_variables=True)
events = capture_events()
try:
1 / 0
except Exception:
capture_exception()
(event,) = events
assert all(
frame["vars"]
for frame in event["exception"]["values"][0]["stacktrace"]["frames"]
)
def test_include_local_variables_disabled(sentry_init, capture_events):
sentry_init(include_local_variables=False)
events = capture_events()
try:
1 / 0
except Exception:
capture_exception()
(event,) = events
assert all(
"vars" not in frame
for frame in event["exception"]["values"][0]["stacktrace"]["frames"]
)
@pytest.mark.parametrize("integrations", [[], [ExecutingIntegration()]])
def test_function_names(sentry_init, capture_events, integrations):
sentry_init(integrations=integrations)
events = capture_events()
def foo():
try:
bar()
except Exception:
capture_exception()
def bar():
1 / 0
foo()
(event,) = events
(thread,) = event["exception"]["values"]
functions = [x["function"] for x in thread["stacktrace"]["frames"]]
if integrations:
assert functions == [
"test_function_names.<locals>.foo",
"test_function_names.<locals>.bar",
]
else:
assert functions == ["foo", "bar"]
def test_attach_stacktrace_enabled(sentry_init, capture_events):
sentry_init(attach_stacktrace=True)
events = capture_events()
def foo():
bar()
def bar():
capture_message("HI")
foo()
(event,) = events
(thread,) = event["threads"]["values"]
functions = [x["function"] for x in thread["stacktrace"]["frames"]]
assert functions[-2:] == ["foo", "bar"]
def test_attach_stacktrace_enabled_no_locals(sentry_init, capture_events):
sentry_init(attach_stacktrace=True, include_local_variables=False)
events = capture_events()
def foo():
bar()
def bar():
capture_message("HI")
foo()
(event,) = events
(thread,) = event["threads"]["values"]
local_vars = [x.get("vars") for x in thread["stacktrace"]["frames"]]
assert local_vars[-2:] == [None, None]
def test_attach_stacktrace_in_app(sentry_init, capture_events):
sentry_init(attach_stacktrace=True, in_app_exclude=["_pytest"])
events = capture_events()
capture_message("hi")
(event,) = events
(thread,) = event["threads"]["values"]
frames = thread["stacktrace"]["frames"]
pytest_frames = [f for f in frames if f["module"].startswith("_pytest")]
assert pytest_frames
assert all(f["in_app"] is False for f in pytest_frames)
def test_attach_stacktrace_disabled(sentry_init, capture_events):
sentry_init(attach_stacktrace=False)
events = capture_events()
capture_message("HI")
(event,) = events
assert "threads" not in event
def test_capture_event_works(sentry_init):
sentry_init(transport=_TestTransport())
pytest.raises(EventCapturedError, lambda: capture_event({}))
pytest.raises(EventCapturedError, lambda: capture_event({}))
@pytest.mark.parametrize("num_messages", [10, 20])
def test_atexit(tmpdir, monkeypatch, num_messages):
app = tmpdir.join("app.py")
app.write(
dedent(
"""
import time
from sentry_sdk import init, transport, capture_message
def send_event(self, event):
time.sleep(0.1)
print(event["message"])
transport.HttpTransport._send_event = send_event
init("http://foobar@localhost/123", shutdown_timeout={num_messages})
for _ in range({num_messages}):
capture_message("HI")
""".format(
num_messages=num_messages
)
)
)
start = time.time()
output = subprocess.check_output([sys.executable, str(app)])
end = time.time()
# Each message takes at least 0.1 seconds to process
assert int(end - start) >= num_messages / 10
assert output.count(b"HI") == num_messages
def test_configure_scope_available(sentry_init, request, monkeypatch):
# Test that scope is configured if client is configured
sentry_init()
with configure_scope() as scope:
assert scope is Hub.current.scope
scope.set_tag("foo", "bar")
calls = []
def callback(scope):
calls.append(scope)
scope.set_tag("foo", "bar")
assert configure_scope(callback) is None
assert len(calls) == 1
assert calls[0] is Hub.current.scope
@pytest.mark.tests_internal_exceptions
def test_client_debug_option_enabled(sentry_init, caplog):
sentry_init(debug=True)
Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None))
assert "OK" in caplog.text
@pytest.mark.tests_internal_exceptions
@pytest.mark.parametrize("with_client", (True, False))
def test_client_debug_option_disabled(with_client, sentry_init, caplog):
if with_client:
sentry_init()
Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None))
assert "OK" not in caplog.text
def test_scope_initialized_before_client(sentry_init, capture_events):
"""
This is a consequence of how configure_scope() works. We must
make `configure_scope()` a noop if no client is configured. Even
if the user later configures a client: We don't know that.
"""
with configure_scope() as scope:
scope.set_tag("foo", 42)
sentry_init()
events = capture_events()
capture_message("hi")
(event,) = events
assert "tags" not in event
def test_weird_chars(sentry_init, capture_events):
sentry_init()
events = capture_events()
# fmt: off
capture_message(u"föö".encode("latin1"))
# fmt: on
(event,) = events
assert json.loads(json.dumps(event)) == event
def test_nan(sentry_init, capture_events):
sentry_init()
events = capture_events()
try:
# should_repr_strings=False
set_tag("mynan", float("nan"))
# should_repr_strings=True
nan = float("nan") # noqa
1 / 0
except Exception:
capture_exception()
(event,) = events
frames = event["exception"]["values"][0]["stacktrace"]["frames"]
(frame,) = frames
assert frame["vars"]["nan"] == "nan"
assert event["tags"]["mynan"] == "nan"
def test_cyclic_frame_vars(sentry_init, capture_events):
sentry_init()
events = capture_events()
try:
a = {}
a["a"] = a
1 / 0
except Exception:
capture_exception()
(event,) = events
assert event["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]["a"] == {
"a": "<cyclic>"
}
def test_cyclic_data(sentry_init, capture_events):
sentry_init()
events = capture_events()
with configure_scope() as scope:
data = {}
data["is_cyclic"] = data
other_data = ""
data["not_cyclic"] = other_data
data["not_cyclic2"] = other_data
scope.set_extra("foo", data)
capture_message("hi")
(event,) = events
data = event["extra"]["foo"]
assert data == {"not_cyclic2": "", "not_cyclic": "", "is_cyclic": "<cyclic>"}
def test_databag_depth_stripping(sentry_init, capture_events, benchmark):
sentry_init()
events = capture_events()
value = ["a"]
for _ in range(100000):
value = [value]
@benchmark
def inner():
del events[:]
try:
a = value # noqa
1 / 0
except Exception:
capture_exception()
(event,) = events
assert len(json.dumps(event)) < 10000
def test_databag_string_stripping(sentry_init, capture_events, benchmark):
sentry_init()
events = capture_events()
@benchmark
def inner():
del events[:]
try:
a = "A" * 1000000 # noqa
1 / 0
except Exception:
capture_exception()
(event,) = events
assert len(json.dumps(event)) < 10000
def test_databag_breadth_stripping(sentry_init, capture_events, benchmark):
sentry_init()
events = capture_events()
@benchmark
def inner():
del events[:]
try:
a = ["a"] * 1000000 # noqa
1 / 0
except Exception:
capture_exception()
(event,) = events
assert (
len(event["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]["a"])
== MAX_DATABAG_BREADTH
)
assert len(json.dumps(event)) < 10000
@pytest.mark.skipif(not HAS_CHAINED_EXCEPTIONS, reason="Only works on 3.3+")
def test_chained_exceptions(sentry_init, capture_events):
sentry_init()
events = capture_events()
try:
try:
raise ValueError()
except Exception:
1 / 0
except Exception:
capture_exception()
(event,) = events
e1, e2 = event["exception"]["values"]
# This is the order all other SDKs send chained exceptions in. Including
# Raven-Python.
assert e1["type"] == "ValueError"
assert e2["type"] == "ZeroDivisionError"
@pytest.mark.tests_internal_exceptions
def test_broken_mapping(sentry_init, capture_events):
sentry_init()
events = capture_events()
class C(Mapping):
def broken(self, *args, **kwargs):
raise Exception("broken")
__getitem__ = broken
__setitem__ = broken
__delitem__ = broken
__iter__ = broken
__len__ = broken
def __repr__(self):
return "broken"
try:
a = C() # noqa
1 / 0
except Exception:
capture_exception()
(event,) = events
assert (
event["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]["a"]
== "<failed to serialize, use init(debug=True) to see error logs>"
)
def test_mapping_sends_exception(sentry_init, capture_events):
sentry_init()
events = capture_events()
class C(Mapping):
def __iter__(self):
try:
1 / 0
except ZeroDivisionError:
capture_exception()
yield "hi"
def __len__(self):
"""List length"""
return 1
def __getitem__(self, ii):
"""Get a list item"""
if ii == "hi":
return "hi"
raise KeyError()
try:
a = C() # noqa
1 / 0
except Exception:
capture_exception()
(event,) = events
assert event["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]["a"] == {
"hi": "'hi'"
}
def test_object_sends_exception(sentry_init, capture_events):
sentry_init()
events = capture_events()
class C(object):
def __repr__(self):
try:
1 / 0
except ZeroDivisionError:
capture_exception()
return "hi, i am a repr"
try:
a = C() # noqa
1 / 0
except Exception:
capture_exception()
(event,) = events
assert (
event["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]["a"]
== "hi, i am a repr"
)
def test_errno_errors(sentry_init, capture_events):
sentry_init()
events = capture_events()
class FooError(Exception):
errno = 69
capture_exception(FooError())
(event,) = events
(exception,) = event["exception"]["values"]
assert exception["mechanism"]["meta"]["errno"]["number"] == 69
def test_non_string_variables(sentry_init, capture_events):
"""There is some extremely terrible code in the wild that
inserts non-strings as variable names into `locals()`."""
sentry_init()
events = capture_events()
try:
locals()[42] = True
1 / 0
except ZeroDivisionError:
capture_exception()
(event,) = events
(exception,) = event["exception"]["values"]
assert exception["type"] == "ZeroDivisionError"
(frame,) = exception["stacktrace"]["frames"]
assert frame["vars"]["42"] == "True"
def test_dict_changed_during_iteration(sentry_init, capture_events):
"""
Some versions of Bottle modify the WSGI environment inside of this __repr__
impl: https://github.com/bottlepy/bottle/blob/0.12.16/bottle.py#L1386
See https://github.com/getsentry/sentry-python/pull/298 for discussion
"""
sentry_init(send_default_pii=True)
events = capture_events()
class TooSmartClass(object):
def __init__(self, environ):
self.environ = environ
def __repr__(self):
if "my_representation" in self.environ:
return self.environ["my_representation"]
self.environ["my_representation"] = "<This is me>"
return self.environ["my_representation"]
try:
environ = {}
environ["a"] = TooSmartClass(environ)
1 / 0
except ZeroDivisionError:
capture_exception()
(event,) = events
(exception,) = event["exception"]["values"]
(frame,) = exception["stacktrace"]["frames"]
assert frame["vars"]["environ"] == {"a": "<This is me>"}
@pytest.mark.parametrize(
"dsn",
[
"http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2",
"http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2",
],
)
def test_init_string_types(dsn, sentry_init):
# Allow unicode strings on Python 3 and both on Python 2 (due to
# unicode_literals)
#
# Supporting bytes on Python 3 is not really wrong but probably would be
# extra code
sentry_init(dsn)
assert (
Hub.current.client.dsn
== "http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2"
)
def test_envelope_types():
"""
Tests for calling the right transport method (capture_event vs
capture_envelope) from the SDK client for different data types.
"""
envelopes = []
events = []
class CustomTransport(Transport):
def capture_envelope(self, envelope):
envelopes.append(envelope)
def capture_event(self, event):
events.append(event)
with Hub(Client(traces_sample_rate=1.0, transport=CustomTransport())):
event_id = capture_message("hello")
# Assert error events get passed in via capture_event
assert not envelopes
event = events.pop()
assert event["event_id"] == event_id
assert "type" not in event
with start_transaction(name="foo"):
pass
# Assert transactions get passed in via capture_envelope
assert not events
envelope = envelopes.pop()
(item,) = envelope.items
assert item.data_category == "transaction"
assert item.headers.get("type") == "transaction"
assert not envelopes
assert not events
@pytest.mark.parametrize(
"sdk_options, expected_breadcrumbs",
[({}, DEFAULT_MAX_BREADCRUMBS), ({"max_breadcrumbs": 50}, 50)],
)
def test_max_breadcrumbs_option(
sentry_init, capture_events, sdk_options, expected_breadcrumbs
):
sentry_init(sdk_options)
events = capture_events()
for _ in range(1231):
add_breadcrumb({"type": "sourdough"})
capture_message("dogs are great")
assert len(events[0]["breadcrumbs"]["values"]) == expected_breadcrumbs
def test_multiple_positional_args(sentry_init):
with pytest.raises(TypeError) as exinfo:
sentry_init(1, None)
assert "Only single positional argument is expected" in str(exinfo.value)