繁体   English   中英

Pytest:在测试结束时运行一个函数

[英]Pytest: run a function at the end of the tests

我想在所有测试结束时运行一个函数。

一种全局拆卸功能。

我在这里找到了一个例子,在这里找到了一些线索但它不符合我的需要。 它在测试开始时运行该函数。 我也看到了函数pytest_runtest_teardown() ,但每次测试后都会调用它。

另外:如果只有在所有测试都通过的情况下才能调用该函数,那就太好了。

我发现:

def pytest_sessionfinish(session, exitstatus):
    """ whole test run finishes. """

exitstatus可用于定义要运行的操作。 关于这个的 pytest 文档

要在所有测试结束时运行函数,请使用带有“会话”范围的 pytest 固定装置。 下面是一个例子:

@pytest.fixture(scope="session", autouse=True)
def cleanup(request):
    """Cleanup a testing directory once we are finished."""
    def remove_test_dir():
        shutil.rmtree(TESTING_DIR)
    request.addfinalizer(remove_test_dir)

@pytest.fixture(scope="session", autouse=True)位添加了一个pytest 固定装置,它将在每个测试会话中运行一次(每次使用pytest时都会运行)。 autouse=True告诉 pytest 自动运行这个装置(不会在其他任何地方被调用)。

cleanup函数中,我们定义了remove_test_dir并使用request.addfinalizer(remove_test_dir)行告诉 pytest 在完成后运行remove_test_dir函数(因为我们将范围设置为“会话”,这将在整个测试会话中运行一次已经完成了)。

您可以使用“atexit”模块。

例如,如果您想在所有测试结束时报告某些内容,则需要添加如下报告功能:

def report(report_dict=report_dict):
    print("THIS IS AFTER TEST...")
    for k, v in report_dict.items():
        print(f"item for report: {k, v}")

然后在模块的末尾,你像这样调用 atexit:

atexit.register(report)

箍这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM