Changeset - 3780c31c5901
[Not reviewed]
0 2 0
Brett Smith - 4 years ago 2020-05-28 13:01:00
brettcsmith@brettcsmith.org
reports: Add Balance.__eq__() method.

It turns out the provided implementation gets us most of the way there,
we just needed to add handling for the special case of zero balances.
Now it's confirmed with tests.
2 files changed with 25 insertions and 0 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/reports/core.py
Show inline comments
...
 
@@ -50,48 +50,56 @@ class Balance(Mapping[str, data.Amount]):
 
    balance in that currency.
 
    """
 
    __slots__ = ('_currency_map',)
 

	
 
    def __init__(self,
 
                 source: Union[Iterable[Tuple[str, data.Amount]],
 
                               Mapping[str, data.Amount]]=(),
 
    ) -> None:
 
        if isinstance(source, Mapping):
 
            source = source.items()
 
        self._currency_map = {
 
            currency: amount.number for currency, amount in source
 
        }
 

	
 
    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 __eq__(self, other: Any) -> bool:
 
        if (self.is_zero()
 
            and isinstance(other, Balance)
 
            and other.is_zero()):
 
            return True
 
        else:
 
            return super().__eq__(other)
 

	
 
    def __neg__(self) -> 'Balance':
 
        return type(self)(
 
            (key, -amt) for key, amt in self.items()
 
        )
 

	
 
    def __getitem__(self, key: str) -> data.Amount:
 
        return data.Amount(self._currency_map[key], key)
 

	
 
    def __iter__(self) -> Iterator[str]:
 
        return iter(self._currency_map)
 

	
 
    def __len__(self) -> int:
 
        return len(self._currency_map)
 

	
 
    def _all_amounts(self,
 
                     op_func: Callable[[DecimalCompat, DecimalCompat], bool],
 
                     operand: DecimalCompat,
 
    ) -> bool:
 
        return all(op_func(number, operand) for number in self._currency_map.values())
 

	
 
    def eq_zero(self) -> bool:
 
        """Returns true if all amounts in the balance == 0."""
 
        return self._all_amounts(operator.eq, 0)
 

	
tests/test_reports_balance.py
Show inline comments
...
 
@@ -112,34 +112,51 @@ def test_ge_zero(balance_map_kwargs, expected):
 
    ({'JPY': 10, 'BRL': 0}, False),
 
    ({'JPY': 10, 'BRL': 20}, False),
 
])
 
def test_le_zero(balance_map_kwargs, expected):
 
    amounts = testutil.balance_map(**balance_map_kwargs)
 
    balance = core.Balance(amounts.items())
 
    assert balance.le_zero() == expected
 

	
 
@pytest.mark.parametrize('balance_map_kwargs', [
 
    {},
 
    {'USD': 0},
 
    {'EUR': 10},
 
    {'JPY': 20, 'BRL': 30},
 
    {'EUR': -15},
 
    {'JPY': -25, 'BRL': -35},
 
    {'JPY': 40, 'USD': 0, 'EUR': -50},
 
])
 
def test_neg(balance_map_kwargs):
 
    amounts = testutil.balance_map(**balance_map_kwargs)
 
    actual = -core.Balance(amounts.items())
 
    assert set(actual) == set(balance_map_kwargs)
 
    for key in balance_map_kwargs:
 
        assert actual[key] == -amounts[key]
 

	
 
@pytest.mark.parametrize('kwargs1,kwargs2,expected', [
 
    ({}, {}, True),
 
    ({}, {'USD': 0}, True),
 
    ({}, {'EUR': 1}, False),
 
    ({'USD': 1}, {'EUR': 1}, False),
 
    ({'USD': 1}, {'USD': '1.0'}, True),
 
    ({'USD': 1}, {'USD': '1.0', 'EUR': '2.0'}, False),
 
    ({'USD': 1, 'BRL': '2.0'}, {'USD': '1.0', 'EUR': '2.0'}, False),
 
    ({'USD': 1, 'EUR': 2, 'BRL': '3.0'}, {'USD': '1.0', 'EUR': '2.0'}, False),
 
    ({'USD': 1, 'EUR': 2}, {'USD': '1.0', 'EUR': '2.0'}, True),
 
])
 
def test_eq(kwargs1, kwargs2, expected):
 
    bal1 = core.Balance(testutil.balance_map(**kwargs1))
 
    bal2 = core.Balance(testutil.balance_map(**kwargs2))
 
    actual = bal1 == bal2
 
    assert actual == expected
 

	
 
@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
0 comments (0 inline, 0 general)