From d29ff6f488c9d0478d29dd32a77e2fe0e76e4fb6 Mon Sep 17 00:00:00 2001
From: Anton Agestam <git@antonagestam.se>
Date: Mon, 19 Apr 2021 17:21:12 +0200
Subject: [PATCH 01/16] Drop support for legacy versions
- Drop support for Django 1.11, 2.1 and 3.0.
- Drop support for Python 3.5.
---
.github/workflows/main.yml | 2
djmoney/models/fields.py | 4 -
djmoney/money.py | 52 +---------------------
djmoney/settings.py | 15 +-----
docs/changes.rst | 15 ++++++
pytest.ini | 3 -
setup.py | 2
tests/conftest.py | 8 ---
tests/contrib/test_django_rest_framework.py | 3 -
tests/settings.py | 16 -------
tests/test_admin.py | 19 --------
tests/test_models.py | 62 +++++++++++++++++----------
tests/test_money.py | 64 ++++------------------------
tests/test_tags.py | 35 ---------------
tests/testapp/models.py | 2
15 files changed, 80 insertions(+), 222 deletions(-)
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -13,7 +13,7 @@ jobs:
- uses: actions/setup-python@v2
with:
- python-version: 3.7
+ python-version: 3.9
- run: pip install pre-commit
- run: pre-commit run --all-files
--- a/djmoney/models/fields.py
+++ b/djmoney/models/fields.py
@@ -213,7 +213,7 @@ class MoneyField(models.DecimalField):
elif isinstance(default, OldMoney):
default = Money(default.amount, default.currency)
if default is not None and default is not NOT_PROVIDED and not isinstance(default, Money):
- raise ValueError("default value must be an instance of Money, is: %s" % default)
+ raise ValueError(f"default value must be an instance of Money, is: {default}")
return default
def to_python(self, value):
@@ -261,7 +261,7 @@ class MoneyField(models.DecimalField):
default=self.default_currency,
editable=False,
choices=self.currency_choices,
- null=self.default_currency is None,
+ null=self.null,
)
currency_field.creation_counter = self.creation_counter - 1
currency_field_name = get_currency_field_name(name, self)
--- a/djmoney/money.py
+++ b/djmoney/money.py
@@ -1,5 +1,3 @@
-import warnings
-from functools import partial
from types import MappingProxyType
from django.conf import settings
@@ -10,20 +8,13 @@ from django.utils.html import avoid_wrap
from django.utils.safestring import mark_safe
import moneyed.l10n
-import moneyed.localization
from moneyed import Currency, Money as DefaultMoney
-from .settings import DECIMAL_PLACES, DECIMAL_PLACES_DISPLAY, IS_DECIMAL_PLACES_DISPLAY_SET, MONEY_FORMAT
+from .settings import DECIMAL_PLACES, MONEY_FORMAT
__all__ = ["Money", "Currency"]
-_warn_decimal_places_display_deprecated = partial(
- warnings.warn,
- "`Money.decimal_places_display` is deprecated and will be removed in django-money 3.0.",
- DeprecationWarning,
-)
-
@deconstructible
class Money(DefaultMoney):
@@ -33,27 +24,11 @@ class Money(DefaultMoney):
use_l10n = None
- def __init__(self, *args, decimal_places_display=None, format_options=None, **kwargs):
+ def __init__(self, *args, format_options=None, **kwargs):
self.decimal_places = kwargs.pop("decimal_places", DECIMAL_PLACES)
- self._decimal_places_display = decimal_places_display
- if decimal_places_display is not None:
- _warn_decimal_places_display_deprecated()
self.format_options = MappingProxyType(format_options) if format_options is not None else None
super().__init__(*args, **kwargs)
- @property
- def decimal_places_display(self):
- _warn_decimal_places_display_deprecated()
- if self._decimal_places_display is None:
- return DECIMAL_PLACES_DISPLAY.get(self.currency.code, self.decimal_places)
- return self._decimal_places_display
-
- @decimal_places_display.setter
- def decimal_places_display(self, value):
- """ Set number of digits being displayed - `None` resets to `DECIMAL_PLACES_DISPLAY` setting """
- _warn_decimal_places_display_deprecated()
- self._decimal_places_display = value
-
def _copy_attributes(self, source, target):
"""Copy attributes to the new `Money` instance.
@@ -118,13 +93,6 @@ class Money(DefaultMoney):
return self.use_l10n
def __str__(self):
- if self._decimal_places_display is not None or IS_DECIMAL_PLACES_DISPLAY_SET:
- kwargs = {"money": self, "decimal_places": self.decimal_places_display}
- if self.is_localized:
- locale = get_current_locale(for_babel=False)
- if locale:
- kwargs["locale"] = locale
- return moneyed.localization.format_money(**kwargs)
format_options = {
**MONEY_FORMAT,
**(self.format_options or {}),
@@ -175,22 +143,10 @@ class Money(DefaultMoney):
__rmul__ = __mul__
-def get_current_locale(for_babel=True):
+def get_current_locale():
# get_language can return None starting from Django 1.8
language = translation.get_language() or settings.LANGUAGE_CODE
- locale = translation.to_locale(language)
-
- if for_babel:
- return locale
-
- if locale.upper() in moneyed.localization._FORMATTER.formatting_definitions:
- return locale
-
- locale = f"{locale}_{locale}".upper()
- if locale in moneyed.localization._FORMATTER.formatting_definitions:
- return locale
-
- return ""
+ return translation.to_locale(language)
def maybe_convert(value, currency):
--- a/djmoney/settings.py
+++ b/djmoney/settings.py
@@ -1,15 +1,14 @@
import operator
-import warnings
from types import MappingProxyType
from django.conf import settings
-from moneyed import CURRENCIES, DEFAULT_CURRENCY, DEFAULT_CURRENCY_CODE
+from moneyed import CURRENCIES, Currency
# The default currency, you can define this in your project's settings module
# This has to be a currency object imported from moneyed
-DEFAULT_CURRENCY = getattr(settings, "DEFAULT_CURRENCY", DEFAULT_CURRENCY)
+DEFAULT_CURRENCY: Currency = getattr(settings, "DEFAULT_CURRENCY", None)
# The default currency choices, you can define this in your project's
@@ -21,18 +20,10 @@ if CURRENCY_CHOICES is None:
if PROJECT_CURRENCIES:
CURRENCY_CHOICES = [(code, CURRENCIES[code].name) for code in PROJECT_CURRENCIES]
else:
- CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if c.code != DEFAULT_CURRENCY_CODE]
+ CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if c != DEFAULT_CURRENCY]
CURRENCY_CHOICES.sort(key=operator.itemgetter(1, 0))
DECIMAL_PLACES = getattr(settings, "CURRENCY_DECIMAL_PLACES", 2)
-_decimal_display_value = getattr(settings, "CURRENCY_DECIMAL_PLACES_DISPLAY", None)
-if _decimal_display_value is not None:
- warnings.warn(
- "`CURRENCY_DECIMAL_PLACES_DISPLAY` is deprecated and will be removed in django-money 3.0.",
- DeprecationWarning,
- )
-DECIMAL_PLACES_DISPLAY = _decimal_display_value or {currency[0]: DECIMAL_PLACES for currency in CURRENCY_CHOICES}
-IS_DECIMAL_PLACES_DISPLAY_SET = _decimal_display_value is not None
OPEN_EXCHANGE_RATES_URL = getattr(settings, "OPEN_EXCHANGE_RATES_URL", "https://openexchangerates.org/api/latest.json")
OPEN_EXCHANGE_RATES_APP_ID = getattr(settings, "OPEN_EXCHANGE_RATES_APP_ID", None)
--- a/docs/changes.rst
+++ b/docs/changes.rst
@@ -4,6 +4,12 @@ Changelog
`Unreleased`_ - TBA
-------------------
+**Changed**
+- Update py-moneyed to 2.0. `#638`_ (`antonagestam`_, `flaeppe`_, `paoloxnet`_)
+- Remove the deprecated ``Money.decimal_places_display`` property and argument. `#638`_ (`antonagestam`_, `flaeppe`_, `paoloxnet`_)
+- Remove the deprecated ``CURRENCY_DECIMAL_PLACES_DISPLAY`` setting. `#638`_ (`antonagestam`_, `flaeppe`_, `paoloxnet`_)
+- Null constraint on an implicit ``CurrencyField`` is now declared from ``null=...`` argument to ``MoneyField``. `#638`_ (`antonagestam`_, `flaeppe`_, `paoloxnet`_)
+
**Fixed**
- Improve the internal check for whether a currency is provided `#657`_ (`davidszotten`_)
@@ -70,6 +76,13 @@ Changelog
- ``Money.decimal_places_display`` will be removed in django-money 3.0.
- ``CURRENCY_DECIMAL_PLACES_DISPLAY`` will be removed in django-money 3.0.
+- Drop support for Django 1.11, 2.1 and 3.0.
+- Drop support for Python 3.5.
+- Add support for Django 3.2.
+- Update py-moneyed to 2.0.
+- Remove the deprecated ``Money.decimal_places_display`` property and argument.
+- Remove the deprecated ``CURRENCY_DECIMAL_PLACES_DISPLAY`` setting.
+
`1.3.1`_ - 2021-02-04
---------------------
@@ -783,6 +796,7 @@ wrapping with ``money_manager``.
.. _#657: https://github.com/django-money/django-money/issues/657
.. _#648: https://github.com/django-money/django-money/issues/648
.. _#646: https://github.com/django-money/django-money/issues/646
+.. _#638: https://github.com/django-money/django-money/issues/638
.. _#637: https://github.com/django-money/django-money/issues/637
.. _#630: https://github.com/django-money/django-money/pull/630
.. _#629: https://github.com/django-money/django-money/pull/629
@@ -951,6 +965,7 @@ wrapping with ``money_manager``.
.. _mstarostik: https://github.com/mstarostik
.. _niklasb: https://github.com/niklasb
.. _nerdoc: https://github.com/nerdoc
+.. _paoloxnet: https://github.com/paoloxnet
.. _pjdelport: https://github.com/pjdelport
.. _plumdog: https://github.com/plumdog
.. _rach: https://github.com/rach
--- a/pytest.ini
+++ b/pytest.ini
@@ -2,6 +2,3 @@
DJANGO_SETTINGS_MODULE=tests.settings
filterwarnings =
error::DeprecationWarning
- ignore:This module and all its contents is deprecated in favour of new moneyed.l10n.format_money\.:DeprecationWarning
- ignore:`Money\.decimal_places_display` is deprecated and will be removed in django-money 3\.0\.:DeprecationWarning
- ignore:`CURRENCY_DECIMAL_PLACES_DISPLAY` is deprecated and will be removed in django-money 3\.0\.:DeprecationWarning
--- a/setup.py
+++ b/setup.py
@@ -66,7 +66,7 @@ setup(
maintainer_email="greg@reinbach.com",
license="BSD",
packages=find_packages(include=["djmoney", "djmoney.*"]),
- install_requires=["setuptools", "Django>=2.2", "py-moneyed>=1.2,<2.0"],
+ install_requires=["setuptools", "Django>=2.2", "py-moneyed>=2.0,<3.0"],
python_requires=">=3.6",
platforms=["Any"],
keywords=["django", "py-money", "money"],
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,5 +1,3 @@
-from unittest import mock
-
import pytest
from djmoney.contrib.exchange.models import ExchangeBackend, Rate, get_default_backend_name
@@ -31,9 +29,3 @@ def concrete_instance(m2m_object):
pytest_plugins = "pytester"
-
-
-@pytest.yield_fixture
-def legacy_formatting():
- with mock.patch("djmoney.money.IS_DECIMAL_PLACES_DISPLAY_SET", True):
- yield
--- a/tests/contrib/test_django_rest_framework.py
+++ b/tests/contrib/test_django_rest_framework.py
@@ -64,10 +64,9 @@ class TestMoneyField:
(NullMoneyFieldModel, "field", {"default_currency": "EUR", "allow_null": True}, None, None),
(NullMoneyFieldModel, "field", None, Money(10, "USD"), Money(10, "USD")),
(NullMoneyFieldModel, "field", {"default_currency": "EUR"}, Money(10, "USD"), Money(10, "USD")),
- (NullMoneyFieldModel, "field", {"default_currency": "EUR"}, 10, Money(10, "EUR")),
+ (ModelWithVanillaMoneyField, "money", {"default_currency": "EUR"}, 10, Money(10, "EUR")),
(ModelWithVanillaMoneyField, "money", None, Money(10, "USD"), Money(10, "USD")),
(ModelWithVanillaMoneyField, "money", {"default_currency": "EUR"}, Money(10, "USD"), Money(10, "USD")),
- (ModelWithVanillaMoneyField, "money", None, 10, Money(10, "XYZ")),
(ModelWithVanillaMoneyField, "money", {"default_currency": "EUR"}, 10, Money(10, "EUR")),
),
)
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -1,8 +1,6 @@
import warnings
-from decimal import ROUND_HALF_EVEN
import moneyed
-from moneyed.localization import _FORMATTER, DEFAULT
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
@@ -36,20 +34,6 @@ SECRET_KEY = "foobar"
USE_L10N = True
-_FORMATTER.add_sign_definition("pl_PL", moneyed.PLN, suffix=" zł")
-_FORMATTER.add_sign_definition(DEFAULT, moneyed.PLN, suffix=" zł")
-_FORMATTER.add_formatting_definition(
- "pl_PL",
- group_size=3,
- group_separator=" ",
- decimal_point=",",
- positive_sign="",
- trailing_positive_sign="",
- negative_sign="-",
- trailing_negative_sign="",
- rounding_method=ROUND_HALF_EVEN,
-)
-
moneyed.add_currency("USDT", "000", "Tether", None)
OPEN_EXCHANGE_RATES_APP_ID = "test"
--- a/tests/test_admin.py
+++ b/tests/test_admin.py
@@ -14,26 +14,7 @@ INTEGER_FIELD = ModelWithVanillaMoneyFie
@pytest.mark.parametrize(
"value, expected",
(
- (Money(10, "RUB"), "10.00 руб."), # Issue 232
- (Money(1234), "1,234.00 XYZ"), # Issue 220
- (Money(1000, "SAR"), "ر.س1,000.00"), # Issue 196
- (Money(1000, "PLN"), "1,000.00 zł"), # Issue 102
- (Money("3.33", "EUR"), "3.33 €"), # Issue 90
- ),
-)
-def test_display_for_field_with_legacy_formatting(legacy_formatting, settings, value, expected):
- settings.USE_L10N = True
- # This locale has no definitions in py-moneyed, so it will work for localized money representation.
- settings.LANGUAGE_CODE = "cs"
- settings.DECIMAL_PLACES_DISPLAY = {}
- assert admin_utils.display_for_field(value, MONEY_FIELD, "") == expected
-
-
-@pytest.mark.parametrize(
- "value, expected",
- (
(Money(10, "RUB"), "10,00\xa0RUB"), # Issue 232
- (Money(1234), "1\xa0234,00\xa0XYZ"), # Issue 220
(Money(1000, "SAR"), "1\xa0000,00\xa0SAR"), # Issue 196
(Money(1000, "PLN"), "1\xa0000,00\xa0PLN"), # Issue 102
(Money("3.33", "EUR"), "3,33\xa0€"), # Issue 90
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -60,8 +60,8 @@ class TestVanillaMoneyField:
@pytest.mark.parametrize(
"model_class, kwargs, expected",
(
- (ModelWithVanillaMoneyField, {"money": Money("100.0")}, Money("100.0")),
- (ModelWithVanillaMoneyField, {"money": OldMoney("100.0")}, Money("100.0")),
+ (ModelWithVanillaMoneyField, {"money": Money("100.0", "USD")}, Money("100.0", "USD")),
+ (ModelWithVanillaMoneyField, {"money": OldMoney("100.0", "USD")}, Money("100.0", "USD")),
(BaseModel, {}, Money(0, "USD")),
(BaseModel, {"money": "111.2"}, Money("111.2", "USD")),
(BaseModel, {"money": Money("123", "PLN")}, Money("123", "PLN")),
@@ -116,7 +116,6 @@ class TestVanillaMoneyField:
@pytest.mark.parametrize(
"model_class, other_value",
(
- (ModelWithVanillaMoneyField, Money("100.0")),
(BaseModel, Money(0, "USD")),
(ModelWithDefaultAsMoney, Money("0.01", "RUB")),
(ModelWithDefaultAsFloat, OldMoney("12.05", "PLN")),
@@ -149,27 +148,35 @@ class TestVanillaMoneyField:
BaseModel.objects.create(money=value)
@pytest.mark.parametrize("money_class", (Money, OldMoney))
- @pytest.mark.parametrize("field_name", ("money", "second_money"))
- def test_save_new_value(self, field_name, money_class):
- ModelWithVanillaMoneyField.objects.create(**{field_name: money_class("100.0")})
+ def test_save_new_value_on_field_without_default(self, money_class):
+ ModelWithVanillaMoneyField.objects.create(money=money_class("100.0", "DKK"))
# Try setting the value directly
retrieved = ModelWithVanillaMoneyField.objects.get()
- setattr(retrieved, field_name, Money(1, "DKK"))
+ retrieved.money = Money(1, "DKK")
retrieved.save()
retrieved = ModelWithVanillaMoneyField.objects.get()
+ assert retrieved.money == Money(1, "DKK")
- assert getattr(retrieved, field_name) == Money(1, "DKK")
+ def test_save_new_value_on_field_with_default(self):
+ ModelWithDefaultAsMoney.objects.create()
+
+ # Try setting the value directly
+ retrieved = ModelWithDefaultAsMoney.objects.get()
+ retrieved.money = Money(1, "DKK")
+ retrieved.save()
+ retrieved = ModelWithDefaultAsMoney.objects.get()
+ assert retrieved.money == Money(1, "DKK")
def test_rounding(self):
- money = Money("100.0623456781123219")
+ money = Money("100.0623456781123219", "USD")
instance = ModelWithVanillaMoneyField.objects.create(money=money)
# TODO. Should instance.money be rounded too?
retrieved = ModelWithVanillaMoneyField.objects.get(pk=instance.pk)
- assert retrieved.money == Money("100.06")
+ assert retrieved.money == Money("100.06", "USD")
@pytest.fixture(params=[Money, OldMoney])
def objects_setup(self, request):
@@ -238,7 +245,7 @@ class TestVanillaMoneyField:
assert ModelWithTwoMoneyFields.objects.filter(**kwargs).count() == expected
def test_exact_match(self):
- money = Money("100.0")
+ money = Money("100.0", "USD")
instance = ModelWithVanillaMoneyField.objects.create(money=money)
retrieved = ModelWithVanillaMoneyField.objects.get(money=money)
@@ -251,9 +258,9 @@ class TestVanillaMoneyField:
ModelIssue300.objects.filter(money__created__gt=date)
def test_range_search(self):
- money = Money("3")
+ money = Money("3", "EUR")
- instance = ModelWithVanillaMoneyField.objects.create(money=Money("100.0"))
+ instance = ModelWithVanillaMoneyField.objects.create(money=Money("100.0", "EUR"))
retrieved = ModelWithVanillaMoneyField.objects.get(money__gt=money)
assert instance.pk == retrieved.pk
@@ -302,12 +309,23 @@ class TestVanillaMoneyField:
instance = NullMoneyFieldModel.objects.create()
assert instance.field is None
+ def test_raises_type_error_setting_currency_to_none_on_nullable_currency_field_while_having_amount(self):
+ with pytest.raises(ValueError, match=r"Missing currency value"):
+ NullMoneyFieldModel(field=10, field_currency=None)
+
+ def test_currency_field_null_switch_not_triggered_from_default_currency(self):
+ # We want a sane default behaviour and simply declaring a `MoneyField(...)`
+ # without any default value args should create non nullable amount and currency
+ # fields
+ assert not ModelWithVanillaMoneyField._meta.get_field("money").null
+ assert not ModelWithVanillaMoneyField._meta.get_field("money_currency").null
+
class TestGetOrCreate:
@pytest.mark.parametrize(
"model, field_name, kwargs, currency",
(
- (ModelWithVanillaMoneyField, "money", {"money_currency": "PLN"}, "PLN"),
+ (ModelWithDefaultAsInt, "money", {"money_currency": "PLN"}, "PLN"),
(ModelWithVanillaMoneyField, "money", {"money": Money(0, "EUR")}, "EUR"),
(ModelWithVanillaMoneyField, "money", {"money": OldMoney(0, "EUR")}, "EUR"),
(ModelWithSharedCurrency, "first", {"first": 10, "second": 15, "currency": "CZK"}, "CZK"),
@@ -381,9 +399,9 @@ class TestNullableCurrency:
assert not ModelWithNullableCurrency.objects.exists()
def test_fails_with_nullable_but_no_default(self):
- with pytest.raises(IntegrityError) as exc:
+ match = r"NOT NULL constraint failed: testapp_modelwithtwomoneyfields.amount1"
+ with pytest.raises(IntegrityError, match=match):
ModelWithTwoMoneyFields.objects.create()
- assert str(exc.value) == "NOT NULL constraint failed: testapp_modelwithtwomoneyfields.amount1"
def test_query_not_null(self):
money = Money(100, "EUR")
@@ -527,9 +545,11 @@ class TestExpressions:
assert ModelWithVanillaMoneyField.objects.get(integer=1).money == Money(0, "USD")
def test_create_func(self):
- instance = ModelWithVanillaMoneyField.objects.create(money=Func(Value(-10), function="ABS"))
+ instance = ModelWithVanillaMoneyField.objects.create(
+ money=Func(Value(-10), function="ABS"), money_currency="USD"
+ )
instance.refresh_from_db()
- assert instance.money.amount == 10
+ assert instance.money == Money(10, "USD")
@pytest.mark.parametrize(
"value, expected", ((None, None), (10, Money(10, "USD")), (Money(10, "EUR"), Money(10, "EUR")))
@@ -541,7 +561,7 @@ class TestExpressions:
def test_value_create_invalid(self):
with pytest.raises(ValidationError):
- ModelWithVanillaMoneyField.objects.create(money=Value("string"))
+ ModelWithVanillaMoneyField.objects.create(money=Value("string"), money_currency="DKK")
def test_expressions_for_non_money_fields(self):
instance = ModelWithVanillaMoneyField.objects.create(money=Money(1, "USD"), integer=0)
@@ -560,7 +580,7 @@ def test_find_models_related_to_money_mo
def test_allow_expression_nodes_without_money():
"""Allow querying on expression nodes that are not Money"""
desc = "hundred"
- ModelWithNonMoneyField.objects.create(money=Money(100.0), desc=desc)
+ ModelWithNonMoneyField.objects.create(money=Money(100.0, "USD"), desc=desc)
instance = ModelWithNonMoneyField.objects.filter(desc=F("desc")).get()
assert instance.desc == desc
@@ -793,7 +813,7 @@ def test_mixer_blend():
except AttributeError:
pass # mixer doesn't work with pypy
else:
- instance = mixer.blend(ModelWithTwoMoneyFields)
+ instance = mixer.blend(ModelWithTwoMoneyFields, amount1_currency="EUR", amount2_currency="USD")
assert isinstance(instance.amount1, Money)
assert isinstance(instance.amount2, Money)
--- a/tests/test_money.py
+++ b/tests/test_money.py
@@ -10,23 +10,19 @@ def test_repr():
def test_legacy_repr():
- assert repr(Money("10.5", "USD", decimal_places_display=2)) == "Money('10.5', 'USD')"
+ assert repr(Money("10.5", "USD")) == "Money('10.5', 'USD')"
def test_html_safe():
assert Money("10.5", "EUR").__html__() == "€10.50"
-def test_legacy_html_safe():
- assert Money("10.5", "EUR", decimal_places_display=2).__html__() == "10.50\xa0€"
-
-
def test_html_unsafe():
class UnsafeMoney(Money):
def __str__(self):
return "<script>"
- assert UnsafeMoney().__html__() == "<script>"
+ assert UnsafeMoney(100, "USD").__html__() == "<script>"
def test_default_mul():
@@ -46,18 +42,6 @@ def test_reverse_truediv_fails():
@pytest.mark.parametrize(
"locale, expected",
(
- ("pl", "PL_PL"),
- ("pl_PL", "pl_PL"),
- ),
-)
-def test_legacy_get_current_locale(locale, expected):
- with override(locale):
- assert get_current_locale(for_babel=False) == expected
-
-
-@pytest.mark.parametrize(
- "locale, expected",
- (
("pl", "pl"),
("pl-pl", "pl_PL"),
("sv", "sv"),
@@ -82,17 +66,8 @@ def test_configurable_decimal_number():
assert mny.decimal_places == 3
-def test_localize_decimal_places_default():
- # use default decimal display places from settings
- assert str(Money("10.543125", "USD")) == "$10.54"
-
-
-def test_localize_decimal_places_overwrite():
- assert str(Money("10.543125", "USD", decimal_places_display=4)) == "$10.5431"
-
-
-def test_localize_decimal_places_both():
- assert str(Money("10.543125", "USD", decimal_places=5, decimal_places_display=1)) == "$10.5"
+def test_localize_defaults_to_currency_decimal_places():
+ assert str(Money("10.543125", "USD", decimal_places=5)) == "$10.54"
def test_add_decimal_places():
@@ -117,10 +92,10 @@ def test_add_decimal_places_zero():
lambda a, d: a * 2,
lambda a, d: 2 * a,
lambda a, d: a / 5,
- lambda a, d: a - Money("2", "USD", decimal_places=d, decimal_places_display=d),
- lambda a, d: Money("2", "USD", decimal_places=d, decimal_places_display=d) - a,
- lambda a, d: a + Money("2", "USD", decimal_places=d, decimal_places_display=d),
- lambda a, d: Money("2", "USD", decimal_places=d, decimal_places_display=d) + a,
+ lambda a, d: a - Money("2", "USD", decimal_places=d),
+ lambda a, d: Money("2", "USD", decimal_places=d) - a,
+ lambda a, d: a + Money("2", "USD", decimal_places=d),
+ lambda a, d: Money("2", "USD", decimal_places=d) + a,
lambda a, d: -a,
lambda a, d: +a,
lambda a, d: abs(a),
@@ -131,19 +106,9 @@ def test_add_decimal_places_zero():
)
def test_keep_decimal_places(operation, decimal_places):
# Arithmetic operations should keep the `decimal_places` value
- amount = Money("1.0000", "USD", decimal_places=decimal_places, decimal_places_display=decimal_places)
+ amount = Money("1.0000", "USD", decimal_places=decimal_places)
new = operation(amount, decimal_places)
assert new.decimal_places == decimal_places
- assert new.decimal_places_display == decimal_places
-
-
-def test_decimal_places_display_overwrite():
- number = Money("1.23456789", "USD")
- assert str(number) == "$1.23"
- number.decimal_places_display = 5
- assert str(number) == "$1.23457"
- number.decimal_places_display = None
- assert str(number) == "$1.23"
def test_sub_negative():
@@ -177,35 +142,28 @@ def test_sub_negative():
],
)
def test_proper_copy_of_attributes(decimal_places_display, decimal_places):
- one = Money(1, "EUR", decimal_places_display=decimal_places_display)
+ one = Money(1, "EUR")
- assert one._decimal_places_display is decimal_places_display
assert one.decimal_places == 2, "default value"
two = Money(2, "EUR", decimal_places=decimal_places)
- assert two._decimal_places_display is None, "default value"
assert two.decimal_places == decimal_places
result = Money(3, "EUR")
one._copy_attributes(two, result)
- assert result._decimal_places_display == decimal_places_display
assert result.decimal_places == max(2, decimal_places) if decimal_places is not None else 2
result = Money(0, "EUR")
- one._copy_attributes(Money(1, "EUR", decimal_places_display=3), result)
-
- assert result._decimal_places_display == max(3, decimal_places_display) if decimal_places_display is not None else 3
+ one._copy_attributes(Money(1, "EUR"), result)
result = Money(0, "EUR")
one._copy_attributes(1, result)
- assert result._decimal_places_display == decimal_places_display
assert result.decimal_places == 2
result = Money(0, "EUR")
two._copy_attributes(1, result)
- assert result._decimal_places_display is None
assert result.decimal_places == decimal_places if decimal_places else 2
--- a/tests/test_tags.py
+++ b/tests/test_tags.py
@@ -56,41 +56,6 @@ def assert_template(string, result, cont
@pytest.mark.parametrize(
"string, result, context",
(
- ('{% load djmoney %}{% money_localize "2.5" "PLN" as NEW_M %}{{NEW_M}}', "2,50 zł", {}),
- ('{% load djmoney %}{% money_localize "2.5" "PLN" %}', "2,50 zł", {}),
- ("{% load djmoney %}{% money_localize amount currency %}", "2,60 zł", {"amount": 2.6, "currency": "PLN"}),
- ("{% load djmoney %}{% money_localize money as NEW_M %}{{NEW_M}}", "2,30 zł", {"money": Money(2.3, "PLN")}),
- ("{% load djmoney %}{% money_localize money off as NEW_M %}{{NEW_M}}", "2.30 zł", {"money": Money(2.3, "PLN")}),
- ("{% load djmoney %}{% money_localize money off as NEW_M %}{{NEW_M}}", "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": Money(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")}),
- (
- # in django 2.0 we fail inside the for loop
- '{% load djmoney %}{% for i in "xxx" %}{% money_localize money %} {% endfor %}',
- "2,30 zł 2,30 zł 2,30 zł ",
- {"money": Money(2.3, "PLN"), "test": "test"},
- ),
- ),
-)
-def test_tag_with_legacy_formatting(legacy_formatting, string, result, context):
- assert_template(string, result, context)
-
-
-@pytest.mark.parametrize(
- "string, result, context",
- (
('{% load djmoney %}{% money_localize "2.5" "PLN" as NEW_M %}{{NEW_M}}', "2,50\xa0zł", {}),
('{% load djmoney %}{% money_localize "2.5" "PLN" %}', "2,50\xa0zł", {}),
("{% load djmoney %}{% money_localize amount currency %}", "2,60\xa0zł", {"amount": 2.6, "currency": "PLN"}),
--- a/tests/testapp/models.py
+++ b/tests/testapp/models.py
@@ -24,7 +24,7 @@ else:
class ModelWithVanillaMoneyField(models.Model):
- money = MoneyField(max_digits=10, decimal_places=2, default=0.0)
+ money = MoneyField(max_digits=10, decimal_places=2)
second_money = MoneyField(max_digits=10, decimal_places=2, default=0.0, default_currency="EUR")
integer = models.IntegerField(default=0)