Skip to content

Commit 571ab5c

Browse files
committed
fail if asyncio test requests async pytest fixture in strict mode
1 parent 575ebe1 commit 571ab5c

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

pytest_asyncio/plugin.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -880,7 +880,20 @@ def pytest_pyfunc_call(pyfuncitem: Function) -> object | None:
880880
"""
881881
if pyfuncitem.get_closest_marker("asyncio") is not None:
882882
if isinstance(pyfuncitem, PytestAsyncioFunction):
883-
pass
883+
asyncio_mode = _get_asyncio_mode(pyfuncitem.config)
884+
for fixtures in pyfuncitem._fixtureinfo.name2fixturedefs.values():
885+
# name2fixturedefs is a dict between fixture name and a list of matching
886+
# fixturedefs. The last entry in the list is closest and the one used.
887+
func = fixtures[-1].func
888+
if (
889+
_is_coroutine_or_asyncgen(func)
890+
and not _is_asyncio_fixture_function(func)
891+
and asyncio_mode == Mode.STRICT
892+
):
893+
pytest.fail(
894+
"asyncio test requested async fixture not marked asyncio, "
895+
"in strict mode. You might want to use @pytest_asyncio.fixture"
896+
)
884897
else:
885898
pyfuncitem.warn(
886899
pytest.PytestWarning(

tests/modes/test_strict_mode.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,31 @@ async def test_anything(any_fixture):
124124
"*coroutine 'any_fixture' was never awaited*",
125125
],
126126
)
127+
128+
129+
def test_strict_mode_marked_test_errors_unmarked_fixture(pytester: Pytester):
130+
pytester.makeini("[pytest]\nasyncio_default_fixture_loop_scope = function")
131+
pytester.makepyfile(
132+
dedent(
133+
"""\
134+
import pytest
135+
136+
# Not using pytest_asyncio.fixture
137+
@pytest.fixture()
138+
async def any_fixture():
139+
raise RuntimeError()
140+
141+
@pytest.mark.asyncio
142+
async def test_anything(any_fixture):
143+
pass
144+
"""
145+
)
146+
)
147+
result = pytester.runpytest_subprocess("--asyncio-mode=strict", "-W default")
148+
result.assert_outcomes(failed=1, skipped=0, warnings=1)
149+
result.stdout.fnmatch_lines(
150+
[
151+
"*asyncio test requested async fixture not marked asyncio in strict mode*",
152+
"*coroutine 'any_fixture' was never awaited*",
153+
],
154+
)

0 commit comments

Comments
 (0)