Pytest:运行 测试结束时的函数

Pytest: run a function at the end of the tests

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

一种全局拆解功能

我找到了一个示例 here and some clues here,但它不符合我的需要。它 运行 是测试开始时的功能。我也看到了函数pytest_runtest_teardown(),但是每次测试后都会调用它。

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

我发现:

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

exitstatus 可用于定义要执行的操作 运行。 pytest docs about this

您可以使用 "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)

抱抱这有帮助!

到运行所有测试结束时的函数,使用带有"session" scope的pytest fixture。这是一个例子:

@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 fixture,每个测试会话将 运行 一次(每次使用 pytest 时都会得到 运行)。 autouse=True 告诉 pytest 自动 运行 这个夹具(没有在其他任何地方调用)。

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