Pytest: run a function at the end of the tests

You can use the "atexit" module.

For instance, if you want to report something at the end of all the test you need to add a report funtion like this:

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}")

then at the end of the module, you call atexit like this:

atexit.register(report)

hoop this helps!


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


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).

Tags:

Python

Pytest