Skip to content

Commit

Permalink
fix: Copying attributes from non Money classes
Browse files Browse the repository at this point in the history
  • Loading branch information
tned73 committed Sep 4, 2021
1 parent 305df73 commit 2214aa8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
4 changes: 2 additions & 2 deletions djmoney/money.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ def _copy_attributes(self, source, target):
"""
for attribute_name in ("decimal_places", "_decimal_places_display"):
selection = [
getattr(candidate, attribute_name, 0)
getattr(candidate, attribute_name, None)
for candidate in (self, source)
if getattr(candidate, attribute_name, 0) is not None
if getattr(candidate, attribute_name, None) is not None
]
if selection:
value = max(selection)
Expand Down
26 changes: 19 additions & 7 deletions tests/test_money.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,13 +187,25 @@ def test_proper_copy_of_attributes(decimal_places_display, decimal_places):
assert two._decimal_places_display is None, "default value"
assert two.decimal_places == decimal_places

three = Money(3, "EUR")
one._copy_attributes(two, three)
result = Money(3, "EUR")
one._copy_attributes(two, result)

assert three._decimal_places_display == decimal_places_display
assert three.decimal_places == max(2, decimal_places) if decimal_places is not None else 2
assert result._decimal_places_display == decimal_places_display
assert result.decimal_places == max(2, decimal_places) if decimal_places is not None else 2

zero = Money(0, "EUR")
one._copy_attributes(Money(1, "EUR", decimal_places_display=3), zero)
result = Money(0, "EUR")
one._copy_attributes(Money(1, "EUR", decimal_places_display=3), result)

assert zero._decimal_places_display == max(3, decimal_places_display) if decimal_places_display is not None else 3
assert result._decimal_places_display == max(3, decimal_places_display) if decimal_places_display is not None else 3

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

0 comments on commit 2214aa8

Please sign in to comment.