Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ContextVar value set in async fixture is not available in test #544

Closed
chbndrhnns opened this issue Mar 15, 2023 · 2 comments
Closed

ContextVar value set in async fixture is not available in test #544

chbndrhnns opened this issue Mar 15, 2023 · 2 comments

Comments

@chbndrhnns
Copy link

It seems I cannot set a value of a ContextVar member from a fixture in pytest if that fixture is async.

In the snippet below, I expect all tests to pass but test_set_in_async_fixture which depends on a async fixture fails.

from contextvars import ContextVar

import pytest

_var = ContextVar("var", default=None)

pytestmark = [pytest.mark.anyio, ]


@pytest.fixture
def anyio_backend():
    return "asyncio"


@pytest.fixture
async def async_():
    _var.set("other")
    yield
    _var.set(None)


@pytest.fixture
def sync_():
    _var.set("other")
    yield
    _var.set(None)


async def test_None():
    assert _var.get() is None


async def test_not_None():
    _var.set("other")
    assert _var.get() == "other"
    _var.set(None)


async def test_set_in_sync_fixture(sync_):
    assert _var.get() == "other"


async def test_set_in_async_fixture(async_):
    assert _var.get() == "other"
@chbndrhnns chbndrhnns changed the title Cannot set contextvar value in async fixture ContextVar value set in async fixture is not available in test Mar 15, 2023
@agronholm
Copy link
Owner

This is a shortcoming of the 3.x series, and is resolved in master. This happens in v3.x because each async fixture is run in a separate task, and is thus isolated from the actual test. The upcoming v4.0 runs each test along with its set of async fixtures within the same task.

@chbndrhnns
Copy link
Author

Awesome, thanks for letting me know!
I noticed there is a similar problem in pytest-asyncio and the suggestion from there works here, too:

A much easier solution is to set the contextvar directly in the sync fixture — note, not async fixture, but sync:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants