26.8. "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" モジュール
     ドキュメンテーション文字列に埋め込まれたテスト。


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

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

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

   import unittest
   from test import support

   class MyTestCase1(unittest.TestCase):

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

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

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

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

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

       ... more test methods ...

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

   ... more test classes ...

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

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

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

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

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

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

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

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

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

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

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

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

     class TestFuncAcceptsSequencesMixin:

         func = mySuperWhammyFunction

         def test_func(self):
             self.func(self.arg)

     class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
         arg = [1, 2, 3]

     class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
         arg = 'abc'

     class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
         arg = (1, 2, 3)

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

参考:

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


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

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

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

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


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

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

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

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

exception test.support.TestFailed

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

exception test.support.ResourceDenied

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

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

test.support.verbose

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

test.support.is_jython

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

test.support.TESTFN

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

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

test.support.forget(module_name)

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

test.support.is_resource_enabled(resource)

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

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

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

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

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

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

test.support.run_unittest(*classes)

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

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

      def test_main():
          support.run_unittest(__name__)

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

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

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

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

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

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

   "check_warnings" は "("message regexp", WarningCategory)" の形をし
   た 2要素タプルを位置引数として受け取ります。1つ以上の *filters* が
   与えられた場合や、オプションのキーワード引数 *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.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) を変更するコンテキストマネージャです。

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

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

test.support.temp_umask(umask)

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

test.support.can_symlink()

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

@test.support.skip_unless_symlink

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

@test.support.anticipate_failure(condition)

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

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

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

test.support.make_bad_fd()

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

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

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

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

   バージョン 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.bind_port(sock, host=HOST)

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

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

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

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

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

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

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

      import os
      from test.support import load_package_tests

      def load_tests(*args):
          return load_package_tests(os.path.dirname(__file__), *args)

test.support.detect_api_mismatch(ref_api, other_api, *, ignore=())

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

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

   バージョン 3.5 で追加.

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

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

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

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

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

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

   使用例:

      import bar
      import foo
      import unittest
      from test import support

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

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

   バージョン 3.6 で追加.

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

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

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

class test.support.EnvironmentVarGuard

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

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

EnvironmentVarGuard.set(envvar, value)

   一時的に、 "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.WarningsRecorder

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

class test.support.FakePath(path)

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