Verify data integrity after inserting a new user record in the database
Preconditions (3)
✅ Expected Result: The inserted user record is found with the correct email, confirming data integrity
import psycopg2 import pytest class TestDatabaseIntegrity: @pytest.fixture(scope='class') def db_connection(self): conn = psycopg2.connect( dbname='testdb', user='testuser', password='testpass', host='localhost' ) yield conn conn.close() def test_insert_and_verify_user(self, db_connection): cursor = db_connection.cursor() # Insert user record insert_query = """INSERT INTO users (username, email) VALUES (%s, %s) RETURNING id""" cursor.execute(insert_query, ('testuser', 'testuser@example.com')) user_id = cursor.fetchone()[0] db_connection.commit() # Query inserted record select_query = "SELECT email FROM users WHERE username = %s" cursor.execute(select_query, ('testuser',)) result = cursor.fetchone() # Assert record exists and email matches assert result is not None, "User record not found" assert result[0] == 'testuser@example.com', f"Email mismatch: expected 'testuser@example.com', got {result[0]}" # Clean up delete_query = "DELETE FROM users WHERE id = %s" cursor.execute(delete_query, (user_id,)) db_connection.commit() cursor.close()
This test connects to the test database using psycopg2. It inserts a user record with a specific username and email. Then it queries the database to retrieve the email for that username. Assertions check that the record exists and the email matches the inserted value, ensuring data integrity. Finally, it deletes the test record to keep the database clean. Using parameterized queries prevents SQL injection. The database connection is properly closed after tests.
Now add data-driven testing with 3 different user records to verify data integrity for multiple inputs
SELECT COUNT(*) FROM users WHERE email = '' OR email IS NULL;
SELECT user_id, COUNT(*) FROM users GROUP BY user_id;
order_date column. Which approach best ensures data integrity?Pass the test and this pattern moves unknown