From 7abb06ee365f41c506ea2aa1f0c50695f1601b41 Mon Sep 17 00:00:00 2001 From: Jacob Gustafson <7557867+Poikilos@users.noreply.github.com> Date: Tue, 7 Jan 2025 12:22:04 -0500 Subject: [PATCH] Add bounds checking to hex_to_dotted_lcc_id. Add emit_cast for logging. --- openlcb/__init__.py | 5 +++++ openlcb/conventions.py | 9 ++++++++- tests/test_conventions.py | 8 ++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/openlcb/__init__.py b/openlcb/__init__.py index 0bfae49..db88c0e 100644 --- a/openlcb/__init__.py +++ b/openlcb/__init__.py @@ -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)) diff --git a/openlcb/conventions.py b/openlcb/conventions.py index 9614d98..cd29dad 100644 --- a/openlcb/conventions.py +++ b/openlcb/conventions.py @@ -1,6 +1,9 @@ from logging import getLogger -from openlcb import only_hex_pairs +from openlcb import ( + only_hex_pairs, + emit_cast, +) logger = getLogger(__name__) @@ -8,6 +11,10 @@ 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)]) diff --git a/tests/test_conventions.py b/tests/test_conventions.py index ea14ef7..6ccd0e7 100644 --- a/tests/test_conventions.py +++ b/tests/test_conventions.py @@ -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()