Add diagnostics to Keenetic NDMS2 Router (#193451)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Joost Lekkerkerker
2026-11-19 17:08:40 +00:00
committed by GitHub
co-authored by Claude
parent 41c4b57db1
commit 747f0a0942
7 changed files with 194 additions and 46 deletions
@@ -0,0 +1,55 @@
"""Diagnostics support for Keenetic NDMS2 Router."""
from collections import Counter
from typing import TYPE_CHECKING, Any
from homeassistant.core import HomeAssistant
from .const import (
CONF_CONSIDER_HOME,
CONF_INCLUDE_ARP,
CONF_INCLUDE_ASSOCIATED,
CONF_INTERFACES,
CONF_TRY_HOTSPOT,
)
from .router import KeeneticConfigEntry
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: KeeneticConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
router = entry.runtime_data
router_info = router.router_info
if TYPE_CHECKING:
# Setup fails when the router information can't be fetched
assert router_info is not None
clients = list(router.last_devices.values())
# The host, credentials, router name, and region are left out, as are the
# MAC addresses, IP addresses, and names of the clients. Clients are only
# counted per tracked interface.
return {
"config_entry": {
CONF_INTERFACES: entry.options[CONF_INTERFACES],
CONF_CONSIDER_HOME: entry.options[CONF_CONSIDER_HOME],
CONF_TRY_HOTSPOT: entry.options[CONF_TRY_HOTSPOT],
CONF_INCLUDE_ARP: entry.options[CONF_INCLUDE_ARP],
CONF_INCLUDE_ASSOCIATED: entry.options[CONF_INCLUDE_ASSOCIATED],
},
"router": {
"available": router.available,
"model": router_info.model,
"manufacturer": router_info.manufacturer,
"vendor": router_info.vendor,
"hw_version": router_info.hw_version,
"fw_version": router_info.fw_version,
"fw_channel": router_info.fw_channel,
},
"clients": {
"total": len(clients),
"per_interface": dict(
sorted(Counter(client.interface for client in clients).items())
),
},
}
@@ -57,6 +57,11 @@ class KeeneticRouter:
"""Read-only accessor for last_devices."""
return self._last_devices
@property
def router_info(self) -> RouterInfo | None:
"""Read-only accessor for the cached router information."""
return self._router_info
@property
def host(self):
"""Return the host of this hub."""
@@ -1,5 +1,7 @@
"""Tests for the Keenetic NDMS2 component."""
from ndms2_client.client import RouterInfo
from homeassistant.components.keenetic_ndms2 import const
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME
from homeassistant.helpers.service_info.ssdp import (
@@ -10,6 +12,18 @@ from homeassistant.helpers.service_info.ssdp import (
MOCK_NAME = "Keenetic Ultra 2030"
MOCK_IP = "0.0.0.0"
CLIENT_MAC = "aa:bb:cc:dd:ee:ff"
MOCK_ROUTER_INFO = RouterInfo(
name=MOCK_NAME,
fw_version="3.0.4",
fw_channel="stable",
model="mock",
hw_version="0000",
manufacturer="pytest",
vendor="foxel",
region="RU",
)
SSDP_LOCATION = f"http://{MOCK_IP}/"
MOCK_DATA = {
@@ -0,0 +1,43 @@
"""Common fixtures for the Keenetic NDMS2 tests."""
from collections.abc import Generator
from unittest.mock import MagicMock, patch
from ndms2_client import Device
import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.components.keenetic_ndms2.const import DEFAULT_INTERFACE, DOMAIN
from homeassistant.core import HomeAssistant
from . import CLIENT_MAC, MOCK_DATA, MOCK_ROUTER_INFO
@pytest.fixture
def mock_client() -> Generator[MagicMock]:
"""Mock the Keenetic client."""
with (
patch("homeassistant.components.keenetic_ndms2.router.TelnetConnection"),
patch(
"homeassistant.components.keenetic_ndms2.router.Client", autospec=True
) as mock_client_class,
):
client = mock_client_class.return_value
client.get_router_info.return_value = MOCK_ROUTER_INFO
client.get_devices.return_value = [
Device(
mac=CLIENT_MAC,
name="Phone",
ip="192.168.1.2",
interface=DEFAULT_INTERFACE,
)
]
yield client
@pytest.fixture
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Return the default mocked config entry."""
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_DATA)
entry.add_to_hass(hass)
return entry
@@ -0,0 +1,31 @@
# serializer version: 1
# name: test_diagnostics
dict({
'clients': dict({
'per_interface': dict({
'Home': 2,
'VPS0': 1,
}),
'total': 3,
}),
'config_entry': dict({
'consider_home': 150,
'include_arp': True,
'include_associated': True,
'interfaces': list([
'Home',
'VPS0',
]),
'try_hotspot': False,
}),
'router': dict({
'available': True,
'fw_channel': 'stable',
'fw_version': '3.0.4',
'hw_version': '0000',
'manufacturer': 'pytest',
'model': 'mock',
'vendor': 'foxel',
}),
})
# ---
@@ -1,12 +1,10 @@
"""Test the Keenetic NDMS2 device tracker."""
from collections.abc import Generator
from datetime import timedelta
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
from ndms2_client import Device
from ndms2_client.client import RouterInfo
import pytest
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
@@ -19,52 +17,10 @@ from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_HOME, STATE_NOT_HOME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import MOCK_DATA, MOCK_NAME
from . import CLIENT_MAC
CLIENT_MAC = "aa:bb:cc:dd:ee:ff"
ENTITY_ID = "device_tracker.phone"
MOCK_ROUTER_INFO = RouterInfo(
name=MOCK_NAME,
fw_version="3.0.4",
fw_channel="stable",
model="mock",
hw_version="0000",
manufacturer="pytest",
vendor="foxel",
region="RU",
)
@pytest.fixture
def mock_client() -> Generator[MagicMock]:
"""Mock the Keenetic client."""
with (
patch("homeassistant.components.keenetic_ndms2.router.TelnetConnection"),
patch(
"homeassistant.components.keenetic_ndms2.router.Client", autospec=True
) as mock_client_class,
):
client = mock_client_class.return_value
client.get_router_info.return_value = MOCK_ROUTER_INFO
client.get_devices.return_value = [
Device(
mac=CLIENT_MAC,
name="Phone",
ip="192.168.1.2",
interface=DEFAULT_INTERFACE,
)
]
yield client
@pytest.fixture
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Return the default mocked config entry."""
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_DATA)
entry.add_to_hass(hass)
return entry
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_client_name_change_renames_device(
@@ -0,0 +1,44 @@
"""Tests for the Keenetic NDMS2 diagnostics."""
from unittest.mock import MagicMock
from ndms2_client import Device
from pytest_homeassistant.common import MockConfigEntry
from pytest_homeassistant.components.diagnostics import get_diagnostics_for_config_entry
from pytest_homeassistant.typing import ClientSessionGenerator
from syrupy.assertion import SnapshotAssertion
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import CLIENT_MAC, MOCK_OPTIONS
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics."""
hass.config_entries.async_update_entry(mock_config_entry, options=MOCK_OPTIONS)
mock_client.get_devices.return_value = [
Device(mac=CLIENT_MAC, name="Phone", ip="192.168.1.2", interface="Home"),
Device(
mac="11:22:33:44:55:66", name="Laptop", ip="192.168.1.3", interface="Home"
),
Device(mac="22:33:44:55:66:77", name="Server", ip="10.0.0.2", interface="VPS0"),
# Clients on interfaces that are not tracked are not counted
Device(
mac="33:44:55:66:77:88", name="Guest", ip="192.168.2.2", interface="Guest"
),
]
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
assert (
await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry)
== snapshot
)