Skip to content

Commit

Permalink
fix(unit_type): Fix Unit 'as_a' conversion bug
Browse files Browse the repository at this point in the history
- Fix bug with '0' value
  • Loading branch information
ed-p-may committed Oct 27, 2023
1 parent 2c872a6 commit 2d8a1fa
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
12 changes: 6 additions & 6 deletions ph_units/unit_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ def unit(self):

def as_a(self, unit):
# type: (str) -> Unit
"""Return a new Unit in the specified unit-type."""
new_value = convert(self.value, self.unit, unit)
if not new_value:
raise ValueError(
"Cannot convert from '{}' to '{}'.".format(self.unit, unit)
)
"""Return a new Unit with the value converted to the specified unit-type."""
try:
new_value = convert(self.value, self.unit, unit)
except Exception as e:
msg = "Error trying to convert '{}' from '{}' to '{}'".format(self.value, self.unit, unit)
raise ValueError(msg, e)
return Unit(new_value, unit)

def _invert_unit(self, unit):
Expand Down
8 changes: 8 additions & 0 deletions tests/test_as_a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from ph_units.unit_type import Unit

def test_basic_use() -> None:
assert Unit(1.0, "KWH").as_a("KBTU") == Unit(3.41214, "KBTU")


def test_zero_value() -> None:
assert Unit(0, "KWH").as_a("KBTU") == Unit(0, "KBTU")

0 comments on commit 2d8a1fa

Please sign in to comment.