Changeset - c6dc2d83aca7
[Not reviewed]
1 7 0
Brett Smith - 4 years ago 2020-04-09 16:00:38
brettcsmith@brettcsmith.org
data.Amount: Introduce class and simplify code to use it.

See docstring for full rationale. This greatly reduces the need for other
plugin code to handle the case of `post.units.number is None`, eliminating
the need for entire methods and letting it do plain numeric comparisons.
8 files changed with 46 insertions and 231 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/data.py
Show inline comments
 
"""Enhanced Beancount data structures for Conservancy
 

	
 
The classes in this module are interface-compatible with Beancount's core data
 
structures, and provide additional business logic that we want to use
 
throughout Conservancy tools.
 
"""
 
# 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 collections
 
import decimal
 
import operator
 

	
 
from beancount.core import account as bc_account
 
from beancount.core import amount as bc_amount
 

	
 
from typing import (
 
    cast,
 
    Callable,
 
    Iterable,
 
    Iterator,
 
    MutableMapping,
 
    Optional,
 
    Sequence,
 
    Union,
 
)
 

	
 
from .beancount_types import (
 
    MetaKey,
 
    MetaValue,
 
    Posting as BasePosting,
 
    Transaction,
 
)
 

	
 
DecimalCompat = Union[decimal.Decimal, int]
 

	
 
LINK_METADATA = frozenset([
 
    'approval',
 
    'check',
 
    'contract',
 
    'invoice',
 
    'purchase-order',
 
    'receipt',
 
    'statement',
 
])
 

	
 
class Account(str):
 
    """Account name string
 

	
 
    This is a string that names an account, like Assets:Bank:Checking
 
    or Income:Donations. This class provides additional methods for common
 
    account name parsing and queries.
 
    """
 
    __slots__ = ()
 

	
 
    SEP = bc_account.sep
 

	
 
    def is_cash_equivalent(self) -> bool:
 
        return (
 
            self.is_under('Assets:') is not None
 
            and self.is_under('Assets:Prepaid', 'Assets:Receivable') is None
 
        )
 

	
 
    def is_checking(self) -> bool:
 
        return self.is_cash_equivalent() and ':Check' in self
 

	
 
    def is_credit_card(self) -> bool:
 
        return self.is_under('Liabilities:CreditCard') is not None
 

	
 
    def is_opening_equity(self) -> bool:
 
        return self.is_under('Equity:Funds', 'Equity:OpeningBalance') is not None
 

	
 
    def is_under(self, *acct_seq: str) -> Optional[str]:
 
        """Return a match if this account is "under" a part of the hierarchy
 

	
 
        Pass in any number of account name strings as arguments. If this
 
        account is under one of those strings in the account hierarchy, the
 
        first matching string will be returned. Otherwise, None is returned.
 

	
 
        You can use the return value of this method as a boolean if you don't
 
        care which account string is matched.
 

	
 
        An account is considered to be under itself:
 

	
 
          Account('Expenses:Tax').is_under('Expenses:Tax') # returns 'Expenses:Tax'
 

	
 
        To do a "strictly under" search, end your search strings with colons:
 

	
 
          Account('Expenses:Tax').is_under('Expenses:Tax:') # returns None
 
          Account('Expenses:Tax').is_under('Expenses:') # returns 'Expenses:'
 

	
 
        This method does check that all the account boundaries match:
 

	
 
          Account('Expenses:Tax').is_under('Exp') # returns None
 
        """
 
        for prefix in acct_seq:
 
            if self.startswith(prefix) and (
 
                prefix.endswith(self.SEP)
 
                or self == prefix
 
                or self[len(prefix)] == self.SEP
 
            ):
 
                return prefix
 
        return None
 

	
 

	
 
class Amount(bc_amount.Amount):
 
    """Beancount amount after processing
 

	
 
    Beancount's native Amount class declares number to be Optional[Decimal],
 
    because the number is None when Beancount first parses a posting that does
 
    not have an amount, because the user wants it to be automatically balanced.
 

	
 
    As part of the loading process, Beancount replaces those None numbers
 
    with the calculated amount, so it will always be a Decimal. This class
 
    overrides the type declaration accordingly, so the type checker knows
 
    that our code doesn't have to consider the possibility that number is
 
    None.
 
    """
 
    number: decimal.Decimal
 

	
 

	
 
class Metadata(MutableMapping[MetaKey, MetaValue]):
 
    """Transaction or posting metadata
 

	
 
    This class wraps a Beancount metadata dictionary with additional methods
 
    for common parsing and query tasks.
 
    """
 
    __slots__ = ('meta',)
 

	
 
    def __init__(self, source: MutableMapping[MetaKey, MetaValue]) -> None:
 
        self.meta = source
 

	
 
    def __iter__(self) -> Iterator[MetaKey]:
 
        return iter(self.meta)
 

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

	
 
    def __getitem__(self, key: MetaKey) -> MetaValue:
 
        return self.meta[key]
 

	
 
    def __setitem__(self, key: MetaKey, value: MetaValue) -> None:
 
        self.meta[key] = value
 

	
 
    def __delitem__(self, key: MetaKey) -> None:
 
        del self.meta[key]
 

	
 
    def get_links(self, key: MetaKey) -> Sequence[str]:
 
        try:
 
            value = self.meta[key]
 
        except KeyError:
 
            return ()
 
        if isinstance(value, str):
 
            return value.split()
 
        else:
 
            raise TypeError("{} metadata is a {}, not str".format(
 
                key, type(value).__name__,
 
            ))
 

	
 

	
 
class PostingMeta(Metadata):
 
    """Combined access to posting metadata with its parent transaction metadata
 

	
 
    This lets you access posting metadata through a single dict-like object.
 
    If you try to look up metadata that doesn't exist on the posting, it will
 
    look for the value in the parent transaction metadata instead.
 

	
 
    You can set and delete metadata as well. Changes only affect the metadata
 
    of the posting, never the transaction. Changes are propagated to the
 
    underlying Beancount data structures.
 

	
 
    Functionally, you can think of this as identical to:
 

	
 
      collections.ChainMap(post.meta, txn.meta)
 

	
 
    Under the hood, this class does a little extra work to avoid creating
 
    posting metadata if it doesn't have to.
 
    """
 
    __slots__ = ('txn', 'index', 'post')
 

	
 
    def __init__(self,
 
                 txn: Transaction,
 
                 index: int,
 
                 post: Optional[BasePosting]=None,
 
    ) -> None:
 
        if post is None:
 
            post = txn.postings[index]
 
        self.txn = txn
 
        self.index = index
 
        self.post = post
 
        if post.meta is None:
 
            self.meta = self.txn.meta
 
        else:
 
            self.meta = collections.ChainMap(post.meta, txn.meta)
 

	
 
    def __getitem__(self, key: MetaKey) -> MetaValue:
 
        try:
 
            return super().__getitem__(key)
 
        except KeyError:
 
            if key == 'entity' and self.txn.payee is not None:
 
                return self.txn.payee
 
            else:
 
                raise
 

	
 
    def __setitem__(self, key: MetaKey, value: MetaValue) -> None:
 
        if self.post.meta is None:
 
            self.post = self.post._replace(meta={key: value})
 
            self.txn.postings[self.index] = self.post
 
            # mypy complains that self.post.meta could be None, but we know
 
            # from two lines up that it's not.
 
            self.meta = collections.ChainMap(self.post.meta, self.txn.meta)  # type:ignore[arg-type]
 
        else:
 
            super().__setitem__(key, value)
 

	
 
    def __delitem__(self, key: MetaKey) -> None:
 
        if self.post.meta is None:
 
            raise KeyError(key)
 
        else:
 
            super().__delitem__(key)
 

	
 

	
 
class Posting(BasePosting):
 
    """Enhanced Posting objects
 

	
 
    This class is a subclass of Beancount's native Posting class where
 
    specific fields are replaced with enhanced versions:
 

	
 
    * The `account` field is an Account object
 
    * The `units` field is our Amount object (which simply declares that the
 
      number is always a Decimal—see that docstring for details)
 
    * The `meta` field is a PostingMeta object
 
    """
 
    __slots__ = ()
 

	
 
    account: Account
 
    units: Amount
 
    # mypy correctly complains that our MutableMapping is not compatible
 
    # with Beancount's meta type declaration of Optional[Dict]. IMO
 
    # Beancount's type declaration is a smidge too specific: I think its type
 
    # declaration should also use MutableMapping, because it would be very
 
    # unusual for code to specifically require a Dict over that.
 
    # If it did, this declaration would pass without issue.
 
    meta: Metadata  # type:ignore[assignment]
 

	
 
    def _compare_amount(self,
 
                        op: Callable[[decimal.Decimal], decimal.Decimal],
 
                        threshold: DecimalCompat,
 
                        default: Optional[bool],
 
    ) -> Optional[bool]:
 
        if self.units.number is None:
 
            return default
 
        else:
 
            return op(self.units.number) > threshold
 

	
 
    def is_credit(self,
 
                  threshold: DecimalCompat=0,
 
                  default: Optional[bool]=None,
 
    ) -> Optional[bool]:
 
        return self._compare_amount(operator.pos, threshold, default)
 

	
 
    def is_debit(self,
 
                  threshold: DecimalCompat=0,
 
                  default: Optional[bool]=None,
 
    ) -> Optional[bool]:
 
        return self._compare_amount(operator.neg, threshold, default)
 

	
 
    def is_payment(self,
 
                  threshold: DecimalCompat=0,
 
                  default: Optional[bool]=None,
 
    ) -> Optional[bool]:
 
        return self.account.is_cash_equivalent() and self.is_debit(threshold, default)
 

	
 

	
 
def balance_of(txn: Transaction,
 
               *preds: Callable[[Account], Optional[bool]],
 
               default: Optional[DecimalCompat]=None,
 
) -> Optional[decimal.Decimal]:
 
) -> decimal.Decimal:
 
    """Return the balance of specified postings in a transaction.
 

	
 
    Given a transaction and a series of account predicates, balance_of
 
    returns the balance of the amounts of all postings with accounts that
 
    match any of the predicates.
 

	
 
    If any of the postings have no amount, returns default.
 
    """
 
    retval = decimal.Decimal(0)
 
    for post in txn.postings:
 
        acct = Account(post.account)
 
        if any(p(acct) for p in preds):
 
            if post.units.number is None:
 
                return None if default is None else decimal.Decimal(default)
 
            else:
 
                retval += post.units.number
 
    return retval
 
    return sum(
 
        (post.units.number for post in iter_postings(txn)
 
         if any(pred(post.account) for pred in preds)),
 
        decimal.Decimal(0),
 
    )
 

	
 
def iter_postings(txn: Transaction) -> Iterator[Posting]:
 
    """Yield an enhanced Posting object for every posting in the transaction"""
 
    for index, source in enumerate(txn.postings):
 
        yield Posting(
 
            Account(source.account),
 
            *source[1:5],
 
            # see rationale above about Posting.meta
 
            PostingMeta(txn, index, source), # type:ignore[arg-type]
 
        )
conservancy_beancount/plugin/meta_approval.py
Show inline comments
 
"""meta_approval - Validate approval metadata"""
 
# 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 decimal
 

	
 
from . import core
 
from .. import config as configmod
 
from .. import data
 
from .. import errors as errormod
 
from ..beancount_types import (
 
    Transaction,
 
)
 

	
 
class MetaApproval(core._RequireLinksPostingMetadataHook):
 
    CHECKED_METADATA = ['approval']
 

	
 
    def __init__(self, config: configmod.Config) -> None:
 
        self.payment_threshold = -config.payment_threshold()
 

	
 
    def _run_on_txn(self, txn: Transaction) -> bool:
 
        if not super()._run_on_txn(txn):
 
            return False
 
        # approval is required when funds leave a cash equivalent asset,
 
        # UNLESS that transaction is a transfer to another asset,
 
        # or paying off a credit card.
 
        balance = data.balance_of(
 
            txn,
 
            data.Account.is_cash_equivalent,
 
            data.Account.is_credit_card,
 
        return (
 
            super()._run_on_txn(txn)
 
            # approval is required when funds leave a cash equivalent asset,
 
            # UNLESS that transaction is a transfer to another asset,
 
            # or paying off a credit card.
 
            and self.payment_threshold > data.balance_of(
 
                txn,
 
                data.Account.is_cash_equivalent,
 
                data.Account.is_credit_card,
 
            )
 
        )
 
        return balance is None or balance < self.payment_threshold
 

	
 
    def _run_on_post(self, txn: Transaction, post: data.Posting) -> bool:
 
        return post.account.is_cash_equivalent() and not post.is_credit(0)
 
        return post.account.is_cash_equivalent() and post.units.number < 0
conservancy_beancount/plugin/meta_payable_documentation.py
Show inline comments
 
"""meta_payable_documentation - Validate payables have supporting docs"""
 
# 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/>.
 

	
 
from . import core
 
from .. import config as configmod
 
from .. import data
 
from .. import errors as errormod
 
from ..beancount_types import (
 
    Transaction,
 
)
 

	
 
class MetaPayableDocumentation(core._RequireLinksPostingMetadataHook):
 
    CHECKED_METADATA = ['approval', 'contract']
 

	
 
    def _run_on_post(self, txn: Transaction, post: data.Posting) -> bool:
 
        if post.account.is_under('Liabilities:Payable:Accounts'):
 
            return not post.is_credit()
 
            return post.units.number < 0
 
        else:
 
            return False
conservancy_beancount/plugin/meta_receipt.py
Show inline comments
 
"""meta_receipt - Validate receipt metadata"""
 
# 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/>.
 

	
 
from decimal import Decimal
 

	
 
from . import core
 
from .. import config as configmod
 
from .. import data
 
from .. import errors as errormod
 
from ..beancount_types import (
 
    MetaKey,
 
    Transaction,
 
)
 

	
 
from typing import (
 
    Callable,
 
)
 

	
 
class MetaReceipt(core._RequireLinksPostingMetadataHook):
 
    CHECKED_METADATA = ['receipt']
 

	
 
    def __init__(self, config: configmod.Config) -> None:
 
        self.payment_threshold = abs(config.payment_threshold())
 

	
 
    def _run_on_post(self, txn: Transaction, post: data.Posting) -> bool:
 
        return (
 
            (post.account.is_cash_equivalent() or post.account.is_credit_card())
 
            and not post.account.is_under('Assets:PayPal')
 
            and post.units.number is not None
 
            and abs(post.units.number) >= self.payment_threshold
 
        )
 

	
 
    def _run_checking_debit(self, txn: Transaction, post: data.Posting) -> errormod.Iter:
 
        receipt_errors = list(self._check_metadata(txn, post, self.CHECKED_METADATA))
 
        if not receipt_errors:
 
            return
 
        for error in receipt_errors:
 
            if error.value is not None:
 
                yield error
 
        try:
 
            check_id = post.meta['check-id']
 
        except KeyError:
 
            check_id_ok = False
 
        else:
 
            check_id_ok = (isinstance(check_id, Decimal)
 
                           and check_id >= 1
 
                           and not check_id % 1)
 
            if not check_id_ok:
 
                yield errormod.InvalidMetadataError(txn, 'check-id', check_id, post, Decimal)
 
        if not check_id_ok:
 
            yield errormod.InvalidMetadataError(txn, 'receipt/check-id', post=post)
 

	
 
    def post_run(self, txn: Transaction, post: data.Posting) -> errormod.Iter:
 
        keys = list(self.CHECKED_METADATA)
 
        is_checking = post.account.is_checking()
 
        if is_checking and post.is_debit():
 
        if is_checking and post.units.number < 0:
 
            return self._run_checking_debit(txn, post)
 
        elif is_checking:
 
            keys.append('check')
 
        elif post.account.is_credit_card() and not post.is_credit():
 
        elif post.account.is_credit_card() and post.units.number <= 0:
 
            keys.append('invoice')
 
        return self._check_metadata(txn, post, keys)
conservancy_beancount/plugin/meta_receivable_documentation.py
Show inline comments
 
"""meta_receivable_documentation - Validate receivables have supporting docs"""
 
# 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 re
 

	
 
from . import core
 
from .. import config as configmod
 
from .. import data
 
from .. import errors as errormod
 
from ..beancount_types import (
 
    MetaKey,
 
    Transaction,
 
)
 

	
 
from typing import (
 
    Dict,
 
    Optional,
 
)
 

	
 
class MetaReceivableDocumentation(core._RequireLinksPostingMetadataHook):
 
    HOOK_GROUPS = frozenset(['network', 'rt'])
 
    CHECKED_METADATA = ['approval', 'contract', 'purchase-order']
 
    # Conservancy invoice filenames have followed two patterns.
 
    # The pre-RT pattern: `YYYY-MM-DD_Entity_invoice-YYYYMMDDNN??_as-sent.pdf`
 
    # The RT pattern: `ProjectInvoice-30NNNN??.pdf`
 
    # This regexp matches both, with a little slack to try to reduce the false
 
    # negative rate due to minor renames, etc.
 
    ISSUED_INVOICE_RE = re.compile(
 
        r'[Ii]nvoice[-_ ]*(?:2[0-9]{9,}|30[0-9]+)[A-Za-z]*[-_ .]',
 
    )
 

	
 
    def __init__(self, config: configmod.Config) -> None:
 
        rt_wrapper = config.rt_wrapper()
 
        # In principle, we could still check for non-RT invoices and enforce
 
        # checks on them without an RT wrapper. In practice, that would
 
        # provide so little utility today it's not worth bothering with.
 
        if rt_wrapper is None:
 
            raise errormod.ConfigurationError("can't log in to RT")
 
        self.rt = rt_wrapper
 

	
 
    def _run_on_post(self, txn: Transaction, post: data.Posting) -> bool:
 
        if not post.account.is_under('Assets:Receivable'):
 
            return False
 
        elif post.is_debit():
 
        elif post.units.number < 0:
 
            return False
 

	
 
        # Get the first invoice, or return False if it doesn't exist.
 
        try:
 
            invoice_link = post.meta.get_links('invoice')[0]
 
        except (IndexError, TypeError):
 
            return False
 

	
 
        # Get the filename, following an RT link if necessary.
 
        rt_args = self.rt.parse(invoice_link)
 
        if rt_args is not None:
 
            ticket_id, attachment_id = rt_args
 
            invoice_link = self.rt.url(ticket_id, attachment_id) or invoice_link
 
        return self.ISSUED_INVOICE_RE.search(invoice_link) is not None
conservancy_beancount/plugin/meta_tax_implication.py
Show inline comments
 
"""meta_tax_implication - Validate tax-implication metadata"""
 
# 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 decimal
 

	
 
from . import core
 
from .. import config as configmod
 
from .. import data
 
from ..beancount_types import (
 
    Transaction,
 
)
 

	
 
class MetaTaxImplication(core._NormalizePostingMetadataHook):
 
    VALUES_ENUM = core.MetadataEnum('tax-implication', [
 
        '1099',
 
        'Accountant-Advises-No-1099',
 
        'Bank-Transfer',
 
        'Foreign-Corporation',
 
        'Foreign-Individual-Contractor',
 
        'Fraud',
 
        'HSA-Contribution',
 
        'Loan',
 
        'Payroll',
 
        'Refund',
 
        'Reimbursement',
 
        'Retirement-Pretax',
 
        'Tax-Payment',
 
        'USA-501c3',
 
        'USA-Corporation',
 
        'USA-LLC-No-1099',
 
        'W2',
 
    ])
 

	
 
    def __init__(self, config: configmod.Config) -> None:
 
        self.payment_threshold = config.payment_threshold()
 
        self.payment_threshold = -config.payment_threshold()
 

	
 
    def _run_on_post(self, txn: Transaction, post: data.Posting) -> bool:
 
        return post.is_payment(self.payment_threshold) is not False
 
        return (
 
            post.account.is_cash_equivalent()
 
            and post.units.number < self.payment_threshold
 
        )
tests/test_data_balance_of.py
Show inline comments
 
"""Test data.balance_of function"""
 
# 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/>.
 

	
 
from decimal import Decimal
 
from operator import methodcaller
 

	
 
import pytest
 

	
 
from . import testutil
 

	
 
from conservancy_beancount import data
 

	
 
is_cash_eq = data.Account.is_cash_equivalent
 

	
 
@pytest.fixture
 
def payable_payment_txn():
 
    return testutil.Transaction(postings=[
 
        ('Liabilities:Payable:Accounts', 50),
 
        ('Assets:Checking', -50),
 
        ('Expenses:BankingFees', 5),
 
        ('Assets:Checking', -5),
 
    ])
 

	
 
@pytest.fixture
 
def none_posting_txn():
 
    return testutil.Transaction(postings=[
 
        ('Income:Donations', -30),
 
        ('Expenses:BankingFees', 3),
 
        ('Assets:Checking', None),
 
    ])
 

	
 
@pytest.fixture
 
def multipost_one_none_txn():
 
    return testutil.Transaction(postings=[
 
        ('Liabilities:Payable:Accounts', 50),
 
        ('Assets:Checking', -50),
 
        ('Expenses:BankingFees', 5),
 
        ('Assets:Checking', None),
 
    ])
 

	
 
def balance_under(txn, *accts):
 
    pred = methodcaller('is_under', *accts)
 
    return data.balance_of(txn, pred)
 

	
 
def test_balance_of_simple_txn():
 
    txn = testutil.Transaction(postings=[
 
        ('Assets:Cash', 50),
 
        ('Income:Donations', -50),
 
    ])
 
    assert balance_under(txn, 'Assets') == 50
 
    assert balance_under(txn, 'Income') == -50
 

	
 
def test_zero_balance_of(payable_payment_txn):
 
    assert balance_under(payable_payment_txn, 'Equity') == 0
 
    assert balance_under(payable_payment_txn, 'Assets:Cash') == 0
 
    assert balance_under(payable_payment_txn, 'Liabilities:CreditCard') == 0
 

	
 
def test_nonzero_balance_of(payable_payment_txn):
 
    assert balance_under(payable_payment_txn, 'Assets', 'Expenses') == -50
 
    assert balance_under(payable_payment_txn, 'Assets', 'Liabilities') == -5
 

	
 
def test_multiarg_balance_of():
 
    txn = testutil.Transaction(postings=[
 
        ('Liabilities:CreditCard', 650),
 
        ('Expenses:BankingFees', 5),
 
        ('Assets:Checking', -655),
 
    ])
 
    assert data.balance_of(txn, is_cash_eq, data.Account.is_credit_card) == -5
 

	
 
def test_balance_of_multipost_txn(payable_payment_txn):
 
    assert data.balance_of(payable_payment_txn, is_cash_eq) == -55
 

	
 
def test_balance_of_none_posting(none_posting_txn):
 
    assert data.balance_of(none_posting_txn, is_cash_eq) is None
 

	
 
def test_balance_of_none_posting_with_default(none_posting_txn):
 
    expected = Decimal('Infinity')
 
    assert expected == data.balance_of(
 
        none_posting_txn, is_cash_eq, default=expected,
 
    )
 

	
 
def test_balance_of_other_side_of_none_posting(none_posting_txn):
 
    assert balance_under(none_posting_txn, 'Income') == -30
 
    assert balance_under(none_posting_txn, 'Expenses') == 3
 

	
 
def test_balance_of_multi_postings_one_none(multipost_one_none_txn):
 
    assert data.balance_of(multipost_one_none_txn, is_cash_eq) is None
 

	
 
def test_balance_of_multi_postings_one_none(multipost_one_none_txn):
 
    expected = Decimal('Infinity')
 
    assert expected == data.balance_of(
 
        multipost_one_none_txn, is_cash_eq, default=expected,
 
    )
tests/test_data_posting.py
Show inline comments
 
deleted file
0 comments (0 inline, 0 general)