Changeset - 4a28596db267
[Not reviewed]
0 3 0
Brett Smith - 4 years ago 2020-06-15 22:08:18
brettcsmith@brettcsmith.org
data: bank-statement and tax-statement are link metadata.

Not including them earlier was an oversight.
3 files changed with 6 insertions and 0 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 datetime
 
import decimal
 
import functools
 
import re
 

	
 
from beancount.core import account as bc_account
 
from beancount.core import amount as bc_amount
 
from beancount.core import convert as bc_convert
 
from beancount.core import position as bc_position
 

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

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

	
 
DecimalCompat = Union[decimal.Decimal, int]
 

	
 
LINK_METADATA = frozenset([
 
    'approval',
 
    'bank-statement',
 
    'check',
 
    'contract',
 
    'invoice',
 
    'purchase-order',
 
    'receipt',
 
    'rt-id',
 
    'statement',
 
    'tax-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
 

	
 
    def _find_part_slice(self, index: int) -> slice:
 
        if index < 0:
 
            raise ValueError(f"bad part index {index!r}")
 
        start = 0
 
        for _ in range(index):
 
            try:
 
                start = self.index(self.SEP, start) + 1
 
            except ValueError:
 
                raise IndexError("part index {index!r} out of range") from None
 
        try:
 
            stop = self.index(self.SEP, start + 1)
 
        except ValueError:
 
            stop = len(self)
 
        return slice(start, stop)
 

	
 
    def count_parts(self) -> int:
 
        return self.count(self.SEP) + 1
 

	
 
    @overload
 
    def slice_parts(self, start: None=None, stop: None=None) -> Sequence[str]: ...
 

	
 
    @overload
 
    def slice_parts(self, start: slice, stop: None=None) -> Sequence[str]: ...
 

	
 
    @overload
 
    def slice_parts(self, start: int, stop: int) -> Sequence[str]: ...
 

	
 
    @overload
 
    def slice_parts(self, start: int, stop: None=None) -> str: ...
 

	
 
    def slice_parts(self,
 
                    start: Optional[Union[int, slice]]=None,
 
                    stop: Optional[int]=None,
 
    ) -> Sequence[str]:
 
        """Slice the account parts like they were a list
 

	
 
        Given a single index, return that part of the account name as a string.
 
        Otherwise, return a list of part names sliced according to the arguments.
 
        """
 
        if start is None:
 
            part_slice = slice(None)
 
        elif isinstance(start, slice):
 
            part_slice = start
 
        elif stop is None:
 
            return self[self._find_part_slice(start)]
 
        else:
 
            part_slice = slice(start, stop)
 
        return self.split(self.SEP)[part_slice]
 

	
 
    def root_part(self, count: int=1) -> str:
 
        """Return the first part(s) of the account name as a string"""
 
        try:
 
            stop = self._find_part_slice(count - 1).stop
 
        except IndexError:
 
            return self
 
        else:
 
            return self[:stop]
 

	
 

	
 
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
 

	
 
    # beancount.core._Amount is the plain namedtuple.
 
    # beancore.core.Amount adds instance methods to it.
 
    # b.c.Amount.__New__ calls `b.c._Amount.__new__`, which confuses type
 
    # checking. See <https://github.com/python/mypy/issues/1279>.
 
    # It works fine if you use super(), which is better practice anyway.
 
    # So we override __new__ just to call _Amount.__new__ this way.
 
    def __new__(cls, number: decimal.Decimal, currency: str) -> 'Amount':
 
        return super(bc_amount.Amount, Amount).__new__(cls, number, currency)
 

	
 

	
 
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',)
 
    _HUMAN_NAMES: MutableMapping[MetaKey, str] = {
 
        # Initialize this dict with special cases.
 
        # We use it as a cache for other metadata names as they're queried.
 
        'check-id': 'Check Number',
 
        'paypal-id': 'PayPal ID',
 
        'rt-id': 'Ticket',
 
    }
 

	
 
    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__,
 
            ))
 

	
 
    def report_links(self, key: MetaKey) -> Sequence[str]:
 
        """Return a sequence of link strings under the named metadata key
 

	
 
        get_links raises a TypeError if the metadata is not a string.
 
        This method simply returns the empty sequence.
 
        Validation code (like in the plugin) usually uses get_links()
 
        while reporting code uses report_links().
 
        """
 
        try:
 
            return self.get_links(key)
 
        except TypeError:
 
            return ()
 

	
 
    @overload
 
    def first_link(self, key: MetaKey, default: None=None) -> Optional[str]: ...
 

	
 
    @overload
 
    def first_link(self, key: MetaKey, default: str) -> str: ...
 

	
 
    def first_link(self, key: MetaKey, default: Optional[str]=None) -> Optional[str]:
 
        try:
 
            return self.get_links(key)[0]
 
        except (IndexError, TypeError):
 
            return default
 

	
 
    @classmethod
 
    def human_name(cls, key: MetaKey) -> str:
 
        """Return the "human" version of a metadata name
 

	
 
        This is usually the metadata key with punctuation replaced with spaces,
 
        and then titlecased, with a few special cases. The return value is
 
        suitable for using in reports.
 
        """
 
        try:
 
            retval = cls._HUMAN_NAMES[key]
 
        except KeyError:
 
            retval = key.replace('-', ' ').title()
 
            retval = re.sub(r'\bId$', 'ID', retval)
 
            cls._HUMAN_NAMES[key] = retval
 
        return retval
 

	
 

	
 
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)
 

	
 
    # This is arguably cheating a litttle bit, but I'd argue the date of
 
    # the parent transaction still qualifies as posting metadata, and
 
    # it's something we want to access so often it's good to have it
 
    # within easy reach.
 
    @property
 
    def date(self) -> datetime.date:
 
        return self.txn.date
 

	
 

	
 
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
 
    cost: Optional[bc_position.Cost]
 
    # 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: PostingMeta  # type:ignore[assignment]
 

	
 
    @classmethod
 
    def from_beancount(cls,
 
                       txn: Transaction,
 
                       index: int,
 
                       post: Optional[BasePosting]=None,
 
    ) -> 'Posting':
 
        if post is None:
 
            post = txn.postings[index]
 
        return cls(
 
            Account(post.account),
 
            *post[1:5],
 
            # see rationale above about Posting.meta
 
            PostingMeta(txn, index, post), # type:ignore[arg-type]
 
        )
 

	
 
    @classmethod
 
    def from_txn(cls, txn: Transaction) -> Iterator['Posting']:
 
        """Yield an enhanced Posting object for every posting in the transaction"""
 
        for index, post in enumerate(txn.postings):
 
            yield cls.from_beancount(txn, index, post)
 

	
 
    @classmethod
 
    def from_entries(cls, entries: Iterable[Directive]) -> Iterator['Posting']:
 
        """Yield an enhanced Posting object for every posting in these entries"""
 
        for entry in entries:
 
            # Because Beancount's own Transaction class isn't type-checkable,
 
            # we can't statically check this. Might as well rely on duck
 
            # typing while we're at it: just try to yield postings from
 
            # everything, and ignore entries that lack a postings attribute.
 
            try:
 
                yield from cls.from_txn(entry)  # type:ignore[arg-type]
 
            except AttributeError:
 
                pass
 

	
 
    def at_cost(self) -> Amount:
 
        if self.cost is None:
 
            return self.units
 
        else:
 
            return Amount(self.units.number * self.cost.number, self.cost.currency)
 

	
 

	
 
_KT = TypeVar('_KT', bound=Hashable)
 
_VT = TypeVar('_VT')
 
class _SizedDict(collections.OrderedDict, MutableMapping[_KT, _VT]):
 
    def __init__(self, maxsize: int=128) -> None:
 
        self.maxsize = maxsize
 
        super().__init__()
 

	
 
    def __setitem__(self, key: _KT, value: _VT) -> None:
 
        super().__setitem__(key, value)
 
        for _ in range(self.maxsize, len(self)):
 
            self.popitem(last=False)
 

	
 

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

	
 
    Given a transaction and a series of account predicates, balance_of
tests/test_meta_repo_links.py
Show inline comments
 
"""Test link checker for repository documents"""
 
# 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 pathlib import Path
 

	
 
import pytest
 

	
 
from . import testutil
 

	
 
from conservancy_beancount import errors as errormod
 
from conservancy_beancount.plugin import meta_repo_links
 

	
 
METADATA_KEYS = [
 
    'approval',
 
    'bank-statement',
 
    'check',
 
    'contract',
 
    'invoice',
 
    'purchase-order',
 
    'receipt',
 
    'statement',
 
    'tax-statement',
 
]
 

	
 
GOOD_LINKS = [Path(s) for s in [
 
    'Projects/project-data.yml',
 
    'Projects/project-list.yml',
 
]]
 

	
 
BAD_LINKS = [Path(s) for s in [
 
    'NonexistentDirectory/NonexistentFile1.txt',
 
    'NonexistentDirectory/NonexistentFile2.txt',
 
]]
 

	
 
NOT_FOUND_MSG = '{} not found in repository: {}'.format
 

	
 
def build_meta(keys=None, *sources):
 
    if keys is None:
 
        keys = iter(METADATA_KEYS)
 
    sources = (itertools.cycle(src) for src in sources)
 
    return {key: ' '.join(str(x) for x in rest)
 
            for key, *rest in zip(keys, *sources)}
 

	
 
@pytest.fixture(scope='module')
 
def hook():
 
    config = testutil.TestConfig(repo_path='repository')
 
    return meta_repo_links.MetaRepoLinks(config)
 

	
 
def test_error_with_no_repository():
 
    config = testutil.TestConfig(repo_path=None)
 
    with pytest.raises(errormod.ConfigurationError):
 
        meta_repo_links.MetaRepoLinks(config)
 

	
 
def test_good_txn_links(hook):
 
    meta = build_meta(None, GOOD_LINKS)
 
    txn = testutil.Transaction(**meta, postings=[
 
        ('Income:Donations', -5),
 
        ('Assets:Cash', 5),
 
    ])
 
    assert not list(hook.run(txn))
 

	
 
def test_good_post_links(hook):
 
    meta = build_meta(None, GOOD_LINKS)
 
    txn = testutil.Transaction(postings=[
 
        ('Income:Donations', -5, meta),
 
        ('Assets:Cash', 5),
 
    ])
 
    assert not list(hook.run(txn))
 

	
 
def test_bad_txn_links(hook):
 
    meta = build_meta(None, BAD_LINKS)
 
    txn = testutil.Transaction(**meta, postings=[
 
        ('Income:Donations', -5),
 
        ('Assets:Cash', 5),
 
    ])
 
    expected = {NOT_FOUND_MSG(key, value) for key, value in meta.items()}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
def test_bad_post_links(hook):
 
    meta = build_meta(None, BAD_LINKS)
 
    txn = testutil.Transaction(postings=[
 
        ('Income:Donations', -5, meta.copy()),
 
        ('Assets:Cash', 5),
 
    ])
 
    expected = {NOT_FOUND_MSG(key, value) for key, value in meta.items()}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
def test_flagged_txn_not_checked(hook):
 
    keys = iter(METADATA_KEYS)
 
    txn_meta = build_meta(keys, BAD_LINKS)
 
    txn_meta['flag'] = '!'
 
    txn = testutil.Transaction(**txn_meta, postings=[
 
        ('Income:Donations', -5, build_meta(keys, BAD_LINKS)),
 
        ('Assets:Checking', 5, build_meta(keys, BAD_LINKS)),
 
    ])
 
    assert not list(hook.run(txn))
 

	
 
@pytest.mark.parametrize('value', testutil.NON_STRING_METADATA_VALUES)
 
def test_bad_metadata_type(hook, value):
 
    txn = testutil.Transaction(**{'check': value}, postings=[
 
        ('Income:Donations', -5),
 
        ('Assets:Cash', 5),
 
    ])
 
    expected = {'transaction has wrong type of check: expected str but is a {}'.format(
 
        type(value).__name__,
 
    )}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
@pytest.mark.parametrize('ext_doc', [
 
    'rt:123',
 
    'rt:456/789',
 
    'rt://ticket/23',
 
    'rt://ticket/34/attachments/567890',
 
])
 
def test_docs_outside_repository_not_checked(hook, ext_doc):
 
    txn = testutil.Transaction(
 
        receipt='{} {} {}'.format(GOOD_LINKS[0], ext_doc, BAD_LINKS[1]),
 
        postings=[
 
            ('Income:Donations', -5),
 
            ('Assets:Cash', 5),
 
        ])
 
    expected = {NOT_FOUND_MSG('receipt', BAD_LINKS[1])}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
def test_mixed_results(hook):
 
    txn = testutil.Transaction(
 
        approval='{} {}'.format(*GOOD_LINKS),
 
        contract='{} {}'.format(BAD_LINKS[0], GOOD_LINKS[1]),
 
        postings=[
 
            ('Income:Donations', -5, {'invoice': '{} {}'.format(*BAD_LINKS)}),
 
            ('Assets:Cash', 5, {'statement': '{} {}'.format(GOOD_LINKS[0], BAD_LINKS[1])}),
 
        ])
 
    expected = {
 
        NOT_FOUND_MSG('contract', BAD_LINKS[0]),
 
        NOT_FOUND_MSG('invoice', BAD_LINKS[0]),
 
        NOT_FOUND_MSG('invoice', BAD_LINKS[1]),
 
        NOT_FOUND_MSG('statement', BAD_LINKS[1]),
 
    }
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
tests/test_meta_rt_links.py
Show inline comments
 
"""Test link checker for RT links"""
 
# 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
 

	
 
import pytest
 

	
 
from . import testutil
 

	
 
from conservancy_beancount import errors as errormod
 
from conservancy_beancount.plugin import meta_rt_links
 

	
 
METADATA_KEYS = [
 
    'approval',
 
    'bank-statement',
 
    'check',
 
    'contract',
 
    'invoice',
 
    'purchase-order',
 
    'receipt',
 
    'rt-id',
 
    'statement',
 
    'tax-statement',
 
]
 

	
 
GOOD_LINKS = [
 
    'rt:1',
 
    'rt:1/5',
 
    'rt://ticket/2',
 
    'rt://ticket/3/attachments/15',
 
]
 

	
 
MALFORMED_LINKS = [
 
    'rt:one',
 
    'rt:two/three',
 
    'rt://4',
 
    'rt://ticket/5/attach/6',
 
]
 

	
 
NOT_FOUND_LINKS = [
 
    'rt:1/10',
 
    'rt:10',
 
    'rt://ticket/9',
 
    'rt://ticket/3/attachments/99',
 
]
 

	
 
MALFORMED_MSG = '{} link is malformed: {}'.format
 
NOT_FOUND_MSG = '{} not found in RT: {}'.format
 

	
 
def build_meta(keys=None, *sources):
 
    if keys is None:
 
        keys = iter(METADATA_KEYS)
 
    sources = (itertools.cycle(src) for src in sources)
 
    return {key: ' '.join(str(x) for x in rest)
 
            for key, *rest in zip(keys, *sources)}
 

	
 
@pytest.fixture(scope='module')
 
def hook():
 
    config = testutil.TestConfig(rt_client=testutil.RTClient())
 
    return meta_rt_links.MetaRTLinks(config)
 

	
 
def test_error_with_no_rt():
 
    config = testutil.TestConfig()
 
    with pytest.raises(errormod.ConfigurationError):
 
        meta_rt_links.MetaRTLinks(config)
 

	
 
def test_good_txn_links(hook):
 
    meta = build_meta(None, GOOD_LINKS)
 
    txn = testutil.Transaction(**meta, postings=[
 
        ('Income:Donations', -5),
 
        ('Assets:Cash', 5),
 
    ])
 
    assert not list(hook.run(txn))
 

	
 
def test_good_post_links(hook):
 
    meta = build_meta(None, GOOD_LINKS)
 
    txn = testutil.Transaction(postings=[
 
        ('Income:Donations', -5, meta),
 
        ('Assets:Cash', 5),
 
    ])
 
    assert not list(hook.run(txn))
 

	
 
@pytest.mark.parametrize('link_source,format_error', [
 
    (MALFORMED_LINKS, MALFORMED_MSG),
 
    (NOT_FOUND_LINKS, NOT_FOUND_MSG),
 
])
 
def test_bad_txn_links(hook, link_source, format_error):
 
    meta = build_meta(None, link_source)
 
    txn = testutil.Transaction(**meta, postings=[
 
        ('Income:Donations', -5),
 
        ('Assets:Cash', 5),
 
    ])
 
    expected = {format_error(key, value) for key, value in meta.items()}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
@pytest.mark.parametrize('link_source,format_error', [
 
    (MALFORMED_LINKS, MALFORMED_MSG),
 
    (NOT_FOUND_LINKS, NOT_FOUND_MSG),
 
])
 
def test_bad_post_links(hook, link_source, format_error):
 
    meta = build_meta(None, link_source)
 
    txn = testutil.Transaction(postings=[
 
        ('Income:Donations', -5, meta.copy()),
 
        ('Assets:Cash', 5),
 
    ])
 
    expected = {format_error(key, value) for key, value in meta.items()}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
@pytest.mark.parametrize('value', testutil.NON_STRING_METADATA_VALUES)
 
def test_bad_metadata_type(hook, value):
 
    txn = testutil.Transaction(**{'rt-id': value}, postings=[
 
        ('Income:Donations', -5),
 
        ('Assets:Cash', 5),
 
    ])
 
    expected = {'transaction has wrong type of rt-id: expected str but is a {}'.format(
 
        type(value).__name__,
 
    )}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
@pytest.mark.parametrize('ext_doc', [
 
    'statement.txt',
 
    'https://example.org/',
 
])
 
def test_docs_outside_rt_not_checked(hook, ext_doc):
 
    txn = testutil.Transaction(
 
        receipt='{} {} {}'.format(GOOD_LINKS[0], ext_doc, MALFORMED_LINKS[1]),
 
        postings=[
 
            ('Income:Donations', -5),
 
            ('Assets:Cash', 5),
 
        ])
 
    expected = {MALFORMED_MSG('receipt', MALFORMED_LINKS[1])}
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
 

	
 
def test_flagged_txn_not_checked(hook):
 
    txn_meta = build_meta(None, MALFORMED_LINKS)
 
    txn_meta['flag'] = '!'
 
    keys = iter(METADATA_KEYS)
 
    txn = testutil.Transaction(**txn_meta, postings=[
 
        ('Income:Donations', -5, build_meta(keys, MALFORMED_LINKS)),
 
        ('Assets:Checking', 5, build_meta(keys, NOT_FOUND_LINKS)),
 
    ])
 
    assert not list(hook.run(txn))
 

	
 
def test_mixed_results(hook):
 
    txn = testutil.Transaction(
 
        approval='{} {}'.format(*GOOD_LINKS),
 
        contract='{} {}'.format(MALFORMED_LINKS[0], GOOD_LINKS[1]),
 
        postings=[
 
            ('Income:Donations', -5, {'invoice': '{} {}'.format(*NOT_FOUND_LINKS)}),
 
            ('Assets:Cash', 5, {'statement': '{} {}'.format(GOOD_LINKS[0], MALFORMED_LINKS[1])}),
 
        ])
 
    expected = {
 
        MALFORMED_MSG('contract', MALFORMED_LINKS[0]),
 
        NOT_FOUND_MSG('invoice', NOT_FOUND_LINKS[0]),
 
        NOT_FOUND_MSG('invoice', NOT_FOUND_LINKS[1]),
 
        MALFORMED_MSG('statement', MALFORMED_LINKS[1]),
 
    }
 
    actual = {error.message for error in hook.run(txn)}
 
    assert expected == actual
0 comments (0 inline, 0 general)