diff --git a/pytest_asyncio/plugin.py b/pytest_asyncio/plugin.py index ac756a2a..062437b7 100644 --- a/pytest_asyncio/plugin.py +++ b/pytest_asyncio/plugin.py @@ -381,12 +381,10 @@ def _create_task_in_context(loop, coro, context): the API added for https://github.com/python/cpython/issues/91150. On earlier versions, the returned task will use the default context instead. """ - if context is not None: - try: - return loop.create_task(coro, context=context) - except TypeError: - pass - return loop.create_task(coro) + try: + return loop.create_task(coro, context=context) + except TypeError: + return loop.create_task(coro) def _wrap_async_fixture(fixturedef: FixtureDef) -> None: diff --git a/tests/async_fixtures/test_async_fixtures_contextvars.py b/tests/async_fixtures/test_async_fixtures_contextvars.py index 3f58be54..bddab379 100644 --- a/tests/async_fixtures/test_async_fixtures_contextvars.py +++ b/tests/async_fixtures/test_async_fixtures_contextvars.py @@ -33,27 +33,34 @@ async def no_var_fixture(): @pytest.fixture(scope="function") -async def var_fixture(no_var_fixture): - with context_var_manager("value"): +async def var_fixture_1(no_var_fixture): + with context_var_manager("value1"): yield @pytest.fixture(scope="function") -async def var_nop_fixture(var_fixture): +async def var_nop_fixture(var_fixture_1): with context_var_manager(_context_var.get()): yield @pytest.fixture(scope="function") -def inner_var_fixture(var_nop_fixture): - assert _context_var.get() == "value" +def var_fixture_2(var_nop_fixture): + assert _context_var.get() == "value1" with context_var_manager("value2"): yield +@pytest.fixture(scope="function") +async def var_fixture_3(var_fixture_2): + assert _context_var.get() == "value2" + with context_var_manager("value3"): + yield + + @pytest.mark.asyncio @pytest.mark.xfail( sys.version_info < (3, 11), reason="requires asyncio Task context support" ) -async def test(inner_var_fixture): - assert _context_var.get() == "value2" +async def test(var_fixture_3): + assert _context_var.get() == "value3"