"""Regressions from the 0.5.3 style and table audit.""" import pytest import zipfile from lxml import etree as ET from mdhelper.docx_exporter import export_markdown_to_docx from mdhelper.docx_style import W, NS from mdhelper.style_sync import normalize_payload from test_style_regressions import browser, parts from docx_assertions import effective_document from mdhelper.style_dialog import DocumentStyleEditorDialog ENGINES = ('builtin', 'python-docx', 'pandoc') TABLE = '| Head | Description |\n|---|---|\n| Alpha | First |\n| Beta | Second |' BACKGROUND_RULES = {'h1': {'background_color': '#ff0000'}, 'table_head': {'background_color': '#0000ff'}, 'table_cell': {'background_color': '#00ff00'}, '_metadata': {'table_head': {'based_on': 'h1'}, 'table_cell': {'based_on': 'h1'}}} CONTINUATION_SOURCE = '1. First\n\n Continuation\n\n2. Second' NESTED_SOURCE = '- Outer\n\n - Inner\n\n - NestedSecond\n\n- Second' NESTED_RULES = normalize_payload({'css': 'p {margin-left:12pt;} li {margin-left:24pt;}'})['rules'] CODE_SOURCE = '`Inline`\n\n```text\nBlock\n```' CODE_RULES = {'code': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt'}} def test_copy_button_has_continuous_pointer_path(qt_application, tmp_path): assert browser(qt_application, tmp_path, normalize_payload({}), TABLE, """(()=>{ const button=document.querySelector('.copy-table-button');button.focus(); const b=button.getBoundingClientRect(),t=document.querySelector('table').getBoundingClientRect(); const tools=document.querySelector('.table-tools').getBoundingClientRect(); return tools.bottom >= t.top && tools.top <= b.top; })()""") @pytest.mark.parametrize('engine', ENGINES) def test_table_background_cancels_paragraph_parent_shading(tmp_path, engine): doc, styles = parts(export_markdown_to_docx(TABLE,tmp_path/'shade.docx',engine=engine,style_rules=BACKGROUND_RULES)) for p in effective_document(doc,styles).iter(W+'p'): assert p.find('w:pPr/w:shd',NS).get(W+'fill') == 'auto' for key, color in (('firstRow','0000ff'),('band1Horz','00ff00')): assert styles.find(f"w:style[@w:styleId='MDHelperTable']/w:tblStylePr[@w:type='{key}']/w:tcPr/w:shd",NS).get(W+'fill') == color assert not doc.findall('.//w:tcPr/w:shd',NS) @pytest.mark.parametrize('engine', ENGINES) def test_list_continuation_does_not_consume_a_number(tmp_path, engine): path=export_markdown_to_docx(CONTINUATION_SOURCE,tmp_path/'list.docx',engine=engine) doc, styles = parts(path) with zipfile.ZipFile(path) as z: numbering=ET.fromstring(z.read('word/numbering.xml')) numbered=[] for p in effective_document(doc,styles).iter(W+'p'): num=p.find('w:pPr/w:numPr',NS) if num is None: continue nid=num.find(W+'numId').get(W+'val') if nid=='0': continue aid=numbering.find(f"w:num[@w:numId='{nid}']/w:abstractNumId",NS).get(W+'val') level=num.find(W+'ilvl').get(W+'val') lvl=numbering.find(f"w:abstractNum[@w:abstractNumId='{aid}']/w:lvl[@w:ilvl='{level}']",NS) if lvl.find(W+'numFmt').get(W+'val')!='none' and lvl.find(W+'lvlText').get(W+'val').strip(): numbered.append(''.join(p.itertext())) assert numbered == ['First','Second'] assert not any('{urn:mdhelper:source}continuation' in p.attrib for p in doc.iter(W+'p')) @pytest.mark.parametrize('engine', ENGINES) def test_loose_nested_list_adds_inner_paragraph_margin(tmp_path, engine): doc, styles = parts(export_markdown_to_docx(NESTED_SOURCE,tmp_path/'nested.docx',engine=engine,style_rules=NESTED_RULES)) indents = {''.join(p.itertext()): int(p.find('w:pPr/w:ind',NS).get(W+'left'))/20 for p in effective_document(doc,styles).iter(W+'p')} assert indents['Outer'] == 36 and indents['Inner'] == 72 @pytest.mark.parametrize('engine', ENGINES) def test_legacy_code_uses_linked_editable_word_base(tmp_path, engine): _, styles = parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/'code.docx',engine=engine,style_rules=CODE_RULES)) assert styles.find("w:style[@w:styleId='MDHelperCode']/w:link",NS).get(W+'val') == 'MDHelperCodeChar' assert styles.find("w:style[@w:styleId='MDHelperCodeChar']/w:link",NS).get(W+'val') == 'MDHelperCode' inline = styles.find("w:style[@w:styleId='MDHelperInlineCode']",NS) assert inline.find(W+'basedOn').get(W+'val') == 'MDHelperCodeChar' assert inline.find('w:rPr/w:color',NS) is None @pytest.mark.parametrize('engine',ENGINES) def test_legacy_code_can_still_request_surrounding_color(tmp_path,engine): rules={**CODE_RULES,'paragraph':{'font_color':'#008000'},'inline_code':{'font_color':'inherit'}} doc,styles=parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/'context-code.docx',engine=engine,style_rules=rules)) run=next(r for r in effective_document(doc,styles).iter(W+'r') if ''.join(r.itertext())=='Inline') assert run.find('w:rPr/w:color',NS).get(W+'val')=='008000' assert styles.find("w:style[@w:styleId='MDHelperInlineCode']/w:basedOn",NS) is None def test_graphical_table_layout_overrides_important_legacy_border(qt_application,tmp_path): dialog=DocumentStyleEditorDialog({'css':'table,th,td {border-style:solid!important;border-width:2pt;border-color:red;}'}) try: dialog.select_target('table') for mode,expected in [('none',['none','none']),('horizontal',['none','solid']),('grid',['solid','solid'])]: dialog.table_border_mode_box.setCurrentIndex(dialog.table_border_mode_box.findData(mode)) payload=dialog.style_payload() assert normalize_payload(payload)==payload assert browser(qt_application,tmp_path,payload,TABLE,"(()=>{const s=getComputedStyle(document.querySelector('td'));return [s.borderLeftStyle,s.borderTopStyle]})()") == expected finally:dialog.close() @pytest.mark.parametrize('background',['#ffeecc','transparent']) def test_bare_cell_css_wins_over_optional_stripes(qt_application,tmp_path,background): payload=normalize_payload({'css':f'table {{ --mdhelper-table-banded-rows:true; }} td {{background-color:{background};}}'}) colors=browser(qt_application,tmp_path,payload,TABLE,"[...document.querySelectorAll('tbody td')].map(e=>getComputedStyle(e).backgroundColor)") assert len(set(colors))==1 for engine in ENGINES: _,styles=parts(export_markdown_to_docx(TABLE,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules'])) for band in ('band1Horz','band2Horz'): shade=styles.find(f"w:style[@w:styleId='MDHelperTable']/w:tblStylePr[@w:type='{band}']/w:tcPr/w:shd",NS) assert shade.get(W+'fill') == ('auto' if background=='transparent' else background[1:]) @pytest.mark.parametrize('legacy',['','table,th,td {background-color:red!important;color:red!important;}']) def test_detached_table_text_preserves_table_decoration(qt_application,tmp_path,legacy): dialog=DocumentStyleEditorDialog({'css':legacy+' table {--mdhelper-table-banded-rows:true;}'}) try: for target in ('table_head','table_cell'): dialog.select_target(target);dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData('')) payload=dialog.style_payload() actual=browser(qt_application,tmp_path,payload,TABLE,"[...document.querySelectorAll('tr > :first-child')].map(e=>{const s=getComputedStyle(e);return [s.backgroundColor,s.color]})") assert [r[0] for r in actual]==['rgb(241, 245, 249)','rgba(0, 0, 0, 0)','rgb(248, 250, 252)'] assert all(r[1]!='rgb(255, 0, 0)' for r in actual) finally:dialog.close() def test_important_code_css_respects_graphical_child_and_detachment(qt_application,tmp_path): dialog=DocumentStyleEditorDialog({'css':'pre,code {color:red!important;}'}) try: dialog.select_target('code_block');dialog.color_combo.setCurrentIndex(dialog.color_combo.findData('custom')) dialog.color_button.setText('#0000ff');dialog._store_and_refresh() dialog.select_target('inline_code');dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData('')) payload=dialog.style_payload() colors=browser(qt_application,tmp_path,payload,CODE_SOURCE,"[...document.querySelectorAll('code')].map(e=>getComputedStyle(e).color)") assert colors[0]!='rgb(255, 0, 0)' and colors[1]=='rgb(0, 0, 255)' for engine in ENGINES: doc,styles=parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules'])) actual={''.join(p.itertext()):p.find('.//w:rPr/w:color',NS).get(W+'val') for p in effective_document(doc,styles).iter(W+'p')} assert actual['Inline']!='ff0000' and actual['Block']=='0000ff' finally:dialog.close() @pytest.mark.parametrize('bad',['color:#gggggg','color:12pt','font-size:"10pt"','font-style:italic normal','font:garbage','text-align:"left"']) def test_invalid_css_keeps_last_valid_core_values(qt_application,tmp_path,bad): payload=normalize_payload({'css':'p {color:red;font-size:20pt;font-style:italic;text-align:center;'+bad+';}'}) rule=payload['rules']['paragraph'] assert rule['font_color']=='#ff0000' and rule['font_size']==20 and rule['italic'] and rule['alignment']=='center' assert browser(qt_application,tmp_path,payload,'Fallback',"(()=>{const s=getComputedStyle(document.querySelector('p'));return [s.color,s.fontStyle,s.textAlign]})()") == ['rgb(255, 0, 0)','italic','center'] @pytest.mark.parametrize('engine',ENGINES) def test_inner_quote_and_container_list_cascade(tmp_path,engine): source='- Item\n\n > Quote\n\n- Second' rules={'blockquote':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}} doc,styles=parts(export_markdown_to_docx(source,tmp_path/'inner.docx',engine=engine,style_rules=rules)) actual={''.join(p.itertext()):p.find('.//w:rPr/w:color',NS).get(W+'val') for p in effective_document(doc,styles).iter(W+'p')} assert actual=={'Item':'0000ff','Quote':'ff0000','Second':'0000ff'} styles.find("w:style[@w:styleId='MDHelperBlockquote']/w:rPr/w:color",NS).set(W+'val','008000') quote=next(p for p in effective_document(doc,styles).iter(W+'p') if ''.join(p.itertext())=='Quote') assert quote.find('.//w:rPr/w:color',NS).get(W+'val')=='008000' for css,color in [('blockquote {color:red;} li {color:blue;}','0000ff'),('blockquote p {color:red;} li {color:blue;}','ff0000')]: payload=normalize_payload({'css':css}) doc,styles=parts(export_markdown_to_docx('> - First\n>\n> - Second',tmp_path/'outer.docx',engine=engine,style_rules=payload['rules'])) assert all(p.find('.//w:rPr/w:color',NS).get(W+'val')==color for p in effective_document(doc,styles).iter(W+'p')) def test_nested_decoration_cancellation_and_wrapping(qt_application,tmp_path): rules={'strong':{'underline':True,'strike':True},'emphasis':{'underline':False}} payload=normalize_payload({'rules':rules}) source='**Outer *Inner words still wrap* outer**' actual=browser(qt_application,tmp_path,payload,source,"""(()=>{ const p=document.querySelector('p');p.style.width='80px'; return {leaves:[...p.querySelectorAll('[data-mdh-text]')].map(e=>[e.textContent,getComputedStyle(e).textDecorationLine]), outer:getComputedStyle(p.querySelector('strong')).textDecorationLine, inner:getComputedStyle(p.querySelector('em')).textDecorationLine, width:p.scrollWidth}; })()""") assert actual['outer']=='none' and actual['inner']=='none' assert actual['leaves']==[['Outer ','underline line-through'],['Inner words still wrap','line-through'],[' outer','underline line-through']] assert actual['width']<=81 for engine in ENGINES: doc,styles=parts(export_markdown_to_docx(source,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules'])) run=next(r for r in effective_document(doc,styles).iter(W+'r') if ''.join(r.itertext())=='Inner words still wrap') assert run.find('w:rPr/w:u',NS).get(W+'val')=='none' assert run.find('w:rPr/w:strike',NS).get(W+'val')=='1' def test_switching_builtin_preset_refreshes_style_panel(qt_application,tmp_path,monkeypatch): from PySide6.QtCore import QSettings,Qt from mdhelper import main_window monkeypatch.setattr(main_window,'QSettings',lambda *_:QSettings(str(tmp_path/'settings.ini'),QSettings.Format.IniFormat)) window=main_window.MainWindow(None,app_root=tmp_path) try: window._set_document_style('default');window.show_style_panel();panel=window.style_panel;panel.refresh(force=True) window._set_document_style('serif');panel.refresh() item=next(panel.listing.item(i) for i in range(panel.listing.count()) if panel.listing.item(i).data(Qt.ItemDataRole.UserRole)=='paragraph') assert item.font().family()=='SimSun' finally:window.close() def test_text_decoration_keeps_code_math_entities_and_raw_content(qt_application,tmp_path): from mdhelper.reader_decoration import wrap_decoration_text raw='
<x>\nline 2
x & y
A --> B
' assert wrap_decoration_text(raw)==raw wrapped=wrap_decoration_text('

A & B C

') assert wrap_decoration_text(wrapped)==wrapped payload=normalize_payload({'rules':{'strong':{'underline':True},'emphasis':{'underline':False},'code_block':{'underline':True}}}) assert browser(qt_application,tmp_path,payload,'**Outer *Inner***\n\n```text\nCode\n```', "getComputedStyle(document.querySelector('pre')).textDecorationLine")=='underline' @pytest.mark.parametrize('conditional',[False,True]) def test_nested_decoration_preserves_advanced_css_effects(qt_application,tmp_path,conditional): css='strong {text-decoration:underline;} em {text-decoration:none;} .reader a {text-decoration:line-through wavy red;}' if conditional:css+=' @media screen {.reader a {text-decoration-line:underline;}}' payload=normalize_payload({'css':css}) assert browser(qt_application,tmp_path,payload,'**Outer *Inner*** [Decor](#link)', "(()=>{const s=getComputedStyle(document.querySelector('a [data-mdh-text]'));return [s.textDecorationLine,s.textDecorationStyle,s.textDecorationColor]})()") == ['underline' if conditional else 'line-through','wavy','rgb(255, 0, 0)'] @pytest.mark.parametrize('kind',['table','code','nested']) @pytest.mark.parametrize('success',[False,True]) def test_copy_buttons_report_failure_and_copy_only_own_cells(qt_application,tmp_path,kind,success): import json,time from PySide6.QtWebEngineCore import QWebEnginePage from mdhelper.markdown_renderer import MarkdownRenderer page=QWebEnginePage();loaded=[] def wait(condition): end=time.monotonic()+15 while not condition() and time.monotonic()Outer
InnerAInnerB
Last' if kind=='nested' else TABLE selector='.copy-code-button' if kind=='code' else '.copy-table-button' try: page.loadFinished.connect(loaded.append);page.setHtml(MarkdownRenderer(tmp_path).render_source(source,tmp_path/'copy.md'));wait(lambda:loaded) js("(()=>{Object.defineProperty(navigator,'clipboard',{value:{writeText:async()=>{throw Error('denied')}}});document.execCommand=()=>{window.copied=document.querySelector('textarea').value;return "+str(success).lower()+"};document.querySelector('"+selector+"').click();return true})()") wait(lambda:js("document.querySelector('"+selector+"').textContent") in ('已复制','复制失败,请重试')) assert js("document.querySelector('"+selector+"').textContent")==('已复制' if success else '复制失败,请重试') copied=js('window.copied') if kind=='nested': assert copied.count('InnerA')==1 and copied.count('InnerB')==1 assert len(copied.split('\n'))==1 and len(copied.split('\t'))==2 elif kind=='code':assert copied.strip()=='Block' else:assert copied=='Head\tDescription\nAlpha\tFirst\nBeta\tSecond' assert js("document.querySelectorAll('textarea').length")==0 finally:page.deleteLater()