pytest-codeblock

Test your documentation code blocks.

PyPI Version Supported Python versions Build Status Documentation Status llms.txt - documentation for LLMs MIT Coverage

pytest-codeblock is a Pytest plugin that discovers Python code examples in your reStructuredText and Markdown documentation files and runs them as part of your test suite. This ensures your docs stay correct and up-to-date.

Features

  • reStructuredText and Markdown support: Automatically find and test code blocks in reStructuredText (.rst) and Markdown (.md) files. The only requirement here is that your code blocks shall have a name starting with test_.

  • Grouping by name: Split a single example across multiple code blocks; the plugin concatenates them into one test.

  • Pytest markers support: Add existing or custom pytest markers to the code blocks and hook into the tests life-cycle using conftest.py.

Prerequisites

  • Python 3.9+

  • pytest is the only required dependency

Documentation

Installation

Install with pip:

pip install pytest-codeblock

Or install with uv:

uv pip install pytest-codeblock

Configuration

Filename: pyproject.toml

[tool.pytest.ini_options]
testpaths = [
    "**/*.rst",
    "**/*.md",
]

Usage

reStructruredText usage

Any code directive, such as .. code-block:: python, .. code:: python, or literal blocks with a preceding .. codeblock-name: <name>, will be collected and executed automatically, if your pytest configuration allows that.

code-block directive example

Note

Note that :name: value has a test_ prefix.

Filename: README.rst

.. code-block:: python
   :name: test_basic_example

   import math

   result = math.pow(3, 2)
   assert result == 9

literalinclude directive example

Note

Note that :name: value has a test_ prefix.

Filename: README.rst

.. literalinclude:: examples/python/basic_example.py
    :name: test_li_basic_example

See a dedicated reStructuredText docs for more.

Markdown usage

Any fenced code block with a recognized Python language tag (e.g., python, py) will be collected and executed automatically, if your pytest configuration allows that.

Note

Note that name value has a test_ prefix.

Filename: README.md

```python name=test_basic_example
import math

result = math.pow(3, 2)
assert result == 9
```

See a dedicated Markdown docs for more.

Tests

Run the tests with pytest:

pytest

Writing documentation

Keep the following hierarchy.

=====
title
=====

header
======

sub-header
----------

sub-sub-header
~~~~~~~~~~~~~~

sub-sub-sub-header
^^^^^^^^^^^^^^^^^^

sub-sub-sub-sub-header
++++++++++++++++++++++

sub-sub-sub-sub-sub-header
**************************

License

MIT

Support

For security issues contact me at the e-mail given in the Author section.

For overall issues, go to GitHub.

Author

Artur Barseghyan <artur.barseghyan@gmail.com>

Project documentation

Contents: