在pytest中,如何确保在类级

时间:2017-02-03 19:56:48

标签: python pytest fixture

我的pytest很旧(版本2.8.3)。

pytestmark = pytest.mark.usefixtures("module_level")

@pytest.fixture(scope='module')
def module_level(request):
    print("module start")
    def fin():
        print("module end")
    request.addfinalizer(fin)

@pytest.fixture(scope='class')
def class_level(request):
    print("class start")
    def fin():
        print("class end")
    request.addfinalizer(fin)

@pytest.mark.usefixtures("class_level")
class TestMyClass:  
    def test_func(self):
        pass

然而,我得到的顺序是:

class start
module start
class end
module end

这不是我想要的。那么,编写模块级设置/清理夹具的正确方法是什么(并确保它在所有事情之前进行设置并在所有事情之后进行清理)?

1 个答案:

答案 0 :(得分:4)

pytest按照它们在测试文件中写入的顺序处理测试,并在需要时按顺序加载灯具。请参阅有关fixtures

的文档

在您的示例中,您首先使用类测试启动pytest,然后加载模块依赖项。

如果您想设置"模块"有多种可能性。第一

a)module_level被class_level用作参数,因此在前面加载(不需要pytestmark)

import pytest

@pytest.fixture(scope='module')
def module_level(request):
    print("module start")
    def fin():
        print("module end")
    request.addfinalizer(fin)

@pytest.fixture(scope='class')
def class_level(request, module_level):
    print("class start")
    def fin():
        print("class end")
    request.addfinalizer(fin)

@pytest.mark.usefixtures("class_level")
class TestMyClass:
    def test_func(self):
        pass

b)使用@pytestmark作为类测试的要求,因此它被加载到前面

import pytest

pytestmark = pytest.mark.usefixtures("module_level")

@pytest.fixture(scope='module')
def module_level(request):
    print("module start")
    def fin():
        print("module end")
    request.addfinalizer(fin)

@pytest.fixture(scope='class')
def class_level(request):
    print("class start")
    def fin():
        print("class end")
    request.addfinalizer(fin)

@pytest.mark.usefixtures("class_level")
@pytestmark
class TestMyClass:
    def test_func(self):
        pass

c)在类测试前面设置一个函数测试,这将首先执行module_level

import pytest

pytestmark = pytest.mark.usefixtures("module_level")

@pytest.fixture(scope='module')
def module_level(request):
    print("module start")
    def fin():
        print("module end")
    request.addfinalizer(fin)

@pytest.fixture(scope='class')
def class_level(request):
    print("class start")
    def fin():
        print("class end")
    request.addfinalizer(fin)

def test_case():
    assert True

@pytest.mark.usefixtures("class_level")
class TestMyClass:
    def test_func(self):
        pass

这会加载"模块"在" class"前面在每种情况下(pytest-2.8.7):

A)

::TestMyClass::test_func module start
class start
class end
module end

b)中

::TestMyClass::test_func module start
class start
class end
module end

c)中

::test_case module start
::TestMyClass::test_func class start
class end
module end