/
test_basics.py
564 lines (421 loc) · 16.2 KB
/
test_basics.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
import os
import sys
import logging
import pytest
from sentry_sdk import (
Client,
push_scope,
configure_scope,
capture_event,
capture_exception,
capture_message,
start_transaction,
add_breadcrumb,
last_event_id,
Hub,
)
from sentry_sdk._compat import reraise
from sentry_sdk.integrations import _AUTO_ENABLING_INTEGRATIONS
from sentry_sdk.integrations.logging import LoggingIntegration
from sentry_sdk.scope import ( # noqa: F401
add_global_event_processor,
global_event_processors,
)
from sentry_sdk.utils import get_sdk_name
def test_processors(sentry_init, capture_events):
sentry_init()
events = capture_events()
with configure_scope() as scope:
def error_processor(event, exc_info):
event["exception"]["values"][0]["value"] += " whatever"
return event
scope.add_error_processor(error_processor, ValueError)
try:
raise ValueError("aha!")
except Exception:
capture_exception()
(event,) = events
assert event["exception"]["values"][0]["value"] == "aha! whatever"
def test_auto_enabling_integrations_catches_import_error(sentry_init, caplog):
caplog.set_level(logging.DEBUG)
REDIS = 12 # noqa: N806
sentry_init(auto_enabling_integrations=True, debug=True)
for import_string in _AUTO_ENABLING_INTEGRATIONS:
# Ignore redis in the test case, because it is installed as a
# dependency for running tests, and therefore always enabled.
if _AUTO_ENABLING_INTEGRATIONS[REDIS] == import_string:
continue
assert any(
record.message.startswith(
"Did not import default integration {}:".format(import_string)
)
for record in caplog.records
), "Problem with checking auto enabling {}".format(import_string)
def test_event_id(sentry_init, capture_events):
sentry_init()
events = capture_events()
try:
raise ValueError("aha!")
except Exception:
event_id = capture_exception()
int(event_id, 16)
assert len(event_id) == 32
(event,) = events
assert event["event_id"] == event_id
assert last_event_id() == event_id
assert Hub.current.last_event_id() == event_id
new_event_id = Hub.current.capture_event({"type": "transaction"})
assert new_event_id is not None
assert new_event_id != event_id
assert Hub.current.last_event_id() == event_id
def test_option_before_send(sentry_init, capture_events, monkeypatch):
def before_send(event, hint):
event["extra"] = {"before_send_called": True}
return event
def do_this():
try:
raise ValueError("aha!")
except Exception:
capture_exception()
sentry_init(before_send=before_send)
events = capture_events()
do_this()
(event,) = events
assert event["extra"] == {"before_send_called": True}
sentry_init()
events = capture_events()
do_this()
(event,) = events
assert "before_send_called" not in event["extra"]
def test_option_before_send_transaction(sentry_init, capture_events, monkeypatch):
def before_send_transaction(event, hint):
assert event["type"] == "transaction"
event["extra"] = {"before_send_transaction_called": True}
return event
sentry_init(
before_send_transaction=before_send_transaction,
traces_sample_rate=1.0,
)
events = capture_events()
transaction = start_transaction(name="foo")
transaction.finish()
(event,) = events
assert event["transaction"] == "foo"
assert event["extra"] == {"before_send_transaction_called": True}
sentry_init(
traces_sample_rate=1.0,
)
events = capture_events()
transaction = start_transaction(name="foo")
transaction.finish()
(event,) = events
assert event["transaction"] == "foo"
assert "before_send_transaction_called" not in event["extra"]
def test_option_before_breadcrumb(sentry_init, capture_events, monkeypatch):
drop_events = False
drop_breadcrumbs = False
reports = []
def record_lost_event(reason, data_category=None, item=None):
reports.append((reason, data_category))
def before_send(event, hint):
assert isinstance(hint["exc_info"][1], ValueError)
if not drop_events:
event["extra"] = {"foo": "bar"}
return event
def before_breadcrumb(crumb, hint):
assert hint == {"foo": 42}
if not drop_breadcrumbs:
crumb["data"] = {"foo": "bar"}
return crumb
sentry_init(before_send=before_send, before_breadcrumb=before_breadcrumb)
events = capture_events()
monkeypatch.setattr(
Hub.current.client.transport, "record_lost_event", record_lost_event
)
def do_this():
add_breadcrumb(message="Hello", hint={"foo": 42})
try:
raise ValueError("aha!")
except Exception:
capture_exception()
do_this()
drop_breadcrumbs = True
do_this()
assert not reports
drop_events = True
do_this()
assert reports == [("before_send", "error")]
normal, no_crumbs = events
assert normal["exception"]["values"][0]["type"] == "ValueError"
(crumb,) = normal["breadcrumbs"]["values"]
assert "timestamp" in crumb
assert crumb["message"] == "Hello"
assert crumb["data"] == {"foo": "bar"}
assert crumb["type"] == "default"
def test_breadcrumb_arguments(sentry_init, capture_events):
assert_hint = {"bar": 42}
def before_breadcrumb(crumb, hint):
assert crumb["foo"] == 42
assert hint == assert_hint
sentry_init(before_breadcrumb=before_breadcrumb)
add_breadcrumb(foo=42, hint=dict(bar=42))
add_breadcrumb(dict(foo=42), dict(bar=42))
add_breadcrumb(dict(foo=42), hint=dict(bar=42))
add_breadcrumb(crumb=dict(foo=42), hint=dict(bar=42))
assert_hint.clear()
add_breadcrumb(foo=42)
add_breadcrumb(crumb=dict(foo=42))
def test_push_scope(sentry_init, capture_events):
sentry_init()
events = capture_events()
with push_scope() as scope:
scope.level = "warning"
try:
1 / 0
except Exception as e:
capture_exception(e)
(event,) = events
assert event["level"] == "warning"
assert "exception" in event
def test_push_scope_null_client(sentry_init, capture_events):
sentry_init()
events = capture_events()
Hub.current.bind_client(None)
with push_scope() as scope:
scope.level = "warning"
try:
1 / 0
except Exception as e:
capture_exception(e)
assert len(events) == 0
@pytest.mark.parametrize("null_client", (True, False))
def test_push_scope_callback(sentry_init, null_client, capture_events):
sentry_init()
if null_client:
Hub.current.bind_client(None)
outer_scope = Hub.current.scope
calls = []
@push_scope
def _(scope):
assert scope is Hub.current.scope
assert scope is not outer_scope
calls.append(1)
# push_scope always needs to execute the callback regardless of
# client state, because that actually runs usercode in it, not
# just scope config code
assert calls == [1]
# Assert scope gets popped correctly
assert Hub.current.scope is outer_scope
def test_breadcrumbs(sentry_init, capture_events):
sentry_init(max_breadcrumbs=10)
events = capture_events()
for i in range(20):
add_breadcrumb(
category="auth", message="Authenticated user %s" % i, level="info"
)
capture_exception(ValueError())
(event,) = events
assert len(event["breadcrumbs"]["values"]) == 10
assert "user 10" in event["breadcrumbs"]["values"][0]["message"]
assert "user 19" in event["breadcrumbs"]["values"][-1]["message"]
del events[:]
for i in range(2):
add_breadcrumb(
category="auth", message="Authenticated user %s" % i, level="info"
)
with configure_scope() as scope:
scope.clear()
capture_exception(ValueError())
(event,) = events
assert len(event["breadcrumbs"]["values"]) == 0
def test_attachments(sentry_init, capture_envelopes):
sentry_init()
envelopes = capture_envelopes()
this_file = os.path.abspath(__file__.rstrip("c"))
with configure_scope() as scope:
scope.add_attachment(bytes=b"Hello World!", filename="message.txt")
scope.add_attachment(path=this_file)
capture_exception(ValueError())
(envelope,) = envelopes
assert len(envelope.items) == 3
assert envelope.get_event()["exception"] is not None
attachments = [x for x in envelope.items if x.type == "attachment"]
(message, pyfile) = attachments
assert message.headers["filename"] == "message.txt"
assert message.headers["type"] == "attachment"
assert message.headers["content_type"] == "text/plain"
assert message.payload.bytes == message.payload.get_bytes() == b"Hello World!"
assert pyfile.headers["filename"] == os.path.basename(this_file)
assert pyfile.headers["type"] == "attachment"
assert pyfile.headers["content_type"].startswith("text/")
assert pyfile.payload.bytes is None
with open(this_file, "rb") as f:
assert pyfile.payload.get_bytes() == f.read()
def test_integration_scoping(sentry_init, capture_events):
logger = logging.getLogger("test_basics")
# This client uses the logging integration
logging_integration = LoggingIntegration(event_level=logging.WARNING)
sentry_init(default_integrations=False, integrations=[logging_integration])
events = capture_events()
logger.warning("This is a warning")
assert len(events) == 1
# This client does not
sentry_init(default_integrations=False)
events = capture_events()
logger.warning("This is not a warning")
assert not events
def test_client_initialized_within_scope(sentry_init, caplog):
caplog.set_level(logging.WARNING)
sentry_init(debug=True)
with push_scope():
Hub.current.bind_client(Client())
(record,) = (x for x in caplog.records if x.levelname == "WARNING")
assert record.msg.startswith("init() called inside of pushed scope.")
def test_scope_leaks_cleaned_up(sentry_init, caplog):
caplog.set_level(logging.WARNING)
sentry_init(debug=True)
old_stack = list(Hub.current._stack)
with push_scope():
push_scope()
assert Hub.current._stack == old_stack
(record,) = (x for x in caplog.records if x.levelname == "WARNING")
assert record.message.startswith("Leaked 1 scopes:")
def test_scope_popped_too_soon(sentry_init, caplog):
caplog.set_level(logging.ERROR)
sentry_init(debug=True)
old_stack = list(Hub.current._stack)
with push_scope():
Hub.current.pop_scope_unsafe()
assert Hub.current._stack == old_stack
(record,) = (x for x in caplog.records if x.levelname == "ERROR")
assert record.message == ("Scope popped too soon. Popped 1 scopes too many.")
def test_scope_event_processor_order(sentry_init, capture_events):
def before_send(event, hint):
event["message"] += "baz"
return event
sentry_init(debug=True, before_send=before_send)
events = capture_events()
with push_scope() as scope:
@scope.add_event_processor
def foo(event, hint):
event["message"] += "foo"
return event
with push_scope() as scope:
@scope.add_event_processor
def bar(event, hint):
event["message"] += "bar"
return event
capture_message("hi")
(event,) = events
assert event["message"] == "hifoobarbaz"
def test_capture_event_with_scope_kwargs(sentry_init, capture_events):
sentry_init(debug=True)
events = capture_events()
capture_event({}, level="info", extras={"foo": "bar"})
(event,) = events
assert event["level"] == "info"
assert event["extra"]["foo"] == "bar"
def test_dedupe_event_processor_drop_records_client_report(
sentry_init, capture_events, capture_client_reports
):
"""
DedupeIntegration internally has an event_processor that filters duplicate exceptions.
We want a duplicate exception to be captured only once and the drop being recorded as
a client report.
"""
sentry_init()
events = capture_events()
reports = capture_client_reports()
try:
raise ValueError("aha!")
except Exception:
try:
capture_exception()
reraise(*sys.exc_info())
except Exception:
capture_exception()
(event,) = events
(report,) = reports
assert event["level"] == "error"
assert "exception" in event
assert report == ("event_processor", "error")
def test_event_processor_drop_records_client_report(
sentry_init, capture_events, capture_client_reports
):
sentry_init(traces_sample_rate=1.0)
events = capture_events()
reports = capture_client_reports()
global global_event_processors
@add_global_event_processor
def foo(event, hint):
return None
capture_message("dropped")
with start_transaction(name="dropped"):
pass
assert len(events) == 0
assert reports == [("event_processor", "error"), ("event_processor", "transaction")]
global_event_processors.pop()
@pytest.mark.parametrize(
"installed_integrations, expected_name",
[
# integrations with own name
(["django"], "sentry.python.django"),
(["flask"], "sentry.python.flask"),
(["fastapi"], "sentry.python.fastapi"),
(["bottle"], "sentry.python.bottle"),
(["falcon"], "sentry.python.falcon"),
(["quart"], "sentry.python.quart"),
(["sanic"], "sentry.python.sanic"),
(["starlette"], "sentry.python.starlette"),
(["chalice"], "sentry.python.chalice"),
(["serverless"], "sentry.python.serverless"),
(["pyramid"], "sentry.python.pyramid"),
(["tornado"], "sentry.python.tornado"),
(["aiohttp"], "sentry.python.aiohttp"),
(["aws_lambda"], "sentry.python.aws_lambda"),
(["gcp"], "sentry.python.gcp"),
(["beam"], "sentry.python.beam"),
(["asgi"], "sentry.python.asgi"),
(["wsgi"], "sentry.python.wsgi"),
# integrations without name
(["argv"], "sentry.python"),
(["atexit"], "sentry.python"),
(["boto3"], "sentry.python"),
(["celery"], "sentry.python"),
(["dedupe"], "sentry.python"),
(["excepthook"], "sentry.python"),
(["executing"], "sentry.python"),
(["modules"], "sentry.python"),
(["pure_eval"], "sentry.python"),
(["redis"], "sentry.python"),
(["rq"], "sentry.python"),
(["sqlalchemy"], "sentry.python"),
(["stdlib"], "sentry.python"),
(["threading"], "sentry.python"),
(["trytond"], "sentry.python"),
(["logging"], "sentry.python"),
(["gnu_backtrace"], "sentry.python"),
(["httpx"], "sentry.python"),
# precedence of frameworks
(["flask", "django", "celery"], "sentry.python.django"),
(["fastapi", "flask", "redis"], "sentry.python.flask"),
(["bottle", "fastapi", "httpx"], "sentry.python.fastapi"),
(["falcon", "bottle", "logging"], "sentry.python.bottle"),
(["quart", "falcon", "gnu_backtrace"], "sentry.python.falcon"),
(["sanic", "quart", "sqlalchemy"], "sentry.python.quart"),
(["starlette", "sanic", "rq"], "sentry.python.sanic"),
(["chalice", "starlette", "modules"], "sentry.python.starlette"),
(["serverless", "chalice", "pure_eval"], "sentry.python.chalice"),
(["pyramid", "serverless", "modules"], "sentry.python.serverless"),
(["tornado", "pyramid", "executing"], "sentry.python.pyramid"),
(["aiohttp", "tornado", "dedupe"], "sentry.python.tornado"),
(["aws_lambda", "aiohttp", "boto3"], "sentry.python.aiohttp"),
(["gcp", "aws_lambda", "atexit"], "sentry.python.aws_lambda"),
(["beam", "gcp", "argv"], "sentry.python.gcp"),
(["asgi", "beam", "stdtlib"], "sentry.python.beam"),
(["wsgi", "asgi", "boto3"], "sentry.python.asgi"),
(["wsgi", "celery", "redis"], "sentry.python.wsgi"),
],
)
def test_get_sdk_name(installed_integrations, expected_name):
assert get_sdk_name(installed_integrations) == expected_name