Skip to content

Commit

Permalink
Add bounds checking to hex_to_dotted_lcc_id. Add emit_cast for logging.
Browse files Browse the repository at this point in the history
  • Loading branch information
Poikilos committed Jan 7, 2025
1 parent 2e2e77a commit 7abb06e
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
5 changes: 5 additions & 0 deletions openlcb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@ def only_hex_pairs(value):
functions (less restrictive).
"""
return hex_pairs_rc.fullmatch(value)


def emit_cast(value):
"""Show type and value, such as for debug output."""
return "{}({})".format(type(value).__name__, repr(value))
9 changes: 8 additions & 1 deletion openlcb/conventions.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
from logging import getLogger

from openlcb import only_hex_pairs
from openlcb import (
only_hex_pairs,
emit_cast,
)

logger = getLogger(__name__)

LCC_ID_SEP = "."


def hex_to_dotted_lcc_id(hex_s):
if (not isinstance(hex_s, str)) or (len(hex_s) != 12):
raise ValueError(
"Only 6 hex pairs (12 characters) allowed, but got {}."
.format(emit_cast(hex_s)))
return LCC_ID_SEP.join([hex_s[i*2:i*2+2] for i in range(len(hex_s)//2)])


Expand Down
8 changes: 8 additions & 0 deletions tests/test_conventions.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ def test_hex_to_dotted_lcc_id(self):
self.assertEqual(hex_to_dotted_lcc_id("02015700049C"),
"02.01.57.00.04.9C")

def test_hex_to_dotted_lcc_id_fail(self):
exception = None
try:
_ = hex_to_dotted_lcc_id("2015700049C")
except ValueError as ex:
exception = ex
self.assertIsInstance(exception, ValueError)


if __name__ == '__main__':
unittest.main()

0 comments on commit 7abb06e

Please sign in to comment.