Skip to content

Commit 4ece0fa

Browse files
committed
refactor: Move logic for test setup from pytest hook to test class.
Compared to performing the same logic in a pytest hook, this approach centralizes the logic for test execution and makes it easier to follow the program flow.
1 parent c68337e commit 4ece0fa

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

pytest_asyncio/plugin.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,20 @@ def loop_scope(self) -> _ScopeName:
457457
default_loop_scope = _get_default_test_loop_scope(self.config)
458458
return _get_marked_loop_scope(marker, default_loop_scope)
459459

460+
def setup(self) -> None:
461+
fixturenames = self.fixturenames
462+
runner_fixture_id = f"_{self.loop_scope}_scoped_runner"
463+
if runner_fixture_id not in fixturenames:
464+
fixturenames.append(runner_fixture_id)
465+
if not getattr(self.obj, "hypothesis", False) and getattr(
466+
self.obj, "is_hypothesis_test", False
467+
):
468+
pytest.fail(
469+
f"test function `{self!r}` is using Hypothesis, but pytest-asyncio "
470+
"only works with Hypothesis 3.64.0 or later."
471+
)
472+
return super().setup()
473+
460474
def runtest(self) -> None:
461475
runner_fixture_id = f"_{self.loop_scope}_scoped_runner"
462476
runner = self._request.getfixturevalue(runner_fixture_id)
@@ -693,24 +707,6 @@ def inner(*args, **kwargs):
693707
return inner
694708

695709

696-
def pytest_runtest_setup(item: pytest.Item) -> None:
697-
marker = item.get_closest_marker("asyncio")
698-
if marker is None or not is_async_test(item):
699-
return
700-
runner_fixture_id = f"_{item.loop_scope}_scoped_runner"
701-
fixturenames = item.fixturenames # type: ignore[attr-defined]
702-
if runner_fixture_id not in fixturenames:
703-
fixturenames.append(runner_fixture_id)
704-
obj = getattr(item, "obj", None)
705-
if not getattr(obj, "hypothesis", False) and getattr(
706-
obj, "is_hypothesis_test", False
707-
):
708-
pytest.fail(
709-
f"test function `{item!r}` is using Hypothesis, but pytest-asyncio "
710-
"only works with Hypothesis 3.64.0 or later."
711-
)
712-
713-
714710
@pytest.hookimpl(wrapper=True)
715711
def pytest_fixture_setup(fixturedef: FixtureDef, request) -> object | None:
716712
asyncio_mode = _get_asyncio_mode(request.config)

0 commit comments

Comments
 (0)