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).
- `get_arp_table()` takes NAPALM's `vrf` argument (#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
+35 -31
View File
@@ -9,10 +9,18 @@ from __future__ import annotations
import logging
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 soco.exceptions import SoCoException
_T = TypeVar("_T")
logger = logging.getLogger(__name__)
@@ -314,35 +322,37 @@ class SonosDriver(MediaDriver):
"""Roll back to the previous config (no-op on Sonos)."""
pass
def get_playback_state(self) -> str:
"""Return the current playback state (PLAYING, PAUSED_PLAYBACK, STOPPED)."""
if self._device is None:
return "STOPPED"
def _read(self, what: str, read: Callable[[Any], _T]) -> _T:
"""Run one read against the connected speaker; a failed read raises.
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:
return self._device.get_playback_state()
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return "STOPPED"
return read(device)
except OSError as exc:
raise ConnectionException(
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]:
"""Return information about the currently playing track."""
if self._device is None:
return {}
try:
return self._device.get_current_track_info()
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return {}
return dict(self._read("the current track", lambda d: d.get_current_track_info()))
def get_volume(self) -> int:
"""Return the current volume (0-100)."""
if self._device is None:
return 0
try:
return self._device.volume
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return 0
return int(self._read("the volume", lambda d: d.volume))
def set_volume(self, volume: int) -> None:
"""Set the volume (0-100)."""
@@ -350,13 +360,7 @@ class SonosDriver(MediaDriver):
def get_mute(self) -> bool:
"""Return whether the speaker is muted."""
if self._device is None:
return False
try:
return bool(self._device.mute)
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return False
return bool(self._read("the mute state", lambda d: d.mute))
def set_mute(self, muted: bool) -> None:
"""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
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
@@ -23,11 +30,16 @@ def create_mock_speaker_info():
class TestSonosDriver:
def setup_method(self):
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.volume = 30
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 = {
"title": "Test Song",
"artist": "Test Artist",
@@ -103,10 +115,51 @@ class TestSonosDriver:
state = self.driver.get_playback_state()
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):
vol = self.driver.get_volume()
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):
self.driver.set_volume(50)
assert self.mock_device.volume == 50
@@ -182,6 +235,22 @@ class TestSonosDriver:
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():
import napalm_sonos.sonos_driver as module