【发布时间】:2020-06-01 22:21:46
【问题描述】:
我想在所有测试通过后清理一些文件。如果它们失败,请保留它们以进行调试。我读了https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures,所以我的conftest.py 中有以下内容:
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# execute all other hooks to obtain the report object
outcome = yield
rep = outcome.get_result()
# set a report attribute for each phase of a call, which can
# be "setup", "call", "teardown"
setattr(item, "rep_" + rep.when, rep)
@pytest.fixture(scope="module", autouse=True)
def teardown(request):
yield
# request.node is an "item" because we use the default
# "function" scope
if request.node.rep_setup.failed:
print("setting up a test failed!", request.node.nodeid)
elif request.node.rep_setup.passed:
#clean up my files
但是,我得到了错误:
AttributeError: 'Module' object has no attribute 'rep_setup'
与文档示例的唯一区别是我的拆解具有'scope=module'。但我必须这样做,因为我想在所有测试通过后清理文件,所有测试都使用一些文件。如果我使用“功能”级别的默认范围,它将在每个测试用例之后而不是在整个模块之后进行清理。我该如何解决这个问题?
更新:在我有'hook'之前,我仍然有teardown,它是“模块”级别,它工作正常,这意味着它在所有测试运行后为我清理了所有文件,唯一的问题是它无论测试通过还是失败,都会为我清理。
【问题讨论】:
标签: python python-3.x testing pytest fixtures