Pytest delete db after tests

Viewed 6550

I have a test suite in pytest-django and I want to create a database at the start of the test and then delete the same as soon a test is completed in order to simulate the scenario without keeping a huge chunk of data. Any help would be appreciated. Thanks in advance!

1 Answers

Take advantage of a fixture teardown using the yield statement instead of return. This allows you to setup database, return any data if you want and then perform any cleanup. If you want this to be performed for every test regardless of a test function declaring the use of the fixture or not, set autouse to True.

@pytest.fixture(autouse=False)
def db():
    # Setup DB here

    # Yield some data, database connection or nothing at all
    yield None

    # Delete DB here when the test ends

def test_something(db):
    # Database will be ready here and db will contain whatever
    # db() function yields. With autouse=True you don't need to
    # set the db fixture as the function param.
    pass
Related