remotivelabs.topology.testing.hamcrest.await_at_most

Hamcrest-specific retry utilities for asynchronous testing.

 1"""
 2# Hamcrest-specific retry utilities for asynchronous testing.
 3"""
 4
 5import inspect
 6from typing import Any, Callable, Protocol, TypeVar
 7
 8from hamcrest import assert_that
 9from hamcrest.core.base_matcher import Matcher
10
11from remotivelabs.topology.testing.retry import retry
12
13T = TypeVar("T")
14
15
16class AwaitAtMost(Protocol):
17    """Protocol for await until functionality."""
18
19    async def until(self, func: Callable[[], Any], matcher: Matcher[Any]) -> None: ...
20
21
22async def _assert_until(func: Callable[[], Any], matcher: Matcher, timeout: float = 10) -> None:
23    if not callable(func):
24        raise TypeError(f"Arguments used in assert_until(Callable, ...) must be of type Callable, was {type(func)}")
25
26    async def operation():
27        result = func()
28        if inspect.isawaitable(result):
29            result = await result
30        assert_that(result, matcher)
31        return result
32
33    try:
34        await retry(operation=operation, timeout=timeout)
35    except TimeoutError as e:
36        raise AssertionError(f"Condition not satisfied within {timeout}s for function {func} and matcher {matcher}") from e
37
38
39def await_at_most(seconds: float) -> AwaitAtMost:
40    """
41    Creates a chainable assertion helper that retries until a hamcrest matcher is satisfied or timeout.
42
43    Provides a fluent syntax for asynchronous polling assertions. Retries calling a function
44    until its result matches the hamcrest matcher or the timeout is reached.
45
46    Args:
47        seconds: The maximum duration to wait before giving up, in seconds.
48
49    Example:
50        ```python
51        from hamcrest import equal_to, greater_than
52
53        async def test_polling():
54            counter = {"value": 0}
55
56            async def increment():
57                counter["value"] += 1
58                return counter["value"]
59
60            # Wait up to 5 seconds for counter to reach 10
61            await await_at_most(5).until(lambda: counter["value"], equal_to(10))
62
63            # Works with async functions too
64            await await_at_most(2).until(increment, greater_than(5))
65        ```
66
67    Raises:
68        TimeoutError: If the matcher condition is not satisfied within the timeout.
69    """
70
71    class _AwaitAtMostImpl:
72        async def until(self, func: Callable[[], Any], matcher: Matcher) -> None:
73            try:
74                await _assert_until(func, matcher, timeout=seconds)
75            except AssertionError as e:
76                raise TimeoutError from e
77
78    return _AwaitAtMostImpl()
class AwaitAtMost(typing.Protocol):
17class AwaitAtMost(Protocol):
18    """Protocol for await until functionality."""
19
20    async def until(self, func: Callable[[], Any], matcher: Matcher[Any]) -> None: ...

Protocol for await until functionality.

AwaitAtMost(*args, **kwargs)
1945def _no_init_or_replace_init(self, *args, **kwargs):
1946    cls = type(self)
1947
1948    if cls._is_protocol:
1949        raise TypeError('Protocols cannot be instantiated')
1950
1951    # Already using a custom `__init__`. No need to calculate correct
1952    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1953    if cls.__init__ is not _no_init_or_replace_init:
1954        return
1955
1956    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1957    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1958    # searches for a proper new `__init__` in the MRO. The new `__init__`
1959    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1960    # instantiation of the protocol subclass will thus use the new
1961    # `__init__` and no longer call `_no_init_or_replace_init`.
1962    for base in cls.__mro__:
1963        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1964        if init is not _no_init_or_replace_init:
1965            cls.__init__ = init
1966            break
1967    else:
1968        # should not happen
1969        cls.__init__ = object.__init__
1970
1971    cls.__init__(self, *args, **kwargs)
async def until( self, func: Callable[[], Any], matcher: hamcrest.core.matcher.Matcher[typing.Any]) -> None:
20    async def until(self, func: Callable[[], Any], matcher: Matcher[Any]) -> None: ...
def await_at_most( seconds: float) -> AwaitAtMost:
40def await_at_most(seconds: float) -> AwaitAtMost:
41    """
42    Creates a chainable assertion helper that retries until a hamcrest matcher is satisfied or timeout.
43
44    Provides a fluent syntax for asynchronous polling assertions. Retries calling a function
45    until its result matches the hamcrest matcher or the timeout is reached.
46
47    Args:
48        seconds: The maximum duration to wait before giving up, in seconds.
49
50    Example:
51        ```python
52        from hamcrest import equal_to, greater_than
53
54        async def test_polling():
55            counter = {"value": 0}
56
57            async def increment():
58                counter["value"] += 1
59                return counter["value"]
60
61            # Wait up to 5 seconds for counter to reach 10
62            await await_at_most(5).until(lambda: counter["value"], equal_to(10))
63
64            # Works with async functions too
65            await await_at_most(2).until(increment, greater_than(5))
66        ```
67
68    Raises:
69        TimeoutError: If the matcher condition is not satisfied within the timeout.
70    """
71
72    class _AwaitAtMostImpl:
73        async def until(self, func: Callable[[], Any], matcher: Matcher) -> None:
74            try:
75                await _assert_until(func, matcher, timeout=seconds)
76            except AssertionError as e:
77                raise TimeoutError from e
78
79    return _AwaitAtMostImpl()

Creates a chainable assertion helper that retries until a hamcrest matcher is satisfied or timeout.

Provides a fluent syntax for asynchronous polling assertions. Retries calling a function until its result matches the hamcrest matcher or the timeout is reached.

Arguments:
  • seconds: The maximum duration to wait before giving up, in seconds.
Example:
from hamcrest import equal_to, greater_than

async def test_polling():
    counter = {"value": 0}

    async def increment():
        counter["value"] += 1
        return counter["value"]

    # Wait up to 5 seconds for counter to reach 10
    await await_at_most(5).until(lambda: counter["value"], equal_to(10))

    # Works with async functions too
    await await_at_most(2).until(increment, greater_than(5))
Raises:
  • TimeoutError: If the matcher condition is not satisfied within the timeout.