diff --git a/micropython/net/ntptime/manifest.py b/micropython/net/ntptime/manifest.py index 9f05d3439..417bbe61a 100644 --- a/micropython/net/ntptime/manifest.py +++ b/micropython/net/ntptime/manifest.py @@ -1,3 +1,3 @@ -metadata(description="NTP client.", version="0.2.0") +metadata(description="NTP client.", version="0.2.1") module("ntptime.py", opt=3) diff --git a/micropython/net/ntptime/ntptime.py b/micropython/net/ntptime/ntptime.py index 1201ca60f..2402a6276 100644 --- a/micropython/net/ntptime/ntptime.py +++ b/micropython/net/ntptime/ntptime.py @@ -19,6 +19,8 @@ def time(): msg = s.recv(48) finally: s.close() + if len(msg) < 48: + raise OSError(-1) val = struct.unpack("!I", msg[40:44])[0] # 2024-01-01 00:00:00 converted to an NTP timestamp diff --git a/micropython/net/ntptime/test_ntptime.py b/micropython/net/ntptime/test_ntptime.py new file mode 100644 index 000000000..2a868e824 --- /dev/null +++ b/micropython/net/ntptime/test_ntptime.py @@ -0,0 +1,75 @@ +import struct +import sys + + +class UDPSock: + def __init__(self, reply): + self._reply = reply + + def settimeout(self, timeout): + pass + + def sendto(self, data, addr): + pass + + def recv(self, n): + return self._reply + + def close(self): + pass + + +class FakeSocketMod: + AF_INET = 2 + SOCK_DGRAM = 2 + + def __init__(self, reply): + self._reply = reply + + def getaddrinfo(self, host, port): + return [(None, None, None, None, ("1.2.3.4", port))] + + def socket(self, *a, **k): + return UDPSock(self._reply) + + +sys.path.insert(0, "micropython/net/ntptime") +# ruff: noqa: E402 +import ntptime + + +def ntp_msg(ts=3913056000): + msg = bytearray(48) + struct.pack_into("!I", msg, 40, ts) + return bytes(msg) + + +def _patch(reply): + orig = ntptime.socket + ntptime.socket = FakeSocketMod(reply) + return orig + + +def test_time_ok(): + orig = _patch(ntp_msg()) + try: + t = ntptime.time() + assert isinstance(t, int) + finally: + ntptime.socket = orig + + +def test_time_short_raises(): + orig = _patch(b"short") + try: + try: + ntptime.time() + assert False, "expected OSError" + except OSError as e: + assert e.args == (-1,) + finally: + ntptime.socket = orig + + +test_time_ok() +test_time_short_raises() diff --git a/tools/ci.sh b/tools/ci.sh index 64c7c9607..7ee7eb4d1 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -58,6 +58,7 @@ function ci_package_tests_run { for test in \ micropython/drivers/storage/sdcard/sdtest.py \ micropython/umqtt.simple/test_umqtt_simple.py \ + micropython/net/ntptime/test_ntptime.py \ micropython/xmltok/test_xmltok.py \ python-ecosys/requests/test_requests.py \ python-stdlib/argparse/test_argparse.py \