codex/aram-mapping-source-parser-20261101
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 351 lines 13.3 KB
Raw
1 """Synthetic-only safety and lifecycle checks for the native Windows pilot."""
2 from __future__ import annotations
3
4 from hashlib import sha256
5 import json
6 import sys
7 import time
8
9 import pytest
10
11 from aram_backend.desktop_five_statement_core import (
12 DesktopFiveInputError, DesktopFiveStatementController,
13 MAX_INPUT_BYTES, MAX_CASH_MANIFEST_BYTES,
14 )
15 from aram_backend.desktop_five_statement import ACTIONS, FiveStatementWindow, main, self_test
16 from test_five_statement_pipeline_integration import (
17 cash_transactions, pipeline_manifest, source_workbook,
18 )
19
20
21 def fixtures(tmp_path, *, manifest=None):
22 xlsx = tmp_path / "synthetic.xlsx"
23 jsonfile = tmp_path / "synthetic.json"
24 xlsx.write_bytes(source_workbook())
25 jsonfile.write_text(
26 json.dumps(pipeline_manifest() if manifest is None else manifest),
27 encoding="utf-8",
28 )
29 return xlsx, jsonfile
30
31
32 def controller_with_files(paths):
33 ctl = DesktopFiveStatementController()
34 ctl.select_workbook(str(paths[0]))
35 ctl.select_manifest(str(paths[1]))
36 return ctl
37
38
39 def test_full_five_statement_preview_is_local_and_never_writes_source_files(tmp_path):
40 paths = fixtures(tmp_path)
41 workbook_digest = sha256(paths[0].read_bytes()).hexdigest()
42 manifest_digest = sha256(paths[1].read_bytes()).hexdigest()
43 ctl = controller_with_files(paths)
44 assert ctl.can_run
45 assert ctl.state == "SELECTED"
46 assert ctl.result is None
47 result = ctl.validate()
48 assert result.eligible_for_analyst_review
49 assert result.reconciliation.eligible_for_analyst_review
50 assert not result.releasable and not result.official_financial_statement
51 assert ctl.result is result
52 assert ctl.state == "ELIGIBLE"
53 assert sha256(paths[0].read_bytes()).hexdigest() == workbook_digest
54 assert sha256(paths[1].read_bytes()).hexdigest() == manifest_digest
55 assert {p.name for p in tmp_path.iterdir()} == {
56 "synthetic.xlsx", "synthetic.json",
57 }
58
59
60 def test_missing_cash_transaction_blocks_without_creating_approved_state(tmp_path):
61 manifest = pipeline_manifest(transactions=cash_transactions()[:-1])
62 ctl = controller_with_files(fixtures(tmp_path, manifest=manifest))
63 result = ctl.validate()
64 assert not result.eligible_for_analyst_review
65 assert ctl.state == "BLOCKED"
66 assert "CASH_FLOW_CANDIDATE_BLOCKED" in result.findings
67
68
69 def test_invalid_manifest_clears_previous_eligible_result(tmp_path):
70 paths = fixtures(tmp_path)
71 ctl = controller_with_files(paths)
72 assert ctl.validate().eligible_for_analyst_review
73 paths[1].write_text("not-json", encoding="utf-8")
74 with pytest.raises(DesktopFiveInputError):
75 ctl.validate()
76 assert ctl.state == "INPUT_ERROR"
77 assert ctl.result is None
78 assert ctl.error_code is not None
79
80
81 def test_changing_selected_file_invalidates_previous_result(tmp_path):
82 paths = fixtures(tmp_path)
83 ctl = controller_with_files(paths)
84 assert ctl.validate().eligible_for_analyst_review
85 old_generation = ctl.generation
86 ctl.select_manifest(str(paths[1]))
87 assert ctl.generation > old_generation
88 assert ctl.result is None
89 assert ctl.state == "SELECTED"
90 ctl.select_workbook(str(paths[0]))
91 assert ctl.result is None
92
93
94 def test_invalid_switch_does_not_leave_old_financial_preview_visible(tmp_path):
95 paths = fixtures(tmp_path)
96 ctl = controller_with_files(paths)
97 ctl.validate()
98 with pytest.raises(DesktopFiveInputError):
99 ctl.select_manifest(str(tmp_path / "missing.json"))
100 assert ctl.manifest_path is None
101 assert not ctl.can_run
102 assert ctl.result is None
103 assert ctl.state == "EMPTY"
104
105
106 def test_removed_source_before_execution_refuses_stale_previously_eligible_file(tmp_path):
107 paths = fixtures(tmp_path)
108 ctl = controller_with_files(paths)
109 ctl.validate()
110 paths[0].unlink()
111 with pytest.raises(DesktopFiveInputError):
112 ctl.validate()
113 assert ctl.result is None
114 assert ctl.state == "INPUT_ERROR"
115
116
117 @pytest.mark.parametrize("selection, name", [
118 ("workbook", "invalid.xls"),
119 ("workbook", "fake.xlsx.exe"),
120 ("manifest", "invalid.txt"),
121 ("manifest", "fake.json.bak"),
122 ])
123 def test_selection_requires_expected_extension(tmp_path, selection, name):
124 target = tmp_path / name
125 target.write_bytes(b"bad")
126 ctl = DesktopFiveStatementController()
127 with pytest.raises(DesktopFiveInputError) as exc:
128 getattr(ctl, "select_" + selection)(str(target))
129 assert exc.value.args[0] == "FILE_EXTENSION_INVALID"
130 assert ctl.result is None
131
132
133 @pytest.mark.parametrize("selection, extension", [
134 ("workbook", ".xlsx"), ("manifest", ".json"),
135 ])
136 def test_selection_rejects_symlinks_and_directories(tmp_path, selection, extension):
137 target = tmp_path / ("target" + extension)
138 target.write_bytes(b"test")
139 link = tmp_path / ("alias" + extension)
140 try:
141 link.symlink_to(target)
142 except (OSError, NotImplementedError):
143 pytest.skip("No symlink support on test runner")
144 ctl = DesktopFiveStatementController()
145 with pytest.raises(DesktopFiveInputError):
146 getattr(ctl, "select_" + selection)(str(link))
147 folder = tmp_path / ("folder" + extension)
148 folder.mkdir()
149 with pytest.raises(DesktopFiveInputError):
150 getattr(ctl, "select_" + selection)(str(folder))
151
152
153 @pytest.mark.parametrize("selection,extension,limit", [
154 ("workbook", ".xlsx", MAX_INPUT_BYTES),
155 ("manifest", ".json", MAX_CASH_MANIFEST_BYTES),
156 ])
157 def test_selection_blocks_empty_and_oversized_files(tmp_path, selection, extension, limit):
158 target = tmp_path / ("oversize" + extension)
159 ctl = DesktopFiveStatementController()
160 target.write_bytes(b"")
161 with pytest.raises(DesktopFiveInputError):
162 getattr(ctl, "select_" + selection)(str(target))
163 with target.open("wb") as stream:
164 stream.truncate(limit + 1)
165 with pytest.raises(DesktopFiveInputError):
166 getattr(ctl, "select_" + selection)(str(target))
167
168
169 def test_controller_clear_discards_both_files_and_all_prior_results(tmp_path):
170 ctl = controller_with_files(fixtures(tmp_path))
171 ctl.validate()
172 ctl.clear()
173 assert ctl.state == "EMPTY"
174 assert ctl.workbook_path is None and ctl.manifest_path is None
175 assert ctl.result is None and ctl.error_code is None
176 assert not ctl.can_run
177 with pytest.raises(DesktopFiveInputError):
178 ctl.validate()
179
180
181 def test_headless_executable_smoke_and_all_enabled_actions_have_methods():
182 assert self_test() == 0
183 assert main(["--self-test"]) == 0
184 assert main(["--unexpected"]) == 2
185 assert set(ACTIONS) == {
186 "file.workbook", "file.manifest", "file.run",
187 "file.clear", "file.exit", "help.about",
188 }
189 for key, method in ACTIONS.items():
190 assert callable(getattr(FiveStatementWindow, method)), key
191
192
193 @pytest.mark.skipif(sys.platform != "win32", reason="Native Tk smoke requires Windows runner")
194 def test_native_window_shows_real_successful_five_statement_result(tmp_path):
195 paths = fixtures(tmp_path)
196 file_names = {"workbook": str(paths[0]), "manifest": str(paths[1])}
197 window = FiveStatementWindow(picker=lambda kind: file_names[kind])
198 try:
199 window.withdraw()
200 window.update_idletasks()
201 assert str(window.run_button.cget("state")) == "disabled"
202 window.workbook_button.invoke()
203 window.manifest_button.invoke()
204 assert str(window.run_button.cget("state")) == "normal"
205 window.run_button.invoke()
206 for _ in range(500):
207 window.update()
208 if not window._busy:
209 break
210 time.sleep(0.02)
211 assert not window._busy
212 assert window.controller.state == "ELIGIBLE"
213 assert window.controller.result is not None
214 assert window.controller.result.eligible_for_analyst_review
215 rows = window.outcome_tree.get_children()
216 assert len(rows) == 5
217 assert all(
218 window.outcome_tree.item(row, "values")[1] == "قابل بررسی"
219 for row in rows
220 )
221 amounts = [
222 window.figures_tree.item(row, "values")
223 for row in window.figures_tree.get_children()
224 ]
225 assert len(amounts) == 28
226 assert ("ترازنامه", "دارایی‌ها", "100", "پیش‌نویس قابل بررسی؛ غیررسمی") in amounts
227 assert ("سود و زیان", "سود خالص", "20", "پیش‌نویس قابل بررسی؛ غیررسمی") in amounts
228 expected_details = (
229 len(window.controller.result.balance_sheet.lines)
230 + len(window.controller.result.income_statement.lines)
231 + len(window.controller.result.equity_changes.note_movements)
232 + len(window.controller.result.equity_changes.account_movements)
233 + len(window.controller.result.cash_flow.cash_flow_lines)
234 + len(window.controller.result.cash_flow.account_reconciliations)
235 + len(window.controller.result.trial_balance.accounts)
236 + len(window.controller.result.mapping_coverage.mappings)
237 )
238 assert len(window._detail_rows) == expected_details
239 assert any(row.item == "Revenue" for row in window._detail_rows)
240 window.detail_filter_var.set("سود و زیان")
241 window.detail_search_var.set("یادداشت R01")
242 window._apply_detail_filter()
243 assert window._filtering
244 assert str(window.detail_search_button.cget("state")) == "disabled"
245 window.update_idletasks()
246 for _ in range(500):
247 window.update()
248 if not window._filtering:
249 break
250 time.sleep(0.01)
251 assert not window._filtering
252 filtered = [
253 window.detail_tree.item(row, "values")
254 for row in window.detail_tree.get_children()
255 ]
256 assert len(filtered) == 2
257 assert {row[1] for row in filtered} == {"Revenue", "حساب REV / Revenue"}
258 window.clear_button.invoke()
259 assert not window.outcome_tree.get_children()
260 assert not window.figures_tree.get_children()
261 assert not window.detail_tree.get_children()
262 assert not window._detail_rows
263 assert window.controller.result is None
264 assert str(window.run_button.cget("state")) == "disabled"
265 finally:
266 if window.winfo_exists():
267 window.destroy()
268
269
270 @pytest.mark.skipif(sys.platform != "win32", reason="Native Tk requires Windows runner")
271 def test_new_detail_query_supersedes_inflight_search_and_ignores_stale_reply(
272 tmp_path, monkeypatch,
273 ):
274 """The initial all-rows filter cannot overwrite a newer exact note query."""
275 import threading
276 import aram_backend.desktop_five_statement as desktop_module
277
278 release_old = threading.Event()
279 started_old = threading.Event()
280 real_filter = desktop_module.filter_preview_details
281
282 def delayed_filter(rows, *, statement, query):
283 if statement == "همه" and query == "":
284 started_old.set()
285 if not release_old.wait(30):
286 raise RuntimeError("Synthetic old filter was not released")
287 return real_filter(rows, statement=statement, query=query)
288
289 monkeypatch.setattr(desktop_module, "filter_preview_details", delayed_filter)
290 paths = fixtures(tmp_path)
291 file_names = {"workbook": str(paths[0]), "manifest": str(paths[1])}
292 try:
293 window = FiveStatementWindow(picker=lambda kind: file_names[kind])
294 except Exception as exc:
295 # Hosted Windows Python images can lack Tcl/Tk runtime files.
296 # Skip only missing runtime, never application behavior errors.
297 import tkinter
298 if isinstance(exc, tkinter.TclError) and (
299 "usable tk.tcl" in str(exc)
300 or "no display name" in str(exc)
301 ):
302 pytest.skip(f"Native Tk runtime unavailable on runner: {exc}")
303 raise
304 try:
305 window.withdraw()
306 window.workbook_button.invoke()
307 window.manifest_button.invoke()
308 window.run_button.invoke()
309 for _ in range(2000):
310 window.update()
311 if not window._busy and started_old.is_set():
312 break
313 time.sleep(0.01)
314 assert not window._busy
315 assert started_old.is_set()
316 assert window._filtering
317 window.detail_filter_var.set("سود و زیان")
318 window.detail_search_var.set("یادداشت R01")
319 window._apply_detail_filter()
320 assert window._filtering
321 for _ in range(500):
322 window.update()
323 if not window._filtering:
324 break
325 time.sleep(0.01)
326 assert not window._filtering
327 rows = window.detail_tree.get_children()
328 assert len(rows) == 2
329 assert {window.detail_tree.item(row, "values")[1] for row in rows} == {
330 "Revenue", "حساب REV / Revenue",
331 }
332
333 release_old.set()
334 for _ in range(30):
335 window.update()
336 time.sleep(0.01)
337 # A superseded full-dataset search must not retain private rows
338 # in the pending event queue after the newer search finishes.
339 assert window._filter_events.empty()
340 rows = window.detail_tree.get_children()
341 assert len(rows) == 2
342 assert {window.detail_tree.item(row, "values")[1] for row in rows} == {
343 "Revenue", "حساب REV / Revenue",
344 }
345 window.clear_button.invoke()
346 assert not window.detail_tree.get_children()
347 assert not window._detail_rows
348 finally:
349 release_old.set()
350 if window.winfo_exists():
351 window.destroy()