Test Database State with Isolated Fixtures
Core idea
A database test creates its own schema and known starting rows, performs an operation, and asserts both its result and persistent state. Use an in-memory connection for isolated SQL behavior; use a private temporary file when testing reopening. A unittest fixture can register close with addCleanup immediately after connecting. Commit setup before testing rollback so setup itself is not undone.
import sqlite3, unittestclass StockTest(unittest.TestCase): def setUp(self): self.db = sqlite3.connect(':memory:', autocommit=False) self.addCleanup(self.db.close) self.db.execute('CREATE TABLE bins (qty INTEGER CHECK(qty>=0))') self.db.execute('INSERT INTO bins VALUES (4)') self.db.commit() def test_rejection(self): with self.assertRaises(sqlite3.IntegrityError): with self.db: self.db.execute('UPDATE bins SET qty=2') self.db.execute('UPDATE bins SET qty=-1') self.assertEqual(self.db.execute('SELECT qty FROM bins').fetchone()[0], 4)result = unittest.TestResult()StockTest('test_rejection').run(result)print(result.testsRun, result.wasSuccessful())The test checks the exception and the restored state; addCleanup closes the connection.
Verify reopening after commit
import sqlite3from contextlib import closingfrom tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as folder: path = Path(folder)/'inventory.db' with closing(sqlite3.connect(path, autocommit=False)) as db: db.execute('CREATE TABLE bins (qty INTEGER)') db.execute('INSERT INTO bins VALUES (8)') db.commit() with closing(sqlite3.connect(path, autocommit=False)) as db: print(db.execute('SELECT qty FROM bins').fetchone()[0])A second connection to the same temporary file sees the committed data. This tests ordinary reopening, not power-loss durability.
Common mistake
Never use production data for routine tests. Avoid relying on a previous test’s state or only checking that an exception occurred. Test the final data and clean up resources. In-memory fixtures do not cover every disk, locking or migration behavior.
Practice
Write separate tests for successful insertion, duplicate rejection and empty selection; create the schema anew in setUp. Add a temporary-file reopening test.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database tests
Check your understanding of database tests.
What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE t(n)') print(db.execute('SELECT count(*) FROM t').fetchone()[0])What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE t(n)') db.commit() db.execute('INSERT INTO t VALUES (3)') db.rollback() print(db.execute('SELECT count(*) FROM t').fetchone()[0])Why commit setup before a rollback test?
What does an in-memory database test not prove?