Reputation: 2912
I would like to run a function at the end of all the tests.
A kind of global teardown function.
I found an example here and some clues here but it doesn't match my need. It runs the function at the beginning of the tests. I also saw the function pytest_runtest_teardown()
, but it is called after each test.
Plus: if the function could be called only if all the tests passed, it would be great.
Upvotes: 48
Views: 42346
Reputation: 5214
You can use the atexit
module calling it at the end of the module as follows:
atexit.register(report)
If you want to report something at the end of all the test you need to add a report funtion as follows:
import 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)
Upvotes: 8
Reputation: 2452
To run a function at the end of all the tests, use a pytest fixture with a "session" scope. Here is an example:
@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)
The @pytest.fixture(scope="session", autouse=True)
bit adds a pytest fixture which will run once every test session (which gets run every time you use pytest
). The autouse=True
tells pytest to run this fixture automatically (without being called anywhere else).
Within the cleanup
function, we define the remove_test_dir
and use the request.addfinalizer(remove_test_dir)
line to tell pytest to run the remove_test_dir
function once it is done (because we set the scope to "session", this will run once the entire testing session is done).
Upvotes: 31
Reputation: 2912
I found:
def pytest_sessionfinish(session, exitstatus):
""" whole test run finishes. """
exitstatus
can be used to define which action to run. pytest docs about this
Upvotes: 53