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

   def test_main():
       support.run_unittest(MyTestCase1,
                            MyTestCase2,
                            ... list other tests ...
                            )

   if __name__ == '__main__':
       test_main()

This boilerplate code allows the testing suite to be run by
"test.regrtest" as well as on its own as a script.

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

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

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

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

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

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

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

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

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

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

     class TestFuncAcceptsSequences(unittest.TestCase):

         func = mySuperWhammyFunction

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

     class AcceptLists(TestFuncAcceptsSequences):
         arg = [1, 2, 3]

     class AcceptStrings(TestFuncAcceptsSequences):
         arg = 'abc'

     class AcceptTuples(TestFuncAcceptsSequences):
         arg = (1, 2, 3)

参考:

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


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

The "test.regrtest" module can be run as a script to drive Python’s
regression test suite, thanks to the "-m" option: **python -m
test.regrtest**. 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.
The names of tests to execute may also be passed to the script.
Specifying a single regression test (**python -m test.regrtest
test_spam**) will minimize output and only print whether the test
passed or failed and thus minimize output.

Running "test.regrtest" 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.regrtest -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.regrtest -uall,-audio,-largefile** will run
"test.regrtest" with all resources except the "audio" and "largefile"
resources. For a list of all resources and more command-line options,
run **python -m test.regrtest -h**.

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

バージョン 2.7.14 で変更: The "test" package can be run as a script:
**python -m test**. This works the same as running the "test.regrtest"
module.


"test.support" — Utility functions for tests
********************************************

注釈: The "test.test_support" module has been renamed to
  "test.support" in Python 3.x and 2.7.14.  The name
  "test.test_support" has been retained as an alias in 2.7.

The "test.support" module provides support for Python’s regression
tests.

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

exception test.support.TestFailed

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

exception test.support.ResourceDenied

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

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

test.support.verbose

   "True" when verbose output is enabled. Should be checked when more
   detailed information is desired about a running test. *verbose* is
   set by "test.regrtest".

test.support.have_unicode

   "True" when Unicode support is available.

test.support.is_jython

   "True" if the running interpreter is Jython.

test.support.TESTFN

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

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

test.support.forget(module_name)

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

test.support.is_resource_enabled(resource)

   Return "True" if *resource* is enabled and available. The list of
   available resources is only set when "test.regrtest" is executing
   the tests.

test.support.requires(resource[, msg])

   Raise "ResourceDenied" if *resource* is not available. *msg* is the
   argument to "ResourceDenied" if it is raised. Always returns "True"
   if called by a function whose "__name__" is "'__main__'". Used when
   tests are executed by "test.regrtest".

test.support.findfile(filename)

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

test.support.run_unittest(*classes)

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

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

      def test_main():
          support.run_unittest(__name__)

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

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

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

   "check_warnings" accepts 2-tuples of the form "("message regexp",
   WarningCategory)" as positional arguments. If one or more *filters*
   are provided, or if the optional keyword argument *quiet* is
   "False", it checks to make sure the warnings are as expected:  each
   specified filter must match at least one of the warnings raised by
   the enclosed code or the test fails, and if any warnings are raised
   that do not match any of the specified filters the test fails.  To
   disable the first of these checks, set *quiet* to "True".

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

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

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

   On entry to the context manager, a "WarningRecorder" instance is
   returned. The underlying warnings list from "catch_warnings()" is
   available via the recorder object’s "warnings" attribute.  As a
   convenience, the attributes of the object representing the most
   recent warning can also be accessed directly through the recorder
   object (see example below).  If no warning has been raised, then
   any of the attributes that would otherwise be expected on an object
   representing a warning will return "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

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

   バージョン 2.6 で追加.

   バージョン 2.7 で変更: 新しいオプション引数 *filters* と *quiet*

test.support.check_py3k_warnings(*filters, quiet=False)

   Similar to "check_warnings()", but for Python 3 compatibility
   warnings. If "sys.py3kwarning == 1", it checks if the warning is
   effectively raised. If "sys.py3kwarning == 0", it checks that no
   warning is raised.  It accepts 2-tuples of the form "("message
   regexp", WarningCategory)" as positional arguments.  When the
   optional keyword argument *quiet* is "True", it does not fail if a
   filter catches nothing.  Without arguments, it defaults to:

      check_py3k_warnings(("", DeprecationWarning), quiet=False)

   バージョン 2.7 で追加.

test.support.captured_stdout()

   This is a context manager that runs the "with" statement body using
   a "StringIO.StringIO" object as sys.stdout.  That object can be
   retrieved using the "as" clause of the "with" statement.

   使用例:

      with captured_stdout() as s:
          print "hello"
      assert s.getvalue() == "hello\n"

   バージョン 2.6 で追加.

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

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

   Module and package deprecation messages are suppressed during this
   import if *deprecated* is "True".

   バージョン 2.7 で追加.

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

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

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

   *blocked* is an iterable of module names that are replaced with "0"
   in the module cache during the import to ensure that attempts to
   import them raise "ImportError".

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

   Module and package deprecation messages are suppressed during this
   import if *deprecated* is "True".

   This function will raise "unittest.SkipTest" if the named module
   cannot be imported.

   使用例:

      # 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'])

   バージョン 2.7 で追加.

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

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

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

   バージョン 2.6 で追加.

class test.support.EnvironmentVarGuard

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

   バージョン 2.6 で追加.

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

EnvironmentVarGuard.set(envvar, value)

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

EnvironmentVarGuard.unset(envvar)

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

class test.support.WarningsRecorder

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

   バージョン 2.6 で追加.
