Files
MDHelper/tests/test_export_improvements.py
T

129 lines
6.7 KiB
Python

from __future__ import annotations
import json
import threading
import zipfile
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
import pytest
from lxml import etree
from PySide6.QtCore import QSettings
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.export_check import check_export
from mdhelper.export_jobs import ExportCancelled
from mdhelper.export_settings import PageSettings, decorate_pdf
from mdhelper.export_workflow import ExportController, ExportContext, ExportSnapshot
from mdhelper.markdown_editor import MarkdownEditorDialog
from mdhelper.markdown_renderer import MarkdownRenderer
from mdhelper.pdf_export import build_pdf_page_layout, build_pdf_export_html
def test_export_check_ignores_code_and_detects_actual_missing_resources(tmp_path):
source = '```md\n![example](ignore.png)\n```\n\n![photo](missing.png)\n\n- a\n - b\n\n$x$\n'
issues = check_export(source, tmp_path / "x.md", "builtin", "p { background: red; font-size: 12pt; }")
messages = "\n".join(i.message for i in issues)
assert "ignore.png" not in messages and "missing.png" in messages
assert "多级列表" in messages and "公式" in messages and "background" in messages
assert "font-size" not in messages
assert any(i.line == 5 and "missing.png" in i.message for i in issues)
@pytest.mark.parametrize("engine", ["pandoc", "python-docx", "builtin"])
def test_word_page_settings_and_inline_styles(tmp_path, engine):
settings = PageSettings(paper="A3", landscape=True, top=22, left=18, include_toc=True, toc_depth=4,
header="项目报告", footer="内部资料", page_numbers=True)
path = tmp_path / (engine + ".docx")
export_markdown_to_docx("# 新内容\n\n正文 **中文加粗。**后续\n", path, engine=engine, page_settings=settings,
style_rules={"paragraph": {"font_size": 14, "font_size_unit": "pt"}})
with zipfile.ZipFile(path) as package:
doc = etree.fromstring(package.read("word/document.xml"))
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
assert doc.xpath("//w:pgSz/@w:orient", namespaces=ns) == ["landscape"]
assert int(doc.xpath("//w:pgSz/@w:w", namespaces=ns)[0]) > int(doc.xpath("//w:pgSz/@w:h", namespaces=ns)[0])
assert any('1-4' in value for value in doc.xpath("//w:fldSimple/@w:instr", namespaces=ns))
assert doc.xpath("//w:r[w:rPr/w:b]/w:t/text()", namespaces=ns)
assert "项目报告" in package.read("word/header1.xml").decode()
footer = package.read("word/footer1.xml").decode()
assert "NUMPAGES" in footer and "内部资料" in footer
def test_cancelled_word_export_preserves_old_output(tmp_path):
path = tmp_path / "old.docx"; path.write_bytes(b"previous output")
cancel = threading.Event()
def stage(_):
cancel.set()
with pytest.raises(ExportCancelled):
export_markdown_to_docx("new", path, engine="builtin", cancel=cancel, progress=stage)
assert path.read_bytes() == b"previous output"
def test_pdf_layout_and_toc_switch():
from mdhelper.markdown_utils import Heading
settings = PageSettings(paper="Letter", landscape=True, include_toc=False)
layout = build_pdf_page_layout(settings)
assert layout.fullRect(layout.Unit.Millimeter).width() > layout.fullRect(layout.Unit.Millimeter).height()
output = build_pdf_export_html('<html data-theme="dark"><style></style><body><h1 id="a">a</h1></body></html>', [Heading(1, "a", "a")],
include_page_markers=False, settings=settings)
assert '<section class="pdf-toc' not in output
assert '<div class="pdf-body-start-marker">' not in output
assert 'data-theme="light"' in output and 'data-theme="dark"' not in output
def test_pdf_header_footer_and_cancel(tmp_path):
from PySide6.QtWidgets import QApplication
from pypdf import PdfWriter, PdfReader
app = QApplication.instance() or QApplication([])
writer = PdfWriter(); writer.add_blank_page(width=842, height=595)
data = BytesIO(); writer.write(data)
result = decorate_pdf(data.getvalue(), PageSettings(landscape=True, header="报告 Header", footer="Footer"))
page = PdfReader(BytesIO(result)).pages[0]
assert float(page.mediabox.width) == 842
text = page.extract_text()
assert "Header" in text and "Footer" in text and "1" in text
cancel = threading.Event(); cancel.set()
with pytest.raises(ExportCancelled):
decorate_pdf(data.getvalue(), PageSettings(), cancel)
def test_all_exports_use_unsaved_snapshot(tmp_path):
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
path = tmp_path / "note.md"; path.write_text("# OLD_DISK", encoding="utf-8")
renderer = MarkdownRenderer(tmp_path)
editor = MarkdownEditorDialog(path, "# FRESH_EDITOR\n\n**最新内容**", renderer, "light", 1, "", 16)
class Controller(ExportController):
def _begin_pdf_export(self, output, content, headings, settings, source_path):
self.pdf = (content, headings, source_path)
def _begin_mhtml_export(self, output, content, source_path):
self.mhtml = (content, source_path)
window = Controller(ExportContext(
parent=None, settings=QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat),
snapshot=lambda: ExportSnapshot(path, editor.source_text(), {}, "", 16, "default"),
render=lambda snapshot: renderer.render_source(snapshot.source, snapshot.path),
page_html=lambda callback: None, configure_web_settings=lambda settings: None, status=lambda text: None))
try:
snapshot = window._export_snapshot()
editor.replace_source_undoable("changed later")
for kind in ("html", "mhtml"):
target = tmp_path / ("result." + kind)
window._export_web_to_path(target, kind, snapshot)
if kind == "mhtml":
text, source_path = window.mhtml
assert source_path == path
else:
text = target.read_text(encoding="utf-8")
assert "FRESH_EDITOR" in text and "OLD_DISK" not in text
window.export_docx_to_path(tmp_path / "result.docx", snapshot=snapshot, page_settings=PageSettings(include_toc=False))
with zipfile.ZipFile(tmp_path / "result.docx") as package:
assert b"FRESH_EDITOR" in package.read("word/document.xml")
window.export_pdf_to_path(tmp_path / "result.pdf", snapshot=snapshot)
assert "FRESH_EDITOR" in window.pdf[0]
assert window.pdf[1][0].title == "FRESH_EDITOR"
assert path.read_text() == "# OLD_DISK"
finally:
editor.preview_refresh_timer.stop(); editor.draft_save_timer.stop()
editor.deleteLater(); app.processEvents()