Skip to content

Commit 939e91a

Browse files
authored
test: unify polling waits behind a single poll_until_condition helper (#1926)
Unifies eventually-consistent / settling waits across the test suite behind a single `poll_until_condition` helper, matching the form shared with apify/apify-client-python#844. ## Changes - **Single helper.** Replace `wait_for_condition` with `poll_until_condition` (`tests/_utils.py`): it polls a sync-or-async callable until an optional `condition` holds (default: truthy) or a wall-clock `timeout` expires, then returns the last result so the caller asserts explicitly. Exponential backoff is folded into a `backoff_factor` argument instead of a separate `call_with_exp_backoff`. - **Shared location + relative imports.** Move the helper from `tests/unit/utils.py` to the shared `tests/_utils.py` and import it relatively. This requires the test tree to be a proper package, so add `__init__.py` to the `tests/unit` and `tests/e2e` subpackages that lacked one (and allow `TID252` in tests). - **Migrate hand-rolled waits.** Replace fixed `sleep`s and `for`/`while` polling loops with the helper: - 5 autoscaling waits — `test_autoscaled_pool.py` - statistics-initialization loop — `test_basic_crawler.py` - 2 sitemap-loader waits — `test_sitemap_request_loader.py` - 2 request-queue background-task waits — `test_request_queue.py` Lint, type-check, and the full unit suite (1883 passed) pass.
1 parent da3c89f commit 939e91a

5 files changed

Lines changed: 76 additions & 44 deletions

File tree

‎tests/unit/_autoscaling/test_autoscaled_pool.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from crawlee._autoscaling._types import LoadRatioInfo, SystemInfo
1616
from crawlee._types import ConcurrencySettings
1717
from crawlee._utils.time import measure_time
18-
from tests.unit.utils import wait_for_condition
18+
from tests.unit.utils import poll_until_condition
1919

2020
if TYPE_CHECKING:
2121
from collections.abc import Awaitable
@@ -192,20 +192,20 @@ def get_historical_system_info() -> SystemInfo:
192192

193193
try:
194194
# Wait until concurrency scales up above 1.
195-
await wait_for_condition(lambda: pool.desired_concurrency > 1, timeout=5.0)
195+
assert await poll_until_condition(lambda: pool.desired_concurrency > 1, timeout=5.0)
196196

197197
# Wait until concurrency reaches maximum.
198-
await wait_for_condition(lambda: pool.desired_concurrency == 4, timeout=5.0)
198+
assert await poll_until_condition(lambda: pool.desired_concurrency == 4, timeout=5.0)
199199

200200
# Multiple concurrent workers should have completed more tasks than a single worker could.
201-
await wait_for_condition(lambda: done_count > 10, timeout=5.0)
201+
assert await poll_until_condition(lambda: done_count > 10, timeout=5.0)
202202

203203
# Simulate CPU overload and wait for the pool to scale down.
204204
overload_active = True
205-
await wait_for_condition(lambda: pool.desired_concurrency < 4, timeout=5.0)
205+
assert await poll_until_condition(lambda: pool.desired_concurrency < 4, timeout=5.0)
206206

207207
# Wait until the pool scales all the way down to minimum.
208-
await wait_for_condition(lambda: pool.desired_concurrency == 1, timeout=5.0)
208+
assert await poll_until_condition(lambda: pool.desired_concurrency == 1, timeout=5.0)
209209
finally:
210210
pool_run_task.cancel()
211211
with suppress(asyncio.CancelledError):

‎tests/unit/crawlers/_basic/test_basic_crawler.py‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from crawlee.statistics import FinalStatistics, StatisticsState
3333
from crawlee.storage_clients import FileSystemStorageClient, MemoryStorageClient
3434
from crawlee.storages import Dataset, KeyValueStore, RequestQueue
35+
from tests.unit.utils import poll_until_condition
3536

3637
if TYPE_CHECKING:
3738
from collections.abc import Callable, Sequence
@@ -1988,17 +1989,13 @@ async def test_crawler_intermediate_statistics() -> None:
19881989
crawler = BasicCrawler()
19891990
check_time = timedelta(seconds=0.1)
19901991

1991-
async def wait_for_statistics_initialization() -> None:
1992-
while not crawler.statistics.active: # noqa: ASYNC110 # It is ok for tests.
1993-
await asyncio.sleep(0.1)
1994-
19951992
@crawler.router.default_handler
19961993
async def handler(_: BasicCrawlingContext) -> None:
19971994
await asyncio.sleep(check_time.total_seconds() * 5)
19981995

19991996
# Start crawler and wait until statistics are initialized.
20001997
crawler_task = asyncio.create_task(crawler.run(['https://a.placeholder.com']))
2001-
await wait_for_statistics_initialization()
1998+
assert await poll_until_condition(lambda: crawler.statistics.active)
20021999

20032000
# Wait some time and check that runtime is updated.
20042001
await asyncio.sleep(check_time.total_seconds())

‎tests/unit/request_loaders/test_sitemap_request_loader.py‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import asyncio
21
import base64
32
import gzip
43
from typing import TYPE_CHECKING
@@ -10,6 +9,7 @@
109
from crawlee.http_clients._base import HttpClient
1110
from crawlee.request_loaders._sitemap_request_loader import SitemapRequestLoader
1211
from crawlee.storages import KeyValueStore
12+
from tests.unit.utils import poll_until_condition
1313

1414
if TYPE_CHECKING:
1515
from crawlee._types import JsonSerializable
@@ -91,9 +91,7 @@ async def test_is_empty_does_not_depend_on_fetch_next_request(server_url: URL, h
9191

9292
assert await sitemap_loader.is_empty()
9393

94-
await asyncio.sleep(0.1)
95-
96-
assert await sitemap_loader.is_finished()
94+
assert await poll_until_condition(sitemap_loader.is_finished)
9795

9896

9997
async def test_abort_sitemap_loading(server_url: URL, http_client: HttpClient) -> None:
@@ -139,18 +137,14 @@ async def test_create_persist_state_for_sitemap_loading(
139137
async def test_data_persistence_for_sitemap_loading(
140138
server_url: URL, http_client: HttpClient, key_value_store: KeyValueStore
141139
) -> None:
142-
async def wait_for_sitemap_loader_not_empty(sitemap_loader: SitemapRequestLoader) -> None:
143-
while await sitemap_loader.is_empty() and not await sitemap_loader.is_finished(): # noqa: ASYNC110
144-
await asyncio.sleep(0.1)
145-
146140
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
147141
persist_key = 'data_persist_state'
148142
sitemap_loader = SitemapRequestLoader(
149143
[str(sitemap_url)], http_client=http_client, persist_state_key=persist_key, enqueue_strategy='all'
150144
)
151145

152-
# Give time to load
153-
await asyncio.wait_for(wait_for_sitemap_loader_not_empty(sitemap_loader), timeout=10)
146+
# Give time to load.
147+
await poll_until_condition(sitemap_loader.is_empty, lambda is_empty: not is_empty, timeout=10)
154148

155149
await sitemap_loader.close()
156150

‎tests/unit/storages/test_request_queue.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from crawlee.storage_clients.models import AddRequestsResponse, ProcessedRequest, UnprocessedRequest
1313
from crawlee.storages import RequestQueue
1414
from crawlee.storages._storage_instance_manager import StorageInstanceManager
15+
from tests.unit.utils import poll_until_condition
1516

1617
if TYPE_CHECKING:
1718
from collections.abc import AsyncGenerator, Sequence
@@ -516,9 +517,8 @@ async def test_add_requests_wait_for_all(
516517
# Immediately after adding, the total count may be less than 15 due to background processing
517518
assert await rq.get_total_count() <= 15
518519

519-
# Wait for background tasks to complete
520-
while await rq.get_total_count() < 15: # noqa: ASYNC110
521-
await asyncio.sleep(0.1)
520+
# Wait for background tasks to complete.
521+
await poll_until_condition(rq.get_total_count, lambda count: count >= 15)
522522

523523
# Verify all requests were added
524524
assert await rq.get_total_count() == 15
@@ -542,8 +542,8 @@ async def test_is_finished(rq: RequestQueue) -> None:
542542
# Queue shouldn't be finished while background tasks are running
543543
assert await rq.is_finished() is False
544544

545-
# Wait for background tasks to finish
546-
await asyncio.sleep(0.2)
545+
# Wait for the background add task to finish.
546+
await poll_until_condition(lambda: not rq._add_requests_tasks)
547547

548548
# Process all requests
549549
while True:

‎tests/unit/utils.py‎

Lines changed: 59 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,75 @@
11
from __future__ import annotations
22

33
import asyncio
4+
import inspect
45
import sys
5-
from typing import TYPE_CHECKING
6+
import time
7+
from typing import TYPE_CHECKING, TypeVar, cast, overload
68

79
import pytest
810

911
if TYPE_CHECKING:
10-
from collections.abc import Callable
12+
from collections.abc import Awaitable, Callable
13+
14+
T = TypeVar('T')
1115

1216
run_alone_on_mac = pytest.mark.run_alone if sys.platform == 'darwin' else lambda x: x
1317

1418

15-
async def wait_for_condition(
16-
condition: Callable[[], bool],
19+
async def maybe_await(value: Awaitable[T] | T) -> T:
20+
"""Await `value` if it is awaitable, otherwise return it unchanged.
21+
22+
Lets `poll_until_condition` accept both sync and async callables.
23+
"""
24+
if inspect.isawaitable(value):
25+
return await cast('Awaitable[T]', value)
26+
return cast('T', value)
27+
28+
29+
@overload
30+
async def poll_until_condition(
31+
fn: Callable[[], Awaitable[T]],
32+
condition: Callable[[T], bool] = ...,
33+
*,
34+
timeout: float = ...,
35+
poll_interval: float = ...,
36+
backoff_factor: float = ...,
37+
) -> T: ...
38+
@overload
39+
async def poll_until_condition(
40+
fn: Callable[[], T],
41+
condition: Callable[[T], bool] = ...,
1742
*,
18-
timeout: float = 5.0,
43+
timeout: float = ...,
44+
poll_interval: float = ...,
45+
backoff_factor: float = ...,
46+
) -> T: ...
47+
async def poll_until_condition(
48+
fn: Callable[[], Awaitable[T] | T],
49+
condition: Callable[[T], bool] = bool,
50+
*,
51+
timeout: float = 5,
1952
poll_interval: float = 0.05,
20-
) -> None:
21-
"""Poll `condition` until it returns True, or raise `AssertionError` on timeout.
53+
backoff_factor: float = 1,
54+
) -> T:
55+
"""Poll `fn` until `condition(result)` is True or the timeout expires.
56+
57+
Polls `fn` at `poll_interval`-second intervals until `condition` is satisfied or `timeout` seconds have elapsed.
58+
Returns the last polled result regardless of whether the condition was met, so the caller can run its own
59+
assertion. The default condition checks for a truthy result.
2260
23-
Args:
24-
condition: A callable that returns True when the desired state is reached.
25-
timeout: Maximum time in seconds to wait before raising.
26-
poll_interval: Time in seconds between condition checks.
61+
Use this instead of a fixed `asyncio.sleep` when waiting for some state to settle (e.g. autoscaling
62+
concurrency) that may take a variable amount of time. For highly variable waits, pass `backoff_factor` > 1
63+
to multiply the interval after each poll, covering a long timeout with few calls.
2764
"""
28-
loop = asyncio.get_running_loop()
29-
deadline = loop.time() + timeout
30-
while loop.time() < deadline:
31-
if condition():
32-
return
33-
await asyncio.sleep(poll_interval)
34-
raise AssertionError(f'Condition not met within {timeout}s')
65+
deadline = time.monotonic() + timeout
66+
delay = poll_interval
67+
result = await maybe_await(fn())
68+
while not condition(result):
69+
remaining = deadline - time.monotonic()
70+
if remaining <= 0:
71+
break
72+
await asyncio.sleep(min(delay, remaining))
73+
delay *= backoff_factor
74+
result = await maybe_await(fn())
75+
return result

0 commit comments

Comments
 (0)