from email import message_from_bytes, policy
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import base64
import pytest
from mdhelper.mhtml_export import portable_archive
def test_archive_embeds_fonts_and_uses_internal_resource_ids(tmp_path):
folder = tmp_path / ("long folder " * 4).strip()
folder.mkdir()
css_path = folder / "style.css"
font = folder / "字体.woff2"
font.write_bytes(b"font data")
image_url = (folder / "image.png").as_uri()
message = MIMEMultipart("related", type="text/html")
html = MIMEText(f'
text
', "html", "utf-8") html["Content-Location"] = (folder / "index.html").as_uri() css = MIMEText('@font-face{font-family:Demo;src:url("字体.woff2") format("woff2"),url(missing.woff)}', "css", "utf-8") css["Content-Location"] = css_path.as_uri() image = MIMEApplication(b"image bytes", "octet-stream") image["Content-Location"] = image_url for part in (html, css, image): message.attach(part) raw = portable_archive(message.as_bytes(policy=policy.SMTP.clone(max_line_length=0))) archive = message_from_bytes(raw, policy=policy.default) parts = archive.get_payload() body = parts[0].get_payload(decode=True).decode() css_text = parts[1].get_payload(decode=True).decode() assert 'src="cid:mdhelper-' in body and 'href="cid:mdhelper-' in body assert image_url not in body and 'text
' in body assert base64.b64encode(font.read_bytes()).decode() in css_text assert 'url("data:,")' in css_text assert str(parts[0]["Content-Location"]) == html["Content-Location"] assert b"=?utf-8?" not in raw def test_unarchived_remote_css_dependency_fails_explicitly(): message = MIMEMultipart("related", type="text/html") css = MIMEText('@font-face{src:url(https://example.invalid/font.woff2)}', "css", "utf-8") css["Content-Location"] = "https://example.invalid/style.css" message.attach(css) with pytest.raises(ValueError, match="font.woff2"): portable_archive(message.as_bytes())