"""Error report tests with real Tk widgets; no DB access or warehouse writes.""" import ast import tempfile import tkinter as tk import unittest from concurrent.futures import Future from pathlib import Path from unittest.mock import Mock, patch import error_dialog from error_dialog import ErrorDialog, build_error_report, showerror class ReportTests(unittest.TestCase): def test_chained_error_and_sql_are_complete(self): from sqlalchemy.exc import StatementError params = {"items": list(range(2000))} try: try: raise ValueError("original cause") except ValueError as cause: raise StatementError("query failed", "SELECT " + "x" * 20000, params, cause) from cause except StatementError as exc: report = build_error_report("Inventory", "User message", exc) self.assertIn("original cause", report) self.assertIn("Traceback", report) self.assertIn("SELECT " + "x" * 20000, report) self.assertIn(repr(params), report) self.assertIn("User message", report) def test_group_has_every_exception_not_default_first_fifteen(self): exc = ExceptionGroup("errors", [ValueError(f"failure-{i}") for i in range(30)]) report = build_error_report("Barcode", "Recovery", exc) for i in range(30): self.assertIn(f"failure-{i}", report) def test_all_live_modules_use_shared_errors(self): root = Path(__file__).resolve().parents[1] for path in root.glob("*.py"): if path.name == "error_dialog.py": continue tree = ast.parse(path.read_text(encoding="utf-8-sig")) for node in ast.walk(tree): if isinstance(node, ast.ImportFrom) and node.module in ("tkinter", "tkinter.messagebox"): self.assertFalse(any(n.name in ("messagebox", "showerror") for n in node.names), path.name) if isinstance(node, ast.Import): self.assertFalse(any(n.name == "tkinter.messagebox" for n in node.names), path.name) def test_confirmations_and_information_remain_native(self): self.assertIs(error_dialog.askyesno, error_dialog.native_messagebox.askyesno) self.assertIs(error_dialog.showinfo, error_dialog.native_messagebox.showinfo) self.assertIs(error_dialog.showwarning, error_dialog.native_messagebox.showwarning) def test_translations_exist(self): from locale_text import load_locale_catalog for lang in ("IT", "ENG"): for key in ("copy", "save", "close", "copy_failed", "save_failed", "saved"): self.assertTrue(load_locale_catalog()[lang]["errors." + key]) class DialogTests(unittest.TestCase): def setUp(self): self.root = tk.Tk() self.root.withdraw() self.report = "Accento: \u00e8\n" + ("SQL " + "x" * 2000 + "\n") * 500 + "END OF REPORT" self.dialog = ErrorDialog(self.root, "Synthetic error", self.report) self.root.update() def tearDown(self): self.root.destroy() def test_full_text_read_only_and_both_scrollbars(self): box = self.dialog.textbox self.assertEqual(box.get("1.0", "end-1c"), self.report) self.assertEqual(box.cget("state"), "disabled") box.insert("end", "forbidden edit") self.assertEqual(box.get("1.0", "end-1c"), self.report) box.yview_moveto(1) box.xview_moveto(1) self.root.update() self.assertAlmostEqual(box.yview()[1], 1) self.assertGreater(box.xview()[0], 0) self.assertTrue(self.dialog.vertical.winfo_ismapped()) self.assertTrue(self.dialog.horizontal.winfo_ismapped()) def test_copy_all_and_selection(self): self.dialog.copy_all() self.assertEqual(self.root.clipboard_get(), self.report) self.dialog.textbox.tag_add("sel", "1.0", "1.7") self.dialog.copy_selection() self.assertEqual(self.root.clipboard_get(), "Accento") self.dialog.select_all() self.dialog.copy_selection() self.assertEqual(self.root.clipboard_get(), self.report) def test_save_utf8_exactly_matches_display_and_clipboard(self): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "error.txt" with patch("error_dialog.filedialog.asksaveasfilename", return_value=str(path)): self.dialog.save_report() self.assertEqual(path.read_text(encoding="utf-8"), self.report) def test_save_cancel_does_nothing(self): with patch("error_dialog.filedialog.asksaveasfilename", return_value=""), \ patch("error_dialog.Path.write_text") as write: self.dialog.save_report() write.assert_not_called() def test_save_error_keeps_report_open(self): with patch("error_dialog.filedialog.asksaveasfilename", return_value="report.txt"), \ patch("error_dialog.Path.write_text", side_effect=PermissionError("denied")): self.dialog.save_report() self.assertIn("denied", self.dialog.status.get()) self.assertTrue(self.dialog.winfo_exists()) self.assertEqual(self.dialog.textbox.get("1.0", "end-1c"), self.report) def test_small_terminal_keeps_buttons_inside_window(self): self.dialog.destroy() with patch.object(ErrorDialog, "winfo_screenwidth", return_value=240), \ patch.object(ErrorDialog, "winfo_screenheight", return_value=320): self.dialog = ErrorDialog(self.root, "Small", self.report) self.root.update() for button in self.dialog.buttons: self.assertLessEqual(button.winfo_rooty() + button.winfo_height(), self.dialog.winfo_rooty() + self.dialog.winfo_height()) self.assertGreater(self.dialog.textbox.winfo_height(), 10) def test_modal_returns_ok_and_restores_existing_grab(self): self.dialog.grab_set() captured = [] def close_report(): for child in self.dialog.winfo_children(): if isinstance(child, ErrorDialog): captured.append(child.report) child.destroy() self.root.after(100, close_report) result = showerror("Test", "message", parent=self.dialog, exception=ValueError("async details")) self.assertEqual(result, "ok") self.assertIn("async details", captured[0]) self.assertEqual(self.root.grab_current(), self.dialog) class BarcodeErrorTests(unittest.TestCase): def test_recovery_preserves_original_exception(self): from barcode_client import BarcodeClientApp app = Mock() app._pending = None original = RuntimeError("original SQL failure") BarcodeClientApp._poll_recovery_future(app, original) app._show_transaction_error.assert_called_once_with(original) def test_failed_recovery_preserves_both_exceptions(self): from barcode_client import BarcodeClientApp app = Mock() app._pending = Future() app._pending.set_exception(ValueError("recovery failed")) original = RuntimeError("SQL failure") with patch("barcode_client.log_exception"): BarcodeClientApp._poll_recovery_future(app, original) group = app._show_transaction_error.call_args.args[0] self.assertIs(group.exceptions[0], original) self.assertEqual(str(group.exceptions[1]), "recovery failed") if __name__ == "__main__": unittest.main()