@davoodmehraban89 / Aram-1 / commits / 3d4bffa
Fork 0

test(finance): verify trial balance movement, zero totals, fail-closed input and source isolation

davoodmehraban89 committed Oct 31, 2026 at 06:51 UTC 3d4bffaf83c529e14addd5650de501edbac95e6a
1 file changed +246
backend/tests/test_trial_balance_diagnostic.py new
+246
@@ -0,0 +1,246 @@
1 +"""Synthetic-only trial-balance controls; no canonical finance workbook is opened."""
2 +from __future__ import annotations
3 +
4 +from io import BytesIO
5 +import json
6 +
7 +import pytest
8 +from openpyxl import Workbook, load_workbook
9 +
10 +from aram_backend.coverage_preview import CoverageError
11 +from aram_backend.pilot_workbook import SHEET_HEADERS
12 +from aram_backend.trial_balance_diagnostic import analyze_trial_balance
13 +
14 +
15 +ROWS = (
16 + ("CASH", "100", "40", "20", "120"),
17 + ("PAY", "-80", "10", "20", "-90"),
18 + ("EQT", "-20", "0", "10", "-30"),
19 +)
20 +
21 +
22 +def workbook() -> bytes:
23 + book = Workbook()
24 + book.remove(book.active)
25 + for name, headers in SHEET_HEADERS.items():
26 + book.create_sheet(name).append(list(headers))
27 +
28 + def add(name, **columns):
29 + book[name].append([columns.get(k) for k in SHEET_HEADERS[name]])
30 +
31 + add("Company", company_code="001", company_name="Synthetic only",
32 + fiscal_year=1404, status="Draft")
33 + for i, (code, opening, debit, credit, closing) in enumerate(ROWS, 2):
34 + add("Accounts", company_code="001", fiscal_year=1404,
35 + general_code=code, general_name="Synthetic GL",
36 + account_full_code=code, account_name="Synthetic " + code,
37 + opening=opening, debit=debit, credit=credit, closing=closing,
38 + source_row=i + 10, closing_delta="0", row_status="Draft")
39 + out = BytesIO()
40 + book.save(out)
41 + book.close()
42 + return out.getvalue()
43 +
44 +
45 +def edit(data, change):
46 + book = load_workbook(BytesIO(data))
47 + change(book)
48 + result = BytesIO()
49 + book.save(result)
50 + book.close()
51 + return result.getvalue()
52 +
53 +
54 +def audit(data=None, **scope):
55 + return analyze_trial_balance(
56 + workbook() if data is None else data,
57 + company_code=scope.get("company_code", "001"),
58 + fiscal_year=scope.get("fiscal_year", 1404),
59 + )
60 +
61 +
62 +def test_balanced_opening_movement_closing_without_financial_approval():
63 + result = audit()
64 + assert result.account_count == 3
65 + assert result.opening_debit_net_total == "0"
66 + assert result.debit_turnover_total == "50"
67 + assert result.credit_turnover_total == "50"
68 + assert result.closing_debit_net_total == "0"
69 + assert result.movement_difference == "0"
70 + assert result.opening_to_closing_difference == "0"
71 + assert result.balanced_for_analyst_review
72 + assert not result.findings
73 + assert [a.account_code for a in result.accounts] == ["CASH", "EQT", "PAY"]
74 + assert not result.source_ledger_completeness_verified
75 + assert not result.accounting_policies_verified
76 + assert not result.official_financial_statement
77 + assert not result.independently_reviewed
78 + assert not result.releasable
79 +
80 +
81 +def test_unbalanced_opening_and_closing_are_both_reported():
82 + def change(book):
83 + book["Accounts"]["Q2"] = "101"
84 + book["Accounts"]["T2"] = "121"
85 + result = audit(edit(workbook(), change))
86 + assert result.opening_debit_net_total == "1"
87 + assert result.closing_debit_net_total == "1"
88 + assert result.movement_difference == "0"
89 + assert not result.balanced_for_analyst_review
90 + assert result.findings == (
91 + "OPENING_DEBIT_NET_UNBALANCED", "CLOSING_DEBIT_NET_UNBALANCED"
92 + )
93 +
94 +
95 +def test_mismatched_debit_credit_turnover_is_reported():
96 + def change(book):
97 + book["Accounts"]["R2"] = "41"
98 + book["Accounts"]["T2"] = "121"
99 + result = audit(edit(workbook(), change))
100 + assert result.debit_turnover_total == "51"
101 + assert result.credit_turnover_total == "50"
102 + assert result.movement_difference == "1"
103 + assert result.closing_debit_net_total == "1"
104 + assert "DEBIT_CREDIT_TURNOVER_UNBALANCED" in result.findings
105 + assert "CLOSING_DEBIT_NET_UNBALANCED" in result.findings
106 +
107 +
108 +def test_inconsistent_account_rollforward_rejected_before_aggregation():
109 + source = edit(workbook(), lambda book: setattr(book["Accounts"]["T2"], "value", "999"))
110 + with pytest.raises(CoverageError) as err:
111 + audit(source)
112 + assert err.value.code == "TRIAL_BALANCE_WORKBOOK_INVALID"
113 +
114 +
115 +def test_negative_turnover_rejected_not_net_off():
116 + def change(book):
117 + book["Accounts"]["R2"] = "-1"
118 + book["Accounts"]["T2"] = "79"
119 + with pytest.raises(CoverageError) as err:
120 + audit(edit(workbook(), change))
121 + assert err.value.code == "TRIAL_BALANCE_NEGATIVE_TURNOVER"
122 +
123 +
124 +def test_all_zero_rows_are_valid_zero_math_without_claiming_completeness():
125 + def change(book):
126 + for row in book["Accounts"].iter_rows(min_row=2):
127 + for index in (16, 17, 18, 19):
128 + row[index].value = "0"
129 + result = audit(edit(workbook(), change))
130 + assert result.balanced_for_analyst_review
131 + assert result.opening_debit_net_total == "0"
132 + assert result.debit_turnover_total == "0"
133 + assert result.credit_turnover_total == "0"
134 + assert result.closing_debit_net_total == "0"
135 + assert not result.source_ledger_completeness_verified
136 +
137 +
138 +def test_scope_excludes_other_company_even_if_other_is_unbalanced():
139 + def change(book):
140 + headers = SHEET_HEADERS["Company"]
141 + book["Company"].append([{
142 + "company_code": "002", "company_name": "Other",
143 + "fiscal_year": 1404, "status": "Draft",
144 + }.get(key) for key in headers])
145 + book["Accounts"].append([{
146 + "company_code": "002", "fiscal_year": 1404,
147 + "general_code": "A", "general_name": "Other",
148 + "account_full_code": "A", "account_name": "Other",
149 + "opening": "999", "debit": "0", "credit": "0",
150 + "closing": "999", "source_row": 14,
151 + "closing_delta": "0", "row_status": "Draft",
152 + }.get(key) for key in SHEET_HEADERS["Accounts"]])
153 + data = edit(workbook(), change)
154 + assert audit(data).balanced_for_analyst_review
155 + other = audit(data, company_code="002")
156 + assert not other.balanced_for_analyst_review
157 + assert other.account_count == 1
158 +
159 +
160 +def test_duplicate_account_fails_closed():
161 + def change(book):
162 + sheet = book["Accounts"]
163 + sheet.append([c.value for c in sheet[2]])
164 + with pytest.raises(CoverageError):
165 + audit(edit(workbook(), change))
166 +
167 +
168 +def test_hidden_auxiliary_sheet_fails_closed():
169 + data = edit(workbook(), lambda book: setattr(book["Checks"], "sheet_state", "hidden"))
170 + with pytest.raises(CoverageError) as err:
171 + audit(data)
172 + assert err.value.code == "HIDDEN_INPUT"
173 +
174 +
175 +def test_hidden_account_row_fails_closed():
176 + data = edit(workbook(), lambda book: setattr(book["Accounts"].row_dimensions[2], "hidden", True))
177 + with pytest.raises(CoverageError) as err:
178 + audit(data)
179 + assert err.value.code == "HIDDEN_INPUT"
180 +
181 +
182 +def test_merged_accounts_fail_closed():
183 + data = edit(workbook(), lambda book: book["Accounts"].merge_cells("C2:D2"))
184 + with pytest.raises(CoverageError) as err:
185 + audit(data)
186 + assert err.value.code in {"MERGED_INPUT", "TRIAL_BALANCE_WORKBOOK_INVALID"}
187 +
188 +
189 +def test_wrong_header_rejected():
190 + data = edit(workbook(), lambda book: setattr(book["Accounts"]["A1"], "value", "other"))
191 + with pytest.raises(CoverageError) as err:
192 + audit(data)
193 + assert err.value.code == "TRIAL_BALANCE_WORKBOOK_INVALID"
194 +
195 +
196 +def test_scope_must_exist_no_fallback():
197 + with pytest.raises(CoverageError) as err:
198 + audit(company_code="999")
199 + assert err.value.code == "TRIAL_BALANCE_COMPANY_NOT_FOUND"
200 + with pytest.raises(CoverageError):
201 + audit(fiscal_year=1403)
202 +
203 +
204 +@pytest.mark.parametrize("bad_company,bad_year", [
205 + ("", 1404), ("001", 0), ("001", True),
206 + ("001", "1404"), (None, 1404),
207 +])
208 +def test_invalid_scope_fails_closed(bad_company, bad_year):
209 + with pytest.raises(CoverageError):
210 + audit(company_code=bad_company, fiscal_year=bad_year)
211 +
212 +
213 +def test_reject_unsafe_non_xlsx_inputs_and_oversize():
214 + with pytest.raises(CoverageError):
215 + audit(b"invalid")
216 + with pytest.raises(CoverageError):
217 + audit(b"x" * (20 * 1024 * 1024 + 1))
218 + with pytest.raises(CoverageError):
219 + audit("not-bytes")
220 +
221 +
222 +def test_scope_with_no_accounts_rejected():
223 + def change(book):
224 + book["Accounts"].delete_rows(2, 3)
225 + with pytest.raises(CoverageError) as err:
226 + audit(edit(workbook(), change))
227 + assert err.value.code == "TRIAL_BALANCE_NO_ACCOUNTS"
228 +
229 +
230 +def test_json_safe_values_and_input_bytes_unchanged():
231 + original = workbook()
232 + snapshot = bytes(original)
233 + result = json.loads(json.dumps(audit(original).to_dict()))
234 + assert original == snapshot
235 + assert result["releasable"] is False
236 + assert len(result["source_sha256"]) == 64
237 + assert result["accounts"][0]["opening"] == "100"
238 +
239 +
240 +def test_account_rows_include_source_lineage_and_net_movement():
241 + result = audit()
242 + cash = next(a for a in result.accounts if a.account_code == "CASH")
243 + assert cash.excel_row == 2
244 + assert cash.source_row == 12
245 + assert cash.debit_net_movement == "20"
246 + assert cash.closing == "120"