190 lines
12 KiB
Python
190 lines
12 KiB
Python
import json
|
|
import time
|
|
import zipfile
|
|
from lxml import etree as ET
|
|
import pytest
|
|
from PySide6.QtCore import Qt, QCoreApplication, QEvent
|
|
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
|
|
|
|
UNIT_RULES = {'h1': {'font_size': 12, 'font_size_unit': 'pt', 'left_indent_value': 2, 'left_indent_unit': 'em',
|
|
'space_before_value': .5, 'space_before_unit': 'line'},
|
|
'h2': {'left_indent_value': 20, 'left_indent_unit': 'pt', 'space_before_value': 0, 'space_before_unit': 'pt'},
|
|
'_metadata': {'h2': {'based_on': 'h1'}}}
|
|
NESTED_SOURCE = '**[InnerLink](https://example.com)** and [**InnerBold**](https://example.com) and [**`InlineCode`**](https://example.com)'
|
|
NESTED_RULES = {'strong': {'font_color': '#ff0000'}, 'link': {'font_color': '#0000ff'}}
|
|
|
|
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() + 30
|
|
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()
|
|
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
|
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 + key for key in ('before', 'beforeLines', 'beforeAutospacing')}
|
|
assert set(child.find('w:pPr/w:ind', NS).attrib) == {W + 'right', W + 'rightChars'}
|
|
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()
|
|
|
|
|
|
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
|
def test_word_unit_switch_clears_inherited_character_and_line_units(tmp_path, engine):
|
|
path = export_markdown_to_docx('# Parent\n\n## ChildUnits', tmp_path / 'units.docx', engine=engine, style_rules=UNIT_RULES)
|
|
doc, styles = parts(path)
|
|
p = next(p for p in effective_document(doc, styles).iter(W + 'p') if 'ChildUnits' in ''.join(p.itertext()))
|
|
ind, spacing = p.find('w:pPr/w:ind', NS), p.find('w:pPr/w:spacing', NS)
|
|
assert ind.get(W + 'left') == '400' and ind.get(W + 'leftChars') == '0'
|
|
assert spacing.get(W + 'before') == spacing.get(W + 'beforeLines') == '0'
|
|
|
|
|
|
def test_reader_separate_language_font_inheritance(qt_application, tmp_path):
|
|
payload = normalize_payload({'rules': {'h1': {'english_font_family': 'Arial'}, 'h2': {'chinese_font_family': 'SimSun'}, '_metadata': {'h2': {'based_on': 'h1'}}}})
|
|
font = browser(qt_application, tmp_path, payload, '## Child', "getComputedStyle(document.querySelector('h2')).fontFamily")
|
|
assert font.startswith('Arial, SimSun')
|
|
|
|
|
|
def test_reader_clear_list_base_and_keep_own_overrides(qt_application, tmp_path):
|
|
payload = normalize_payload({'rules': {'list': {'font_color': '#ff0000', 'bold': True, 'background_color': '#ffff00', 'list_marker': 'upper-roman'},
|
|
'list_bullet': {'italic': True}, '_metadata': {'list_bullet': {'based_on': ''}}}})
|
|
actual = browser(qt_application, tmp_path, payload, '- Item', "(()=>{const s=getComputedStyle(document.querySelector('li'));return [s.color,s.fontWeight,s.fontStyle,s.backgroundColor,s.listStyleType]})()")
|
|
assert actual == ['rgb(35, 39, 47)', '400', 'italic', 'rgba(0, 0, 0, 0)', 'disc']
|
|
# Legacy configurations without metadata still inherit the list baseline.
|
|
payload = normalize_payload({'rules': {'list': {'font_color': '#ff0000', 'bold': True}}})
|
|
assert browser(qt_application, tmp_path, payload, '- Item', "getComputedStyle(document.querySelector('li')).color") == 'rgb(255, 0, 0)'
|
|
|
|
|
|
@pytest.mark.parametrize('points', [10, 60])
|
|
def test_reader_nested_list_indent_uses_own_core_setting(qt_application, tmp_path, points):
|
|
payload = normalize_payload({'rules': {'list_bullet': {'level_indent': points}}})
|
|
padding = browser(qt_application, tmp_path, payload, '- Outer\n - Inner', "parseFloat(getComputedStyle(document.querySelector('li > ul')).paddingLeft)")
|
|
assert padding == pytest.approx(points * 4/3, abs=.01)
|
|
|
|
|
|
@pytest.mark.parametrize('css,expected', [
|
|
('a {text-decoration-line:underline; text-decoration:none;}', False),
|
|
('a {text-decoration:underline !important; text-decoration-line:none;}', True),
|
|
('.reader a {text-decoration:none;} a {text-decoration-line:underline;}', False),
|
|
])
|
|
def test_decoration_shorthand_obeys_cascade_in_browser_controls_and_word(qt_application, tmp_path, css, expected):
|
|
payload = normalize_payload({'css': css})
|
|
assert payload['rules']['link']['underline'] is expected
|
|
actual = browser(qt_application, tmp_path, payload, '[Link](#link)', "getComputedStyle(document.querySelector('p a [data-mdh-text]') || document.querySelector('p a')).textDecorationLine")
|
|
assert ('underline' in actual) is expected
|
|
dialog = DocumentStyleEditorDialog(payload)
|
|
try:
|
|
dialog.select_target('link')
|
|
assert dialog.bool_boxes['underline'].isChecked() is expected
|
|
finally: dialog.close()
|
|
path = export_markdown_to_docx('[Link](https://example.com)', tmp_path / 'decoration.docx', style_rules=payload['rules'])
|
|
_, styles = parts(path)
|
|
assert styles.find("w:style[@w:styleId='MDHelperLink']/w:rPr/w:u", NS).get(W + 'val') == ('single' if expected else 'none')
|
|
|
|
|
|
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
|
def test_word_retains_nested_inline_order_and_styles_remain_editable(tmp_path, engine):
|
|
path = export_markdown_to_docx(NESTED_SOURCE, tmp_path / 'nested.docx', engine=engine, style_rules=NESTED_RULES)
|
|
doc, styles = parts(path)
|
|
assert not any((s.find(W + 'name').get(W + 'val', '') if s.find(W + 'name') is not None else '').startswith('MDHelperSource_') for s in styles)
|
|
def color(word):
|
|
rendered = effective_document(doc, styles)
|
|
run = next(r for r in rendered.iter(W + 'r') if word in ''.join(r.itertext()))
|
|
return run.find('w:rPr/w:color', NS).get(W + 'val')
|
|
assert color('InnerLink') == '0000ff' and color('InnerBold') == 'ff0000'
|
|
code = next(r for r in effective_document(doc, styles).iter(W + 'r') if 'InlineCode' in ''.join(r.itertext()))
|
|
assert code.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Consolas'
|
|
styles.find("w:style[@w:styleId='MDHelperLink']/w:rPr/w:color", NS).set(W + 'val', '008800')
|
|
assert color('InnerLink') == '008800' and color('InnerBold') == 'ff0000'
|
|
|
|
|
|
def test_pandoc_footnotes_and_equations_survive_semantic_annotation(tmp_path):
|
|
source = 'Math $x^2$ and a note[^1].\n\n[^1]: **[Link](https://example.com)** and `code`.'
|
|
path = export_markdown_to_docx(source, tmp_path / 'notes.docx', engine='pandoc', style_rules=NESTED_RULES)
|
|
with zipfile.ZipFile(path) as z:
|
|
document = ET.fromstring(z.read('word/document.xml')); notes = ET.fromstring(z.read('word/footnotes.xml'))
|
|
styles = ET.fromstring(z.read('word/styles.xml')); ids = {s.get(W + 'styleId') for s in styles}
|
|
assert document.find('.//{http://schemas.openxmlformats.org/officeDocument/2006/math}oMath') is not None
|
|
assert document.find('.//w:footnoteReference', NS) is not None
|
|
assert document.find(".//w:rStyle[@w:val='FootnoteReference']", NS) is not None
|
|
assert all(ref.get(W + 'val') in ids for ref in notes.findall('.//w:rStyle', NS))
|
|
assert notes.find('.//w:hyperlink', NS) is not None
|