doctest python 試験対策

doctestを使ってテストする方法を学ぶ

doctestについて doctestは、関数のdocstringに記述されたテストを実行するモジュール テストの記述方法は、関数のdocstringに>>>で始まるコードを記述する その後に、期待される出力を記述する 例:

def add(a: int, b: int) -> int:
    """
    2つの引数を受け取り、それらを足し合わせた結果を返す

    >>> add(1, 2)
    3
    >>> add(3, 4)
    7
    """
    return a + b

if __name__ == "__main__":
    import doctest
    doctest.testmod()

このコードを実行すると、関数のdocstringに記述されたテストが実行される テストが成功した場合は、何も表示されない テストが失敗した場合は、失敗したテストの内容が表示される

せっかくなので失敗したテストを見てみる 以下のコードを追加して、テストを失敗させてみる

def subtract(a: int, b: int) -> int:
    """
    2つの引数を受け取り、それらを引いた結果を返す

    >>> subtract(3, 2)
    -1
    >>> subtract(5, 4)
    -1
    """
    return a - b

 このコードを実行すると、以下のようなエラーが表示される
 **********************************************************************
 File "/Users/shirotabi/Dev/myModule/myPython/MyPythonModule/exam/how_to_test.py", line 32, in __main__.subtract
 Failed example:
     subtract(3, 2)
 Expected:
     -1
 Got:
     1
 **********************************************************************
 File "/Users/shirotabi/Dev/myModule/myPython/MyPythonModule/exam/how_to_test.py", line 34, in __main__.subtract
 Failed example:
     subtract(5, 4)
 Expected:
     -1
 Got:
     1
 **********************************************************************
 1 items had failures:
    2 of   2 in __main__.subtract
 ***Test Failed*** 2 failures.

doctestで使える記号 doctestでは、以下の記号を使うことができる

  • +: 期待される出力が改行を含む場合に使う

  • ...: 複数行の出力を表す

  • ELLIPSIS: 任意の文字列を表す

  • IGNORE_EXCEPTION_DETAIL: 例外の詳細を無視する

  • NORMALIZE_WHITESPACE: 空白文字の違いを無視する

  • SKIP: テストをスキップする

使ってみよう

def example_multiline_output():
   """
   Returns a multiline string

   >>> example_multiline_output()
   Hello
   World
   """
   return "Hello\nWorld"

def example_ellipsis():
   """
   Demonstrates the use of ellipsis for ignoring part of the output.

   >>> example_ellipsis()
   'Start of output...end of output'
   """
   return "Start of output and some extra content that is ignored end of output"

def example_exception():
   """
   Raises a ValueError to demonstrate IGNORE_EXCEPTION_DETAIL.

   >>> example_exception() # doctest: +IGNORE_EXCEPTION_DETAIL
   Traceback (most recent call last):
   ValueError: Some error message
   """
   raise ValueError("Some error message with details")

def example_whitespace():
   """
   Demonstrates NORMALIZE_WHITESPACE.

   >>> example_whitespace() # doctest: +NORMALIZE_WHITESPACE
   'This   is a    test'
   """
   return "This is a test"

def example_skip():
   """
   This test will be skipped.

   >>> example_skip() # doctest: +SKIP
   'This will not be tested'
   """
   return "This will not be tested"


doctestはテキストファイルに記述することもできる テキストファイルに記述する場合は、以下のように記述する

Python doctestではテキストファイルも扱えます。


>>> def add(a, b):
...     return a + b
>>> add(2, 3)
5

This is another example.

>>> def multiply(a, b):
...     return a * b
>>> multiply(2, 3)
6

実行するには

import doctest

if __name__ == "__main__":
    doctest.testfile("doctest.txt")

このコードを実行すると、doctest.txtに記述されたテストが実行される

この記事が気に入ったらサポートをしてみませんか?