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.
“Autouse” fixtures are a convenient way to make all tests automatically request them. This can cut out a lot of redundant requests, and can even provide more advanced fixture usage (more on that further down).
Fixtures with scope session will only be executed once per session. Every time you run pytest , it's considered to be one session.
Pytest fixtures are functions that can be used to manage our apps states and dependencies. Most importantly, they can provide data for testing and a wide range of value types when explicitly called by our testing software. You can use the mock data that fixtures create across multiple tests.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With