def test_mixed_addition(): five_dollars = Money.dollar(5) ten_francs = Money.franc(10) bank = Bank() bank.add_rate("CHF", "USD", 2) result = bank.reduce(five_dollars + ten_francs, "USD") assert result == Money.dollar(10)
def test_currency_accessor(self): # In the old code, accessing `myinstance.myfield_currency` would work. # Here we test for that and emulate the old behavior. This should # probably not be part of the official API and when removed, this test # can be removed as well. created = SimpleMoneyModel.objects.create(name="zero dollars", price=Money(0)) self.assertEqual(created.price_currency, "XXX") self.assertEqual(created.price.currency, "XXX") created = SimpleMoneyModel.objects.create(name="zero dollars", price=Money(0, "USD")) self.assertEqual(created.price_currency, "USD") self.assertEqual(created.price.currency, "USD") # This actually wouldn't work in the old code without a round trip to the db created.price_currency = 'EUR' self.assertEqual(created.price_currency, "EUR") self.assertEqual(created.price.currency, "EUR") created.save() created = SimpleMoneyModel.objects.get(pk=created.pk) self.assertEqual(created.price_currency, "EUR") self.assertEqual(created.price.currency, "EUR")
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 test_mixed_addition(self): five_bucks = Money.dollar(5) ten_francs = Money.franc(10) bank = Bank() bank.add_rate('CHF', 'USD', 2) result = bank.reduce(five_bucks.plus(ten_francs), 'USD') self.assertTrue(result.equals(Money.dollar(10)))
def test_allocation(self): """ It allocates money amount to given ratios """ data = [ # amount, ratios, amount_per_ratio [100, [1, 1, 1], [34, 33, 33]], [100, [1], [100]], [101, [1, 1, 1], [34, 34, 33]], [101, [3, 7], [30, 71]], [101, [7, 3], [71, 30]], [5, [3, 7], [2, 3]], [5, [7, 3], [4, 1]], [5, [7, 3, 0], [4, 1, 0]], [2, [1, 1, 1], [1, 1, 0]], [1, [1, 1], [1, 0]], [-5, [7, 3], [-3, -2]], ] for amount, ratios, result in data: with self.subTest(): money = Money(amount, self.currency) allocation = money.allocate(ratios) for index, money in enumerate(allocation): self.assertEqual(result[index], money.amount)
def test_less_or_equal_than(self): """ It returns true when money amount is less or equal than given money object """ money1 = Money(0, self.currency) money2 = Money(0, self.currency) self.assertTrue(money1 <= money2)
def test_create_money_instance(self): """ It creates a new money instance with given amount using the same currency """ original = Money(10, self.currency) new = original.instance(100) self.assertEqual(self.currency, new.currency)
def test_greater_or_equal_than(self): """ It returns true when money amount is greater or equal to given money object """ money1 = Money(0, self.currency) money2 = Money(0, self.currency) self.assertTrue(money1 >= money2)
def test_greater_than(self): """ It returns true when money amount is greater than given money object """ money1 = Money(10, self.currency) money2 = Money(0, self.currency) self.assertTrue(money1 > money2)
def test_subtract_fail(self): """ An exception is thrown when subtracting money with different currencies """ eur = Money(0, Currency('eur')) usd = Money(0, Currency('usd')) with self.assertRaises(ValueError): eur - usd
def test_simple_addition(): five: Money = Money.dollar(5) # "sum" is a reserved keyword in Python, so everything that is named "sum" # in the books example will be named "sum_" for consistencies sake sum_ = five + five bank = Bank() reduced = bank.reduce(sum_, "USD") assert reduced == Money.dollar(10)
def test_sum_times(): five_dollars = Money.dollar(5) ten_francs = Money.franc(10) bank = Bank() bank.add_rate("CHF", "USD", 2) sum_ = Sum(five_dollars, ten_francs) * 2 result = bank.reduce(sum_, "USD") assert result == Money.dollar(20)
def cents_to_brl(value): if value: value = int(value) # valor com centavos em float value = float(value) / 100 m = Money(value, "BRL") return m.format("pt_BR", "¤ #,##0.00") return None
def test_zero_edge_case(self): created = SimpleMoneyModel.objects.create(name="zero dollars", price=Money(0, "USD")) self.assertEqual(created.price, Money(0, "USD")) ent = SimpleMoneyModel.objects.filter( price__exact=Money(0, "USD")).get() self.assertEqual(ent.price, Money(0, "USD"))
def test_sum_times(self): five_bucks = Money.dollar(5) ten_francs = Money.franc(10) bank = Bank() bank.add_rate('CHF', 'USD', 2) sum = Sum(five_bucks, ten_francs).times(2) result = bank.reduce(sum, 'USD') self.assertTrue(result.equals(Money.dollar(20)))
def test_sum_plus_money(self): five_bucks = Money.dollar(5) ten_francs = Money.franc(10) bank = Bank() bank.add_rate('CHF', 'USD', 2) sum = Sum(five_bucks, ten_francs).plus(five_bucks) result = bank.reduce(sum, 'USD') self.assertEqual(result, Money.dollar(15))
def test_equals(self): """ It returns true when two money objects are equal """ money1 = Money(0, self.currency) money2 = Money(0, self.currency) self.assertTrue(money1 == money2)
def test_price_amount_to_string(self): e1 = SimpleMoneyModel(price=Money('200', 'JPY')) e2 = SimpleMoneyModel(price=Money('200.0', 'JPY')) self.assertEqual(str(e1.price), "JPY 200") self.assertEqual(str(e1.price.amount), "200") self.assertEqual(str(e2.price.amount), "200.0")
def test_subtract(self): """ It subtracts two money objects """ for amount in [[10, 10, 0], [0, 0, 0], [10, 20, -10]]: with self.subTest(): money1 = Money(amount[0], self.currency) money2 = Money(amount[1], self.currency) difference = money1 - money2 self.assertEqual(amount[2], difference.amount)
def gui_text(): c = Configs() currency = getattr(Currency, c.money) update_date = datetime.datetime.now().strftime(c.date_frmt) update_hour = datetime.datetime.now().strftime(c.hour_frmt) placeholder, one_btc_value = convert_to_money(1, c.money) one_btc_value_frmt = Money(str(one_btc_value), currency). \ format(c.money_frmt) start_replacements = { "title": c.title, "update_date": update_date, "update_time": update_hour, "btc_value": one_btc_value_frmt, "currency": c.money } txt = ["\n".join(c.str_title).format(**start_replacements)] for wallet in c.wallets: wallet_name = wallet["name"] wallet_addr = wallet['address'] balance_btc = final_balance(wallet_addr) if balance_btc is not None: balance_money, btc_value = convert_to_money(balance_btc, c.money) balance_money = Money(str(balance_money), currency).format(c.money_frmt) wallet_replacements = { "btc_balance": balance_btc, "money_balance": balance_money, "wallet": wallet_name, "wallet_address": wallet_addr } txt.append("\n".join( c.str_wallet_view).format(**wallet_replacements, **start_replacements)) else: wallet_replacements = { "wallet": wallet_name, "wallet_address": wallet_addr } txt.append("\n".join( c.str_fail_wallet_view).format(**wallet_replacements, **start_replacements)) txt.append("\n".join(c.str_extra_content).format(**start_replacements)) return ''.join(txt)
def test_add(self): """ It adds two money objects """ for amount in [[10, 10, 20], [0, 0, 0], [-10, 10, 0]]: with self.subTest(): money1 = Money(amount[0], self.currency) money2 = Money(amount[1], self.currency) sum = money1 + money2 self.assertEqual(amount[2], sum.amount)
def test_subtract(self): assert Money('3.5') - Money('1.25') == Money('2.25') assert Money('4') - Money('5.5') == Money('-1.5') with pytest.raises(CurrencyMismatchError): Money('3.5', Currency.EUR) - Money('1.8', Currency.GBP) with pytest.raises(InvalidOperandError): Money('5.5') - 6.32 with pytest.raises(InvalidOperandError): 666.32 - Money('5.5')
def test_creation_parsed(self): result = Money('XXX -10.50') self.assertEqual(result.amount, Decimal("-10.50")) self.assertEqual(result.currency.code, 'XXX') result = Money('USD -11.50') self.assertEqual(result.amount, Decimal("-11.50")) self.assertEqual(result.currency.code, 'USD') result = Money('JPY -12.50') self.assertEqual(result.amount, Decimal("-12.50")) self.assertEqual(result.currency.code, 'JPY')
def test_not_equals(self): """ It returns false when two money objects are not equal """ money1 = Money(0, self.currency) money2 = Money(10, self.currency) self.assertFalse(money1 == money2) money1 = Money(0, Currency('EUR')) money2 = Money(0, Currency('USD')) self.assertFalse(money1 == money2)
def test_equal(self): assert Money('3.5') == Money('3.5') assert Money('4.0', Currency.GBP) == Money('4.0', Currency.GBP) assert not Money('6.9') == Money('43') with pytest.raises(CurrencyMismatchError): Money('3.5', Currency.EUR) == Money('3.5', Currency.GBP) with pytest.raises(InvalidOperandError): Money('5.5') == 5.5
def test_greater_than_or_equal(self): assert Money('3.5') >= Money('1.2') assert not Money('5.13') >= Money('104.2') assert Money('2.2') >= Money('2.2') with pytest.raises(CurrencyMismatchError): Money('3.5', Currency.EUR) >= Money('1.2', Currency.GBP) with pytest.raises(InvalidOperandError): Money('3.5') >= 1.2
def test_less_than(self): assert Money('1.2') < Money('3.5') assert not Money('104.2') < Money('5.13') assert not Money('2.2') < Money('2.2') with pytest.raises(CurrencyMismatchError): Money('1.2', Currency.GBP) < Money('3.5', Currency.EUR) with pytest.raises(InvalidOperandError): 1.2 < Money('3.5')
def test_not_equal(self): assert Money('3.5') != Money('46.44') assert Money('4.0', Currency.GBP) != Money('12.01', Currency.GBP) assert not Money('6.9') != Money('6.9') with pytest.raises(CurrencyMismatchError): Money('3.5', Currency.EUR) != Money('23', Currency.GBP) with pytest.raises(InvalidOperandError): Money('5.5') != 666.32
class MoneyModelDefaultMoneyUSD(models.Model): name = models.CharField(max_length=100) price = fields.MoneyField(max_digits=12, decimal_places=3, default=Money("123.45", "USD")) zero = fields.MoneyField(max_digits=12, decimal_places=3, default=Money("0", "USD")) def __str__(self): return self.name + " " + str(self.price) class Meta: app_label = 'tests'
def test_assign(self): price = Money(100, "USD") ent = SimpleMoneyModel(name='test', price=price.amount, price_currency=price.currency) ent.save() self.assertEqual(ent.price, Money(100, "USD")) ent.price = Money(10, "USD") ent.save() self.assertEqual(ent.price, Money(10, "USD")) ent_same = SimpleMoneyModel.objects.get(pk=ent.id) self.assertEqual(ent_same.price, Money(10, "USD"))
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_reduce_money(self): bank = Bank() result = bank.reduce(Money.dollar(1), 'USD') self.assertTrue(Money.dollar(1).equals(result))
def test_franc_multiplication(self): six = Money.franc(6) self.assertTrue(Money.franc(12).equals(six.times(2))) self.assertTrue(Money.franc(30).equals(six.times(5)))
def test_dollar_multiplication(self): six = Money.dollar(6) self.assertTrue(Money.dollar(12).equals(six.times(2))) self.assertTrue(Money.dollar(30).equals(six.times(5)))
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_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_dollar_inequality(self): self.assertFalse(Money.dollar(42).equals(Money.dollar(69)))
def test_dollar_equality(self): self.assertTrue(Money.dollar(42).equals(Money.dollar(42)))
def test_franc_dollar_inequality(self): self.assertFalse(Money.franc(5).equals(Money.dollar(5)))
def test_currency(self): self.assertEqual('USD', Money.dollar(1).currency()) self.assertEqual('CHF', Money.franc(1).currency())
def test_simple_addition(self): sum = Sum(Money.dollar(3), Money.dollar(4)) bank = Bank() reduced = bank.reduce(sum, 'USD') self.assertTrue(reduced.equals(Money.dollar(7)))
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)
def test_reduce_money_different_currency(self): bank = Bank() bank.add_rate('CHF', 'USD', 2) result = bank.reduce(Money.franc(2), 'USD') self.assertTrue(Money.dollar(1).equals(result))