Changeset - 4cba2b2681ac
[Not reviewed]
0 2 0
Brett Smith - 4 years ago 2020-06-04 02:20:37
brettcsmith@brettcsmith.org
reports: Balance has built-in tolerance for zero comparisons.
2 files changed with 26 insertions and 8 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/reports/core.py
Show inline comments
...
 
@@ -82,6 +82,13 @@ class Balance(Mapping[str, data.Amount]):
 
    """
 
    __slots__ = ('_currency_map',)
 
    __slots__ = ('_currency_map', 'tolerance')
 
    TOLERANCE = Decimal('0.01')
 

	
 
    def __init__(self, source: Iterable[data.Amount]=()) -> None:
 
    def __init__(self,
 
                 source: Iterable[data.Amount]=(),
 
                 tolerance: Optional[Decimal]=None,
 
    ) -> None:
 
        if tolerance is None:
 
            tolerance = self.TOLERANCE
 
        self._currency_map = {amount.currency: amount for amount in source}
 
        self.tolerance = tolerance
 

	
...
 
@@ -149,5 +156,10 @@ class Balance(Mapping[str, data.Amount]):
 

	
 
    @staticmethod
 
    def within_tolerance(dec: DecimalCompat, tolerance: DecimalCompat) -> bool:
 
        dec = cast(Decimal, dec)
 
        return abs(dec) < tolerance
 

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

	
...
 
@@ -156,8 +168,8 @@ class Balance(Mapping[str, data.Amount]):
 
    def ge_zero(self) -> bool:
 
        """Returns true if all amounts in the balance >= 0."""
 
        return self._all_amounts(operator.ge, 0)
 
        """Returns true if all amounts in the balance >= 0, within tolerance."""
 
        return self._all_amounts(operator.ge, -self.tolerance)
 

	
 
    def le_zero(self) -> bool:
 
        """Returns true if all amounts in the balance <= 0."""
 
        return self._all_amounts(operator.le, 0)
 
        """Returns true if all amounts in the balance <= 0, within tolerance."""
 
        return self._all_amounts(operator.le, self.tolerance)
 

	
tests/test_reports_balance.py
Show inline comments
...
 
@@ -94,2 +94,4 @@ def test_mixed_balance():
 
    ({'JPY': 10, 'BRL': 20}, False),
 
    ({'USD': '0.00015'}, True),
 
    ({'EUR': '-0.00052'}, True),
 
])
...
 
@@ -110,2 +112,4 @@ def test_eq_zero(mapping, expected):
 
    ({'JPY': 10, 'BRL': 20}, True),
 
    ({'USD': '0.00015'}, True),
 
    ({'EUR': '-0.00052'}, True),
 
])
...
 
@@ -125,2 +129,4 @@ def test_ge_zero(mapping, expected):
 
    ({'JPY': 10, 'BRL': 20}, False),
 
    ({'USD': '0.00015'}, True),
 
    ({'EUR': '-0.00052'}, True),
 
])
0 comments (0 inline, 0 general)