1"""Run a package's documentation examples, the python files under ``docs/examples/``.
3An example is a file a page shows whole or by named section through
4the snippets extension, so the code a reader sees and the code that
5runs are one file. This plugin, loaded through the ``pytest11`` entry
6point, collects every ``docs/examples/**/*.py`` pytest is pointed at
7as one test item per file, executed whole in a fresh module namespace
8under its own path, so a failure's traceback names the example's file
9and line. The python extension's examples runner, the function it
10answers ``python.examples.runner`` with, points pytest at a package's
11examples directory. A package's own setup around an example, a
12registry capture or a recording mode, is its
13``docs/examples/conftest.py``'s business through the ``example``
14marker every item carries; the conftest itself is never an example.
15"""
29 from collections.abc import Iterator
31#: The marker every example item carries, for a conftest's hooks.
36 """Register the marker, so a strict-markers run accepts it."""
37 config.addinivalue_line(
38 "markers", f"{MARKER}: a documentation example, a file under docs/examples/"
39 )
43 file_path: Path, parent: pytest.Collector
44) -> pytest.Collector | None:
45 """Collect an example file; every other file is another collector's."""
46 if not is_example(file_path):
47 return None
53 module_path: Path, parent: pytest.Collector
54) -> pytest.Collector | None:
55 """Keep pytest's python collector off an example.
57 Pytest collects a file named on its command line as a test module
58 whatever its name, and one whose name matches ``python_files`` in
59 a directory it walks. Either way it would import the example
60 outside the setup its conftest gives it, and run the example's
61 ``test_*`` functions as tests of the workspace: a function showing
62 a reader how to test a tasks file then runs the workspace's own
63 gate from inside it. The example stays this plugin's, run whole.
64 """
65 if not is_example(module_path):
66 return None
71 """One example file: one item, the file run whole."""
80 """An example as pytest's python collector sees it: nothing to collect."""
87 """The run of one example file in a fresh module namespace."""
90 """Execute the file under its own path; a raise is the failure, at its line."""
91 source = self.path.read_text(encoding="utf-8")
92 code = compile(source, str(self.path), "exec")
93 # A real module in sys.modules, not a bare dict: dataclasses
94 # resolving string annotations and typing's evaluation look
95 # the defining module up by name.
96 module = types.ModuleType(f"docs_example_{self.name.replace('-', '_')}")
97 module.__file__ = str(self.path)
98 sys.modules[module.__name__] = module
99 try:
100 exec(code, module.__dict__)
101 finally:
102 del sys.modules[module.__name__]
105 """The file, its first line, and the name the report prints."""