Files
napalm-tplink-jetstream/tests/unit/test_time_sync.py
T
Christian Manivong dc41b8497e
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 52s
driver / test (3.12) (pull_request) Successful in 1m1s
driver / lowest (pull_request) Successful in 26s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 2m6s
driver / publish (pull_request) Skipped
feat(time-sync): the switch's NTP servers and zone through TimeSyncMixin
netOrk aligns every device's NTP servers and time zone with its site's
(NetOrk/netork#2360, #2366). A JetStream keeps both in one line,
system-time ntp <zone> <primary> <backup> <hours>, with the zone as a
UTC offset from a fixed list and summer time in a system-time dst line
of its own.

get_time_sync() reads the servers from that line and the zone as None:
the switch keeps no name to map back. configure_time_sync() writes an
IANA zone as its offset and a dst recurring rule from the zone's POSIX
rule (posix_tz/parse_posix_tz), and refuses before sending anything
what the switch cannot take: more than two servers, anything but IPv4
addresses, an offset it does not offer, a change outside HH:MM of a day.
Servers and zone share the ntp line, so a call with both writes it once.
A change is saved to the startup configuration; values the switch
already has are not sent again, so the alignment on every poll does not
churn.

The code lives in time_sync.py; get_ntp_servers() now reads through it,
so the driver file shrinks (1999 -> 1987 lines).
2026-11-11 15:17:51 +01:00

297 lines
9.5 KiB
Python

"""The switch's time sources and zone through napalm-device-types' TimeSyncMixin (netOrk #2366).
A JetStream keeps both in one line of its configuration, ``system-time ntp <zone>
<primary> <backup> <hours>``, with the zone as a UTC offset from a fixed list, and
summer time in a ``system-time dst`` line of its own (CLI reference guide, "System
Time Commands"). The fake switch below keeps those lines the way ``show
running-config`` lists them and applies what the driver sends in ``configure``.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from napalm_device_types import TimeSyncMixin
from napalm_tplink_jetstream.time_sync import dst_command, parse_ntp_line, zone_token
from napalm_tplink_jetstream.tplink_jetstream import TPLinkJetstreamDriver
RUNNING_CONFIG = """\
!SG2210P
#
#
system-time ntp UTC+01:00 192.168.1.1 192.168.1.2 12
system-time dst recurring 5 Sun Mar 02:00 5 Sun Oct 03:00 60
#
hostname "SW-1"
#
"""
#: Manual time: no ``system-time ntp`` line at all.
RUNNING_CONFIG_MANUAL = """\
!SG2210P
#
hostname "SW-1"
#
"""
class FakeSwitch:
"""The ``system-time`` lines of a switch's running configuration."""
def __init__(self, config: str) -> None:
self.lines = config.splitlines()
self.sent: list[str] = []
self.saved = 0
self.refuse = False
def send_command(self, cmd: str, **_kw: object) -> str:
if cmd == "show running-config":
return "\n".join(self.lines)
if cmd in ("configure", "end"):
return ""
if cmd == "copy running-config startup-config":
self.saved += 1
return "Saving user config OK!"
self.sent.append(cmd)
if self.refuse:
return "Error: Invalid parameter."
if cmd == "no system-time dst":
self.lines = [x for x in self.lines if not x.startswith("system-time dst")]
elif cmd.startswith("system-time "):
kind = cmd.split()[1]
kept = [x for x in self.lines if not x.startswith(f"system-time {kind}")]
self.lines = [kept[0], cmd, *kept[1:]]
return ""
@pytest.fixture
def switch() -> FakeSwitch:
return FakeSwitch(RUNNING_CONFIG)
@pytest.fixture
def driver(switch: FakeSwitch) -> TPLinkJetstreamDriver:
d = TPLinkJetstreamDriver("10.0.0.1", "admin", "pw")
d.device = MagicMock()
d.device.base_prompt = "SW-1"
d.device.send_command.side_effect = switch.send_command
return d
# -- reading -----------------------------------------------------------------
def test_the_driver_is_a_time_sync_driver():
assert issubclass(TPLinkJetstreamDriver, TimeSyncMixin)
assert callable(getattr(TPLinkJetstreamDriver, "get_time_sync", None))
assert TPLinkJetstreamDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"})
def test_reads_the_servers_and_no_zone_name(driver):
assert driver.get_time_sync() == {
"ntp_servers": ["192.168.1.1", "192.168.1.2"],
"timezone": None, # an offset and a summer-time rule, no name
"synchronized": None,
"daemon": None,
}
def test_manual_time_has_no_servers(driver, switch):
switch.lines = RUNNING_CONFIG_MANUAL.splitlines()
assert driver.get_time_sync()["ntp_servers"] == []
assert driver.get_ntp_servers() == {}
@pytest.mark.parametrize(
"line, servers",
[
("system-time ntp UTC+01:00 10.0.0.1 10.0.0.1 12", ["10.0.0.1"]), # one server, twice
("system-time ntp UTC+01:00 10.0.0.1 0.0.0.0 12", ["10.0.0.1"]), # no backup
("system-time ntp UTC 10.0.0.1 10.0.0.2 24", ["10.0.0.1", "10.0.0.2"]),
],
)
def test_a_server_counts_once_and_an_empty_backup_not_at_all(line, servers):
parsed = parse_ntp_line(line)
assert parsed is not None
assert parsed.servers == servers
def test_get_ntp_servers_lists_what_get_time_sync_reads(driver, switch):
switch.lines[3] = "system-time ntp UTC+01:00 10.0.0.1 0.0.0.0 12"
assert driver.get_ntp_servers() == {"10.0.0.1": {}}
assert driver.get_time_sync()["ntp_servers"] == ["10.0.0.1"]
# -- the zone as the switch takes it ------------------------------------------
@pytest.mark.parametrize(
"seconds, token",
[(3600, "UTC+01:00"), (0, "UTC"), (-18000, "UTC-05:00"), (19800, "UTC+05:30")],
)
def test_the_zone_token_is_an_offset_from_the_switchs_list(seconds, token):
assert zone_token(seconds) == token
@pytest.mark.parametrize("seconds", [45900, 50400, 31500]) # Chatham, Kiribati, Eucla
def test_an_offset_the_switch_does_not_offer_is_refused(seconds):
with pytest.raises(ValueError, match="does not offer"):
zone_token(seconds)
def test_summer_time_of_europe():
assert dst_command("Europe/Berlin") == (
"UTC+01:00",
"system-time dst recurring 5 Sun Mar 02:00 5 Sun Oct 03:00 60",
)
def test_summer_time_of_the_usa():
assert dst_command("America/New_York") == (
"UTC-05:00",
"system-time dst recurring 2 Sun Mar 02:00 1 Sun Nov 02:00 60",
)
def test_a_zone_without_summer_time():
assert dst_command("Asia/Kolkata") == ("UTC+05:30", None)
assert dst_command("UTC") == ("UTC", None)
def test_negative_summer_time_is_turned_round():
"""Dublin keeps IST as standard time and GMT as "summer" time; the switch only adds."""
assert dst_command("Europe/Dublin") == (
"UTC",
"system-time dst recurring 5 Sun Mar 01:00 5 Sun Oct 02:00 60",
)
def test_summer_time_outside_a_day_is_refused():
"""America/Nuuk changes at -01:00 and 00:00 local time; the switch takes HH:MM of a day."""
with pytest.raises(ValueError, match="time of day"):
dst_command("America/Nuuk")
# -- writing the servers -----------------------------------------------------
def test_writes_the_servers_keeping_zone_and_interval(driver, switch):
result = driver.configure_time_sync(ntp_servers=["10.0.0.5", "10.0.0.6"])
assert result["success"] is True, result
assert switch.sent == ["system-time ntp UTC+01:00 10.0.0.5 10.0.0.6 12"]
assert switch.saved == 1
def test_one_server_is_primary_and_backup(driver, switch):
result = driver.configure_time_sync(ntp_servers=["10.0.0.5"])
assert result["success"] is True, result
assert switch.sent == ["system-time ntp UTC+01:00 10.0.0.5 10.0.0.5 12"]
def test_the_same_servers_again_change_nothing(driver, switch):
result = driver.configure_time_sync(ntp_servers=["192.168.1.1", "192.168.1.2"])
assert result["success"] is True, result
assert switch.sent == []
assert switch.saved == 0
def test_servers_on_a_switch_on_manual_time_turn_ntp_on_in_utc(driver, switch):
switch.lines = RUNNING_CONFIG_MANUAL.splitlines()
result = driver.configure_time_sync(ntp_servers=["10.0.0.5"])
assert result["success"] is True, result
assert switch.sent == ["system-time ntp UTC 10.0.0.5 10.0.0.5 12"]
@pytest.mark.parametrize(
"servers, why",
[
(["10.0.0.1", "10.0.0.2", "10.0.0.3"], "at most 2"),
(["ntp.example.org"], "IPv4 addresses"),
(["2001:db8::1"], "IPv4 addresses"),
],
)
def test_servers_the_switch_cannot_take_are_refused_before_writing(driver, switch, servers, why):
result = driver.configure_time_sync(ntp_servers=servers)
assert result["success"] is False
assert why in result["output"]
assert switch.sent == []
def test_a_refused_command_fails_the_step_and_is_not_saved(driver, switch):
switch.refuse = True
result = driver.configure_time_sync(ntp_servers=["10.0.0.5"])
assert result["success"] is False
assert "Invalid parameter" in result["output"]
assert switch.saved == 0
# -- writing the zone --------------------------------------------------------
def test_writes_offset_and_summer_time(driver, switch):
result = driver.configure_time_sync(timezone="America/New_York")
assert result["success"] is True, result
assert switch.sent == [
"system-time ntp UTC-05:00 192.168.1.1 192.168.1.2 12",
"system-time dst recurring 2 Sun Mar 02:00 1 Sun Nov 02:00 60",
]
assert switch.saved == 1
def test_the_same_zone_again_changes_nothing(driver, switch):
result = driver.configure_time_sync(timezone="Europe/Berlin")
assert result["success"] is True, result
assert switch.sent == []
assert switch.saved == 0
def test_a_zone_without_summer_time_switches_it_off(driver, switch):
result = driver.configure_time_sync(timezone="Africa/Lagos")
assert result["success"] is True, result
assert switch.sent == ["no system-time dst"]
def test_servers_and_zone_take_one_ntp_line(driver, switch):
result = driver.configure_time_sync(ntp_servers=["10.0.0.5"], timezone="America/New_York")
assert result["success"] is True, result
assert switch.sent == [
"system-time ntp UTC-05:00 10.0.0.5 10.0.0.5 12",
"system-time dst recurring 2 Sun Mar 02:00 1 Sun Nov 02:00 60",
]
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
def test_a_zone_needs_servers_on_a_switch_on_manual_time(driver, switch):
switch.lines = RUNNING_CONFIG_MANUAL.splitlines()
result = driver.configure_time_sync(timezone="Europe/Berlin")
assert result["success"] is False
assert "NTP servers" in result["output"]
assert switch.sent == []
def test_a_zone_the_switch_cannot_show_is_refused_before_writing(driver, switch):
result = driver.configure_time_sync(ntp_servers=["10.0.0.5"], timezone="Pacific/Chatham")
assert result["success"] is False
assert "does not offer" in result["output"]
assert switch.sent == []