Debian Codegraph @

src/trio/_tests/test_contextvars.py

raw
1 from __future__ import annotations
2
3 import contextvars
4
5 from .. import _core
6
7 trio_testing_contextvar: contextvars.ContextVar[str] = contextvars.ContextVar(
8 "trio_testing_contextvar",
9 )
10
11
12 async def test_contextvars_default() -> None:
13 trio_testing_contextvar.set("main")
14 record: list[str] = []
15
16 async def child() -> None:
17 value = trio_testing_contextvar.get()
18 record.append(value)
19
20 async with _core.open_nursery() as nursery:
21 nursery.start_soon(child)
22 assert record == ["main"]
23
24
25 async def test_contextvars_set() -> None:
26 trio_testing_contextvar.set("main")
27 record: list[str] = []
28
29 async def child() -> None:
30 trio_testing_contextvar.set("child")
31 value = trio_testing_contextvar.get()
32 record.append(value)
33
34 async with _core.open_nursery() as nursery:
35 nursery.start_soon(child)
36 value = trio_testing_contextvar.get()
37 assert record == ["child"]
38 assert value == "main"
39
40
41 async def test_contextvars_copy() -> None:
42 trio_testing_contextvar.set("main")
43 context = contextvars.copy_context()
44 trio_testing_contextvar.set("second_main")
45 record: list[str] = []
46
47 async def child() -> None:
48 value = trio_testing_contextvar.get()
49 record.append(value)
50
51 async with _core.open_nursery() as nursery:
52 context.run(nursery.start_soon, child)
53 nursery.start_soon(child)
54 value = trio_testing_contextvar.get()
55 assert set(record) == {"main", "second_main"}
56 assert value == "second_main"