Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest: run a function at the end of the tests

Tags:

python

pytest

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.

like image 837
user4780495 Avatar asked Jan 26 '17 10:01

user4780495


People also ask

What is pytest Autouse?

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

How often is a fixture function in pytest executed?

Fixtures with scope session will only be executed once per session. Every time you run pytest , it's considered to be one session.

What is pytest fixture ()?

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.


2 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

like image 180
user4780495 Avatar answered Sep 28 '22 06:09

user4780495


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

like image 41
Floyd Avatar answered Sep 28 '22 05:09

Floyd