PyTest 跳过 module_teardown() [英] PyTest skip module_teardown()

查看:58
本文介绍了PyTest 跳过 module_teardown()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的测试模块中有以下代码

I have following code in my tests module

def teardown_module():
    clean_database()
def test1(): pass
def test2(): assert 0

并且我希望 teardown_module()(一些清理代码)仅在某些测试失败时才被调用.否则(如果全部通过)不应调用此代码.我可以用 PyTest 做这样的把戏吗?

and I want teardown_module() (some cleanup code) to be called only if some test failed. Otherwise (if all passed) this code shouldn't have to be called. Can I do such a trick with PyTest?

推荐答案

可以.但这有点像黑客.如此处所写:http://pytest.org/latest/example/simple.html#making-test-result-information-available-in-fixtures您执行以下操作,以设置用于保存测试调用的每个阶段的状态的属性:

You can. But it is a little bit of a hack. As written here: http://pytest.org/latest/example/simple.html#making-test-result-information-available-in-fixtures you do the following, to set up an attribute for saving the status of each phase of the testcall:

# content of conftest.py
import pytest
@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    rep = __multicall__.execute()
    setattr(item, "rep_" + rep.when, rep)
    return rep

在夹具中,您只需检查这些属性的条件,如下所示:

and in the fixture you just examine the condition on those attributes like this:

import pytest
@pytest.yield_fixture(scope="module", autouse=True)
def myfixture(request):
    print "SETUP"
    yield
    # probably should not use "_collected" to iterate over test functions
    if any(call.rep_call.outcome != "passed" for call in request.node._collected):
        print "TEARDOWN"

这样,如果与该模块夹具相关的任何测试未通过"(即失败"或跳过"),则条件成立.

This way if any of the tests associated with that module fixture is not "passed" (so "failed" or "skipped") then the condition holds.

这篇关于PyTest 跳过 module_teardown()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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