From ec8cfbd9a44a49fdfc4ccdeb12f1a34f3f9105ce Mon Sep 17 00:00:00 2001 From: MFlys Date: Thu, 3 Dec 2026 02:05:36 +0300 Subject: [PATCH] Protect applied unsaved scenario changes before closing --- .../workflows/offline-climate-regression.yml | 10 ++- examples/scenario/PORTABLE.md | 8 ++- examples/scenario/README.md | 8 ++- examples/scenario/editor.py | 26 ++++++-- examples/scenario/test_editor_gui.py | 61 +++++++++++++++++++ 5 files changed, 103 insertions(+), 10 deletions(-) diff --git a/.github/workflows/offline-climate-regression.yml b/.github/workflows/offline-climate-regression.yml index c3150fb..a79b463 100644 --- a/.github/workflows/offline-climate-regression.yml +++ b/.github/workflows/offline-climate-regression.yml @@ -8,6 +8,8 @@ on: - 'examples/scenario/test_editor_gui.py' - 'examples/scenario/PORTABLE.md' - 'scripts/export_scenario_preview.py' + - 'docs/downloads/fixturekit-scenario-preview-p1.zip' + - 'docs/downloads/fixturekit-scenario-preview-p1.zip.sha256' - '.gitattributes' - 'LICENSE' - 'examples/scenario/test_editor.py' @@ -26,6 +28,8 @@ on: - 'examples/scenario/test_editor_gui.py' - 'examples/scenario/PORTABLE.md' - 'scripts/export_scenario_preview.py' + - 'docs/downloads/fixturekit-scenario-preview-p1.zip' + - 'docs/downloads/fixturekit-scenario-preview-p1.zip.sha256' - '.gitattributes' - 'LICENSE' - 'examples/scenario/test_editor.py' @@ -60,12 +64,14 @@ jobs: - run: python -m examples.scenario.offline_regression --manifest examples/scenario/climate-custom.json - run: python -m examples.scenario.offline_regression --manifest examples/scenario/switch-custom.json - run: python -m examples.scenario.offline_regression --manifest examples/scenario/climate-timed.json - - name: Export standalone preview twice + - name: Preserve historical P1 archive + run: python -c "import hashlib; from pathlib import Path; p = Path('docs/downloads/fixturekit-scenario-preview-p1.zip'); expected = '5f5526174c47d7d9792a632841a9f1113e22f7dbbfc1bdeb3829b1c3d7bbca4e'; assert hashlib.sha256(p.read_bytes()).hexdigest() == expected; assert p.with_suffix('.zip.sha256').read_text().split() == [expected, p.name]" + - name: Export current source preview twice run: | python scripts/export_scenario_preview.py preview.zip python scripts/export_scenario_preview.py preview-repeat.zip python -c "from pathlib import Path; assert Path('preview.zip').read_bytes() == Path('preview-repeat.zip').read_bytes()" - python -c "import hashlib; from pathlib import Path; assert hashlib.sha256(Path('preview.zip').read_bytes()).hexdigest() == '5f5526174c47d7d9792a632841a9f1113e22f7dbbfc1bdeb3829b1c3d7bbca4e'" + python -c "import hashlib; from pathlib import Path; assert hashlib.sha256(Path('preview.zip').read_bytes()).hexdigest() == '03d7d7f470beab91077f8891bd8ce10f449f49e133da2287adfbba6a60c763b9'" python -m zipfile -e preview.zip preview-extracted - name: Validate extracted preview independently of checkout working-directory: preview-extracted diff --git a/examples/scenario/PORTABLE.md b/examples/scenario/PORTABLE.md index 5355d38..3724398 100644 --- a/examples/scenario/PORTABLE.md +++ b/examples/scenario/PORTABLE.md @@ -1,6 +1,10 @@ -# FixtureKit Scenario Preview P1 +# FixtureKit Scenario Preview (source candidate) Experimental standalone source bundle for synthetic climate and switch regression tests. +The historical P1 ZIP remains unchanged; its editor can close without warning +when applied steps have not been saved. Save before closing P1. The current +source candidate corrects that behavior. + Uses the published FixtureKit Core 0.1.0a10 unchanged. Python 3.12 is required; Tk is optional for the editor. No Home Assistant, live hardware or network transport. @@ -24,7 +28,7 @@ For a graphical desktop session with Tk: Choose a device, add steps with separate response and expected-state fields, then Run. Use Update to apply changes, or Reset fields to discard them. Save new never -overwrites existing files. New/Open ask before replacing a scenario. Use only +overwrites existing files. New/Open/Close ask before discarding unsaved scenario changes or unapplied fields. Use only reviewed synthetic manifests. Each scenario accepts 1–32 steps, optional integer virtual advances up to 120000 ms per step and 600000 ms total. No real clock changes, physical commands or arbitrary executable manifests. Exit 0 pass, 1 regression diff --git a/examples/scenario/README.md b/examples/scenario/README.md index 347a2b5..84cad5c 100644 --- a/examples/scenario/README.md +++ b/examples/scenario/README.md @@ -98,12 +98,16 @@ Run to display the counts-only regression result using the same in-memory validation and execution path as the CLI. Save only reviewed synthetic data. Apply edited fields using Add or Update before Run or Save. Reset fields restores the selected step; selecting another step asks before discarding -unapplied fields. New and Open ask before replacing a nonempty scenario. This editor executes +unapplied fields. In the current source editor, New, Open and Close ask before discarding +unsaved scenario changes or unapplied fields. A failed Save new does not +mark the scenario saved. The historical published P1 editor does not protect +applied unsaved steps when closing; save before closing P1. This editor executes only the fixed synthetic reader, not user Python code, live devices or the HA lab. It is source-only; the historical Studio P1/P2 archives are unchanged. Headless model tests do not establish cross-platform GUI usability. -For a minimal source bundle, see [Scenario Preview P1 instructions](PORTABLE.md). +For a minimal source bundle, see [source preview instructions](PORTABLE.md). +The historical [published P1 ZIP](https://flyzdev.github.io/fixturekit/downloads/fixturekit-scenario-preview-p1.zip) remains unchanged. From a trusted source checkout, `python scripts/export_scenario_preview.py preview.zip` creates a deterministic ZIP without overwriting an existing file. This is a candidate export, not an additional PyPI version or an installer. diff --git a/examples/scenario/editor.py b/examples/scenario/editor.py index d8a3c61..0793e57 100644 --- a/examples/scenario/editor.py +++ b/examples/scenario/editor.py @@ -81,6 +81,7 @@ def build_window(root, tk, ttk, dialogs, messages): root.geometry('850x610') root.minsize(650, 500) model = Editor() + saved_document = json.dumps(model.document(), sort_keys=True) frame = ttk.Frame(root, padding=16) frame.pack(fill='both', expand=True) frame.columnconfigure(0, weight=1) @@ -143,8 +144,14 @@ def show(result): def dirty(): return tuple(v.get() for v in variables) != clean_fields + def unsaved(): + # JSON preserves numeric representation (20 versus 20.0). + return json.dumps(model.document(), sort_keys=True) != saved_document + def mark_fields(*args): - draft_status.set('Unapplied fields: Add, Update or Reset fields before Run/Save.' if dirty() else 'Fields match the current step.') + fields_message = ('Unapplied fields: Add, Update or Reset fields before Run/Save.' + if dirty() else 'Fields match the current step.') + draft_status.set(fields_message + (' Unsaved scenario changes.' if unsaved() else '')) if dirty(): show({}) status.set('Result cleared. Apply or reset fields, then run again.') @@ -235,22 +242,33 @@ def move(delta): if index is not None: refresh(model.move(index, delta)) + def confirm_discard(title): + return not (dirty() or unsaved()) or messages.askyesno( + title, 'Discard unsaved scenario changes and unapplied fields?', parent=root) + def new_file(): - if (not model.steps and not dirty()) or messages.askyesno('New scenario', 'Discard current scenario and unapplied fields?', parent=root): + nonlocal saved_document + if confirm_discard('New scenario'): model.steps.clear() + saved_document = json.dumps(model.document(), sort_keys=True) refresh() def open_file(): + nonlocal saved_document path = dialogs.askopenfilename(parent=root, filetypes=[('JSON manifest', '*.json')]) - if path and ((not model.steps and not dirty()) or messages.askyesno('Replace scenario', 'Replace current scenario and unapplied fields?', parent=root)): + if path and confirm_discard('Replace scenario'): model.replace(read_json(Path(path))) + saved_document = json.dumps(model.document(), sort_keys=True) refresh(0) def save_file(): + nonlocal saved_document require_applied() path = dialogs.asksaveasfilename(parent=root, defaultextension='.json', filetypes=[('New JSON manifest', '*.json')]) if path: model.save(path) + saved_document = json.dumps(model.document(), sort_keys=True) + mark_fields() status.set('Saved new manifest. Existing files are never overwritten.') def run(): @@ -260,7 +278,7 @@ def run(): status.set('Regression result: ' + result['status']) def close_window(): - if not dirty() or messages.askyesno('Close editor', 'Discard unapplied fields?', parent=root): + if confirm_discard('Close editor'): root.destroy() root.protocol('WM_DELETE_WINDOW', close_window) diff --git a/examples/scenario/test_editor_gui.py b/examples/scenario/test_editor_gui.py index 4d0f0f5..623da99 100644 --- a/examples/scenario/test_editor_gui.py +++ b/examples/scenario/test_editor_gui.py @@ -72,3 +72,64 @@ def change(widget, value): self.assertEqual(entries[1].get(), '99') click('Run') self.assertIn('"status": "fail"', report.get('1.0', 'end')) + + def test_close_protects_applied_unsaved_steps_and_failed_save(self): + from pathlib import Path + import tempfile + import tkinter as tk + from tkinter import ttk + from unittest.mock import Mock, patch + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'scenario.json' + dialogs = Mock() + dialogs.asksaveasfilename.return_value = str(path) + dialogs.askopenfilename.return_value = str(path) + messages = Mock() + messages.askyesno.return_value = False + root = tk.Tk() + root.withdraw() + self.addCleanup(root.destroy) + model = build_window(root, tk, ttk, dialogs, messages) + root.update() + + def descendants(widget): + for child in widget.winfo_children(): + yield child + yield from descendants(child) + + buttons = {w.cget('text'): w for w in descendants(root) if isinstance(w, ttk.Button)} + def click(label): + buttons[label].invoke() + root.update() + + def attempt_close(expect_destroy): + messages.askyesno.reset_mock() + with patch.object(root, 'destroy') as destroy: + root.tk.call(root.protocol('WM_DELETE_WINDOW')) + self.assertEqual(destroy.called, expect_destroy) + self.assertEqual(messages.askyesno.called, not expect_destroy) + + attempt_close(True) + click('Add') + attempt_close(False) + self.assertEqual(len(model.steps), 1) + click('Save new…') + self.assertTrue(path.exists()) + attempt_close(True) + click('Add') + click('Save new…') # existing filename must not mark the document saved + messages.showerror.assert_called() + attempt_close(False) + click('New') + self.assertEqual(len(model.steps), 2) + click('Open…') + self.assertEqual(len(model.steps), 2) + messages.askyesno.return_value = True + click('Open…') + self.assertEqual(len(model.steps), 1) + messages.askyesno.return_value = False + attempt_close(True) + click('Remove') + self.assertEqual(len(model.steps), 0) + attempt_close(False)