[英]Pytest: run a function at the end of the tests
我发现:
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.