pytest 2.3 在类中添加拆卸 [英] pytest 2.3 adding teardowns within the class

查看:24
本文介绍了pytest 2.3 在类中添加拆卸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm researching new version of pytest (2.3) and getting very excited about the new functionality where you

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

"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"

来自这里

当它作为函数使用的时候已经很清楚了,但是如何在类中使用它呢?

It's all pretty clear when it's used as function, but how to use it in the class?

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 让它工作起来:

Ok, I got it working by having a 'session'-wide 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 回复电子邮件并帮助我获得最终版本.

Thanks @hpk42 for answering e-mails and helping me get the final version.

注意:连同 xfailing 其余步骤改进的场景 现在是一个非常好的测试步骤结构

NOTE: together with xfailing the rest of the steps and improved scenarios this now makes a pretty good Test-Step structure

这篇关于pytest 2.3 在类中添加拆卸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆