from __future__ import annotations
import doctest
import os
import re
import textwrap
import traceback
from pathlib import Path
import pytest
SITE = Path(__file__).parent / "site"
FENCE = re.compile(
r"^(?P<indent>[ \t]*)(?P<ticks>`{3,})(?P<info>[^\n`]*)\n(?P<body>.*?)^(?P=indent)(?P=ticks)[ \t]*$",
re.M | re.S,
)
LANGS = {"python": "python", "py": "python", "python3": "python", "pycon": "pycon"}
FLAGS = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
def blocks(text: str):
for m in FENCE.finditer(text):
info = m["info"].strip().strip("{}").split()
lang = LANGS.get(info[0].lstrip(".")) if info else None
if lang and "notest" not in info:
line = text.count("\n", 0, m.start()) + 2 yield lang, line, textwrap.dedent(m["body"])
def pytest_collect_file(file_path: Path, parent):
if file_path.suffix == ".md" and file_path.is_relative_to(SITE):
found = list(blocks(file_path.read_text()))
if found:
return MarkdownPage.from_parent(parent, path=file_path, found=found)
return None
class MarkdownPage(pytest.File):
def __init__(self, *, found, **kw):
super().__init__(**kw)
self.found = found
def collect(self):
yield MarkdownExamples.from_parent(self, name="examples", found=self.found)
class ExampleError(Exception):
class MarkdownExamples(pytest.Item):
def __init__(self, *, found, **kw):
super().__init__(**kw)
self.found = found
def runtest(self):
tmp = self.config._tmp_path_factory.mktemp("docs-example") globs = {"__name__": "__docs__"}
cwd = os.getcwd()
os.chdir(tmp)
try:
for lang, line, body in self.found:
where = f"{self.path.relative_to(SITE.parent.parent)}:{line}"
if lang == "python":
try:
code = compile(
"\n" * (line - 1) + body,
str(self.path),
"exec",
dont_inherit=True,
)
exec(code, globs) except Exception:
raise ExampleError(
f"{where}\n{traceback.format_exc()}"
) from None
else:
test = doctest.DocTestParser().get_doctest(
body, globs, where, str(self.path), line - 1
)
out: list[str] = []
runner = doctest.DocTestRunner(optionflags=FLAGS)
runner.run(test, out=out.append, clear_globs=False)
globs.update(test.globs) if runner.failures:
raise ExampleError("".join(out))
finally:
os.chdir(cwd)
def repr_failure(self, excinfo):
if isinstance(excinfo.value, ExampleError):
return str(excinfo.value)
return super().repr_failure(excinfo)
def reportinfo(self):
return self.path, 0, f"examples in {self.path.name}"