Files
MDHelper/tests/test_table_presentation.py

103 lines
6.7 KiB
Python

"""Table appearance, editable settings, and all three Word export engines."""
import pytest
from mdhelper.style_sync import normalize_payload
from mdhelper.style_catalog import explicit_rules
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS
from mdhelper.table_style import TABLE_OPTIONS, HEADER_COLOR
from test_style_regressions import browser, parts
SOURCE = '| Stage | Description |\n|---|---|\n| A | First |\n| B | Second |\n| C | Third |'
RULE = {'table_border_mode': 'horizontal', 'table_banded_rows': True, 'table_stripe_color': '#eaf3fa',
'table_repeat_header': False, 'table_allow_row_split': True, 'cell_padding': 6,
'border_color': '#aabbcc', 'border_width': .75}
def test_table_controls_css_roundtrip_and_legacy_values(qt_application):
legacy = {'table': {'cell_padding': 0, 'border_color': '#123456', 'font_size': 20, 'font_size_unit': 'pt'}}
assert normalize_payload({'rules': legacy})['rules'] == legacy
dialog = DocumentStyleEditorDialog({'rules': legacy})
try:
dialog.select_target('table')
for field, box in (('table_border_mode', dialog.table_border_mode_box), ('table_banded_rows', dialog.table_banded_rows_box),
('table_repeat_header', dialog.table_repeat_header_box), ('table_allow_row_split', dialog.table_allow_row_split_box)):
box.setCurrentIndex(box.findData(RULE[field]))
dialog.table_stripe_color_edit.setText(RULE['table_stripe_color'])
dialog.table_stripe_color_edit.editingFinished.emit()
payload = dialog.style_payload()
assert payload['rules']['table'] == {**legacy['table'], **{k: v for k, v in RULE.items() if k in TABLE_OPTIONS}}
assert normalize_payload(payload) == payload
assert not (set(TABLE_OPTIONS) & explicit_rules(payload['rules'])['table_cell'].keys())
dialog.extra_css_edit.setPlainText(payload['css'].replace('horizontal', 'none').replace('table-repeat-header: false', 'table-repeat-header: true'))
dialog._sync_from_css()
assert dialog.table_border_mode_box.currentData() == 'none'
assert dialog.table_repeat_header_box.currentData() is True
finally:
dialog.close()
@pytest.mark.parametrize('mode', ['grid', 'horizontal', 'none'])
def test_table_borders_stripes_and_header_in_browser(qt_application, tmp_path, mode):
payload = normalize_payload({'rules': {'table': {**RULE, 'table_border_mode': mode}}})
actual = browser(qt_application, tmp_path, payload, SOURCE, """(()=>{
const cells = [...document.querySelectorAll('tbody td:first-child')];
const s = getComputedStyle(cells[0]);
return [s.borderLeftStyle, s.borderTopStyle, cells.map(c=>getComputedStyle(c).backgroundColor),
getComputedStyle(document.querySelector('th')).backgroundColor];
})()""")
assert actual[0] == ('solid' if mode == 'grid' else 'none')
assert actual[1] == ('none' if mode == 'none' else 'solid')
assert actual[2] == ['rgba(0, 0, 0, 0)', 'rgb(234, 243, 250)', 'rgba(0, 0, 0, 0)']
assert actual[3] == 'rgb(241, 245, 249)'
def test_table_small_width_long_content_and_copy_button(qt_application, tmp_path):
source = SOURCE + '\n\n| URL |\n|---|\n| https://example.com/' + 'longword' * 30 + ' |'
actual = browser(qt_application, tmp_path, normalize_payload({}), source, """(()=>{
const reader=document.querySelector('.reader'); reader.style.width='280px'; reader.style.padding='0';
const button=document.querySelector('.copy-table-button'); button.focus();
const table=document.querySelector('table'), scroll=document.querySelector('.table-scroll');
const tools=document.querySelector('.table-tools');
return {widths:[...document.querySelectorAll('.table-scroll')].map(e=>[e.clientWidth,e.scrollWidth]),
opacity:getComputedStyle(tools).opacity, outside:button.getBoundingClientRect().bottom<=table.getBoundingClientRect().top,
toolbarSpace:scroll.getBoundingClientRect().top-table.closest('.table-wrapper').getBoundingClientRect().top};
})()""")
assert all(width <= 281 and scroll <= width + 1 for width, scroll in actual['widths'])
assert actual['opacity'] == '1' and actual['outside'] and actual['toolbarSpace'] == 0
def test_explicit_cell_background_and_dark_default_stripes(qt_application, tmp_path):
payload = normalize_payload({'rules': {'table': {'table_banded_rows': True}, 'table_cell': {'background_color': '#ffeecc'}}})
assert browser(qt_application, tmp_path, payload, SOURCE,
"getComputedStyle(document.querySelector('tbody tr:nth-child(2) td')).backgroundColor") == 'rgb(255, 238, 204)'
payload = normalize_payload({'rules': {'table': {'table_banded_rows': True}}})
assert browser(qt_application, tmp_path, payload, SOURCE,
"(()=>{document.documentElement.dataset.theme='dark';return getComputedStyle(document.querySelector('tbody tr:nth-child(2) td')).backgroundColor})()") == 'rgb(37, 44, 55)'
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
@pytest.mark.parametrize('custom', [False, True])
def test_word_table_styles_pagination_and_editable_backgrounds(tmp_path, engine, custom):
rules = {'table': RULE, 'table_head': {'background_color': '#ddeeff'}} if custom else {}
doc, styles = parts(export_markdown_to_docx(SOURCE, tmp_path / 'table.docx', engine=engine, style_rules=rules))
style = styles.find("w:style[@w:styleId='MDHelperTable']", NS)
assert style is not None
assert style.find('w:tblPr/w:tblStyleRowBandSize', NS).get(W+'val') == '1'
rows = doc.findall('.//w:tbl/w:tr', NS)
assert [r.find('w:trPr/w:tblHeader', NS).get(W+'val') for r in rows] == (['0']*4 if custom else ['1','0','0','0'])
assert all(r.find('w:trPr/w:cantSplit', NS).get(W+'val') == ('0' if custom else '1') for r in rows)
borders = style.find('w:tblPr/w:tblBorders', NS)
assert borders.find(W+'insideV').get(W+'val') == ('none' if custom else 'single')
assert borders.find(W+'insideH').get(W+'val') == 'single'
header = style.find("w:tblStylePr[@w:type='firstRow']/w:tcPr/w:shd", NS)
assert header.get(W+'fill') == ('ddeeff' if custom else HEADER_COLOR[1:])
stripe = style.find("w:tblStylePr[@w:type='band2Horz']/w:tcPr/w:shd", NS)
assert (stripe is not None) == custom
if custom: assert stripe.get(W+'fill') == 'eaf3fa'
assert not doc.findall('.//w:tcPr/w:shd', NS)
assert not doc.findall('.//w:tblPr/w:tblBorders', NS)
assert styles.find("w:style[@w:styleId='MDHelperTableHead']/w:pPr/w:shd", NS) is None
assert doc.find('.//w:tblPr/w:tblLayout', NS).get(W+'type') == 'autofit'
assert all(tc.get(W+'type') == 'auto' for tc in doc.findall('.//w:tcPr/w:tcW', NS))