"test" --- Python 用回帰テストパッケージ
****************************************

注釈:

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

======================================================================

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

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

参考:

  "unittest" モジュール
     PyUnit 回帰テストを書く。

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


"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 の著書。


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

"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** とすると、 "audio" と
"largefile" リソースを除く全てのリソースを使って "test" を実行します。
すべてのリソースのリストと追加のコマンドラインオプションを出力するには
、 **python -m test -h** を実行してください。

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


"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

   システムが Android の場合 "True" になります。

test.support.unix_shell

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

test.support.FS_NONASCII

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

test.support.TESTFN

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

test.support.TESTFN_UNICODE

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

test.support.TESTFN_ENCODING

   "sys.getfilesystemencoding()" を設定します。

test.support.TESTFN_UNENCODABLE

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

test.support.TESTFN_UNDECODABLE

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

test.support.TESTFN_NONASCII

   "FS_NONASCII" 文字を含むファイル名を設定します。

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

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

test.support.PGO

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

test.support.PIPE_MAX_SIZE

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

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

   CPython 上で実行されていて、Windows 上ではなく、 "WITH_DOC_STRINGS"
   が設定されていない場合に "True" を返します。

test.support.HAVE_DOCSTRINGS

   docstring があるかを確認します。

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.forget(module_name)

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

test.support.unload(name)

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

test.support.unlink(filename)

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

test.support.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.

test.support.rmtree(path)

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

test.support.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.

test.support.is_resource_enabled(resource)

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

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.system_must_validate_cert(f)

   Raise "unittest.SkipTest" on TLS certification validation failures.

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.create_empty_file(filename)

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

test.support.fd_count()

   Count the number of open file descriptors.

test.support.match_test(test)

   Match *test* to patterns set in "set_match_tests()".

test.support.set_match_tests(patterns)

   Define match test with regular expression *patterns*.

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, optionflags=0)

   与えられた *module* の "doctest.testmod()" を実行します。
   "(failure_count, test_count)" を返します。

   If *verbosity* is "None", "doctest.testmod()" is run with verbosity
   set to "verbose".  Otherwise, it is run with verbosity set to
   "None".  *optionflags* is passed as "optionflags" to
   "doctest.testmod()".

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:

      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.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* が
   与えられた場合や、オプションのキーワード引数 *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*

test.support.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.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.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* に変更し与えるコンテキストマ
   ネージャです。

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

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

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

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

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

test.support.temp_umask(umask)

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

test.support.disable_faulthandler()

   A context manager that replaces "sys.stderr" with "sys.__stderr__".

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 upon entry
   and reenables it upon exit.

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

   バージョン 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.

   バージョン 3.9 で追加.

test.support.wait_threads_exit(timeout=60.0)

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

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

   Context manager to start *threads*.  It attempts to join the
   threads upon exit.

test.support.calcobjsize(fmt)

   Return "struct.calcsize()" for "nP{fmt}0n" or, if
   "gettotalrefcount" exists, "2PnP{fmt}0P".

test.support.calcvobjsize(fmt)

   Return "struct.calcsize()" for "nPn{fmt}0n" or, if
   "gettotalrefcount" exists, "2PnPn{fmt}0P".

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

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

test.support.can_xattr()

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

@test.support.skip_unless_symlink

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

@test.support.skip_unless_xattr

   A decorator for running tests that require support for xattr.

@test.support.anticipate_failure(condition)

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

@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, raise
   "unittest.SkipTest".

@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, raise
   "unittest.SkipTest".

@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, raise
   "unittest.SkipTest".

@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.cpython_only(test)

   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.no_tracing(func)

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

@test.support.refcount_test(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.reap_threads(func)

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

@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(f)

   Decorator for tests that fill the address space.  *f* is the
   function to wrap.

test.support.make_bad_fd()

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

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

   バージョン 3.8 で追加.

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

   Open *url*.  If open fails, raises "TestFailed".

test.support.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".

   バージョン 3.1 で追加.

test.support.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'])

   バージョン 3.1 で追加.

test.support.modules_setup()

   Return a copy of "sys.modules".

test.support.modules_cleanup(oldmodules)

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

test.support.threading_setup()

   Return current thread count and copy of dangling threads.

test.support.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.join_thread(thread, timeout=30.0)

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

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_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 support.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)

   バージョン 3.8 で追加.

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)

   バージョン 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.fs_is_case_insensitive(directory)

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

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.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 that *iter* is 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=(), 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 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.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.

   バージョン 3.9.14 で追加.

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

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

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

class test.support.EnvironmentVarGuard

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

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

EnvironmentVarGuard.set(envvar, value)

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

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

class test.support.SaveSignals

   Class to save and restore signal handlers registered by the Python
   signal 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*).

class test.support.WarningsRecorder

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

class test.support.BasicTestRunner

   run(test)

      Run *test* and return the result.

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__()".


"test.support.socket_helper" --- Utilities for socket tests
***********************************************************

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

バージョン 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 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 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.

バージョン 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.
