Files
MDHelper/tests/test_style_regressions.py
T

98 lines
5.2 KiB
Python

import json
import time
import zipfile
from lxml import etree as ET
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWebEngineCore import QWebEnginePage
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS, val
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.style_sync import normalize_payload, render_css
from mdhelper.markdown_renderer import MarkdownRenderer
from docx_assertions import effective_document
PARTIAL_RULES = {
'h1': {'chinese_font_family': 'SimSun', 'english_font_family': 'Arial', 'font_size': 12, 'font_size_unit': 'pt',
'space_after_value': 8, 'space_after_unit': 'pt', 'line_height_value': 1.5, 'line_spacing_mode': 'multiple',
'left_indent_value': 24, 'left_indent_unit': 'pt'},
'h2': {'english_font_family': 'Courier New', 'space_before_value': 12, 'space_before_unit': 'pt',
'right_indent_value': 8, 'right_indent_unit': 'pt'},
'_metadata': {'h2': {'based_on': 'h1'}},
}
def parts(path):
with zipfile.ZipFile(path) as z:
return ET.fromstring(z.read('word/document.xml')), ET.fromstring(z.read('word/styles.xml'))
def browser(qapp, tmp_path, payload, source, expression):
page = QWebEnginePage(); loaded = []; result = []
def wait(predicate):
end = time.monotonic() + 12
while not predicate() and time.monotonic() < end: qapp.processEvents(); time.sleep(.01)
assert predicate(), 'WebEngine timed out'
try:
page.loadFinished.connect(loaded.append)
page.setHtml(MarkdownRenderer(tmp_path).render_source(source, tmp_path / 'test.md',
document_style_css=render_css(payload['css'], payload['rules'])))
wait(lambda: loaded)
page.runJavaScript('JSON.stringify(' + expression + ')', result.append)
wait(lambda: result)
return json.loads(result[0])
finally: page.deleteLater(); qapp.processEvents()
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_word_inherits_other_attributes_when_one_attribute_is_explicit(tmp_path, engine):
path = export_markdown_to_docx('# Parent\n\n## Child', tmp_path / 'partial.docx', engine=engine, style_rules=PARTIAL_RULES)
doc, styles = parts(path)
base = styles.find("w:style[@w:styleId='MDHelperH1']", NS)
child = styles.find("w:style[@w:styleId='MDHelperH2']", NS)
assert child.find('w:rPr/w:rFonts', NS).get(W + 'eastAsia') is None
assert child.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Courier New'
assert set(child.find('w:pPr/w:spacing', NS).attrib) == {W + 'before'}
assert set(child.find('w:pPr/w:ind', NS).attrib) == {W + 'right'}
base.find('w:rPr/w:rFonts', NS).set(W + 'eastAsia', 'KaiTi')
base.find('w:pPr/w:spacing', NS).set(W + 'after', '480')
rendered = effective_document(doc, styles)
paragraph = next(p for p in rendered.iter(W + 'p') if 'Child' in ''.join(p.itertext()))
assert paragraph.find('.//w:rFonts', NS).get(W + 'eastAsia') == 'KaiTi'
assert paragraph.find('w:pPr/w:spacing', NS).get(W + 'after') == '480'
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_word_semantic_emphasis_survives_paragraph_style_changes(tmp_path, engine):
path = export_markdown_to_docx('Plain **StrongText** *ItalicText* ~~Deleted~~\n\n# Title **HeadingStrong**', tmp_path / 'emphasis.docx', engine=engine)
doc, styles = parts(path)
base = styles.find("w:style[@w:styleId='MDHelperParagraph']/w:rPr", NS)
for tag in ('b', 'i', 'strike'): val(base, tag, 1)
val(styles.find("w:style[@w:styleId='MDHelperH1']/w:rPr", NS), 'b', 0)
rendered = effective_document(doc, styles)
for text, tag in (('StrongText', 'b'), ('HeadingStrong', 'b'), ('ItalicText', 'i'), ('Deleted', 'strike')):
run = next(r for r in rendered.iter(W + 'r') if text in ''.join(r.itertext()))
assert run.find('w:rPr/w:' + tag, NS).get(W + 'val') == '1'
for run in doc.iter(W + 'r'):
assert run.find('w:rPr/w:sz', NS) is None
assert run.find('w:rPr/w:rFonts', NS) is None
assert run.find('w:rPr/w:color', NS) is None
@pytest.mark.parametrize('key,changed,source,selector', [('strike', 'underline', '~~Text~~', 's'), ('link', 'strike', '[Text](#text)', 'p a')])
def test_graphical_decoration_preserves_inherited_counterpart(qt_application, tmp_path, key, changed, source, selector):
dialog = DocumentStyleEditorDialog({})
try:
dialog.select_target(key)
dialog.bool_boxes[changed].setCheckState(Qt.CheckState.Checked)
payload = dialog.style_payload()
assert payload['rules'][key] == {changed: True}
assert normalize_payload(payload)['rules'][key] == {changed: True}
actual = browser(qt_application, tmp_path, payload, source, f'getComputedStyle(document.querySelector("{selector}")).textDecorationLine')
assert set(actual.split()) == {'underline', 'line-through'}
# Explicitly switching the other property off is still respected.
other = 'strike' if changed == 'underline' else 'underline'
dialog.bool_boxes[other].setCheckState(Qt.CheckState.Unchecked)
assert dialog.style_payload()['rules'][key][other] is False
finally: dialog.close()