Test Overview
This test verifies that data is correctly migrated from the old database schema to the new schema without loss or corruption. It checks that all expected tables and records exist after migration.
This test verifies that data is correctly migrated from the old database schema to the new schema without loss or corruption. It checks that all expected tables and records exist after migration.
import unittest import sqlite3 class TestDatabaseMigration(unittest.TestCase): def setUp(self): # Connect to old and new databases self.old_db = sqlite3.connect(':memory:') self.new_db = sqlite3.connect(':memory:') self.create_old_schema() self.create_new_schema() self.insert_old_data() self.perform_migration() def create_old_schema(self): cursor = self.old_db.cursor() cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)') self.old_db.commit() def create_new_schema(self): cursor = self.new_db.cursor() cursor.execute('CREATE TABLE users (user_id INTEGER PRIMARY KEY, full_name TEXT, age INTEGER)') self.new_db.commit() def insert_old_data(self): cursor = self.old_db.cursor() cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 30)) cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 25)) self.old_db.commit() def perform_migration(self): old_cursor = self.old_db.cursor() new_cursor = self.new_db.cursor() old_cursor.execute('SELECT id, name, age FROM users') rows = old_cursor.fetchall() for row in rows: new_cursor.execute('INSERT INTO users (user_id, full_name, age) VALUES (?, ?, ?)', row) self.new_db.commit() def test_data_migrated_correctly(self): new_cursor = self.new_db.cursor() new_cursor.execute('SELECT user_id, full_name, age FROM users ORDER BY user_id') migrated_rows = new_cursor.fetchall() expected = [(1, 'Alice', 30), (2, 'Bob', 25)] self.assertEqual(migrated_rows, expected) def tearDown(self): self.old_db.close() self.new_db.close() if __name__ == '__main__': unittest.main()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and sets up in-memory old and new databases | Two empty in-memory SQLite databases are created with old and new schemas | - | PASS |
| 2 | Insert sample data into old database's users table | Old database users table contains two records: Alice (30), Bob (25) | - | PASS |
| 3 | Perform migration by copying data from old to new database with new schema | New database users table populated with migrated records matching old data | - | PASS |
| 4 | Query new database users table and compare data to expected records | New database users table has records: (1, 'Alice', 30), (2, 'Bob', 25) | Assert that migrated data equals expected data [(1, 'Alice', 30), (2, 'Bob', 25)] | PASS |
| 5 | Close database connections and end test | Databases closed, test ends cleanly | - | PASS |