def test_addition(self): result = Currency(50.11, external_value=True) + Currency( "40.50", external_value=True) assert isinstance(result, Currency) assert str(result) == "90.61" assert result.external_value == 90.61 # this addition will be on the thousandth of a cent value so it wont move the needed much when casted to dollars result = Currency(50.11, external_value=True) + 40.50 assert isinstance(result, Currency) assert str(result) == "50.11" assert result.external_value == 50.11
def test_division(self): with pytest.raises(TypeError): Currency(50.11, external_value=True) / Currency( "3", external_value=True) result = Currency(50.11, external_value=True) / 5.5 assert isinstance(result, Currency) assert str(result) == "9.11" assert result.external_value == 9.11 result = Currency(50.11, external_value=True) / 2 assert isinstance(result, Currency) assert str(result) == "25.05" assert result.external_value == 25.05 val = Currency(454.23, external_value=True) val = val / 43.25 assert val.external_value == 10.5
def test_multiplication(self): with pytest.raises(TypeError): Currency(50.11, external_value=True) * Currency( "3", external_value=True) result = Currency(50.11, external_value=True) * 5.5 assert isinstance(result, Currency) assert str(result) == "275.61" assert result.external_value == 275.61 result = Currency(50.11, external_value=True) * 2 assert isinstance(result, Currency) assert str(result) == "100.22" assert result.external_value == 100.22 val = Currency(454.23, external_value=True) val = val * 6 assert val.external_value == 2725.38
def get_prep_value(self, value): if isinstance(value, Currency): value = value.value elif isinstance(value, int): pass elif isinstance(value, ( str, float, Decimal, )): value = Currency(value, external_value=True).value return super().get_prep_value(value)
def to_internal_value(self, data): # run this method to validate the data input for decimal but discard its return val super().to_internal_value(data) if isinstance(data, Currency): pass elif isinstance(data, (int, str, float, Decimal)): data = Currency(data, external_value=True) # round up to the nearest cent to avoid being fractions of a cent short when paying a invoice data.round_up_to_cents() else: raise ValueError( f'Invalid data type {type(data)} for CurrencySerializerField') return data
def from_db_value(self, value, expression, connection): return Currency(value) if value is not None else value
def test_negative(self): refund_amount = Currency("-500.34", external_value=True) assert refund_amount.value < 0 assert refund_amount.external_value < 0 assert refund_amount.external_value == -500.34
def test_bool(self): total = Currency(0) assert not total assert not bool(total)