Pytest: run a function at the end of the tests

Question:

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.

Asked By: user4780495

||

Answers:

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

Answered By: user4780495

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 as follows:

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 as follows:

atexit.register(report)

hoop this helps!

Answered By: Moshe Slavin

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

Answered By: Floyd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.