# `test` --- Regression tests package for Python

注釈

The `test` package is meant for internal use by Python only. It is documented for the benefit of the core developers of Python. Any use of this package outside of Python's standard library is discouraged as code mentioned here can change or be removed without notice between releases of Python.

The `test` package contains all regression tests for Python as well as the modules `test.support` and `test.regrtest`. `test.support` is used to enhance your tests while `test.regrtest` drives the testing suite.

Each module in the `test` package whose name starts with `test_` is a testing suite for a specific module or feature. All new tests should be written using the `unittest` or `doctest` module. Some older tests are written using a "traditional" testing style that compares output printed to `sys.stdout`; this style of test is considered deprecated.

参考

`unittest` モジュール

  PyUnit 回帰テストを書く。

`doctest` モジュール

  ドキュメンテーション文字列に埋め込まれたテスト。

## Writing Unit Tests for the `test` package

`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)

  When using this pattern, remember that all classes that inherit from `unittest.TestCase` are run as tests. The `TestFuncAcceptsSequencesMixin` class in the example above does not have any data and so can't be run by itself, thus it does not inherit from `unittest.TestCase`.

参考

Test Driven Development

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

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

The `test` package can be run as a script to drive Python's regression test suite, thanks to the `-m` option: python -m test. Under the hood, it uses `test.regrtest`; the call python -m test.regrtest used in previous Python versions still works. Running the script by itself automatically starts running all regression tests in the `test` package. It does this by finding all modules in the package whose name starts with `test_`, importing them, and executing the function `test_main()` if present or loading the tests via unittest.TestLoader.loadTestsFromModule if `test_main` does not exist. The names of tests to execute may also be passed to the script. Specifying a single regression test (python -m test test_spam) will minimize output and only print whether the test passed or failed.

Running `test` directly allows what resources are available for tests to use to be set. You do this by using the `-u` command-line option. Specifying `all` as the value for the `-u` option enables all possible resources: python -m test -uall. If all but one resource is desired (a more common case), a comma-separated list of resources that are not desired may be listed after `all`. The command python -m test -uall,-audio,-largefile will run `test` with all resources except the `audio` and `largefile` resources. For a list of all resources and more command-line options, run python -m test -h.

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

Added in version 3.14: Output is colorized by default and can be controlled using environment variables.

# `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` です。実行中のテストについてのより詳細な情報が欲しいときにチェックします。 verbose は `test.regrtest` によって設定されます。

test.support.is_jython

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

test.support.is_android

  `True` if `sys.platform` is `android`.

test.support.is_emscripten

  `True` if `sys.platform` is `emscripten`.

test.support.is_wasi

  `True` if `sys.platform` is `wasi`.

test.support.is_apple_mobile

  `True` if `sys.platform` is `ios`, `tvos`, or `watchos`.

test.support.is_apple

  `True` if `sys.platform` is `darwin` or `is_apple_mobile` is `True`.

test.support.unix_shell

  Windows 以外ではシェルのパスです; そうでない場合は `None` です。

test.support.LOOPBACK_TIMEOUT

  Timeout in seconds for tests using a network server listening on the network local loopback interface like `127.0.0.1`.

  The timeout is long enough to prevent test failure: it takes into account that the client and the server can run in different threads or even different processes.

  The timeout should be long enough for `connect()`, `recv()` and `send()` methods of `socket.socket`.

  デフォルト値は5秒です。

  `INTERNET_TIMEOUT` も参照してください。

test.support.INTERNET_TIMEOUT

  Timeout in seconds for network requests going to the internet.

  The timeout is short enough to prevent a test to wait for too long if the internet request is blocked for whatever reason.

  Usually, a timeout using `INTERNET_TIMEOUT` should not mark a test as failed, but skip the test instead: see `transient_internet()`.

  デフォルト値は1分です。

  `LOOPBACK_TIMEOUT` も参照してください。

test.support.SHORT_TIMEOUT

  Timeout in seconds to mark a test as failed if the test takes "too long".

  The timeout value depends on the regrtest `--timeout` command line option.

  If a test using `SHORT_TIMEOUT` starts to fail randomly on slow buildbots, use `LONG_TIMEOUT` instead.

  デフォルト値は30秒です。

test.support.LONG_TIMEOUT

  Timeout in seconds to detect when a test hangs.

  It is long enough to reduce the risk of test failure on the slowest Python buildbots. It should not be used to mark a test as failed if the test takes "too long". The timeout value depends on the regrtest `--timeout` command line option.

  デフォルト値は5分です。

  See also `LOOPBACK_TIMEOUT`, `INTERNET_TIMEOUT` and `SHORT_TIMEOUT`.

test.support.PGO

  テストが PGO (Profile Guided Optimization) の役に立たないときにスキップできるなら設定します。

test.support.PIPE_MAX_SIZE

  書き込みをブロックするための、基底にある OS のパイプバッファサイズより大きいであろう定数。

test.support.Py_DEBUG

  `True` if Python was built with the `Py_DEBUG` macro defined, that is, if Python was built in debug mode.

  Added in version 3.12.

test.support.SOCK_MAX_SIZE

  書き込みをブロックするための、基底にある OS のソケットバッファサイズより大きいであろう定数。

test.support.TEST_SUPPORT_DIR

  `test.support` を含んだトップディレクトリを設定します。

test.support.TEST_HOME_DIR

  テストパッケージのトップディレクトリを設定します。

test.support.TEST_DATA_DIR

  テストパッケージ内の `data` ディレクトリを設定します。

test.support.MAX_Py_ssize_t

  大量のメモリを使うテストのための `sys.maxsize` を設定します。

test.support.max_memuse

  大量のメモリを使うテストのためのメモリ上限となる `set_memlimit()` を設定します。 `MAX_Py_ssize_t` が設定上限です。

test.support.real_max_memuse

  大量のメモリを使うテストのためのメモリ上限となる `set_memlimit()` を設定します。 `MAX_Py_ssize_t` の設定上限はありません。

test.support.MISSING_C_DOCSTRINGS

  Set to `True` if Python is built without docstrings (the `WITH_DOC_STRINGS` macro is not defined). See the `configure --without-doc-strings` option.

  See also the `HAVE_DOCSTRINGS` variable.

test.support.HAVE_DOCSTRINGS

  Set to `True` if function docstrings are available. See the `python -OO` option, which strips docstrings of functions implemented in Python.

  See also the `MISSING_C_DOCSTRINGS` variable.

test.support.TEST_HTTP_URL

  ネットワークテスト専用の HTTP サーバーの URL を定義します。

test.support.ALWAYS_EQ

  Object that is equal to anything. Used to test mixed type comparison.

test.support.NEVER_EQ

  Object that is not equal to anything (even to `ALWAYS_EQ`). Used to test mixed type comparison.

test.support.LARGEST

  Object that is greater than anything (except itself). Used to test mixed type comparison.

test.support.SMALLEST

  Object that is less than anything (except itself). Used to test mixed type comparison.

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

test.support.busy_retry(timeout, err_msg=None, /, *, error=True)

  Run the loop body until `break` stops the loop.

  After timeout seconds, raise an `AssertionError` if error is true, or just stop the loop if error is false.

  以下はプログラム例です:

      for _ in support.busy_retry(support.SHORT_TIMEOUT):
          if check():
              break

  Example of error=False usage:

      for _ in support.busy_retry(support.SHORT_TIMEOUT, error=False):
          if check():
              break
      else:
          raise RuntimeError('my custom error')

test.support.sleeping_retry(timeout, err_msg=None, /, *, init_delay=0.010, max_delay=1.0, error=True)

  Wait strategy that applies exponential backoff.

  Run the loop body until `break` stops the loop. Sleep at each loop iteration, but not at the first iteration. The sleep delay is doubled at each iteration (up to max_delay seconds).

  See `busy_retry()` documentation for the parameters usage.

  Example raising an exception after SHORT_TIMEOUT seconds:

      for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
          if check():
              break

  Example of error=False usage:

      for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False):
          if check():
              break
      else:
          raise RuntimeError('my custom error')

test.support.is_resource_enabled(resource)

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

test.support.get_resource_value(resource)

  Return the value specified for resource (as `-u resource=value`). Return `None` if resource is disabled or no value is specified.

test.support.python_is_optimized()

  Return `True` if Python was not built with `-O0` or `-Og`.

test.support.with_pymalloc()

  Return `_testcapi.WITH_PYMALLOC`.

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

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

test.support.sortdict(dict)

  Return a repr of dict with keys sorted.

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

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

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

test.support.get_pagesize()

  Get size of a page in bytes.

  Added in version 3.12.

test.support.setswitchinterval(interval)

  Set the `sys.setswitchinterval()` to the given interval. Defines a minimum interval for Android systems to prevent the system from hanging.

test.support.check_impl_detail(**guards)

  Use this check to guard CPython's implementation-specific tests or to run them only on the implementations guarded by the arguments. This function returns `True` or `False` depending on the host platform. Example usage:

      check_impl_detail()               # Only on CPython (default).
      check_impl_detail(jython=True)    # Only on Jython.
      check_impl_detail(cpython=False)  # Everywhere except CPython.

test.support.set_memlimit(limit)

  Set the values for `max_memuse` and `real_max_memuse` for big memory tests.

test.support.record_original_stdout(stdout)

  Store the value from stdout. It is meant to hold the stdout at the time the regrtest began.

test.support.get_original_stdout()

  Return the original stdout set by `record_original_stdout()` or `sys.stdout` if it's not set.

test.support.args_from_interpreter_flags()

  Return a list of command line arguments reproducing the current settings in `sys.flags` and `sys.warnoptions`.

test.support.optim_args_from_interpreter_flags()

  Return a list of command line arguments reproducing the current optimization settings in `sys.flags`.

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.disable_faulthandler()

  A context manager that temporary disables `faulthandler`.

test.support.gc_collect()

  Force as many objects as possible to be collected. This is needed because timely deallocation is not guaranteed by the garbage collector. This means that `__del__` methods may be called later than expected and weakrefs may remain alive for longer than expected.

test.support.disable_gc()

  A context manager that disables the garbage collector on entry. On exit, the garbage collector is restored to its prior state.

test.support.swap_attr(obj, attr, new_val)

  Context manager to swap out an attribute with a new object.

  使い方:

      with swap_attr(obj, "attr", 5):
          ...

  This will set `obj.attr` to 5 for the duration of the `with` block, restoring the old value at the end of the block. If `attr` doesn't exist on `obj`, it will be created and then deleted at the end of the block.

  The old value (or `None` if it doesn't exist) will be assigned to the target of the "as" clause, if there is one.

test.support.swap_item(obj, attr, new_val)

  Context manager to swap out an item with a new object.

  使い方:

      with swap_item(obj, "item", 5):
          ...

  This will set `obj["item"]` to 5 for the duration of the `with` block, restoring the old value at the end of the block. If `item` doesn't exist on `obj`, it will be created and then deleted at the end of the block.

  The old value (or `None` if it doesn't exist) will be assigned to the target of the "as" clause, if there is one.

test.support.flush_std_streams()

  Call the `flush()` method on `sys.stdout` and then on `sys.stderr`. It can be used to make sure that the logs order is consistent before writing into stderr.

  Added in version 3.11.

test.support.print_warning(msg)

  Print a warning into `sys.__stderr__`. Format the message as: `f"Warning -- {msg}"`. If msg is made of multiple lines, add `"Warning -- "` prefix to each line.

  Added in version 3.9.

test.support.wait_process(pid, *, exitcode, timeout=None)

  Wait until process pid completes and check that the process exit code is exitcode.

  Raise an `AssertionError` if the process exit code is not equal to exitcode.

  If the process runs longer than timeout seconds (`SHORT_TIMEOUT` by default), kill the process and raise an `AssertionError`. The timeout feature is not available on Windows.

  Added in version 3.9.

test.support.calcobjsize(fmt)

  Return the size of the `PyObject` whose structure members are defined by fmt. The returned value includes the size of the Python object header and alignment.

test.support.calcvobjsize(fmt)

  Return the size of the `PyVarObject` whose structure members are defined by fmt. The returned value includes the size of the Python object header and alignment.

test.support.checksizeof(test, o, size)

  For testcase test, assert that the `sys.getsizeof` for o plus the GC header size equals size.

@test.support.anticipate_failure(condition)

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

test.support.system_must_validate_cert(f)

  A decorator that skips the decorated test on TLS certification validation failures.

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

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

@test.support.run_with_tz(tz)

  A decorator for running a function in a specific timezone, correctly resetting it after it has finished.

@test.support.requires_freebsd_version(*min_version)

  Decorator for the minimum version when running test on FreeBSD. If the FreeBSD version is less than the minimum, the test is skipped.

@test.support.requires_linux_version(*min_version)

  Decorator for the minimum version when running test on Linux. If the Linux version is less than the minimum, the test is skipped.

@test.support.requires_mac_version(*min_version)

  Decorator for the minimum version when running test on macOS. If the macOS version is less than the minimum, the test is skipped.

@test.support.requires_gil_enabled

  Decorator for skipping tests on the free-threaded build. If the GIL is disabled, the test is skipped.

@test.support.requires_IEEE_754

  Decorator for skipping tests on non-IEEE 754 platforms.

@test.support.requires_zlib

  Decorator for skipping tests if `zlib` doesn't exist.

@test.support.requires_gzip

  Decorator for skipping tests if `gzip` doesn't exist.

@test.support.requires_bz2

  Decorator for skipping tests if `bz2` doesn't exist.

@test.support.requires_lzma

  Decorator for skipping tests if `lzma` doesn't exist.

@test.support.requires_resource(resource)

  Decorator for skipping tests if resource is not available.

@test.support.requires_docstrings

  Decorator for only running the test if `HAVE_DOCSTRINGS`.

@test.support.requires_limited_api

  Decorator for only running the test if Limited C API is available.

@test.support.cpython_only

  Decorator for tests only applicable to CPython.

@test.support.impl_detail(msg=None, **guards)

  Decorator for invoking `check_impl_detail()` on guards. If that returns `False`, then uses msg as the reason for skipping the test.

@test.support.thread_unsafe(reason=None)

  Decorator for marking tests as thread-unsafe. This test always runs in one thread even when invoked with `--parallel-threads`.

@test.support.no_tracing

  Decorator to temporarily turn off tracing for the duration of the test.

@test.support.refcount_test

  Decorator for tests which involve reference counting. The decorator does not run the test if it is not run by CPython. Any trace function is unset for the duration of the test to prevent unexpected refcounts caused by the trace function.

@test.support.bigmemtest(size, memuse, dry_run=True)

  Decorator for bigmem tests.

  size is a requested size for the test (in arbitrary, test-interpreted units.) memuse is the number of bytes per unit for the test, or a good estimate of it. For example, a test that needs two byte buffers, of 4 GiB each, could be decorated with `@bigmemtest(size=_4G, memuse=2)`.

  The size argument is normally passed to the decorated test method as an extra argument. If dry_run is `True`, the value passed to the test method may be less than the requested value. If dry_run is `False`, it means the test doesn't support dummy runs when `-M` is not specified.

@test.support.bigaddrspacetest

  Decorator for tests that fill the address space.

test.support.linked_to_musl()

  Return `False` if there is no evidence the interpreter was compiled with `musl`, otherwise return a version triple, either `(0, 0, 0)` if the version is unknown, or the actual version if it is known. Intended for use in `skip` decorators. `emscripten` and `wasi` are assumed to be compiled with `musl`; otherwise `platform.libc_ver` is checked.

test.support.check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None)

  Test for syntax errors in statement by attempting to compile statement. testcase is the `unittest` instance for the test. errtext is the regular expression which should match the string representation of the raised `SyntaxError`. If lineno is not `None`, compares to the line of the exception. If offset is not `None`, compares to the offset of the exception.

test.support.open_urlresource(url, *args, **kw)

  Open url. If open fails, raises `TestFailed`.

test.support.reap_children()

  Use this at the end of `test_main` whenever sub-processes are started. This will help ensure that no extra children (zombies) stick around to hog resources and create problems when looking for refleaks.

test.support.get_attribute(obj, name)

  Get an attribute, raising `unittest.SkipTest` if `AttributeError` is raised.

test.support.catch_unraisable_exception()

  Context manager catching unraisable exception using `sys.unraisablehook()`.

  Storing the exception value (`cm.unraisable.exc_value`) creates a reference cycle. The reference cycle is broken explicitly when the context manager exits.

  Storing the object (`cm.unraisable.object`) can resurrect it if it is set to an object which is being finalized. Exiting the context manager clears the stored object.

  使い方:

      with support.catch_unraisable_exception() as cm:
          # code creating an "unraisable exception"
          ...

          # check the unraisable exception: use cm.unraisable
          ...

      # cm.unraisable attribute no longer exists at this point
      # (to break a reference cycle)

  Added in version 3.8.

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 '__'.

  Added in version 3.5.

test.support.patch(test_instance, object_to_patch, attr_name, new_value)

  Override object_to_patch.attr_name with new_value. Also add cleanup procedure to test_instance to restore object_to_patch for attr_name. The attr_name should be a valid attribute for object_to_patch.

test.support.run_in_subinterp(code)

  Run code in subinterpreter. Raise `unittest.SkipTest` if `tracemalloc` is enabled.

test.support.check_free_after_iterating(test, iter, cls, args=())

  Assert instances of cls are deallocated after iterating.

test.support.missing_compiler_executable(cmd_names=[])

  Check for the existence of the compiler executables whose names are listed in cmd_names or all the compiler executables when cmd_names is empty and return the first missing executable or `None` when none is found missing.

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

  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 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 not_exported 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'}
              not_exported = {'baz'}  # Undocumented name.
              # bar imports part of its API from _bar.
              support.check__all__(self, bar, ('bar', '_bar'),
                                   extra=extra, not_exported=not_exported)

  Added in version 3.6.

test.support.skip_if_broken_multiprocessing_synchronize()

  Skip tests if the `multiprocessing.synchronize` module is missing, if there is no available semaphore implementation, or if creating a lock raises an `OSError`.

  Added in version 3.10.

test.support.check_disallow_instantiation(test_case, tp, *args, **kwds)

  Assert that type tp cannot be instantiated using args and kwds.

  Added in version 3.10.

test.support.adjust_int_max_str_digits(max_digits)

  This function returns a context manager that will change the global `sys.set_int_max_str_digits()` setting for the duration of the context to allow execution of test code that needs a different limit on the number of digits when converting between an integer and string.

  Added in version 3.11.

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

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.SaveSignals

  Class to save and restore signal handlers registered by the Python signal handler.

  save(self)

    Save the signal handlers to a dictionary mapping signal numbers to the current signal handler.

  restore(self)

    Set the signal numbers from the `save()` dictionary to the saved handler.

class test.support.Matcher
  matches(self, d, **kwargs)

    Try to match a single dict with the supplied arguments.

  match_value(self, k, dv, v)

    Try to match a single stored value (dv) with a supplied value (v).

# `test.support.socket_helper` --- Utilities for socket tests

The `test.support.socket_helper` module provides support for socket tests.

Added in version 3.9.

test.support.socket_helper.IPV6_ENABLED

  Set to `True` if IPv6 is enabled on this host, `False` otherwise.

test.support.socket_helper.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.socket_helper.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.socket_helper.bind_unix_socket(sock, addr)

  Bind a Unix socket, raising `unittest.SkipTest` if `PermissionError` is raised.

@test.support.socket_helper.skip_unless_bind_unix_socket

  A decorator for running tests that require a functional `bind()` for Unix sockets.

test.support.socket_helper.transient_internet(resource_name, *, timeout=30.0, errnos=())

  A context manager that raises `ResourceDenied` when various issues with the internet connection manifest themselves as exceptions.

# `test.support.script_helper` --- Utilities for the Python execution tests

The `test.support.script_helper` module provides support for Python's script execution tests.

test.support.script_helper.interpreter_requires_environment()

  Return `True` if `sys.executable interpreter` requires environment variables in order to be able to run at all.

  This is designed to be used with `@unittest.skipIf()` to annotate tests that need to use an `assert_python*()` function to launch an isolated mode (`-I`) or no environment mode (`-E`) sub-interpreter process.

  A normal build & test does not run into this situation but it can happen when trying to run the standard library test suite from an interpreter that doesn't have an obvious home with Python's current home finding logic.

  Setting `PYTHONHOME` is one way to get most of the testsuite to run in that situation. `PYTHONPATH` or `PYTHONUSERSITE` are other common environment variables that might impact whether or not the interpreter can start.

test.support.script_helper.run_python_until_end(*args, **env_vars)

  Set up the environment based on env_vars for running the interpreter in a subprocess. The values can include `__isolated`, `__cleanenv`, `__cwd`, and `TERM`.

  バージョン 3.9 で変更: The function no longer strips whitespaces from stderr.

test.support.script_helper.assert_python_ok(*args, **env_vars)

  Assert that running the interpreter with args and optional environment variables env_vars succeeds (`rc == 0`) and return a `(return code, stdout, stderr)` tuple.

  If the __cleanenv keyword-only parameter is set, env_vars is used as a fresh environment.

  Python is started in isolated mode (command line option `-I`), except if the __isolated keyword-only parameter is set to `False`.

  バージョン 3.9 で変更: The function no longer strips whitespaces from stderr.

test.support.script_helper.assert_python_failure(*args, **env_vars)

  Assert that running the interpreter with args and optional environment variables env_vars fails (`rc != 0`) and return a `(return code, stdout, stderr)` tuple.

  See `assert_python_ok()` for more options.

  バージョン 3.9 で変更: The function no longer strips whitespaces from stderr.

test.support.script_helper.spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)

  Run a Python subprocess with the given arguments.

  kw is extra keyword args to pass to `subprocess.Popen()`. Returns a `subprocess.Popen` object.

test.support.script_helper.kill_python(p)

  Run the given `subprocess.Popen` process until completion and return stdout.

test.support.script_helper.make_script(script_dir, script_basename, source, omit_suffix=False)

  Create script containing source in path script_dir and script_basename. If omit_suffix is `False`, append `.py` to the name. Return the full script path.

test.support.script_helper.make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None)

  Create zip file at zip_dir and zip_basename with extension `zip` which contains the files in script_name. name_in_zip is the archive name. Return a tuple containing `(full path, full path of archive name)`.

test.support.script_helper.make_pkg(pkg_dir, init_source='')

  Create a directory named pkg_dir containing an `__init__` file with init_source as its contents.

test.support.script_helper.make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source, depth=1, compiled=False)

  Create a zip package directory with a path of zip_dir and zip_basename containing an empty `__init__` file and a file script_basename containing the source. If compiled is `True`, both source files will be compiled and added to the zip package. Return a tuple of the full zip path and the archive name for the zip file.

# `test.support.bytecode_helper` --- Support tools for testing correct bytecode generation

The `test.support.bytecode_helper` module provides support for testing and inspecting bytecode generation.

Added in version 3.9.

The module defines the following class:

class test.support.bytecode_helper.BytecodeTestCase(unittest.TestCase)

  This class has custom assertion methods for inspecting bytecode.

BytecodeTestCase.get_disassembly_as_string(co)

  Return the disassembly of co as string.

BytecodeTestCase.assertInBytecode(x, opname, argval=_UNSPECIFIED)

  Return instr if opname is found, otherwise throws `AssertionError`.

BytecodeTestCase.assertNotInBytecode(x, opname, argval=_UNSPECIFIED)

  Throws `AssertionError` if opname is found.

# `test.support.threading_helper` --- Utilities for threading tests

The `test.support.threading_helper` module provides support for threading tests.

Added in version 3.10.

test.support.threading_helper.join_thread(thread, timeout=None)

  Join a thread within timeout. Raise an `AssertionError` if thread is still alive after timeout seconds.

@test.support.threading_helper.reap_threads

  Decorator to ensure the threads are cleaned up even if the test fails.

test.support.threading_helper.start_threads(threads, unlock=None)

  Context manager to start threads, which is a sequence of threads. unlock is a function called after the threads are started, even if an exception was raised; an example would be `threading.Event.set()`. `start_threads` will attempt to join the started threads upon exit.

test.support.threading_helper.threading_cleanup(*original_values)

  Cleanup up threads not specified in original_values. Designed to emit a warning if a test leaves running threads in the background.

test.support.threading_helper.threading_setup()

  Return current thread count and copy of dangling threads.

test.support.threading_helper.wait_threads_exit(timeout=None)

  Context manager to wait until all threads created in the `with` statement exit.

test.support.threading_helper.catch_threading_exception()

  Context manager catching `threading.Thread` exception using `threading.excepthook()`.

  Attributes set when an exception is caught:

  - `exc_type`

  - `exc_value`

  - `exc_traceback`

  - `thread`

  See `threading.excepthook()` documentation.

  These attributes are deleted at the context manager exit.

  使い方:

      with threading_helper.catch_threading_exception() as cm:
          # code spawning a thread which raises an exception
          ...

          # check the thread exception, use cm attributes:
          # exc_type, exc_value, exc_traceback, thread
          ...

      # exc_type, exc_value, exc_traceback, thread attributes of cm no longer
      # exists at this point
      # (to avoid reference cycles)

  Added in version 3.8.

test.support.threading_helper.run_concurrently(worker_func, nthreads, args=(), kwargs={})

  Run the worker function concurrently in multiple threads. Re-raises an exception if any thread raises one, after all threads have finished.

# `test.support.os_helper` --- Utilities for os tests

The `test.support.os_helper` module provides support for os tests.

Added in version 3.10.

test.support.os_helper.FS_NONASCII

  `os.fsencode()` でエンコードできる 非 ASCII 文字。

test.support.os_helper.SAVEDCWD

  `os.getcwd()` に設定されます。

test.support.os_helper.TESTFN

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

test.support.os_helper.TESTFN_NONASCII

  Set to a filename containing the `FS_NONASCII` character, if it exists. This guarantees that if the filename exists, it can be encoded and decoded with the default filesystem encoding. This allows tests that require a non-ASCII filename to be easily skipped on platforms where they can't work.

test.support.os_helper.TESTFN_UNENCODABLE

  strictモードのファイルシステムエンコーディングでエンコードできないファイル名（str型）に設定します。そのようなファイル名を生成できない場合は、 `None` になる可能性があります。

test.support.os_helper.TESTFN_UNDECODABLE

  strictモードのファイルシステムエンコーディングでデコードできないファイル名（bytes型）に設定します。そのようなファイル名を生成できない場合は、 `None` になる可能性があります。

test.support.os_helper.TESTFN_UNICODE

  非 ASCII 名を一時ファイルに設定します。

class test.support.os_helper.EnvironmentVarGuard

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

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

class test.support.os_helper.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__()`.

EnvironmentVarGuard.set(envvar, value)

  一時的に、 `envvar` を `value` にセットします。

EnvironmentVarGuard.unset(envvar, *others)

  Temporarily unset one or more environment variables.

  バージョン 3.14 で変更: More than one environment variable can be unset.

test.support.os_helper.can_symlink()

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

test.support.os_helper.can_xattr()

  Return `True` if the OS supports xattr, `False` otherwise.

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

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

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

test.support.os_helper.create_empty_file(filename)

  Create an empty file with filename. If it already exists, truncate it.

test.support.os_helper.fd_count()

  Count the number of open file descriptors.

test.support.os_helper.fs_is_case_insensitive(directory)

  Return `True` if the file system for directory is case-insensitive.

test.support.os_helper.make_bad_fd()

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

test.support.os_helper.rmdir(filename)

  Call `os.rmdir()` on filename. On Windows platforms, this is wrapped with a wait loop that checks for the existence of the file, which is needed due to antivirus programs that can hold files open and prevent deletion.

test.support.os_helper.rmtree(path)

  Call `shutil.rmtree()` on path or call `os.lstat()` and `os.rmdir()` to remove a path and its contents. As with `rmdir()`, on Windows platforms this is wrapped with a wait loop that checks for the existence of the files.

@test.support.os_helper.skip_unless_symlink

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

@test.support.os_helper.skip_unless_xattr

  A decorator for running tests that require support for xattr.

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

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

  一時的にカレントディレクトリを変更する前に、カレントディレクトリに name という名前のディレクトリを作成します。 name が `None` の場合は、一時ディレクトリは `tempfile.mkdtemp()` を使って作成されます。

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

test.support.os_helper.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.os_helper.temp_umask(umask)

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

test.support.os_helper.unlink(filename)

  Call `os.unlink()` on filename. As with `rmdir()`, on Windows platforms, this is wrapped with a wait loop that checks for the existence of the file.

# `test.support.import_helper` --- Utilities for import tests

The `test.support.import_helper` module provides support for import tests.

Added in version 3.10.

test.support.import_helper.forget(module_name)

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

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

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

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

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

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

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

  指定したモジュールがインポートできなかった場合に、この関数は `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'])

  Added in version 3.1.

test.support.import_helper.import_module(name, deprecated=False, *, required_on=())

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

  Module and package deprecation messages are suppressed during this import if deprecated is `True`. If a module is required on a platform but optional for others, set required_on to an iterable of platform prefixes which will be compared against `sys.platform`.

  Added in version 3.1.

test.support.import_helper.modules_setup()

  Return a copy of `sys.modules`.

test.support.import_helper.modules_cleanup(oldmodules)

  Remove modules except for oldmodules and `encodings` in order to preserve internal cache.

test.support.import_helper.unload(name)

  `sys.modules` から name を削除します。

test.support.import_helper.make_legacy_pyc(source)

  Move a PEP 3147/PEP 488 pyc file to its legacy pyc location and return the file system path to the legacy pyc file. The source value is the file system path to the source file. It does not need to exist, however the PEP 3147/488 pyc file must exist.

class test.support.import_helper.CleanImport(*module_names)

  A context manager to force import to return a new module reference. This is useful for testing module-level behaviors, such as the emission of a `DeprecationWarning` on import. Example usage:

      with CleanImport('foo'):
          importlib.import_module('foo')  # New reference.

class test.support.import_helper.DirsOnSysPath(*paths)

  A context manager to temporarily add directories to `sys.path`.

  This makes a copy of `sys.path`, appends any directories given as positional arguments, then reverts `sys.path` to the copied settings when the context ends.

  Note that all `sys.path` modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block.

# `test.support.warnings_helper` --- Utilities for warnings tests

The `test.support.warnings_helper` module provides support for warnings tests.

Added in version 3.10.

test.support.warnings_helper.ignore_warnings(*, category)

  Suppress warnings that are instances of category, which must be `Warning` or a subclass. Roughly equivalent to `warnings.catch_warnings()` with `warnings.simplefilter('ignore', category=category)`. For example:

      @warning_helper.ignore_warnings(category=DeprecationWarning)
      def test_suppress_warning():
          # do something

  Added in version 3.8.

test.support.warnings_helper.check_no_resource_warning(testcase)

  Context manager to check that no `ResourceWarning` was raised. You must remove the object which may emit `ResourceWarning` before the end of the context manager.

test.support.warnings_helper.check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None)

  Test for syntax warning in statement by attempting to compile statement. Test also that the `SyntaxWarning` is emitted only once, and that it will be converted to a `SyntaxError` when turned into error. testcase is the `unittest` instance for the test. errtext is the regular expression which should match the string representation of the emitted `SyntaxWarning` and raised `SyntaxError`. If lineno is not `None`, compares to the line of the warning and exception. If offset is not `None`, compares to the offset of the exception.

  Added in version 3.8.

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

  A convenience wrapper for `warnings.catch_warnings()` that makes it easier to test that a warning was correctly raised. It is approximately equivalent to calling `warnings.catch_warnings(record=True)` with `warnings.simplefilter()` set to `always` and with the option to automatically validate the results that are recorded.

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

  引数が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 で変更: 新しいオプション引数 filters と quiet

class test.support.warnings_helper.WarningsRecorder

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