Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c587915584 | ||
|
|
fe0e0b3e7d | ||
|
|
8b419c54e6 | ||
|
|
244e7f4992 | ||
|
|
75d4257793 | ||
|
|
94fa378796 | ||
|
|
245c2f030c | ||
|
|
3783f74eb8 | ||
|
|
5dbfe62271 | ||
|
|
e326350437 | ||
|
|
666a5f0f35 | ||
|
|
7b624ae3fc | ||
|
|
d0008ece9a |
No files matched your search
@@ -6,6 +6,37 @@ All notable changes to this driver. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- `get_time_sync()` and `configure_time_sync()` through napalm-device-types'
|
||||
`TimeSyncMixin` (4.35.0), over TR-064's `Time:1` service: the box's NTP servers
|
||||
in its order (`GetInfo`, an empty slot is no server), written with
|
||||
`SetNTPServers` (NetOrk/netork#2367). `time_sync_writes` is `{"ntp_servers"}`:
|
||||
AVM documents the zone fields as not supported, and the box keeps its zone as an
|
||||
offset with a summer-time rule, so `timezone` reads `None` unless the box names
|
||||
an IANA zone. The box keeps two servers; a longer list is refused before
|
||||
anything is written, and servers the box already has are not written again.
|
||||
TR-064 says nothing about whether the clock is synchronised (`None`), nor whether
|
||||
the box serves time to its network (NetOrk/netork#2371).
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.35.0.
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
|
||||
3.12 venv no longer has.
|
||||
|
||||
### Fixed
|
||||
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
|
||||
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now": the host
|
||||
list says a host is active, not when the box last saw it (NetOrk/netork#1327).
|
||||
- `get_interfaces()` reports the `wan` speed in Mbit/s as NAPALM defines it: a
|
||||
250 Mbit/s line was shown as 250000 (#2).
|
||||
- `get_system_config()` reports the box's time zone (`NewLocalTimeZoneName`) as
|
||||
`timezone`; it held the box's current local time (#3).
|
||||
- `get_system_config()`'s `firmware_version` is documented for what it is: the
|
||||
version the box offers as an update, empty when it offers none, not the running
|
||||
version (that is `get_facts()["os_version"]`). Unchanged in behaviour (#3).
|
||||
|
||||
## [0.3.0] - 2026-10-23
|
||||
|
||||
The first release on PyPI.
|
||||
|
||||
@@ -6,7 +6,7 @@ NAPALM community driver for **AVM FritzBox** routers (read-only, via TR-064).
|
||||
|
||||
| Dependency | Minimum version |
|
||||
|---|---|
|
||||
| Python | 3.10 |
|
||||
| Python | 3.12 |
|
||||
| NAPALM | 4.0 |
|
||||
| napalm-device-types | 4.21.1 |
|
||||
| fritzconnection | 1.13 |
|
||||
@@ -66,10 +66,41 @@ d.close()
|
||||
FritzBox serves TR-064 over HTTPS with a self-signed certificate; `fritzconnection`
|
||||
does not verify it, so no separate `verify` option is needed.
|
||||
|
||||
## `get_system_config()`
|
||||
|
||||
A snapshot of the box's settings, every field best-effort (a TR-064 service the
|
||||
box does not offer leaves its fields out). Two of them are easy to misread:
|
||||
|
||||
- `firmware_version` is the version the box **offers** as an update, empty when
|
||||
it offers none — not the version running, which is `get_facts()["os_version"]`.
|
||||
`firmware_update_available` says whether there is one. A box that only answers
|
||||
`UserInterface1.GetInfo` (not `X_AVM-DE_GetInfo`) reports
|
||||
`firmware_update_available` without `firmware_version`.
|
||||
- `timezone` is the box's time zone name (`NewLocalTimeZoneName`).
|
||||
|
||||
## Time sync
|
||||
|
||||
`get_time_sync()` and `configure_time_sync()` (napalm-device-types'
|
||||
`TimeSyncMixin`) use TR-064's `Time:1` service
|
||||
([AVM: TR-064 Support – Time](https://fritz.support/resources/TR-064_Time.pdf)):
|
||||
|
||||
- `ntp_servers` are `NewNTPServer1` and `NewNTPServer2` from `GetInfo`; an empty
|
||||
slot is no server. `configure_time_sync(ntp_servers=[...])` writes them with
|
||||
`SetNTPServers`: two at most (a longer list is refused before anything is
|
||||
written), a missing second one as an empty slot. Servers the box already has,
|
||||
in that order, are not written again.
|
||||
- The zone is not written (`time_sync_writes == {"ntp_servers"}`): AVM documents
|
||||
the zone fields as not supported. The box reports its zone, if at all, as a
|
||||
POSIX rule (`CET-1CEST,M3.5.0,M10.5.0/3`), so `timezone` is `None` unless it
|
||||
names an IANA zone.
|
||||
- `synchronized` and `daemon` are `None`: TR-064 says neither.
|
||||
- Whether the box serves time to its home network ("FRITZ!Box als Zeitserver im
|
||||
Heimnetz bereitstellen") is not in TR-064 either, so the driver cannot report it.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Read-only: configuration management methods (`load_merge_candidate`,
|
||||
`commit_config`, ...) are not implemented.
|
||||
- Configuration management methods (`load_merge_candidate`, `commit_config`, ...)
|
||||
are not implemented; the only write is the NTP servers (see *Time sync*).
|
||||
- `get_nat_translations()` is derived from the enabled port-forwarding rules —
|
||||
TR-064 does not expose a live connection-tracking table.
|
||||
- `get_vpn_tunnels()` returns an empty dict — FritzOS does not expose VPN
|
||||
@@ -87,7 +118,7 @@ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
||||
```
|
||||
|
||||
CI ([.gitea/workflows/ci.yml](.gitea/workflows/ci.yml)) calls the shared workflow of
|
||||
the NAPALM driver standard: ruff, mypy, the tests on Python 3.10–3.13, bandit,
|
||||
the NAPALM driver standard: ruff, mypy, the tests on Python 3.12 and 3.13, bandit,
|
||||
pip-audit and a build check.
|
||||
|
||||
## License
|
||||
|
||||
+80
-12
@@ -26,8 +26,9 @@ FritzBox always serves TR-064 over HTTPS with a self-signed certificate;
|
||||
``fritzconnection`` does not verify it, so no separate ``verify`` option is
|
||||
needed.
|
||||
|
||||
This driver is read-only: it does not implement NAPALM's configuration
|
||||
management methods (``load_merge_candidate``, ``commit_config``, ...).
|
||||
The driver writes one thing: the box's NTP servers (``configure_time_sync``,
|
||||
TR-064 ``Time:1``). It does not implement NAPALM's configuration management
|
||||
methods (``load_merge_candidate``, ``commit_config``, ...).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -46,6 +47,7 @@ from fritzconnection.core.exceptions import (
|
||||
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
|
||||
from napalm_device_types import FingerprintRule, ResidentialGatewayDriver
|
||||
from napalm_device_types.models import (
|
||||
FixStepOutcomeDict,
|
||||
HostDict,
|
||||
NATTranslationDict,
|
||||
PortForwardDict,
|
||||
@@ -55,6 +57,8 @@ from napalm_device_types.models import (
|
||||
WANStatusDict,
|
||||
WirelessClientDict,
|
||||
)
|
||||
from napalm_device_types.posix_tz import is_iana_zone
|
||||
from napalm_device_types.time_sync import TimeSyncDict, TimeSyncMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -66,6 +70,9 @@ _ANY_REMOTE = "0.0.0.0" # nosec B104
|
||||
# (e.g. a service not present on a given FritzOS version/model).
|
||||
_OPTIONAL_SERVICE_ERRORS = (FritzServiceError, FritzActionError, FritzConnectionException)
|
||||
|
||||
#: TR-064 reports the WAN sync rate in bit/s; NAPALM's interface ``speed`` is Mbit/s.
|
||||
_BIT_PER_MBIT = 1_000_000
|
||||
|
||||
|
||||
def _to_float(value: Any, default: float = 0.0) -> float:
|
||||
"""Convert a TR-064 field to float, returning *default* for non-numeric values like 'Auto'."""
|
||||
@@ -75,8 +82,8 @@ def _to_float(value: Any, default: float = 0.0) -> float:
|
||||
return default
|
||||
|
||||
|
||||
class FritzBoxDriver(ResidentialGatewayDriver):
|
||||
"""NAPALM driver for AVM FritzBox (read-only, TR-064)."""
|
||||
class FritzBoxDriver(ResidentialGatewayDriver, TimeSyncMixin):
|
||||
"""NAPALM driver for AVM FritzBox (TR-064); it writes only its NTP servers."""
|
||||
|
||||
VENDOR = "AVM"
|
||||
DRIVER_NAME = "fritzbox"
|
||||
@@ -96,6 +103,12 @@ class FritzBoxDriver(ResidentialGatewayDriver):
|
||||
_WAN_IP_SERVICES = ("WANIPConnection1", "WANPPPConnection1")
|
||||
_WLAN_SERVICES = ("WLANConfiguration1", "WLANConfiguration2", "WLANConfiguration3")
|
||||
|
||||
#: TR-064 ``Time:1`` reads and sets the NTP servers only; its zone fields are
|
||||
#: "not supported" (AVM, TR-064 Support -- Time, 2025-08-07).
|
||||
time_sync_writes = frozenset({"ntp_servers"})
|
||||
#: ``SetNTPServers`` takes two servers, ``NewNTPServer1`` and ``NewNTPServer2``.
|
||||
_NTP_SLOTS = 2
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hostname: str,
|
||||
@@ -265,7 +278,7 @@ class FritzBoxDriver(ResidentialGatewayDriver):
|
||||
"description": link.get("NewWANAccessType", "WAN"),
|
||||
"last_flapped": -1.0,
|
||||
"mac_address": "",
|
||||
"speed": _to_float(link.get("NewLayer1DownstreamMaxBitRate")) / 1000,
|
||||
"speed": _to_float(link.get("NewLayer1DownstreamMaxBitRate")) / _BIT_PER_MBIT,
|
||||
"mtu": 1500,
|
||||
}
|
||||
except _OPTIONAL_SERVICE_ERRORS:
|
||||
@@ -331,11 +344,11 @@ class FritzBoxDriver(ResidentialGatewayDriver):
|
||||
return result
|
||||
|
||||
def get_system_config(self) -> dict[str, Any]:
|
||||
"""Return a system configuration snapshot for storage as ``system_snapshot``.
|
||||
"""Return a best-effort snapshot of DSL statistics, firmware updates, DNS and NTP.
|
||||
|
||||
Collects DSL line statistics, firmware update status, upstream DNS
|
||||
servers and NTP settings. All fields are best-effort: missing
|
||||
TR-064 services are silently skipped.
|
||||
``firmware_version`` is the version on *offer* (empty when none), not the one
|
||||
running (``get_facts()["os_version"]``); a box answering only
|
||||
``UserInterface1.GetInfo`` leaves it out. A missing TR-064 service is skipped.
|
||||
"""
|
||||
available = self.fc.services if self.fc else {}
|
||||
result: dict[str, Any] = {}
|
||||
@@ -402,7 +415,7 @@ class FritzBoxDriver(ResidentialGatewayDriver):
|
||||
time_info = self._call("Time1", "GetInfo")
|
||||
result["ntp_server"] = time_info.get("NewNTPServer1", "")
|
||||
result["ntp_server2"] = time_info.get("NewNTPServer2", "")
|
||||
result["timezone"] = time_info.get("NewCurrentLocalTime", "")
|
||||
result["timezone"] = time_info.get("NewLocalTimeZoneName", "")
|
||||
except _OPTIONAL_SERVICE_ERRORS:
|
||||
pass
|
||||
|
||||
@@ -411,7 +424,9 @@ class FritzBoxDriver(ResidentialGatewayDriver):
|
||||
def get_arp_table(self, vrf: str = "") -> list[dict[str, Any]]:
|
||||
"""Return the ARP table, derived from :meth:`get_hosts`.
|
||||
|
||||
Each entry contains: ``interface``, ``mac``, ``ip``, ``age``.
|
||||
Each entry contains: ``interface``, ``mac``, ``ip``, ``age``. The host
|
||||
list says whether a host is active, not when the box last saw it, so
|
||||
``age`` is ``-1.0`` (unknown, napalm-device-types' ``ARP_AGE_UNKNOWN``).
|
||||
"""
|
||||
arp_table: list[dict[str, Any]] = []
|
||||
for host in self.get_hosts():
|
||||
@@ -422,11 +437,64 @@ class FritzBoxDriver(ResidentialGatewayDriver):
|
||||
"interface": host["interface_type"],
|
||||
"mac": host["mac"],
|
||||
"ip": host["ip"],
|
||||
"age": 0.0,
|
||||
"age": -1.0,
|
||||
}
|
||||
)
|
||||
return arp_table
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Time sync (napalm-device-types TimeSyncMixin)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _time_info(self) -> dict[str, Any]:
|
||||
if self.fc is not None and "Time1" not in self.fc.services:
|
||||
raise FritzServiceError("this FRITZ!Box offers no TR-064 Time service")
|
||||
return self._call("Time1", "GetInfo")
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""The box's NTP servers, from ``Time1.GetInfo``; one TR-064 call.
|
||||
|
||||
An empty server slot is no server. The box keeps its zone as an offset with
|
||||
a summer-time rule (``NewLocalTimeZoneName`` holds a POSIX rule, or nothing),
|
||||
so ``timezone`` is None unless the box names an IANA zone. TR-064 says
|
||||
neither whether the clock is synchronised nor anything about the client.
|
||||
"""
|
||||
info = self._time_info()
|
||||
servers = [
|
||||
name
|
||||
for name in (
|
||||
str(info.get(f"NewNTPServer{slot}") or "").strip()
|
||||
for slot in range(1, self._NTP_SLOTS + 1)
|
||||
)
|
||||
if name
|
||||
]
|
||||
zone = str(info.get("NewLocalTimeZoneName") or "").strip()
|
||||
return {
|
||||
"ntp_servers": servers,
|
||||
"timezone": zone if is_iana_zone(zone) else None,
|
||||
"synchronized": None,
|
||||
"daemon": None,
|
||||
}
|
||||
|
||||
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
"""``Time1.SetNTPServers`` with *servers*, an empty slot for a missing second.
|
||||
|
||||
More than two are refused: the box would drop the rest. Servers the box
|
||||
already has, in this order, are not written again.
|
||||
"""
|
||||
if len(servers) > self._NTP_SLOTS:
|
||||
return {
|
||||
"ok": False,
|
||||
"output": f"a FRITZ!Box keeps two NTP servers, not {len(servers)}: "
|
||||
+ ", ".join(servers),
|
||||
}
|
||||
now = self.get_time_sync()["ntp_servers"]
|
||||
if [s.lower() for s in now] == [s.lower() for s in servers]:
|
||||
return {"ok": True, "output": "the box already has these NTP servers"}
|
||||
first, second = [*servers, "", ""][: self._NTP_SLOTS]
|
||||
self._call("Time1", "SetNTPServers", NewNTPServer1=first, NewNTPServer2=second)
|
||||
return {"ok": True, "output": f"NTP servers set to {', '.join(servers)}"}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Residential gateway extensions
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
+5
-7
@@ -8,15 +8,13 @@ version = "0.3.0"
|
||||
description = "NAPALM driver for AVM FritzBox (TR-064 via fritzconnection)."
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
requires-python = ">=3.10"
|
||||
requires-python = ">=3.12"
|
||||
authors = [
|
||||
{ name = "Christian Manivong" },
|
||||
]
|
||||
classifiers = [
|
||||
"Topic :: Utilities",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Operating System :: POSIX :: Linux",
|
||||
@@ -24,8 +22,8 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0.0",
|
||||
"napalm-device-types>=4.21.1",
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.35.0",
|
||||
"fritzconnection>=1.13.0",
|
||||
]
|
||||
|
||||
@@ -49,7 +47,7 @@ napalm_fritzbox = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py310"
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
@@ -59,7 +57,7 @@ select = ["E", "F", "I", "UP", "B"]
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Shared test setup: unit tests never open a socket."""
|
||||
|
||||
import gc
|
||||
import socket
|
||||
from collections.abc import Iterator
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
_attempts: list[str] = []
|
||||
|
||||
|
||||
def _refuse_create_connection(address: Any, *args: Any, **kwargs: Any) -> socket.socket:
|
||||
_attempts.append(f"create_connection{address!r}")
|
||||
raise OSError("unit tests never open a socket")
|
||||
|
||||
|
||||
def _refuse_connect(self: socket.socket, address: Any) -> None:
|
||||
_attempts.append(f"connect{address!r}")
|
||||
raise OSError("unit tests never open a socket")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _no_network() -> Iterator[None]:
|
||||
"""Refuse every connection and fail the run if anything tried one.
|
||||
|
||||
A connection attempted from ``__del__`` (NAPALM's ``NetworkDriver.__del__`` calls
|
||||
``is_alive()`` on a driver that was never closed) is swallowed there, so the
|
||||
attempts are recorded and checked once every driver has been collected.
|
||||
"""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(socket, "create_connection", _refuse_create_connection)
|
||||
mp.setattr(socket.socket, "connect", _refuse_connect)
|
||||
yield
|
||||
gc.collect()
|
||||
assert not _attempts, f"unit tests tried to open a socket: {_attempts}"
|
||||
@@ -161,6 +161,8 @@ TIME_INFO = {
|
||||
"NewNTPServer1": "ntp.example.com",
|
||||
"NewNTPServer2": "",
|
||||
"NewCurrentLocalTime": "2026-06-24T16:00:00+02:00",
|
||||
"NewLocalTimeZone": "+01:00",
|
||||
"NewLocalTimeZoneName": "CET-1CEST,M3.5.0,M10.5.0/3",
|
||||
}
|
||||
|
||||
IPV6_FIREWALL_STATUS = {"NewFirewallEnabled": True, "NewInboundPinholeAllowed": True}
|
||||
@@ -266,6 +268,8 @@ def driver():
|
||||
drv = FritzBoxDriver(hostname="fritz.box", username="user", password="pass")
|
||||
drv.fc = mock_fc
|
||||
yield drv
|
||||
# An open driver makes NAPALM's __del__ probe fritz.box over the network (#11).
|
||||
drv.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -286,6 +290,8 @@ def pppoe_driver():
|
||||
drv = FritzBoxDriver(hostname="fritz.box", username="user", password="pass")
|
||||
drv.fc = mock_fc
|
||||
yield drv
|
||||
# An open driver makes NAPALM's __del__ probe fritz.box over the network (#11).
|
||||
drv.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -307,6 +313,7 @@ class TestOpenClose:
|
||||
with patch("napalm_fritzbox.fritzbox.FritzConnection", return_value=mock_fc):
|
||||
drv.open()
|
||||
assert drv.fc is mock_fc
|
||||
drv.close()
|
||||
|
||||
def test_close_clears_fc(self, driver):
|
||||
driver.close()
|
||||
@@ -393,6 +400,10 @@ class TestGetInterfaces:
|
||||
assert interfaces["wan"]["is_up"] is True
|
||||
assert interfaces["wan"]["description"] == "DSL"
|
||||
|
||||
def test_wan_speed_in_mbit(self, driver):
|
||||
# NewLayer1DownstreamMaxBitRate is bit/s: 250 000 000 bit/s is 250 Mbit/s.
|
||||
assert driver.get_interfaces()["wan"]["speed"] == 250.0
|
||||
|
||||
def test_wlan_interfaces_present(self, driver):
|
||||
interfaces = driver.get_interfaces()
|
||||
assert interfaces["wlanconfiguration1"]["description"] == "MyWifi"
|
||||
@@ -440,6 +451,11 @@ class TestGetArpTable:
|
||||
assert arp_table[0]["mac"] == "11:22:33:44:55:66"
|
||||
assert arp_table[0]["ip"] == "192.168.1.50"
|
||||
|
||||
def test_age_is_unknown(self, driver):
|
||||
# The host list says a host is active, not when the box last saw it;
|
||||
# 0.0 would read as "confirmed just now" (NetOrk/netork#1327).
|
||||
assert [e["age"] for e in driver.get_arp_table()] == [-1.0]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_wan_status()
|
||||
@@ -703,6 +719,16 @@ class TestGetSystemConfig:
|
||||
def test_ntp_server(self, driver):
|
||||
assert driver.get_system_config()["ntp_server"] == "ntp.example.com"
|
||||
|
||||
def test_timezone_is_the_zone_name_not_the_clock(self, driver):
|
||||
assert driver.get_system_config()["timezone"] == "CET-1CEST,M3.5.0,M10.5.0/3"
|
||||
|
||||
def test_timezone_empty_when_box_names_none(self, driver):
|
||||
time_info = {k: v for k, v in TIME_INFO.items() if k != "NewLocalTimeZoneName"}
|
||||
driver.fc.call_action.side_effect = lambda svc, act, **kw: (
|
||||
time_info if (svc, act) == ("Time1", "GetInfo") else _call_action(svc, act, **kw)
|
||||
)
|
||||
assert driver.get_system_config()["timezone"] == ""
|
||||
|
||||
def test_empty_when_no_dsl_service(self, driver):
|
||||
del driver.fc.services["WANDSLInterfaceConfig1"]
|
||||
cfg = driver.get_system_config()
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""get_time_sync() / configure_time_sync() over TR-064's Time:1 service (NetOrk/netork#2367).
|
||||
|
||||
The answers are what AVM documents for ``urn:dslforum-org:service:Time:1``
|
||||
(TR-064 Support -- Time, version 5, 2025-08-07): ``GetInfo`` returns the two NTP
|
||||
servers and the box's clock; the zone fields are "not supported" -- a box fills
|
||||
``NewLocalTimeZoneName`` with a POSIX rule or leaves it empty. ``SetNTPServers``
|
||||
takes exactly two names; an empty one is an unused slot.
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fritzconnection.core.exceptions import FritzServiceError
|
||||
|
||||
from napalm_fritzbox.fritzbox import FritzBoxDriver
|
||||
|
||||
GET_INFO = {
|
||||
"NewNTPServer1": "ntp.example.com",
|
||||
"NewNTPServer2": "",
|
||||
"NewCurrentLocalTime": "2026-11-11T10:00:00+01:00",
|
||||
"NewLocalTimeZone": "",
|
||||
"NewLocalTimeZoneName": "CET-1CEST,M3.5.0,M10.5.0/3",
|
||||
"NewDaylightSavingsUsed": False,
|
||||
"NewDaylightSavingsStart": "0001-01-01T00:00:00",
|
||||
"NewDaylightSavingsEnd": "0001-01-01T00:00:00",
|
||||
}
|
||||
|
||||
|
||||
class FakeTimeService:
|
||||
"""The box's Time:1 service: GetInfo reads what SetNTPServers stored."""
|
||||
|
||||
def __init__(self, info: dict) -> None:
|
||||
self.info = dict(info)
|
||||
self.sets: list[dict] = []
|
||||
|
||||
def __call__(self, service: str, action: str, **kwargs: str) -> dict:
|
||||
if service != "Time1":
|
||||
raise FritzServiceError(f"no service {service}")
|
||||
if action == "GetInfo":
|
||||
return dict(self.info)
|
||||
if action == "SetNTPServers":
|
||||
self.sets.append(kwargs)
|
||||
self.info["NewNTPServer1"] = kwargs["NewNTPServer1"]
|
||||
self.info["NewNTPServer2"] = kwargs["NewNTPServer2"]
|
||||
return {}
|
||||
raise AssertionError(f"unexpected action {action}")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def box():
|
||||
fake = FakeTimeService(GET_INFO)
|
||||
mock_fc = MagicMock()
|
||||
mock_fc.services = {"Time1": MagicMock()}
|
||||
mock_fc.call_action.side_effect = fake
|
||||
drv = FritzBoxDriver(hostname="fritz.box", username="user", password="pass")
|
||||
drv.fc = mock_fc
|
||||
yield drv, fake
|
||||
drv.close()
|
||||
|
||||
|
||||
class TestRead:
|
||||
def test_is_offered(self, box):
|
||||
drv, _ = box
|
||||
assert callable(getattr(drv, "get_time_sync", None))
|
||||
assert callable(getattr(drv, "configure_time_sync", None))
|
||||
|
||||
def test_servers_without_the_empty_slot(self, box):
|
||||
drv, _ = box
|
||||
assert drv.get_time_sync() == {
|
||||
"ntp_servers": ["ntp.example.com"],
|
||||
"timezone": None,
|
||||
"synchronized": None,
|
||||
"daemon": None,
|
||||
}
|
||||
|
||||
def test_both_servers_in_the_box_order(self, box):
|
||||
drv, fake = box
|
||||
fake.info.update(NewNTPServer1=" 2.europe.pool.ntp.org ", NewNTPServer2="192.0.2.1")
|
||||
assert drv.get_time_sync()["ntp_servers"] == ["2.europe.pool.ntp.org", "192.0.2.1"]
|
||||
|
||||
def test_no_servers(self, box):
|
||||
drv, fake = box
|
||||
fake.info.update(NewNTPServer1="", NewNTPServer2="")
|
||||
assert drv.get_time_sync()["ntp_servers"] == []
|
||||
|
||||
def test_a_posix_rule_is_no_zone_name(self, box):
|
||||
"""The box keeps an offset and a summer-time rule, not a name."""
|
||||
drv, _ = box
|
||||
assert drv.get_time_sync()["timezone"] is None
|
||||
|
||||
def test_a_zone_name_the_box_gives_is_kept(self, box):
|
||||
drv, fake = box
|
||||
fake.info["NewLocalTimeZoneName"] = "Europe/Berlin"
|
||||
assert drv.get_time_sync()["timezone"] == "Europe/Berlin"
|
||||
|
||||
def test_a_missing_zone_field_is_none(self, box):
|
||||
drv, fake = box
|
||||
del fake.info["NewLocalTimeZoneName"]
|
||||
assert drv.get_time_sync()["timezone"] is None
|
||||
|
||||
def test_a_box_without_the_service_cannot_tell(self, box):
|
||||
drv, _ = box
|
||||
drv.fc.services = {}
|
||||
with pytest.raises(FritzServiceError):
|
||||
drv.get_time_sync()
|
||||
|
||||
def test_system_config_names_the_same_servers(self, box):
|
||||
drv, fake = box
|
||||
fake.info.update(NewNTPServer1="a.example.org", NewNTPServer2="b.example.org")
|
||||
config = drv.get_system_config()
|
||||
assert [config["ntp_server"], config["ntp_server2"]] == drv.get_time_sync()["ntp_servers"]
|
||||
|
||||
|
||||
class TestWrite:
|
||||
def test_writes_only_servers(self, box):
|
||||
drv, _ = box
|
||||
assert drv.time_sync_writes == frozenset({"ntp_servers"})
|
||||
with pytest.raises(ValueError, match="timezone"):
|
||||
drv.configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
def test_two_servers(self, box):
|
||||
drv, fake = box
|
||||
result = drv.configure_time_sync(ntp_servers=["ntp1.example.org", "10.0.0.1"])
|
||||
assert result["success"], result["output"]
|
||||
assert fake.sets == [{"NewNTPServer1": "ntp1.example.org", "NewNTPServer2": "10.0.0.1"}]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "verify"]
|
||||
|
||||
def test_one_server_empties_the_second_slot(self, box):
|
||||
drv, fake = box
|
||||
fake.info["NewNTPServer2"] = "old.example.org"
|
||||
result = drv.configure_time_sync(ntp_servers=["10.0.0.1"])
|
||||
assert result["success"], result["output"]
|
||||
assert fake.sets == [{"NewNTPServer1": "10.0.0.1", "NewNTPServer2": ""}]
|
||||
assert drv.get_time_sync()["ntp_servers"] == ["10.0.0.1"]
|
||||
|
||||
def test_more_than_two_is_refused_before_writing(self, box):
|
||||
drv, fake = box
|
||||
result = drv.configure_time_sync(ntp_servers=["a.example.org", "b.example.org", "c.org"])
|
||||
assert not result["success"]
|
||||
assert result["steps"][0]["step"] == "ntp_servers"
|
||||
assert "two" in result["steps"][0]["output"]
|
||||
assert fake.sets == []
|
||||
|
||||
def test_the_same_servers_again_write_nothing(self, box):
|
||||
drv, fake = box
|
||||
result = drv.configure_time_sync(ntp_servers=["NTP.example.com"])
|
||||
assert result["success"], result["output"]
|
||||
assert fake.sets == []
|
||||
|
||||
def test_a_box_that_keeps_other_servers_fails_verify(self, box):
|
||||
drv, fake = box
|
||||
drv.fc.call_action.side_effect = lambda s, a, **kw: (
|
||||
{} if a == "SetNTPServers" else fake(s, a)
|
||||
)
|
||||
result = drv.configure_time_sync(ntp_servers=["10.0.0.1"])
|
||||
assert not result["success"]
|
||||
assert result["steps"][-1]["step"] == "verify"
|
||||
assert "ntp.example.com" in result["steps"][-1]["output"]
|
||||
|
||||
def test_a_refused_write_fails_the_step(self, box):
|
||||
drv, fake = box
|
||||
|
||||
def refuse(service, action, **kwargs):
|
||||
if action == "SetNTPServers":
|
||||
raise FritzServiceError("UPnPError 606: Action not authorized")
|
||||
return fake(service, action)
|
||||
|
||||
drv.fc.call_action.side_effect = refuse
|
||||
result = drv.configure_time_sync(ntp_servers=["10.0.0.1"])
|
||||
assert not result["success"]
|
||||
assert "606" in result["steps"][0]["output"]
|
||||
Reference in new issue
Block a user