fix(driver): raise from getters instead of answering defaults (#9) #10

Merged
christianmanivong merged 1 commits from fix/bugs-2026-11-02 into main 2026-11-02 08:23:40 +00:00
3 changed files with 116 additions and 35 deletions

No files matched your search

+8
View File
@@ -18,6 +18,14 @@ All notable changes to this driver. The format follows
instead of returning as if the speaker had done it (#2). instead of returning as if the speaker had done it (#2).
- `get_arp_table()` takes NAPALM's `vrf` argument (#2). - `get_arp_table()` takes NAPALM's `vrf` argument (#2).
- The driver module carries its docstring again (`__doc__` was `None`) (#2). - The driver module carries its docstring again (`__doc__` was `None`) (#2).
- `get_playback_state()` reports the speaker's real transport state (`PLAYING`,
`PAUSED_PLAYBACK`, `STOPPED`, `TRANSITIONING`); it called a method SoCo does not
have and answered `STOPPED` for every speaker (#9).
- `get_volume()`, `get_mute()`, `get_playback_state()` and `get_current_track()` raise
instead of answering `0`, `False`, `STOPPED` or `{}`: `ConnectionClosedException`
when the driver is not connected, `ConnectionException` when the speaker cannot be
reached, `CommandErrorException` when it refuses the request. An unreachable speaker
no longer reads as a silent, stopped one (#9).
## [0.3.0] - 2026-10-23 ## [0.3.0] - 2026-10-23
+35 -31
View File
@@ -9,10 +9,18 @@ from __future__ import annotations
import logging import logging
import socket import socket
from typing import Any from collections.abc import Callable
from typing import Any, TypeVar
from napalm.base.exceptions import ConnectionClosedException, ConnectionException from napalm.base.exceptions import (
CommandErrorException,
ConnectionClosedException,
ConnectionException,
)
from napalm_device_types import FingerprintRule, MediaDriver, PortSpec from napalm_device_types import FingerprintRule, MediaDriver, PortSpec
from soco.exceptions import SoCoException
_T = TypeVar("_T")
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -314,35 +322,37 @@ class SonosDriver(MediaDriver):
"""Roll back to the previous config (no-op on Sonos).""" """Roll back to the previous config (no-op on Sonos)."""
pass pass
def get_playback_state(self) -> str: def _read(self, what: str, read: Callable[[Any], _T]) -> _T:
"""Return the current playback state (PLAYING, PAUSED_PLAYBACK, STOPPED).""" """Run one read against the connected speaker; a failed read raises.
if self._device is None:
return "STOPPED" Network errors (``requests``' exceptions are ``OSError``) become
``ConnectionException``, an error the speaker answered with becomes
``CommandErrorException``; the cause stays attached.
"""
device = self._connected_device()
try: try:
return self._device.get_playback_state() return read(device)
except Exception: except OSError as exc:
# Broad catch: SoCo transport errors are unpredictable raise ConnectionException(
return "STOPPED" f"Cannot read {what} from Sonos at {self.hostname}: {exc}"
) from exc
except SoCoException as exc:
raise CommandErrorException(
f"Sonos at {self.hostname} refused to report {what}: {exc}"
) from exc
def get_playback_state(self) -> str:
"""Return the transport state: PLAYING, PAUSED_PLAYBACK, STOPPED or TRANSITIONING."""
info = self._read("the playback state", lambda d: d.get_current_transport_info())
return str(info["current_transport_state"])
def get_current_track(self) -> dict[str, Any]: def get_current_track(self) -> dict[str, Any]:
"""Return information about the currently playing track.""" """Return information about the currently playing track."""
if self._device is None: return dict(self._read("the current track", lambda d: d.get_current_track_info()))
return {}
try:
return self._device.get_current_track_info()
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return {}
def get_volume(self) -> int: def get_volume(self) -> int:
"""Return the current volume (0-100).""" """Return the current volume (0-100)."""
if self._device is None: return int(self._read("the volume", lambda d: d.volume))
return 0
try:
return self._device.volume
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return 0
def set_volume(self, volume: int) -> None: def set_volume(self, volume: int) -> None:
"""Set the volume (0-100).""" """Set the volume (0-100)."""
@@ -350,13 +360,7 @@ class SonosDriver(MediaDriver):
def get_mute(self) -> bool: def get_mute(self) -> bool:
"""Return whether the speaker is muted.""" """Return whether the speaker is muted."""
if self._device is None: return bool(self._read("the mute state", lambda d: d.mute))
return False
try:
return bool(self._device.mute)
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return False
def set_mute(self, muted: bool) -> None: def set_mute(self, muted: bool) -> None:
"""Mute or unmute the speaker.""" """Mute or unmute the speaker."""
+73 -4
View File
@@ -1,7 +1,14 @@
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, PropertyMock, patch
import pytest import pytest
from napalm.base.exceptions import ConnectionClosedException, ConnectionException import requests
import soco
from napalm.base.exceptions import (
CommandErrorException,
ConnectionClosedException,
ConnectionException,
)
from soco.exceptions import SoCoUPnPException
from napalm_sonos import SonosDriver from napalm_sonos import SonosDriver
@@ -23,11 +30,16 @@ def create_mock_speaker_info():
class TestSonosDriver: class TestSonosDriver:
def setup_method(self): def setup_method(self):
self.driver = SonosDriver("192.168.1.100") self.driver = SonosDriver("192.168.1.100")
self.mock_device = MagicMock() # spec: a call to a method SoCo does not have fails instead of being invented (#9).
self.mock_device = MagicMock(spec=soco.SoCo)
self.mock_device.get_speaker_info.return_value = create_mock_speaker_info() self.mock_device.get_speaker_info.return_value = create_mock_speaker_info()
self.mock_device.volume = 30 self.mock_device.volume = 30
self.mock_device.mute = False self.mock_device.mute = False
self.mock_device.get_playback_state.return_value = "PLAYING" self.mock_device.get_current_transport_info.return_value = {
"current_transport_state": "PLAYING",
"current_transport_status": "OK",
"current_transport_speed": "1",
}
self.mock_device.get_current_track_info.return_value = { self.mock_device.get_current_track_info.return_value = {
"title": "Test Song", "title": "Test Song",
"artist": "Test Artist", "artist": "Test Artist",
@@ -103,10 +115,51 @@ class TestSonosDriver:
state = self.driver.get_playback_state() state = self.driver.get_playback_state()
assert state == "PLAYING" assert state == "PLAYING"
def test_get_playback_state_reads_the_transport_state(self):
"""SoCo has no get_playback_state(); the state is in the transport info (#9)."""
self.mock_device.get_current_transport_info.return_value = {
"current_transport_state": "PAUSED_PLAYBACK",
"current_transport_status": "OK",
"current_transport_speed": "1",
}
assert self.driver.get_playback_state() == "PAUSED_PLAYBACK"
def test_get_volume(self): def test_get_volume(self):
vol = self.driver.get_volume() vol = self.driver.get_volume()
assert vol == 30 assert vol == 30
def test_a_refused_upnp_read_raises(self):
"""A speaker that refuses the read is not a stopped one (#9)."""
self.mock_device.get_current_transport_info.side_effect = SoCoUPnPException(
"UPnP Error 701", "701", "<error/>"
)
with pytest.raises(CommandErrorException) as exc:
self.driver.get_playback_state()
assert isinstance(exc.value.__cause__, SoCoUPnPException)
def test_an_unreachable_speaker_raises_instead_of_reading_silent(self):
"""An unreachable speaker read as volume 0 and not muted (#9)."""
type(self.mock_device).volume = PropertyMock(
side_effect=requests.exceptions.ConnectTimeout("timed out")
)
with pytest.raises(ConnectionException) as exc:
self.driver.get_volume()
assert isinstance(exc.value.__cause__, requests.exceptions.ConnectTimeout)
def test_a_failed_mute_read_raises(self):
type(self.mock_device).mute = PropertyMock(
side_effect=requests.exceptions.ConnectionError("refused")
)
with pytest.raises(ConnectionException):
self.driver.get_mute()
def test_a_failed_track_read_raises(self):
self.mock_device.get_current_track_info.side_effect = requests.exceptions.ReadTimeout(
"timed out"
)
with pytest.raises(ConnectionException):
self.driver.get_current_track()
def test_set_volume(self): def test_set_volume(self):
self.driver.set_volume(50) self.driver.set_volume(50)
assert self.mock_device.volume == 50 assert self.mock_device.volume == 50
@@ -182,6 +235,22 @@ class TestSonosDriver:
assert self.mock_device.volume == 42 assert self.mock_device.volume == 42
@pytest.mark.parametrize(
"getter",
[
lambda d: d.get_volume(),
lambda d: d.get_mute(),
lambda d: d.get_playback_state(),
lambda d: d.get_current_track(),
],
ids=["get_volume", "get_mute", "get_playback_state", "get_current_track"],
)
def test_a_getter_refuses_when_not_connected(getter):
"""A default (0, False, "STOPPED", {}) made a driver never opened read as a quiet speaker."""
with pytest.raises(ConnectionClosedException):
getter(SonosDriver("192.168.1.100"))
def test_the_driver_module_has_its_docstring(): def test_the_driver_module_has_its_docstring():
import napalm_sonos.sonos_driver as module import napalm_sonos.sonos_driver as module