Adolfo Banchio
Adolfo Banchio

Reputation: 11

How to create a pytest fixture to clean a database

I'm working on a Python project with FastAPI and Pony ORM. We're creating unit tests for each module of the program, and we want to be able to run all the tests together (there's one test file for each module). However, we have an issue where each test inserts data into the database (using Pony ORM), and since all the other tests assume the database is clean at the start, they fail when executed one after the other.

I wanted to know if it's possible with pytest to create a function that runs after each test module and cleans the database so that each test can work with an empty database and function correctly.

We have all the tests in a directory called "test/." We're all relatively new to this technology, so some things are challenging for us.

I've already tried creating a pytest fixture with scope="module" that performs db.droptables(cleardata=True) and db.generate_mapping, but it didn't yield results.

Upvotes: 1

Views: 427

Answers (1)

Diego Torres Milano
Diego Torres Milano

Reputation: 69388

Create a fixture that cleans the db

import logging

import pytest


@pytest.fixture(scope="function", autouse=True)
def clean_db():
    yield
    logging.info("Cleaning db...")
    # clean here


def test_1():
    logging.info("test something")


def test_2():
    logging.info("test something else")

you can verify the logs and see the cleaning db message

test_db.py::test_1
---------------------------------------------------- live log call -----------------------------------------------------
2023-09-30 18:30:27 [    INFO] test something (test_db.py:13)
PASSED                                                                                                           [ 50%]
-------------------------------------------------- live log teardown ---------------------------------------------------
2023-09-30 18:30:27 [    INFO] Cleaning db... (test_db.py:9)

test_db.py::test_2
---------------------------------------------------- live log call -----------------------------------------------------
2023-09-30 18:30:27 [    INFO] test something else (test_db.py:17)
PASSED                                                                                                           [100%]
-------------------------------------------------- live log teardown ---------------------------------------------------
2023-09-30 18:30:27 [    INFO] Cleaning db... (test_db.py:9)


================================================== 2 passed in 0.01s ===================================================

Upvotes: 1

Related Questions