def __set__(self, obj, value): if value is None: # Money(0) is False self._set_values(obj, None, '') elif isinstance(value, Money): self._set_values(obj, value.amount, value.currency) elif isinstance(value, Decimal): _, currency = self._get_values(obj) # use what is currently set self._set_values(obj, value, currency) else: # It could be an int, or some other python native type try: amount = Decimal(str(value)) _, currency = self._get_values( obj) # use what is currently set self._set_values(obj, amount, currency) except TypeError: # Lastly, assume string type 'XXX 123' or something Money can # handle. try: _, currency = self._get_values( obj) # use what is currently set m = Money.from_string(str(value)) self._set_values(obj, m.amount, m.currency) except TypeError: msg = 'Cannot assign "%s"' % type(value) raise TypeError(msg)
def test_price_attribute(self): e = SimpleMoneyModel() e.price = Money(3, "BGN") self.assertEqual(e.price, Money(3, "BGN")) e.price = Money.from_string("BGN 5.0") self.assertEqual(e.price, Money(5, "BGN"))
def __set__(self, obj, value): if value is None: # Money(0) is False self._set_values(obj, None, '') elif isinstance(value, Money): self._set_values(obj, value.amount, value.currency) elif isinstance(value, Decimal): _, currency = self._get_values(obj) # use what is currently set self._set_values(obj, value, currency) else: # It could be an int, or some other python native type try: amount = Decimal(str(value)) _, currency = self._get_values(obj) # use what is currently set self._set_values(obj, amount, currency) except TypeError: # Lastly, assume string type 'XXX 123' or something Money can # handle. try: _, currency = self._get_values(obj) # use what is currently set m = Money.from_string(str(value)) self._set_values(obj, m.amount, m.currency) except TypeError: msg = 'Cannot assign "%s"' % type(value) raise TypeError(msg)
def test_string_parse_default_currency(): value = Money.from_string("100.0") assert value.amount == Decimal("100.0") assert value.currency == 'XXX' assert value.currency == CURRENCY['XXX']
def test_string_parse(): value = Money.from_string("USD 100.0") assert value.amount == Decimal("100.0") assert value.currency == 'USD' assert value.currency == CURRENCY['USD']
def test_price_from_string(self): price1 = Money("400", "USD") price2 = Money.from_string("USD 400") self.assertEqual(price1, price2) self.assertEqual(price1.amount, price2.amount) self.assertEqual(price1.currency, price2.currency)