diff --git a/CHANGELOG.md b/CHANGELOG.md index c8d70d0..42424fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ 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, NetOrk/netork#2366). The switch keeps servers and zone in one + `system-time ntp ` line: the read lists its servers + (one listed as primary and backup counts once, an empty `0.0.0.0` backup not at all), + and the zone as `None`, since the switch keeps a UTC offset, not a name. A write takes + at most 2 IPv4 addresses (one server goes in as primary and backup) and an IANA zone, + written as its UTC offset from the switch's list and a `system-time dst recurring` line + from the zone's POSIX rule (`no system-time dst` for a zone without summer time); a + zone the switch cannot show (UTC+12:45, a change at 24:00) is refused before anything + is sent. Writing the servers switches the clock from manual time to NTP. A change is + saved with `copy running-config startup-config`; what the switch already has is not + sent again. `get_ntp_servers()` lists the same servers. + ### Fixed - `get_snmp_information()` reads each community from the table's `Name` column and its access from the `Type` column (#14). It took the `Index` column as the community, so @@ -24,6 +38,7 @@ All notable changes to this driver. The format follows none: without a listed community it reports the agent as not running. ### 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 diff --git a/README.md b/README.md index 7c735f4..316aafc 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,8 @@ with driver("192.168.0.1", "admin", "admin") as device: | `get_lldp_neighbors` | ✅ | | `get_lldp_neighbors_detail` | ✅ | | `get_vlans` | ✅ | +| `get_ntp_servers` | ✅ | +| `get_time_sync` / `configure_time_sync` | ✅ Up to 2 IPv4 servers; the zone as a UTC offset and a summer-time rule (read back as `None`) | | `cli` | ✅ | | `is_alive` | ✅ | | `get_bgp_neighbors` | ❌ Not applicable | diff --git a/napalm_tplink_jetstream/time_sync.py b/napalm_tplink_jetstream/time_sync.py new file mode 100644 index 0000000..34eebe9 --- /dev/null +++ b/napalm_tplink_jetstream/time_sync.py @@ -0,0 +1,254 @@ +"""The switch's time sources and zone (napalm-device-types ``TimeSyncMixin``). + +A JetStream keeps both in one line of its configuration (CLI reference guide, +"System Time Commands"):: + + system-time ntp + system-time dst recurring + +The zone is a UTC offset from the list the switch offers (``UTC+01:00``, ``UTC``), +the servers are two IPv4 addresses, the rate is in hours. Summer time is a line of +its own. The switch keeps no zone name, so ``timezone`` reads as None; an IANA name +is written as its offset and summer-time rule, from the zone's POSIX rule. + +Writing the ``ntp`` line also switches the clock from manual time to NTP. Every +change is saved to the startup configuration, and nothing is sent when the switch +already has what is asked. +""" + +from __future__ import annotations + +import ipaddress +import re +from collections.abc import Sequence +from typing import TYPE_CHECKING, ClassVar, NamedTuple + +from napalm_device_types import TimeSyncDict, TimeSyncMixin +from napalm_device_types.models import FixResultDict, FixStepOutcomeDict +from napalm_device_types.posix_tz import DstTransitionDict, parse_posix_tz, posix_tz + +#: ``system-time ntp`` takes a primary and a backup server. +MAX_SERVERS = 2 +#: Hours between two fetches when the switch had no ``ntp`` line yet (its default). +DEFAULT_FETCHING_RATE = 12 +#: An empty backup server as the switch lists it. +_NO_SERVER = "0.0.0.0" # nosec B104 - a listed value, nothing binds to it + +#: The offsets ``system-time ntp`` offers, in minutes east of UTC. +OFFERED_OFFSETS = frozenset( + [hours * 60 for hours in range(-12, 14)] + [-270, -210, 210, 270, 330, 345, 390, 570] +) + +_DAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") +_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") +_ZONE = re.compile(r"UTC(?:([+-])(\d{1,2}):(\d{2}))?", re.I) +_NTP_LINE = re.compile(r"system-time\s+ntp\s+(\S+)\s+(.*)", re.I) + + +class NtpLine(NamedTuple): + """The ``system-time ntp`` line: zone token, servers in order, fetching rate.""" + + zone: str + servers: list[str] + rate: int + + +def parse_ntp_line(running: str) -> NtpLine | None: + """The ``system-time ntp`` line of *running*; None on manual time. + + A server listed as primary and backup counts once, an empty backup not at all. + """ + for line in running.splitlines(): + match = _NTP_LINE.fullmatch(line.strip()) + if match is None: + continue + tokens = match.group(2).split() + rate = int(tokens[-1]) if tokens and tokens[-1].isdigit() else DEFAULT_FETCHING_RATE + servers: list[str] = [] + for token in tokens: + if not token.isdigit() and token != _NO_SERVER and token not in servers: + servers.append(token) + return NtpLine(match.group(1), servers, rate) + return None + + +def _dst_line(running: str) -> str | None: + for line in running.splitlines(): + if line.strip().lower().startswith("system-time dst"): + return " ".join(line.split()) + return None + + +def _zone_minutes(token: str) -> int | None: + match = _ZONE.fullmatch(token) + if match is None: + return None + sign, hours, minutes = match.groups() + if sign is None: + return 0 + return (1 if sign == "+" else -1) * (int(hours) * 60 + int(minutes)) + + +def zone_token(utc_offset: int) -> str: + """*utc_offset* (seconds east of UTC) as ``system-time ntp`` takes it. + + :raises ValueError: for an offset the switch does not offer. + """ + minutes, rest = divmod(utc_offset, 60) + if rest or minutes not in OFFERED_OFFSETS: + raise ValueError(f"the switch does not offer the UTC offset {utc_offset / 3600:+g} h") + if minutes == 0: + return "UTC" + hours, mins = divmod(abs(minutes), 60) + return f"UTC{'+' if minutes > 0 else '-'}{hours:02d}:{mins:02d}" + + +def _when(transition: DstTransitionDict) -> str: + seconds = transition["time"] + if not 0 <= seconds < 86400 or seconds % 60: + raise ValueError("the switch takes a summer-time change at a time of day (HH:MM)") + clock = f"{seconds // 3600:02d}:{seconds % 3600 // 60:02d}" + weekday, month = _DAYS[transition["weekday"]], _MONTHS[transition["month"] - 1] + return f"{transition['week']} {weekday} {month} {clock}" + + +def dst_command(zone: str) -> tuple[str, str | None]: + """*zone* as the switch keeps it: the zone token and the ``system-time dst`` line. + + The line is None for a zone without summer time. A zone whose "summer" time is + behind its standard time (Europe/Dublin) is written the other way round: the + switch only puts the clock forward. + + :raises ValueError: for a zone the switch cannot show. + """ + rule = posix_tz(zone) + parts = parse_posix_tz(rule) if rule else None + if parts is None: + raise ValueError(f"no summer-time rule the switch can take for {zone}") + std, summer = parts["utc_offset"], parts["dst_offset"] + start, end = parts["dst_start"], parts["dst_end"] + if summer is not None and summer < std: + std, summer, start, end = summer, std, end, start + token = zone_token(std) + if summer is None: + return token, None + if start is None or end is None: + raise ValueError(f"{zone} has summer time without a rule for it") + shift = (summer - std) // 60 + return token, f"system-time dst recurring {_when(start)} {_when(end)} {shift}" + + +def _check_servers(servers: Sequence[str]) -> None: + if len(servers) > MAX_SERVERS: + raise ValueError(f"the switch takes at most {MAX_SERVERS} NTP servers, not {len(servers)}") + for server in servers: + try: + ipaddress.IPv4Address(server) + except ValueError: + raise ValueError( + f"the switch takes NTP servers as IPv4 addresses only, not {server!r}" + ) from None + + +def _ntp_command(zone: str, servers: Sequence[str], rate: int) -> str: + backup = servers[1] if len(servers) > 1 else servers[0] + return f"system-time ntp {zone} {servers[0]} {backup} {rate}" + + +class JetstreamTimeSyncMixin(TimeSyncMixin): + """``get_time_sync`` and ``configure_time_sync`` over the switch's CLI.""" + + time_sync_writes: ClassVar[frozenset[str]] = frozenset({"ntp_servers", "timezone"}) + + #: The zone a running configure_time_sync was asked for: its servers step + #: writes the ``ntp`` line with that zone's offset already. + _zone_asked: str | None = None + + if TYPE_CHECKING: # pragma: no cover - the driver's own helpers + + def _send_command(self, command: str | list[str]) -> str: ... + def _enter_config_mode(self) -> None: ... + def _exit_config_mode(self) -> None: ... + def _apply_config_lines(self, config_text: str) -> list[str]: ... + def _save_config(self) -> None: ... + + def get_time_sync(self) -> TimeSyncDict: + """The servers of the ``system-time ntp`` line; no zone name, no sync state. + + The switch shows neither whether its last fetch worked nor a zone name. + """ + line = parse_ntp_line(self._send_command("show running-config")) + return { + "ntp_servers": line.servers if line else [], + "timezone": None, + "synchronized": None, + "daemon": None, + } + + def configure_time_sync( + self, ntp_servers: Sequence[str] | None = None, timezone: str | None = None + ) -> FixResultDict: + """The template's steps; servers and zone share one ``ntp`` line.""" + self._zone_asked = timezone + try: + return TimeSyncMixin.configure_time_sync(self, ntp_servers, timezone) + finally: + self._zone_asked = None + + def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict: + _check_servers(servers) + line = parse_ntp_line(self._send_command("show running-config")) + if self._zone_asked is not None: + zone = dst_command(self._zone_asked)[0] + else: + zone = line.zone if line else "UTC" + if line and _same_zone(line.zone, zone) and _same(line.servers, servers): + return {"ok": True, "output": "the switch already has these servers"} + rate = line.rate if line else DEFAULT_FETCHING_RATE + self._apply_time_commands([_ntp_command(zone, servers, rate)]) + return {"ok": True, "output": f"NTP servers set: {', '.join(servers)}"} + + def _write_time_zone(self, zone: str) -> FixStepOutcomeDict: + token, dst = dst_command(zone) + running = self._send_command("show running-config") + line = parse_ntp_line(running) + if line is None: + raise ValueError( + "the switch keeps its time zone with its NTP servers and has none:" + " name the NTP servers too" + ) + commands = ( + [] if _same_zone(line.zone, token) else [_ntp_command(token, line.servers, line.rate)] + ) + current = _dst_line(running) + if dst is None and current is not None: + commands.append("no system-time dst") + elif dst is not None and (current or "").lower() != dst.lower(): + commands.append(dst) + if not commands: + return {"ok": True, "output": f"the switch is already in {zone}"} + self._apply_time_commands(commands) + return {"ok": True, "output": f"time zone set: {token}, " + (dst or "no summer time")} + + def _apply_time_commands(self, commands: list[str]) -> None: + """Send *commands* in ``configure`` and save them; raise on a refused one.""" + self._enter_config_mode() + try: + errors = self._apply_config_lines("\n".join(commands)) + finally: + self._exit_config_mode() + if errors: + raise RuntimeError("the switch refused:\n" + "\n".join(errors)) + self._save_config() + + +def _same(have: Sequence[str], want: Sequence[str]) -> bool: + return [s.lower() for s in have] == [s.lower() for s in want] + + +def _same_zone(have: str, want: str) -> bool: + minutes = _zone_minutes(have) + return minutes is not None and minutes == _zone_minutes(want) + + +__all__ = ["JetstreamTimeSyncMixin", "NtpLine", "dst_command", "parse_ntp_line", "zone_token"] diff --git a/napalm_tplink_jetstream/tplink_jetstream.py b/napalm_tplink_jetstream/tplink_jetstream.py index 208dc35..96968ea 100644 --- a/napalm_tplink_jetstream/tplink_jetstream.py +++ b/napalm_tplink_jetstream/tplink_jetstream.py @@ -40,6 +40,7 @@ from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutExc from napalm_tplink_jetstream._ssh import netmiko_connect_args from napalm_tplink_jetstream.parsers import parse_snmp_communities, parse_snmp_community_access +from napalm_tplink_jetstream.time_sync import JetstreamTimeSyncMixin logger = logging.getLogger(__name__) @@ -47,7 +48,9 @@ logger = logging.getLogger(__name__) _PASSWORD_NOT_SHOWN = "" # nosec B105 -class TPLinkJetstreamDriver(ConfigLifecycleMixin, SnmpAgentMixin, SwitchDriver): +class TPLinkJetstreamDriver( + JetstreamTimeSyncMixin, ConfigLifecycleMixin, SnmpAgentMixin, SwitchDriver +): """NAPALM driver for TP-Link Jetstream managed switches.""" VENDOR = "TP-Link" @@ -1459,23 +1462,8 @@ class TPLinkJetstreamDriver(ConfigLifecycleMixin, SnmpAgentMixin, SwitchDriver): } def get_ntp_servers(self) -> dict[str, dict]: - """Return configured NTP servers. - - Extracts the server list from the running configuration line:: - - system-time ntp [ ...] - """ - running = self._send_command("show running-config") - servers: dict[str, dict] = {} - for line in running.splitlines(): - m = re.match(r"^system-time\s+ntp\s+\S+\s+(.*)", line.strip(), re.I) - if m: - tokens = m.group(1).split() - # Last token is the update interval (numeric), rest are servers - server_tokens = [t for t in tokens if not t.isdigit()] - for srv in server_tokens: - servers[srv] = {} - return servers + """The servers of the ``system-time ntp`` line, as ``get_time_sync`` reads them.""" + return {server: {} for server in self.get_time_sync()["ntp_servers"]} def get_ntp_peers(self) -> dict[str, dict]: """Return NTP peers (same as servers on TP-Link Jetstream).""" diff --git a/pyproject.toml b/pyproject.toml index caa8961..b9ea412 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.21.1", + "napalm-device-types>=4.35.0", "netmiko>=4.0.0", "paramiko>=5.0.0", # CVE-2026-44405 "netaddr>=0.7.10", diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index a32a5ef..4e0b135 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -27,7 +27,7 @@ "napalm_tplink_jetstream.tplink_jetstream" ], "python_file_lines": { - "napalm_tplink_jetstream/tplink_jetstream.py": 1999 + "napalm_tplink_jetstream/tplink_jetstream.py": 1987 }, "untyped_public": [] } diff --git a/tests/unit/test_time_sync.py b/tests/unit/test_time_sync.py new file mode 100644 index 0000000..f023cea --- /dev/null +++ b/tests/unit/test_time_sync.py @@ -0,0 +1,296 @@ +"""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 + ``, 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 == []