From f320eb8aafbceafbbfca02617db4846b3571e598 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Isma=C3=ABl=20Bouya?= Date: Mon, 12 Feb 2018 02:13:17 +0100 Subject: [PATCH] Add missing amount operations --- portfolio.py | 8 ++++++++ test.py | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/portfolio.py b/portfolio.py index 17a17ba..21a9834 100644 --- a/portfolio.py +++ b/portfolio.py @@ -124,6 +124,8 @@ class Amount: return Amount(self.currency, abs(self.value)) def __add__(self, other): + if other == 0: + return self if other.currency != self.currency and other.value * self.value != 0: raise Exception("Summing amounts must be done with same currencies") return Amount(self.currency, self.value + other.value) @@ -141,6 +143,12 @@ class Amount: raise Exception("Summing amounts must be done with same currencies") return Amount(self.currency, self.value - other.value) + def __rsub__(self, other): + if other == 0: + return -self + else: + return -self.__sub__(other) + def __mul__(self, value): if not isinstance(value, (int, float, D)): raise TypeError("Amount may only be multiplied by numbers") diff --git a/test.py b/test.py index 1965521..c496e11 100644 --- a/test.py +++ b/test.py @@ -220,6 +220,8 @@ class AmountTest(WebMockTestCase): amount4 = portfolio.Amount("ETH", 0.0) self.assertEqual(amount1, amount1 + amount4) + self.assertEqual(amount1, amount1 + 0) + def test__radd(self): amount = portfolio.Amount("XVG", "12.9") @@ -241,6 +243,13 @@ class AmountTest(WebMockTestCase): amount4 = portfolio.Amount("ETH", 0.0) self.assertEqual(amount1, amount1 - amount4) + def test__rsub(self): + amount = portfolio.Amount("ETH", "1.6") + with self.assertRaises(Exception): + 3 - amount + + self.assertEqual(portfolio.Amount("ETH", "-1.6"), -amount) + def test__mul(self): amount = portfolio.Amount("XEM", 11) -- 2.41.0