You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.rst
+117Lines changed: 117 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,3 +3,120 @@ pytest-time
3
3
4
4
The pytest-time plugin extends pytest to control ``time`` — the built-in Python
5
5
module, not the concept within the universe.
6
+
7
+
Fixtures
8
+
--------
9
+
10
+
Pytest-time offers several fixtures for use in your projects, depending on your particular needs.
11
+
12
+
Instant Sleep
13
+
~~~~~~~~~~~~~
14
+
15
+
The ``instant_sleep`` fixture is the most basic wrapper and is designed to be used at any scope. It monkeypatches the built-in ``time`` module to be chronologically consistent while not actually sleeping when running ``time.sleep``. This includes modifying the behaviour of ``time.time()``, ``time.monotonic()`` and their nanosecond counterparts to include the additional delay expected after sleeping.
This code will behave almost identically with and without the ``instant_sleep`` fixture in use. To demonstrate, let's time this file with the fixture enabled...
37
+
38
+
.. code:: text
39
+
40
+
$ time pytest test_instant_sleep.py
41
+
=========== test session starts ===========
42
+
platform linux -- Python 3.11.4, pytest-7.3.1, pluggy-1.0.0
=========== 3 passed in 111.01s (0:01:51) ===========
71
+
72
+
real 1m51.354s
73
+
user 0m0.250s
74
+
sys 0m0.020s
75
+
76
+
The sleep is, for practical purposes, essentially instant. And yet, the ``time`` module still acts as though the appropriate time has passed.
77
+
78
+
Recording Time Calls
79
+
~~~~~~~~~~~~~~~~~~~~~
80
+
81
+
Pytest-time also provides ``mock_time``, a fixture that wraps several ``time`` functions in Mock objects but still runs the real calls. This is useful if you need to ensure that certain calls occurred, etc. The fixture will provide Mock objects for inspection in tests:
82
+
83
+
.. code:: python
84
+
:number-lines:
85
+
86
+
import time
87
+
88
+
deftest_mock_time(mock_time):
89
+
start_time = time.time()
90
+
start_monotonic = time.monotonic()
91
+
92
+
time.sleep(1) # Actually sleeps for a second
93
+
94
+
assert time.time() >= start_time +1
95
+
assert time.monotonic() >= start_monotonic +1
96
+
97
+
mock_time.sleep.assert_called_once_with(1)
98
+
assertlen(mock_time.time.mock_calls) ==2
99
+
assertlen(mock_time.monotonic.mock_calls) ==2
100
+
101
+
Mocking a Powernap
102
+
~~~~~~~~~~~~~~~~~~
103
+
104
+
The two above are combined for you in the ``mock_instant_sleep`` fixture. This fixture replaces the relevant ``time`` functions as in the ```instant_sleep`` fixture, but also provides mock wrappers around those functions, allowing for recording time.
0 commit comments