目次

前のトピックへ

カスタムマーカーを使う

次のトピックへ

Python 以外のテストを扱う

標準的な (Python) テスト探索の変更

ディレクトリの再帰探索の変更

ini ファイルで norecursedirs オプションを設定できます。例えば、プロジェクトのルートディレクトリにある setup.cfg に設定します:

# setup.cfg の内容
[pytest]
norecursedirs = .svn _build tmp*

これは典型的な subversion と sphinx の build ディレクトリと tmp という接頭辞をもつディレクトリを再帰探索しない設定です。

命名規則の変更

python_files, python_classes, python_functions オプションを設定することで別の命名規則を使うこともできます。サンプルを紹介します:

# setup.cfg の内容
# tox.ini または pytest.init ファイルでも定義できる
[pytest]
python_files=check_*.py
python_classes=Check
python_functions=check

この設定は Python ファイル名に check_ 、 クラス名に Check 、関数名に check という接頭辞を py.test が探すようにします。例えば、次のようなファイルです:

# check_myapp.py の内容
class CheckMyApp:
    def check_simple(self):
        pass
    def check_complex(self):
        pass

テストコレクションは次のようになります:

$ py.test --collect-only
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4
collecting ... collected 2 items
<Module 'check_myapp.py'>
  <Class 'CheckMyApp'>
    <Instance '()'>
      <Function 'check_simple'>
      <Function 'check_complex'>

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

Python パッケージとしてコマンドライン引数を解釈

py.test がファイルシステムのパスから Python パッケージ名として引数を解釈するように --pyargs オプションを使えます。例えば、unittest2 をインストール済みなら、次のように指定できます:

py.test --pyargs unittest2.test.test_skipping -q

それぞれのテストモジュールを実行します。その他のオプションと同様に ini ファイルと addopts オプションにより、この変更を永続化できます:

# pytest.ini の内容
[pytest]
addopts = --pyargs

単純に py.test NAME を実行すると、NAME がインポート可能なパッケージ/モジュールとして存在しているかどうかをチェックします。存在しない場合、ファイルシステム上のパスとして NAME を扱います。

コレクションの探索

次のようにテストを実行せずにコレクションツリーをピークできます:

. $ py.test --collect-only pythoncollection.py
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4
collecting ... collected 3 items
<Module 'pythoncollection.py'>
  <Function 'test_function'>
  <Class 'TestClass'>
    <Instance '()'>
      <Function 'test_method'>
      <Function 'test_anothermethod'>

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