Skip to main content

Run markdown code fences through pytest

Project description

Pytest Markdown Docs

A plugin for pytest that uses markdown code snippets from markdown files and docstrings as tests.

Detects Python code fences (triple backtick escaped blocks) in markdown files as well as inline Python docstrings (similar to doctests) and runs them as tests.

Python file example:

# mymodule.py
class Foo:
    def bar(self):
        """Bar the foo

        This is a sample docstring for the bar method

        Usage:
        ```python
        import mymodule
        result = mymodule.Foo().bar()
        assert result == "hello"
        ```
        """
        return "hello"

Markdown file examples:

# Title

Lorem ipsum yada yada yada

```python
import mymodule
result = mymodule.Foo().bar()
assert result == "hello"
```

Usage

First, make sure to install the plugin:

pip install pytest-markdown-docs

To enable markdown python tests, pass the --markdown-docs flag to pytest:

pytest --markdown-docs

You can also use the markdown-docs flag to filter only markdown-docs tests:

pytest --markdown-docs -m markdown-docs

Detection conditions

Fence blocks (```) starting with the python, python3 or py language definitions are detected as tests in:

  • Python (.py) files, within docstrings of classes and functions
  • .md, .mdx and .svx files

Skipping tests

To exclude a Python code fence from testing, add a notest info string to the code fence, e.g:

```python notest
print("this will not be run")
```

Code block dependencies

Sometimes you might wish to run code blocks that depend on entities to already be declared in the scope of the code, without explicitly declaring them. There are currently two ways you can do this with pytest-markdown:

Injecting global/local variables

If you have some common imports or other common variables that you want to make use of in snippets, you can add them by creating a pytest_markdown_docs_globals hook in your conftest.py:

def pytest_markdown_docs_globals():
    import math
    return {"math": math, "myvar": "hello"}

With this conftest, you would be able to run the following markdown snippet as a test, without causing an error:

```python
print(myvar, math.pi)
```

Fixtures

You can use both autouse=True pytest fixtures in a conftest.py or named fixtures with your markdown tests. To specify named fixtures, add fixture:<name> markers to the code fence info string, e.g.,

```python fixture:capsys
print("hello")
captured = capsys.readouterr()
assert captured.out == "hello\n"
```

As you can see above, the fixture value will be injected as a global. For autouse=True fixtures, the value is only injected as a global if it's explicitly added using a fixture:<name> marker.

Depending on previous snippets

If you have multiple snippets following each other and want to keep the side effects from the previous snippets, you can do so by adding the continuation info string to your code fence:

```python
a = "hello"
```

```python continuation
assert a + " world" == "hello world"
```

Testing of this plugin

You can test this module itself (sadly not using markdown tests at the moment) using pytest:

> poetry run pytest

Or for fun, you can use this plugin to include testing of the validity of snippets in this README.md file:

> poetry run pytest --markdown-docs

Known issues

  • Code for docstring-inlined test discovery can probably be done better (similar to how doctest does it). Currently, seems to sometimes traverse into Python's standard library which isn't great...
  • Traceback logic is extremely hacky, wouldn't be surprised if the tracebacks look weird sometimes
    • Line numbers are "wrong" for docstring-inlined snippets (since we don't know where in the file the docstring starts)
    • Line numbers are "wrong" for continuation blocks even in pure markdown files (can be worked out with some refactoring)
  • There are probably more appropriate ways to use pytest internal APIs to get more features "for free" - current state of the code is a bit "patch it til' it works".
  • Assertions are not rewritten w/ pretty data structure inspection like they are with regular pytest tests by default

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest_markdown_docs-0.5.0.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

pytest_markdown_docs-0.5.0-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file pytest_markdown_docs-0.5.0.tar.gz.

File metadata

  • Download URL: pytest_markdown_docs-0.5.0.tar.gz
  • Upload date:
  • Size: 6.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.12.0 Darwin/23.1.0

File hashes

Hashes for pytest_markdown_docs-0.5.0.tar.gz
Algorithm Hash digest
SHA256 b18acc9a28fcda4773c48e78ca9fcef29903f4f315d2bbddbed3ec900990b116
MD5 1c1c0dbf268af38734ae38db96e4952a
BLAKE2b-256 c4c883e877a457b7dadf2c37411e2b638cec4c5f416750239905b6a5656a7898

See more details on using hashes here.

File details

Details for the file pytest_markdown_docs-0.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pytest_markdown_docs-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 635f57232447a3a8eb9272ffd577359a42b7b6a02799aa6c823736b6b40135a1
MD5 82f86206e48b3db5f8cfb4e002969d97
BLAKE2b-256 4ca7ad09ebaf33c39fcb5db578fe6bdbabfea0996d3f58dfd50ed9a8c32c449a

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page