目次

前のトピックへ

py.test リファレンスドキュメント

次のトピックへ

基本的なテストの設定

Pytest 組み込みヘルパー機能

組み込みの pytest.* 関数とヘルパーオブジェクト

Python インタープリターの対話モードから次のように入力すると:

import pytest
help(pytest)

グローバルに利用できるヘルパー機能の概要を把握できます。

pytest: unit and functional testing with Python.

pytest.main(args=None, plugins=None)

return exit code, after performing an in-process test run.

パラメタ:
  • args – list of command line arguments.
  • plugins – list of plugin objects to be auto-registered during initialization.
pytest.fail(msg='', pytrace=True)

explicitely fail an currently-executing test with the given Message.

パラメタ:pytrace – if false the msg represents the full failure information and no python traceback will be reported.
pytest.skip(msg='')

skip an executing test with the given message. Note: it’s usually better to use the py.test.mark.skipif marker to declare a test to be skipped under certain conditions like mismatching platforms or dependencies. See the pytest_skipping plugin for details.

pytest.exit(msg)

exit testing process as if KeyboardInterrupt was triggered.

pytest.importorskip(modname, minversion=None)

return imported module if it has a higher __version__ than the optionally specified ‘minversion’ - otherwise call py.test.skip() with a message detailing the mismatch.

pytest.fixture(scope='function', params=None, autouse=False)

(return a) decorator to mark a fixture factory function.

This decorator can be used (with or or without parameters) to define a fixture function. The name of the fixture function can later be referenced to cause its invocation ahead of running tests: test modules or classes can use the pytest.mark.usefixtures(fixturename) marker. Test functions can directly use fixture names as input arguments in which case the fixture instance returned from the fixture function will be injected.

パラメタ:
  • scope – the scope for which this fixture is shared, one of “function” (default), “class”, “module”, “session”.
  • params – an optional list of parameters which will cause multiple invocations of the fixture function and all of the tests using it.
  • autouse – if True, the fixture func is activated for all tests that can see it. If False (the default) then an explicit reference is needed to activate the fixture.
pytest.raises(ExpectedException, *args, **kwargs)

assert that a code block/function call raises @ExpectedException and raise a failure exception otherwise.

If using Python 2.5 or above, you may use this function as a context manager:

>>> with raises(ZeroDivisionError):
...    1/0

Or you can specify a callable by passing a to-be-called lambda:

>>> raises(ZeroDivisionError, lambda: 1/0)
<ExceptionInfo ...>

or you can specify an arbitrary callable with arguments:

>>> def f(x): return 1/x
...
>>> raises(ZeroDivisionError, f, 0)
<ExceptionInfo ...>
>>> raises(ZeroDivisionError, f, x=0)
<ExceptionInfo ...>

A third possibility is to use a string to be executed:

>>> raises(ZeroDivisionError, "f(0)")
<ExceptionInfo ...>
pytest.xfail(reason='')

xfail an executing test or setup functions with the given reason.

pytest.deprecated_call(func, *args, **kwargs)

assert that calling func(*args, **kwargs) triggers a DeprecationWarning.

組み込み関数の引数

次のように入力して、利用できる組み込みまたはプロジェクトカスタムの 関数の引数 を確認できます。

$ py.test –fixtures
====================== test session starts =======================
platform linux2 – Python 2.7.1 – pytest-2.2.4
collected 0 items
pytestconfig
pytest の config オブジェクトとコマンドラインオプションへのアクセス

capsys
sys.stdout/sys.stderr への書き込み内容を取得できる
キャプチャした出力内容は (out, err) のタプルを返す
capsys.readouterr() メソッドで利用できる

capfd
ファイルディスクリプタ 1 と 2 へ書き込み内容を取得できる
キャプチャした出力内容は (out, err) のタプルを返す
capsys.readouterr() メソッドで利用できる

tmpdir
基本となる一時ディレクトリ配下にサブディレクトリを作成して、
テスト関数の実行毎に一意な一時ディレクトリのオブジェクトを返す
これは py.path.local のパスオブジェクトが返される

monkeypatch
オブジェクト、ディクショナリ、os.environ を変更する
次のヘルパーメソッドを提供する monkeypatch オブジェクトが返される

monkeypatch.setattr(obj, name, value, raising=True)
monkeypatch.delattr(obj, name, raising=True)
monkeypatch.setitem(mapping, name, value)
monkeypatch.delitem(obj, name, raising=True)
monkeypatch.setenv(name, value, prepend=False)
monkeypatch.delenv(name, value, raising=True)
monkeypatch.syspath_prepend(path)
monkeypatch.chdir(path)

全ての変更はテスト関数の呼び出しが終わった後で元に戻ります
raising パラメーターは、セット/削除の操作対象がないときに
KeyError や AttributeError を発生させるかどうかを決めます

recwarn
次のメソッドを提供する WarningsRecorder インスタンスを返す

* pop(category=None): category に一致する最後の警告を返す
* clear(): 警告のリストを削除する

参照してください

======================== in 0.00 seconds ========================