From 502e348a148262e074765d483650387f0f306d01 Mon Sep 17 00:00:00 2001 From: PH Tools Date: Mon, 6 Jan 2025 14:54:40 -0500 Subject: [PATCH] fix(converter): Add new unit-parser - Add 'validate_unit_type' to check input unit strings against the dictionary of valid types. --- ph_units/converter.py | 19 +++++++++++++++++++ ph_units/unit_types/envelope.py | 2 +- tests/test_converter.py | 8 ++++++++ tests/test_parser.py | 1 + 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/ph_units/converter.py b/ph_units/converter.py index 4645aac..fc4e4a1 100644 --- a/ph_units/converter.py +++ b/ph_units/converter.py @@ -159,6 +159,25 @@ def _conversion_factor(_schema, _input_unit, _target_unit): ) +def validate_unit_type(_unit_type): + # type: (str | None) -> str | None + """Return the valid unit type from the input string. + + examples: + "in." -> "IN" + "m" -> "M" + "Btu/hr-sf-F" -> "BTU/HR-FT2-F" + None -> None + "not-a-unit" -> Exception + """ + + if _unit_type is None: + return None + + return _standardize_unit_name(_unit_type, unit_type_alias_dict) + + + def convert(_value, _input_unit, _target_unit): # type: (Optional[Union[float, int, str]], Optional[str], str) -> Optional[Union[int, float]] """Convert a value from a one unit-type to another (ie: "M" -> "FT"). diff --git a/ph_units/unit_types/envelope.py b/ph_units/unit_types/envelope.py index 9a855fa..e1e3c46 100644 --- a/ph_units/unit_types/envelope.py +++ b/ph_units/unit_types/envelope.py @@ -8,7 +8,7 @@ class WattsPerMeterSquaredKelvin(Base_UnitType): """W/M2K (U-Value)""" __symbol__ = "W/M2K" - __aliases__ = ["U-SI", "W/M²K"] + __aliases__ = ["U-SI", "W/M²K", "W/M2-K", "W/M²-K"] __factors__ = { "W/M2K": "{}*1", "M2K/W": "(1/{})", diff --git a/tests/test_converter.py b/tests/test_converter.py index 6e3c5ea..e719c49 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -7,6 +7,7 @@ _standardize_unit_name, unit_type_alias_dict, unit_type_dict, + validate_unit_type ) @@ -27,3 +28,10 @@ def test_standardize_unit_name_alias() -> None: def test_standardize_gives_error() -> None: with pytest.raises(UnitTypeNameNotFound): _standardize_unit_name("Not/A-Unit", unit_type_alias_dict) + +def test_validate_unit_type() -> None: + assert validate_unit_type("FT") == "FT" + assert validate_unit_type("ft") == "FT" + assert validate_unit_type("Btu/hr-ft2-F") == "BTU/HR-FT2-F" + with pytest.raises(UnitTypeNameNotFound): + validate_unit_type("Not/A-Unit") \ No newline at end of file diff --git a/tests/test_parser.py b/tests/test_parser.py index 21b53dd..8605264 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -46,3 +46,4 @@ def test_parse_string_with_units(): def test_parse_string_no_value(): assert parse_input("Missing Value") == ("", "MISSING VALUE") +