pytest-examples

0.0.18 · active · verified Mon Apr 13

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.

Warnings

Install

Imports

Quickstart

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.

import pytest

# my_lib.py (example code to be tested)
def add_two_things(a, b):
    """
    Adds two things.

    >>> add_two_things(1, 2)
    3
    """
    return a + b

# test_my_lib.py (pytest test file)
def test_add_two_things_example():
    # This test primarily ensures pytest-examples is installed and discoverable.
    # The actual testing of examples is done by running `pytest`.
    pass

# To run tests and check examples:
# 1. Save the above code into 'my_lib.py' and 'test_my_lib.py'
# 2. Run from your terminal in the same directory: pytest --py-examples
# 3. To lint and run, and optionally update: pytest --py-examples --update-examples

view raw JSON →