-
Notifications
You must be signed in to change notification settings - Fork 159
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Maintain contextvars.Context in fixtures and tests
The approach I've taken here is to maintain a contextvars.Context instance in a contextvars.ContextVar, copying it from the ambient context whenever we create a new event loop. The fixture setup and teardown run within that context, and each test function gets a copy (as if it were created as a new asyncio.Task from within the fixture task). Fixes #127.
- Loading branch information
Showing
2 changed files
with
101 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
""" | ||
Regression test for https://github.com/pytest-dev/pytest-asyncio/issues/127: | ||
contextvars were not properly maintained among fixtures and tests. | ||
""" | ||
|
||
from __future__ import annotations | ||
|
||
import sys | ||
from contextlib import asynccontextmanager | ||
from contextvars import ContextVar | ||
|
||
import pytest | ||
|
||
|
||
@asynccontextmanager | ||
async def context_var_manager(): | ||
context_var = ContextVar("context_var") | ||
token = context_var.set("value") | ||
try: | ||
yield context_var | ||
finally: | ||
context_var.reset(token) | ||
|
||
|
||
@pytest.fixture(scope="function") | ||
async def context_var(): | ||
async with context_var_manager() as v: | ||
yield v | ||
|
||
|
||
@pytest.mark.asyncio | ||
@pytest.mark.xfail( | ||
sys.version_info < (3, 11), reason="requires asyncio Task context support" | ||
) | ||
async def test(context_var): | ||
assert context_var.get() == "value" |