如何在模块范围内有一个基于运行测试结果的拆分功能。

问题描述 投票:1回答:1

我想在所有测试通过后清理一些文件。如果失败了,就保留下来调试。我读到 https:/docs.pytest.orgenlatestexamplesimple.html#making-test-result-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'

与doc例子的唯一区别是,我的 teardown有'。scope=module'. 但我必须这样做,因为我想在所有测试通过后清理文件,有些文件被所有测试使用。如果我使用默认的范围,即 "函数 "级别,它将在每个测试用例后清理,而不是在整个模块后清理。我该如何解决这个问题?

更新:在我使用'hook'之前,我仍然有一个叫做 teardown 这是 "模块 "级别的,它工作得很好,也就是说在所有测试运行后,它为我清理了所有文件,唯一的问题是,无论测试通过或失败,它都会为我清理。

python python-3.x testing pytest fixtures
1个回答
1
投票

如果你在模块范围内。request.node 代表模块,而不是单个测试。如果你想只检查失败的测试,你可以检查会话。

@pytest.fixture(scope="module", autouse=True)
def teardown(request):
    yield
    if request.session.testsfailed > 0:
        print(f"{} test(s) failed!", request.session.testsfailed)
    else:
        #  clean up my files

如果你只对这些感兴趣的话,我不确定请求中是否有任何关于设置失败的信息。在这种情况下,你可以实现一个文件范围内的夹具,在设置失败时设置一个标志,然后使用这个,类似于。

SETUP_FAILED = False

@pytest.fixture(autouse=True)
def teardown_test(request):
    yield
    if request.node.rep_setup.failed:
        global SETUP_FAILED
        SETUP_FAILED = True

@pytest.fixture(scope="module", autouse=True)
def teardown_module():
    global SETUP_FAILED
    SETUP_FAILED = False
    yield
    if SETUP_FAILED:
        print("At least one test setup failed!")
    else:
        #  clean up my files

这不是很好,也许有人知道一个更好的解决方案,但它会工作.如果需要的话,你也可以收集关于设置失败的测试的信息。

© www.soinside.com 2019 - 2024. All rights reserved.