"""get_ntp_stats on chrony (Proxmox VE's default) and on ntpd (#18).""" from __future__ import annotations from unittest.mock import patch import pytest # chrony 4.x, ``chronyc -n -c sources`` then ``chronyc -n -c sourcestats``, # behind the markers the driver's command prints. CHRONY = """\ CHRONY_SOURCES ^,*,192.168.1.1,2,6,377,8,-0.000012345,-0.000013000,0.012345678 ^,+,10.0.0.2,3,10,17,301,0.000250000,0.000251000,0.020000000 ^,?,10.0.0.3,0,6,0,-,0.000000000,0.000000000,0.000000000 CHRONY_SOURCESTATS 192.168.1.1,10,6,320,-0.012,0.150,-0.000001234,0.000045678 10.0.0.2,6,4,1200,0.003,0.400,0.000200000,0.000500000 """ # ntpd's ``ntpq -pn``: a candidate without tally mark keeps its leading space. NTPQ = """\ remote refid st t when poll reach delay offset jitter ============================================================================== *192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123 192.168.1.5 10.0.0.1 3 u 40 64 377 2.000 0.100 0.050 """ def _stats(driver, output): with patch.object(driver, "_exec_ssh_command", return_value=output): return driver.get_ntp_stats() class TestChrony: def test_every_source_is_reported(self, driver): assert [s["remote"] for s in _stats(driver, CHRONY)] == [ "192.168.1.1", "10.0.0.2", "10.0.0.3", ] def test_the_selected_source_is_synchronized(self, driver): stats = _stats(driver, CHRONY) assert [s["synchronized"] for s in stats] == [True, False, False] def test_fields_in_ntpq_units(self, driver): first = _stats(driver, CHRONY)[0] assert first == { "remote": "192.168.1.1", "referenceid": "", "synchronized": True, "stratum": 2, "type": "u", "when": "8", "hostpoll": 64, "reachability": 377, "delay": 0.0, "offset": pytest.approx(-0.013), "jitter": pytest.approx(0.045678), } def test_a_source_without_statistics_has_no_jitter(self, driver): last = _stats(driver, CHRONY)[2] assert last["jitter"] == 0.0 assert last["when"] == "-" assert last["reachability"] == 0 def test_the_command_asks_chrony_first(self, driver): with patch.object(driver, "_exec_ssh_command", return_value="") as exec_: driver.get_ntp_stats() assert "chronyc -n -c sources" in exec_.call_args[0][0] assert "ntpq -pn" in exec_.call_args[0][0] class TestNtpd: def test_a_peer_without_tally_mark_is_kept(self, driver): stats = _stats(driver, NTPQ) assert [s["remote"] for s in stats] == ["192.168.1.1", "192.168.1.5"] assert [s["synchronized"] for s in stats] == [True, False] assert stats[1]["stratum"] == 3