Files
MDHelper/tests/reliability_smoke.py
T
shen 8dae91c2ca fix: protect editor content and harden document exports
Protect pending edits on window close, keep save-as paths and drafts consistent,
copy relative image resources, reject oversized table imports without truncation,
and preserve independent preview scrolling during refresh.

Archive rendered MHTML resources with portable references and embedded local
fonts. Preserve existing outputs on export cancellation or failure. Convert
editor match positions and filter directory results in linear passes.

Include the previously completed editor image/table/history improvements,
undoable replacement, export snapshots, shared page settings, and cancellable
PDF/Word export workflow. Update documentation and version to 0.3.1.

Validation: 142 pytest cases passed; GUI smoke, improvements integration, and
offline MHTML/scroll reliability smoke checks passed.
2026-10-29 18:22:42 +08:00

127 lines
6.5 KiB
Python

"""Real WebEngine checks for independent preview scrolling and offline MHTML."""
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1")
os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox --log-level=3")
import json
import sys
import tempfile
import time
from email import message_from_bytes
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from PySide6.QtCore import QSettings, QUrl
from PySide6.QtGui import QImage, QColor
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineUrlRequestInterceptor
from PySide6.QtWidgets import QApplication, QMessageBox
from mdhelper import main_window
def main():
app = QApplication.instance() or QApplication([])
app.setQuitOnLastWindowClosed(False)
warnings = []
QMessageBox.warning = staticmethod(lambda *args: warnings.append(str(args[2])))
QMessageBox.question = staticmethod(lambda *args: QMessageBox.StandardButton.Discard)
def wait(condition, seconds=30):
end = time.monotonic() + seconds
while not condition() and time.monotonic() < end:
app.processEvents()
time.sleep(.01)
assert condition(), f"Timed out; warnings: {warnings}"
def js(page, script):
values = []
page.runJavaScript(script, 1, values.append)
wait(lambda: bool(values), 10)
return values[0]
with tempfile.TemporaryDirectory(prefix="mdhelper-reliability-") as temporary:
root = Path(temporary)
settings = QSettings(str(root / "settings.ini"), QSettings.Format.IniFormat)
main_window.QSettings = lambda *args: settings
os.environ["MDHELPER_HISTORY_DIR"] = str(root / "history")
picture = root / "picture.png"
image = QImage(35, 27, QImage.Format.Format_RGB32)
image.fill(QColor("red")); assert image.save(str(picture))
path = root / "note.md"
path.write_text("# Old disk", encoding="utf-8")
window = main_window.MainWindow(None, app_root=ROOT)
window.prepare_reader_before_show(); window.resize(1200, 800); window.show()
window.open_document(path); window.edit_current_markdown()
editor = window.tabs.currentWidget()
source = "# FRESH_EDITOR\n\n" + "\n\n".join("Paragraph " + str(i) + " content" * 30 for i in range(120))
source += '\n\n![offline image](picture.png)\n\n$$x^2 + y^2 = z^2$$\n\n```mermaid\ngraph LR\n A-->B\n```\n'
editor.replace_source_undoable(source)
page = editor.preview.page()
wait(lambda: not editor._preview_dirty)
wait(lambda: float(js(page, "document.body ? document.body.scrollHeight : 0") or 0) > 5000)
editor.sync_scroll_checkbox.setChecked(False)
js(page, "window.scrollTo(0, 2500)")
wait(lambda: float(js(page, "window.scrollY") or 0) > 2000)
before = js(page, "window.scrollY")
loaded = []
page.loadFinished.connect(loaded.append)
editor.replace_source_undoable(source + "\nlatest edit")
wait(lambda: bool(loaded))
wait(lambda: abs(float(js(page, "window.scrollY") or 0) - before) < 3)
after = js(page, "window.scrollY")
output = root / "portable.mhtml"
window.export_mhtml_to_path(output)
wait(lambda: not window._mhtml_exports)
assert not warnings and output.exists(), warnings
message = message_from_bytes(output.read_bytes())
types = [part.get_content_type() for part in message.walk()]
assert "image/png" in types and "text/css" in types, types
html = next(part.get_payload(decode=True) for part in message.walk() if part.get_content_type() == "text/html").decode("utf-8")
assert "FRESH_EDITOR" in html and "latest edit" in html and "Old disk" not in html
assert 'katex' in html and '<svg' in html
# Remove the original image and block all file/network resource fallback.
archived_urls = {QUrl(part.get("Content-Location")).toString()
for part in message.walk() if part.get("Content-Location")}
picture.unlink()
offline = root / "moved" / "archive.mhtml"
offline.parent.mkdir(); output.rename(offline)
class OfflineOnly(QWebEngineUrlRequestInterceptor):
def interceptRequest(self, info):
url = info.requestUrl()
is_archive = url.isLocalFile() and Path(url.toLocalFile()).resolve() == offline.resolve()
if url.scheme() in {"file", "http", "https"} and not is_archive:
info.block(True)
profile = QWebEngineProfile(window)
blocker = OfflineOnly(profile); profile.setUrlRequestInterceptor(blocker)
archive = QWebEnginePage(profile, window)
window._configure_web_settings(archive.settings())
loaded = []
archive.loadFinished.connect(loaded.append)
archive.load(QUrl.fromLocalFile(str(offline)))
wait(lambda: bool(loaded))
assert loaded[-1]
state = json.loads(js(archive, "JSON.stringify({width:[...document.images].find(i=>i.getAttribute('src'))?.naturalWidth,math:!!document.querySelector('.katex'),diagram:!!document.querySelector('svg'),font:document.fonts.status})"))
assert state == {"width": 35, "math": True, "diagram": True, "font": "loaded"}, (state, js(archive, "JSON.stringify([...document.images].map(i=>({src:i.src,width:i.naturalWidth,complete:i.complete,loading:i.loading})))"), archived_urls)
archive.destroyed.connect(profile.deleteLater); archive.deleteLater(); app.processEvents()
# Cancelling a new archive must leave an existing output untouched.
output.write_bytes(b"previous export")
window.export_mhtml_to_path(output)
next(iter(window._mhtml_exports)).cancel()
assert not window._mhtml_exports and output.read_bytes() == b"previous export"
assert not list(root.glob(".mdhelper-mhtml-*"))
window.export_mhtml_to_path(output)
wait(lambda: not window._mhtml_exports)
assert warnings and output.read_bytes() == b"previous export"
assert not list(root.glob(".mdhelper-mhtml-*"))
window.close(); app.processEvents()
print(json.dumps({"preview_before": before, "preview_after": after, "mhtml_parts": types,
"offline": state, "cancel_and_failure_preserve_output": True}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())