Skip to content

Commit

Permalink
Fix #40 -- Raise type error with proper message
Browse files Browse the repository at this point in the history
If two measures are multiplied that are not compatible – should
not be multipled, like mass x mass -, the error message should
indicate that incompatibility.
  • Loading branch information
codingjoe committed Apr 18, 2020
1 parent b6e1c9f commit bbc0356
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
2 changes: 1 addition & 1 deletion measurement/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,11 +339,11 @@ def __isub__(self, other):
def __mul__(self, other):
try:
value = getattr(self, self.unit.org_name) * other
return type(self)(value=value, unit=self.unit.org_name)
except TypeError as e:
raise TypeError(
f"can't multiply type '{qualname(self)}' and '{qualname(other)}'"
) from e
return type(self)(value=value, unit=self.unit.org_name)

def __imul__(self, other):
return self * other
Expand Down
7 changes: 6 additions & 1 deletion tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pytest

from measurement.base import ImmutableKeyDict, MetricUnit, Unit, qualname
from measurement.measures import Distance
from measurement.measures import Distance, Mass


def test_qualname():
Expand Down Expand Up @@ -165,6 +165,11 @@ def test_mul__raise__type_error(self):
str(e.value) == f"can't multiply type '{qualname(self.measure)}' and 'str'"
)

def test_mul__raise_for_same_type(self):
with pytest.raises(TypeError) as e:
Mass("1 kg") * Mass("1 kg")
assert str(e.value) == f"can't multiply type 'Mass' and 'Mass'"

def test_imul(self):
d = self.measure(**{self.unit: 2})
d *= 2
Expand Down

0 comments on commit bbc0356

Please sign in to comment.