是否可以将 setup_method 与固定装置一起使用?

Is it possible to use setup_method with fixtures?

我有以下代码:

import pytest

@pytest.fixture
def example_smtp():
    return "example"

class TestClass(object):
    def test_function(self, example_smtp):
        # 1
        obj = NewObject(example_smtp)
        obj.initialize()

        print example_smtp
        # here may rise exception
        some_action()

        # 2
        # but we have to cleanup
        obj.cleanup()

some_action() 可能会引发异常,所以我想将 1 和 2 移动到 setup_method 和 teardown_method,但我不知道该怎么做。 setup_method 只允许两个参数,所以我不能在其中使用 example_smtp。

我已经使用请求对象的 addfinalizer() 函数解决了这个问题。

import pytest

@pytest.fixture
def example_smtp():
        return "example"

class TestClass(object):
        @pytest.fixture
        def obj(self, request, example_smtp):
                print 'initialize', example_smtp

                def fin():
                        print 'finalize'
                request.addfinalizer(fin)

        def test(self, obj):
                some_action_raise_error()

感谢 jonrsharpe 提供有关产量固定装置的信息。

更好的方法是只编写一个 fixture 为您创建 NewObject 并在之后清理:

import pytest

@pytest.fixture
def example_smtp():
    return "example"

class TestClass(object):

    @pytest.yield_fixture(autouse=True)
    def obj(self):
        obj = NewObject(example_smtp)
        obj.initialize()
        yield obj
        obj.cleanup()            

    def test_function(self, obj, example_smtp):
        # use obj here
        some_action(obj)

但是如果你真的更喜欢有一个类似"setup_method"的函数(也许你正在初始化几个没有出现在你的代码片段中的对象),你可以改为声明一个 autouse 夹具:

import pytest

@pytest.fixture
def example_smtp():
    return "example"

class TestClass(object):

    @pytest.yield_fixture(autouse=True)
    def some_setup(self):
        self.obj = ...
        # ... setup other objects, perhaps
        yield 
        # ... cleanup everything
        self.obj.cleanup()

    def test_function(self, example_smtp):
        some_action(self.obj) 

IMO,没有令人信服的理由 not 在使用 pytest 样式测试 类(IOW,不是子类 unittest.TestCase)时使用固定装置,因为如果你想为您完成所有 setup/cleanup 的单一方法 您可以使用 autouse fixture。