tests: add function to wait while condition holds

This adds a new utils function that is a slight generalisation
of `wait_for` with an additional condition that must always be
met while waiting.

`wait_for` now calls this new function with the condition being
one that is always true.
This commit is contained in:
jp1ac4 2024-02-08 13:11:25 +00:00
parent f5a15513f2
commit 1e7653e08a
No known key found for this signature in database
GPG Key ID: A7ACD32423568D7B

View File

@ -35,17 +35,33 @@ def wait_for(success, timeout=TIMEOUT, debug_fn=None):
debug_fn is logged at each call to success, it can be useful for debugging
when tests fail.
"""
wait_for_while_condition_holds(success, lambda: True, timeout, debug_fn)
def wait_for_while_condition_holds(success, condition, timeout=TIMEOUT, debug_fn=None):
"""
Run success() either until it returns True, or until the timeout is reached,
as long as condition() holds.
debug_fn is logged at each call to success, it can be useful for debugging
when tests fail.
"""
start_time = time.time()
interval = 0.25
while not success() and time.time() < start_time + timeout:
while True:
if time.time() >= start_time + timeout:
raise ValueError("Error waiting for {}", success)
if not condition():
raise ValueError(
"Condition {} not met while waiting for {}", condition, success
)
if success():
return
if debug_fn is not None:
logging.info(debug_fn())
time.sleep(interval)
interval *= 2
if interval > 5:
interval = 5
if time.time() > start_time + timeout:
raise ValueError("Error waiting for {}", success)
def get_txid(hex_tx):