fix: protect editor saves and clear failed restored tab state

This commit is contained in:
2026-11-05 21:38:35 +08:00
parent a3bef33988
commit 0e072eed3b
7 changed files with 192 additions and 22 deletions
+82
View File
@@ -0,0 +1,82 @@
"""Ordinary saves must protect the exact disk version reviewed by the editor."""
from pathlib import Path
import pytest
from PySide6.QtCore import QSettings
from PySide6.QtWidgets import QMessageBox
from mdhelper import file_versions as files, main_window
from mdhelper.document_session import DocumentStore
@pytest.mark.parametrize('boundary', ['store', 'flush', 'replace'])
def test_editor_save_conflict_preserves_external_file_and_unsaved_buffer(qt_application, tmp_path, monkeypatch, boundary):
settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat)
monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings)
monkeypatch.setenv('MDHELPER_HISTORY_DIR', str(tmp_path/'history'))
monkeypatch.setattr(QMessageBox, 'warning', lambda *args: QMessageBox.StandardButton.Cancel)
path = tmp_path/'note.md'; path.write_bytes(b'Original')
window = main_window.MainWindow(tmp_path)
try:
window.open_document(path); window.edit_current_markdown()
editor = window.tabs.currentWidget()
editor.replace_source_undoable('Editor contents')
external = b'External saved at commit'
injected = False
def change():
nonlocal injected
if not injected:
injected = True; path.write_bytes(external)
if boundary == 'store':
save = DocumentStore.save
def race(target, source, **kwargs):
change(); return save(target, source, **kwargs)
monkeypatch.setattr(DocumentStore, 'save', staticmethod(race))
elif boundary == 'flush':
fsync = files.os.fsync
def race(descriptor):
fsync(descriptor); change()
monkeypatch.setattr(files.os, 'fsync', race)
else:
replace = files._replace_with_backup
def race(temporary, target, backup):
if target == path: change()
replace(temporary, target, backup)
monkeypatch.setattr(files, '_replace_with_backup', race)
assert not window._save_editor_tab(editor, path, editor.source_text(), editor.file_signature)
assert injected and path.read_bytes() == external
assert editor.has_unsaved_changes() and editor.source_text() == 'Editor contents'
assert editor.session.saved_source == 'Original'
assert path not in window.internal_save_paths
if boundary == 'replace':
assert external in [p.read_bytes() for p in tmp_path.glob('.*.conflict-*.bak')]
finally:
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Discard)
window.close()
def test_new_editor_save_cannot_overwrite_concurrent_creation(tmp_path, monkeypatch):
path = tmp_path/'new.md'
rename = files.os.rename
def race(source, target):
if Path(target) == path: path.write_bytes(b'External creation')
rename(source, target)
monkeypatch.setattr(files.os, 'rename', race)
with pytest.raises(FileExistsError): files.VersionStore(tmp_path/'history').save(path, 'Editor')
assert path.read_bytes() == b'External creation'
def test_save_as_checks_destination_snapshot_before_image_relocation(qt_application, tmp_path, monkeypatch):
settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat)
monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings)
monkeypatch.setattr(QMessageBox, 'warning', lambda *args: QMessageBox.StandardButton.Cancel)
source = tmp_path/'original.md'; source.write_text('Original')
target = tmp_path/'other'/'new.md'; target.parent.mkdir()
def relocate(text, original, destination):
destination.write_text('External creation'); return text
monkeypatch.setattr(DocumentStore, 'prepare_save', staticmethod(relocate))
window = main_window.MainWindow(tmp_path)
try:
window.open_document(source); window.edit_current_markdown()
editor = window.tabs.currentWidget()
assert not window._save_editor_tab(editor, target, 'Editor', editor.file_signature)
assert target.read_text() == 'External creation' and editor.session.path == source
finally: window.close()
+3 -6
View File
@@ -76,12 +76,9 @@ def test_failed_atomic_save_keeps_original_and_history(tmp_path, monkeypatch):
from mdhelper import file_versions
path = tmp_path / "note.md"; path.write_bytes(b"original\r\n")
store = VersionStore(tmp_path / "history")
replace = file_versions.os.replace
def failure(source, destination):
if Path(destination) == path:
raise OSError("simulated sharing violation")
replace(source, destination)
monkeypatch.setattr(file_versions.os, "replace", failure)
def failure(source, destination, backup):
raise OSError("simulated sharing violation")
monkeypatch.setattr(file_versions, "_replace_with_backup", failure)
with pytest.raises(OSError):
store.save(path, "changed")
assert path.read_bytes() == b"original\r\n"
+1 -1
View File
@@ -59,7 +59,7 @@ def test_failed_close_save_keeps_window_and_recoverable_draft(editing, monkeypat
editor.replace_source_undoable("not saved")
monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save)
from mdhelper.file_versions import VersionStore
def fail(*args):
def fail(*args, **kwargs):
raise OSError("simulated disk failure")
monkeypatch.setattr(VersionStore, "save", fail)
assert not window.close()
+53
View File
@@ -0,0 +1,53 @@
"""A failed lazy tab must not expose another document to editing/export actions."""
import pytest
from PySide6.QtCore import QSettings
from PySide6.QtWidgets import QMessageBox
from mdhelper import main_window
from mdhelper.workspace_state import WorkspaceStore, TabState
from mdhelper.tab_controller import document_path
from test_workspace_state import wait_until
@pytest.mark.parametrize('failure', ['deleted', 'invalid_utf8', 'unreadable'])
def test_failed_lazy_tab_clears_current_document_and_can_retry(qt_application, tmp_path, monkeypatch, failure):
settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat)
monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings)
monkeypatch.setattr(QMessageBox, 'warning', lambda *args: QMessageBox.StandardButton.Cancel)
monkeypatch.setattr(QMessageBox, 'critical', lambda *args: QMessageBox.StandardButton.Ok)
monkeypatch.setattr(QMessageBox, 'information', lambda *args: QMessageBox.StandardButton.Ok)
first, second = tmp_path/'first.md', tmp_path/'second.md'
first.write_text('# First'); second.write_text('# Second')
WorkspaceStore(settings).save(tmp_path, [TabState(str(first)), TabState(str(second))], 0)
window = main_window.MainWindow(tmp_path, defer_startup=True)
try:
window.prepare_reader_before_show(); window._restore_workspace()
host = window.tabs.widget(1)
render = window._render_document_file
if failure == 'deleted': second.unlink()
elif failure == 'invalid_utf8': second.write_bytes(b'\xff')
else:
def fail(path):
if path == second: raise PermissionError('Sharing violation')
return render(path)
monkeypatch.setattr(window, '_render_document_file', fail)
window.tabs.setCurrentIndex(1)
assert window.current_file is None and window._export_snapshot() is None
assert not window.edit_current_action.isEnabled() and window.toc_tree.topLevelItemCount() == 0
assert host.workspace_state.path == str(second)
assert host.stack.currentWidget() is host.welcome_view
assert window.windowTitle() == 'second.md - MDHelper'
window.edit_current_markdown()
assert window.tabs.currentWidget() is host and window.tabs.count() == 2
window.tabs.setCurrentIndex(0)
assert window.current_file == first
second.write_text('# Second\n\nRecovered text', encoding='utf8')
monkeypatch.setattr(window, '_render_document_file', render)
window.tabs.setCurrentIndex(1)
wait_until(qt_application, lambda: host.stack.currentWidget() is host.reader_view)
text=[]; host.reader_view.page().toPlainText(text.append)
wait_until(qt_application, lambda: bool(text))
assert 'Recovered text' in text[0]
assert window.current_file == second and window.edit_current_action.isEnabled()
window.edit_current_markdown()
assert document_path(window.tabs.currentWidget()) == second
finally: window.close()