def render(self, context): money = self.money.resolve(context) if self.money else None amount = self.amount.resolve(context) if self.amount else None currency = self.currency.resolve(context) if self.currency else None if money is not None: if isinstance(money, Money): money = MoneyPatched._patch_to_current_class(money) else: raise TemplateSyntaxError('The variable "money" must be an ' 'instance of Money.') elif amount is not None and currency is not None: money = MoneyPatched(float(amount), str(currency)) else: raise TemplateSyntaxError('You must define both variables: ' 'amount and currency.') money.use_l10n = self.use_l10n if self.var_name is None: return money # as <var_name> context[self.var_name.token] = money return ''
def _possible_earnings_per_week(self): earnings = MoneyPatched(0, 'USD') hourly_earnings = MoneyPatched(0, 'USD') for chore in self.chores.filter(active=True): if chore.frequency == chore.DAILY: earnings += 7 * chore.value elif chore.frequency == chore.WEEKLY: earnings += chore.value elif chore.frequency == chore.HOURLY: hourly_earnings += chore.value msg = str(earnings) + ' + ' + str(hourly_earnings) + ' per hour' return msg
def testOnOff(self): # with a tag template "money_localize" self.assertTemplate( '{% load djmoney %}{% money_localize money %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) # without a tag template "money_localize" self.assertTemplate( '{{ money }}', '2,30 zł', context={'money': MoneyPatched(2.3, 'PLN')}) with self.settings(USE_L10N=False): # money_localize has a default setting USE_L10N = True self.assertTemplate( '{% load djmoney %}{% money_localize money %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) # without a tag template "money_localize" self.assertTemplate( '{{ money }}', '2.30 zł', context={'money': MoneyPatched(2.3, 'PLN')}) mp = MoneyPatched(2.3, 'PLN') mp.use_l10n = True self.assertTemplate( '{{ money }}', '2,30 zł', context={'money': mp}) self.assertTemplate( '{% load djmoney %}{% money_localize money on %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) with self.settings(USE_L10N=False): self.assertTemplate( '{% load djmoney %}{% money_localize money on %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) self.assertTemplate( '{% load djmoney %}{% money_localize money off %}', '2.30 zł', context={'money': Money(2.3, 'PLN')})
def test_sub(self): with patch('djmoney.models.fields.convert_money', side_effect=lambda amount, cur_from, cur_to: Money( (amount * Decimal(0.88)), cur_to)): result = MoneyPatched(10, 'EUR') - Money(1, 'USD') self.assertEqual(round(result.amount, 2), 9.23) self.assertEqual(result.currency, moneyed.EUR)
def test_djmoney_rates_not_installed(self, settings): settings.AUTO_CONVERT_MONEY = True settings.INSTALLED_APPS.remove('djmoney_rates') with pytest.raises(ImproperlyConfigured) as exc: MoneyPatched(10, 'EUR') - Money(1, 'USD') assert str(exc.value) == 'You must install djmoney-rates to use AUTO_CONVERT_MONEY = True'
def compare_field(self, field, obj_value, data_value): if re.match(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$', str(data_value)): data_value = datetime.datetime.strptime(str(data_value), '%Y-%m-%dT%H:%M:%S.%fZ') obj_value = datetime.datetime.strptime( str(obj_value)[:min(26, len(str(obj_value)))], '%Y-%m-%d %H:%M:%S.%f') elif isinstance(obj_value, (int, long, float)): data_value = int(float(data_value)) obj_value = int(float(obj_value)) elif hasattr(obj_value, 'id'): obj_value = obj_value.id elif isinstance(obj_value, MoneyPatched): data_value = MoneyPatched(Decimal(data_value), currency='BYN') elif type(obj_value) != type(data_value): obj_value = str(obj_value) data_value = str(data_value) self.assertEqual( obj_value, data_value, '{} not equal (db: {}, r: {})'.format(field, obj_value, data_value))
def test_migration_serialization(): imports = set(['import djmoney.models.fields']) if PY2: serialized = 'djmoney.models.fields.MoneyPatched(100, b\'GBP\')' else: serialized = 'djmoney.models.fields.MoneyPatched(100, \'GBP\')' assert MigrationWriter.serialize(MoneyPatched(100, 'GBP')) == (serialized, imports)
def employee_pay(self): """ Return each employee's pay for this session in a dict of: {TKEmployee: MoneyPatched(USD)} """ return { emp: MoneyPatched(emp.wage.amount * Decimal(self.hours()), USD) for emp in self.employees.all() }
def testOnOff(self): # with a tag template "money_localize" self.assertTemplate('{% load djmoney %}{% money_localize money %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) # without a tag template "money_localize" self.assertTemplate('{{ money }}', '2,30 zł', context={'money': MoneyPatched(2.3, 'PLN')}) with self.settings(USE_L10N=False): # money_localize has a default setting USE_L10N = True self.assertTemplate('{% load djmoney %}{% money_localize money %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) # without a tag template "money_localize" self.assertTemplate('{{ money }}', '2.30 zł', context={'money': MoneyPatched(2.3, 'PLN')}) mp = MoneyPatched(2.3, 'PLN') mp.use_l10n = True self.assertTemplate('{{ money }}', '2,30 zł', context={'money': mp}) self.assertTemplate('{% load djmoney %}{% money_localize money on %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) with self.settings(USE_L10N=False): self.assertTemplate( '{% load djmoney %}{% money_localize money on %}', '2,30 zł', context={'money': Money(2.3, 'PLN')}) self.assertTemplate('{% load djmoney %}{% money_localize money off %}', '2.30 zł', context={'money': Money(2.3, 'PLN')})
def render(self, context): price = self.price.resolve(context) if not isinstance(price, Decimal): price = Decimal(price) try: money = convert_money(price, self.price_currency.resolve(context), self.currency.resolve(context)) patched_money = MoneyPatched._patch_to_current_class(money) if self.decimal: patched_money.decimal_places = self.decimal.resolve(context) return patched_money except template.VariableDoesNotExist: return ''
def test_string_repr_no_order(self): """ Test string representation when order is empty. """ # When purchase = mommy.make("Purchase", price=MoneyPatched(50, "DOP"), item__name="Blue Cheese", item__weight=Weight(kg=0.500), item__brand__name="Generic", order=None, location=self.location) # Then self.assertEqual(str(purchase), "Blue Cheese (Generic), 0.5 kg at 50.00 DOP - #N/A")
def render(self, context): price = self.price.resolve(context) if not isinstance(price, Decimal): price = Decimal(price) try: money = convert_money( price, self.price_currency.resolve(context), self.currency.resolve(context) ) patched_money = MoneyPatched._patch_to_current_class(money) if self.decimal: patched_money.decimal_places = self.decimal.resolve(context) return patched_money except template.VariableDoesNotExist: return ''
'0.00 zł', { 'money': Money(0, 'PLN') }), ( # with a tag template "money_localize" '{% load djmoney %}{% money_localize money %}', '2,30 zł', { 'money': Money(2.3, 'PLN') }), ( # without a tag template "money_localize" '{{ money }}', '2,30 zł', { 'money': MoneyPatched(2.3, 'PLN') }), ('{% load djmoney %}{% money_localize money off %}', '2.30 zł', { 'money': Money(2.3, 'PLN') }), ('{% load djmoney %}{% money_localize money on %}', '2,30 zł', { 'money': Money(2.3, 'PLN') }))) def test_tag(string, result, context): assert_template(string, result, context) @pytest.mark.parametrize( 'string, result, context', ( (
def _money_from_obj(self, obj): amount = obj.__dict__[self.field.name] currency = obj.__dict__[self.currency_field_name] if amount is None: return None return MoneyPatched(amount=amount, currency=currency)
def test_exception(self): with pytest.raises(TypeError): MoneyPatched(10, 'EUR') == Money(10, 'USD')
def test_ne(self): assert MoneyPatched(1, 'EUR') != Money(2, 'EUR')
def test_eq(self): assert MoneyPatched(1, 'EUR') == Money(1, 'EUR')
def test_sub(self): result = MoneyPatched(10, 'EUR') - Money(1, 'USD') assert Decimal(str(round(result.amount, 2))) == Decimal('9.23') assert result.currency == moneyed.EUR
def test_deprecation(): with pytest.warns(None) as warnings: MoneyPatched(1, 'USD') assert str(warnings[0].message) == "'djmoney.models.fields.MoneyPatched' is deprecated. " \ "Use 'djmoney.money.Money' instead"
def test_forced_l10n(): mp = MoneyPatched(2.3, 'PLN') mp.use_l10n = True assert_template('{{ money }}', '2,30 zł', {'money': mp})
def test_eq(self): self.assertEqual(MoneyPatched(1, 'EUR'), Money(1, 'EUR')) self.assertNotEqual(MoneyPatched(1, 'EUR'), Money(2, 'EUR')) with self.assertRaises(TypeError): MoneyPatched(10, 'EUR') == Money(10, 'USD')
def test_sub_default(self): with pytest.raises(TypeError): MoneyPatched(10, 'EUR') - Money(1, 'USD')
def test_override_decorator(): """ When current locale is changed, MoneyPatched instances should be represented correctly. """ with override('cs'): assert str(MoneyPatched(10, 'CZK')) == 'Kč10.00'
def test_incompatibility(self, settings): settings.AUTO_CONVERT_MONEY = True with pytest.raises(ImproperlyConfigured) as exc: MoneyPatched(10, 'EUR') - Money(1, 'USD') assert str(exc.value) == 'djmoney_rates doesn\'t support Django 1.9+'
def test_add(self): result = MoneyPatched(10, 'EUR') + Money(1, 'USD') assert Decimal(str(round(result.amount, 2))) == Decimal('10.88') assert result.currency == moneyed.EUR
def test_sub_with_auto_convert(self, settings): settings.AUTO_CONVERT_MONEY = True result = MoneyPatched(10, 'EUR') - Money(1, 'USD') assert Decimal(str(round(result.amount, 2))) == Decimal('9.23') assert result.currency == moneyed.EUR
class Capsule(TimeStamped): """ Capsule model. """ flavor = models.CharField(max_length=100) price_cost = MoneyField(max_digits=10, decimal_places=2, validators=[MinValueValidator(MoneyPatched(0, 'BRL'))]) price_sale = MoneyField(max_digits=10, decimal_places=2, validators=[MinValueValidator(MoneyPatched(0, 'BRL'))]) cod_vendor = models.CharField(max_length=100, blank=True, null=True) is_active = models.BooleanField(default=True) @staticmethod def create(flavor, price_cost, price_sale, cod_vendor, is_active): """ Create a capsule. """ capsule = Capsule() capsule.flavor = flavor capsule.is_active = is_active capsule.save() return capsule
def test_ne_currency(self): assert MoneyPatched(10, 'EUR') != Money(10, 'USD')