Changeset - d8df34ebaf6f
[Not reviewed]
0 2 0
Brett Smith - 4 years ago 2020-05-28 13:03:23
brettcsmith@brettcsmith.org
reports: Balance.format() accepts None as a format.
2 files changed with 12 insertions and 1 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/reports/core.py
Show inline comments
...
 
@@ -52,137 +52,140 @@ class Balance(Mapping[str, data.Amount]):
 
    Each key is a Beancount currency string, and each value represents the
 
    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:
 
        return self.format()
 

	
 
    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)
 

	
 
    is_zero = eq_zero
 

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

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

	
 
    def format(self,
 
               fmt: str='#,#00.00 ¤¤',
 
               fmt: Optional[str]='#,#00.00 ¤¤',
 
               sep: str=', ',
 
               empty: str="Zero balance",
 
    ) -> str:
 
        """Formats the balance as a string with the given parameters
 

	
 
        If the balance is zero, returns ``empty``. Otherwise, returns a string
 
        with each amount in the balance formatted as ``fmt``, separated by
 
        ``sep``.
 

	
 
        If you set ``fmt`` to None, amounts will be formatted according to the
 
        user's locale. The default format is Beancount's input format.
 
        """
 
        amounts = [amount for amount in self.values() if amount.number]
 
        if not amounts:
 
            return empty
 
        amounts.sort(key=lambda amt: abs(amt.number), reverse=True)
 
        return sep.join(
 
            babel.numbers.format_currency(amt.number, amt.currency, fmt)
 
            for amt in amounts
 
        )
 

	
 

	
 
class MutableBalance(Balance):
 
    __slots__ = ()
 

	
 
    def add_amount(self, amount: data.Amount) -> None:
 
        try:
 
            self._currency_map[amount.currency] += amount.number
 
        except KeyError:
 
            self._currency_map[amount.currency] = amount.number
 

	
 

	
 
class RelatedPostings(Sequence[data.Posting]):
 
    """Collect and query related postings
 

	
 
    This class provides common functionality for collecting related postings
 
    and running queries on them: iterating over them, tallying their balance,
 
    etc.
 

	
 
    This class doesn't know anything about how the postings are related. That's
 
    entirely up to the caller.
 

	
 
    A common pattern is to use this class with collections.defaultdict
 
    to organize postings based on some key. See the group_by_meta classmethod
 
    for an example.
 
    """
 

	
 
    def __init__(self, source: Iterable[data.Posting]=()) -> None:
 
        self._postings: List[data.Posting] = list(source)
 

	
 
    @classmethod
 
    def group_by_meta(cls,
 
                      postings: Iterable[data.Posting],
 
                      key: MetaKey,
 
                      default: Optional[MetaValue]=None,
 
    ) -> Mapping[Optional[MetaValue], 'RelatedPostings']:
 
        """Relate postings by metadata value
 

	
 
        This method takes an iterable of postings and returns a mapping.
 
        The keys of the mapping are the values of post.meta.get(key, default).
 
        The values are RelatedPostings instances that contain all the postings
 
        that had that same metadata value.
 
        """
 
        retval: DefaultDict[Optional[MetaValue], 'RelatedPostings'] = collections.defaultdict(cls)
 
        for post in postings:
 
            retval[post.meta.get(key, default)].add(post)
 
        retval.default_factory = None
 
        return retval
 

	
 
    @overload
 
    def __getitem__(self, index: int) -> data.Posting: ...
 

	
 
    @overload
 
    def __getitem__(self, s: slice) -> Sequence[data.Posting]: ...
 

	
tests/test_reports_balance.py
Show inline comments
 
"""test_reports_balance - Unit tests for reports.core.Balance"""
 
# Copyright © 2020  Brett Smith
 
#
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU Affero General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU Affero General Public License for more details.
 
#
 
# You should have received a copy of the GNU Affero General Public License
 
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
 

	
 
import itertools
 

	
 
from decimal import Decimal
 

	
 
import pytest
 

	
 
from . import testutil
 

	
 
import babel.numbers
 

	
 
from conservancy_beancount.reports import core
 

	
 
DEFAULT_STRINGS = [
 
    ({}, "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': '-5500.00', 'BRL': '-8500.00'}, "-8,500.00 BRL, -5,500 JPY"),
 
]
 

	
 
def test_empty_balance():
 
    balance = core.Balance()
 
    assert not balance
 
    assert len(balance) == 0
 
    assert balance.is_zero()
 
    with pytest.raises(KeyError):
 
        balance['USD']
 

	
 
@pytest.mark.parametrize('currencies', [
 
    'USD',
 
    'EUR GBP',
 
    'JPY INR BRL',
 
])
 
def test_zero_balance(currencies):
 
    keys = currencies.split()
 
    balance = core.Balance(testutil.balance_map((key, 0) for key in keys))
 
    assert balance
 
    assert len(balance) == len(keys)
 
    assert balance.is_zero()
 
    assert all(balance[key].number == 0 for key in keys)
 
    assert all(balance[key].currency == key for key in keys)
 

	
 
@pytest.mark.parametrize('currencies', [
 
    'USD',
 
    'EUR GBP',
 
    'JPY INR BRL',
 
])
 
def test_nonzero_balance(currencies):
 
    amounts = testutil.balance_map(zip(currencies.split(), itertools.count(110, 100)))
 
    balance = core.Balance(amounts.items())
 
    assert balance
 
    assert len(balance) == len(amounts)
 
    assert not balance.is_zero()
 
    assert all(balance[key] == amt for key, amt in amounts.items())
 

	
 
def test_mixed_balance():
 
    amounts = testutil.balance_map(USD=0, EUR=120)
 
    balance = core.Balance(amounts.items())
 
    assert 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', [
 
    ({}, True),
 
    ({'USD': 0}, True),
 
    ({'USD': 0, 'EUR': 0}, True),
 
    ({'USD': -10, 'EUR': 0}, False),
 
    ({'EUR': -10}, False),
 
    ({'USD': -10, 'EUR': -20}, False),
 
    ({'USD': 10, 'EUR': -20}, False),
 
    ({'JPY': 10}, False),
 
    ({'JPY': 10, 'BRL': 0}, False),
 
    ({'JPY': 10, 'BRL': 20}, False),
...
 
@@ -130,72 +132,78 @@ def test_le_zero(balance_map_kwargs, expected):
 
    {'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', DEFAULT_STRINGS)
 
def test_str(balance_map_kwargs, expected):
 
    amounts = testutil.balance_map(**balance_map_kwargs)
 
    assert str(core.Balance(amounts.items())) == expected
 

	
 
@pytest.mark.parametrize('bal_kwargs,expected', DEFAULT_STRINGS)
 
def test_format_defaults(bal_kwargs, expected):
 
    amounts = testutil.balance_map(**bal_kwargs)
 
    assert core.Balance(amounts).format() == expected
 

	
 
@pytest.mark.parametrize('fmt,expected', [
 
    ('¤##0.0', '¥5000, -€1500.00'),
 
    ('#,#00.0¤¤', '5,000JPY, -1,500.00EUR'),
 
    ('¤+##0.0;¤-##0.0', '¥+5000, €-1500.00'),
 
    ('#,#00.0 ¤¤;(#,#00.0 ¤¤)', '5,000 JPY, (1,500.00 EUR)'),
 
])
 
def test_format_fmt(fmt, expected):
 
    amounts = testutil.balance_map(JPY=5000, EUR=-1500)
 
    balance = core.Balance(amounts)
 
    assert balance.format(fmt) == expected
 

	
 
@pytest.mark.parametrize('sep', [
 
    '; ',
 
    '—',
 
    '\0',
 
])
 
def test_format_sep(sep):
 
    bal_kwargs, expected = DEFAULT_STRINGS[-1]
 
    expected = expected.replace(', ', sep)
 
    amounts = testutil.balance_map(**bal_kwargs)
 
    balance = core.Balance(amounts)
 
    assert balance.format(sep=sep) == expected
 

	
 
def test_format_none():
 
    amounts = testutil.balance_map(BRL=65000)
 
    balance = core.Balance(amounts)
 
    expected = babel.numbers.format_currency(65000, 'BRL')
 
    assert balance.format(None) == expected
 

	
 
@pytest.mark.parametrize('empty', [
 
    "N/A",
 
    "Zero",
 
    "ø",
 
])
 
def test_format_empty(empty):
 
    balance = core.Balance()
 
    assert balance.format(empty=empty) == empty
0 comments (0 inline, 0 general)