setup_method中的py.test会话级别装置

adi*_*adi 10 python pytest

有没有办法在测试类的设置中以某种方式使用来自conftest.py的pytest fixtures ?我需要在会话启动时初始化一个对象,并在一些测试类的设置中使用它.

像这样的东西:

# conftest.py:

import pytest

@pytest.fixture(scope="session", autouse=True)
def myfixture(request):
    return "myfixture"
Run Code Online (Sandbox Code Playgroud)
# test_aaa.py

class TestAAA(object):

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

    ...
Run Code Online (Sandbox Code Playgroud)

ald*_*nor 6

我认为你不能直接这样做。pytest.mark.usefixtures但是,如果有帮助的话,您可以用 来装饰整个类:

@pytest.mark.usefixtures(['myfixture'])
class TestAAA(object):
    ...
Run Code Online (Sandbox Code Playgroud)

IIRC,setup_method将在任何自动应用的装置之前调用。

您还可以将autouse其用于类级别的装置,如下所示:

class TestAAA(object):
    @pytest.fixture(autouse=True)
    def init_aaa(self, myfixture):
        ...
Run Code Online (Sandbox Code Playgroud)


Dmi*_*rev 5

我为pytest <= 3.7.0(针对pytest 3.7.1版本停止工作)的测试类使用了这种设置:

# 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"
Run Code Online (Sandbox Code Playgroud)
# test_aaa.py

import pytest

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

    def test_function1(self):
        # now you can use myfixture without passing it as param to each test function   
        assert self.myfixture == "myfixture"
Run Code Online (Sandbox Code Playgroud)