Debian Codegraph @

tests/waiting.py

raw
1 """Every wait the tests do, bounded and in one place.
2
3 `wait_until` polls state another thread or process sets; the `wait_for_*`
4 coroutines poll state the app sets, pumping its messages as they go. `settle`
5 is the only duration: establishing that nothing *else* happens takes one.
6 """
7
8 from __future__ import annotations
9
10 import random
11 import socket
12 import time
13 from typing import TYPE_CHECKING, Callable, Sequence, TypeVar, Union
14
15 if TYPE_CHECKING:
16 from textual.message import Message
17 from textual.pilot import Pilot
18
19 T = TypeVar("T")
20 MessageT = TypeVar("MessageT", bound="Message")
21
22 Description = Union[str, Callable[[], str]]
23 """What a wait was for. A callable is resolved at the raise, so it can report
24 the state the wait gave up on rather than the state it started from."""
25
26 TIMEOUT = 10.0
27 """Seconds any one wait may take before the test has failed."""
28
29 POLL_INTERVAL = 0.02
30 """Seconds between polls of something this thread cannot await."""
31
32 SETTLE_SECONDS = 0.3
33 """How long "and then nothing else happened" takes to establish."""
34
35
36 def _timed_out(seconds: float, description: Description) -> AssertionError:
37 resolved = description() if callable(description) else description
38 return AssertionError(f"timed out after {seconds}s waiting for {resolved}")
39
40
41 def wait_until(
42 predicate: Callable[[], bool], *, description: Description, seconds: float = TIMEOUT
43 ) -> None:
44 """Poll until something another thread or process does becomes true."""
45 deadline = time.monotonic() + seconds
46 while time.monotonic() < deadline:
47 if predicate():
48 return
49 time.sleep(POLL_INTERVAL)
50 if not predicate():
51 raise _timed_out(seconds, description)
52
53
54 def settle(seconds: float = SETTLE_SECONDS) -> None:
55 """Give whatever must not happen time to happen, before asserting it did not."""
56 time.sleep(seconds)
57
58
59 async def settle_app(pilot: Pilot, seconds: float = SETTLE_SECONDS) -> None:
60 """`settle`, for an app that is running: a blocking sleep would stop the
61 loop the thing that must not happen would have to happen on."""
62 deadline = time.monotonic() + seconds
63 while time.monotonic() < deadline:
64 await pilot.pause(POLL_INTERVAL)
65
66
67 async def wait_for(
68 pilot: Pilot,
69 predicate: Callable[[], bool],
70 *,
71 description: Description,
72 seconds: float = TIMEOUT,
73 interval: float | None = None,
74 ) -> None:
75 """Pump the app until `predicate` holds, or fail saying what never happened.
76
77 `interval` is for a condition a thread sets, where a blocking sleep would
78 stop the app's own loop; the default hands the loop back until it is idle.
79 """
80 deadline = time.monotonic() + seconds
81 while True:
82 if predicate():
83 return
84 if time.monotonic() >= deadline:
85 raise _timed_out(seconds, description)
86 await pilot.pause(interval)
87
88
89 async def wait_for_value(
90 pilot: Pilot,
91 get: Callable[[], T | None],
92 *,
93 description: Description,
94 seconds: float = TIMEOUT,
95 interval: float | None = None,
96 ) -> T:
97 """The value `get` returns once it is not None, pumping the app until it is."""
98 value: T | None = None
99
100 def arrived() -> bool:
101 nonlocal value
102 value = get()
103 return value is not None
104
105 await wait_for(
106 pilot, arrived, description=description, seconds=seconds, interval=interval
107 )
108 assert value is not None
109 return value
110
111
112 async def wait_for_messages(
113 pilot: Pilot,
114 messages: Sequence[Message],
115 message_type: type[MessageT],
116 *,
117 count: int = 1,
118 exactly: bool = False,
119 seconds: float = TIMEOUT,
120 ) -> list[MessageT]:
121 """The first `count` messages of a type a `message_hook` has collected.
122
123 `exactly` also asserts there is no `count + 1`th, which is what a test
124 proving one keypress ran one query and not two is asserting.
125 """
126
127 def collected() -> list[MessageT]:
128 return [m for m in messages if isinstance(m, message_type)]
129
130 await wait_for(
131 pilot,
132 lambda: len(collected()) >= count,
133 description=lambda: (
134 f"{count} {message_type.__name__} message"
135 f"{'' if count == 1 else 's'}, saw {len(collected())}"
136 ),
137 seconds=seconds,
138 )
139 if exactly:
140 assert len(collected()) == count, (
141 f"expected {count} {message_type.__name__} message"
142 f"{'' if count == 1 else 's'}, got {len(collected())}"
143 )
144 return collected()[:count]
145
146
147 _PORT_RANGE = (20000, 30000)
148 """Where a test's ports come from: below the ephemeral range every supported
149 platform hands out on its own (32768 on Linux, 49152 on macOS and Windows), so
150 only something that asked for a port by number competes for one."""
151
152 _handed_out: set[int] = set()
153 """Ports this process has already named, which it must not name twice."""
154
155 _draw = random.Random()
156 """Seeded from the OS, so two xdist workers walk different candidates."""
157
158
159 def free_port() -> int:
160 """A loopback port nothing is listening on, drawn from below the ephemeral range.
161
162 It can only report a port that was free a moment ago; a caller that hands
163 one to a child has `on_a_free_port`.
164 """
165 low, high = _PORT_RANGE
166 for _ in range(100):
167 port = _draw.randrange(low, high)
168 if port in _handed_out:
169 continue
170 try:
171 with socket.socket() as sock:
172 sock.bind(("127.0.0.1", port))
173 except OSError:
174 continue
175 _handed_out.add(port)
176 return port
177 raise AssertionError(f"no free port between {low} and {high}")
178
179
180 def accepts(port: int, *, timeout: float = 1.0) -> bool:
181 """Whether a loopback port accepts a connection right now."""
182 try:
183 with socket.create_connection(("127.0.0.1", port), timeout=timeout):
184 return True
185 except OSError:
186 return False
187
188
189 def on_a_free_port(
190 start: Callable[[int], T],
191 *,
192 retry_on: Callable[[BaseException], bool],
193 attempts: int = 5,
194 ) -> T:
195 """Call `start` with a free port, retrying while `retry_on` says it lost it.
196
197 `retry_on` reads the exception rather than naming its type, because the one
198 a driver raises for a port it could not take is the one it raises for
199 everything else, and retrying a real failure five times is five timeouts.
200 """
201 for attempt in range(attempts):
202 try:
203 return start(free_port())
204 except BaseException as e:
205 if attempt == attempts - 1 or not retry_on(e):
206 raise
207 raise AssertionError("unreachable")