Skip to content

Commit 6fbeb60

Browse files
committed
refactor ClockEventLoop to only advance time but otherwise act as standard loop
improve documentation of ClockEventLoop
1 parent 997afe2 commit 6fbeb60

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

pytest_asyncio/plugin.py

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -161,22 +161,35 @@ def pytest_runtest_setup(item):
161161

162162
class ClockEventLoop(asyncio.new_event_loop().__class__):
163163
"""
164-
A custom event loop that explicitly advances time when requested.
164+
A custom event loop that explicitly advances time when requested. Otherwise,
165+
this event loop advances time as expected.
165166
"""
166-
_now = 0
167+
def __init__(self, *args, **kwargs):
168+
super().__init__(*args, **kwargs)
169+
self._offset = 0
167170

168171
def time(self):
169-
return self._now
170-
171-
def advance_time(self, amount):
172+
"""
173+
Return the time according the event loop's clock.
174+
175+
This time is adjusted by the stored offset that allows for advancement
176+
with `advance_time`.
177+
"""
178+
return super().time() + self._offset
179+
180+
async def advance_time(self, seconds):
181+
'''
182+
Advance time by a given offset in seconds.
183+
'''
184+
if seconds < 0:
185+
raise ValueError('cannot go backwards in time')
172186
# advance the clock and run the loop
173-
self._now += amount
174-
self._run_once()
175-
176-
if amount > 0:
177-
# Once advanced, new tasks may have just been scheduled for running
178-
# in the next loop, advance once more to start these handlers
179-
self._run_once()
187+
self._offset += seconds
188+
# Once advanced, new tasks may have just been scheduled for running
189+
# in the next loop, advance once more to start these handlers
190+
await asyncio.sleep(0)
191+
await asyncio.sleep(0)
192+
await asyncio.sleep(0)
180193

181194

182195
# maps marker to the name of the event loop fixture that will be available

0 commit comments

Comments
 (0)