Python Pytest:在测试结束时运行函数
我想在所有测试结束时运行一个函数 一种全局拆卸函数 我找到了一个例子和一些线索,但它不符合我的需要。它在测试开始时运行函数。我还看到了函数Python Pytest:在测试结束时运行函数,python,pytest,Python,Pytest,我想在所有测试结束时运行一个函数 一种全局拆卸函数 我找到了一个例子和一些线索,但它不符合我的需要。它在测试开始时运行函数。我还看到了函数pytest\u runtest\u teardown(),但它是在每次测试后调用的 另外:如果只有在所有测试都通过的情况下才能调用该函数,那就太好了。我发现: def pytest_sessionfinish(session, exitstatus): """ whole test run finishes. """ exitstatus可用于定义
pytest\u runtest\u teardown()
,但它是在每次测试后调用的
另外:如果只有在所有测试都通过的情况下才能调用该函数,那就太好了。我发现:
def pytest_sessionfinish(session, exitstatus):
""" whole test run finishes. """
exitstatus
可用于定义要运行的操作 您可以使用“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.register(report)
然后在模块末尾,您可以这样调用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.register(report)
这有帮助 要在所有测试结束时运行函数,请使用带有。以下是一个例子:
@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时都会运行该变量)。autouse=True
告诉pytest自动运行这个fixture(无需在其他任何地方调用)
在cleanup
函数中,我们定义remove\u test\u dir
并使用request.addfinalizer(remove\u test\u dir)
行告诉pytest在完成后运行remove\u test\u dir
函数(因为我们将范围设置为“session”,这将在整个测试会话完成后运行).pytest\u unconfigure
似乎可以完成这项工作,但也许有人会想出更好的主意,让您的夹具在最后运行一些功能,您应该使用request.addfinalizer(拆卸功能)
。要使其在孔结束会话时运行,而不是在每个测试用例中运行,请将确切范围指定为@pytest.fixture(scope=“session”)
使用addfinalizer
的缺点是捕获输出,而使用pytest\u sessionfinish