Files
MDHelper/tests/test_word_named_styles.py

131 lines
8.0 KiB
Python

import json
import zipfile
from lxml import etree as ET
import pytest
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_semantic import style_id, RUN_FIELDS, PARAGRAPH_FIELDS
from mdhelper.docx_style import W, NS
from mdhelper.document_style import resolved_rules
from mdhelper.style_sync import normalize_payload, render_css
from docx_assertions import effective_document
SOURCE = '# Title **bold title**\n\nBody **strong** *emphasis* ~~strike~~ `code` [link](https://example.com) [**bold link**](https://example.com).\n\nSecond **strong second**.\n\n- Bullet\n\n1. Ordered\n\n - Nested\n\n- [ ] Task\n\n> Quote\n\n```python\nprint(1)\n```\n\n| Header | **Strong header** |\n|---|---|\n| Cell | Content |'
def read_parts(path):
with zipfile.ZipFile(path) as package:
return {name: ET.fromstring(package.read(name)) for name in ('word/document.xml', 'word/styles.xml', 'word/_rels/document.xml.rels')}
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_shared_named_styles_without_direct_format_overrides(tmp_path, engine):
path = export_markdown_to_docx(SOURCE, tmp_path / 'named.docx', engine=engine)
parts = read_parts(path); doc = parts['word/document.xml']; styles = parts['word/styles.xml']
by_id = {s.get(W + 'styleId'): s for s in styles.findall(W + 'style')}
for paragraph in doc.iter(W + 'p'):
ppr = paragraph.find(W + 'pPr')
assert all(ppr.find(W + field) is None for field in PARAGRAPH_FIELDS)
assert ppr.find(W + 'pStyle').get(W + 'val') in by_id
for run in doc.iter(W + 'r'):
rpr = run.find(W + 'rPr')
protected = {'b', 'bCs', 'i', 'iCs', 'strike'}
assert all(rpr.find(W + field) is None for field in set(RUN_FIELDS) - protected)
ref = rpr.find(W + 'rStyle')
if ref is not None: assert ref.get(W + 'val') in by_id
paragraph_ids = {p.find('w:pPr/w:pStyle', NS).get(W + 'val') for p in doc.iter(W + 'p')}
assert {style_id(k) for k in ('paragraph', 'h1', 'list_bullet', 'list_ordered', 'list_task', 'blockquote', 'code_block', 'table_head', 'table_cell')} <= paragraph_ids
for key in ('strong', 'emphasis', 'strike', 'link', 'inline_code'):
style = by_id[style_id(key)]
assert style.get(W + 'type') == 'character'
assert style.find('w:rPr/w:sz', NS) is None
assert by_id[style_id('strong')].find('w:rPr/w:rFonts', NS) is None
assert doc.find('.//w:hyperlink', NS) is not None
assert any(e.get('Target') == 'https://example.com' for e in parts['word/_rels/document.xml.rels'])
# Editing the shared body style reaches plain and strongly emphasized text.
by_id[style_id('paragraph')].find('w:rPr/w:sz', NS).set(W + 'val', '46')
effective = effective_document(doc, styles)
for word in ('Body', 'strong second'):
run = next(r for r in effective.iter(W + 'r') if word in ''.join(r.itertext()))
assert run.find('w:rPr/w:sz', NS).get(W + 'val') == '46'
# Combined styles inherit link color instead of baking it into every run.
mixed = next(s for s in styles if 'MixLinkStrong' == s.get(W + 'styleId', '').removeprefix('MDHelper'))
assert mixed.find('w:basedOn', NS).get(W + 'val') == style_id('link')
assert mixed.find('w:rPr/w:color', NS) is None
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_inheritance_metadata_and_character_overrides_survive_export(tmp_path, engine):
rules = {'h1': {'font_size': 28, 'font_size_unit': 'pt', 'font_color': '#123456'},
'h2': {'alignment': 'center'}, 'link': {'underline': False, 'font_color': '#ff0000'},
'strong': {'font_color': '#008800'},
'_metadata': {'h2': {'name': '子章节', 'based_on': 'h1'}, 'emphasis': {'based_on': 'strong'}}}
payload = normalize_payload(json.loads(json.dumps({'rules': rules})))
path = export_markdown_to_docx('# One\n\n## Two\n\n[link](https://example.com) *emphasized*', tmp_path / 'inherit.docx', engine=engine, style_rules=payload['rules'])
parts = read_parts(path); styles = parts['word/styles.xml']
h2 = styles.find(f"w:style[@w:styleId='{style_id('h2')}']", NS)
assert h2.find('w:name', NS).get(W + 'val') == 'MDHelper 子章节'
assert h2.find('w:basedOn', NS).get(W + 'val') == style_id('h1')
assert h2.find('w:rPr/w:sz', NS) is None
assert h2.find('w:pPr/w:jc', NS).get(W + 'val') == 'center'
link = styles.find(f"w:style[@w:styleId='{style_id('link')}']", NS)
assert link.find('w:rPr/w:u', NS).get(W + 'val') == 'none'
assert link.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000'
emphasis = styles.find(f"w:style[@w:styleId='{style_id('emphasis')}']", NS)
assert emphasis.find('w:basedOn', NS).get(W + 'val') == style_id('strong')
assert emphasis.find('w:rPr/w:i', NS) is not None
def test_inherit_default_parent_values_in_reader_and_word():
rules = {'_metadata': {'h2': {'based_on': 'h1'}}}
effective = resolved_rules(rules, font_size_px=20)
assert effective['h2']['font_size'] == effective['h1']['font_size'] == 41
css = render_css('', rules, font_size_px=20)
assert '.reader h2' in css and 'font-size: 41px' in css
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_table_borders_padding_and_nested_list_styles(tmp_path, engine):
rules = {'table': {'border_width': 1.5, 'border_color': '#123456', 'cell_padding': 6},
'table_head': {'background_color': '#ffeecc'}, 'list_bullet': {'level_indent': 24},
'list_ordered': {'list_marker': 'upper-roman'}}
path = export_markdown_to_docx(SOURCE, tmp_path / 'containers.docx', engine=engine, style_rules=rules)
with zipfile.ZipFile(path) as package:
styles = ET.fromstring(package.read('word/styles.xml'))
numbers = ET.fromstring(package.read('word/numbering.xml'))
table = styles.find(f"w:style[@w:styleId='{style_id('table')}']", NS)
assert table.find('w:tblPr/w:tblBorders/w:top', NS).get(W + 'sz') == '12'
assert table.find('w:tblPr/w:tblCellMar/w:top', NS).get(W + 'w') == '120'
assert table.find("w:tblStylePr[@w:type='firstRow']/w:tcPr/w:shd", NS).get(W + 'fill') == 'ffeecc'
nested = styles.find(f"w:style[@w:styleId='{style_id('list_bullet')}Level2']", NS)
assert nested.find('w:basedOn', NS).get(W + 'val') == style_id('list_bullet')
assert nested.find('w:rPr', NS) is None
assert numbers.find(".//w:numFmt[@w:val='upperRoman']", NS) is not None
def test_explicit_child_font_stays_independent_even_when_initially_equal(tmp_path):
rules = {'h1': {'font_size': 28, 'font_size_unit': 'pt'}, 'h2': {'font_size': 28, 'font_size_unit': 'pt'},
'_metadata': {'h2': {'based_on': 'h1'}}}
path = export_markdown_to_docx('## Child', tmp_path / 'child.docx', style_rules=rules)
styles = read_parts(path)['word/styles.xml']
child = styles.find(f"w:style[@w:styleId='{style_id('h2')}']", NS)
assert child.find('w:rPr/w:sz', NS).get(W + 'val') == '56'
def test_duplicate_display_names_do_not_merge_distinct_word_styles(tmp_path):
path = export_markdown_to_docx('# Heading\n\nBody', tmp_path / 'names.docx',
style_rules={'_metadata': {'h1': {'name': '正文'}}})
styles = read_parts(path)['word/styles.xml']
names = [s.find(W + 'name').get(W + 'val') for s in styles.findall(W + 'style')]
assert len(names) == len(set(names))
def test_project_preset_retains_semantic_names_and_bases():
from mdhelper.project_presets import capture_preset, portable_preset, read_portable_preset
from mdhelper.preferences import ReaderPreferences
from mdhelper.export_settings import PageSettings
rules = {'h1': {'font_size': 22}, '_metadata': {'h2': {'name': '章节', 'based_on': 'h1'}}}
reader = ReaderPreferences.from_mapping({'document_style_id': 'custom:test', 'custom_document_styles': {'custom:test': {'rules': rules}}})
preset = read_portable_preset(json.loads(json.dumps(portable_preset(capture_preset('Styles', reader, PageSettings())))))
assert preset['reader']['custom_document_styles']['custom:test']['rules']['_metadata'] == rules['_metadata']