Skip to content

Commit

Permalink
Catch NTPExceptions when requesting time from timeserver
Browse files Browse the repository at this point in the history
Fixes #256. When the request times out, this exception is thrown. For
now, just default to the local time. The timeout parameter in the
request() function of the NTPClient can also be adjusted. This can be
extended for (hopefully) better reliability of the NTP request.
  • Loading branch information
jdholtz committed May 2, 2024
1 parent d86ea6b commit 9cf88c6
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def get_current_time() -> datetime:

try:
response = c.request(NTP_SERVER, version=3)
except socket.gaierror:
except (socket.gaierror, ntplib.NTPException):
logger.debug("Error requesting time from NTP server. Using local time")
return datetime.utcnow()

Expand Down
7 changes: 5 additions & 2 deletions tests/unit/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,11 @@ def test_get_current_time_returns_a_datetime_from_ntp_server(mocker: MockerFixtu
assert utils.get_current_time() == datetime(1999, 12, 31, 23, 59, 59)


def test_get_current_time_returns_local_datetime_on_failed_request(mocker: MockerFixture) -> None:
mocker.patch("ntplib.NTPClient.request", side_effect=socket.gaierror)
@pytest.mark.parametrize("exception", [socket.gaierror, ntplib.NTPException])
def test_get_current_time_returns_local_datetime_on_failed_request(
mocker: MockerFixture, exception: Exception
) -> None:
mocker.patch("ntplib.NTPClient.request", side_effect=exception)
mock_datetime = mocker.patch("lib.utils.datetime")
mock_datetime.utcnow.return_value = datetime(1999, 12, 31, 18, 59, 59)

Expand Down

0 comments on commit 9cf88c6

Please sign in to comment.