Files
MDHelper/tests/test_style_revision_052.py

250 lines
15 KiB
Python

"""Cross-surface regressions found in the 0.5.1 style audit."""
import json
from PySide6.QtCore import Qt, QSettings
import pytest
from mdhelper import main_window
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.style_sync import normalize_payload, analyze_css
from mdhelper.document_style import resolved_rules
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS, child
from docx_assertions import effective_document
from test_style_regressions import browser, parts
ENGINES = ['builtin', 'python-docx', 'pandoc']
REPEATED_SOURCE = '**Outer *middle **Deep** middle* outer**'
REPEATED_RULES = {'strong': {'font_color': '#ff0000'}, 'emphasis': {'font_color': '#0000ff'}}
ABSOLUTE_PAYLOAD = {'css_sync_version': 1,
'css': '.reader h1 {font-size:20pt;} .reader h2 {text-indent:24pt;}',
'rules': {'_metadata': {'h2': {'based_on': 'h1'}}}}
SCOPED_SOURCE = 'BodyText\n\n> QuoteText\n\n- TightItem\n- TightSecond\n\n---\n\n- LooseItem\n\n- LooseSecond'
SCOPED_CSS = 'p {color:red; font-size:20pt;} blockquote {color:blue;}'
def text_run(document, word):
return next(r for r in document.iter(W + 'r') if word in ''.join(r.itertext()))
def test_unrelated_controls_preserve_css_values_outside_ui_range(qt_application):
source = '.reader table, .reader th, .reader td {padding:150pt; border-width:30pt; letter-spacing:1.2345pt;}'
dialog = DocumentStyleEditorDialog({'css': source})
try:
dialog.select_target('table')
dialog.bool_boxes['italic'].setCheckState(Qt.CheckState.Checked)
payload = dialog.style_payload()
assert payload['rules']['table'] == dict(italic=True, cell_padding=150, border_width=30, letter_spacing=1.2345)
assert 'padding:150pt' in payload['css'] and 'letter-spacing:1.2345pt' in payload['css']
dialog.cell_padding_spin.setValue(80)
rule = dialog.style_payload()['rules']['table']
assert rule['cell_padding'] == 80 and rule['border_width'] == 30
finally: dialog.close()
@pytest.mark.parametrize('engine', ENGINES)
def test_preset_copy_roundtrip_keeps_word_defaults(qt_application, tmp_path, monkeypatch, engine):
monkeypatch.setattr(main_window, 'QSettings', lambda *_: QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat))
window = main_window.MainWindow(None, app_root=tmp_path)
dialog = DocumentStyleEditorDialog(window._style_payload_for_id('serif'), parent=window)
try:
dialog.select_target('link')
dialog.bool_boxes['strike'].setCheckState(Qt.CheckState.Checked)
payload = normalize_payload(json.loads(json.dumps(dialog.style_payload())))
assert payload['rules']['_preset'] == 'serif'
before = resolved_rules({}, preset='serif')['paragraph']
after = resolved_rules(payload['rules'], preset='custom:copy')['paragraph']
assert after == before
path = export_markdown_to_docx('BookText', tmp_path / 'book.docx', engine=engine,
style_rules=payload['rules'], preset='custom:copy')
doc, styles = parts(path)
run = text_run(effective_document(doc, styles), 'BookText')
assert run.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Georgia'
assert run.find('w:rPr/w:rFonts', NS).get(W + 'eastAsia') == 'SimSun'
assert styles.find("w:style[@w:styleId='MDHelperParagraph']/w:pPr/w:spacing", NS).get(W + 'line') == '437'
finally: dialog.close(); window.close()
@pytest.mark.parametrize('detached', [False, True])
def test_code_block_overrides_legacy_inner_code_rules(qt_application, tmp_path, detached):
rules = {'code': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt', 'english_font_family': 'Arial'}}
if detached: rules['_metadata'] = {'code_block': {'based_on': ''}}
else: rules['code_block'] = {'font_color': '#0000ff', 'font_size': 10, 'font_size_unit': 'pt', 'english_font_family': 'Consolas'}
payload = normalize_payload({'rules': rules})
values = browser(qt_application, tmp_path, payload, '```python\nprint("CodeText")\n```',
"[...document.querySelectorAll('pre,pre code,pre code span')].map(e=>{const s=getComputedStyle(e);return [s.color,s.fontSize,s.fontFamily]})")
assert all(item == values[0] for item in values)
assert values[0][0] == ('rgb(35, 39, 47)' if detached else 'rgb(0, 0, 255)')
# A legacy style without a semantic override keeps its former appearance.
legacy = normalize_payload({'rules': {'code': rules['code']}})
assert browser(qt_application, tmp_path, legacy, '```text\nOld\n```',
"getComputedStyle(document.querySelector('pre code')).color") == 'rgb(255, 0, 0)'
def test_dark_theme_defaults_do_not_override_explicit_style_colors(qt_application, tmp_path):
payload = normalize_payload({'rules': {'h1': {'font_color': '#ff0000'}, 'link': {'font_color': '#ff0000'},
'code_block': {'background_color': '#ffff00'}}})
values = browser(qt_application, tmp_path, payload, '# Header\n\n[Link](https://example.com)\n\n```text\nCode\n```',
"(()=>{document.documentElement.dataset.theme='dark';return [getComputedStyle(document.querySelector('h1')).color,getComputedStyle(document.querySelector('a')).color,getComputedStyle(document.querySelector('pre')).backgroundColor,getComputedStyle(document.documentElement).colorScheme]})()")
assert values == ['rgb(255, 0, 0)', 'rgb(255, 0, 0)', 'rgb(255, 255, 0)', 'dark']
defaults = browser(qt_application, tmp_path, normalize_payload({}), '# Header\n\n[Link](#header)',
"(()=>{document.documentElement.dataset.theme='dark';return [getComputedStyle(document.querySelector('h1')).color,getComputedStyle(document.querySelector('a')).color]})()")
assert defaults == ['rgb(244, 247, 251)', 'rgb(121, 184, 255)']
@pytest.mark.parametrize('engine', ENGINES)
def test_repeated_nested_character_style_keeps_innermost_precedence(tmp_path, engine):
path = export_markdown_to_docx(REPEATED_SOURCE, tmp_path / 'repeated.docx', engine=engine, style_rules=REPEATED_RULES)
doc, styles = parts(path)
run = text_run(effective_document(doc, styles), 'Deep')
assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000'
assert run.find('w:rPr/w:b', NS).get(W + 'val') == '1'
assert run.find('w:rPr/w:i', NS).get(W + 'val') == '1'
@pytest.mark.parametrize('engine', ENGINES)
def test_nested_list_inherits_right_and_hanging_indent_edits(tmp_path, engine):
path = export_markdown_to_docx('- OuterList\n - InnerList', tmp_path / 'list.docx', engine=engine)
doc, styles = parts(path)
nested = styles.find("w:style[@w:styleId='MDHelperListBulletLevel2']/w:pPr/w:ind", NS)
assert set(nested.attrib) == {W + 'left', W + 'leftChars'}
base = child(styles.find("w:style[@w:styleId='MDHelperListBullet']/w:pPr", NS), 'ind')
base.set(W + 'right', '400'); base.set(W + 'rightChars', '0')
base.set(W + 'hangingChars', '200')
rendered = effective_document(doc, styles)
inner = next(p for p in rendered.iter(W + 'p') if 'InnerList' in ''.join(p.itertext()))
assert inner.find('w:pPr/w:ind', NS).get(W + 'right') == '400'
assert inner.find('w:pPr/w:ind', NS).get(W + 'hangingChars') == '200'
@pytest.mark.parametrize('engine', ENGINES)
def test_absolute_first_indent_survives_inherited_font_and_gui_roundtrip(qt_application, tmp_path, engine):
payload = normalize_payload(ABSOLUTE_PAYLOAD)
dialog = DocumentStyleEditorDialog(payload)
try:
dialog.select_target('h2')
assert dialog.indent_unit_combo.currentData() == 'pt' and dialog.indent_spin.value() == 24
dialog.bool_boxes['italic'].setCheckState(Qt.CheckState.Checked)
payload = normalize_payload(dialog.style_payload())
assert payload['rules']['h2']['indent_value'] == 24 and payload['rules']['h2']['indent_unit'] == 'pt'
path = export_markdown_to_docx('## Indented', tmp_path / 'indent.docx', engine=engine, style_rules=payload['rules'])
doc, styles = parts(path)
ind = effective_document(doc, styles).find('.//w:pPr/w:ind', NS)
assert ind.get(W + 'firstLine') == '480' and ind.get(W + 'firstLineChars') == '0'
finally: dialog.close()
@pytest.mark.parametrize('engine', ENGINES)
def test_p_selector_covers_quotes_and_loose_lists_without_changing_tight_lists(qt_application, tmp_path, engine):
payload = normalize_payload({'css': SCOPED_CSS})
assert payload['rules']['blockquote']['font_color'] == '#ff0000'
dialog = DocumentStyleEditorDialog(payload)
try:
dialog.font_size_spin.setValue(21)
payload = normalize_payload(dialog.style_payload())
assert payload['rules']['blockquote']['font_size'] == 21
assert payload['rules']['_list_paragraph']['font_size'] == 21
finally: dialog.close()
path = export_markdown_to_docx(SCOPED_SOURCE, tmp_path / 'scope.docx', engine=engine, style_rules=payload['rules'])
doc, styles = parts(path)
rendered = effective_document(doc, styles)
for word in ('BodyText', 'QuoteText', 'LooseItem', 'LooseSecond'):
run = text_run(rendered, word)
assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000', (engine, word)
assert run.find('w:rPr/w:sz', NS).get(W + 'val') == '42'
assert text_run(rendered, 'TightItem').find('w:rPr/w:color', NS).get(W + 'val') == 'auto'
for word in ('LooseItem', 'LooseSecond'):
p = next(p for p in doc.iter(W + 'p') if word in ''.join(p.itertext()))
assert p.find('w:pPr/w:numPr', NS) is not None
assert not any('MDHelperSourceListParagraph' in str(s.attrib) for s in styles)
def test_reader_p_scope_and_table_paragraph_spacing(qt_application, tmp_path):
payload = normalize_payload({'css': SCOPED_CSS})
colors = browser(qt_application, tmp_path, payload, SCOPED_SOURCE,
"[...document.querySelectorAll('p,li')].filter(e=>['BodyText','QuoteText','TightItem','LooseItem'].includes(e.textContent.trim())).map(e=>[e.textContent.trim(),getComputedStyle(e).color])")
assert ['BodyText', 'rgb(255, 0, 0)'] in colors and ['QuoteText', 'rgb(255, 0, 0)'] in colors
assert ['LooseItem', 'rgb(255, 0, 0)'] in colors and ['TightItem', 'rgb(35, 39, 47)'] in colors
sizes = []
for amount in (0, 30):
payload = normalize_payload({'rules': {'table_cell': {'space_before_value': amount, 'space_before_unit': 'pt',
'space_after_value': amount, 'space_after_unit': 'pt'}}})
sizes.append(browser(qt_application, tmp_path, payload, '| Header |\n|---|\n| Cell |',
"(()=>{let c=document.querySelector('td'),p=c.querySelector('.mdhelper-cell-paragraph');return [c.getBoundingClientRect().height,p.getBoundingClientRect().top-c.getBoundingClientRect().top]})()"))
assert sizes[1][0] - sizes[0][0] == pytest.approx(80, abs=.1)
assert sizes[1][1] - sizes[0][1] == pytest.approx(40, abs=.1)
@pytest.mark.parametrize('engine', ENGINES)
def test_contextual_color_follows_paragraph_and_outer_inline_color(qt_application, tmp_path, engine):
source = 'Body **Colored** [Link](https://example.com)\n\n# Heading **HeadingColor**\n\n**[Nested](https://example.com)**'
css = '.reader p {color:red;} h1 {color:blue;} strong {color:currentColor;} a {color:currentColor;}'
payload = normalize_payload({'css': css})
assert payload['rules']['strong']['font_color'] == 'inherit'
dialog = DocumentStyleEditorDialog(payload)
try:
dialog.select_target('strong')
assert dialog.color_combo.currentData() == 'inherit'
assert normalize_payload(dialog.style_payload()) == payload
finally: dialog.close()
path = export_markdown_to_docx(source, tmp_path / 'color.docx', engine=engine, style_rules=payload['rules'])
doc, styles = parts(path)
rendered = effective_document(doc, styles)
for word, color in (('Colored', 'ff0000'), ('Link', 'ff0000'), ('Nested', 'ff0000'), ('HeadingColor', '0000ff')):
assert text_run(rendered, word).find('w:rPr/w:color', NS).get(W + 'val') == color
assert styles.find("w:style[@w:styleId='MDHelperStrong']/w:rPr/w:color", NS) is None
@pytest.mark.parametrize('invalid', ['font-size:nope', 'font-size:-2pt !important', 'font-size:20wrong', 'color:invalid !important'])
def test_invalid_declaration_keeps_previous_valid_core_value(qt_application, tmp_path, invalid):
css = 'p {font-size:20pt;color:red;' + invalid + ';}'
payload = normalize_payload({'css': css})
assert payload['rules']['paragraph']['font_size'] == 20
assert payload['rules']['paragraph']['font_color'] == '#ff0000'
assert payload['css'] == css and analyze_css(css).notes
value = browser(qt_application, tmp_path, payload, 'Text',
"(()=>{const s=getComputedStyle(document.querySelector('p'));return [parseFloat(s.fontSize),s.color]})()")
assert value[0] == pytest.approx(20 * 4/3, abs=.01) and value[1] == 'rgb(255, 0, 0)'
@pytest.mark.parametrize('value', ['calc(10pt + 2vw)', '5vw', 'larger', 'var(--size)'])
def test_valid_extended_values_do_not_restore_obsolete_core_values(value):
result = analyze_css('p {font-size:20pt;font-size:' + value + ';color:red;}')
assert 'font_size' not in result.rules['paragraph']
assert result.notes
def test_graphical_quote_override_wins_over_broad_p_rule(qt_application, tmp_path):
dialog = DocumentStyleEditorDialog({'css': SCOPED_CSS})
try:
dialog.select_target('blockquote')
dialog.color_button.setText('#008800')
dialog._store_and_refresh()
payload = dialog.style_payload()
assert payload['rules']['blockquote']['font_color'] == '#008800'
assert payload['rules']['paragraph']['font_color'] == '#ff0000'
assert browser(qt_application, tmp_path, payload, '> Quote',
"getComputedStyle(document.querySelector('blockquote p')).color") == 'rgb(0, 136, 0)'
finally: dialog.close()
@pytest.mark.parametrize('engine', ENGINES)
@pytest.mark.parametrize('colored_base', [False, True])
def test_contextual_color_preserves_other_resolved_character_fields(tmp_path, engine, colored_base):
rules = {'paragraph': {'font_color': '#ff0000'}, 'emphasis': {'english_font_family': 'Arial'},
'strong': {'font_color': 'inherit'}, '_metadata': {'strong': {'based_on': 'emphasis'}}}
if colored_base: rules['emphasis']['font_color'] = '#0000ff'
path = export_markdown_to_docx('**InheritedText**', tmp_path / 'context-base.docx', engine=engine, style_rules=rules)
doc, styles = parts(path)
run = text_run(effective_document(doc, styles), 'InheritedText')
assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000'
assert run.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Arial'
assert run.find('w:rPr/w:i', NS).get(W + 'val') == '1'
if not colored_base:
assert styles.find("w:style[@w:styleId='MDHelperStrong']/w:basedOn", NS).get(W + 'val') == 'MDHelperEmphasis'
def test_invalid_shorthand_does_not_apply_its_valid_components():
result = analyze_css('p {margin:20pt; margin:3pt nope; font-size:18pt; font:14pt/nope Arial;}')
rule = result.rules['paragraph']
assert rule['space_before_value'] == rule['space_after_value'] == rule['left_indent_value'] == rule['right_indent_value'] == 20
assert rule['font_size'] == 18