Skip to content

add advance_time fixture and test (closes #83, #95, #96 #110) #113

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

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
add pytest-option '--advance-time-sleep' for configuration
  • Loading branch information
derekbrokeit committed May 23, 2019
commit 9c17c458bb461ed6ef496945d25182aef5a1ef35
23 changes: 17 additions & 6 deletions pytest_asyncio/plugin.py
Original file line number Diff line number Diff line change
@@ -32,6 +32,13 @@ def pytest_configure(config):
"run using an asyncio event loop")


def pytest_addoption(parser):
"""inject commandline option for advance_time"""
parser.addoption(
"--advance-time-sleep", type=float, default=0, help="sleep duration for advance_time fixture",
)


@pytest.mark.tryfirst
def pytest_pycollect_makeitem(collector, name, obj):
"""A pytest hook to collect asyncio coroutines."""
@@ -165,12 +172,15 @@ class EventLoopClockAdvancer:
call is awaited, the caller task will wait an iteration for the update to
wake up any awaiting handlers.
"""
__slots__ = ("offset", "loop", "_base_time",)

def __init__(self, loop):
__slots__ = ("offset", "loop", "sleep_duration", "_base_time")

def __init__(self, loop, sleep_duration=0.0):
breakpoint()
self.offset = 0.0
self._base_time = loop.time
self.loop = loop
self.sleep_duration = sleep_duration

# incorporate offset timing into the event loop
self.loop.time = self.time
@@ -189,15 +199,15 @@ async def __call__(self, seconds):
of time are proceeding.
"""
# sleep so that the loop does everything currently waiting
await asyncio.sleep(0)
await asyncio.sleep(self.sleep_duration)

if seconds > 0:
# advance the clock by the given offset
self.offset += seconds

# Once the clock is adjusted, new tasks may have just been
# scheduled for running in the next pass through the event loop
await asyncio.sleep(0)
await asyncio.sleep(self.sleep_duration)


@pytest.yield_fixture
@@ -239,5 +249,6 @@ def factory():


@pytest.fixture
def advance_time(event_loop):
return EventLoopClockAdvancer(event_loop)
def advance_time(event_loop, request):
sleep_duration = request.config.getoption("--advance-time-sleep")
return EventLoopClockAdvancer(event_loop, sleep_duration)