-
Notifications
You must be signed in to change notification settings - Fork 608
Expand file tree
/
Copy pathtest_asyncio.py
More file actions
505 lines (367 loc) · 14.5 KB
/
test_asyncio.py
File metadata and controls
505 lines (367 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
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
import asyncio
import inspect
import sys
from unittest.mock import MagicMock, patch
import pytest
import sentry_sdk
from sentry_sdk.consts import OP
from sentry_sdk.integrations.asyncio import (
AsyncioIntegration,
patch_asyncio,
enable_asyncio_integration,
)
try:
from contextvars import Context, ContextVar
except ImportError:
pass # All tests will be skipped with incompatible versions
minimum_python_38 = pytest.mark.skipif(
sys.version_info < (3, 8), reason="Asyncio tests need Python >= 3.8"
)
minimum_python_311 = pytest.mark.skipif(
sys.version_info < (3, 11),
reason="Asyncio task context parameter was introduced in Python 3.11",
)
async def foo():
await asyncio.sleep(0.01)
async def bar():
await asyncio.sleep(0.01)
async def boom():
1 / 0
def get_sentry_task_factory(mock_get_running_loop):
"""
Patches (mocked) asyncio and gets the sentry_task_factory.
"""
mock_loop = mock_get_running_loop.return_value
patch_asyncio()
patched_factory = mock_loop.set_task_factory.call_args[0][0]
return patched_factory
@minimum_python_38
@pytest.mark.asyncio(loop_scope="module")
async def test_create_task(
sentry_init,
capture_events,
):
sentry_init(
traces_sample_rate=1.0,
send_default_pii=True,
integrations=[
AsyncioIntegration(),
],
)
events = capture_events()
with sentry_sdk.start_transaction(name="test_transaction_for_create_task"):
with sentry_sdk.start_span(op="root", name="not so important"):
foo_task = asyncio.create_task(foo())
bar_task = asyncio.create_task(bar())
if hasattr(foo_task.get_coro(), "__name__"):
assert foo_task.get_coro().__name__ == "foo"
if hasattr(bar_task.get_coro(), "__name__"):
assert bar_task.get_coro().__name__ == "bar"
tasks = [foo_task, bar_task]
await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
sentry_sdk.flush()
(transaction_event,) = events
assert transaction_event["spans"][0]["op"] == "root"
assert transaction_event["spans"][0]["description"] == "not so important"
assert transaction_event["spans"][1]["op"] == OP.FUNCTION
assert transaction_event["spans"][1]["description"] == "foo"
assert (
transaction_event["spans"][1]["parent_span_id"]
== transaction_event["spans"][0]["span_id"]
)
assert transaction_event["spans"][2]["op"] == OP.FUNCTION
assert transaction_event["spans"][2]["description"] == "bar"
assert (
transaction_event["spans"][2]["parent_span_id"]
== transaction_event["spans"][0]["span_id"]
)
@minimum_python_38
@pytest.mark.asyncio(loop_scope="module")
async def test_gather(
sentry_init,
capture_events,
):
sentry_init(
traces_sample_rate=1.0,
send_default_pii=True,
integrations=[
AsyncioIntegration(),
],
)
events = capture_events()
with sentry_sdk.start_transaction(name="test_transaction_for_gather"):
with sentry_sdk.start_span(op="root", name="not so important"):
await asyncio.gather(foo(), bar(), return_exceptions=True)
sentry_sdk.flush()
(transaction_event,) = events
assert transaction_event["spans"][0]["op"] == "root"
assert transaction_event["spans"][0]["description"] == "not so important"
assert transaction_event["spans"][1]["op"] == OP.FUNCTION
assert transaction_event["spans"][1]["description"] == "foo"
assert (
transaction_event["spans"][1]["parent_span_id"]
== transaction_event["spans"][0]["span_id"]
)
assert transaction_event["spans"][2]["op"] == OP.FUNCTION
assert transaction_event["spans"][2]["description"] == "bar"
assert (
transaction_event["spans"][2]["parent_span_id"]
== transaction_event["spans"][0]["span_id"]
)
@minimum_python_38
@pytest.mark.asyncio(loop_scope="module")
async def test_exception(
sentry_init,
capture_events,
):
sentry_init(
traces_sample_rate=1.0,
send_default_pii=True,
integrations=[
AsyncioIntegration(),
],
)
events = capture_events()
with sentry_sdk.start_transaction(name="test_exception"):
with sentry_sdk.start_span(op="root", name="not so important"):
tasks = [asyncio.create_task(boom()), asyncio.create_task(bar())]
await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
sentry_sdk.flush()
(error_event, _) = events
assert error_event["transaction"] == "test_exception"
assert error_event["contexts"]["trace"]["op"] == "function"
assert error_event["exception"]["values"][0]["type"] == "ZeroDivisionError"
assert error_event["exception"]["values"][0]["value"] == "division by zero"
assert error_event["exception"]["values"][0]["mechanism"]["handled"] is False
assert error_event["exception"]["values"][0]["mechanism"]["type"] == "asyncio"
@minimum_python_38
@pytest.mark.asyncio(loop_scope="module")
async def test_task_result(sentry_init):
sentry_init(
integrations=[
AsyncioIntegration(),
],
)
async def add(a, b):
return a + b
result = await asyncio.create_task(add(1, 2))
assert result == 3, result
@minimum_python_311
@pytest.mark.asyncio(loop_scope="module")
async def test_task_with_context(sentry_init):
"""
Integration test to ensure working context parameter in Python 3.11+
"""
sentry_init(
integrations=[
AsyncioIntegration(),
],
)
var = ContextVar("var")
var.set("original value")
async def change_value():
var.set("changed value")
async def retrieve_value():
return var.get()
# Create a context and run both tasks within the context
ctx = Context()
async with asyncio.TaskGroup() as tg:
tg.create_task(change_value(), context=ctx)
retrieve_task = tg.create_task(retrieve_value(), context=ctx)
assert retrieve_task.result() == "changed value"
@minimum_python_38
@patch("asyncio.get_running_loop")
def test_patch_asyncio(mock_get_running_loop):
"""
Test that the patch_asyncio function will patch the task factory.
"""
mock_loop = mock_get_running_loop.return_value
mock_loop.get_task_factory.return_value._is_sentry_task_factory = False
patch_asyncio()
assert mock_loop.set_task_factory.called
set_task_factory_args, _ = mock_loop.set_task_factory.call_args
assert len(set_task_factory_args) == 1
sentry_task_factory, *_ = set_task_factory_args
assert callable(sentry_task_factory)
@minimum_python_38
@patch("asyncio.get_running_loop")
@patch("sentry_sdk.integrations.asyncio.Task")
def test_sentry_task_factory_no_factory(MockTask, mock_get_running_loop): # noqa: N803
mock_loop = mock_get_running_loop.return_value
mock_coro = MagicMock()
# Set the original task factory to None
mock_loop.get_task_factory.return_value = None
# Retieve sentry task factory (since it is an inner function within patch_asyncio)
sentry_task_factory = get_sentry_task_factory(mock_get_running_loop)
# The call we are testing
ret_val = sentry_task_factory(mock_loop, mock_coro)
assert MockTask.called
assert ret_val == MockTask.return_value
task_args, task_kwargs = MockTask.call_args
assert len(task_args) == 1
coro_param, *_ = task_args
assert inspect.iscoroutine(coro_param)
assert "loop" in task_kwargs
assert task_kwargs["loop"] == mock_loop
@minimum_python_38
@patch("asyncio.get_running_loop")
def test_sentry_task_factory_with_factory(mock_get_running_loop):
mock_loop = mock_get_running_loop.return_value
mock_coro = MagicMock()
# The original task factory will be mocked out here, let's retrieve the value for later
orig_task_factory = mock_loop.get_task_factory.return_value
orig_task_factory._is_sentry_task_factory = False
# Retieve sentry task factory (since it is an inner function within patch_asyncio)
sentry_task_factory = get_sentry_task_factory(mock_get_running_loop)
# The call we are testing
ret_val = sentry_task_factory(mock_loop, mock_coro)
assert orig_task_factory.called
assert ret_val == orig_task_factory.return_value
task_factory_args, _ = orig_task_factory.call_args
assert len(task_factory_args) == 2
loop_arg, coro_arg = task_factory_args
assert loop_arg == mock_loop
assert inspect.iscoroutine(coro_arg)
@minimum_python_311
@patch("asyncio.get_running_loop")
@patch("sentry_sdk.integrations.asyncio.Task")
def test_sentry_task_factory_context_no_factory(
MockTask,
mock_get_running_loop, # noqa: N803
):
mock_loop = mock_get_running_loop.return_value
mock_coro = MagicMock()
mock_context = MagicMock()
# Set the original task factory to None
mock_loop.get_task_factory.return_value = None
# Retieve sentry task factory (since it is an inner function within patch_asyncio)
sentry_task_factory = get_sentry_task_factory(mock_get_running_loop)
# The call we are testing
ret_val = sentry_task_factory(mock_loop, mock_coro, context=mock_context)
assert MockTask.called
assert ret_val == MockTask.return_value
task_args, task_kwargs = MockTask.call_args
assert len(task_args) == 1
coro_param, *_ = task_args
assert inspect.iscoroutine(coro_param)
assert "loop" in task_kwargs
assert task_kwargs["loop"] == mock_loop
assert "context" in task_kwargs
assert task_kwargs["context"] == mock_context
@minimum_python_311
@patch("asyncio.get_running_loop")
def test_sentry_task_factory_context_with_factory(mock_get_running_loop):
mock_loop = mock_get_running_loop.return_value
mock_coro = MagicMock()
mock_context = MagicMock()
# The original task factory will be mocked out here, let's retrieve the value for later
orig_task_factory = mock_loop.get_task_factory.return_value
orig_task_factory._is_sentry_task_factory = False
# Retieve sentry task factory (since it is an inner function within patch_asyncio)
sentry_task_factory = get_sentry_task_factory(mock_get_running_loop)
# The call we are testing
ret_val = sentry_task_factory(mock_loop, mock_coro, context=mock_context)
assert orig_task_factory.called
assert ret_val == orig_task_factory.return_value
task_factory_args, task_factory_kwargs = orig_task_factory.call_args
assert len(task_factory_args) == 2
loop_arg, coro_arg = task_factory_args
assert loop_arg == mock_loop
assert inspect.iscoroutine(coro_arg)
assert "context" in task_factory_kwargs
assert task_factory_kwargs["context"] == mock_context
@minimum_python_38
@pytest.mark.asyncio(loop_scope="module")
async def test_span_origin(
sentry_init,
capture_events,
):
sentry_init(
integrations=[AsyncioIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
with sentry_sdk.start_transaction(name="something"):
tasks = [
asyncio.create_task(foo()),
]
await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
sentry_sdk.flush()
(event,) = events
assert event["contexts"]["trace"]["origin"] == "manual"
assert event["spans"][0]["origin"] == "auto.function.asyncio"
@minimum_python_38
@pytest.mark.asyncio
async def test_delayed_enable_integration(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
assert "asyncio" not in sentry_sdk.get_client().integrations
events = capture_events()
with sentry_sdk.start_transaction(name="test"):
await asyncio.create_task(foo())
assert len(events) == 1
(transaction,) = events
assert not transaction["spans"]
enable_asyncio_integration()
events = capture_events()
assert "asyncio" in sentry_sdk.get_client().integrations
with sentry_sdk.start_transaction(name="test"):
await asyncio.create_task(foo())
assert len(events) == 1
(transaction,) = events
assert transaction["spans"]
assert transaction["spans"][0]["origin"] == "auto.function.asyncio"
@minimum_python_38
@pytest.mark.asyncio
async def test_delayed_enable_integration_with_options(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
assert "asyncio" not in sentry_sdk.get_client().integrations
mock_init = MagicMock(return_value=None)
mock_setup_once = MagicMock()
with patch(
"sentry_sdk.integrations.asyncio.AsyncioIntegration.__init__", mock_init
):
with patch(
"sentry_sdk.integrations.asyncio.AsyncioIntegration.setup_once",
mock_setup_once,
):
enable_asyncio_integration("arg", kwarg="kwarg")
assert "asyncio" in sentry_sdk.get_client().integrations
mock_init.assert_called_once_with("arg", kwarg="kwarg")
mock_setup_once.assert_called_once()
@minimum_python_38
@pytest.mark.asyncio
async def test_delayed_enable_enabled_integration(sentry_init, uninstall_integration):
# Ensure asyncio integration is not already installed from previous tests
uninstall_integration("asyncio")
integration = AsyncioIntegration()
sentry_init(integrations=[integration], traces_sample_rate=1.0)
assert "asyncio" in sentry_sdk.get_client().integrations
# Get the task factory after initial setup - it should be Sentry's
loop = asyncio.get_running_loop()
task_factory_before = loop.get_task_factory()
assert getattr(task_factory_before, "_is_sentry_task_factory", False) is True
enable_asyncio_integration()
assert "asyncio" in sentry_sdk.get_client().integrations
# The task factory should be the same (loop not re-patched)
task_factory_after = loop.get_task_factory()
assert task_factory_before is task_factory_after
@minimum_python_38
@pytest.mark.asyncio
async def test_delayed_enable_integration_after_disabling(sentry_init, capture_events):
sentry_init(disabled_integrations=[AsyncioIntegration()], traces_sample_rate=1.0)
assert "asyncio" not in sentry_sdk.get_client().integrations
events = capture_events()
with sentry_sdk.start_transaction(name="test"):
await asyncio.create_task(foo())
assert len(events) == 1
(transaction,) = events
assert not transaction["spans"]
enable_asyncio_integration()
events = capture_events()
assert "asyncio" in sentry_sdk.get_client().integrations
with sentry_sdk.start_transaction(name="test"):
await asyncio.create_task(foo())
assert len(events) == 1
(transaction,) = events
assert transaction["spans"]
assert transaction["spans"][0]["origin"] == "auto.function.asyncio"