Search⌘ K
AI Features

Integrity Tests: pytest

Explore how to implement integrity tests with pytest to maintain database accuracy. Understand using SQLAlchemy constraints, clean and unclean data fixtures, and automated tests to detect and fix data inconsistencies efficiently.

Integrity tests using pytest

In some cases, periodically checking for data issues is insufficient. Instead, we can clean the data using functions. These must be tested on a separate instance of a database with the unclean data purposely put in place, using separate fixtures for clean and unclean test data. We need a new function that drops the data but keeps the schema, but be sure to only run this on the test connection.

Python 3.5
def drop_tables():
for Table in [Employee, Project, Assignment]:
session.query(Table).delete()

The fixture uses this to define a clean-data session.

Python 3.8
import json
import pytest
from flask_orm2 import drop_tables, add_sample_data, clean_data
from flask_orm2 import Employee, Project, Assignment, session
@pytest.fixture(scope='module')
def db_session_clean():
'''Creates a database and populates it with clean data'''
drop_tables() # drop tables, but keep schema
add_sample_data() # populate uncleanly
clean_data()
yield session

The tests are ...