|
5 | 5 | import tempfile
|
6 | 6 | import time
|
7 | 7 |
|
| 8 | +from .exc import WaitTimeout |
| 9 | + |
8 | 10 | logger = logging.getLogger(__name__)
|
9 | 11 |
|
10 | 12 | TEST_SESSION_PREFIX = "libtmux_"
|
11 | 13 | RETRY_TIMEOUT_SECONDS = int(os.getenv("RETRY_TIMEOUT_SECONDS", 8))
|
| 14 | +RETRY_INTERVAL_SECONDS = float(os.getenv("RETRY_INTERVAL_SECONDS", 0.05)) |
12 | 15 |
|
13 | 16 | namer = tempfile._RandomNameSequence()
|
14 | 17 | current_dir = os.path.abspath(os.path.dirname(__file__))
|
@@ -43,6 +46,52 @@ def retry(seconds=RETRY_TIMEOUT_SECONDS):
|
43 | 46 | return (lambda: time.time() < time.time() + seconds)()
|
44 | 47 |
|
45 | 48 |
|
| 49 | +def retry_until( |
| 50 | + fun, |
| 51 | + seconds=RETRY_TIMEOUT_SECONDS, |
| 52 | + *, |
| 53 | + interval=RETRY_INTERVAL_SECONDS, |
| 54 | + raises=True, |
| 55 | +): |
| 56 | + """ |
| 57 | + Retry a function until a condition meets or the specified time passes. |
| 58 | +
|
| 59 | + Parameters |
| 60 | + ---------- |
| 61 | + fun : callable |
| 62 | + A function that will be called repeatedly until it returns ``True`` or |
| 63 | + the specified time passes. |
| 64 | + seconds : int |
| 65 | + Seconds to retry. Defaults to ``8``, which is configurable via |
| 66 | + ``RETRY_TIMEOUT_SECONDS`` environment variables. |
| 67 | + interval : float |
| 68 | + Time in seconds to wait between calls. Defaults to ``0.05`` and is |
| 69 | + configurable via ``RETRY_INTERVAL_SECONDS`` environment variable. |
| 70 | + raises : bool |
| 71 | + Wether or not to raise an exception on timeout. Defaults to ``True``. |
| 72 | +
|
| 73 | + Examples |
| 74 | + -------- |
| 75 | +
|
| 76 | + >>> def f(): |
| 77 | + ... p = w.attached_pane |
| 78 | + ... p.server._update_panes() |
| 79 | + ... return p.current_path == pane_path |
| 80 | + ... |
| 81 | + ... retry(f) |
| 82 | + """ |
| 83 | + ini = time.time() |
| 84 | + |
| 85 | + while not fun(): |
| 86 | + end = time.time() |
| 87 | + if end - ini >= seconds: |
| 88 | + if raises: |
| 89 | + raise WaitTimeout() |
| 90 | + else: |
| 91 | + break |
| 92 | + time.sleep(interval) |
| 93 | + |
| 94 | + |
46 | 95 | def get_test_session_name(server, prefix=TEST_SESSION_PREFIX):
|
47 | 96 | """
|
48 | 97 | Faker to create a session name that doesn't exist.
|
|
0 commit comments