#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.13"
# dependencies = ["pytest", "playwright"]
# ///
"""
Browser tests for markdown-to-rich-text.html: drive a real Chromium, then read back what landed on the clipboard.
uv run tests/test_markdown_to_rich_text.py # self-contained
uv run --with playwright playwright install chromium # once, to get the browser
The page loads marked and DOMPurify from jsdelivr, so these need network access.
"""
import sys
from pathlib import Path
import pytest
playwright_api = pytest.importorskip("playwright.sync_api")
PAGE = (Path(__file__).resolve().parent.parent / "markdown-to-rich-text.html").as_uri()
SAMPLE = """# Title
## Section
Some **bold**, *italic* and `inline code`, a [web link](https://example.com) and a [repo link](src/app.ts#L42).
- [x] done
- [ ] to do
| Name | Value |
| --- | :---: |
| a | 1 |
```python
print("hi")
```
> quoted
"""
READ_CLIPBOARD = """async () => {
const [item] = await navigator.clipboard.read();
const get = async t => item.types.includes(t) ? (await item.getType(t)).text() : null;
return { html: await get("text/html"), text: await get("text/plain") };
}"""
@pytest.fixture(scope="module")
def browser():
with playwright_api.sync_playwright() as p:
try:
b = p.chromium.launch()
except Exception as e:
pytest.skip(f"Chromium not installed: {e}")
yield b
b.close()
@pytest.fixture
def page(browser):
ctx = browser.new_context(permissions=["clipboard-read", "clipboard-write"])
pg = ctx.new_page()
pg.goto(PAGE) # module scripts, CDN imports included, run before the load event goto waits for
yield pg
ctx.close()
def copied(page, markdown):
page.fill("#md", markdown)
page.click("#copy")
page.wait_for_selector("#status:has-text('Copied')")
return page.evaluate(READ_CLIPBOARD)
def test_copy_puts_formatted_html_and_markdown_on_the_clipboard(page):
clip = copied(page, SAMPLE)
html = clip["html"]
assert clip["text"].replace("\r\n", "\n") == SAMPLE
assert "
start more
' def test_single_newlines_are_line_breaks(page): html = copied(page, "**Traveller:** me\n**Purpose:** a workshop\n")["html"] assert "Traveller: meOne sentence.\nAnother sentence.
" in html and "New paragraph.
" in html assert page.inner_text("#preview p:first-child") == "One sentence. Another sentence." # the newline renders as a space assert "item\ncontinued" in html and "Hardbody
' in html and 'body
" in html page.reload() assert page.input_value("#size") == "" # the choice is remembered if __name__ == "__main__": sys.exit(pytest.main([__file__, "-v"]))