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

时间:2016-05-25 12:17:45

标签: python pytest

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

这样的事情:

# 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))

    ...

3 个答案:

答案 0 :(得分:4)

我使用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"
# 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"

答案 1 :(得分:3)

我认为你不能直接这样做。但是,您可以使用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):
        ...

答案 2 :(得分:1)

对于上面提供的示例,从灯具返回的对象可以设置为测试类的属性。此类的任何方法都可以访问。

# test_fixture.py

import pytest

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

def test_function1(self):
    assert self.myfixture == "myfixture"

或者如果您继承自unittest.Testcase,则可以执行以下操作

# test_fixture.py

import pytest
from unittest import TestCase

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

    def test_function1(self):
        self.assertEqual(self.myfixture, "myfixture")