"""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()