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
import contextvars
 
from .. import _core
 
trio_testing_contextvar = contextvars.ContextVar("trio_testing_contextvar")
 
 
async def test_contextvars_default():
    trio_testing_contextvar.set("main")
    record = []
 
    async def child():
        value = trio_testing_contextvar.get()
        record.append(value)
 
    async with _core.open_nursery() as nursery:
        nursery.start_soon(child)
    assert record == ["main"]
 
 
async def test_contextvars_set():
    trio_testing_contextvar.set("main")
    record = []
 
    async def child():
        trio_testing_contextvar.set("child")
        value = trio_testing_contextvar.get()
        record.append(value)
 
    async with _core.open_nursery() as nursery:
        nursery.start_soon(child)
    value = trio_testing_contextvar.get()
    assert record == ["child"]
    assert value == "main"
 
 
async def test_contextvars_copy():
    trio_testing_contextvar.set("main")
    context = contextvars.copy_context()
    trio_testing_contextvar.set("second_main")
    record = []
 
    async def child():
        value = trio_testing_contextvar.get()
        record.append(value)
 
    async with _core.open_nursery() as nursery:
        context.run(nursery.start_soon, child)
        nursery.start_soon(child)
    value = trio_testing_contextvar.get()
    assert set(record) == {"main", "second_main"}
    assert value == "second_main"