我想在所有测试结束时运行一个函数。
一种全球拆解功能。
我找到了一个示例here和一些线索here,但它与我的需求不符。它在测试开始时运行该功能。我也看到了函数pytest_runtest_teardown()
,但在每次测试后调用它。
另外:如果只有在通过所有测试后才能调用该函数,那就太棒了。
答案 0 :(得分:11)
我找到了:
def pytest_sessionfinish(session, exitstatus):
""" whole test run finishes. """
exitstatus
可用于定义要运行的操作。 pytest docs about this
答案 1 :(得分:2)
要在所有测试结束时运行功能,请使用带有"session" scope的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 fixture,它将在每个测试会话中运行一次(每次使用pytest
时都会运行)。 autouse=True
告诉pytest自动运行此Fixture(无需在其他任何地方调用)。
在cleanup
函数中,我们定义remove_test_dir
并使用request.addfinalizer(remove_test_dir)
行告诉pytest一旦完成运行remove_test_dir
函数(因为我们将作用域为“会话”,则将在整个测试会话完成后运行。
答案 2 :(得分:1)
您可以使用“ 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)
哎呀,这很有帮助!