sphinx.ext.doctest -- ドキュメント内の簡易テスト

It is often helpful to include snippets of code in your documentation and demonstrate the results of executing them. But it is important to ensure that the documentation stays up-to-date with the code.

This extension allows you to test such code snippets in the documentation in a natural way. If you mark the code blocks as shown here, the doctest builder will collect them and run them as doctest tests.

Within each document, you can assign each snippet to a group. Each group consists of:

  • ゼロ個以上のセットアップコードブロック。テストに必要なモジュールをimportします。

  • ひとつ以上のテストブロック。

doctestビルダーを使用してドキュメントをビルドすると、それぞれのドキュメントごとに同一グループの要素が集められて次々に実行されます。最初はセットアップコードブロックが実行され、その後はファイルの中で登場する順番にテストブロックが実行されます。

テストブロックには以下の2種類あります:

  • Pythonコード(含プロンプト)と出力が交互に書かれている、インタラクティブモードに似たdoctestスタイルのブロック

  • 通常のPythonコードと、出力を1つから構成される、コード-出力スタイルのブロック

ディレクティブ

グループ引数は以下のように解釈されます: もしも何も指定されなかった場合には、defaultというグループ名が指定されたとみなします。もしも*が指定されると、そのブロックはdefaultを含む、すべてのグループに対して割り当てられたものとみなします。そうでなければ、これ以外の場合はグループ名は、カンマ区切りのリストでなければなりません。

.. testsetup:: [group]

セットアップのためのコードブロックです。このコードは他のビルダーを使用したときには出力されませんが、それが所属するグループのdoctestが実行される前に実行されます。

.. testcleanup:: [group]

片付けをするためのコードブロックです。このコードは他のビルダーを使用したときには出力されませんが、それが所属するグループのdoctestが実行された後に実行されます。

Added in version 1.1.

.. doctest:: [group]

A doctest-style code block. You can use standard doctest flags for controlling how actual output is compared with what you give as output. The default set of flags is specified by the doctest_default_flags configuration variable.

This directive supports five options:

  • hideはフラグオプションです。他のビルダーの使用時に、doctestブロックを隠します。デフォルトでは、ハイライトされたdoctestブロックとして表示されます。

  • optionsは文字列オプションです。それぞれのテストのサンプルに対して、カンマ区切りのdoctestフラグのリストを設定するのに使用します。doctestコメントの中でサンプルごとにフラグを明示することもできますが、他のビルダーをしようすると、そのフラグまでレンダリングされてしまいます。

  • pyversion, a string option, can be used to specify the required Python version for the example to be tested. For instance, in the following case the example will be tested only for Python versions greater than 3.10:

    .. doctest::
       :pyversion: > 3.10
    

    The following operands are supported:

    • ~=: Compatible release clause

    • ==: Version matching clause

    • !=: Version exclusion clause

    • <=, >=: Inclusive ordered comparison clause

    • <, >: Exclusive ordered comparison clause

    • ===: Arbitrary equality clause.

    pyversion option is followed PEP-440: Version Specifiers.

    Added in version 1.6.

    バージョン 1.7 で変更: Supported PEP-440 operands and notations

  • trim-doctest-flags and no-trim-doctest-flags, a flag option, doctest flags (comments looking like # doctest: FLAG, ...) at the ends of lines and <BLANKLINE> markers are removed (or not removed) individually. Default is trim-doctest-flags.

標準ライブラリのdoctestでは、予想出力の中に空行を入れたい場合には<BLANKLINE>というキーワードを指定しなければなりませんでした。<BLANKLINE>はHTMLやLaTeXなど、人が読める出力を行うビルドの際には削除されます。

doctestの中で書くのと同様に、インラインでdoctestのオプションを指定することもできます:

>>> datetime.date.now()   # doctest: +SKIP
datetime.date(2008, 1, 1)

これらのオプションは、テストの実行時には識別されますが、HTMLなどの出力の際には削除されます。

.. testcode:: [group]

コード-出力タイプのテストのコードブロックです。

This directive supports three options:

  • hideはフラグオプションです。他のビルダーの使用時に、codeブロックを隠します。デフォルトでは、ハイライトされたcodeブロックとして表示されます。

  • trim-doctest-flags and no-trim-doctest-flags, a flag option, doctest flags (comments looking like # doctest: FLAG, ...) at the ends of lines and <BLANKLINE> markers are removed (or not removed) individually. Default is trim-doctest-flags.

注釈

testcode ブロックの中のコードは、含まれている文の量に関わらず、すべて、一度だけ実行されます。そのため、単なる式の場合には、出力は 行われませんprint を使用してください。サンプル:

.. testcode::

   1+1         # this will give no output!
   print(2+2)  # this will give output

.. testoutput::

   4

doctestモジュールも、通常の出力と、例外メッセージを同じコードスニペット内で混ぜた書き方をサポートしていないように、testcode/testoutputにも同様の制限がある点に注意してください。

.. testoutput:: [group]

最後に定義された testcode ブロックに対応する出力, もしくは例外メッセージを定義します。

This directive supports four options:

  • hideはフラグオプションです。他のビルダーの使用時に、ブロックを隠します。デフォルトでは、ハイライトせずにリテラルブロックとして表示されます。

  • optionsは文字列オプションで、通常のdoctestブロックと同じように、カンマ区切りのdoctestのフラグを設定するのに使用されます。

  • trim-doctest-flags and no-trim-doctest-flags, a flag option, doctest flags (comments looking like # doctest: FLAG, ...) at the ends of lines and <BLANKLINE> markers are removed (or not removed) individually. Default is trim-doctest-flags.

サンプル:

.. testcode::

   print('Output     text.')

.. testoutput::
   :hide:
   :options: -ELLIPSIS, +NORMALIZE_WHITESPACE

   Output text.

以下のコードはこれらのディレクティブの使用方法のサンプルです。 doctest を使用したテストと、 testcode および testoutput の二つで構成されたテストは等価です.

The parrot module
=================

.. testsetup:: *

   import parrot

The parrot module is a module about parrots.

Doctest example:

.. doctest::

   >>> parrot.voom(3000)
   This parrot wouldn't voom if you put 3000 volts through it!

Test-Output example:

.. testcode::

   parrot.voom(3000)

This would output:

.. testoutput::

   This parrot wouldn't voom if you put 3000 volts through it!

Skipping tests conditionally

skipif, a string option, can be used to skip directives conditionally. This may be useful e.g. when a different set of tests should be run depending on the environment (hardware, network/VPN, optional dependencies or different versions of dependencies). The skipif option is supported by all of the doctest directives. Below are typical use cases for skipif when used for different directives:

  • testsetup and testcleanup

    • conditionally skip test setup and/or cleanup

    • customize setup/cleanup code per environment

  • doctest

    • conditionally skip both a test and its output verification

  • testcode

    • conditionally skip a test

    • customize test code per environment

  • testoutput

    • conditionally skip output assertion for a skipped test

    • expect different output depending on the environment

The value of the skipif option is evaluated as a Python expression. If the result is a true value, the directive is omitted from the test run just as if it wasn't present in the file at all.

Instead of repeating an expression, the doctest_global_setup configuration option can be used to assign it to a variable which can then be used instead.

Here's an example which skips some tests if Pandas is not installed:

conf.py
extensions = ['sphinx.ext.doctest']
doctest_global_setup = '''
try:
    import pandas as pd
except ImportError:
    pd = None
'''
contents.rst
.. testsetup::
   :skipif: pd is None

   data = pd.Series([42])

.. doctest::
   :skipif: pd is None

   >>> data.iloc[0]
   42

.. testcode::
   :skipif: pd is None

   print(data.iloc[-1])

.. testoutput::
   :skipif: pd is None

   42

設定

The doctest extension uses the following configuration values:

doctest_default_flags

By default, these options are enabled:

  • ELLIPSIS, allowing you to put ellipses in the expected output that match anything in the actual output;

  • IGNORE_EXCEPTION_DETAIL, causing everything following the leftmost colon and any module information in the exception name to be ignored;

  • DONT_ACCEPT_TRUE_FOR_1, rejecting "True" in the output where "1" is given -- the default behavior of accepting this substitution is a relic of pre-Python 2.2 times.

Added in version 1.5.

doctest_show_successes

Defaults to True. Controls whether successes are reported.

For a project with many doctests, it may be useful to set this to False to only highlight failures.

Added in version 7.2.

doctest_path

doctestビルダーが使用されるときに、 sys.path に対して追加されるディレクトリのリストです。必ず絶対パスで記述してください。

doctest_global_setup

Pythonコードを記述します。このコードはテストされるすべてのファイルのtestsetupディレクティブに書き込んだのと同じように扱われます。例えば、doctest時にいつでも必要となるモジュールをimportするといった用途に使用できます。

Added in version 0.6.

doctest_global_cleanup

すべてのテストグループがテストを終了したあとに呼ばれる、 testcleanup ディレクティブを、すべてのファイルに作ります。この設定にはPythonのコードを書きます。すべてのテンポラリファイルを削除などの使い方ができます。

Added in version 1.1.

doctest_test_doctest_blocks

この値に空でない文字列(デフォルトは'default')が設定されると、標準のreSTのdoctestブロックもテストされるようになります。それらのテストには、ここで与えられたグループ名が設定されます。

reSTのdoctestブロックは、reSTの中のパラグラフとして単純にdoctestが置かれます:

Some documentation text.

>>> print(1)
1

Some more documentation text.

reSTの場合は、doctestブロックを表現するのに特別な::は使用されません。docutilsは>>>から始まる行を識別します。そのため、doctestのために追加でインデントを設定する必要はありません。

この設定値がデフォルトのままであったとすると、上記のコード片は、下記のように書いた場合と同じようにdoctestビルダーから解釈されます:

Some documentation text.

.. doctest::

   >>> print(1)
   1

Some more documentation text.

この機能があるおかげで autodoc 拡張を使用して取り込んだdocstring中のdoctestを簡単に実行できます。特別なディレクティブでマークアップする必要はありません。

しかし、 reST doctest ブロックには空行を含めることができないということに注意してください。それらは一つのブロックの終わりと別のブロックの開始として解釈されるでしょう。また <BLANKLINE># doctest: オプションの除去は doctest ブロックの中でのみ機能します。ただし、 trim_doctest_flags を設定して、 Python コンソールの内容を含むすべてのコードブロックでもそれを実現できます。