py.test は よく練られたフック を呼び出すことにより、設定、コレクション、実行、レポートの全箇所で処理を実装します。事実上、任意の Python モジュールをプラグインとして登録できます。このプラグインは、フック関数の区別や検出を容易にして pytest_ という接頭辞をもつ全フック関数から任意のフック関数 (通常は2つか3つ) を実装します。3つの基本的な配置場所があります:
ローカルの conftest.py プラグインは、ディレクトリ固有のフック実装を含みます。セッションとテストの実行処理は、ファイルシステムのルートディレクトリに近い conftest.py ファイルで定義された全てのフックを実行します。ファイルを次の場所に置くと仮定してください:
a/conftest.py:
def pytest_runtest_setup(item):
# 'a' ディレクトリにある各テストの実行向けに呼ばれる
print ("setting up", item)
a/test_in_subdir.py:
def test_sub():
pass
test_flat.py:
def test_flat():
pass
このコードの実行方法です:
py.test test_flat.py # "setting up" を表示しない
py.test a/test_sub.py # "setting up" を表示
注釈
Python パッケージディレクトリ (例えば __Init__.py を含むディレクトリ) に置かれてない conftest.py ファイルがある場合、PYTHONPATH または sys.path に同じ名前をもつ別の conftest.py ファイルを置く可能性があり、”import conftest” が曖昧になるときがあります。こういったプロジェクトでは、パッケージスコープの中で conftest.py を置くか conftest.py ファイルから決してインポートしないかのどちらか一方を選択するのが良いプラクティスです。
プラグインのインストールは、普通の Python インストールツールを使って行います。例えば:
pip install pytest-NAME
pip uninstall pytest-NAME
プラグインがインストール済みなら、py.test が自動的に検出してそのプラグインを組み込みます。プラグインを有効化する必要はありません。既知のプラグイン一覧を紹介します:
“pytest-” で pypi.python.org を検索 すると、もっとプラグインが見つかるでしょう。
自分でプラグインを作成したいなら、たくさんある実際のプラグインをコピーしてから始めると良いです:
これらの全プラグインは、機能を追加/拡張するためにドキュメント付きの よく練られたフック を実装します。
自分で作成したプラグインを外部から利用できるようにしたいなら、 py.test がプラグインモジュールを見つけられるように、ディストリビューションのいわゆるエントリーポイントを定義します。エントリーポイントは setuptools または distribute が提供する機能です。py.test は、プラグインを検出するために pytest11 というエントリーポイントを調べます。このように setuptools/distribute の setup 処理でエントリーポイントを定義することにより、自分のプラグインを利用できます。
# サンプルの ./setup.py ファイル
from setuptools import setup
setup(
name="myproject",
packages = ['myproject']
# 次のように記述して py.test からプラグインを利用可能にする
entry_points = {
'pytest11': [
'name_of_plugin = myproject.pluginmodule',
]
},
)
パッケージがこの方法でインストールされる場合、py.test は よく練られたフック を定義するプラグインとして myproject.pluginmodule を読み込みます。
py.test は、次の方法でツール起動時にプラグインモジュールを読み込みます。
テストモジュール、または conftest ファイル内でプラグインを要求できます:
pytest_plugins = "name1", "name2",
テストモジュール、または conftest プラグインが読み込まれるとき、指定したプラグインも同様に読み込まれます。さらに次のようにドット区切りのパスも使えます:
pytest_plugins = "myapp.testsupport.myplugin"
これは py.test プラグインとして指定したモジュールをインポートします。
あるプラグインと別のプラグインのコードを協調させたいなら、次のようにプラグインマネージャーを使ってリファレンスを取得できます:
plugin = config.pluginmanager.getplugin("name_of_plugin")
既存のプラグイン名を調べたい場合は --traceconfig オプションを使ってください。
自分の環境で有効なプラグインを調べたいなら、次のように実行してください:
py.test --traceconfig
有効なプラグインとその名前を表示する拡張テストヘッダーを取得します。 conftest.py が読み込まれるときにそのローカルプラグインも表示します。
プラグインを読み込ませない、または登録を解除できます:
py.test -p no:NAME
このオプションは、有効化/読み込もうとするプラグインが既に存在するものとして扱います。プラグイン名を取得する方法は 有効なプラグインの検出 を参照してください。
次のプラグインのソースコードが pytest リポジトリ に含まれています。
_pytest.assertion | |
_pytest.capture | |
_pytest.config | |
_pytest.doctest | Module doctest – a framework for running examples in docstrings. |
_pytest.genscript | |
_pytest.helpconfig | |
_pytest.junitxml | |
_pytest.mark | |
_pytest.monkeypatch | |
_pytest.nose | |
_pytest.pastebin | |
_pytest.pdb | A Python debugger. |
_pytest.pytester | (disabled by default) support for testing pytest and pytest plugins. |
_pytest.python | |
_pytest.recwarn | |
_pytest.resultlog | |
_pytest.runner | |
_pytest.main | |
_pytest.skipping | |
_pytest.terminal | |
_pytest.tmpdir | |
_pytest.unittest | Python unit testing framework, based on Erich Gamma’s JUnit and Kent Beck’s Smalltalk testing framework. |
py.test は、初期化、テスト実行、レポートを実装するフック関数を呼び出します。py.test がプラグインを読み込むとき、各フック関数名はその対応するフック仕様を確認します。各フック関数名とその引数の名前は、フック仕様に一致する必要があります。但し、フック関数を単に指定しないことにより 少ない パラメーターは許容します。引数の名前やフック名そのものを誤入力した場合、利用できる引数を表示するエラーが表示されます。
(deprecated) modify command line arguments before option parsing.
return initialized config object, parsing the specified args.
return dict of name->object to be made globally available in the pytest namespace. This hook is called before command line options are parsed.
register argparse-style options and ini-style config values.
This function must be implemented in a plugin and is called once at the beginning of a test run.
パラメタ: | parser – To add command line options, call parser.addoption(...). To add ini-file values call parser.addini(...). |
---|
Options can later be accessed through the config object, respectively:
The config object is passed around on many internal objects via the .config attribute or can be retrieved as the pytestconfig fixture or accessed via (deprecated) pytest.config.
called for performing the main command line action. The default implementation will invoke the configure hooks and runtest_mainloop.
フックに関連する全ての runtest は pytest.Item オブジェクトを受け取ります。
implements the runtest_setup/call/teardown protocol for the given test item, including capturing exceptions and calling reporting hooks.
パラメタ: |
|
---|---|
Return boolean: | True if no further hook implementations should be invoked. |
called after pytest_runtest_call.
パラメタ: | nextitem – the scheduled-to-be-next test item (None if no further test item is scheduled). This argument can be used to perform exact teardowns, i.e. calling just enough finalizers so that nextitem only needs to call setup-functions. |
---|
return a _pytest.runner.TestReport object for the given pytest.Item and _pytest.runner.CallInfo.
より深く理解するには _pytest.runner の実際のフックのデフォルト実装を調べることになるかもしれません。さらに、テストが失敗したときにそのまま対話式のデバッガーに入る、その入出力のキャプチャや _pytest.capture と相互にやり取りする _pytest.pdb もきっと見たくなるでしょう。
実際にレポートを行う _pytest.terminal は、テスト実行に関する情報を表示するためにレポートフックを使います。
py.test はファイルとディレクトリを探索するために次のフックを呼び出します:
return True to prevent considering this path for collection. This hook is consulted for all files and directories prior to calling more specific hooks.
called before traversing a directory for collection files.
return collection Node or None for the given path. Any new node needs to have the specified parent as a parent.
Python モジュール内のオブジェクトのコレクションに影響を与えるには、次のフックが使えます:
access to configuration values, pluginmanager and plugin hooks.
add a line to an ini-file option. The option must have been declared but might not yet be set in which case the line becomes the the first line in its value.
return configuration value from an ini file. If the specified name hasn’t been registered through a prior parser.addini call (usually from a plugin), a ValueError is raised.
return command line option value.
パラメタ: |
|
---|
access to command line option as attributes. (deprecated), use getoption() instead
a pluginmanager instance
Parser for command line arguments and ini-file values.
register an ini-file option.
Name: | name of the ini-variable |
---|---|
Type: | type of the variable, can be pathlist, args or linelist. |
Default: | default value if no ini-file option exists but is queried. |
The value of ini-variables can be retrieved via a call to config.getini(name).
register a command line option.
Opts: | option names, can be short or long options. |
---|---|
Attrs: | same attributes which the add_option() function of the argparse library accepts. |
After command line parsing options are available on the pytest config object via config.option.NAME where NAME is usually set by passing a dest attribute, for example addoption("--long", dest="NAME", ...).
get (or create) a named option Group.
Name: | name of the option group. |
---|---|
Description: | long description for –help output. |
After: | name of other group, used for ordering –help output. |
The returned group object has an addoption method with the same signature as parser.addoption but will be shown in the respective group in the output of pytest. --help.
base class for Collector and Item the test collection tree. Collector subclasses have children, Items are terminal nodes.
dynamically add a marker object to the node.
marker can be a string or pytest.mark.* instance.
register a function to be called when this node is finalized.
This method can only be called when this node is active in a setup chain, for example during self.setup().
the pytest config object
allow adding of extra keywords to use for matching
filesystem path where this node was collected from (can be None)
get a marker object from this node or None if the node doesn’t have a marker with that name.
get the next parent node (including ourself) which is an instance of the given class
keywords/markers collected from all scopes
return list of all parent collectors up to self, starting from root of collection tree.
a unique name within the scope of the parent node
the parent collector node.
the session this node is part of
Result/Exception info a function invocation.
None or ExceptionInfo object.
context of invocation: one of “setup”, “call”, “teardown”, “memocollect”
Basic test report object (also used for setup and teardown calls if they fail).
time it took to run just the test
a name -> value dictionary containing all keywords and markers associated with a test invocation.
a (filesystempath, lineno, domaininfo) tuple indicating the actual location of a test item - it might be different from the collected one e.g. if a method is inherited from a different module.
None or a failure representation.
normalized collection node id
test outcome, always one of “passed”, “failed”, “skipped”.
list of (secname, data) extra information which needs to marshallable
one of ‘setup’, ‘call’, ‘teardown’ to indicate runtest phase.