Files
MDHelper/tests/test_document_style.py
T

189 lines
10 KiB
Python

from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import zipfile
from pathlib import Path
from lxml import etree as ET
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication
from mdhelper.document_style import build_document_style_css, normalize_rule
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.style_dialog import DocumentStyleEditorDialog
W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
NS = {"w": W[1:-1]}
SOURCE = "# Heading 标题\n\nBody 正文 **bold** and *italic*.\n\nSecond 第二段。\n\n- List 列表\n\n> Quote 引用\n\n```\nCode 代码\n```\n\n| Table | 表头 |\n| --- | --- |\n| Cell | 单元格 |\n"
RULE = dict(chinese_font_family="宋体", english_font_family="Times New Roman", font_size=10.5, font_size_unit="pt",
bold=False, italic=False, font_color="#123456", letter_spacing=1.25, alignment="justify",
left_indent_value=1.5, left_indent_unit="cm", right_indent_value=6, right_indent_unit="pt",
indent_mode="first", indent_value=2, line_spacing_mode="exact", line_height_value=20,
space_before_value=0, space_before_unit="pt", space_after_value=0, space_after_unit="pt",
contextual_spacing=True, keep_with_next=True, keep_lines_together=True, page_break_before=False, widow_control=False)
def test_css_preserves_zero_and_explicit_false():
css = build_document_style_css({"h2": RULE})
for expected in ("font-weight: 400", "font-style: normal", "font-size: 10.5pt", "margin-top: 0pt",
"margin-bottom: 0pt", "text-indent: 2em", "text-align: justify", "letter-spacing: 1.25pt",
"line-height: 20pt", "break-before: auto", "widows: 1", "h2 + h2"):
assert expected in css
def test_contextual_spacing_stays_within_the_selected_target():
css = build_document_style_css({"paragraph": {"contextual_spacing": True}, "blockquote": {"contextual_spacing": True}})
assert ".reader p + p" not in css
assert ".reader blockquote > p + p" in css
def test_legacy_rule_migration_preserves_units_and_resolves_conflicting_indents():
rule = normalize_rule(dict(font_size=18, first_line_indent_chars=2, hanging_indent_chars=1,
line_height_value=22, line_height_unit="pt", space_after_value=.6, space_after_unit="multiple"))
assert rule["indent_mode"] == "hanging" and rule["indent_value"] == 1
assert rule["line_spacing_mode"] == "exact" and rule["space_after_unit"] == "em"
assert "font-size: 18px" in build_document_style_css({"paragraph": rule})
@pytest.fixture
def app():
return QApplication.instance() or QApplication([])
def test_dialog_roundtrip_inherit_reset_and_live_preview(app):
dialog = DocumentStyleEditorDialog({"rules": {"paragraph": RULE}, "extra_css": ""})
try:
assert dialog.style_payload()["rules"]["paragraph"] == RULE
assert dialog.preview.document().firstBlock().blockFormat().textIndent() > 0
dialog.indent_mode_combo.setCurrentIndex(dialog.indent_mode_combo.findData("hanging"))
assert dialog.preview.document().firstBlock().blockFormat().textIndent() < 0
dialog.space_after_spin.setValue(0)
dialog.bold_checkbox.setCheckState(Qt.CheckState.Unchecked)
saved = dialog.style_payload()["rules"]["paragraph"]
assert saved["bold"] is False and saved["space_after_value"] == 0
dialog.target_list.setCurrentRow(2)
assert dialog.bold_checkbox.checkState() == Qt.CheckState.PartiallyChecked
dialog.target_list.setCurrentRow(0)
assert dialog.indent_mode_combo.currentData() == "hanging"
dialog._reset_current_rule()
assert dialog.style_payload()["rules"] == {}
finally:
dialog.close()
def test_dialog_legacy_px_and_no_duplicate_generated_css(app):
dialog = DocumentStyleEditorDialog({"rules": {"paragraph": {"font_size": 18}}, "css": ".reader p {font-size:18px}"})
try:
assert dialog.font_size_unit_combo.currentData() == "px"
assert dialog.extra_css_edit.toPlainText().count("font-size:") == 1
dialog.font_size_preset_combo.setCurrentIndex(dialog.font_size_preset_combo.findData(10.5))
rule = dialog.style_payload()["rules"]["paragraph"]
assert rule["font_size"] == 10.5 and rule["font_size_unit"] == "pt"
finally:
dialog.close()
def read_xml(path):
from docx_assertions import effective_document
with zipfile.ZipFile(path) as package:
document, styles = ET.fromstring(package.read("word/document.xml")), ET.fromstring(package.read("word/styles.xml"))
return effective_document(document, styles), styles
@pytest.mark.parametrize("engine", ["builtin", "python-docx", "pandoc"])
def test_word_preserves_all_settings_and_content(tmp_path: Path, engine):
rules = {key: dict(RULE) for key in ("paragraph", "h1", "list", "blockquote", "code", "table")}
path = export_markdown_to_docx(SOURCE, tmp_path / f"{engine}.docx", engine=engine, style_rules=rules)
doc, styles = read_xml(path)
paragraphs = doc.findall(".//w:p", NS)
assert len(paragraphs) >= 10
for p in paragraphs:
ppr = p.find(W + "pPr")
assert ppr.find(W + "jc").get(W + "val") == "both"
spacing = ppr.find(W + "spacing")
assert spacing.get(W + "before") == spacing.get(W + "after") == "0"
assert spacing.get(W + "line") == "400" and spacing.get(W + "lineRule") == "exact"
ind = ppr.find(W + "ind")
# List geometry uses absolute lengths so Word's document grid cannot
# shift code/heading continuations away from their list's text column.
assert ind.get(W + "firstLineChars") == ("0" if ppr.find(W + 'numPr') is not None else "200")
assert ind.get(W + "firstLine") == "420" and ind.get(W + "right") == "120"
assert ind.get(W + "left") == "850"
for name, value in (("keepNext", "1"), ("keepLines", "1"), ("contextualSpacing", "1"), ("pageBreakBefore", "0"), ("widowControl", "0")):
assert ppr.find(W + name).get(W + "val") == value
for run in p.findall(".//w:r", NS):
rpr = run.find(W + "rPr")
assert rpr.find(W + "rFonts").get(W + "eastAsia") == "宋体"
assert rpr.find(W + "rFonts").get(W + "ascii") == "Times New Roman"
assert rpr.find(W + "sz").get(W + "val") == "21"
assert rpr.find(W + "color").get(W + "val") == "123456"
assert rpr.find(W + "spacing").get(W + "val") == "25"
heading = paragraphs[0]
assert heading.find(".//w:rPr/w:b", NS).get(W + "val") == "0"
body = next(p for p in paragraphs if "Body" in "".join(p.itertext()))
bold_run = next(r for r in body.findall("w:r", NS) if "".join(r.itertext()) == "bold")
assert bold_run.find("w:rPr/w:b", NS).get(W + "val") == "1"
# Every assigned style exists in the styles part (including the basic exporter).
ids = {s.get(W + "styleId") for s in styles.findall(W + "style")}
assert all(p.find("w:pPr/w:pStyle", NS).get(W + "val") in ids for p in paragraphs)
from docx import Document
assert Document(str(path)).tables
@pytest.mark.parametrize("mode,value,expected", [("multiple", 1.5, ("360", "auto")), ("exact", 18, ("360", "exact")), ("at_least", 18, ("360", "atLeast"))])
def test_word_line_modes_hanging_and_line_spacing_units(tmp_path, mode, value, expected):
rule = dict(RULE, line_spacing_mode=mode, line_height_value=value, indent_mode="hanging", indent_value=1.5,
space_after_value=.5, space_after_unit="line", page_break_before=True)
path = export_markdown_to_docx("段落", tmp_path / "modes.docx", style_rules={"paragraph": rule})
doc, _ = read_xml(path)
ppr = doc.find(".//w:pPr", NS)
spacing = ppr.find(W + "spacing")
assert (spacing.get(W + "line"), spacing.get(W + "lineRule")) == expected
assert spacing.get(W + "afterLines") == "50"
ind = ppr.find(W + "ind")
assert ind.get(W + "hangingChars") == "150" and ind.get(W + "firstLine") is None
assert ind.get(W + "left") == "850" # Hanging does not change the chosen left indent.
assert ppr.find(W + "pageBreakBefore").get(W + "val") == "1"
@pytest.mark.parametrize("engine", ["builtin", "python-docx", "pandoc"])
def test_word_targets_are_independent(tmp_path, engine):
rules = {key: {"font_color": color} for key, color in [("paragraph", "#111111"), ("h1", "#222222"),
("list", "#333333"), ("blockquote", "#444444"), ("code", "#555555"), ("table", "#666666")]}
path = export_markdown_to_docx(SOURCE, tmp_path / "targets.docx", engine=engine, style_rules=rules)
doc, _ = read_xml(path)
for word, color in [("Body", "111111"), ("Heading", "222222"), ("List", "333333"), ("Quote", "444444"), ("Code", "555555"), ("Cell", "666666")]:
run = next(r for r in doc.iter(W + "r") if word in "".join(r.itertext()))
assert run.find("w:rPr/w:color", NS).get(W + "val") == color
def test_pandoc_exports_supplied_text_and_relative_destination(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
source = tmp_path / "original.md"
source.write_text("Old", encoding="utf-8")
result = export_markdown_to_docx("Updated", Path("output.docx"), engine="pandoc", source_path=source)
doc, _ = read_xml(result)
assert "Updated" in "".join(doc.itertext()) and "Old" not in "".join(doc.itertext())
def test_pandoc_style_processing_preserves_math_links_and_numbering(tmp_path):
source = "[OpenAI](https://openai.com) and $x^2+y^2$.\n\n1. First\n2. Second\n\n - Nested\n"
path = export_markdown_to_docx(source, tmp_path / "semantic.docx", engine="pandoc", style_rules={"paragraph": RULE})
with zipfile.ZipFile(path) as package:
xml = ET.fromstring(package.read("word/document.xml"))
from docx_assertions import effective_document
xml = effective_document(xml, ET.fromstring(package.read('word/styles.xml')))
rels = package.read("word/_rels/document.xml.rels").decode()
assert xml.find(".//w:hyperlink", NS) is not None
assert "https://openai.com" in rels
assert xml.find(".//{http://schemas.openxmlformats.org/officeDocument/2006/math}oMath") is not None
assert xml.find(".//w:numPr", NS) is not None
assert "word/numbering.xml" in package.namelist()
levels = xml.findall(".//w:pPr[w:numPr]", NS)
nested = [p for p in levels if p.find("w:numPr/w:ilvl", NS).get(W + "val") == "1"]
assert nested and int(nested[0].find(W + "ind").get(W + "left")) > 720
assert nested[0].find(W + "ind").get(W + "leftChars") == "0"
assert nested[0].find(W + "ind").get(W + "left") == "1200"