gpt4 book ai didi

python - pytest 2.3 在类中添加拆卸

转载 作者:行者123 更新时间:2023-11-30 23:40:38 27 4
gpt4 key购买 nike

我正在研究新版本的 pytest (2.3),并对新功能感到非常兴奋

"can precisely control teardown by registering one or multiple teardown functions as soon as they have performed some actions which need undoing, eliminating the no need for a separate “teardown” decorator"

来自here

作为函数使用就很清楚了,但是如何在类中使用呢?

class Test(object):

@pytest.setup(scope='class')
def stp(self):
self.propty = "something"

def test_something(self):
... # some code
# need to add something to the teardown

def test_something_else(self):
... # some code
# need to add even more to the teardown

最佳答案

好吧,我通过使用一个“ session ”范围的 funcarg finalizer 使其工作:

@pytest.fixture(scope = "session")
def finalizer():
return Finalizer()

class Finalizer(object):

def __init__(self):
self.fin_funcs = []

def add_fin_func(self, func):
self.fin_funcs.append(func)

def remove_fin_func(self, func):
try:
self.fin_funcs.remove(func)
except:
pass

def execute(self):
for func in reversed(self.fin_funcs):
func()
self.fin_funcs = []

class TestSomething(object):

@classmethod
@pytest.fixture(scope = "class", autouse = True)
def setup(self, request, finalizer):

self.finalizer = finalizer
request.addfinalizer(self.finalizer.execute)
self.finalizer.add_fin_func(lambda: some_teardown())

def test_with_teardown(self):

#some test
self.finalizer.add_fin_func(self.additional_teardown)

def additional_teardown(self):
#additional teardown

感谢 @hpk42 回复电子邮件并帮助我获得最终版本。

注意:与 xfailing the rest of the steps 一起和 improved scenarios现在,这构成了一个非常好的测试步骤结构

关于python - pytest 2.3 在类中添加拆卸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12538808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com