I want to run additional setup and teardown checks before and after each test in my test suite. I've looked at fixtures but not sure on whether they are the correct approach. I need to run the setup code prior to each test and I need to run the teardown checks after each test.
My use-case is checking for code that doesn't cleanup correctly: it leaves temporary files. In my setup, I will check the files and in the teardown I also check the files. If there are extra files I want the test to fail.
You can use a
fixture
in order to achieve what you want.Detailed Explanation
@pytest.fixture(autouse=True)
, from the docs: "Occasionally, you may want to have fixtures get invoked automatically without declaring a function argument explicitly or a usefixtures decorator." Therefore, this fixture will run every time a test is executed.# Setup: fill with any logic you want
, this logic will be executed before every test is actually run. In your case, you can add your assert statements that will be executed before the actual test.yield
, as indicated in the comment, this is where testing happens# Teardown : fill with any logic you want
, this logic will be executed after every test. This logic is guaranteed to run regardless of what happens during the tests.Note: in
pytest
there is a difference between a failing test and an error while executing a test. A Failure indicates that the test failed in some way. An Error indicates that you couldn't get to the point of doing a proper test.Consider the following examples:
Assert fails before test is run -> ERROR
Assert fails after test is run -> ERROR
Test fails -> FAILED
Test passes -> PASSED