Contextvars with pytest async-generator fixture

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)

async def myfixture():
    token = myvar.set(1)
    myvar.reset(token)  # <-- "different context" error

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?

pytest-dev/pytest-asyncio#153 may resolve this issue.
Looking forward to it.