from pathlib import Path import re from urllib.parse import unquote, urlsplit import pytest from PySide6.QtCore import QSettings, QTimer from PySide6.QtWidgets import QApplication, QFileDialog, QMessageBox, QPushButton, QTableWidget from mdhelper import main_window from mdhelper.document_tree import DocumentEntry from mdhelper.editor_assets import relocate_images, store_image from mdhelper.markdown_editor import MarkdownEditorDialog from mdhelper.markdown_renderer import MarkdownRenderer from mdhelper.search import SearchIndex from mdhelper.table_editor import edit_table, format_table, parse_tsv @pytest.fixture def editing(tmp_path, monkeypatch, qt_application): settings = QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat) monkeypatch.setattr(main_window, "QSettings", lambda *args: settings) monkeypatch.setenv("MDHELPER_HISTORY_DIR", str(tmp_path / "history")) monkeypatch.setattr(QMessageBox, "warning", lambda *args: QMessageBox.StandardButton.Cancel) monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Cancel) path = tmp_path / "original.md" path.write_text("# Original", encoding="utf-8") window = main_window.MainWindow(None, app_root=Path(__file__).resolve().parents[1]) window.open_document(path) window.edit_current_markdown() editor = window.tabs.currentWidget() yield window, editor, path monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Discard) window.close() window.deleteLater() qt_application.processEvents() @pytest.mark.parametrize("choice", ["Save", "Discard", "Cancel"]) def test_close_protects_live_text_before_draft_timer(editing, monkeypatch, choice): window, editor, path = editing editor.replace_source_undoable("# Latest changes") assert editor.draft_save_timer.isActive() calls = [] def decide(*args): calls.append(args) assert window.editor_drafts[str(path)]["source"] == "# Latest changes" return getattr(QMessageBox.StandardButton, choice) monkeypatch.setattr(QMessageBox, "question", decide) assert window.close() == (choice != "Cancel") assert len(calls) == 1 assert path.read_text(encoding="utf-8") == ("# Latest changes" if choice == "Save" else "# Original") assert (str(path) in window.editor_drafts) == (choice == "Cancel") if choice != "Cancel": assert not editor.draft_save_timer.isActive() def test_failed_close_save_keeps_window_and_recoverable_draft(editing, monkeypatch): window, editor, path = editing editor.replace_source_undoable("not saved") monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save) from mdhelper.file_versions import VersionStore def fail(*args): raise OSError("simulated disk failure") monkeypatch.setattr(VersionStore, "save", fail) assert not window.close() assert editor.has_unsaved_changes() assert window.editor_drafts[str(path)]["source"] == "not saved" assert path.read_text() == "# Original" def test_close_saves_background_editors_without_changing_active_document(editing, monkeypatch, tmp_path): window, first, path = editing first.replace_source_undoable("first changes") second_path = tmp_path / "second.md" second_path.write_text("second original", encoding="utf-8") window.open_document(second_path, new_tab=True) window.edit_current_markdown() second = window.tabs.currentWidget() second.replace_source_undoable("second changes") monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Cancel) assert not window.close() assert set(window.editor_drafts) == {str(path), str(second_path)} assert window._save_editor_tab(first, path, first.source_text(), first.file_signature) assert window.current_file == second_path monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save) assert window.close() assert path.read_text() == "first changes" and second_path.read_text() == "second changes" assert not window.editor_drafts def test_close_does_not_recover_draft_that_user_already_undid(editing, monkeypatch): window, editor, path = editing editor.replace_source_undoable("undone edit") editor._auto_save_draft() editor.editor.undo() assert not editor.has_unsaved_changes() def no_prompt(*args): pytest.fail("clean editor must not prompt") monkeypatch.setattr(QMessageBox, "question", no_prompt) assert window.close() assert str(path) not in window.editor_drafts @pytest.mark.parametrize("operation", ["tab", "all", "project"]) def test_all_close_routes_use_save_discard_cancel(editing, monkeypatch, operation): window, editor, path = editing editor.replace_source_undoable("pending changes") actions = {"tab": lambda: window._close_tab(window.tabs.indexOf(editor)), "all": window._close_all_tabs, "project": window.close_project_folder} monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Cancel) actions[operation]() assert window.tabs.indexOf(editor) >= 0 and path.read_text() == "# Original" assert window.editor_drafts[str(path)]["source"] == "pending changes" monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save) actions[operation]() assert window.tabs.indexOf(editor) == -1 and path.read_text() == "pending changes" assert not window.editor_drafts def test_save_as_changes_draft_ownership_only_after_success(editing, monkeypatch, tmp_path): window, editor, original = editing target = tmp_path / "elsewhere" / "copy.md" editor.replace_source_undoable("save as") monkeypatch.setattr(QFileDialog, "getSaveFileName", lambda *args: (str(target), "Markdown")) save = window.save_markdown_source monkeypatch.setattr(window, "save_markdown_source", lambda *args, **kwargs: False) editor._choose_save_as_path() assert editor.path == original and editor.save_target_path == original assert window.current_file == original and editor.has_unsaved_changes() monkeypatch.setattr(window, "save_markdown_source", save) editor._choose_save_as_path() assert editor.path == target and not editor.has_unsaved_changes() editor.replace_source_undoable("new draft for B") editor._auto_save_draft() assert set(window.editor_drafts) == {str(target)} assert window.editor_drafts[str(target)]["source"] == "new draft for B" assert original.read_text() == "# Original" def test_save_recreates_externally_deleted_file(editing): window, editor, path = editing editor.replace_source_undoable("recovered") path.unlink() assert window._save_editor_tab(editor, path, editor.source_text(), editor.file_signature) assert path.read_text() == "recovered" def test_save_as_missing_image_keeps_original_context(editing, tmp_path): window, editor, original = editing source = "![missing](missing.png)" editor.replace_source_undoable(source) target = tmp_path / "elsewhere" / "copy.md" assert not window._save_editor_tab(editor, target, source, editor.file_signature) assert editor.path == original and editor.source_text() == source assert editor.has_unsaved_changes() and not target.exists() assert original.read_text() == "# Original" def test_export_snapshot_keeps_rendering_choices_after_ui_changes(editing, tmp_path): window, editor, path = editing window.theme = "dark" snapshot = window._export_snapshot() window.theme = "light" editor.replace_source_undoable("changed later") output = tmp_path / "snapshot.html" window.exports._export_web_to_path(output, "html", snapshot) html = output.read_text(encoding="utf-8") assert 'data-theme="dark"' in html and "changed later" not in html def test_save_as_copies_images_and_can_undo_rewritten_urls(editing, tmp_path): window, editor, original = editing source = store_image(original, b"image bytes") editor.replace_source_undoable(source) target = tmp_path / "elsewhere" / "copy.md" assert window._save_editor_tab(editor, target, source, editor.file_signature) saved = target.read_text(encoding="utf-8") url = re.search(r'\]\(([^)]+)\)', saved)[1] assert (target.parent / unquote(url)).read_bytes() == b"image bytes" assert editor.source_text() == saved and not editor.has_unsaved_changes() editor.editor.undo() assert editor.source_text() == source and editor.has_unsaved_changes() def test_relocate_parsed_images_preserves_examples_and_titles(tmp_path): original = tmp_path / "original.md" target = tmp_path / "new folder" / "copy.md" (tmp_path / "image (1).png").write_bytes(b"image") source = '''![inline]( "Title") ![ref][picture] [picture]: "Reference title" `![code](missing.png)` and \\![escaped](missing.png) ```md ![fenced](missing.png) ``` ![indented](missing.png) src="ignored.png" ''' moved = relocate_images(source, original, target) assert '`![code](missing.png)`' in moved and '\\![escaped](missing.png)' in moved assert '![fenced](missing.png)' in moved and ' ![indented](missing.png)' in moved assert '[picture]: "Reference title"' in moved assert '' in moved assert '"Title"' in moved and '"Reference title"' in moved tokens = MarkdownRenderer(tmp_path).markdown.parse(moved) images = [c for t in tokens for c in t.children or [] if c.type == "image"] assert len(images) == 2 for image in images: assert (target.parent / unquote(urlsplit(image.attrGet("src")).path)).read_bytes() == b"image" assert len(list((target.parent / "copy.assets").iterdir())) == 1 assert 'src="copy.assets/' in moved @pytest.mark.parametrize("content", ["\n".join(["x"] * 1001), "\t".join(["x"] * 101)]) def test_table_limit_is_explicit_and_keeps_existing_cells(content, monkeypatch): with pytest.raises(ValueError): parse_tsv(content) warnings, states = [], [] monkeypatch.setattr(QMessageBox, "warning", lambda *args: warnings.append(args[2])) def paste(): dialog = QApplication.activeModalWidget() QApplication.clipboard().setText(content) next(b for b in dialog.findChildren(QPushButton) if b.text() == "从 Excel 粘贴").click() table = dialog.findChild(QTableWidget) states.append((table.rowCount(), table.columnCount(), table.item(0, 0).text())) dialog.accept() QTimer.singleShot(0, paste) rows = [["original", "value"], ["a", "b"]] assert edit_table(None, rows) == format_table(rows, []) assert warnings and states == [(2, 2, "original")] def test_existing_large_table_is_not_opened_or_truncated(monkeypatch): warnings = [] monkeypatch.setattr(QMessageBox, "warning", lambda *args: warnings.append(args[2])) assert edit_table(None, [["x"] * 101]) is None assert warnings assert parse_tsv("\n") == [[""]] def test_find_conversion_visits_each_character_once(): class CountingText(str): examined = 0 def __getitem__(self, key): value = super().__getitem__(key) if isinstance(key, slice): self.examined += len(value) return value source = CountingText("😀xx中 " * 10000) spans = MarkdownEditorDialog._qt_match_spans(source, re.finditer("x", source)) assert spans[:4] == [(2, 3), (3, 4), (8, 9), (9, 10)] assert len(spans) == 20000 and source.examined <= len(source) def test_directory_filter_visits_each_entry_once_and_keeps_all_hits(tmp_path, monkeypatch): entries = [DocumentEntry(tmp_path / f"{i}.md", "no title match", f"{i}.md") for i in range(150)] index = SearchIndex(entries) calls = [] monkeypatch.setattr(index, "_body_for", lambda entry: calls.append(entry.path) or "needle") visible, results = index.filter("needle") assert len(visible) == 150 and len(results) == 80 assert len(calls) == len(set(calls)) == 150 calls.clear() assert index.filter("") == ({e.path for e in entries}, []) assert not calls # A direct entry lookup must not iterate the full index either. class NoIteration(list): def __iter__(self): raise AssertionError("quadratic lookup") index._records = NoIteration(index._records) assert index.matches_entry(entries[-1], "needle")