Exemplo n.º 1
0
    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 ''
Exemplo n.º 2
0
    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 ''
Exemplo n.º 3
0
 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
Exemplo n.º 4
0
    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')})
Exemplo n.º 5
0
 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)
Exemplo n.º 6
0
    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'
Exemplo n.º 7
0
    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))
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
 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()
     }
Exemplo n.º 10
0
    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')})
Exemplo n.º 11
0
 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 ''
Exemplo n.º 12
0
    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")
Exemplo n.º 13
0
 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 ''
Exemplo n.º 14
0
         '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',
    (
        (
Exemplo n.º 15
0
 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)
Exemplo n.º 16
0
 def test_exception(self):
     with pytest.raises(TypeError):
         MoneyPatched(10, 'EUR') == Money(10, 'USD')
Exemplo n.º 17
0
 def test_ne(self):
     assert MoneyPatched(1, 'EUR') != Money(2, 'EUR')
Exemplo n.º 18
0
 def test_eq(self):
     assert MoneyPatched(1, 'EUR') == Money(1, 'EUR')
Exemplo n.º 19
0
 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
Exemplo n.º 20
0
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"
Exemplo n.º 21
0
def test_forced_l10n():
    mp = MoneyPatched(2.3, 'PLN')
    mp.use_l10n = True
    assert_template('{{ money }}', '2,30 zł', {'money': mp})
Exemplo n.º 22
0
 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')
Exemplo n.º 23
0
 def test_sub_default(self):
     with pytest.raises(TypeError):
         MoneyPatched(10, 'EUR') - Money(1, 'USD')
Exemplo n.º 24
0
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'
Exemplo n.º 25
0
 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+'
Exemplo n.º 26
0
 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
Exemplo n.º 27
0
 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
Exemplo n.º 28
0
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
Exemplo n.º 29
0
def test_forced_l10n():
    mp = MoneyPatched(2.3, 'PLN')
    mp.use_l10n = True
    assert_template('{{ money }}', '2,30 zł', {'money': mp})
Exemplo n.º 30
0
 def test_ne_currency(self):
     assert MoneyPatched(10, 'EUR') != Money(10, 'USD')