"""A pytest fixture for making time.sleep instant with proper side effects."""from__future__importannotationsfromtypingimportcastimportpytestfrompytest_timeimportfake_timeclassInstantSleep(fake_time.FakeTime):"""A time faker that makes sleep instant, adjusting time values accordingly. This uses the real system clock, but adjusts the values from ``time`` after each ``sleep`` call. """def__init__(self)->None:super().__init__()self.offset_ns=0defsleep(self,secs:float)->None:"""Fake sleeping by adjusting a time offset."""ifsecs<0:returnself.offset_ns+=round(secs*1_000_000_000)deftime_ns(self)->int:"""Get time.time_ns."""returncast(int,self._time.time_ns()+self.offset_ns)defmonotonic_ns(self)->int:"""Get time.monotonic_ns."""returncast(int,self._time.monotonic_ns()+self.offset_ns)
[docs]@pytest.fixturedefinstant_sleep(monkeypatch:pytest.MonkeyPatch)->InstantSleep:"""Fixture for speeding through time.sleep."""sleep=InstantSleep()sleep.install(monkeypatch)returnsleep