reports: Add Balance.__str__() method.

This commit is contained in:
Brett Smith 2020-04-29 11:37:38 -04:00
parent 5a1f7122bd
commit 68acb86e7e
2 changed files with 18 additions and 0 deletions

View file

@ -60,6 +60,13 @@ class Balance(Mapping[str, data.Amount]):
def __repr__(self) -> str:
return f"{type(self).__name__}({self._currency_map!r})"
def __str__(self) -> str:
amounts = [amount for amount in self.values() if amount.number]
if not amounts:
return "Zero balance"
amounts.sort(key=lambda amt: abs(amt.number), reverse=True)
return ', '.join(str(amount) for amount in amounts)
def __getitem__(self, key: str) -> data.Amount:
return data.Amount(self._currency_map[key], key)

View file

@ -66,3 +66,14 @@ def test_mixed_balance():
assert len(balance) == 2
assert not balance.is_zero()
assert all(balance[key] == amt for key, amt in amounts.items())
@pytest.mark.parametrize('balance_map_kwargs,expected', [
({}, "Zero balance"),
({'JPY': 0, 'BRL': 0}, "Zero balance"),
({'USD': '20.00'}, "20.00 USD"),
({'EUR': '50.00', 'GBP': '80.00'}, "80.00 GBP, 50.00 EUR"),
({'JPY': '-55.00', 'BRL': '-85.00'}, "-85.00 BRL, -55.00 JPY"),
])
def test_str(balance_map_kwargs, expected):
amounts = testutil.balance_map(**balance_map_kwargs)
assert str(core.Balance(amounts.items())) == expected