pytest-examples is a pytest plugin designed for testing Python code examples found within docstrings and markdown files. It can lint these code examples using tools like ruff and black, run them to verify their correctness, and even check if print statements are inlined as expected. The library is currently at version 0.0.18 and follows an active development and release cadence, often aligning with its upstream `pytest` and `pydantic` projects.
pip install pytest-examplesVerified import paths — ran on the pinned version, not inferred.
To use `pytest-examples`, ensure it is installed alongside `pytest`. The plugin automatically discovers code examples in docstrings (like the `add_two_things` function above) and markdown files. You typically invoke `pytest` with specific flags to enable `pytest-examples`'s features. The `--py-examples` flag enables example collection and running, and `--update-examples` enables in-place updates for formatting and print statement checks.
Always run `pytest` with `--py-examples` to enable example testing. Add `--update-examples` if you intend to format or update print statements in place.
Review changes carefully after running `pytest --update-examples`. Consider running without `--update-examples` first to see only report failures, then with it only when explicit updates are desired. Use version control to track and revert unwanted changes.
Ensure your example code is valid Python syntax. For docstrings, follow standard Python docstring conventions. For markdown, clearly delineate code blocks (e.g., using ````py`). Verify `pytest`'s overall test discovery is working as expected in your project setup.