Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 85 additions & 23 deletions ovoscope/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

import dataclasses
import time
from typing import Callable, List, Optional
from typing import Any, Callable, List, Optional
from unittest.mock import MagicMock, patch

from ovos_bus_client.message import Message
Expand Down Expand Up @@ -267,6 +267,17 @@ class OCPPlayerHarness:
backend_namespace: Namespace for ``MockOCPBackend``; default ``"audio"``.
"""

#: How long an assertion waits for the state it expects, in seconds.
#:
#: The transport methods emit on the bus and return; the player transitions
#: on ANOTHER thread. A read taken straight afterwards can land before the
#: transition, and then "not yet" is indistinguishable from "wrong". Raise
#: it on a slow box, or set it to 0 to get the old single-read behaviour.
settle_timeout: float = 2.0

#: How often an assertion re-reads while it waits, in seconds.
settle_interval: float = 0.01

def __init__(self, backend_namespace: str = "audio",
backend_factory: Optional[Callable[[FakeBus], AudioBackend]] = None,
modernize: bool = True,
Expand Down Expand Up @@ -581,51 +592,102 @@ def simulate_invalid_stream(self) -> None:
# Assertion helpers
# ------------------------------------------------------------------

def _eventually(self, read: Callable[[], Any],
ok: Callable[[Any], bool],
describe: Callable[[Any], str]) -> Any:
"""Re-read until *ok* holds, or fail after ``settle_timeout``.

A transport method emits on the bus and returns; the player transitions
on another thread. A single read cannot tell "not yet" from "wrong", so
every state assertion waits for the value it expects instead of
sampling once.

It returns as soon as *ok* holds, so a passing assertion costs one read
and the suite does not get slower. On timeout it raises the message
*describe* builds from the value it last read, with the deadline
appended, so a real failure still names the state it really saw.

Args:
read: Reads the value under test. Called repeatedly.
ok: True when the value is what the assertion wants.
describe: Builds the failure message from the last value read.

Returns:
The value that satisfied *ok*.
"""
deadline = time.monotonic() + self.settle_timeout
while True:
value = read()
if ok(value):
return value
if time.monotonic() >= deadline:
raise AssertionError(
f"{describe(value)} after {self.settle_timeout}s")
time.sleep(self.settle_interval)

def assert_player_state(self, state: PlayerState) -> None:
"""Assert the player is in the given ``PlayerState``.
"""Assert the player reaches the given ``PlayerState``.

Args:
state: Expected ``PlayerState``.
"""
assert self.player.state == state, (
f"Expected PlayerState.{state.name}, "
f"got PlayerState.{self.player.state.name}"
)
self._eventually(
lambda: self.player.state,
lambda actual: actual == state,
lambda actual: (f"Expected PlayerState.{state.name}, "
f"got PlayerState.{actual.name}"))

def assert_media_state(self, state: MediaState) -> None:
"""Assert the player's media state matches *state*.
"""Assert the player's media state reaches *state*.

Args:
state: Expected ``MediaState``.
"""
assert self.player.media_state == state, (
f"Expected MediaState.{state.name}, "
f"got MediaState.{self.player.media_state.name}"
)
self._eventually(
lambda: self.player.media_state,
lambda actual: actual == state,
lambda actual: (f"Expected MediaState.{state.name}, "
f"got MediaState.{actual.name}"))

def assert_backend_playing(self) -> None:
"""Assert the mock backend is currently playing."""
assert self.backend.is_playing, "Expected backend to be playing"
"""Assert the mock backend reaches the playing state."""
self._eventually(lambda: self.backend.is_playing,
lambda playing: playing,
lambda playing: "Expected backend to be playing")

def assert_backend_paused(self) -> None:
"""Assert the mock backend is currently paused."""
assert self.backend.is_paused, "Expected backend to be paused"
"""Assert the mock backend reaches the paused state."""
self._eventually(lambda: self.backend.is_paused,
lambda paused: paused,
lambda paused: "Expected backend to be paused")

def assert_backend_stopped(self) -> None:
"""Assert the mock backend is neither playing nor paused."""
assert not self.backend.is_playing, \
"Expected backend to be stopped (is_playing=True)"
assert not self.backend.is_paused, \
"Expected backend to be stopped (is_paused=True)"
"""Assert the mock backend reaches a stopped state.

Two conditions, read TOGETHER: a backend that stops playing and pauses
in the same transition must never look stopped in between, and two
sequential single-condition waits could see exactly that.
"""
def _describe(state) -> str:
which = "is_playing=True" if state[0] else "is_paused=True"
return f"Expected backend to be stopped ({which})"

self._eventually(
lambda: (self.backend.is_playing, self.backend.is_paused),
lambda state: not state[0] and not state[1],
_describe)

def assert_now_playing_uri(self, uri: str) -> None:
"""Assert the currently playing URI matches *uri*.
"""Assert the currently playing URI reaches *uri*.

Args:
uri: Expected URI string.
"""
actual = self.player.now_playing.uri if self.player.now_playing else None
assert actual == uri, f"Expected now_playing.uri={uri!r}, got {actual!r}"
self._eventually(
lambda: (self.player.now_playing.uri
if self.player.now_playing else None),
lambda actual: actual == uri,
lambda actual: f"Expected now_playing.uri={uri!r}, got {actual!r}")


# ---------------------------------------------------------------------------
Expand Down
128 changes: 128 additions & 0 deletions test/unittests/test_the_asserts_wait.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""The OCP assertions wait for a transition instead of sampling once.

`OCPPlayerHarness.play()` emits on the bus and returns; the player transitions
on ANOTHER thread. Every assertion used to read once, so on a busy box the read
landed before the transition and reported the state it had not left yet: "not
yet" and "wrong" are different answers and one read cannot tell them apart.
Measured by the plugins lane in ovos-media-plugin-chromecast at origin/dev,
4 failures in 12 runs, always the first assert after play().

These rows drive the waiting helper directly, so they do not need a player or a
bus, and they pin the three properties that make the fix safe rather than
merely green.
"""
import time
import unittest

from ovoscope.media import OCPPlayerHarness


class _Harness(OCPPlayerHarness):
"""The helper alone: no bus, no player, no backend."""

def __init__(self): # deliberately not calling super().__init__
pass


class TestTheWaitingHelper(unittest.TestCase):

def test_a_value_that_is_already_right_returns_at_once(self):
"""A passing assertion must not make the suite slower."""
h = _Harness()
started = time.monotonic()
h._eventually(lambda: "ready", lambda v: v == "ready",
lambda v: "never used")
self.assertLess(time.monotonic() - started, 0.05)

def test_a_value_that_arrives_late_is_waited_for(self):
"""The defect: the transition lands after the first read."""
h = _Harness()
reads = []

def read():
reads.append(len(reads))
# "not yet" for the first few reads, then the real state
return "playing" if len(reads) > 3 else "stopped"

h._eventually(read, lambda v: v == "playing", lambda v: "no")
self.assertGreater(len(reads), 1,
"it must re-read, not sample once")

def test_a_value_that_never_arrives_still_fails(self):
"""The control that matters. A polling assertion that always passes
would be worse than the flake it replaces."""
h = _Harness()
h.settle_timeout = 0.2
started = time.monotonic()
with self.assertRaises(AssertionError) as caught:
h._eventually(lambda: "stopped", lambda v: v == "playing",
lambda v: f"Expected playing, got {v}")
elapsed = time.monotonic() - started
self.assertGreaterEqual(elapsed, 0.2, "it must wait the deadline")
# the message names the state it really read, and the deadline
self.assertIn("got stopped", str(caught.exception))
self.assertIn("0.2s", str(caught.exception))

def test_a_zero_timeout_reads_once(self):
"""The old behaviour stays reachable, for a caller that wants it."""
h = _Harness()
h.settle_timeout = 0
reads = []
with self.assertRaises(AssertionError):
h._eventually(lambda: reads.append(1) or "stopped",
lambda v: v == "playing",
lambda v: f"Expected playing, got {v}")
self.assertEqual(len(reads), 1)


class TestAssertBackendStoppedReadsBothTogether(unittest.TestCase):
"""is_playing and is_paused are read in ONE pass.

A backend that stops playing and pauses in the same transition must never
look stopped in between. Two sequential single-condition waits could see
exactly that, so the two conditions are read as one tuple.
"""

def test_a_backend_that_is_paused_is_not_stopped(self):
class _Backend:
is_playing = False
is_paused = True

h = _Harness()
h.settle_timeout = 0.05
h.backend = _Backend()
with self.assertRaises(AssertionError) as caught:
h.assert_backend_stopped()
self.assertIn("is_paused=True", str(caught.exception))

def test_a_backend_that_is_playing_is_not_stopped(self):
class _Backend:
is_playing = True
is_paused = False

h = _Harness()
h.settle_timeout = 0.05
h.backend = _Backend()
with self.assertRaises(AssertionError) as caught:
h.assert_backend_stopped()
self.assertIn("is_playing=True", str(caught.exception))

def test_a_backend_that_stops_late_passes(self):
class _Backend:
def __init__(self):
self.reads = 0

@property
def is_playing(self):
self.reads += 1
return self.reads < 3

is_paused = False

h = _Harness()
h.backend = _Backend()
h.assert_backend_stopped() # must not raise


if __name__ == "__main__":
unittest.main()
Loading