| 1 |
import time |
| 2 |
from math import inf |
| 3 |
|
| 4 |
from .. import _core |
| 5 |
from .._abc import Clock |
| 6 |
from .._util import final |
| 7 |
from ._run import GLOBAL_RUN_CONTEXT |
| 8 |
|
| 9 |
################################################################ |
| 10 |
# The glorious MockClock |
| 11 |
################################################################ |
| 12 |
|
| 13 |
|
| 14 |
# Prior art: |
| 15 |
# https://twistedmatrix.com/documents/current/api/twisted.internet.task.Clock.html |
| 16 |
# https://github.com/ztellman/manifold/issues/57 |
| 17 |
@final |
| 18 |
class MockClock(Clock): |
| 19 |
"""A user-controllable clock suitable for writing tests. |
| 20 |
|
| 21 |
Args: |
| 22 |
rate (float): the initial :attr:`rate`. |
| 23 |
autojump_threshold (float): the initial :attr:`autojump_threshold`. |
| 24 |
|
| 25 |
.. attribute:: rate |
| 26 |
|
| 27 |
How many seconds of clock time pass per second of real time. Default is |
| 28 |
0.0, i.e. the clock only advances through manuals calls to :meth:`jump` |
| 29 |
or when the :attr:`autojump_threshold` is triggered. You can assign to |
| 30 |
this attribute to change it. |
| 31 |
|
| 32 |
.. attribute:: autojump_threshold |
| 33 |
|
| 34 |
The clock keeps an eye on the run loop, and if at any point it detects |
| 35 |
that all tasks have been blocked for this many real seconds (i.e., |
| 36 |
according to the actual clock, not this clock), then the clock |
| 37 |
automatically jumps ahead to the run loop's next scheduled |
| 38 |
timeout. Default is :data:`math.inf`, i.e., to never autojump. You can |
| 39 |
assign to this attribute to change it. |
| 40 |
|
| 41 |
Basically the idea is that if you have code or tests that use sleeps |
| 42 |
and timeouts, you can use this to make it run much faster, totally |
| 43 |
automatically. (At least, as long as those sleeps/timeouts are |
| 44 |
happening inside Trio; if your test involves talking to external |
| 45 |
service and waiting for it to timeout then obviously we can't help you |
| 46 |
there.) |
| 47 |
|
| 48 |
You should set this to the smallest value that lets you reliably avoid |
| 49 |
"false alarms" where some I/O is in flight (e.g. between two halves of |
| 50 |
a socketpair) but the threshold gets triggered and time gets advanced |
| 51 |
anyway. This will depend on the details of your tests and test |
| 52 |
environment. If you aren't doing any I/O (like in our sleeping example |
| 53 |
above) then just set it to zero, and the clock will jump whenever all |
| 54 |
tasks are blocked. |
| 55 |
|
| 56 |
.. note:: If you use ``autojump_threshold`` and |
| 57 |
`wait_all_tasks_blocked` at the same time, then you might wonder how |
| 58 |
they interact, since they both cause things to happen after the run |
| 59 |
loop goes idle for some time. The answer is: |
| 60 |
`wait_all_tasks_blocked` takes priority. If there's a task blocked |
| 61 |
in `wait_all_tasks_blocked`, then the autojump feature treats that |
| 62 |
as active task and does *not* jump the clock. |
| 63 |
|
| 64 |
""" |
| 65 |
|
| 66 |
def __init__(self, rate: float = 0.0, autojump_threshold: float = inf) -> None: |
| 67 |
# when the real clock said 'real_base', the virtual time was |
| 68 |
# 'virtual_base', and since then it's advanced at 'rate' virtual |
| 69 |
# seconds per real second. |
| 70 |
self._real_base = 0.0 |
| 71 |
self._virtual_base = 0.0 |
| 72 |
self._rate = 0.0 |
| 73 |
|
| 74 |
# kept as an attribute so that our tests can monkeypatch it |
| 75 |
self._real_clock = time.perf_counter |
| 76 |
|
| 77 |
# use the property update logic to set initial values |
| 78 |
self.rate = rate |
| 79 |
self.autojump_threshold = autojump_threshold |
| 80 |
|
| 81 |
def __repr__(self) -> str: |
| 82 |
return f"<MockClock, time={self.current_time():.7f}, rate={self._rate} @ {id(self):#x}>" |
| 83 |
|
| 84 |
@property |
| 85 |
def rate(self) -> float: |
| 86 |
return self._rate |
| 87 |
|
| 88 |
@rate.setter |
| 89 |
def rate(self, new_rate: float) -> None: |
| 90 |
if new_rate < 0: |
| 91 |
raise ValueError("rate must be >= 0") |
| 92 |
else: |
| 93 |
real = self._real_clock() |
| 94 |
virtual = self._real_to_virtual(real) |
| 95 |
self._virtual_base = virtual |
| 96 |
self._real_base = real |
| 97 |
self._rate = float(new_rate) |
| 98 |
|
| 99 |
@property |
| 100 |
def autojump_threshold(self) -> float: |
| 101 |
return self._autojump_threshold |
| 102 |
|
| 103 |
@autojump_threshold.setter |
| 104 |
def autojump_threshold(self, new_autojump_threshold: float) -> None: |
| 105 |
self._autojump_threshold = float(new_autojump_threshold) |
| 106 |
self._try_resync_autojump_threshold() |
| 107 |
|
| 108 |
# runner.clock_autojump_threshold is an internal API that isn't easily |
| 109 |
# usable by custom third-party Clock objects. If you need access to this |
| 110 |
# functionality, let us know, and we'll figure out how to make a public |
| 111 |
# API. Discussion: |
| 112 |
# |
| 113 |
# https://github.com/python-trio/trio/issues/1587 |
| 114 |
def _try_resync_autojump_threshold(self) -> None: |
| 115 |
try: |
| 116 |
runner = GLOBAL_RUN_CONTEXT.runner |
| 117 |
if runner.is_guest: |
| 118 |
runner.force_guest_tick_asap() |
| 119 |
except AttributeError: |
| 120 |
pass |
| 121 |
else: |
| 122 |
if runner.clock is self: |
| 123 |
runner.clock_autojump_threshold = self._autojump_threshold |
| 124 |
|
| 125 |
# Invoked by the run loop when runner.clock_autojump_threshold is |
| 126 |
# exceeded. |
| 127 |
def _autojump(self) -> None: |
| 128 |
statistics = _core.current_statistics() |
| 129 |
jump = statistics.seconds_to_next_deadline |
| 130 |
if 0 < jump < inf: |
| 131 |
self.jump(jump) |
| 132 |
|
| 133 |
def _real_to_virtual(self, real: float) -> float: |
| 134 |
real_offset = real - self._real_base |
| 135 |
virtual_offset = self._rate * real_offset |
| 136 |
return self._virtual_base + virtual_offset |
| 137 |
|
| 138 |
def start_clock(self) -> None: |
| 139 |
self._try_resync_autojump_threshold() |
| 140 |
|
| 141 |
def current_time(self) -> float: |
| 142 |
return self._real_to_virtual(self._real_clock()) |
| 143 |
|
| 144 |
def deadline_to_sleep_time(self, deadline: float) -> float: |
| 145 |
virtual_timeout = deadline - self.current_time() |
| 146 |
if virtual_timeout <= 0: |
| 147 |
return 0 |
| 148 |
elif self._rate > 0: |
| 149 |
return virtual_timeout / self._rate |
| 150 |
else: |
| 151 |
return 999999999 |
| 152 |
|
| 153 |
def jump(self, seconds: float) -> None: |
| 154 |
"""Manually advance the clock by the given number of seconds. |
| 155 |
|
| 156 |
Args: |
| 157 |
seconds (float): the number of seconds to jump the clock forward. |
| 158 |
|
| 159 |
Raises: |
| 160 |
ValueError: if you try to pass a negative value for ``seconds``. |
| 161 |
|
| 162 |
""" |
| 163 |
if seconds < 0: |
| 164 |
raise ValueError("time can't go backwards") |
| 165 |
self._virtual_base += seconds |