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


  “可以通过注册一个或多个来精确控制拆解
  拆卸功能一旦执行了一些操作,
  需要撤消,无需单独的“拆解”
  装饰员”


来自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

最佳答案

好的,我通过在整个“会话”范围内使用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 stepsimproved scenarios一起构成了一个很好的Test-Step结构

10-06 00:55