feat(time-sync): TimeSyncMixin, PosixTimeSyncMixin and the posix_tz helpers
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 19s
driver / types (pull_request) Successful in 57s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m14s
driver / lowest (pull_request) Successful in 38s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m23s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 19s
driver / types (pull_request) Successful in 57s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m14s
driver / lowest (pull_request) Successful in 38s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m23s
driver / publish (pull_request) Skipped
netOrk gets one list of NTP servers and a time zone per site and aligns every device that differs (NetOrk/netork#2360). The contract comes first, so the drivers can be built against it at the same time (#2361): TimeSyncMixin declares get_time_sync() -> TimeSyncDict (servers in the device's order, the zone as an IANA name, synchronised, the client) and carries configure_time_sync(ntp_servers=None, timezone=None) as a fix template: None leaves a value alone, the device ends up with exactly the servers given, and a verify step reads it back. time_sync_writes says which of the two values a driver writes; anything else, an unknown zone, a malformed server or an empty list is refused before anything is written. PosixTimeSyncMixin implements it over run_command for Linux-like hosts: one reading as the login user (timedatectl, chrony's configuration and chronyc, timedatectl show-timesync, ntpd and OpenNTPD), the zone through timedatectl set-timezone, chrony's servers in a file of their own with every other source commented out, systemd-timesyncd's in a drop-in that resets NTP= and empties FallbackNTP=. ntpd and OpenNTPD are read only. posix_tz moves here from netOrk, so OpenWrt can write the POSIX rule and a switch the UTC offset and summer-time rule (parse_posix_tz). It reads the tzdata package, now a dependency. Release 4.35.0: the drivers that implement it need it on PyPI.
This commit is contained in:
1 parent
278a707157
commit
073087da69
12 files changed
+2032
-2
No files matched your search
@@ -0,0 +1,161 @@
|
||||
"""A time zone as a device takes it: an IANA name, a POSIX TZ rule, or its parts.
|
||||
|
||||
The wire carries IANA names (``Europe/Berlin``). OpenWrt hands ``TZ`` to libc and
|
||||
wants the rule itself (``CET-1CEST,M3.5.0,M10.5.0/3``); a switch wants a UTC
|
||||
offset and the summer-time rule. The rule is the footer of the zone's TZif file
|
||||
from the ``tzdata`` package (moved here from netOrk's ``core/posix_tz.py`` for
|
||||
NetOrk/netork#2361).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib.resources import files
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
PosixTzDict,
|
||||
UnknownTimezone,
|
||||
is_iana_zone,
|
||||
is_posix_tz,
|
||||
parse_posix_tz,
|
||||
posix_tz,
|
||||
)
|
||||
|
||||
BERLIN = "CET-1CEST,M3.5.0,M10.5.0/3"
|
||||
|
||||
|
||||
def _zones() -> list[str]:
|
||||
return files("tzdata").joinpath("zones").read_text().split()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("zone", "rule"),
|
||||
[
|
||||
("Europe/Berlin", BERLIN),
|
||||
("America/New_York", "EST5EDT,M3.2.0,M11.1.0"),
|
||||
("America/Sao_Paulo", "<-03>3"),
|
||||
("Australia/Lord_Howe", "<+1030>-10:30<+11>-11,M10.1.0,M4.1.0"),
|
||||
("Asia/Kolkata", "IST-5:30"),
|
||||
("UTC", "UTC0"),
|
||||
],
|
||||
)
|
||||
def test_an_iana_name_becomes_its_posix_rule(zone, rule):
|
||||
assert posix_tz(zone) == rule
|
||||
assert is_iana_zone(zone)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rule", [BERLIN, "<+03>-3", "EST5EDT,M3.2.0/2,M11.1.0/2", "UTC0"])
|
||||
def test_a_posix_string_is_taken_as_it_is(rule):
|
||||
assert posix_tz(rule) == rule
|
||||
assert not is_iana_zone(rule)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
["Mars/Olympus_Mons", "Europe", "../../etc/passwd", "/etc/localtime", "Europe/../UTC", ""],
|
||||
)
|
||||
def test_neither_a_zone_nor_a_rule_has_none(value):
|
||||
assert posix_tz(value) is None
|
||||
assert not is_iana_zone(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["UTC", "GMT0", BERLIN, "<-03>3", "IST-5:30"])
|
||||
def test_posix_strings(value):
|
||||
assert is_posix_tz(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["Europe/Berlin", "America/Argentina/Buenos_Aires", "", "CET-"])
|
||||
def test_not_posix_strings(value):
|
||||
assert not is_posix_tz(value)
|
||||
|
||||
|
||||
def test_every_zone_of_the_database_has_a_rule_the_check_accepts():
|
||||
# A caller tells an IANA name from a rule with is_posix_tz; it must never
|
||||
# take the database's own rule for a name.
|
||||
zones = _zones()
|
||||
missing = [z for z in zones if not is_posix_tz(posix_tz(z) or "")]
|
||||
assert len(zones) > 500
|
||||
assert missing == []
|
||||
|
||||
|
||||
def test_the_refusal_names_the_zone_in_plain_english():
|
||||
exc = UnknownTimezone("Mars/Olympus_Mons")
|
||||
|
||||
assert isinstance(exc, ValueError)
|
||||
assert exc.zone == "Mars/Olympus_Mons"
|
||||
assert "Mars/Olympus_Mons" in str(exc)
|
||||
assert "Europe/Berlin" in str(exc)
|
||||
|
||||
|
||||
class TestTheRuleInParts:
|
||||
"""What a switch takes: the standard offset and, where there is one, the summer-time rule."""
|
||||
|
||||
def test_berlin(self):
|
||||
assert parse_posix_tz(BERLIN) == PosixTzDict(
|
||||
std_name="CET",
|
||||
utc_offset=3600,
|
||||
dst_name="CEST",
|
||||
dst_offset=7200,
|
||||
dst_start={"month": 3, "week": 5, "weekday": 0, "time": 7200},
|
||||
dst_end={"month": 10, "week": 5, "weekday": 0, "time": 10800},
|
||||
)
|
||||
|
||||
def test_utc_has_no_summer_time(self):
|
||||
assert parse_posix_tz("UTC0") == {
|
||||
"std_name": "UTC",
|
||||
"utc_offset": 0,
|
||||
"dst_name": None,
|
||||
"dst_offset": None,
|
||||
"dst_start": None,
|
||||
"dst_end": None,
|
||||
}
|
||||
|
||||
@pytest.mark.parametrize("bare", ["UTC", "GMT"])
|
||||
def test_the_bare_names_openwrt_writes(self, bare):
|
||||
parts = parse_posix_tz(bare)
|
||||
assert parts is not None
|
||||
assert (parts["std_name"], parts["utc_offset"], parts["dst_name"]) == (bare, 0, None)
|
||||
|
||||
def test_sao_paulo_has_given_up_summer_time(self):
|
||||
parts = parse_posix_tz(posix_tz("America/Sao_Paulo") or "")
|
||||
assert parts is not None
|
||||
assert (parts["std_name"], parts["utc_offset"], parts["dst_offset"]) == (
|
||||
"-03",
|
||||
-10800,
|
||||
None,
|
||||
)
|
||||
|
||||
def test_lord_howe_moves_by_half_an_hour(self):
|
||||
parts = parse_posix_tz(posix_tz("Australia/Lord_Howe") or "")
|
||||
assert parts is not None
|
||||
assert (parts["utc_offset"], parts["dst_offset"]) == (37800, 39600)
|
||||
assert parts["dst_start"] == {"month": 10, "week": 1, "weekday": 0, "time": 7200}
|
||||
assert parts["dst_end"] == {"month": 4, "week": 1, "weekday": 0, "time": 7200}
|
||||
|
||||
def test_new_york_is_west_of_utc_and_gains_an_hour_by_default(self):
|
||||
parts = parse_posix_tz("EST5EDT,M3.2.0,M11.1.0")
|
||||
assert parts is not None
|
||||
assert (parts["utc_offset"], parts["dst_offset"]) == (-18000, -14400)
|
||||
|
||||
def test_a_transition_time_may_lie_outside_the_day(self):
|
||||
# Greenland's rule: a day's -1:00 and 0:00 (RFC 8536 3.3.1 allows -167..167 hours).
|
||||
parts = parse_posix_tz("<-02>2<-01>,M3.5.0/-1,M10.5.0/0")
|
||||
assert parts is not None
|
||||
assert parts["dst_start"] == {"month": 3, "week": 5, "weekday": 0, "time": -3600}
|
||||
assert parts["dst_end"] == {"month": 10, "week": 5, "weekday": 0, "time": 0}
|
||||
|
||||
def test_offsets_with_minutes_and_seconds(self):
|
||||
parts = parse_posix_tz("<+1245>-12:45<+1345>,M9.5.0/2:45,M4.1.0/3:45")
|
||||
assert parts is not None
|
||||
assert (parts["utc_offset"], parts["dst_offset"]) == (45900, 49500)
|
||||
assert parts["dst_start"] == {"month": 9, "week": 5, "weekday": 0, "time": 9900}
|
||||
|
||||
@pytest.mark.parametrize("rule", ["Europe/Berlin", "", "CET-", "CET-1CEST,J60,J300"])
|
||||
def test_what_it_cannot_take_apart_is_none(self, rule):
|
||||
# Julian-day rules are POSIX, but no zone of the database uses them.
|
||||
assert parse_posix_tz(rule) is None
|
||||
|
||||
def test_every_zone_of_the_database_comes_apart(self):
|
||||
broken = [z for z in _zones() if parse_posix_tz(posix_tz(z) or "") is None]
|
||||
assert broken == []
|
||||
@@ -0,0 +1,231 @@
|
||||
"""TimeSyncMixin: a device's time sources and time zone, read and set (NetOrk/netork#2361).
|
||||
|
||||
The application keeps one list of NTP servers and a zone per site, and aligns a
|
||||
device that differs. ``get_time_sync`` is declared only, so ``callable(getattr(
|
||||
driver, "get_time_sync", None))`` is the truthful answer; ``configure_time_sync``
|
||||
is a template of steps like every fix, and an API driver overrides it whole.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
from typing import ClassVar, get_type_hints
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
TIME_SYNC_VALUES,
|
||||
AccessPointDriver,
|
||||
DeviceTypeDriver,
|
||||
FirewallDriver,
|
||||
OSDriver,
|
||||
SwitchDriver,
|
||||
TimeSyncDict,
|
||||
TimeSyncMixin,
|
||||
UnknownTimezone,
|
||||
check_ntp_servers,
|
||||
)
|
||||
|
||||
|
||||
def test_the_shape():
|
||||
hints = get_type_hints(TimeSyncDict)
|
||||
assert hints == {
|
||||
"ntp_servers": list[str],
|
||||
"timezone": str | None,
|
||||
"synchronized": bool | None,
|
||||
"daemon": str | None,
|
||||
}
|
||||
|
||||
|
||||
def test_the_two_values_a_driver_may_write():
|
||||
assert frozenset({"ntp_servers", "timezone"}) == TIME_SYNC_VALUES
|
||||
|
||||
|
||||
def test_no_role_demands_it():
|
||||
for role in (AccessPointDriver, FirewallDriver, OSDriver, SwitchDriver, DeviceTypeDriver):
|
||||
assert not issubclass(role, TimeSyncMixin)
|
||||
|
||||
|
||||
def test_the_reading_is_declared_not_implemented():
|
||||
assert not hasattr(TimeSyncMixin, "get_time_sync")
|
||||
source = inspect.getsource(TimeSyncMixin)
|
||||
assert "def get_time_sync(self) -> TimeSyncDict" in source
|
||||
assert "time_sync_writes: ClassVar[frozenset[str]]" in source
|
||||
|
||||
|
||||
def test_the_template_takes_both_values_or_none_of_them():
|
||||
signature = inspect.signature(TimeSyncMixin.configure_time_sync)
|
||||
assert list(signature.parameters) == ["self", "ntp_servers", "timezone"]
|
||||
assert signature.parameters["ntp_servers"].default is None
|
||||
assert signature.parameters["timezone"].default is None
|
||||
|
||||
|
||||
class _Device(TimeSyncMixin):
|
||||
"""A device that keeps its values in memory and reads back what it was given."""
|
||||
|
||||
time_sync_writes: ClassVar[frozenset[str]] = frozenset({"ntp_servers", "timezone"})
|
||||
|
||||
def __init__(self, *, keeps_zone_name: bool = True, fail: str = "") -> None:
|
||||
self.state: TimeSyncDict = {
|
||||
"ntp_servers": ["0.pool.ntp.org"],
|
||||
"timezone": "UTC",
|
||||
"synchronized": True,
|
||||
"daemon": None,
|
||||
}
|
||||
self.keeps_zone_name = keeps_zone_name
|
||||
self.fail = fail
|
||||
self.calls: list[tuple[str, object]] = []
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
state = dict(self.state)
|
||||
if not self.keeps_zone_name:
|
||||
state["timezone"] = None
|
||||
return state # type: ignore[return-value]
|
||||
|
||||
def _write_ntp_servers(self, servers):
|
||||
self.calls.append(("ntp_servers", servers))
|
||||
if self.fail == "ntp_servers":
|
||||
return {"ok": False, "output": "refused"}
|
||||
self.state["ntp_servers"] = list(servers)
|
||||
return {"ok": True, "output": "written"}
|
||||
|
||||
def _write_time_zone(self, zone):
|
||||
self.calls.append(("timezone", zone))
|
||||
self.state["timezone"] = zone
|
||||
return {"ok": True, "output": f"zone {zone}"}
|
||||
|
||||
|
||||
class TestConfigureTimeSync:
|
||||
def test_both_values_then_a_check(self):
|
||||
device = _Device()
|
||||
result = device.configure_time_sync(["ntp1.example.org", "10.0.0.1"], "Europe/Berlin")
|
||||
|
||||
assert result["success"] is True
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
|
||||
assert device.calls == [
|
||||
("ntp_servers", ["ntp1.example.org", "10.0.0.1"]),
|
||||
("timezone", "Europe/Berlin"),
|
||||
]
|
||||
|
||||
def test_none_leaves_a_value_alone(self):
|
||||
device = _Device()
|
||||
result = device.configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
assert result["success"] is True
|
||||
assert device.calls == [("timezone", "Europe/Berlin")]
|
||||
assert device.state["ntp_servers"] == ["0.pool.ntp.org"]
|
||||
|
||||
def test_servers_alone(self):
|
||||
device = _Device()
|
||||
assert device.configure_time_sync(["ntp1.example.org"])["success"] is True
|
||||
assert device.calls == [("ntp_servers", ["ntp1.example.org"])]
|
||||
|
||||
def test_an_unknown_zone_is_refused_before_anything_is_written(self):
|
||||
device = _Device()
|
||||
with pytest.raises(UnknownTimezone, match="Mars/Olympus_Mons"):
|
||||
device.configure_time_sync(["ntp1.example.org"], "Mars/Olympus_Mons")
|
||||
assert device.calls == []
|
||||
|
||||
def test_a_posix_rule_is_not_a_zone_on_the_wire(self):
|
||||
with pytest.raises(UnknownTimezone):
|
||||
_Device().configure_time_sync(timezone="CET-1CEST,M3.5.0,M10.5.0/3")
|
||||
|
||||
def test_a_value_the_driver_cannot_write_is_refused_before_anything_is_written(self):
|
||||
class Bmc(_Device):
|
||||
time_sync_writes = frozenset({"ntp_servers"})
|
||||
|
||||
device = Bmc()
|
||||
with pytest.raises(ValueError, match="timezone"):
|
||||
device.configure_time_sync(["ntp1.example.org"], "Europe/Berlin")
|
||||
assert device.calls == []
|
||||
|
||||
def test_a_driver_that_names_nothing_it_writes_writes_nothing(self):
|
||||
class Silent(TimeSyncMixin):
|
||||
"""Mixes the contract in and never says what it writes."""
|
||||
|
||||
with pytest.raises(ValueError, match="ntp_servers"):
|
||||
Silent().configure_time_sync(["ntp1.example.org"])
|
||||
|
||||
def test_nothing_asked_is_a_mistake(self):
|
||||
with pytest.raises(ValueError, match="nothing"):
|
||||
_Device().configure_time_sync()
|
||||
|
||||
def test_a_failed_step_stops_the_rest(self):
|
||||
device = _Device(fail="ntp_servers")
|
||||
result = device.configure_time_sync(["ntp1.example.org"], "Europe/Berlin")
|
||||
|
||||
assert result["success"] is False
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers"]
|
||||
assert device.calls == [("ntp_servers", ["ntp1.example.org"])]
|
||||
|
||||
def test_the_check_reads_back_what_was_written(self):
|
||||
class Stubborn(_Device):
|
||||
def _write_ntp_servers(self, servers):
|
||||
self.calls.append(("ntp_servers", servers))
|
||||
return {"ok": True, "output": "written"} # and nothing changed
|
||||
|
||||
result = Stubborn().configure_time_sync(["ntp1.example.org"])
|
||||
|
||||
assert result["success"] is False
|
||||
verify = result["steps"][-1]
|
||||
assert verify["step"] == "verify"
|
||||
assert "0.pool.ntp.org" in verify["output"]
|
||||
|
||||
def test_the_check_names_the_zone_the_device_kept(self):
|
||||
class Elsewhere(_Device):
|
||||
def _write_time_zone(self, zone):
|
||||
return {"ok": True, "output": "set"} # and the device stayed on UTC
|
||||
|
||||
result = Elsewhere().configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["output"] == "the device is in the time zone UTC"
|
||||
|
||||
def test_servers_compare_without_case(self):
|
||||
class Lower(_Device):
|
||||
def get_time_sync(self):
|
||||
state = super().get_time_sync()
|
||||
state["ntp_servers"] = [s.lower() for s in state["ntp_servers"]]
|
||||
return state
|
||||
|
||||
assert Lower().configure_time_sync(["NTP1.Example.org"])["success"] is True
|
||||
|
||||
def test_a_device_without_a_zone_name_is_not_checked_for_one(self):
|
||||
# A switch keeps an offset and a summer-time rule, not a name: it reads None.
|
||||
result = _Device(keeps_zone_name=False).configure_time_sync(timezone="Europe/Berlin")
|
||||
assert result["success"] is True
|
||||
|
||||
|
||||
class TestCheckNtpServers:
|
||||
def test_in_order_stripped_each_once(self):
|
||||
assert check_ntp_servers([" ntp1.example.org", "10.0.0.1", "NTP1.example.org", "::1"]) == [
|
||||
"ntp1.example.org",
|
||||
"10.0.0.1",
|
||||
"::1",
|
||||
]
|
||||
|
||||
def test_none_at_all_is_refused(self):
|
||||
# A device without a source drifts; leaving the value alone is None, not [].
|
||||
with pytest.raises(ValueError, match="at least one"):
|
||||
check_ntp_servers([])
|
||||
with pytest.raises(ValueError, match="at least one"):
|
||||
check_ntp_servers([" "])
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
[
|
||||
"ntp1.example.org iburst",
|
||||
"-ntp.example.org",
|
||||
"ntp1.example.org\nserver evil",
|
||||
"ntp;reboot",
|
||||
"$(id)",
|
||||
"a" * 254,
|
||||
],
|
||||
)
|
||||
def test_only_a_host_name_or_an_address(self, bad):
|
||||
with pytest.raises(ValueError, match="not a host name or address"):
|
||||
check_ntp_servers([bad])
|
||||
|
||||
def test_a_string_is_not_a_list_of_servers(self):
|
||||
with pytest.raises(TypeError):
|
||||
check_ntp_servers("ntp1.example.org") # type: ignore[arg-type]
|
||||
@@ -0,0 +1,543 @@
|
||||
"""Time sync on a POSIX host, over the command channel: chrony, systemd-timesyncd, timedatectl.
|
||||
|
||||
The reading is run by a real ``sh`` over a directory tree that stands in for the
|
||||
host, with ``timedatectl``, ``systemctl`` and ``chronyc`` replaced by scripts that
|
||||
keep a log -- so the shell itself is tested, not a hand-written copy of its output.
|
||||
``sed`` and ``install`` are the real ones, so the files the writes leave are what a
|
||||
host would get (NetOrk/netork#2361).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import PosixTimeSyncMixin, UnknownTimezone, parse_time_sync
|
||||
from napalm_device_types.channel import CommandResult
|
||||
from napalm_device_types.time_sync_posix import (
|
||||
chrony_synchronized,
|
||||
parse_key_values,
|
||||
timesyncd_servers,
|
||||
)
|
||||
|
||||
# What the tools print, as recorded.
|
||||
|
||||
TIMEDATECTL = """\
|
||||
Timezone=Europe/Berlin
|
||||
LocalRTC=no
|
||||
CanNTP=yes
|
||||
NTP=yes
|
||||
NTPSynchronized=yes
|
||||
TimeUSec=Wed 2026-11-11 14:23:16 CET
|
||||
RTCTimeUSec=Wed 2026-11-11 13:23:16 CET
|
||||
"""
|
||||
|
||||
#: Ubuntu 24.04 without any server configured: only the compiled-in fallback.
|
||||
TIMESYNC_FALLBACK = """\
|
||||
FallbackNTPServers=ntp.ubuntu.com
|
||||
ServerName=ntp.ubuntu.com
|
||||
ServerAddress=91.189.91.157
|
||||
RootDistanceMaxUSec=5s
|
||||
PollIntervalMinUSec=32s
|
||||
PollIntervalMaxUSec=34min 8s
|
||||
PollIntervalUSec=34min 8s
|
||||
NTPMessage={ Leap=0, Version=4, Mode=4, Stratum=2, Precision=-24, RootDelay=42.190ms, RootDispersion=1.190ms, Reference=84A36001, Ignored=no, PacketCount=119, Jitter=7.481ms }
|
||||
Frequency=455471
|
||||
"""
|
||||
|
||||
TIMESYNC_CONFIGURED = """\
|
||||
LinkNTPServers=192.168.1.1
|
||||
SystemNTPServers=ntp1.example.org ntp2.example.org
|
||||
FallbackNTPServers=0.debian.pool.ntp.org 1.debian.pool.ntp.org
|
||||
ServerName=ntp1.example.org
|
||||
"""
|
||||
|
||||
CHRONYC_SYNCED = """\
|
||||
MS Name/IP address Stratum Poll Reach LastRx Last sample
|
||||
===============================================================================
|
||||
^- 162.159.200.123 3 6 377 41 +814us[ +814us] +/- 14ms
|
||||
^* 192.168.1.1 2 6 377 40 -45us[ -63us] +/- 10ms
|
||||
"""
|
||||
|
||||
CHRONYC_UNSYNCED = """\
|
||||
MS Name/IP address Stratum Poll Reach LastRx Last sample
|
||||
===============================================================================
|
||||
^? 162.159.200.123 0 6 0 - +0ns[ +0ns] +/- 0ns
|
||||
"""
|
||||
|
||||
#: Debian 12's chrony.conf, comments shortened, its directories under the test's root.
|
||||
DEBIAN_CHRONY_CONF = """\
|
||||
# Welcome to the chrony configuration file. See chrony.conf(5) for more
|
||||
# information about usable directives.
|
||||
|
||||
# Include configuration files found in /etc/chrony/conf.d.
|
||||
confdir {root}/etc/chrony/conf.d
|
||||
|
||||
# Use Debian vendor zone.
|
||||
pool 2.debian.pool.ntp.org iburst
|
||||
|
||||
# Use time sources from DHCP.
|
||||
sourcedir {root}/run/chrony-dhcp
|
||||
|
||||
# Use NTP sources found in /etc/chrony/sources.d.
|
||||
sourcedir {root}/etc/chrony/sources.d
|
||||
|
||||
keyfile /etc/chrony/chrony.keys
|
||||
driftfile /var/lib/chrony/chrony.drift
|
||||
rtcsync
|
||||
makestep 1 3
|
||||
leapsectz right/UTC
|
||||
"""
|
||||
|
||||
TIMEDATECTL_TOOL = """#!/bin/sh
|
||||
echo "timedatectl $*" >> "$LOG"
|
||||
case "$1" in
|
||||
show) cat "$FIX/timedatectl" ;;
|
||||
show-timesync) [ -f "$FIX/timesync" ] && cat "$FIX/timesync" ;;
|
||||
set-timezone)
|
||||
[ "$2" = "$REFUSE_ZONE" ] && { echo "Failed to set time zone: Invalid or not installed time zone '$2'" >&2; exit 1; }
|
||||
sed -i "s#^Timezone=.*#Timezone=$2#" "$FIX/timedatectl" ;;
|
||||
esac
|
||||
"""
|
||||
|
||||
SYSTEMCTL_TOOL = """#!/bin/sh
|
||||
echo "systemctl $*" >> "$LOG"
|
||||
case "$1" in
|
||||
is-active)
|
||||
u=${2%.service}
|
||||
case " $ACTIVE " in *" $u "*) echo active ;; *) echo inactive; exit 3 ;; esac ;;
|
||||
restart)
|
||||
[ -n "$FAIL_RESTART" ] && { echo "Job for $2 failed." >&2; exit 1; }
|
||||
if [ "$2" = systemd-timesyncd.service ]; then
|
||||
servers=$(sed -n 's/^NTP=\\(..*\\)$/\\1/p' "$DROPIN")
|
||||
printf 'SystemNTPServers=%s\\n' "$servers" > "$FIX/timesync"
|
||||
fi ;;
|
||||
esac
|
||||
"""
|
||||
|
||||
CHRONYC_TOOL = """#!/bin/sh
|
||||
echo "chronyc $*" >> "$LOG"
|
||||
case "$*" in
|
||||
"-n sources") [ -f "$FIX/chronyc" ] && cat "$FIX/chronyc" ;;
|
||||
"reload sources") exit "${RELOAD_EXIT:-0}" ;;
|
||||
esac
|
||||
"""
|
||||
|
||||
|
||||
class Host(PosixTimeSyncMixin):
|
||||
"""A host in a directory; every command is run by sh, root or not."""
|
||||
|
||||
def __init__(self, root: Path, *, active: str = "chrony") -> None:
|
||||
self.root = root
|
||||
etc = root / "etc"
|
||||
self.CHRONY_CONFIGS = (str(etc / "chrony/chrony.conf"), str(etc / "chrony.conf")) # type: ignore[misc]
|
||||
self.CHRONY_SOURCES_FILE = str(etc / "chrony/sources.d/netork.sources") # type: ignore[misc]
|
||||
self.CHRONY_INCLUDE_FILE = str(etc / "chrony.d/netork.conf") # type: ignore[misc]
|
||||
self.TIMESYNCD_DROPIN = str(etc / "systemd/timesyncd.conf.d/netork.conf") # type: ignore[misc]
|
||||
self.NTPD_CONFIGS = (str(etc / "ntpsec/ntp.conf"), str(etc / "ntp.conf")) # type: ignore[misc]
|
||||
self.OPENNTPD_CONFIGS = (str(etc / "openntpd/ntpd.conf"),) # type: ignore[misc]
|
||||
self.TIME_ZONE_SH = ( # type: ignore[misc]
|
||||
f"cat {etc}/timezone 2>/dev/null || readlink {etc}/localtime 2>/dev/null"
|
||||
)
|
||||
self.env = {
|
||||
"PATH": f"{root / 'bin'}:{os.environ['PATH']}",
|
||||
"LOG": str(root / "log"),
|
||||
"FIX": str(root / "fix"),
|
||||
"ACTIVE": active,
|
||||
"DROPIN": self.TIMESYNCD_DROPIN,
|
||||
}
|
||||
self.commands: list[tuple[str, bool]] = []
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None): # type: ignore[no-untyped-def]
|
||||
self.commands.append((command, privileged))
|
||||
done = subprocess.run(
|
||||
["sh", "-c", command],
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
env={**os.environ, **self.env},
|
||||
timeout=30,
|
||||
)
|
||||
return CommandResult(done.stdout.decode(), done.stderr.decode(), done.returncode)
|
||||
|
||||
def log(self) -> list[str]:
|
||||
log = self.root / "log"
|
||||
return log.read_text().splitlines() if log.exists() else []
|
||||
|
||||
def privileged(self) -> list[str]:
|
||||
return [c for c, p in self.commands if p]
|
||||
|
||||
|
||||
def _tool(root: Path, name: str, body: str) -> None:
|
||||
path = root / "bin" / name
|
||||
path.write_text(body)
|
||||
path.chmod(0o755)
|
||||
|
||||
|
||||
def _write(path: Path, text: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def root(tmp_path: Path) -> Path:
|
||||
for d in ("bin", "fix", "etc"):
|
||||
(tmp_path / d).mkdir()
|
||||
(tmp_path / "fix/timedatectl").write_text(TIMEDATECTL)
|
||||
for name, body in (
|
||||
("timedatectl", TIMEDATECTL_TOOL),
|
||||
("systemctl", SYSTEMCTL_TOOL),
|
||||
("chronyc", CHRONYC_TOOL),
|
||||
):
|
||||
_tool(tmp_path, name, body)
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def debian(root: Path) -> Path:
|
||||
"""chrony as Debian 12 ships it, with a source in each place it reads."""
|
||||
_write(root / "etc/chrony/chrony.conf", DEBIAN_CHRONY_CONF.format(root=root))
|
||||
_write(root / "etc/chrony/conf.d/local.conf", "server ntp-conf.example.org iburst\n")
|
||||
_write(root / "run/chrony-dhcp/eth0.sources", "server 192.168.1.1 iburst\n")
|
||||
_write(root / "etc/chrony/sources.d/other.sources", "server ntp-other.example.org\n")
|
||||
(root / "fix/chronyc").write_text(CHRONYC_SYNCED)
|
||||
return root
|
||||
|
||||
|
||||
def _no_timedatectl(root: Path) -> None:
|
||||
"""A host without systemd: the command is not there (the build host's must not answer)."""
|
||||
_tool(root, "timedatectl", '#!/bin/sh\necho "sh: timedatectl: not found" >&2\nexit 127\n')
|
||||
|
||||
|
||||
def _text(path: Path) -> str:
|
||||
return path.read_text()
|
||||
|
||||
|
||||
class TestParsing:
|
||||
def test_key_values(self):
|
||||
values = parse_key_values(TIMEDATECTL)
|
||||
assert values["Timezone"] == "Europe/Berlin"
|
||||
assert values["NTPSynchronized"] == "yes"
|
||||
|
||||
def test_timesyncd_uses_the_fallback_only_when_nothing_else_is_known(self):
|
||||
assert timesyncd_servers(parse_key_values(TIMESYNC_FALLBACK)) == ["ntp.ubuntu.com"]
|
||||
# runtime, then system, then link: the order timesyncd tries them in.
|
||||
assert timesyncd_servers(parse_key_values(TIMESYNC_CONFIGURED)) == [
|
||||
"ntp1.example.org",
|
||||
"ntp2.example.org",
|
||||
"192.168.1.1",
|
||||
]
|
||||
assert timesyncd_servers({}) == []
|
||||
|
||||
def test_chrony_is_synchronised_while_it_has_selected_a_source(self):
|
||||
assert chrony_synchronized(CHRONYC_SYNCED) is True
|
||||
assert chrony_synchronized(CHRONYC_UNSYNCED) is False
|
||||
assert chrony_synchronized("") is None
|
||||
|
||||
def test_chrony_without_a_main_configuration_has_no_sources(self):
|
||||
assert parse_time_sync("@@ts active\nchrony chrony active\n@@ts end\n")["ntp_servers"] == []
|
||||
|
||||
def test_a_reading_cut_short_raises(self):
|
||||
with pytest.raises(ValueError, match="cut short"):
|
||||
parse_time_sync("@@ts timedatectl\nTimezone=UTC\n")
|
||||
|
||||
|
||||
class TestReading:
|
||||
def test_chrony_names_its_sources_in_the_order_it_reads_them(self, debian: Path):
|
||||
host = Host(debian)
|
||||
assert host.get_time_sync() == {
|
||||
"ntp_servers": [
|
||||
"ntp-conf.example.org",
|
||||
"2.debian.pool.ntp.org",
|
||||
"192.168.1.1",
|
||||
"ntp-other.example.org",
|
||||
],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
}
|
||||
|
||||
def test_the_reading_is_one_round_trip_without_root(self, debian: Path):
|
||||
host = Host(debian)
|
||||
host.get_time_sync()
|
||||
assert [p for _, p in host.commands] == [False]
|
||||
|
||||
def test_chrony_says_whether_it_is_synchronised_not_the_kernel(self, debian: Path):
|
||||
(debian / "fix/chronyc").write_text(CHRONYC_UNSYNCED)
|
||||
assert Host(debian).get_time_sync()["synchronized"] is False
|
||||
|
||||
def test_without_an_answer_from_chronyc_the_kernel_says(self, debian: Path):
|
||||
(debian / "fix/chronyc").unlink()
|
||||
assert Host(debian).get_time_sync()["synchronized"] is True
|
||||
|
||||
def test_commented_and_other_directives_are_no_sources(self, root: Path):
|
||||
_write(
|
||||
root / "etc/chrony.conf",
|
||||
"#pool 2.rhel.pool.ntp.org iburst\n! server old.example.org\n"
|
||||
" server ntp1.example.org iburst\nrefclock PPS /dev/pps0\npeer peer.example.org\n",
|
||||
)
|
||||
reading = Host(root, active="chronyd").get_time_sync()
|
||||
assert reading["ntp_servers"] == ["ntp1.example.org", "peer.example.org"]
|
||||
assert reading["daemon"] == "chrony"
|
||||
|
||||
def test_an_include_pattern_is_followed(self, root: Path):
|
||||
_write(root / "etc/chrony.conf", f"include {root}/etc/chrony.d/*.conf\nmakestep 1 3\n")
|
||||
_write(root / "etc/chrony.d/pool.conf", "pool suse.pool.ntp.org iburst\n")
|
||||
assert Host(root).get_time_sync()["ntp_servers"] == ["suse.pool.ntp.org"]
|
||||
|
||||
def test_timesyncd(self, root: Path):
|
||||
(root / "fix/timesync").write_text(TIMESYNC_CONFIGURED)
|
||||
reading = Host(root, active="systemd-timesyncd").get_time_sync()
|
||||
assert reading["daemon"] == "systemd-timesyncd"
|
||||
assert reading["ntp_servers"] == ["ntp1.example.org", "ntp2.example.org", "192.168.1.1"]
|
||||
assert reading["synchronized"] is True
|
||||
|
||||
def test_ntpd(self, root: Path):
|
||||
_write(
|
||||
root / "etc/ntpsec/ntp.conf",
|
||||
"driftfile /var/lib/ntpsec/ntp.drift\npool 0.debian.pool.ntp.org iburst\n"
|
||||
"server 127.127.1.0\nserver ntp1.example.org iburst\nrestrict default kod\n",
|
||||
)
|
||||
reading = Host(root, active="ntpsec").get_time_sync()
|
||||
assert reading["daemon"] == "ntpd"
|
||||
assert reading["ntp_servers"] == ["0.debian.pool.ntp.org", "ntp1.example.org"]
|
||||
|
||||
def test_openntpd(self, root: Path):
|
||||
_write(
|
||||
root / "etc/openntpd/ntpd.conf",
|
||||
'servers pool.ntp.org\nserver ntp1.example.org\nconstraints from "https://www.google.com"\n',
|
||||
)
|
||||
reading = Host(root, active="openntpd").get_time_sync()
|
||||
assert reading["daemon"] == "openntpd"
|
||||
assert reading["ntp_servers"] == ["pool.ntp.org", "ntp1.example.org"]
|
||||
|
||||
def test_no_client_runs(self, root: Path):
|
||||
(root / "fix/timedatectl").write_text(
|
||||
TIMEDATECTL.replace("NTPSynchronized=yes", "NTPSynchronized=no")
|
||||
)
|
||||
assert Host(root, active="").get_time_sync() == {
|
||||
"ntp_servers": [],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": False,
|
||||
"daemon": None,
|
||||
}
|
||||
|
||||
def test_without_timedatectl_the_zone_comes_from_the_files(self, root: Path):
|
||||
_no_timedatectl(root)
|
||||
(root / "etc/localtime").symlink_to("/usr/share/zoneinfo/America/Sao_Paulo")
|
||||
reading = Host(root, active="").get_time_sync()
|
||||
assert reading["timezone"] == "America/Sao_Paulo"
|
||||
assert reading["synchronized"] is None
|
||||
|
||||
def test_etc_timezone_wins_over_the_link(self, root: Path):
|
||||
_no_timedatectl(root)
|
||||
(root / "etc/timezone").write_text("Australia/Lord_Howe\n")
|
||||
assert Host(root, active="").get_time_sync()["timezone"] == "Australia/Lord_Howe"
|
||||
|
||||
def test_a_copied_localtime_has_no_name(self, root: Path):
|
||||
_no_timedatectl(root)
|
||||
assert Host(root, active="").get_time_sync()["timezone"] is None
|
||||
|
||||
|
||||
class TestChronyServers:
|
||||
def test_exactly_these_servers(self, debian: Path):
|
||||
host = Host(debian)
|
||||
result = host.configure_time_sync(["ntp1.example.org", "10.0.0.1", "2.de.pool.ntp.org"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert _text(debian / "etc/chrony/sources.d/netork.sources") == (
|
||||
"server ntp1.example.org iburst\nserver 10.0.0.1 iburst\npool 2.de.pool.ntp.org iburst\n"
|
||||
)
|
||||
conf = _text(debian / "etc/chrony/chrony.conf")
|
||||
assert "\n#napalm-time-sync: pool 2.debian.pool.ntp.org iburst\n" in conf
|
||||
assert f"\n#napalm-time-sync: sourcedir {debian}/run/chrony-dhcp\n" in conf
|
||||
assert f"\nsourcedir {debian}/etc/chrony/sources.d\n" in conf
|
||||
assert f"\nconfdir {debian}/etc/chrony/conf.d\n" in conf
|
||||
assert _text(debian / "etc/chrony/conf.d/local.conf") == (
|
||||
"#napalm-time-sync: server ntp-conf.example.org iburst\n"
|
||||
)
|
||||
assert _text(debian / "etc/chrony/sources.d/other.sources") == (
|
||||
"#napalm-time-sync: server ntp-other.example.org\n"
|
||||
)
|
||||
# DHCP's own file is left alone: it is not read any more.
|
||||
assert _text(debian / "run/chrony-dhcp/eth0.sources") == "server 192.168.1.1 iburst\n"
|
||||
# The main configuration changed: chronyd reads it only when it starts.
|
||||
assert "systemctl restart chrony.service" in host.log()
|
||||
assert host.get_time_sync()["ntp_servers"] == [
|
||||
"ntp1.example.org",
|
||||
"10.0.0.1",
|
||||
"2.de.pool.ntp.org",
|
||||
]
|
||||
|
||||
def test_a_second_run_only_reloads_the_sources(self, debian: Path):
|
||||
Host(debian).configure_time_sync(["ntp1.example.org"])
|
||||
conf = _text(debian / "etc/chrony/chrony.conf")
|
||||
(debian / "log").unlink()
|
||||
|
||||
host = Host(debian)
|
||||
result = host.configure_time_sync(["ntp2.example.org", "ntp1.example.org"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert _text(debian / "etc/chrony/chrony.conf") == conf
|
||||
assert "chronyc reload sources" in host.log()
|
||||
assert not any(line.startswith("systemctl restart") for line in host.log())
|
||||
assert _text(debian / "etc/chrony/sources.d/netork.sources") == (
|
||||
"server ntp2.example.org iburst\nserver ntp1.example.org iburst\n"
|
||||
)
|
||||
|
||||
def test_a_chronyd_that_cannot_reload_sources_is_restarted(self, debian: Path):
|
||||
Host(debian).configure_time_sync(["ntp1.example.org"])
|
||||
host = Host(debian)
|
||||
host.env["RELOAD_EXIT"] = "1"
|
||||
assert host.configure_time_sync(["ntp2.example.org"])["success"] is True
|
||||
log = host.log()
|
||||
reload = log.index("chronyc reload sources")
|
||||
assert log[reload + 1] == "systemctl restart chrony.service"
|
||||
|
||||
def test_writes_are_root_s_and_root_reads_no_stdin(self, debian: Path):
|
||||
host = Host(debian)
|
||||
host.configure_time_sync(["ntp1.example.org"])
|
||||
staged = [c for c, p in host.commands if not p and "mktemp" in c]
|
||||
assert len(staged) == 1
|
||||
assert host.privileged()
|
||||
assert all("mktemp" not in c for c in host.privileged())
|
||||
|
||||
def test_rhel_without_a_directory_gets_an_include(self, root: Path):
|
||||
_write(
|
||||
root / "etc/chrony.conf",
|
||||
"pool 2.rhel.pool.ntp.org iburst\ndriftfile /var/lib/chrony/drift\n",
|
||||
)
|
||||
host = Host(root, active="chronyd")
|
||||
result = host.configure_time_sync(["ntp1.example.org"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
include = root / "etc/chrony.d/netork.conf"
|
||||
assert _text(include) == "server ntp1.example.org iburst\n"
|
||||
assert _text(root / "etc/chrony.conf") == (
|
||||
"#napalm-time-sync: pool 2.rhel.pool.ntp.org iburst\n"
|
||||
"driftfile /var/lib/chrony/drift\n"
|
||||
f"# napalm-time-sync: the time sources\ninclude {include}\n"
|
||||
)
|
||||
assert "systemctl restart chronyd.service" in host.log()
|
||||
|
||||
def test_an_include_that_already_takes_the_file_is_used(self, root: Path):
|
||||
_write(root / "etc/chrony.conf", f"include {root}/etc/chrony.d/*.conf\n")
|
||||
_write(root / "etc/chrony.d/pool.conf", "pool suse.pool.ntp.org iburst\n")
|
||||
host = Host(root)
|
||||
assert host.configure_time_sync(["ntp1.example.org"])["success"] is True
|
||||
assert _text(root / "etc/chrony.conf") == f"include {root}/etc/chrony.d/*.conf\n"
|
||||
assert (
|
||||
_text(root / "etc/chrony.d/pool.conf")
|
||||
== "#napalm-time-sync: pool suse.pool.ntp.org iburst\n"
|
||||
)
|
||||
assert _text(root / "etc/chrony.d/netork.conf") == "server ntp1.example.org iburst\n"
|
||||
|
||||
def test_a_confdir_takes_the_file_where_sources_d_is_not_read(self, root: Path):
|
||||
_write(
|
||||
root / "etc/chrony/chrony.conf",
|
||||
f"confdir {root}/etc/chrony/conf.d\npool a.pool.ntp.org\n",
|
||||
)
|
||||
host = Host(root)
|
||||
assert host.configure_time_sync(["ntp1.example.org"])["success"] is True
|
||||
assert _text(root / "etc/chrony/conf.d/netork.conf") == "server ntp1.example.org iburst\n"
|
||||
assert not (root / "etc/chrony/sources.d/netork.sources").exists()
|
||||
|
||||
def test_a_failed_restart_fails_the_step(self, debian: Path):
|
||||
host = Host(debian)
|
||||
host.env["FAIL_RESTART"] = "1"
|
||||
result = host.configure_time_sync(["ntp1.example.org"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "Job for chrony.service failed." in result["steps"][0]["output"]
|
||||
|
||||
def test_a_file_that_cannot_be_staged_is_not_installed(self, debian: Path):
|
||||
_tool(debian, "mktemp", "#!/bin/sh\necho 'mktemp: failed' >&2\nexit 1\n")
|
||||
host = Host(debian)
|
||||
result = host.configure_time_sync(["ntp1.example.org"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "cannot stage" in result["steps"][0]["output"]
|
||||
assert host.privileged() == []
|
||||
|
||||
def test_no_configuration_is_a_failed_step(self, root: Path):
|
||||
result = Host(root).configure_time_sync(["ntp1.example.org"])
|
||||
assert result["success"] is False
|
||||
assert "chrony" in result["steps"][0]["output"]
|
||||
|
||||
|
||||
class TestTimesyncdServers:
|
||||
def test_a_drop_in_with_exactly_these_servers(self, root: Path):
|
||||
(root / "fix/timesync").write_text(TIMESYNC_FALLBACK)
|
||||
host = Host(root, active="systemd-timesyncd")
|
||||
result = host.configure_time_sync(["ntp1.example.org", "10.0.0.1"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert _text(root / "etc/systemd/timesyncd.conf.d/netork.conf").endswith(
|
||||
"[Time]\nNTP=\nNTP=ntp1.example.org 10.0.0.1\nFallbackNTP=\n"
|
||||
)
|
||||
assert "systemctl restart systemd-timesyncd.service" in host.log()
|
||||
assert host.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"]
|
||||
|
||||
def test_servers_from_dhcp_stay_and_the_check_says_so(self, root: Path):
|
||||
(root / "fix/timesync").write_text(TIMESYNC_CONFIGURED)
|
||||
tool = (root / "bin/systemctl").read_text()
|
||||
(root / "bin/systemctl").write_text(
|
||||
tool.replace(
|
||||
"printf 'SystemNTPServers", "printf 'LinkNTPServers=192.168.1.1\\nSystemNTPServers"
|
||||
)
|
||||
)
|
||||
result = Host(root, active="systemd-timesyncd").configure_time_sync(["ntp1.example.org"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["step"] == "verify"
|
||||
assert "192.168.1.1" in result["steps"][-1]["output"]
|
||||
|
||||
|
||||
class TestOtherClients:
|
||||
@pytest.mark.parametrize("active", ["ntpsec", "openntpd", ""])
|
||||
def test_only_chrony_and_timesyncd_are_written(self, root: Path, active: str):
|
||||
host = Host(root, active=active)
|
||||
result = host.configure_time_sync(["ntp1.example.org"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "chrony and systemd-timesyncd" in result["steps"][0]["output"]
|
||||
assert host.privileged() == []
|
||||
|
||||
|
||||
class TestTimeZone:
|
||||
def test_timedatectl_sets_it(self, root: Path):
|
||||
host = Host(root, active="")
|
||||
result = host.configure_time_sync(timezone="America/Sao_Paulo")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert host.privileged() == ["timedatectl set-timezone America/Sao_Paulo"]
|
||||
assert host.get_time_sync()["timezone"] == "America/Sao_Paulo"
|
||||
|
||||
def test_a_zone_the_host_does_not_know_fails_the_step(self, root: Path):
|
||||
host = Host(root, active="")
|
||||
host.env["REFUSE_ZONE"] = "Europe/Kyiv"
|
||||
result = host.configure_time_sync(timezone="Europe/Kyiv")
|
||||
|
||||
assert result["success"] is False
|
||||
assert "Invalid or not installed time zone" in result["steps"][0]["output"]
|
||||
|
||||
def test_an_unknown_zone_is_refused_before_anything_is_written(self, debian: Path):
|
||||
host = Host(debian)
|
||||
with pytest.raises(UnknownTimezone):
|
||||
host.configure_time_sync(["ntp1.example.org"], "Mars/Olympus_Mons")
|
||||
assert host.commands == []
|
||||
|
||||
def test_both_at_once(self, debian: Path):
|
||||
host = Host(debian)
|
||||
result = host.configure_time_sync(["ntp1.example.org"], "UTC")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
|
||||
reading = host.get_time_sync()
|
||||
assert (reading["ntp_servers"], reading["timezone"]) == (["ntp1.example.org"], "UTC")
|
||||
|
||||
|
||||
def test_it_writes_both_values():
|
||||
assert frozenset({"ntp_servers", "timezone"}) == PosixTimeSyncMixin.time_sync_writes
|
||||
Reference in new issue
Block a user