patchwise-agent-studio / coworker /tests /test_interfaces.py
EnergyVenom's picture
Astra: interface testing (opt-in), 26D screen fixes for journals, transactions and invoice types (15e2c63d18cb)
2a2e3d4 verified
Raw History Blame Contribute Delete
28 kB
"""Interface (import) testing: the client's volume that arrives through imports (AutoInvoice "Receivables Import", Payables invoice
import "External") is tested the way the client's integrations create it. A FBDI file of one tagged test document is uploaded through
Fusion's ERP Integration REST service by the automation (automation/src/fusion/interfaces.ts, rest.ts, steps.ts).
Covered here, without a browser or a pod: the FBDI builders and the call (the TypeScript check script, and the column tables read
from the source), the step checks of import_payables_invoice and import_receivables_transaction (scenario-only, never in a canary),
the opt-in (the pod's allow_imports setting: default off, admin only, audited, never on a practice pod; passed to runs as
FPT_ALLOW_IMPORTS=1 and on both env allow-lists), the egress rule for writes to a pod, the clean-up of an imported document, and
the usage coverage of the sources External and Receivables Import (and not of Spreadsheet or ERS)."""
from __future__ import annotations
import json
import re
import shutil
import subprocess
import unittest
import yaml
from ..adapters import cases as cases_adapter
from ..adapters import remote_runner
from ..config import ROOT
from ..platform import cleanup, left_on_pod, usage
from ..platform import step_writer as sw
from ..platform.egress import CLEANUP_PATH, EgressDenied
from ..platform.pods import PodRegistry
from .fakes import REST, bearer, make_app
from .test_ar_business_actions import AR_INV, TestCleanupOfReceivables
from .test_business_actions import runner_actions, yaml_draft
from .test_po_gl_business_actions import AP_INV, draft, problems
AUTOMATION = ROOT / "automation"
BIN = AUTOMATION / "node_modules" / ".bin"
TSX = BIN / "tsx.cmd" if (BIN / "tsx.cmd").exists() else BIN / "tsx"
FUSION = AUTOMATION / "src" / "fusion"
INTERFACES_TS = (FUSION / "interfaces.ts").read_text(encoding="utf-8")
BASE = "https://acme-test.fa.ocs.oraclecloud.com"
POD = {"name": "Acme test pod", "kind": "fusion", "base_url": BASE, "environment": "test", "modules": ["AP", "AR"]}
IMPORTS = ("import_payables_invoice", "import_receivables_transaction")
SCENARIOS = ("AP-FUS-040", "AR-FUS-040")
def columns(name: str) -> list[str]:
"""A FBDI column table of interfaces.ts, in its order."""
body = INTERFACES_TS.split(f"export const {name} = [", 1)[1].split("] as const;", 1)[0]
out: list[str] = []
for part in re.findall(r"'([^']*)'|\.\.\.seq\('([^']*)', (\d+)\)", body):
out += [part[0]] if part[0] else [f"{part[1]} {i}" for i in range(1, int(part[2]) + 1)]
return out
class TestFbdiBuilders(unittest.TestCase):
"""The builders are pure TypeScript: scripts/check-interfaces.ts runs them (and has Python's zipfile read the zip back)."""
@unittest.skipUnless(shutil.which("node") and TSX.exists(), "tsx is not installed (npm ci in automation/)")
def test_the_check_script_passes(self):
r = subprocess.run([str(TSX), "scripts/check-interfaces.ts"], cwd=AUTOMATION, capture_output=True, text=True, timeout=180,
shell=TSX.suffix == ".cmd")
self.assertEqual(r.returncode, 0, (r.stdout + r.stderr)[-1500:])
self.assertIn("interfaces: all checks pass", r.stdout)
def test_the_column_order_is_the_templates_for_the_columns_the_test_fills(self):
header, lines, ar = columns("AP_INVOICE_COLUMNS"), columns("AP_LINE_COLUMNS"), columns("AR_LINE_COLUMNS")
self.assertEqual(header[:6], ["Invoice ID", "Business Unit", "Source", "Invoice Number", "Invoice Amount", "Invoice Date"])
self.assertEqual(lines[:4], ["Invoice ID", "Line Number", "Line Type", "Amount"]) # the line is tied to its header by the first column
self.assertEqual(ar[:3], ["Business Unit Name", "Batch Source Name", "Transaction Type Name"])
self.assertEqual(ar.index("Transaction Number"), 6)
self.assertEqual(ar[-15:], [f"Interface Line Attribute {i}" for i in range(1, 16)])
for table in (header, lines, ar):
self.assertEqual(len(table), len(set(table)), "a column name twice")
def test_every_document_is_tagged_so_clean_up_and_left_on_pod_find_it(self):
# the AP invoice number and the import set, the AR transaction number, customer order number (REST: PurchaseOrder) and attribute 1
for text in ("'Invoice Number': nonEmpty('the invoice number', a.tag)", "'Import Set': a.tag", "'Customer Order Number': a.tag",
"'Interface Line Attribute 1': a.tag"):
self.assertIn(text, INTERFACES_TS)
self.assertIn("PurchaseOrder='${q(numberOrTag)}'", (FUSION / "rest.ts").read_text(encoding="utf-8"))
def test_the_oracle_specific_assumptions_are_one_table(self):
for text in ("fin$/payables$/import$", "fin$/receivables$/import$", ",APXIIMPT", ",AutoInvoiceImportEss"):
self.assertEqual(INTERFACES_TS.count(text), 1, text)
self.assertEqual(len(re.findall(r"interfaceDetails: \d+,", INTERFACES_TS)), 2) # one per import
for text in ("fin$/", "APXIIMPT", "AutoInvoiceImportEss"): # and nowhere else in the automation
for f in ("steps.ts", "ui.ts", "fixtures.ts"):
self.assertNotIn(text, (FUSION / f).read_text(encoding="utf-8"), (f, text))
class TestRestCallsAreGated(unittest.TestCase):
REST_TS = (FUSION / "rest.ts").read_text(encoding="utf-8")
def test_the_only_write_to_the_erp_integration_service_checks_the_opt_in_and_production(self):
self.assertEqual(self.REST_TS.count("'erpintegrations'"), 1)
body = self.REST_TS.split("async importBulkData(", 1)[1].split("\n }\n", 1)[0]
self.assertLess(body.index("importsAllowed()"), body.index("this.call('POST'"))
self.assertLess(body.index("looksLikeProduction("), body.index("this.call('POST'"))
for f in ("steps.ts", "ui.ts", "fixtures.ts", "interfaces.ts"):
self.assertNotIn("erpintegrations'", (FUSION / f).read_text(encoding="utf-8"), f)
self.assertIn('if (!importsAllowed())', (FUSION / "steps.ts").read_text(encoding="utf-8")) # the actions refuse first themselves
self.assertEqual((FUSION / "steps.ts").read_text(encoding="utf-8").count("if (!ctx.rest.available) return importSkipped("), 2) # no REST: skipped
def test_the_python_egress_never_posts_to_the_erp_integration_service(self):
# the runner calls the pod directly: no Python egress is in that path, so FPT_ALLOW_IMPORTS is the gate. The gate in Python stays
# shut for it: a POST to it is allowed neither to clean up nor, without SEED_ALLOWED=1, to seed
app, c, svc, pod = make_app()
path = f"{REST}/erpintegrations"
for purpose in ("read", "cleanup", "seed"):
with self.assertRaises(EgressDenied, msg=purpose):
svc.egress.fusion_request(BASE, "POST", path, auth=("u", "p"), purpose=purpose, json_body={})
self.assertFalse(svc.cfg.seed_allowed)
class TestAllowedActions(unittest.TestCase):
def test_each_is_offered_belongs_to_its_area_and_the_runner_has_it(self):
known = runner_actions()
for a, area in (("import_payables_invoice", "AP"), ("import_receivables_transaction", "AR")):
self.assertIn(a, sw.ALLOWED_ACTIONS)
self.assertIn(a, known)
self.assertIn(a, sw.BUSINESS_AREAS[area]["actions"])
self.assertIn(a, sw.SCENARIO_ONLY_ACTIONS)
self.assertIn(f"{sw.BUSINESS_AREAS[area]['name']} business action", sw.ALLOWED_ACTIONS[a])
self.assertIn("allow imports", sw.ALLOWED_ACTIONS[a].lower())
self.assertFalse(re.search(r"\d", sw.ALLOWED_ACTIONS[a]), a) # no figure the leak check could take for data
self.assertEqual(sw.IMPORT_ACTIONS, IMPORTS)
def test_none_is_in_a_canary(self):
for cid in ("CANARY-AP", "CANARY-AR", "CANARY-GL", "CANARY-PO"):
acts = {s["action"] for s in yaml.safe_load((sw.CASES_DIR / f"{cid}.yaml").read_text(encoding="utf-8"))["steps"]}
self.assertFalse(acts & set(IMPORTS), cid)
def test_a_draft_keeps_the_import_steps_fields(self):
d = draft([{"action": "import_payables_invoice", "source": "External", "name": "inv"},
{"action": "import_receivables_transaction", "transaction_source": "Receivables Import", "transaction_type": "Invoice"}])
steps = yaml.safe_load(sw.to_case_yaml({"title": "t", "type": "happy", "task": AP_INV["task"]}, d, "AP-AI-001"))["steps"]
self.assertEqual((steps[1]["source"], steps[1]["name"]), ("External", "inv"))
self.assertEqual((steps[2]["transaction_source"], steps[2]["transaction_type"]), ("Receivables Import", "Invoice"))
class TestStepChecks(unittest.TestCase):
def ap(self, *steps, **over):
return problems(draft([*steps], **over), AP_INV)
def ar(self, *steps, **over):
return problems(draft([*steps], **over), AR_INV)
def test_an_imported_invoice_is_checked_validated_and_checked_again_without_a_screen_before_it(self):
self.assertEqual(self.ap({"action": "import_payables_invoice", "source": "External"}, {"action": "expect_invoice", "source": "external"},
{"action": "validate_invoice"}, {"action": "expect_invoice", "status": "Validated", "source": "External"}), "")
self.assertEqual(self.ap({"action": "import_payables_invoice", "name": "imp"}, {"action": "expect_invoice", "name": "imp", "source": "{{tv.s}}"},
test_values={"amount": "5", "s": "External"}), "") # a placeholder is a pod value: not compared
def test_an_imported_transaction_may_be_checked_for_its_import_source_a_keyed_one_may_not(self):
self.assertEqual(self.ar({"action": "import_receivables_transaction", "transaction_source": "Receivables Import", "transaction_type": "Invoice"},
{"action": "find_transaction"}, {"action": "expect_transaction", "transaction_source": "receivables import",
"transaction_type": "invoice", "amount_at_least": "{{tv.amount}}"}), "")
p = self.ar({"action": "create_transaction", "transaction_source": "Receivables Import"})
self.assertIn("an import is a scheduled process", p)
self.assertIn("make it with import_receivables_transaction", p)
p = self.ar({"action": "create_transaction"}, {"action": "expect_transaction", "transaction_source": "AutoInvoice"})
self.assertIn("the transaction was not imported", p)
def test_the_source_must_be_the_one_it_came_in_with(self):
self.assertIn("the invoice came in as external (import_payables_invoice)",
self.ap({"action": "import_payables_invoice"}, {"action": "expect_invoice", "source": "Spreadsheet"}))
self.assertIn("the invoice came in as manual invoice entry (create_invoice)",
self.ap({"action": "create_invoice"}, {"action": "expect_invoice", "source": "External"}))
self.assertEqual(self.ap({"action": "create_invoice"}, {"action": "expect_invoice", "source": "Manual Invoice Entry"}), "")
self.assertIn("transaction_source 'Other': the transaction was created from receivables import",
self.ar({"action": "import_receivables_transaction", "transaction_source": "Receivables Import"},
{"action": "expect_transaction", "transaction_source": "Other"}))
self.assertIn("source must be the invoice source's name", self.ap({"action": "import_payables_invoice", "source": "5; drop"}))
def test_the_amount_manual_and_the_fields_are_checked(self):
self.assertIn("a standard invoice has a positive amount", self.ap({"action": "import_payables_invoice", "value": "-5"}))
self.assertIn("a standard invoice has a positive amount", self.ap({"action": "import_payables_invoice"}, test_values={"amount": "-5"}))
self.assertIn("needs an amount", self.ap({"action": "import_payables_invoice"}, test_values={}))
self.assertIn("needs an amount", self.ar({"action": "import_receivables_transaction"}, test_values={}))
self.assertIn("'Manual': Manual is the source of a transaction keyed in",
self.ar({"action": "import_receivables_transaction", "transaction_source": "Manual"}))
self.assertIn("a credit memo is entered with a negative amount",
self.ar({"action": "import_receivables_transaction", "transaction_type": "Credit Memo", "value": "5"}))
# the fields belong to their actions, and the journal source stays Manual
self.assertIn("transaction_source belongs to", self.ar({"action": "find_transaction", "transaction_source": "Manual"}))
self.assertIn("source belongs to create_journal or expect_journal, not validate_invoice", self.ap({"action": "validate_invoice", "source": "External"}))
self.assertIn("a person enters only Manual journals", problems(draft([{"action": "create_journal", "source": "Payables"}]), {
"task": "General Accounting > Journals > Create Journal", "fields": [{"label": "Journal Batch", "kind": "text"}], "buttons": [], "menus": {},
"sections": [], "tables": {}}))
def test_an_import_belongs_to_its_areas_screens(self):
self.assertIn("import_receivables_transaction is a Receivables business action and this scenario is not on a Receivables screen",
self.ap({"action": "import_receivables_transaction"}))
self.assertIn("import_payables_invoice is a Payables business action and this scenario is not on a Payables screen",
self.ar({"action": "import_payables_invoice"}))
def test_an_expectation_needs_the_document_an_import_made(self):
self.assertIn("expect_invoice needs an invoice created (create_invoice) or remembered", self.ap({"action": "expect_invoice", "source": "External"}))
self.assertIn("expect_transaction needs a transaction created", self.ar({"action": "expect_transaction", "transaction_source": "Receivables Import"}))
self.assertIn("needs an invoice created", self.ap({"action": "import_payables_invoice", "name": "a"}, {"action": "expect_invoice", "name": "b"}))
class TestScenarios(unittest.TestCase):
def test_each_loads_as_a_fusion_scenario_passes_the_checks_and_has_its_spec(self):
lib = {c["id"]: c for c in cases_adapter.load_cases()}
known = runner_actions()
for cid, module, inv in (("AP-FUS-040", "AP", AP_INV), ("AR-FUS-040", "AR", AR_INV)):
self.assertIn(cid, lib)
self.assertEqual((lib[cid]["target"], lib[cid]["module"]), ("fusion", module), cid)
d = yaml_draft(cid)
acts = {s["action"] for s in d["steps"]}
self.assertTrue(acts <= set(sw.ALLOWED_ACTIONS) and acts <= known, (cid, acts))
self.assertEqual(sw.check_steps(d, inv), [], cid)
doc = yaml.safe_load((sw.CASES_DIR / f"{cid}.yaml").read_text(encoding="utf-8"))
self.assertEqual(doc["runner"], "steps")
self.assertFalse(doc.get("canary"))
entry = (ROOT / "automation" / "tests" / "fusion" / "steps" / f"{cid}.spec.ts").read_text(encoding="utf-8")
self.assertIn(f"stepsTest('{cid}', ['@{cid}','@{module}'", entry)
self.assertIn("allow", " ".join(doc["preconditions"]).lower()) # the precondition says imports must be allowed
def test_they_do_what_their_titles_say(self):
ap = yaml_draft("AP-FUS-040")["steps"]
self.assertEqual([s["action"] for s in ap][1:], ["import_payables_invoice", "expect_invoice", "validate_invoice", "expect_invoice"])
self.assertEqual((ap[1]["source"], ap[2]["source"], ap[4]["source"], ap[4]["status"]), ("External", "External", "External", "Validated"))
ar = yaml_draft("AR-FUS-040")["steps"]
self.assertEqual([s["action"] for s in ar][1:], ["import_receivables_transaction", "find_transaction", "expect_transaction"])
self.assertEqual((ar[1]["transaction_source"], ar[3]["transaction_source"], ar[1]["transaction_type"], ar[3]["transaction_type"]),
("Receivables Import",) * 2 + ("Invoice",) * 2)
for cid in SCENARIOS:
self.assertIn("never in\n# a canary", (sw.CASES_DIR / f"{cid}.yaml").read_text(encoding="utf-8").replace("\r\n", "\n"))
def profile() -> dict:
"""A profile in which the sources of both areas are used (counts are small samples of a client's records)."""
def dims(code: str, values_by_dim: dict[tuple[str, str], list[str]]) -> dict:
out = []
for (resource, key), values in values_by_dim.items():
spec = next(s for s in usage.USAGE[code] if s["resource"] == resource)
d = next(x for x in spec["dimensions"] if x["key"] == key)
field = d["field"] if isinstance(d["field"], str) else d["field"][0]
out.append(usage.count_dimension(d, [{field: v} for v in values for _ in range(10)], resource))
return out
return {"read_at": "2026-11-21T00:00:00Z", "days": 90, "since": "2026-08-23", "areas": [
{"code": "AP", "name": "Payables", "status": "read", "resources": [{"resource": "invoices", "status": "read", "total": 100}],
"dimensions": dims("AP", {("invoices", "source"): ["Manual Invoice Entry", "External", "Spreadsheet", "ERS"]})},
{"code": "AR", "name": "Receivables", "status": "read", "resources": [{"resource": "receivablesInvoices", "status": "read", "total": 100}],
"dimensions": dims("AR", {("receivablesInvoices", "transaction_source"): ["Manual", "Receivables Import"]})}]}
class TestUsageCoverage(unittest.TestCase):
def setUp(self):
self.lib = list(cases_adapter.load_cases())
self.by = {(v["area"], v["value"]): v for v in usage.coverage(profile(), self.lib)["variants"]}
def ids(self, area: str, value: str) -> set[str]:
return {m["id"] for m in self.by[(area, value)]["matches"]}
def test_external_and_receivables_import_are_covered_by_their_import_scenarios(self):
for area, value, cid in (("AP", "External", "AP-FUS-040"), ("AR", "Receivables Import", "AR-FUS-040")):
self.assertEqual(self.by[(area, value)]["status"], "covered", value)
self.assertIn(cid, self.ids(area, value))
def test_the_other_sources_are_not_claimed_by_them(self):
# Spreadsheet (ADFdi) and ERS are other ways in: the Payables import scenario is not about them
for value in ("Spreadsheet", "ERS"):
self.assertNotIn("AP-FUS-040", self.ids("AP", value), value)
self.assertNotEqual(self.by[("AP", value)]["status"], "covered", value)
# keyed in on a screen is not an import, and an import is not keyed in
self.assertNotIn("AP-FUS-040", self.ids("AP", "Manual Invoice Entry"))
self.assertNotIn("AR-FUS-040", self.ids("AR", "Manual"))
self.assertNotIn("AP-FUS-012", self.ids("AP", "External"))
self.assertTrue(not ({"AR-FUS-001", "AR-FUS-002", "AR-FUS-003", "AR-FUS-004", "AR-FUS-006"} & self.ids("AR", "Receivables Import")))
class TestAllowImportsSetting(unittest.TestCase):
def setUp(self):
self.app, self.c, self.svc, self.pod = make_app()
self.h = {r: bearer(self.c, r) for r in ("viewer", "consultant", "admin")}
r = self.c.post("/api/pods", json=POD, headers=self.h["admin"])
self.assertEqual(r.status_code, 201, r.text)
self.row = r.json()
self.pid = self.row["id"]
self.c.post(f"/api/pods/{self.pid}/credentials", json={"module": "AP", "username": "zz.ap", "password": "pw-imports-test-1"}, headers=self.h["admin"])
self.reg = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit)
def patch(self, body, who="admin", pid=None):
return self.c.patch(f"/api/pods/{pid or self.pid}", json=body, headers=self.h[who])
def audit(self, kind):
rows = self.c.get("/api/audit?limit=500", headers=self.h["admin"]).json()
return [a for a in (rows["items"] if isinstance(rows, dict) else rows) if a["kind"] == kind]
def test_it_is_off_by_default_and_the_run_is_not_told_otherwise(self):
self.assertIs(self.row["allow_imports"], False)
self.assertNotIn("FPT_ALLOW_IMPORTS", self.reg.executor_env(self.pid))
self.assertFalse(self.reg.get(self.pid)["allow_imports"])
def test_an_admin_switches_it_on_and_off_and_the_runs_follow(self):
r = self.patch({"allow_imports": True})
self.assertEqual(r.status_code, 200, r.text)
self.assertIs(r.json()["allow_imports"], True)
self.assertEqual(self.reg.executor_env(self.pid)["FPT_ALLOW_IMPORTS"], "1")
self.assertIs(next(p for p in self.c.get("/api/pods", headers=self.h["viewer"]).json() if p["id"] == self.pid)["allow_imports"], True)
self.patch({"notes": "another change"}) # an unrelated change keeps it
self.assertEqual(self.reg.executor_env(self.pid)["FPT_ALLOW_IMPORTS"], "1")
self.assertIs(self.patch({"allow_imports": False}).json()["allow_imports"], False)
self.assertNotIn("FPT_ALLOW_IMPORTS", self.reg.executor_env(self.pid))
def test_only_an_admin_may_and_a_refusal_changes_nothing(self):
for who in ("viewer", "consultant"):
self.assertEqual(self.patch({"allow_imports": True}, who).status_code, 403, who)
self.assertEqual(self.c.patch(f"/api/pods/{self.pid}", json={"allow_imports": True}).status_code, 401)
self.assertFalse(self.reg.get(self.pid)["allow_imports"])
self.assertEqual(self.audit("pod.imports_allowed"), [])
def test_each_change_is_audited_with_who_and_a_repeat_is_not(self):
self.patch({"allow_imports": True})
self.patch({"allow_imports": True}) # no change
self.patch({"allow_imports": False})
on, off = self.audit("pod.imports_allowed"), self.audit("pod.imports_refused")
self.assertEqual((len(on), len(off)), (1, 1))
self.assertEqual((on[0]["actor"], off[0]["actor"]), ("admin", "admin"))
self.assertIn(f"pod {self.pid}", on[0]["summary"])
self.assertIs(on[0]["payload"]["allow_imports"], True)
self.assertIs(off[0]["payload"]["allow_imports"], False)
def test_the_practice_pod_has_no_erp_integration_service(self):
mock = next(p for p in self.c.get("/api/pods", headers=self.h["viewer"]).json() if p["kind"] == "mock")
r = self.patch({"allow_imports": True}, pid=mock["id"])
self.assertEqual((r.status_code, r.json()["code"]), (422, "BAD_ALLOW_IMPORTS"), r.text)
self.assertFalse(self.reg.get(mock["id"])["allow_imports"])
self.assertIsNone(self.reg.executor_env(mock["id"]))
def test_a_production_pod_cannot_exist_so_it_never_gets_the_flag(self):
r = self.c.post("/api/pods", json={**POD, "name": "Prod pod", "base_url": "https://acme-prod.fa.ocs.oraclecloud.com"}, headers=self.h["admin"])
self.assertEqual((r.status_code, r.json()["code"]), (422, "PROD_REFUSED"))
r = self.patch({"base_url": "https://acme-prod.fa.ocs.oraclecloud.com", "allow_imports": True}) # nor by editing a test pod into one
self.assertEqual((r.status_code, r.json()["code"]), (422, "PROD_REFUSED"))
self.assertFalse(self.reg.get(self.pid)["allow_imports"])
def test_the_flag_reaches_a_runner_only_through_both_allow_lists_and_not_from_the_servers_own_environment(self):
self.assertIn("FPT_ALLOW_IMPORTS", remote_runner.ENV_KEYS)
server = (ROOT / "automation" / "remote_runner" / "server.py").read_text(encoding="utf-8")
self.assertRegex(server, r'ENV_KEYS = \{[^}]*"FPT_ALLOW_IMPORTS"')
self.assertRegex(server, r'os\.environ\.items\(\) if k not in \("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE", "FPT_ALLOW_IMPORTS"\)')
local = (ROOT / "coworker" / "adapters" / "playwright.py").read_text(encoding="utf-8")
self.assertIn('env.pop("FPT_ALLOW_IMPORTS", None)', local)
self.assertIn('if "FPT_ALLOW_IMPORTS" not in (cred_env or {})', local)
class TestCleanUpOfImportedDocuments(unittest.TestCase):
"""An imported AR transaction is numbered by Fusion when its source numbers automatically: it is found by the tag in its customer
order number (REST: PurchaseOrder), and a completed one is listed for a person to credit like a screen one."""
def setUp(self):
t = TestCleanupOfReceivables()
t.setUp()
self.t = t
self.pod, self.svc, self.dir, self.rid = t.pod, t.svc, t.dir, t.rid
def sweep(self, *records) -> dict:
with (self.dir / cleanup.LEDGER).open("w", encoding="utf-8") as fh:
for r in records:
fh.write(json.dumps({"test": "Import a transaction", **r}) + "\n")
return cleanup.sweep(self.svc, self.rid, "cancelled")
def test_a_complete_imported_transaction_is_listed_for_a_person_and_an_incomplete_one_is_deleted(self):
self.pod.txns = {61: {"CustomerTransactionId": 61, "TransactionNumber": "AUTO-9001", "PurchaseOrder": "FPT-ARFUS040-1", "InvoiceStatus": "Complete"},
62: {"CustomerTransactionId": 62, "TransactionNumber": "AUTO-9002", "PurchaseOrder": "FPT-ARFUS040-2", "InvoiceStatus": "Incomplete"}}
out = self.sweep({"kind": "ar_transaction", "number": "FPT-ARFUS040-1"}, {"kind": "ar_transaction", "number": "FPT-ARFUS040-2"},
{"kind": "ar_transaction", "number": "FPT-ARFUS040-3"})
left = {x["number"]: x["why"] for x in out["left"]}
self.assertIn("transaction AUTO-9001 is complete", left["FPT-ARFUS040-1"])
self.assertIn("credit it on Manage Transactions", left["FPT-ARFUS040-1"])
done = {x["number"]: x["result"] for x in out["cleaned"]}
self.assertIn("AUTO-9002 deleted", done["FPT-ARFUS040-2"])
self.assertEqual(done["FPT-ARFUS040-3"], "not saved, nothing to clean up")
self.assertEqual(self.pod.writes, [("DELETE", f"{REST}/receivablesInvoices/62")])
def test_it_lands_in_the_left_on_pod_ledger_and_is_looked_at_again_by_the_tag(self):
self.pod.txns = {61: {"CustomerTransactionId": 61, "TransactionNumber": "AUTO-9001", "PurchaseOrder": "FPT-ARFUS040-1", "InvoiceStatus": "Complete"}}
self.sweep({"kind": "ar_transaction", "number": "FPT-ARFUS040-1"})
left_on_pod.record(self.svc, self.rid)
row = self.svc.db.one("SELECT * FROM left_on_pod WHERE reference=?", ("FPT-ARFUS040-1",))
self.assertEqual((row["kind"], row["status"]), ("ar_transaction", "open"))
self.assertIn("Credit Transaction", row["todo"])
self.assertEqual(left_on_pod.recheck(self.svc, row["id"])["check_state"], "still_on_pod")
self.assertEqual(self.pod.writes, []) # looking again changes nothing
def test_an_imported_ap_invoice_is_cancelled_like_a_screen_one(self):
self.assertIn("ap_invoice", left_on_pod.KINDS)
self.assertTrue(CLEANUP_PATH.fullmatch(f"{REST}/invoices/action/cancelInvoice"))
# steps.ts registers it with the same track() as create_invoice: the ledger and the fixture cancel it
steps = (FUSION / "steps.ts").read_text(encoding="utf-8")
body = steps.split("import_payables_invoice: async", 1)[1].split("import_receivables_transaction: async", 1)[0]
self.assertIn("ctx.track(testNumber(", body)
self.assertLess(body.index("ctx.track(testNumber("), body.index("ctx.rest.importBulkData(")) # registered before the upload
body_ar = steps.split("import_receivables_transaction: async", 1)[1].split("// General Ledger business actions", 1)[0]
self.assertLess(body_ar.index("ctx.docs.track('ar_transaction'"), body_ar.index("ctx.rest.importBulkData("))
if __name__ == "__main__":
unittest.main()