Skip to content

Commit 66fb6f3

Browse files
fixed minor error in get device id with trailing \n char
1 parent 122e0b4 commit 66fb6f3

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

‎src/science_mode_4/general/general_device_id.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ def __init__(self, data: bytes):
2525

2626
if not data is None:
2727
self._result_error = ResultAndError(data[0])
28-
self._device_id = data[1:11].decode()
28+
# device id is a fixed 10 byte char array, null padded/terminated -> strip
29+
# the padding so callers don't get a trailing "\x00" in the string
30+
raw_device_id = data[1:11]
31+
end = raw_device_id.find(b"\x00")
32+
self._device_id = raw_device_id[:end if end != -1 else len(raw_device_id)].decode()
2933

3034

3135
@property

‎tests/test_general_device_id.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""Tests for PacketGeneralGetDeviceIdAck"""
2+
# pylint: disable=missing-function-docstring
3+
# test names are self-explanatory, docstrings would only restate them
4+
5+
from science_mode_4.general.general_device_id import PacketGeneralGetDeviceIdAck
6+
from science_mode_4.protocol.types import ResultAndError
7+
8+
9+
def _build_data(result_error: int, device_id: str) -> bytes:
10+
return bytes([result_error]) + device_id.encode().ljust(10, b"\x00")
11+
12+
13+
def test_device_id_strips_null_padding():
14+
# regression test: data[1:11].decode() used to include the null padding bytes
15+
# verbatim, so a device id shorter than 10 chars came back with a trailing "\x00"
16+
ack = PacketGeneralGetDeviceIdAck(_build_data(0, "220824001"))
17+
assert ack.device_id == "220824001"
18+
assert "\x00" not in ack.device_id
19+
20+
21+
def test_device_id_uses_full_field_when_not_null_terminated():
22+
ack = PacketGeneralGetDeviceIdAck(_build_data(0, "1234567890"))
23+
assert ack.device_id == "1234567890"
24+
25+
26+
def test_result_error_is_parsed():
27+
ack = PacketGeneralGetDeviceIdAck(_build_data(1, "220824001"))
28+
assert ack.result_error == ResultAndError.TRANSFER_ERROR
29+
30+
31+
def test_device_id_defaults_to_empty_string_without_data():
32+
ack = PacketGeneralGetDeviceIdAck(None)
33+
assert ack.device_id == ""
34+
assert ack.result_error == ResultAndError.NO_ERROR

0 commit comments

Comments
 (0)