Skip to content

Instantly share code, notes, and snippets.

@Midnighter
Last active September 8, 2019 13:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Midnighter/3509f2ab902b96874f473dca498baaf8 to your computer and use it in GitHub Desktop.
Save Midnighter/3509f2ab902b96874f473dca498baaf8 to your computer and use it in GitHub Desktop.
How to make autodoc recognize any Python module.

How to Auto Document Your Pytest Test Suite

Triggered by this recent tweet advertising a new pytest plugin that can document itself, I want to briefly describe how you can get sphinx-autodoc to recognize and document the tests.

It is slightly more work since you have to tell Sphinx to auto-document each individual module manually. At least, I haven't yet spent the time to os.walk the test directory and document each one. Assuming the following project structure we can ensure documentation of our tests by modifying the Sphinx configuration (docs/conf.py) and creating a document.

python-package
├── docs
│   ├── conf.py
│   ├── index.rst
│   ├── test_suite.rst
│   └── test_unit.rst
├── src
│   └── package
└── tests
    └── test_unit.py

Sphinx Configuration

So typically when you use autodoc, in your conf.py you add your package to the path. Add something like this to your docs/conf.py in order to also discover tests:

import sys
from os.path import dirname, join


PROJECT_ROOT = dirname((dirname(__file__))
SRC_ROOT = join(PROJECT_ROOT, "src")
TEST_ROOT = join(PROJECT_ROOT, "tests")

sys.path.insert(0, SRC_ROOT)
sys.path.insert(1, TEST_ROOT)

you can os.walk the TEST_ROOT and add the directories to the path if you have multiple levels there.

Creating Auto Documentation

You would then create a new test_unit.rst file somewhere in docs which should contain something like:

.. automodule:: test_unit
    :members:
    :show-inheritance:

and include it somewhere in your documentation, for example, a test suite table of contents in test_suite.rst:

==========
Test Suite
==========

.. toctree::
   :maxdepth: 2

   test_unit

which itself could be included in the index.rst:

=====================
Package Documentation
=====================

.. toctree::
   :maxdepth: 2

   test_suite

Copyright

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment