26.8. test — Python 用回帰テストパッケージ

注釈

test パッケージは Python の内部利用専用です。 ドキュメント化されているのは Python の中心開発者のためです。 ここで述べられているコードは Python のリリースで予告なく変更されたり、削除される可能性があるため、Python 標準ライブラリー外でこのパッケージを使用することは推奨されません。


test パッケージには、Python 用の全ての回帰テストの他に、 test.support モジュールと test.regrtest モジュールが入っています。 test.support はテストを充実させるために使い、 test.regrtest はテストスイートを実行するのに使います。

test パッケージ内のモジュールのうち、名前が test_ で始まるものは、特定のモジュールや機能に対するテストスイートです。新しいテストはすべて unittestdoctest モジュールを使って書くようにしてください。古いテストのいくつかは、 sys.stdout への出力を比較する「従来の」テスト形式になっていますが、この形式のテストは廃止予定です。

参考

unittest モジュール
PyUnit 回帰テストを書く。
doctest モジュール
ドキュメンテーション文字列に埋め込まれたテスト。

26.8.1. test パッケージのためのユニットテストを書く

unittest モジュールを使ってテストを書く場合、幾つかのガイドラインに従うことが推奨されます。 1つは、テストモジュールの名前を、 test_ で始め、テスト対象となるモジュール名で終えることです。テストモジュール中のテストメソッドは名前を test_ で始めて、そのメソッドが何をテストしているかという説明で終えます。これはテスト実行プログラムが、そのメソッドをテストメソッドとして認識するために必要です。また、テストメソッドにはドキュメンテーション文字列を入れるべきではありません。コメント(例えば # True あるいは False だけを返すテスト関数 )を使用して、テストメソッドのドキュメントを記述してください。これは、ドキュメンテーション文字列が存在する場合はその内容が出力されてしまうため、どのテストを実行しているのかをいちいち表示したくないからです。

以下のような決まり文句を使います:

import unittest
from test import support

class MyTestCase1(unittest.TestCase):

    # Only use setUp() and tearDown() if necessary

    def setUp(self):
        ... code to execute in preparation for tests ...

    def tearDown(self):
        ... code to execute to clean up after tests ...

    def test_feature_one(self):
        # Test feature one.
        ... testing code ...

    def test_feature_two(self):
        # Test feature two.
        ... testing code ...

    ... more test methods ...

class MyTestCase2(unittest.TestCase):
    ... same structure as MyTestCase1 ...

... more test classes ...

if __name__ == '__main__':
    unittest.main()

このコードのパターンを使うと test.regrtest からテストスイートを実行でき、 unittest のコマンドラインインターフェースをサポートしているスクリプトとして自分自身を起動したり、 python -m unittest というコマンドラインインターフェースを通して起動したりできます。

回帰テストの目的はコードを解き明かすことです。そのためには以下のいくつかのガイドラインに従ってください:

  • テストスイートから、すべてのクラス、関数および定数を実行するべきです。これには外部に公開される外部APIだけでなく「プライベートな」コードも含みます。

  • ホワイトボックス・テスト(対象のコードの詳細を元にテストを書くこと)を推奨します。ブラックボックス・テスト(公開されるインタフェース仕様だけをテストすること)は、すべての境界条件を確実にテストするには完全ではありません。

  • すべての取りうる値を、無効値も含めてテストするようにしてください。そのようなテストを書くことで、全ての有効値が通るだけでなく、不適切な値が正しく処理されることも確認できます。

  • コード内のできる限り多くのパスを網羅してください。分岐するように入力を調整したテストを書くことで、コードの多くのパスをたどることができます。

  • テスト対象のコードにバグが発見された場合は、明示的にテスト追加するようにしてください。そのようなテストを追加することで、将来コードを変更した際にエラーが再発することを防止できます。

  • テストの後始末 (例えば一時ファイルをすべて閉じたり削除したりすること) を必ず行ってください。

  • テストがオペレーティングシステムの特定の状況に依存する場合、テスト開始時に条件を満たしているかを検証してください。

  • インポートするモジュールをできるかぎり少なくし、可能な限り早期にインポートを行ってください。そうすることで、テストの外部依存性を最小限にし、モジュールのインポートによる副作用から生じる変則的な動作を最小限にできます。

  • できる限りテストコードを再利用するようにしましょう。時として、入力の違いだけを記述すれば良くなるくらい、テストコードを小さくすることができます。例えば以下のように、サブクラスで入力を指定することで、コードの重複を最小化することができます:

    class TestFuncAcceptsSequencesMixin:
    
        func = mySuperWhammyFunction
    
        def test_func(self):
            self.func(self.arg)
    
    class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
        arg = [1, 2, 3]
    
    class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
        arg = 'abc'
    
    class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
        arg = (1, 2, 3)
    

    このパターンを使うときには、 unittest.TestCase を継承した全てのクラスがテストとして実行されることを忘れないでください。 上の例の Mixin クラスはテストデータを持っておらず、それ自身は実行できないので、 unittest.TestCase を継承していません。

参考

Test Driven Development
コードより前にテストを書く方法論に関する Kent Beck の著書。

26.8.2. コマンドラインインタフェースを利用してテストを実行する

test パッケージはスクリプトとして Python の回帰テストスイートを実行できます。 -m オプションを利用して、 python -m test.regrtest として実行します。 この仕組みの内部では test.regrtest; を使っています; 古いバージョンの Python で使われている python -m test.regrtest という呼び出しは今でも上手く動きます。 スクリプトを実行すると、自動的に test パッケージ内のすべての回帰テストを実行し始めます。 パッケージ内の名前が test_ で始まる全モジュールを見つけ、それをインポートし、もしあるなら関数 test_main() を実行し、 test_main が無い場合は unittest.TestLoader.loadTestsFromModule からテストをロードしてテストを実行します。 実行するテストの名前もスクリプトに渡される可能性があります。 単一の回帰テストを指定 (python -m test test_spam) すると、出力を最小限にし、テストが成功したかあるいは失敗したかだけを出力します。

直接 test を実行すると、テストに利用するリソースを設定できます。これを行うには、 -u コマンドラインオプションを使います。 -u のオプションに all を指定すると、すべてのリソースを有効にします: python -m test -uall 。(よくある場合ですが) 何か一つを除く全てが必要な場合、カンマで区切った不要なリソースのリストを all の後に並べます。コマンド python -m test -uall,-audio,-largefile とすると、 audiolargefile リソースを除く全てのリソースを使って test を実行します。すべてのリソースのリストと追加のコマンドラインオプションを出力するには、 python -m test -h を実行してください。

テストを実行しようとするプラットフォームによっては、回帰テストを実行する別の方法があります。 Unix では、Python をビルドしたトップレベルディレクトリで make test を実行できます。 Windows上では、 PCBuild ディレクトリから rt.bat を実行すると、すべての回帰テストを実行します。

26.9. test.support — テストのためのユーティリティ関数

test.support モジュールでは、 Python の回帰テストに対するサポートを提供しています。

注釈

test.support はパブリックなモジュールではありません。 ここでドキュメント化されているのは Python 開発者がテストを書くのを助けるためです。 このモジュールの API はリリース間で後方非互換な変更がなされる可能性があります。

このモジュールは次の例外を定義しています:

exception test.support.TestFailed

テストが失敗したとき送出される例外です。これは、 unittest ベースのテストでは廃止予定で、 unittest.TestCase の assertXXX メソッドが推奨されます。

exception test.support.ResourceDenied

unittest.SkipTest のサブクラスです。 (ネットワーク接続のような) リソースが利用できないとき送出されます。 requires() 関数によって送出されます。

test.support モジュールでは、以下の定数を定義しています:

test.support.verbose

冗長な出力が有効な場合は True です。実行中のテストについてのより詳細な情報が欲しいときにチェックします。 verbosetest.regrtest によって設定されます。

test.support.is_jython

実行中のインタプリタが Jython ならば True になります。

test.support.TESTFN

テンポラリファイルの名前として安全に利用できる名前に設定されます。作成した一時ファイルは全て閉じ、unlink (削除) しなければなりません。

test.support モジュールでは、以下の関数を定義しています:

test.support.forget(module_name)

モジュール名 module_namesys.modules から取り除き、モジュールのバイトコンパイル済みファイルを全て削除します。

test.support.is_resource_enabled(resource)

resource が有効で利用可能ならば True を返します。利用可能なリソースのリストは、 test.regrtest がテストを実行している間のみ設定されます。

test.support.requires(resource, msg=None)

resource が利用できなければ、 ResourceDenied を送出します。その場合、 msgResourceDenied の引数になります。 __name__'__main__' である関数にから呼び出された場合には常に True を返します。テストを test.regrtest から実行するときに使われます。

test.support.findfile(filename, subdir=None)

filename という名前のファイルへのパスを返します。一致するものが見つからなければ、 filename 自体を返します。 filename 自体もファイルへのパスでありえるので、 filename が返っても失敗ではありません。

subdir を設定することで、パスのディレクトリを直接見に行くのではなく、相対パスを使って見付けにいくように指示できます。
test.support.run_unittest(*classes)

渡された unittest.TestCase サブクラスを実行します。この関数は名前が test_ で始まるメソッドを探して、テストを個別に実行します。

引数に文字列を渡すことも許可されています。その場合、文字列は sys.module のキーでなければなりません。指定された各モジュールは、 unittest.TestLoader.loadTestsFromModule() でスキャンされます。この関数は、よく次のような test_main() 関数の形で利用されます。

def test_main():
    support.run_unittest(__name__)

この関数は、名前で指定されたモジュールの中の全ての定義されたテストを実行します。

test.support.run_doctest(module, verbosity=None)

与えられた moduledoctest.testmod() を実行します。(failure_count, test_count) を返します。

verbosityNone の場合、 doctest.testmod() は冗長性 (verbosity) に verbose を設定して実行されます。 そうでない場合は、冗長性に None を設定して実行されます。

test.support.check_warnings(*filters, quiet=True)

warning が正しく発行されているかどうかチェックする、 warnings.catch_warnings() を使いやすくするラッパーです。これは、 warnings.simplefilter()always に設定して、記録された結果を自動的に検証するオプションと共に warnings.catch_warnings(record=True) を呼ぶのとほぼ同じです。

check_warnings("message regexp", WarningCategory) の形をした 2要素タプルを位置引数として受け取ります。1つ以上の filters が与えられた場合や、オプションのキーワード引数 quietFalse の場合、警告が期待通りであるかどうかをチェックします。指定された各 filter は最低でも1回は囲われたコード内で発生した警告とマッチしなければテストが失敗しますし、指定されたどの filter ともマッチしない警告が発生してもテストが失敗します。前者のチェックを無効にするには、quietTrue にします。

引数が1つもない場合、デフォルトでは次のようになります:

check_warnings(("", Warning), quiet=True)

この場合、全ての警告は補足され、エラーは発生しません。

コンテキストマネージャーに入る時、 WarningRecorder インスタンスが返されます。このレコーダーオブジェクトの warnings 属性から、 catch_warnings() から得られる警告のリストを取得することができます。便利さのために、レコーダーオブジェクトから直接、一番最近に発生した警告を表すオブジェクトの属性にアクセスできます(以下にある例を参照してください)。警告が1つも発生しなかった場合、それらの全ての属性は None を返します。

レコーダーオブジェクトの reset() メソッドは警告リストをクリアします。

コンテキストマネージャーは次のようにして使います:

with check_warnings(("assertion is always true", SyntaxWarning),
                    ("", UserWarning)):
    exec('assert(False, "Hey!")')
    warnings.warn(UserWarning("Hide me!"))

この場合、どちらの警告も発生しなかった場合や、それ以外の警告が発生した場合は、 check_warnings() はエラーを発生させます。

警告が発生したかどうかだけでなく、もっと詳しいチェックが必要な場合は、次のようなコードになります:

with check_warnings(quiet=True) as w:
    warnings.warn("foo")
    assert str(w.args[0]) == "foo"
    warnings.warn("bar")
    assert str(w.args[0]) == "bar"
    assert str(w.warnings[0].args[0]) == "foo"
    assert str(w.warnings[1].args[0]) == "bar"
    w.reset()
    assert len(w.warnings) == 0

全ての警告をキャプチャし、テストコードがその警告を直接テストします。

バージョン 3.2 で変更: 新しいオプション引数 filtersquiet

test.support.captured_stdin()
test.support.captured_stdout()
test.support.captured_stderr()

名前付きストリ-ムを io.StringIO オブジェクトで一時的に置き換えるコンテクストマネージャです。

出力ストリームの使用例:

with captured_stdout() as stdout, captured_stderr() as stderr:
    print("hello")
    print("error", file=sys.stderr)
assert stdout.getvalue() == "hello\n"
assert stderr.getvalue() == "error\n"

入力ストリ-ムの使用例:

with captured_stdin() as stdin:
    stdin.write('hello\n')
    stdin.seek(0)
    # call test code that consumes from sys.stdin
    captured = input()
self.assertEqual(captured, "hello")
test.support.temp_dir(path=None, quiet=False)

path に一時ディレクトリを作成し与えるコンテキストマネージャです。

If path is None, the temporary directory is created using tempfile.mkdtemp(). If quiet is False, the context manager raises an exception on error. Otherwise, if path is specified and cannot be created, only a warning is issued.

test.support.change_cwd(path, quiet=False)

カレントディレクトリを一時的に path に変更し与えるコンテキストマネージャです。

quietFalse の場合、コンテキストマネージャはエラーが起きると例外を送出します。 それ以外の場合には、警告を出すだけでカレントディレクトリは同じままにしておきます。

test.support.temp_cwd(name='tempcwd', quiet=False)

一時的に新しいディレクトリを作成し、カレントディレクトリ (current working directory, CWD) を変更するコンテキストマネージャです。

The context manager creates a temporary directory in the current directory with name name before temporarily changing the current working directory. If name is None, the temporary directory is created using tempfile.mkdtemp().

quietFalse でカレントディレクトリの作成や変更ができない場合、例外を送出します。 それ以外の場合には、警告を出すだけで元のカレントディレクトリが使われます。

test.support.temp_umask(umask)

一時的にプロセスの umask を設定するコンテキストマネージャ。

OS がシンボリックリンクをサポートする場合 True を返し、その他の場合は False を返します。

シンボリックリンクのサポートが必要なテストを実行することを表すデコレータ。

@test.support.anticipate_failure(condition)

ある条件で unittest.expectedFailure() の印をテストに付けるデコレータ。 このデコレータを使うときはいつも、関連する問題を指し示すコメントを付けておくべきです。

@test.support.run_with_locale(catstr, *locales)

別のロケールで関数を実行し、完了したら適切に元の状態に戻すためのデコレータ。 catstr は (例えば "LC_ALL" のような) ロケールカテゴリを文字列で表したものです。 渡された locales が順々に試され、一番最初に出てきた妥当なロケールが使われます。

test.support.make_bad_fd()

一時ファイルを開いた後に閉じ、そのファイル記述子を返すことで無効な記述子を作成します。

test.support.import_module(name, deprecated=False)

この関数は name で指定されたモジュールをインポートして返します。通常のインポートと異なり、この関数はモジュールをインポートできなかった場合に unittest.SkipTest 例外を発生させます。

deprecatedTrue の場合、インポート中はモジュールとパッケージの廃止メッセージが抑制されます。

バージョン 3.1 で追加.

test.support.import_fresh_module(name, fresh=(), blocked=(), deprecated=False)

この関数は、 name で指定された Python モジュールを、インポート前に sys.modules から削除することで新規にインポートしてそのコピーを返します。 reload() 関数と違い、もとのモジュールはこの操作によって影響をうけません。

fresh は、同じようにインポート前に sys.modules から削除されるモジュール名の iterable です。

blocked もモジュール名のイテラブルで、インポート中にモジュールキャッシュ内でその名前を None に置き換えることで、そのモジュールをインポートしようとすると ImportError を発生させます。

指定されたモジュールと freshblocked 引数内のモジュール名はインポート前に保存され、フレッシュなインポートが完了したら sys.modules に戻されます。

deprecatedTrue の場合、インポート中はモジュールとパッケージの廃止メッセージが抑制されます。

指定したモジュールがインポートできなかった場合に、この関数は ImportError を送出します。

使用例:

# Get copies of the warnings module for testing without affecting the
# version being used by the rest of the test suite. One copy uses the
# C implementation, the other is forced to use the pure Python fallback
# implementation
py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = import_fresh_module('warnings', fresh=['_warnings'])

バージョン 3.1 で追加.

test.support.bind_port(sock, host=HOST)

Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, and the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should never set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets.

Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from binding to our host/port for the duration of the test.

test.support.find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)

Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the sock parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned.

Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl’s s_server mode). Always prefer bind_port() over find_unused_port() where possible. Using a hard coded port is discouraged since it can make multiple instances of the test impossible to run simultaneously, which is a problem for buildbots.

test.support.load_package_tests(pkg_dir, loader, standard_tests, pattern)

Generic implementation of the unittest load_tests protocol for use in test packages. pkg_dir is the root directory of the package; loader, standard_tests, and pattern are the arguments expected by load_tests. In simple cases, the test package’s __init__.py can be the following:

import os
from test.support import load_package_tests

def load_tests(*args):
    return load_package_tests(os.path.dirname(__file__), *args)
test.support.detect_api_mismatch(ref_api, other_api, *, ignore=())

Returns the set of attributes, functions or methods of ref_api not found on other_api, except for a defined list of items to be ignored in this check specified in ignore.

By default this skips private attributes beginning with '_' but includes all magic methods, i.e. those starting and ending in '__'.

バージョン 3.5 で追加.

test.support.check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())

Assert that the __all__ variable of module contains all public names.

The module’s public names (its API) are detected automatically based on whether they match the public name convention and were defined in module.

The name_of_module argument can specify (as a string or tuple thereof) what module(s) an API could be defined in in order to be detected as a public API. One case for this is when module imports part of its public API from other modules, possibly a C backend (like csv and its _csv).

The extra argument can be a set of names that wouldn’t otherwise be automatically detected as "public", like objects without a proper __module__ attribute. If provided, it will be added to the automatically detected ones.

The blacklist argument can be a set of names that must not be treated as part of the public API even though their names indicate otherwise.

使用例:

import bar
import foo
import unittest
from test import support

class MiscTestCase(unittest.TestCase):
    def test__all__(self):
        support.check__all__(self, foo)

class OtherTestCase(unittest.TestCase):
    def test__all__(self):
        extra = {'BAR_CONST', 'FOO_CONST'}
        blacklist = {'baz'}  # Undocumented name.
        # bar imports part of its API from _bar.
        support.check__all__(self, bar, ('bar', '_bar'),
                             extra=extra, blacklist=blacklist)

バージョン 3.6 で追加.

test.support モジュールでは、以下のクラスを定義しています:

class test.support.TransientResource(exc, **kwargs)

このクラスのインスタンスはコンテキストマネージャーで、指定された型の例外が発生した場合に ResourceDenied 例外を発生させます。キーワード引数は全て、 with 文の中で発生した全ての例外の属性名/属性値と比較されます。全てのキーワード引数が例外の属性に一致した場合に、 ResourceDenied 例外が発生します。

class test.support.EnvironmentVarGuard

一時的に環境変数をセット・アンセットするためのクラスです。このクラスのインスタンスはコンテキストマネージャーとして利用されます。また、 os.environ に対する参照・更新を行う完全な辞書のインタフェースを持ちます。コンテキストマネージャーが終了した時、このインスタンス経由で環境変数へ行った全ての変更はロールバックされます。

バージョン 3.1 で変更: 辞書のインタフェースを追加しました。

EnvironmentVarGuard.set(envvar, value)

一時的に、 envvarvalue にセットします。

EnvironmentVarGuard.unset(envvar)

一時的に envvar をアンセットします。

class test.support.SuppressCrashReport

A context manager used to try to prevent crash dialog popups on tests that are expected to crash a subprocess.

On Windows, it disables Windows Error Reporting dialogs using SetErrorMode.

On UNIX, resource.setrlimit() is used to set resource.RLIMIT_CORE’s soft limit to 0 to prevent coredump file creation.

On both platforms, the old value is restored by __exit__().

class test.support.WarningsRecorder

ユニットテスト時に warning を記録するためのクラスです。上の、 check_warnings() のドキュメントを参照してください。

class test.support.FakePath(path)

Simple path-like object. It implements the __fspath__() method which just returns the path argument. If path is an exception, it will be raised in __fspath__().