diff --git a/looptime/plugin.py b/looptime/plugin.py index 6b6405a..c2ca31f 100644 --- a/looptime/plugin.py +++ b/looptime/plugin.py @@ -5,15 +5,33 @@ import pytest -from looptime import loops, patchers +from looptime import loops, patchers, timeproxies -@pytest.hookimpl(hookwrapper=True) +@pytest.fixture() +def looptime() -> timeproxies.LoopTimeProxy: + return timeproxies.LoopTimeProxy() + + +def pytest_configure(config: Any) -> None: + config.addinivalue_line('markers', "looptime: configure the fake fast-forwarding loop time.") + + +def pytest_addoption(parser: Any) -> None: + group = parser.getgroup("asyncio time contraction") + group.addoption("--no-looptime", dest='looptime', action="store_const", const=False, + help="Force all (even marked) tests to the true loop time.") + group.addoption("--looptime", dest='looptime', action="store_const", const=True, + help="Run unmarked tests with the fake loop time by default.") + + +@pytest.hookimpl(wrapper=True) def pytest_fixture_setup(fixturedef: Any, request: Any) -> Any: + result = yield + if fixturedef.argname == "event_loop": - result = yield - loop = cast(asyncio.BaseEventLoop, result.get_result()) if result.excinfo is None else None - if loop is not None and not isinstance(loop, loops.LoopTimeEventLoop): + loop = cast(asyncio.BaseEventLoop, result) + if not isinstance(loop, loops.LoopTimeEventLoop): # True means implicitly on; False means explicitly off; None means "only if marked". option: bool | None = request.config.getoption('looptime') @@ -28,18 +46,6 @@ def pytest_fixture_setup(fixturedef: Any, request: Any) -> Any: if enabled: patched_loop = patchers.patch_event_loop(loop) patched_loop.setup_looptime(**options) - result.force_result(patched_loop) - else: - yield - - -def pytest_configure(config: Any) -> None: - config.addinivalue_line('markers', "looptime: configure the fake fast-forwarding loop time.") - + result = patched_loop -def pytest_addoption(parser: Any) -> None: - group = parser.getgroup("asyncio time contraction") - group.addoption("--no-looptime", dest='looptime', action="store_const", const=False, - help="Force all (even marked) tests to the true loop time.") - group.addoption("--looptime", dest='looptime', action="store_const", const=True, - help="Run unmarked tests with the fake loop time by default.") + return result diff --git a/looptime/timeproxies.py b/looptime/timeproxies.py index 7886df2..e4662b5 100644 --- a/looptime/timeproxies.py +++ b/looptime/timeproxies.py @@ -31,13 +31,3 @@ def __matmul__(self, other: object) -> LoopTimeProxy: @property def _value(self) -> float: return self._loop.time() if self._loop is not None else asyncio.get_running_loop().time() - - -try: - import pytest -except ImportError: - pass -else: - @pytest.fixture() - def looptime() -> LoopTimeProxy: - return LoopTimeProxy()