Files
MDHelper/tests/test_style_sync.py
T

235 lines
11 KiB
Python

import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import zipfile
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QDialogButtonBox
from mdhelper.style_sync import analyze_css, patch_core, source_from_payload, normalize_payload, render_css
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.docx_exporter import export_markdown_to_docx
@pytest.fixture
def app():
return QApplication.instance() or QApplication([])
def test_graphical_changes_update_full_css_without_losing_extensions(app):
source = '.reader p { font-size: 12pt; border: 1px solid red; }\n@media print { p { background: #eee; } }'
dialog = DocumentStyleEditorDialog({"css": source})
try:
assert dialog.font_size_spin.value() == 12
dialog.font_size_spin.setValue(14)
payload = dialog.style_payload()
assert payload["css_sync_version"] == 1
assert payload["rules"]["paragraph"]["font_size"] == 14
assert 'border: 1px solid red;' in payload["css"]
assert 'p:not' not in payload["css"] # Update the authored object rule in place.
assert '@media print { p { background: #eee; } }' in payload["css"]
reopened = DocumentStyleEditorDialog(payload)
try:
assert reopened.style_payload() == payload
finally:
reopened.close()
finally:
dialog.close()
def test_css_to_controls_immediate_save_and_undo(app):
dialog = DocumentStyleEditorDialog()
try:
dialog.extra_css_edit.setPlainText('p {font-size:10.5pt; font-weight:700; text-indent:2em; color:rgb(255,0,0); margin:0;}')
# Saving before the debounce timer fires must use the new CSS.
rules = dialog.style_payload()["rules"]["paragraph"]
assert rules["font_size"] == 10.5 and rules["bold"] is True
assert rules["font_color"] == "#ff0000"
assert dialog.font_size_spin.value() == 10.5
assert dialog.bold_checkbox.checkState() == Qt.CheckState.Checked
assert dialog.indent_mode_combo.currentData() == "first"
assert dialog.space_before_spin.value() == 0
before = dialog.extra_css_edit.toPlainText()
dialog.font_size_spin.setValue(16)
dialog.extra_css_edit.undo()
assert dialog.style_payload()["css"] == before
assert dialog.font_size_spin.value() == 10.5
finally:
dialog.close()
def test_invalid_css_does_not_clobber_previous_rules(app):
dialog = DocumentStyleEditorDialog({"css": 'p {font-size:14pt;} '})
try:
dialog.extra_css_edit.setPlainText('p {font-size:')
assert not dialog._sync_from_css()
assert dialog.rules["paragraph"]["font_size"] == 14
assert not dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
with pytest.raises(ValueError):
dialog.style_payload()
dialog.extra_css_edit.setPlainText('p {font-size:16pt;}')
assert dialog.style_payload()["rules"]["paragraph"]["font_size"] == 16
assert dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
finally:
dialog.close()
def test_cascade_grouped_selectors_important_and_preserved_comments():
source = '/* keep ; } */ p,h1,.custom { font-size:12pt !important; background:url("a;b.png"); } p {font-size:20px;}'
before = analyze_css(source).rules["paragraph"]
assert before["font_size"] == 12
patched = patch_core(source, "paragraph", before, {**before, "font_size": 18})
result = analyze_css(patched)
assert result.rules["paragraph"]["font_size"] == 18
assert result.rules["h1"]["font_size"] == 12
assert 'background:url("a;b.png");' in patched
assert '/* keep ; } */' in patched and '.custom' in patched
assert 'font-size: 18pt !important' in patched
def test_margin_shorthand_change_one_side_preserves_other_sides():
source = 'p {margin: 1pt 2pt 3pt 4pt; box-shadow:0 1px 2px #333;}'
before = analyze_css(source).rules["paragraph"]
updated = patch_core(source, "paragraph", before, {**before, "space_before_value": 0})
rule = analyze_css(updated).rules["paragraph"]
assert rule["space_before_value"] == 0
assert rule["right_indent_value"] == 2
assert rule["space_after_value"] == 3 and rule["left_indent_value"] == 4
assert 'box-shadow:0 1px 2px #333;' in updated
def test_font_shorthand_and_individual_override():
source = 'p {font: italic bold 14pt/1.5 "Times New Roman", "宋体"; color: navy;}'
rule = analyze_css(source).rules["paragraph"]
assert rule["font_size"] == 14 and rule["bold"] and rule["italic"]
assert rule["chinese_font_family"] == "宋体" and rule["line_height_value"] == 1.5
result = analyze_css(patch_core(source, "paragraph", rule, {**rule, "font_size": 16}))
assert result.rules["paragraph"]["font_size"] == 16
assert result.rules["paragraph"]["bold"] and result.rules["paragraph"]["italic"]
def test_unsupported_values_remain_css_and_do_not_reappear_as_stale_controls():
source = 'p {font-size:12pt; font:var(--other); font-size:calc(10pt + 2vw); color:red;} @media screen {p {color:blue;}}'
result = analyze_css(source)
assert not result.errors
assert "font_size" not in result.rules["paragraph"]
assert result.notes
changed = patch_core(source, "paragraph", result.rules["paragraph"], {**result.rules["paragraph"], "font_color": "#008000"})
assert 'font-size:calc(10pt + 2vw)' in changed
assert '@media screen {p {color:blue;}}' in changed
assert analyze_css(changed).rules["paragraph"]["font_color"] == "#008000"
@pytest.mark.parametrize("field,value", [("chinese_font_family", "宋体"), ("english_font_family", "Arial")])
def test_single_language_font_and_word_only_modes_roundtrip(field, value):
rule = {field: value, "line_spacing_mode": "at_least", "line_height_value": 22, "contextual_spacing": False,
"keep_with_next": False, "keep_lines_together": True, "page_break_before": True, "widow_control": False}
migrated = normalize_payload({"rules": {"paragraph": rule}})
assert migrated["rules"]["paragraph"] == rule
assert normalize_payload(migrated) == migrated
def test_reset_only_removes_core_leaving_extensions_and_other_targets(app):
dialog = DocumentStyleEditorDialog({"css": 'p,h2 {font-size:14pt; border:1px solid blue;} p {color:red;}'} )
try:
dialog._reset_current_rule()
payload = dialog.style_payload()
assert "paragraph" not in payload["rules"]
assert payload["rules"]["h2"]["font_size"] == 14
assert "border:1px solid blue" in payload["css"]
finally:
dialog.close()
def test_valid_nested_and_conditional_extensions_are_preserved():
source = 'p {color: red; &:hover {color: blue;}} @supports (display:grid) {p{display:grid;}}'
result = analyze_css(source)
assert not result.errors and result.rules["paragraph"]["font_color"] == "#ff0000"
changed = patch_core(source, "paragraph", result.rules["paragraph"], {"font_color": "#008000"})
assert '&:hover {color: blue;}' in changed and '@supports' in changed
@pytest.mark.parametrize("engine", ["builtin", "python-docx", "pandoc"])
def test_css_edits_reach_word_via_saved_rules(tmp_path, engine):
payload = normalize_payload({"css": 'p {font-size:14pt;color:#123456; margin:0; text-align:center; line-height:24pt; --mdhelper-line-spacing-mode:at-least;}'} )
docx = export_markdown_to_docx("CSS 同步到 Word", tmp_path / f"{engine}.docx", engine=engine, style_rules=payload["rules"])
from lxml import etree
with zipfile.ZipFile(docx) as archive:
doc = etree.fromstring(archive.read("word/document.xml"))
from docx_assertions import effective_document
doc = effective_document(doc, etree.fromstring(archive.read('word/styles.xml')))
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
w = "{" + ns["w"] + "}"
assert doc.find(".//w:sz", ns).get(w + "val") == "28"
assert doc.find(".//w:color", ns).get(w + "val") == "123456"
assert doc.find(".//w:jc", ns).get(w + "val") == "center"
assert doc.find(".//w:spacing", ns).get(w + "lineRule") == "atLeast"
def test_contextual_helper_materialization_and_legacy_extra_css_override():
source = source_from_payload({"rules": {"paragraph": {"font_size": 12, "font_size_unit": "pt"}},
"extra_css": '.reader p {font-size:14pt; --mdhelper-contextual-spacing:true;}'} )
result = analyze_css(source)
assert result.rules["paragraph"]["font_size"] == 14
rendered = render_css(source, result.rules)
assert '--reader-math-font-size: 14pt' in rendered and 'margin-bottom: 0' in rendered
def test_debounced_typing_keeps_css_text_and_cursor(app):
from PySide6.QtTest import QTest
dialog = DocumentStyleEditorDialog()
try:
dialog.tabs.setCurrentIndex(1)
source = 'p { font-size: 15pt; color: blue; } /* authored */'
dialog.extra_css_edit.setPlainText(source)
cursor = dialog.extra_css_edit.textCursor()
cursor.setPosition(9)
dialog.extra_css_edit.setTextCursor(cursor)
QTest.qWait(450)
assert dialog.font_size_spin.value() == 15
assert dialog.extra_css_edit.toPlainText() == source
assert dialog.extra_css_edit.textCursor().position() == 9
finally:
dialog.close()
def test_style_file_roundtrip_reader_and_word_integration(app, tmp_path, monkeypatch):
from PySide6.QtCore import QSettings
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:
source = 'p {font-size:14pt; color:red; border:1px solid blue;}'
window.custom_document_styles['custom:sync'] = window._normalize_document_style_payload({'name': '同步测试', 'css': source})
style_file = tmp_path / 'test.mdhelper-style'
window._write_document_style_file(style_file, 'custom:sync')
imported = window._import_document_style_file(style_file)
payload = window._style_payload_for_id(imported)
assert payload['css'] == source and payload['css_sync_version'] == 1
assert payload['rules']['paragraph']['font_size'] == 14
window.document_style_id = imported
assert 'border:1px solid blue' in window._document_style_css()
markdown = tmp_path / 'test.md'
markdown.write_text('同步正文', encoding='utf-8')
window.current_file = markdown
docx_path = window.export_docx_to_path(tmp_path / 'test.docx')
with zipfile.ZipFile(docx_path) as archive:
xml = archive.read('word/styles.xml').decode()
assert 'w:sz w:val="28"' in xml and 'w:color w:val="ff0000"' in xml
finally:
window.close()
def test_selector_formatting_and_case_sensitive_custom_properties():
source = '.reader p:not(:where( li p,blockquote p,.admonition p,th p,td p )) {font-size:14pt; --MDHELPER-contextual-spacing:true;}'
result = analyze_css(source)
assert result.rules["paragraph"]["font_size"] == 14
assert "contextual_spacing" not in result.rules["paragraph"]
assert analyze_css('p {font-size:;}').errors
def test_reset_can_remove_unrepresentable_core_values():
source = 'p {font-size:calc(10pt + 1vw); border:1px solid red; font:var(--dynamic);}'
changed = patch_core(source, "paragraph", {}, {}, reset=True)
assert 'font' not in changed and 'border:1px solid red' in changed