|
| 1 | +"""Allows you to use `pytest docs` to run the examples.""" |
| 2 | + |
| 3 | +import pathlib |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +examples_to_skip = { |
| 10 | + "101_example.py", |
| 11 | + "__init__.py", |
| 12 | + "simple_rag_with_filter.py", |
| 13 | + "mcp_example.py", |
| 14 | + "client.py", |
| 15 | +} |
| 16 | + |
| 17 | + |
| 18 | +def pytest_terminal_summary(terminalreporter, exitstatus, config): |
| 19 | + # Append the skipped examples if needed. |
| 20 | + if len(examples_to_skip) == 0: |
| 21 | + return |
| 22 | + |
| 23 | + terminalreporter.ensure_newline() |
| 24 | + terminalreporter.section("Skipped Examples", sep="=", blue=True, bold=True) |
| 25 | + terminalreporter.line( |
| 26 | + f"Examples with the following names were skipped because they cannot be easily run in the pytest framework; please run them manually:\n{'\n'.join(examples_to_skip)}" |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +# This doesn't replace the existing pytest file collection behavior. |
| 31 | +def pytest_collect_file(parent: pytest.Dir, file_path: pathlib.PosixPath): |
| 32 | + # Do a quick check that it's a .py file in the expected `docs/examples` folder. We can make |
| 33 | + # this more exact if needed. |
| 34 | + if ( |
| 35 | + file_path.suffix == ".py" |
| 36 | + and "docs" in file_path.parts |
| 37 | + and "examples" in file_path.parts |
| 38 | + ): |
| 39 | + # Skip this test. It requires additional setup. |
| 40 | + if file_path.name in examples_to_skip: |
| 41 | + return |
| 42 | + |
| 43 | + return ExampleFile.from_parent(parent, path=file_path) |
| 44 | + |
| 45 | + # TODO: Support running jupyter notebooks: |
| 46 | + # - use nbmake or directly use nbclient as documented below |
| 47 | + # - install the nbclient package |
| 48 | + # - run either using python api or jupyter execute |
| 49 | + # - must replace background processes |
| 50 | + # if file_path.suffix == ".ipynb": |
| 51 | + # return ExampleFile.from_parent(parent, path=file_path) |
| 52 | + |
| 53 | + |
| 54 | +class ExampleFile(pytest.File): |
| 55 | + def collect(self): |
| 56 | + return [ExampleItem.from_parent(self, name=self.name)] |
| 57 | + |
| 58 | + |
| 59 | +class ExampleItem(pytest.Item): |
| 60 | + def __init__(self, **kwargs): |
| 61 | + super().__init__(**kwargs) |
| 62 | + |
| 63 | + def runtest(self): |
| 64 | + process = subprocess.Popen( |
| 65 | + [sys.executable, self.path], |
| 66 | + stdout=subprocess.PIPE, |
| 67 | + stderr=subprocess.PIPE, |
| 68 | + text=True, |
| 69 | + bufsize=1, # Enable line-buffering |
| 70 | + ) |
| 71 | + |
| 72 | + # Capture stdout output and output it so it behaves like a regular test with -s. |
| 73 | + stdout_lines = [] |
| 74 | + if process.stdout is not None: |
| 75 | + for line in process.stdout: |
| 76 | + sys.stdout.write(line) |
| 77 | + sys.stdout.flush() # Ensure the output is printed immediately |
| 78 | + stdout_lines.append(line) |
| 79 | + process.stdout.close() |
| 80 | + |
| 81 | + retcode = process.wait() |
| 82 | + |
| 83 | + # Capture stderr output. |
| 84 | + stderr = "" |
| 85 | + if process.stderr is not None: |
| 86 | + stderr = process.stderr.read() |
| 87 | + |
| 88 | + if retcode != 0: |
| 89 | + raise ExampleTestException( |
| 90 | + (f"Example failed with exit code {retcode}.\nStderr: {stderr}\n") |
| 91 | + ) |
| 92 | + |
| 93 | + def repr_failure(self, excinfo, style=None): |
| 94 | + """Called when self.runtest() raises an exception.""" |
| 95 | + if isinstance(excinfo.value, ExampleTestException): |
| 96 | + return str(excinfo.value) |
| 97 | + |
| 98 | + return super().repr_failure(excinfo) |
| 99 | + |
| 100 | + def reportinfo(self): |
| 101 | + return self.path, 0, f"usecase: {self.name}" |
| 102 | + |
| 103 | + |
| 104 | +class ExampleTestException(Exception): |
| 105 | + """Custom exception for error reporting.""" |
0 commit comments