Skip to content

Commit

Permalink
fix(converter): Add new unit-parser
Browse files Browse the repository at this point in the history
- Add 'validate_unit_type' to check input unit strings against the dictionary of valid types.
  • Loading branch information
ed-p-may committed Jan 6, 2025
1 parent 061bcf3 commit 502e348
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
19 changes: 19 additions & 0 deletions ph_units/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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").
Expand Down
2 changes: 1 addition & 1 deletion ph_units/unit_types/envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/{})",
Expand Down
8 changes: 8 additions & 0 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
_standardize_unit_name,
unit_type_alias_dict,
unit_type_dict,
validate_unit_type
)


Expand All @@ -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")
1 change: 1 addition & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,4 @@ def test_parse_string_with_units():

def test_parse_string_no_value():
assert parse_input("Missing Value") == ("", "MISSING VALUE")

0 comments on commit 502e348

Please sign in to comment.