我有以下代码:
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。
答案 0 :(得分:2)
更好的方法是编写一个为您创建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)
的工具并在之后进行清理:
autouse
但是,如果您真的更喜欢使用" setup_method" -like函数(也许您正在初始化几个不会出现在您的代码段中的对象),那么您可以声明改为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)
灯具:
unittest.TestCase
IMO,使用pytest样式测试类(IOW,而不是子类化autouse
)时,没有令人信服的理由不使用灯具,因为如果你想要一个单独的方法所有设置/清理都可以使用{{1}}夹具。
答案 1 :(得分:0)
我已经通过请求对象的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提供有关屈服夹具的信息。