feat: background poller

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Sonnet 5.5 committed 2026-10-22 13:18:00 +02:00
1 parent 36e01c4b1c
commit 839c1824a9
2 files changed
+165

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
import threading
import time
from poller import Poller
class FakeClock:
def __init__(self):
self.now = 1000.0
def __call__(self):
return self.now
def flaky(results):
"""fetch() returning each item of `results` in turn; an Exception item is raised."""
items = iter(results)
def fetch():
item = next(items)
if isinstance(item, Exception):
raise item
return item
return fetch
def test_success_stores_value_and_bumps_version():
p = Poller(flaky(["a"]), interval=10)
assert p.poll_once() is True
assert (p.value, p.version, p.failures) == ("a", 1, 0)
def test_failure_keeps_last_good_value_and_counts():
p = Poller(flaky(["a", RuntimeError("boom")]), interval=10)
p.poll_once()
assert p.poll_once() is False
assert (p.value, p.version, p.failures) == ("a", 1, 1)
def test_success_resets_failures():
p = Poller(flaky([RuntimeError("x"), RuntimeError("y"), "b"]), interval=10)
p.poll_once()
p.poll_once()
assert p.failures == 2
p.poll_once()
assert (p.value, p.failures) == ("b", 0)
def test_age_uses_injected_clock():
clock = FakeClock()
p = Poller(flaky(["a"]), interval=10, clock=clock)
p.poll_once()
clock.now += 90
assert p.age() == 90
def test_age_none_before_first_success():
p = Poller(flaky([RuntimeError("x")]), interval=10)
assert p.age() is None
p.poll_once()
assert p.age() is None
def test_slow_fetch_does_not_block_reader():
release = threading.Event()
def slow():
release.wait(5)
return "late"
p = Poller(slow, interval=60)
p.start()
try:
assert p.value is None # returns immediately although fetch is blocked
release.set()
deadline = time.monotonic() + 5
while p.version == 0 and time.monotonic() < deadline:
time.sleep(0.01)
assert (p.value, p.version) == ("late", 1)
finally:
release.set()
p.stop()