Setting a context variable and resetting it with the token received when setting it require to happen in the same asyncio task or in the same context.
The problem is that when using pytest async-generator fixtures (which works well since Python 3.6), this assumption is broken, because pytest creates two different asyncio tasks for the first part of fixture and the second part of fixture.
All my real-world usage scenarios work well but only testing fails.
import contextvars import pytest myvar = contextvars.ContextVar('myvar', default=0) @pytest.fixture async def myfixture(): token = myvar.set(1) yield myvar.reset(token) # <-- "different context" error @pytest.mark.asyncio async def test_myvar(myfixture): assert myvar.get() == 1 # <-- failure since myvar.get() returns 0
The error is:
ValueError: <Token var=<ContextVar name='myvar' at 0x108636db0> at 0x108fbbc00> was created in a different Context
How could I workaround this issue?