pytest-markdown-docs
pytest-markdown-docs is a pytest plugin that collects and executes Python code blocks found within Markdown files and Python docstrings as tests. It allows developers to ensure that documentation examples remain correct and up-to-date by integrating them into the standard pytest test suite. The library is currently at version 0.9.2 and follows an active, though not strictly fixed, release cadence.
Warnings
- gotcha The plugin's test collection is only activated when the `--markdown-docs` command-line flag is explicitly passed to pytest. Simply installing the plugin is not enough.
- gotcha Traceback line numbers for code within docstring-inlined snippets or continuation blocks might be inaccurate or confusing compared to standard Python files, as the plugin's internal handling of source locations is 'hacky'.
- gotcha Assertions within Markdown code fences are not rewritten by pytest to provide rich, detailed comparison diffs like they are for standard Python test functions.
- breaking Older versions of `pytest-markdown-docs` (before 0.9.x) might have had compatibility issues with `pytest > 7.0.0` due to internal API changes in pytest.
- gotcha To prevent a specific Python code fence from being collected as a test, add `notest` to its info string (e.g., ````python notest````). Otherwise, any `python`, `python3`, or `py` code fence will be treated as a test.
Install
-
pip install pytest-markdown-docs
Quickstart
import pytest
# Save this content as README.md
readme_content = """
# My Project
This is a sample project with a Python code example.
```python
def add(a, b):
return a + b
assert add(1, 2) == 3
assert add(-1, 1) == 0
```
Another block that should be skipped:
```python notest
print('This code should not run as a test')
assert False # This would fail if not skipped
```
"""
with open('README.md', 'w') as f:
f.write(readme_content)
# To run this, save the above content as a Python file (e.g., quickstart.py),
# then execute from your terminal:
# python -c "import quickstart" # Creates README.md
# pytest --markdown-docs README.md
#
# Expected output will show 2 passed tests from the first code block.