"""Time sync on Windows: w32time and the time zone over PowerShell Remoting (NetOrk/netork#2367). The reading is one script whose JSON a fake host answers, starting from tests/fixtures/synthetic/time_sync.json (a workgroup host as Windows installs it: ``time.windows.com,0x9``, Type NTP). The fake host applies what the write scripts say, so ``verify`` reads back what a host would. The status text is ``w32tm /query /status`` as Windows prints it, in English and in German. """ from __future__ import annotations import json import re from pathlib import Path from typing import Any import pytest from napalm_device_types import TimeSyncMixin from napalm_windows import WindowsDriver from napalm_windows import time_sync as mod from napalm_windows.time_zones import IANA_TO_WINDOWS, WINDOWS_TO_IANA, windows_time_zone from napalm_windows.transport import PowerShellError FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "time_sync.json" UNSYNCED = ( "Leap Indicator: 3(not synchronized)\nStratum: 0 (unspecified)\n" "Precision: -23 (119.209ns per tick)\nSource: Local CMOS Clock\n" ) GERMAN = "Sprungindikator: 0(keine Warnung)\nStratum: 3 (Sekundärreferenz - synchr. über (S)NTP)\n" NOT_STARTED = "Folgender Fehler ist aufgetreten: Der Dienst wurde nicht gestartet. (0x80070426)\n" class FakeHost: """Answers the reading from *state*; applies the write scripts to it.""" def __init__(self, **changes: Any) -> None: self.state: dict[str, Any] = {**json.loads(FIXTURE.read_text()), **changes} self.sent: list[str] = [] self.fail: str | None = None self.is_open = True def run(self, script: str) -> str: self.sent.append(script) if script == mod._PS_TIME_SYNC: return json.dumps(self.state) if self.fail: raise PowerShellError(self.fail) peers = re.search(r"-Name NtpServer -Value '([^']*)'", script) if peers and "-Name Type -Value 'NTP'" in script and "w32tm /config /update" in script: self.state.update(type="NTP", ntp_server=peers.group(1), service="Running") zone = re.search(r"Set-TimeZone -Id '([^']*)'", script) if zone: self.state.update(zone=zone.group(1), dst_off="0") marker = re.search(r"-Name IanaTimeZone -Value '([^']*)'", script) if marker: self.state["iana_zone"] = marker.group(1) return "" def close(self) -> None: self.is_open = False @property def writes(self) -> list[str]: return [s for s in self.sent if s != mod._PS_TIME_SYNC] def _driver(**changes: Any) -> tuple[WindowsDriver, FakeHost]: host = FakeHost(**changes) d = WindowsDriver("win01", "admin", "secret") d._transport = host # type: ignore[assignment] return d, host # --------------------------------------------------------------------------- # The zone table (CLDR windowsZones.xml, generated) # --------------------------------------------------------------------------- class TestZoneTable: def test_every_windows_zone_reads_back_as_itself(self): """The name a zone is read as is a name that writes that zone.""" for windows, iana in WINDOWS_TO_IANA.items(): assert IANA_TO_WINDOWS[iana] == windows def test_every_name_is_a_real_zone(self): from zoneinfo import ZoneInfo for name in [*WINDOWS_TO_IANA.values(), *IANA_TO_WINDOWS]: ZoneInfo(name) @pytest.mark.parametrize( ("iana", "windows"), [ ("Europe/Berlin", "W. Europe Standard Time"), ("Europe/Vienna", "W. Europe Standard Time"), ("Europe/London", "GMT Standard Time"), ("Asia/Kolkata", "India Standard Time"), # CLDR keeps Asia/Calcutta ("Asia/Calcutta", "India Standard Time"), ("Europe/Kyiv", "FLE Standard Time"), ("America/New_York", "Eastern Standard Time"), ("Etc/UTC", "UTC"), ("UTC", "UTC"), # a tzdata link to Etc/UTC ("CET", None), # not a zone CLDR maps ], ) def test_an_iana_name_as_windows_zone(self, iana, windows): assert windows_time_zone(iana) == windows def test_renamed_zones_read_as_their_current_name(self): assert WINDOWS_TO_IANA["India Standard Time"] == "Asia/Kolkata" assert WINDOWS_TO_IANA["FLE Standard Time"] == "Europe/Kyiv" assert WINDOWS_TO_IANA["Greenland Standard Time"] == "America/Nuuk" # A merge in tzdata is no rename: Reykjavik keeps its name. assert WINDOWS_TO_IANA["Greenwich Standard Time"] == "Atlantic/Reykjavik" # --------------------------------------------------------------------------- # Reading # --------------------------------------------------------------------------- class TestRead: def test_is_offered_and_writes_both(self): assert issubclass(WindowsDriver, TimeSyncMixin) assert callable(WindowsDriver.get_time_sync) assert WindowsDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"}) def test_a_workgroup_host_as_installed(self): d, host = _driver() assert d.get_time_sync() == { "ntp_servers": ["time.windows.com"], "timezone": "Europe/Berlin", "synchronized": True, "daemon": "w32time", } assert host.sent == [mod._PS_TIME_SYNC] def test_servers_without_their_flags_in_order(self): d, _ = _driver(ntp_server="ntp1.example.org,0x8 10.0.0.1,0x8 ntp1.example.org,0x1") assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"] def test_a_domain_member_reports_the_servers_configured(self): d, _ = _driver(type="NT5DS") assert d.get_time_sync()["ntp_servers"] == ["time.windows.com"] assert d.get_time_sync()["daemon"] == "w32time" def test_group_policy_overrides_the_local_settings(self): d, _ = _driver(policy_type="NTP", policy_server="ntp.corp.example,0x8") assert d.get_time_sync()["ntp_servers"] == ["ntp.corp.example"] def test_nosync_has_no_source(self): d, _ = _driver(type="NoSync") assert d.get_time_sync()["ntp_servers"] == [] @pytest.mark.parametrize( ("service", "status", "synchronized"), [ ("Running", UNSYNCED, False), ("Running", GERMAN, True), ("Running", NOT_STARTED, None), ("Running", None, None), ("Stopped", None, False), (None, None, None), ], ) def test_synchronized_from_the_leap_indicator(self, service, status, synchronized): d, _ = _driver(service=service, status=status) assert d.get_time_sync()["synchronized"] is synchronized @pytest.mark.parametrize( ("zone", "marker", "iana"), [ ("W. Europe Standard Time", "Europe/Vienna", "Europe/Vienna"), ("GMT Standard Time", "Europe/Vienna", "Europe/London"), # changed by hand since ("W. Europe Standard Time\u0000\u0000", None, "Europe/Berlin"), ("Some Custom Standard Time", None, None), ("", None, None), ], ) def test_the_zone(self, zone, marker, iana): d, _ = _driver(zone=zone, iana_zone=marker) assert d.get_time_sync()["timezone"] == iana def test_summer_time_switched_off_is_not_the_zone(self): d, _ = _driver(dst_off="1", iana_zone="Europe/Berlin") assert d.get_time_sync()["timezone"] is None def test_a_cut_reading_raises(self): d, host = _driver() host.run = lambda script: "" # type: ignore[method-assign] with pytest.raises(ValueError): d.get_time_sync() # --------------------------------------------------------------------------- # Writing # --------------------------------------------------------------------------- class TestWriteServers: def test_sets_manual_peers_in_client_mode(self): d, host = _driver() result = d.configure_time_sync(ntp_servers=["ntp1.example.org", "10.0.0.1"]) assert result["success"], result["output"] (script,) = host.writes assert "-Name NtpServer -Value 'ntp1.example.org,0x8 10.0.0.1,0x8'" in script assert "-Name Type -Value 'NTP'" in script assert "Start-Service -Name W32Time" in script assert script.index("Set-ItemProperty") < script.index("w32tm /config /update") assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"] def test_the_same_servers_again_write_nothing(self): d, host = _driver(ntp_server="NTP1.example.org,0x8") result = d.configure_time_sync(ntp_servers=["ntp1.example.org"]) assert result["success"], result["output"] assert host.writes == [] def test_nosync_with_the_same_servers_is_written(self): d, host = _driver(type="NoSync", ntp_server="ntp1.example.org,0x8") assert d.configure_time_sync(ntp_servers=["ntp1.example.org"])["success"] assert len(host.writes) == 1 @pytest.mark.parametrize("kind", ["NT5DS", "AllSync"]) def test_a_domain_member_is_refused(self, kind): d, host = _driver(type=kind) result = d.configure_time_sync(ntp_servers=["10.0.0.1"]) assert not result["success"] assert "domain" in result["steps"][0]["output"] assert host.writes == [] def test_group_policy_is_refused(self): d, host = _driver(policy_server="ntp.corp.example,0x8") result = d.configure_time_sync(ntp_servers=["10.0.0.1"]) assert not result["success"] assert "group policy" in result["steps"][0]["output"] assert host.writes == [] def test_a_failed_script_fails_the_step(self): d, host = _driver() host.fail = "w32tm /config: The service cannot be started (0x80070422)" result = d.configure_time_sync(ntp_servers=["10.0.0.1"]) assert not result["success"] assert "0x80070422" in result["steps"][0]["output"] class TestWriteZone: def test_sets_the_windows_zone_and_remembers_the_name(self): d, host = _driver(zone="GMT Standard Time") result = d.configure_time_sync(timezone="Europe/Vienna") assert result["success"], result["output"] (script,) = host.writes assert "Set-TimeZone -Id 'W. Europe Standard Time'" in script assert "-Name IanaTimeZone -Value 'Europe/Vienna'" in script assert d.get_time_sync()["timezone"] == "Europe/Vienna" def test_the_same_windows_zone_only_remembers_the_name(self): d, host = _driver() result = d.configure_time_sync(timezone="Europe/Vienna") assert result["success"], result["output"] (script,) = host.writes assert "Set-TimeZone" not in script assert d.get_time_sync()["timezone"] == "Europe/Vienna" def test_the_same_zone_again_writes_nothing(self): d, host = _driver(iana_zone="Europe/Berlin") assert d.configure_time_sync(timezone="Europe/Berlin")["success"] assert host.writes == [] def test_summer_time_off_is_turned_on(self): d, host = _driver(dst_off="1", iana_zone="Europe/Berlin") result = d.configure_time_sync(timezone="Europe/Berlin") assert result["success"], result["output"] assert "Set-TimeZone -Id 'W. Europe Standard Time'" in host.writes[0] def test_a_zone_windows_does_not_have_is_refused(self): d, host = _driver() result = d.configure_time_sync(timezone="CET") assert not result["success"] assert "no Windows time zone" in result["steps"][0]["output"] assert host.writes == [] def test_servers_and_zone_together(self): d, host = _driver() result = d.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="America/New_York") assert result["success"], result["output"] assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"] assert d.get_time_sync()["timezone"] == "America/New_York"