Skip to content

Commit

Permalink
Add Money.__abs__ and Money.__hash__
Browse files Browse the repository at this point in the history
  • Loading branch information
zzzsochi committed Feb 14, 2017
1 parent 8ac4f3d commit fb03e0e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
16 changes: 16 additions & 0 deletions tests/test_fields_money.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,22 @@ def test_money_str(self, iv, cur, ov):
def test_money_cents(self, func, iv, cur, ov):
assert func(fields.Money(iv, cur)) == ov

def tests_abs(self):
value = abs(fields.Money('-3.14', 'RUB'))
assert isinstance(value, fields.Money)
assert value.currency.string == 'RUB'
assert value > 0
assert value.total_cents > 0

@pytest.mark.parametrize('first, seccond, equal', [
(fields.Money('3.14', 'RUB'), fields.Money('3.14', 'RUB'), True),
(fields.Money('3.14', 'RUB'), fields.Money('2.48', 'RUB'), False),
(fields.Money('3.14', 'RUB'), fields.Money('-3.14', 'RUB'), False),
(fields.Money('3.14', 'RUB'), fields.Money('3.14', 'EUR'), False),
])
def tests_hash(self, first, seccond, equal):
assert (hash(first) == hash(seccond)) is equal


class TestCurrencyStorage:
@pytest.mark.parametrize('key, code, string, precision', [
Expand Down
8 changes: 7 additions & 1 deletion yadm/fields/money/money.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class DocClass(Document):
{
id: ObjectId('534272984c78591787e1a964'),
money: {v: 314, c: 840}
money: {v: 314, c: 'USD'}
}
"""
from decimal import Decimal, Context, ROUND_UP
Expand Down Expand Up @@ -132,6 +132,9 @@ def total_cents(self) -> int:
quantized = self.value.quantize(precision_decimal, ROUND_UP)
return int(quantized * 10 ** precision)

def __abs__(self):
return self.__class__(abs(self._value), self.currency)

@_checker
def __add__(self, target):
return self.__class__(self.value + target.value, self.currency)
Expand Down Expand Up @@ -179,6 +182,9 @@ def __le__(self, other):
def __bool__(self):
return bool(self.value)

def __hash__(self):
return hash(str(self))

def __str__(self):
precision = self.currency.precision
precision_decimal = Decimal('1.' + '0' * precision)
Expand Down

0 comments on commit fb03e0e

Please sign in to comment.