From: Ismaƫl Bouya Date: Mon, 12 Feb 2018 01:13:17 +0000 (+0100) Subject: Add missing amount operations X-Git-Tag: v0.1~9 X-Git-Url: https://git.immae.eu/?a=commitdiff_plain;h=f320eb8aafbceafbbfca02617db4846b3571e598;hp=0c79fad318711394874d94672e96db6da1ed9c52;p=perso%2FImmae%2FProjets%2FCryptomonnaies%2FCryptoportfolio%2FTrader.git Add missing amount operations --- 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)