| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextvars |
| 4 |
import time |
| 5 |
from typing import Any |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from ..util import busy_wait |
| 10 |
from .util import parametrize_setstatprofile |
| 11 |
|
| 12 |
|
| 13 |
@parametrize_setstatprofile |
| 14 |
def test_context_type(setstatprofile): |
| 15 |
with pytest.raises(TypeError): |
| 16 |
setstatprofile(lambda f, e, a: 0, 1e6, "not a context var") |
| 17 |
setstatprofile(None) |
| 18 |
|
| 19 |
|
| 20 |
profiler_context_var: contextvars.ContextVar[object | None] = contextvars.ContextVar( |
| 21 |
"profiler_context_var", default=None |
| 22 |
) |
| 23 |
|
| 24 |
|
| 25 |
@parametrize_setstatprofile |
| 26 |
def test_context_tracking(setstatprofile): |
| 27 |
profile_calls = [] |
| 28 |
|
| 29 |
def profile_callback(frame, event, arg): |
| 30 |
nonlocal profile_calls |
| 31 |
profile_calls.append((frame, event, arg)) |
| 32 |
|
| 33 |
profiler_1 = object() |
| 34 |
profiler_2 = object() |
| 35 |
|
| 36 |
context_1 = contextvars.copy_context() |
| 37 |
context_2 = contextvars.copy_context() |
| 38 |
|
| 39 |
context_1.run(profiler_context_var.set, profiler_1) |
| 40 |
context_2.run(profiler_context_var.set, profiler_2) |
| 41 |
|
| 42 |
setstatprofile( |
| 43 |
profile_callback, |
| 44 |
1e10, |
| 45 |
profiler_context_var, |
| 46 |
) |
| 47 |
|
| 48 |
context_1.run(busy_wait, 0.001) |
| 49 |
context_2.run(busy_wait, 0.001) |
| 50 |
|
| 51 |
setstatprofile(None) |
| 52 |
|
| 53 |
assert all(c[1] == "context_changed" for c in profile_calls) |
| 54 |
assert len(profile_calls) == 4 |
| 55 |
|
| 56 |
new, old, _ = profile_calls[0][2] |
| 57 |
assert old is None |
| 58 |
assert new is profiler_1 |
| 59 |
|
| 60 |
new, old, _ = profile_calls[1][2] |
| 61 |
assert old is profiler_1 |
| 62 |
assert new is None |
| 63 |
|
| 64 |
new, old, _ = profile_calls[2][2] |
| 65 |
assert old is None |
| 66 |
assert new is profiler_2 |
| 67 |
|
| 68 |
new, old, _ = profile_calls[3][2] |
| 69 |
assert old is profiler_2 |
| 70 |
assert new is None |