Files @ c712105bed3c
Branch filter:

Location: NPO-Accounting/conservancy_beancount/tests/test_meta_receivable_documentation.py

Brett Smith
Revise chart of accounts used throughout.

The main impetus of this change is to rename accounts that were outside
Beancount's accepted five root accounts, to move them into that
structure. This includes:

Accrued:*Payable: → Liabilities:Payable:*
Accrued:*Receivable: → Assets:Receivable:*
UneanedIncome:* → Liabilities:UnearnedIncome:*

Note the last change did inspire in a change to our validation rules. We no
longer require income-type on unearned income, because it's no longer
considered income at all. Once it's earned and converted to an Income
account, that has an income-type of course.

This did inspire another rename that was not required, but
provided more consistency with the other account names above:

Assets:Prepaid* → Assets:Prepaid:*

Where applicable, I have generally extended tests to make sure one of each
of the five account types is tested. (This mostly meant adding an Equity
account to the tests.) I also added tests for key parts of the hierarchy,
like Assets:Receivable and Liabilities:Payable, where applicable.

As part of this change, Account.is_real_asset() got renamed to
Account.is_cash_equivalent(), to better self-document its purpose.
"""Test metadata for receivables includes supporting documentation"""
# 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 random

import pytest

from . import testutil

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

TEST_ACCT = 'Assets:Receivable:Accounts'
OTHER_ACCT = 'Income:Donations'

SUPPORTING_METADATA = [
    'approval',
    'contract',
    'purchase-order',
]

NON_SUPPORTING_METADATA = [
    'check',
    'receipt',
    'statement',
]

ISSUED_INVOICE_LINKS = [
    'rt:1/6',
    'rt://ticket/2/attachments/10',
    'Financial/Invoices/Company_invoice-2020030405_as-sent.pdf',
    'Projects/Alpha/Invoices/ProjectInvoice-304567.pdf',
]

RECEIVED_INVOICE_LINKS = [
    'rt:1/4',
    'rt://ticket/2/attachments/14',
    'Financial/Invoices/Invoice-23456789.csv',
    'Projects/Bravo/Invoices/Statement304567.pdf',
]

MISSING_MSG = f"{TEST_ACCT} missing approval/contract/purchase-order"

# for supporting links, use the lists from testutil

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

def seed_meta(invoice=ISSUED_INVOICE_LINKS[0],
              support_values=testutil.NON_LINK_METADATA_STRINGS,
              **kwargs,
):
    meta = dict(testutil.combine_values(
        SUPPORTING_METADATA,
        support_values,
    ))
    meta.update(kwargs)
    meta['invoice'] = invoice
    return meta

def wrong_type_message(key, wrong_value):
    return  "{} has wrong type of {}: expected str but is a {}".format(
        TEST_ACCT,
        key,
        type(wrong_value).__name__,
    )

def check(hook, expected, test_acct=TEST_ACCT, other_acct=OTHER_ACCT, *,
          txn_meta={}, post_meta={}, min_amt=10):
    amount = '{:.02f}'.format(min_amt + random.random() * 100)
    txn = testutil.Transaction(**txn_meta, postings=[
        (test_acct, amount, post_meta),
        (other_acct, f'-{amount}'),
    ])
    actual = {error.message for error in hook.run(txn)}
    if expected is None:
        assert not actual
    elif isinstance(expected, str):
        assert expected in actual
    else:
        assert actual == expected

@pytest.mark.parametrize('invoice,support_key,support_value', testutil.combine_values(
    ISSUED_INVOICE_LINKS,
    SUPPORTING_METADATA,
    testutil.LINK_METADATA_STRINGS,
))
def test_valid_docs_in_post(hook, invoice, support_key, support_value):
    meta = seed_meta(invoice)
    meta[support_key] = support_value
    check(hook, None, post_meta=meta)

@pytest.mark.parametrize('invoice,support_key,support_value', testutil.combine_values(
    ISSUED_INVOICE_LINKS,
    SUPPORTING_METADATA,
    testutil.LINK_METADATA_STRINGS,
))
def test_valid_docs_in_txn(hook, invoice, support_key, support_value):
    meta = seed_meta(invoice)
    meta[support_key] = support_value
    check(hook, None, txn_meta=meta)

@pytest.mark.parametrize('invoice,meta_type', testutil.combine_values(
    ISSUED_INVOICE_LINKS,
    ['post_meta', 'txn_meta'],
))
def test_no_valid_docs(hook, invoice, meta_type):
    meta = seed_meta(invoice)
    meta.update((key, value) for key, value in testutil.combine_values(
        NON_SUPPORTING_METADATA,
        testutil.LINK_METADATA_STRINGS,
    ))
    check(hook, {MISSING_MSG}, **{meta_type: meta})

@pytest.mark.parametrize('invoice,meta_type', testutil.combine_values(
    ISSUED_INVOICE_LINKS,
    ['post_meta', 'txn_meta'],
))
def test_docs_all_bad_type(hook, invoice, meta_type):
    meta = seed_meta(invoice, testutil.NON_STRING_METADATA_VALUES)
    expected = {
        wrong_type_message(key, value)
        for key, value in meta.items()
        if key != 'invoice'
    }
    expected.add(MISSING_MSG)
    check(hook, expected, **{meta_type: meta})

@pytest.mark.parametrize('invoice,support_key,support_value', testutil.combine_values(
    ISSUED_INVOICE_LINKS,
    SUPPORTING_METADATA,
    testutil.LINK_METADATA_STRINGS,
))
def test_type_errors_reported_with_valid_post_docs(hook, invoice, support_key, support_value):
    meta = seed_meta(invoice, testutil.NON_STRING_METADATA_VALUES)
    meta[support_key] = support_value
    expected = {
        wrong_type_message(key, value)
        for key, value in meta.items()
        if key != 'invoice' and  key != support_key
    }
    check(hook, expected, post_meta=meta)

@pytest.mark.parametrize('invoice,support_key,support_value', testutil.combine_values(
    ISSUED_INVOICE_LINKS,
    SUPPORTING_METADATA,
    testutil.LINK_METADATA_STRINGS,
))
def test_type_errors_reported_with_valid_txn_docs(hook, invoice, support_key, support_value):
    meta = seed_meta(invoice, testutil.NON_STRING_METADATA_VALUES)
    meta[support_key] = support_value
    expected = {
        wrong_type_message(key, value)
        for key, value in meta.items()
        if key != 'invoice' and  key != support_key
    }
    check(hook, expected, txn_meta=meta)

@pytest.mark.parametrize('invoice,meta_type', testutil.combine_values(
    RECEIVED_INVOICE_LINKS,
    ['post_meta', 'txn_meta'],
))
def test_received_invoices_not_checked(hook, invoice, meta_type):
    check(hook, None, **{meta_type: {'invoice': invoice}})

@pytest.mark.parametrize('account', [
    'Assets:Bank:Checking',
    'Assets:Cash',
    'Equity:OpeningBalance',
    'Expenses:BankingFees',
    'Liabilities:CreditCard',
    'Liabilities:Payable:Accounts',
])
def test_does_not_apply_to_other_accounts(hook, account):
    meta = seed_meta()
    check(hook, None, account, 'Expenses:Other', post_meta=meta)

def test_configuration_error_without_rt():
    config = testutil.TestConfig()
    with pytest.raises(errormod.ConfigurationError):
        meta_receivable_documentation.MetaReceivableDocumentation(config)