Skip to content

Commit 0bfba40

Browse files
openvoiceos-botJarbasAlclaude
authored
fix: let the player asserts wait for the bus instead of reading once (#218)
OCPPlayerHarness.play() emits on the bus and sleeps a fixed 50ms, and assert_player_state then reads self.player.state once. The emit returns immediately and the player transitions on another thread, so the read lands before the transition whenever the box is busy. "Not yet" and "wrong" are different answers and one read cannot tell them apart. Measured in ovos-media-plugin-chromecast at its dev: 4 failures in 12 runs, always test_play_pause_resume_stop_through_ocp, always the first assert after play(). Replacing only that assert with a polling one, through a throwaway conftest and with nothing else changed, took it to 0 in 12. That is what identifies the cause. This adds settle_timeout and one _eventually() helper, and routes the six state asserts through it. It returns as soon as the value matches, so a passing assert costs nothing and the suite does not slow down; on timeout it raises the message it raised before, the time it waited and the deadline it waited to. All six say this, because _eventually appends it once instead of each message spelling it. With this branch installed, chromecast reports 0 failures in 12 runs of the pair and 0 in 12 of the whole directory, with no local conftest. A polling assert that always passed would be worse than the flake, so the control matters: driving the harness with nothing played and asserting PLAYING still fails, after 2.01s, naming the state it actually read. The review of this branch asked for two things, and they are in this commit. First, every test pinned _eventually directly and nothing pinned that the six asserts route through it: reverting assert_player_state to a single read left the new file green. test_five_asserts_wait_the_class_ timeout_before_they_fail now calls each of the six on a player that never transitions, with the class settle_timeout patched small, and asserts on the elapsed time, so a single read fails it. Second, a widened default was not caught: the deadline tests build their own timeout, so settle_timeout = 30.0 passed. The default is now bounded to 0.5s..5.0s, because six asserts share the number and a silent widening turns a two-second answer into a suite that takes minutes to say the same thing. Three mutations, new file run against each: helper loop removed 3 failed, settle_timeout = 30.0 1 failed, assert_player_state single read 1 failed. The last two passed before this commit. The two backend booleans also dropped the value they were handed, so their timeout message could not say what was read. They now name is_playing and is_paused. The time.sleep(0.05) calls in the transport methods are left alone. With the asserts polling they are redundant, but removing them is a wider change to a shared harness and buys 50ms. Co-authored-by: JarbasAi <jarbasai@mailfence.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent a1df882 commit 0bfba40

2 files changed

Lines changed: 229 additions & 22 deletions

File tree

‎ovoscope/media.py‎

Lines changed: 55 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -581,51 +581,84 @@ def simulate_invalid_stream(self) -> None:
581581
# Assertion helpers
582582
# ------------------------------------------------------------------
583583

584+
#: How long an assert waits for the bus to deliver before it fails.
585+
#: The transport calls emit and return; the player changes state on
586+
#: another thread, so "not yet" and "wrong" are different answers and
587+
#: only a deadline tells them apart.
588+
settle_timeout = 2.0
589+
590+
def _eventually(self, read, want, describe):
591+
"""Wait for ``read()`` to equal ``want``, then return.
592+
593+
Returns as soon as it matches, so a passing assert costs nothing.
594+
On timeout raises with the last value read, the time it waited and
595+
the deadline it waited to, so "not yet" reads differently from
596+
"wrong".
597+
"""
598+
started = time.monotonic()
599+
deadline = started + self.settle_timeout
600+
got = read()
601+
while got != want and time.monotonic() < deadline:
602+
time.sleep(0.01)
603+
got = read()
604+
if got != want:
605+
waited = time.monotonic() - started
606+
raise AssertionError(
607+
f"{describe(got)} after {waited:.2f}s "
608+
f"(settle_timeout={self.settle_timeout}s)")
609+
584610
def assert_player_state(self, state: PlayerState) -> None:
585-
"""Assert the player is in the given ``PlayerState``.
611+
"""Assert the player reaches the given ``PlayerState``.
586612
587613
Args:
588614
state: Expected ``PlayerState``.
589615
"""
590-
assert self.player.state == state, (
591-
f"Expected PlayerState.{state.name}, "
592-
f"got PlayerState.{self.player.state.name}"
593-
)
616+
self._eventually(
617+
lambda: self.player.state, state,
618+
lambda got: (f"Expected PlayerState.{state.name}, "
619+
f"got PlayerState.{got.name}"))
594620

595621
def assert_media_state(self, state: MediaState) -> None:
596-
"""Assert the player's media state matches *state*.
622+
"""Assert the player reaches the given ``MediaState``.
597623
598624
Args:
599625
state: Expected ``MediaState``.
600626
"""
601-
assert self.player.media_state == state, (
602-
f"Expected MediaState.{state.name}, "
603-
f"got MediaState.{self.player.media_state.name}"
604-
)
627+
self._eventually(
628+
lambda: self.player.media_state, state,
629+
lambda got: (f"Expected MediaState.{state.name}, "
630+
f"got MediaState.{got.name}"))
605631

606632
def assert_backend_playing(self) -> None:
607-
"""Assert the mock backend is currently playing."""
608-
assert self.backend.is_playing, "Expected backend to be playing"
633+
"""Assert the mock backend reaches playing."""
634+
self._eventually(lambda: bool(self.backend.is_playing), True,
635+
lambda got: f"Expected backend to be playing, "
636+
f"got is_playing={got}")
609637

610638
def assert_backend_paused(self) -> None:
611-
"""Assert the mock backend is currently paused."""
612-
assert self.backend.is_paused, "Expected backend to be paused"
639+
"""Assert the mock backend reaches paused."""
640+
self._eventually(lambda: bool(self.backend.is_paused), True,
641+
lambda got: f"Expected backend to be paused, "
642+
f"got is_paused={got}")
613643

614644
def assert_backend_stopped(self) -> None:
615-
"""Assert the mock backend is neither playing nor paused."""
616-
assert not self.backend.is_playing, \
617-
"Expected backend to be stopped (is_playing=True)"
618-
assert not self.backend.is_paused, \
619-
"Expected backend to be stopped (is_paused=True)"
645+
"""Assert the mock backend reaches neither playing nor paused."""
646+
self._eventually(
647+
lambda: (bool(self.backend.is_playing),
648+
bool(self.backend.is_paused)), (False, False),
649+
lambda got: (f"Expected backend to be stopped "
650+
f"(is_playing={got[0]}, is_paused={got[1]})"))
620651

621652
def assert_now_playing_uri(self, uri: str) -> None:
622-
"""Assert the currently playing URI matches *uri*.
653+
"""Assert the currently playing URI reaches *uri*.
623654
624655
Args:
625656
uri: Expected URI string.
626657
"""
627-
actual = self.player.now_playing.uri if self.player.now_playing else None
628-
assert actual == uri, f"Expected now_playing.uri={uri!r}, got {actual!r}"
658+
self._eventually(
659+
lambda: (self.player.now_playing.uri
660+
if self.player.now_playing else None), uri,
661+
lambda got: f"Expected now_playing.uri={uri!r}, got {got!r}")
629662

630663

631664
# ---------------------------------------------------------------------------
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
"""The player asserts wait for the bus instead of reading once.
2+
3+
The harness emits on the bus and the player transitions on another thread,
4+
so an assert that reads a single time reports "not yet" as "wrong". These
5+
pin the waiting, and pin that waiting did not make the assert vacuous.
6+
"""
7+
import time
8+
import unittest
9+
from types import SimpleNamespace
10+
from unittest import mock
11+
12+
from ovos_utils.ocp import MediaState, PlayerState
13+
14+
from ovoscope.media import OCPPlayerHarness
15+
16+
17+
class _LateState:
18+
"""A value that becomes ``final`` only after ``delay`` seconds.
19+
20+
Stands in for the player transitioning on the bus thread.
21+
"""
22+
23+
def __init__(self, first, final, delay):
24+
self.first, self.final, self.delay = first, final, delay
25+
self.ready_at = time.monotonic() + delay
26+
self.reads = 0
27+
28+
def read(self):
29+
self.reads += 1
30+
return self.final if time.monotonic() >= self.ready_at else self.first
31+
32+
33+
def _harness(timeout=1.0):
34+
"""An OCPPlayerHarness without its __init__: _eventually touches only
35+
settle_timeout, so the real method is called on a plain stand-in."""
36+
stub = SimpleNamespace(settle_timeout=timeout)
37+
stub._eventually = lambda read, want, describe: (
38+
OCPPlayerHarness._eventually(stub, read, want, describe))
39+
return stub
40+
41+
42+
class TestEventuallyWaits(unittest.TestCase):
43+
def test_a_late_value_is_accepted(self):
44+
late = _LateState(PlayerState.STOPPED, PlayerState.PLAYING, 0.20)
45+
h = _harness()
46+
started = time.monotonic()
47+
h._eventually(late.read, PlayerState.PLAYING, lambda got: f"got {got}")
48+
waited = time.monotonic() - started
49+
self.assertGreaterEqual(waited, 0.20,
50+
"it returned before the value could change")
51+
self.assertGreater(late.reads, 1, "it read only once")
52+
53+
def test_a_value_already_right_returns_at_once(self):
54+
"""A passing assert must not cost the settle timeout, or every green
55+
suite pays for this fix."""
56+
h = _harness(timeout=5.0)
57+
started = time.monotonic()
58+
h._eventually(lambda: PlayerState.PLAYING, PlayerState.PLAYING,
59+
lambda got: f"got {got}")
60+
self.assertLess(time.monotonic() - started, 0.5)
61+
62+
def test_a_value_that_never_arrives_still_fails(self):
63+
"""The control. A polling assert that always passed would be worse
64+
than the flake it replaces."""
65+
h = _harness(timeout=0.2)
66+
with self.assertRaises(AssertionError) as caught:
67+
h._eventually(lambda: PlayerState.STOPPED, PlayerState.PLAYING,
68+
lambda got: f"got PlayerState.{got.name}")
69+
self.assertIn("STOPPED", str(caught.exception),
70+
"the message must name the value actually read")
71+
72+
def test_the_deadline_is_honoured(self):
73+
h = _harness(timeout=0.2)
74+
started = time.monotonic()
75+
with self.assertRaises(AssertionError):
76+
h._eventually(lambda: MediaState.NO_MEDIA, MediaState.LOADED_MEDIA,
77+
lambda got: f"got {got}")
78+
waited = time.monotonic() - started
79+
self.assertGreaterEqual(waited, 0.2)
80+
self.assertLess(waited, 2.0, "it waited well past its own deadline")
81+
82+
83+
class _NeverPlays:
84+
"""A player and backend that stay stopped, however long anyone waits."""
85+
86+
state = PlayerState.STOPPED
87+
media_state = MediaState.NO_MEDIA
88+
now_playing = None
89+
is_playing = False
90+
is_paused = False
91+
92+
93+
def _real_harness():
94+
"""A real OCPPlayerHarness without its __init__.
95+
96+
The asserts read only ``self.player`` and ``self.backend``, so the real
97+
methods run against a stand-in that never transitions.
98+
"""
99+
h = object.__new__(OCPPlayerHarness)
100+
h.player = _NeverPlays()
101+
h.backend = _NeverPlays()
102+
return h
103+
104+
105+
class TestTheAssertsRouteThroughTheHelper(unittest.TestCase):
106+
"""C1: the helper being right proves nothing if the asserts do not use it.
107+
108+
Reverting any one assert to a single read leaves it raising at once, so
109+
the elapsed time is what pins the routing, not the raise.
110+
"""
111+
112+
#: Small enough to keep the file fast, large enough that a single read
113+
#: cannot reach it.
114+
PATCHED = 0.30
115+
116+
def _each_assert(self, h):
117+
return [
118+
("assert_player_state",
119+
lambda: h.assert_player_state(PlayerState.PLAYING)),
120+
("assert_media_state",
121+
lambda: h.assert_media_state(MediaState.LOADED_MEDIA)),
122+
("assert_backend_playing", h.assert_backend_playing),
123+
("assert_backend_paused", h.assert_backend_paused),
124+
("assert_backend_stopped",
125+
lambda: h.assert_backend_stopped()),
126+
("assert_now_playing_uri",
127+
lambda: h.assert_now_playing_uri("file:///x.mp3")),
128+
]
129+
130+
def test_five_asserts_wait_the_class_timeout_before_they_fail(self):
131+
h = _real_harness()
132+
with mock.patch.object(OCPPlayerHarness, "settle_timeout",
133+
self.PATCHED):
134+
for name, call in self._each_assert(h):
135+
if name == "assert_backend_stopped":
136+
# The stand-in genuinely satisfies this one: a waiting
137+
# assert on a value already right must return at once.
138+
started = time.monotonic()
139+
call()
140+
self.assertLess(time.monotonic() - started, self.PATCHED,
141+
f"{name} waited on a value already right")
142+
continue
143+
started = time.monotonic()
144+
with self.assertRaises(AssertionError) as caught:
145+
call()
146+
waited = time.monotonic() - started
147+
self.assertGreaterEqual(
148+
waited, self.PATCHED,
149+
f"{name} failed after {waited:.3f}s: it read once "
150+
f"instead of waiting the class settle_timeout")
151+
self.assertLess(waited, self.PATCHED * 10,
152+
f"{name} waited past its own deadline")
153+
self.assertIn("after", str(caught.exception),
154+
f"{name} does not say that it waited")
155+
self.assertIn("settle_timeout", str(caught.exception),
156+
f"{name} does not name the deadline it used")
157+
158+
159+
class TestHarnessExposesTheTimeout(unittest.TestCase):
160+
def test_settle_timeout_is_a_class_attribute(self):
161+
"""A suite on a slow runner has to be able to raise it."""
162+
self.assertIsInstance(OCPPlayerHarness.settle_timeout, float)
163+
self.assertGreater(OCPPlayerHarness.settle_timeout, 0)
164+
165+
def test_the_default_timeout_stays_within_a_readable_range(self):
166+
"""A silently widened default turns a two-second answer into a
167+
suite that takes minutes to say the same thing. Six asserts share
168+
this number, so the bound is part of the contract."""
169+
self.assertGreaterEqual(OCPPlayerHarness.settle_timeout, 0.5)
170+
self.assertLessEqual(OCPPlayerHarness.settle_timeout, 5.0)
171+
172+
173+
if __name__ == "__main__":
174+
unittest.main()

0 commit comments

Comments
 (0)