2016-05-25 22 views
2

テストクラスのセットアップで、何とかconftest.pyのpytestフィクスチャを使用する方法はありますか? セッションを開始するときにオブジェクトを初期化し、いくつかのテストクラスの設定でオブジェクトを使用する必要があります。私はあなたがそれを直接行うことができるとは思わないpy.test setup_methodのセッションレベルフィクスチャ

# conftest.py: 

import pytest 

@pytest.fixture(scope="session", autouse=True) 
def myfixture(request): 
    return "myfixture" 

# test_aaa.py 

class TestAAA(object): 

    def setup(self, method, myfixture): 
     print("setup myfixture: {}".format(myfixture)) 

    ... 

答えて

2

:このような

何か。それが助け場合は、あなたがpytest.mark.usefixturesでクラス全体を飾ることができ、:

@pytest.mark.usefixtures(['myfixture']) 
class TestAAA(object): 
    ... 

をIIRC、setup_methodが自動的に適用器具のいずれかの前に呼び出されます。

また、そのようなクラスレベルの備品のためのautouseを利用することができます

class TestAAA(object): 
    @pytest.fixture(autouse=True) 
    def init_aaa(self, myfixture): 
     ... 
+0

を感謝を! 2番目のオプションを使用しましたが、setup_methodはinit_aaaの前に呼び出されました。そこでsetup_methodをsetup(これはクラスの各テストメソッドの前に呼び出される)に置き換え、うまくいった。私の元の質問を編集します。 – adi

+0

@adi私は 'setup'を' autouse = True'を持つ 'init_aaa'メソッドで置き換えることができると思います。 – aldanor

+0

私の場合は両方とも必要です(私は "myfixture"を提供するすべてのテストの基本クラスを作成し、この基本クラスを継承して誰かにセットアップ方法を決定させたい) – adi

2

私はテストクラスのためのセットアップのこの種の使用:

# conftest.py: 

import pytest 

# autouse=True does not work for fixtures that return value 
# request param for fixture function is only required if the fixture uses it: 
# e.g. for a teardown or parametrization. Otherwise don't use it. 
@pytest.fixture(scope="session") 
def myfixture(): 
    return "myfixture" 

# test_aaa.py 

class TestAAA(object): 
    @classmethod 
    @pytest.fixture(scope="class", autouse=True) 
    def setup(self, myfixture): 
     self.myfixture = myfixture 

    test_function1(self): 
     # now you can use myfixture without passing it as param to each test function 
     assert myfixture == "myfixture" 
関連する問題