def test_return_the_difference_between_the_two_same_nationality_money(self): money_yen1 = Money.yen(20) money_yen2 = Money.yen(5) expected = Money.yen(15) money_diff = money_yen1 - money_yen2 self.assertTrue(expected == money_diff)
def test_return_the_sum_of_two_same_nationality_money(self): money_yen1 = Money.yen(10) money_yen2 = Money.yen(5) expected = Money.yen(15) money_sum = money_yen1 + money_yen2 self.assertTrue(expected == money_sum)
def test_less_equal_with_two_different_nationality_money(self): greatest = Money.dollar(20.1) median = Money.yen(10) median.set_exchanger(DummyExchanger()) least = Money.dollar(19.9) self.check_less_operator_of_rich_comparison(median.__le__, greatest, median, least, True)
def testMixedAddition(self): fiveBucks = Money.dollar(5) tenFrancs = Money.franc(10) bank = Bank() bank.addRate('CHF', 'USD', 2) result = bank.reduce(fiveBucks.plus(tenFrancs), 'USD') self.assertEquals(Money.dollar(10), result)
def load_from_db(self, id): rows = self.select_by_id('player', id) for row in rows: self.id = row[0] self.name = row[1] self.password = row[2] self.email = row[3] with self.connection: cursor = self.connection.cursor() cursor.execute( "select achievement_id from achievement_player where player_id={}".format(id)) for achievement_player_row in cursor.fetchall(): achievement_id = achievement_player_row[0] achievement = Achievement(self.connection) self.achievements.append(achievement.load_from_db(achievement_id)) cursor.execute( "select counter_id from counter_player where player_id={}".format(id)) for counter_player_row in cursor.fetchall(): counter_id = counter_player_row[0] counter = Counter(self.connection) self.counters.append(counter.load_from_db(counter_id)) cursor.execute("select id from money where player_id={}".format(id)) for money_row in cursor.fetchall(): money_id = money_row[0] money = Money(self.connection) money.load_from_db(money_id) self.wallet[money.type] = money
def testSumTimes(self): fiveBucks = Money.dollar(5) tenFrancs = Money.franc(10) bank = Bank() bank.addRate('CHF', 'USD', 2) sum = Sum(fiveBucks, tenFrancs).times(2) result = bank.reduce(sum, 'USD') self.assertEquals(Money.dollar(20), result)
def test_return_the_difference_between_the_different_nationality_money(self): money_yen = Money.yen(10) money_yen.set_exchanger(DummyExchanger()) money_dollar = Money.dollar(2) expected = Money.yen(9) money_diff = money_yen - money_dollar self.assertTrue(expected == money_diff)
def test_return_the_sum_of_two_different_nationality_money(self): money_yen = Money.yen(10) money_yen.set_exchanger(DummyExchanger()) money_dollar = Money.dollar(5) expected = Money.yen(12.5) money_sum = money_yen + money_dollar self.assertTrue(expected == money_sum)
def test_return_the_money_that_aligned_the_unit_to_currency_of_each_nationality(self): money_yen = Money.yen(10.2) expected = (10, 0) self.assertTrue(expected == money_yen.currency()) money_dollar = Money.dollar(10.2) expected = (10, 20) self.assertTrue(expected == money_dollar.currency())
def test_money_exchange_yen_to_dollar(self): money = Money.yen(10) money.set_exchanger(DummyExchanger()) expected = Money.dollar(20) result_money = money.exchange("dollar") self.assertTrue(expected == result_money)
def testMoney(self): """""" USD100 = Money(100, "USD") EUR100 = Money(100, "EUR") self.assertEquals(Decimal(139),EUR100.convert_to_default()) self.assertEquals(Decimal(100),EUR100.convert_to_default() - 39) Currency.objects.set_currency('1.5', 'EUR') exc2 = Currency.objects.get_currency("EUR") self.assertEquals(Decimal('1.5'), exc2.exchange_rate) EUR1000 = Money(1000, "EUR") self.assertEquals(Decimal(1500),EUR1000.convert_to_default()) self.assertNotEquals(Decimal(150),EUR100.convert_to_default())
def __init__(self, amount=Decimal("0.0"), currency=None): if isinstance(amount, OriginalMoney): try: amount = amount.amount except AttributeError: # just in case python-money is not installed (Decimal assumes as OriginalMoney) pass currency = currency or settings.DEFAULT_CURRENCY if OriginalMoney == Decimal: OriginalMoney.__init__(self, amount) self.amount = amount self.currency = currency else: OriginalMoney.__init__(self, str(amount).replace(get_format('THOUSAND_SEPARATOR'),''), currency)
def convert(self, value, currency): currency = str(currency).upper() if currency != "USD": if currency not in self.currencies: print("Currency: " + str(currency)) assert currency in self.currencies, "ERROR: currency is not in listed currencies." value = float(value) / 100.0 val_money = Money(value, currency) return float(val_money.to("USD")) # Does this only for USD return float(value) / 100.0
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_both_fixed_currency_and_default_valid(self): testfield = MoneyField( name='testfield', decimal_places=2, max_digits=8, currency='USD', default=Money('1234.00', 'USD'), )
def __get__(self, instance, owner): if instance: if instance._values.get(self.name, self.default) is None: return None return Money(instance._values.get(self.name, self.default), getattr(instance, self.currency_field)) else: return self
def test_too_much_withdraw(self): """ test that raise the ValueError after withdraw higher than available. """ bank_account = set_up() bank_account.deposit(Money(9000)) ck = Check(10000) bank_account.deposit(ck) with self.assertRaises(ValueError): bank_account.withdraw(10000)
class ParametrizedDefaultAsMoneyModel(models.Model): """ The simplest possible declaration with a Money object """ value = fields.MoneyField(max_digits=12, decimal_places=3, default=Money(100, 'JPY')) def expected_value(self): return Money('100', 'JPY')
def _combine_payments(*payment_groups): combined_payments = {} for payments in payment_groups: for a, p in payments.items(): if a not in combined_payments: combined_payments[a] = Money(0) combined_payments[a] += p return combined_payments
def weekly_money_recovered_in_dollars(self): weekly_money_recovered_in_dollars = float( self.get_percent_time_spent() - self.IDEAL_PERCENT_TIME_IN_MEETINGS) weekly_money_recovered_in_dollars /= 100 weekly_money_recovered_in_dollars *= self.COST_PER_SECOND weekly_money_recovered_in_dollars *= self.PERSON_SECONDS_PER_WEEK return Money(weekly_money_recovered_in_dollars, self.CURRENCY)
def test_greater_equal_with_money_and_real_number(self): greatest = 10.1 median = Money.yen(10) least = 9.9 self.check_greater_operator_of_rich_comparison(median.__ge__, greatest, median.value, least, True)
def __get__(self, obj, model): """Return a Money object if called in a model instance""" if obj is None: return self.field amount, currency = self._get_values(obj) if amount is None or currency is None: return None return Money(amount, currency)
def test_converts_amount_field_into_money_object(self, mocks): mocks.reader.return_value = [[ 'accountName', 'goalName', 'total', 'startDate' ], ['biz', 'baz', '5000,50', '06.06.2017']] gc = GoalConnector() gc_entry = list(gc.all())[0] assert gc_entry['total'] == Money('5000.50', 'RUR')
def getamount(): id = request.form['itemid'] amt = db.session.query(Items).get(id) if amt != None: formatted = Money(amount=amt.item_amt, currency='NGN') return str(formatted) else: return "You have to make a choice"
def calculate_prices(self, country): """ Calculate shipping price, shipping discount and set a flag if the product qualifies for free shipping @param country: @return: None """ rule_price = None rule_price_extra = None for current_rule in self.shipping_profile.shipping_rules.all(): if country in current_rule.countries.all(): rule_price = current_rule.rule_price rule_price_extra = current_rule.rule_price_extra break # no country found, use rest of the world if not rule_price or not rule_price_extra: rule_price = self.shipping_profile.others_price rule_price_extra = self.shipping_profile.others_price_extra self.shipping_prices[country] = rule_price, rule_price_extra # # check for free shipping # # set default values self.shipping_discounts[country] = ( Money(amount="0", currency=purchase_settings.DEFAULT_CURRENCY), Money(amount="0", currency=purchase_settings.DEFAULT_CURRENCY)) self.free_shippings[country] = False free_shippings = FreeShipping.objects.filter(shipping_to=country) if rule_price and rule_price_extra: if rule_price.amount == 0: self.free_shippings[country] = True elif free_shippings: free_shipping = free_shippings[0] discount_amount = self.price.amount * free_shipping.percent_discount if rule_price < discount_amount: self.shipping_discounts[ country] = rule_price, rule_price_extra self.free_shippings[country] = True
def total_gmv(self): """Total Gross Merchandise Value of sales See also: UserProfile.total_gmv """ orders = self.orders paid_orders = orders.filter(Q(is_joomla_order=True) | ~Q(payment=None)) return Money(0, purchase_settings.DEFAULT_CURRENCY) + sum( [obj.total() for obj in paid_orders])
def test_creation_unspecified_amount(self): """ Same thing as above but with the unspecified 'xxx' currency """ result = Money(currency='USD') self.assertEqual(result.amount, 0) self.assertEqual(result.currency.code, 'USD')
def load(): id = request.form['itemid'] amt = db.session.query(Items).get(id) if amt != None: formatted = Money(amount=amt.item_amt, currency="NGN") return str(formatted) else: return "YOU need to make a choice"
def test_data_decompressed(self): form = self.Form(data={ 'price_0': Decimal('1234.00'), 'price_1': 'EUR', }) self.assertTrue(form.is_valid()) obj = form.save() self.assertEqual(obj.price, Money('1234.00', 'EUR'))
def setUp( self ) : '''Optional. Run before for each test.''' self.u1 = Money( 13, 'USD' ) self.u1copy = Money( 13, 'USD' ) self.u2 = Money( 8, 'USD' ) self.u2copy = Money( 8, 'USD' ) self.p1 = Money( 13, 'PLN' ) self.n1 = Money( -13, 'USD' ) self.n2 = Money( -18, 'USD' ) self.n2copy = Money( -18, 'USD' )
def load(self, file_object): object_as_dict = json.load(file_object) self.id = object_as_dict["id"] self.type = object_as_dict["type"] self.nickname = object_as_dict["nickname"] self.email = object_as_dict["email"] self.password = object_as_dict["password"] gold = Money(code=object_as_dict["wallet"]["gold"]["code"], amount=object_as_dict["wallet"]["gold"]["amount"]) silver= Money(code=object_as_dict["wallet"]["silver"]["code"], amount=object_as_dict["wallet"]["silver"]["amount"]) copper = Money(code=object_as_dict["wallet"]["copper"]["code"], amount=object_as_dict["wallet"]["copper"]["amount"]) self.wallet = Wallet(gold, silver, copper) self.session = object_as_dict["session"] self.created = object_as_dict["created"] self.updated = object_as_dict["updated"] return object_as_dict
def to_python(self, value): if isinstance(value, str): try: (currency, value) = value.split() if currency and value: return Money(value, currency) except ValueError: pass return value
def apply(self, div: Dividend, pf: Portfolio): for account in pf.get_accounts(): for position in account.get_positions(): if position.get_tradable().get_ticker_id() == div.get_tradable( ).get_ticker_id(): qty = position.get_qty() amt_paid = Money(qty * div.get_amount().amount, div.get_amount().currency) account.get_cash_balance().deposit(amt_paid)
def __get__(self, obj, type=None): if obj is None: return self amount = obj.__dict__[self.field.name] if amount is None: return None else: return Money(amount, getattr(obj, self.currency_name))
def model_from_db_view(request, amount='0', currency='XXX'): # db roundtrip instance = SimpleMoneyModel.objects.create(price=Money(amount, currency)) instance = SimpleMoneyModel.objects.get(pk=instance.pk) print instance, instance.pk money = instance.price return render_to_response('view.html', {'money': money})
def test_backend_not_set(self): with pytest.raises(ExchangeBackendNotSet): _ = xrates.backend_name with pytest.raises(ExchangeBackendNotSet): xrates.base = 'USD' with pytest.raises(ExchangeBackendNotSet): Money('4', 'USD').to('JPY')
def send_donation_confirmation(self, donation): """Method to send a confirmation to a donor Args: donation(int): Donation amount in cents Returns: None """ donation = Money(amount=(donation / 100), currency="USD") donation = donation.format('en_US').split(".")[0] email_msg = u"Thank you for your donation of {}!\r\n We've added it to the match campaign and have let the matcher know as well.".format(donation) email_msg += u"\r\n\r\nThanks!\r\n - Donatemates" subject = u"Donatemates: Donation confirmation" self.send_email(self.donor_address, subject, email_msg, self.lame_html(email_msg))
def test_equality(self): ten_bucks = Money(10, 'USD') a_hamilton = Money(10, 'USD') juu_en = Money(10, 'JPY') nada = Money(0, 'USD') # Scalars cannot be compared to Money class self.assertFalse(ten_bucks == 10) # unless it is 0 self.assertTrue(nada == 0) # Money is equal to money of the same type self.assertTrue(ten_bucks == a_hamilton) # But not different currencies self.assertFalse(ten_bucks == juu_en)
def load(self, file_object): object_as_dict = json.load(file_object) self.name = object_as_dict["name"] self.email = object_as_dict["email"] self.password = object_as_dict["password"] self.password = object_as_dict["session"] gold = Money(code=object_as_dict["wallet"]["gold"]["code"], amount=object_as_dict["wallet"]["gold"]["amount"]) silver = Money(code=object_as_dict["wallet"]["silver"]["code"], amount=object_as_dict["wallet"]["silver"]["amount"]) copper = Money(code=object_as_dict["wallet"]["copper"]["code"], amount=object_as_dict["wallet"]["copper"]["amount"]) self.wallet = Wallet(gold, silver, copper) return object_as_dict
def test_both_default_and_currency_default(self): with self.assertRaises(FieldError): testfield = MoneyField( name='testfield', decimal_places=2, max_digits=8, currency_default='EUR', default=Money('1234.00', 'EUR'), )
def calculate_receive_amount(transfer_details, sender_account, send_amount, receive_currency) -> [Money, Money]: percentage = transfer_details['commission']['percentage'] fix = transfer_details['commission']['fix'] send_amount = Money(send_amount, sender_account.currency) commission = InternalTransfer.calculate_commission( send_amount, percentage, fix, transfer_details['min_commission'], transfer_details['max_commission'], ) receive_amount = (send_amount - commission).to(receive_currency) if receive_amount.amount < 0: receive_amount = Money(0, receive_currency) return receive_amount, commission
def __init__( self, name: str, amount: Union[str, int, Decimal], code: str = "", comment: str = "", currency: Optional[str] = None, ): """ Initialize a Entry instance with the default currency of the project. Use the currency parameter to alter the currency for this entry. """ self.name = name if currency: self.currency = currency self.amount = Money(amount, self.currency) self.code = code self.comment = comment
def parse(cls, amount): """Attempt to turn a string into a Money object.""" currency = cls.DEFAULT_CURRENCY if not amount: amount = '0' if amount[0] == '$': currency = 'USD' amount = amount[1:] return Money(amount, currency)
def append_logs(self): # I wanted this to be able to record the transactions so the business could then model their metrics # Ideally, the program should export to a table format, but I was having issues with the CSV export # Also, it'd be a good idea to create an inventory system to know how many items we have on hand. with open("log_book.txt", "a+") as log_book: if os.stat("log_book.txt").st_size == 0: log_book.write("-" * 71 + "\n") log_book.write( "| {:<20} | {:>12} | {:>12} | {:>14} |\n".format( "Date", "Net Income", "Sales Tax", "Total Payment")) log_book.write("-" * 71 + "\n") log_book.write("| {:<20} | {:>12} | {:>12} | {:>14} |\n".format( datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"), Money(sum(self.total_price), "USD").format('en_US'), Money((sum(self.total_price) * self.sales_tax), "USD").format('en_US'), Money(sum(self.total_price) * (1 + self.sales_tax), "USD").format('en_US')))
def to_python(self, value): if value is None: return value if isinstance(value, Money): return value elif isinstance(value, Decimal): return Money(value) else: m = self.postgres_money_re.match(value) if m is not None: return Money(amount=m.group(1), currency=m.group(2)) else: return Money.from_string(value)
def load_from_db(self, email): cur = con.cursor() sql_data_email = { "email": email } sql_query = """SELECT id, type, name, email, password, created, updated FROM player WHERE email=%(email)s""" cur.execute(sql_query, sql_data_email) row = cur.fetchone() self.player_id = row[0] self.name = row[2] self.email = row[3] self.password = row[4] self.created = row[5] self.updated = row[6] if row[1] == 'Player': self.__class__ = Player elif row[1] == 'Admin': self.__class__ = Admin else: self.__class__ = Moder self.sessions = Session().load_from_db_player(self.player_id) self.wallet = Money().load_from_db_player(self.player_id) self.achievements = Achievement().load_from_db_player(self.player_id) self.counter = Counter().load_from_db_player(self.player_id)
def __rmod__(self, other): return Money(OriginalMoney.__rmod__(self, other))
def __div__(self, other): return Money(OriginalMoney.__div__(self, other))
def __neg__(self): return Money(OriginalMoney.__neg__(self))
def __pos__(self): return Money(OriginalMoney.__pos__(self))
def testSimpleAddition(self): five = Money.dollar(5) sum = five.plus(five) bank = Bank() reduced = bank.reduce(sum, 'USD') self.assertEquals(Money.dollar(10), reduced)
def testMultiplication(self): five = Money.dollar(5) self.assertEquals(Money.dollar(10), five.times(2)) self.assertEquals(Money.dollar(15), five.times(3))
def testReduceMoneyDifferentCurrency(self): bank = Bank() bank.addRate('CHF', 'USD', 2) result = bank.reduce(Money.franc(2), 'USD') self.assertEquals(Money.dollar(1), result)
def testReduceSum(self): sum = Sum(Money.dollar(3), Money.dollar(4)) bank = Bank() result = bank.reduce(sum, 'USD') self.assertEquals(Money.dollar(7), result)
def testPlusReturnsSum(self): five = Money.dollar(5) sum = five.plus(five) self.assertEquals(five, sum.augend) self.assertEquals(five, sum.addend)
def convert_to_default(self): return Money(OriginalMoney.convert_to_default(self))
def testEquality(self): self.assertTrue(Money.dollar(5) == Money.dollar(5)) self.assertFalse(Money.dollar(5) == Money.dollar(6)) self.assertFalse(Money.franc(5) == Money.dollar(5))
def testCurrency(self): self.assertEquals('USD', Money.dollar(1).currency) self.assertEquals('CHF', Money.franc(1).currency)
def testReduceMoney(self): bank = Bank() result = bank.reduce(Money.dollar(1), 'USD') self.assertEquals(Money.dollar(1), result)
def test_multiply(self): money = Money(2) money.multiply(3) self.assertEqual(6, money.get_amount())