Files
md2pdf/tests/test_md2doc_blocks.py

75 lines
2.2 KiB
Python

"""Tests for block-level element renderers."""
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
from docx import Document
from bs4 import BeautifulSoup
from md2doc import STYLES, _render_table, _render_pre, _render_blockquote, _render_hr
W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def get_doc_xml(doc):
tmp = Path(__file__).parent / "_tmp_blocks.docx"
doc.save(tmp)
try:
with zipfile.ZipFile(tmp) as z:
return ET.fromstring(z.read("word/document.xml"))
finally:
tmp.unlink()
def test_table_renders_with_header_shading():
html = """
<table>
<thead><tr><th>Name</th><th>Value</th></tr></thead>
<tbody>
<tr><td>A</td><td>1</td></tr>
</tbody>
</table>
"""
doc = Document()
node = BeautifulSoup(html, "html.parser").find("table")
_render_table(doc, node, style=STYLES["elegant"])
root = get_doc_xml(doc)
trs = list(root.iter(f"{{{W_NS}}}tr"))
assert len(trs) == 2
shds = list(root.iter(f"{{{W_NS}}}shd"))
assert len(shds) >= 2 # at least 2 header cells
def test_pre_renders_with_shading():
html = '<pre><code>print("hello")</code></pre>'
doc = Document()
node = BeautifulSoup(html, "html.parser").find("pre")
_render_pre(doc, node, style=STYLES["elegant"])
root = get_doc_xml(doc)
shds = list(root.iter(f"{{{W_NS}}}shd"))
assert len(shds) >= 1
texts = [t.text for t in root.iter(f"{{{W_NS}}}t")]
assert any('print' in t for t in texts)
def test_blockquote_renders_with_indent_and_italic():
html = "<blockquote>A quoted passage</blockquote>"
doc = Document()
node = BeautifulSoup(html, "html.parser").find("blockquote")
_render_blockquote(doc, node, style=STYLES["elegant"])
root = get_doc_xml(doc)
italic_el = list(root.iter(f"{{{W_NS}}}i"))
assert len(italic_el) >= 1
indents = list(root.iter(f"{{{W_NS}}}ind"))
assert len(indents) >= 1
def test_hr_renders_as_paragraph_with_bottom_border():
html = "<hr/>"
doc = Document()
node = BeautifulSoup(html, "html.parser").find("hr")
_render_hr(doc, node, style=STYLES["elegant"])
root = get_doc_xml(doc)
bottoms = list(root.iter(f"{{{W_NS}}}bottom"))
assert len(bottoms) >= 1