MCPcopy Create free account
hub / github.com/pytest-dev/pytest / mock_timing

Function mock_timing

testing/conftest.py:182–216  ·  view source on GitHub ↗

Mocks _pytest.timing with a known object that can be used to control timing in tests deterministically. pytest itself should always use functions from `_pytest.timing` instead of `time` directly. This then allows us more control over time during testing, if testing code also uses `

(monkeypatch: MonkeyPatch)

Source from the content-addressed store, hash-verified

180
181@pytest.fixture
182def mock_timing(monkeypatch: MonkeyPatch):
183 """Mocks _pytest.timing with a known object that can be used to control timing in tests
184 deterministically.
185
186 pytest itself should always use functions from `_pytest.timing` instead of `time` directly.
187
188 This then allows us more control over time during testing, if testing code also
189 uses `_pytest.timing` functions.
190
191 Time is static, and only advances through `sleep` calls, thus tests might sleep over large
192 numbers and obtain accurate time() calls at the end, making tests reliable and instant.
193 """
194 import attr
195
196 @attr.s
197 class MockTiming:
198
199 _current_time = attr.ib(default=1590150050.0)
200
201 def sleep(self, seconds):
202 self._current_time += seconds
203
204 def time(self):
205 return self._current_time
206
207 def patch(self):
208 from _pytest import timing
209
210 monkeypatch.setattr(timing, "sleep", self.sleep)
211 monkeypatch.setattr(timing, "time", self.time)
212 monkeypatch.setattr(timing, "perf_counter", self.time)
213
214 result = MockTiming()
215 result.patch()
216 return result

Callers

nothing calls this directly

Calls 2

patchMethod · 0.95
MockTimingClass · 0.85

Tested by

no test coverage detected