def test_area_divide(self): area = Area(sq_m=300) value = 2 expected_result = 150 with self.subTest(value=value, type=pretty_name(value)): result = area / value self.assertIsInstance(result, Area) self.assertEqual(result.sq_m, expected_result) value = Area(sq_m=2) with self.subTest(value=value, type=pretty_name(value)): self.assertRaises(TypeError, area.__div__, value)
def __truediv__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)}) else: raise TypeError('%(class)s must be divided by a number' % {"class": pretty_name(self)})
def test_multiply(self): m1 = 100 m2 = 200 d1 = Distance(m=m1) values = [150.5, Distance(m=m2)] expected_results = [150.5 * m1, m1 * m2] for value, expected_result in zip(values, expected_results): with self.subTest(value=value, type=pretty_name(value)): result = d1 * value if isinstance(value, Distance): self.assertIsInstance(result, Area) result = result.sq_m else: result = result.m self.assertAlmostEqual(result, expected_result, 6) with self.subTest(value=value, type=pretty_name(value)): mult = lambda x: x[0] * x[1] self.assertRaises(TypeError, mult, (d1, "can't multiply"))
def __truediv__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)} ) else: raise TypeError( '%(class)s must be divided by a number' % { "class": pretty_name(self) } )
def __mul__(self, other): if isinstance(other, self.__class__): return Area(default_unit=AREA_PREFIX + self._default_unit, **{ AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard) }) elif isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)}) else: raise TypeError( '%(dst)s must be multiplied with number or %(dst)s' % { "dst": pretty_name(self.__class__), })
def __mul__(self, other): if isinstance(other, self.__class__): return Area( default_unit=AREA_PREFIX + self._default_unit, **{ AREA_PREFIX + self.STANDARD_UNIT: ( self.standard * other.standard ) } ) elif isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)} ) else: raise TypeError( '%(dst)s must be multiplied with number or %(dst)s' % { "dst": pretty_name(self.__class__), } )
def test_addition_typeerrors(self): t1 = Temperature(c=100) values = [1, 1.5, 0, -1] for value in values: with self.subTest(value=value, value_type=pretty_name(value)): self.assertRaises(TypeError, sum, t1, value)