Python Master Course V2 — 116. Integration Tests for Files and SQLite
What you will be able to do
- Separate unit contracts from component integration behavior
- Verify SQLite transactions, constraints and rollback
- Keep filesystem and database tests independent and repeatable
Prerequisites: 075–076: CSV and JSON; 083–090: SQLite and transactions; 112–115: testing.
Your local workspace
Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson116, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.
Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.
python -m pip install pytestThe examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.
Integration means exercising a real collaboration
A unit test can check integer parsing in isolation. An integration test asks whether the parser, CSV reader, database connection and schema work together. The distinction is scope, not speed: a tiny SQLite integration test may be very fast. Its value comes from keeping the real boundary behavior, including transactions and constraints, rather than replacing every component with a fake.
The import contract is all-or-nothing. A file has exactly item_id,quantity columns; IDs are nonempty strings, quantities are nonnegative integers, and IDs must be unique in the database. If any row fails, none of that file's inserts should remain. Existing records must survive a rejected import. A primary key enforces identity, and a CHECK constraint provides an additional database-level nonnegative rule. Python validation gives clearer messages, but database constraints protect against other writers too.
Transactions group changes into one unit. BEGIN starts the unit, COMMIT makes it durable, and ROLLBACK cancels its uncommitted work. Connection context managers have transaction behavior that depends on connection settings and Python's transaction-control mode; they also do not universally mean “close this connection.” This example chooses explicit SQL transaction commands with isolation_level=None, then closes in finally. That is deliberately compatible with Python 3.11 and later and avoids relying on a changing default.
Use a database file inside tmp_path, not a developer database. A separate connection used for verification demonstrates committed visibility. An in-memory database is useful for some tests, but separate connections normally have separate in-memory databases; a temporary file makes this collaboration easier to understand. Small temporary files are a realistic and still local integration boundary.
A transactional CSV importer
Save importer.py. Schema initialization is a distinct operation, completed before the import transaction. Parameter placeholders carry row values; constructing SQL by concatenating untrusted input is unnecessary and unsafe. The exception handler rolls back then re-raises so callers retain the actual failure.
import csv
import sqlite3
from pathlib import Path
def initialize(database):
connection = sqlite3.connect(database, isolation_level=None)
try:
connection.execute(
"CREATE TABLE IF NOT EXISTS stock ("
"item_id TEXT PRIMARY KEY, "
"quantity INTEGER NOT NULL CHECK(quantity >= 0))"
)
finally:
connection.close()
def import_csv(source, database):
connection = sqlite3.connect(database, isolation_level=None)
try:
connection.execute("BEGIN")
count = 0
try:
with Path(source).open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
if reader.fieldnames != ["item_id", "quantity"]:
raise ValueError("expected item_id,quantity header")
for line, row in enumerate(reader, start=2):
if None in row or row["quantity"] is None:
raise ValueError(f"wrong column count on line {line}")
item_id = row["item_id"].strip()
quantity = int(row["quantity"])
if not item_id or quantity < 0:
raise ValueError(f"invalid row on line {line}")
connection.execute(
"INSERT INTO stock VALUES (?, ?)", (item_id, quantity)
)
count += 1
connection.execute("COMMIT")
except Exception:
connection.execute("ROLLBACK")
raise
return count
finally:
connection.close()The broad exception handler is justified narrowly here because it performs cleanup and immediately re-raises; it does not suppress or reinterpret unexpected errors. KeyboardInterrupt is outside Exception and connection closing still releases an unfinished SQLite transaction. This example is not designed for multi-writer migration management.
Guided lab: prove rollback after a partial insert
import sqlite3
import pytest
from importer import import_csv, initialize
def stored_rows(database):
connection = sqlite3.connect(database)
try:
return connection.execute(
"SELECT item_id, quantity FROM stock ORDER BY item_id"
).fetchall()
finally:
connection.close()
@pytest.fixture
def database(tmp_path):
path = tmp_path / "stock.sqlite"
initialize(path)
return path
def test_success(tmp_path, database):
source = tmp_path / "good.csv"
source.write_text("item_id,quantity\nA,2\nB,3\n", encoding="utf-8")
assert import_csv(source, database) == 2
assert stored_rows(database) == [("A", 2), ("B", 3)]
def test_duplicate_rolls_back_only_new_import(tmp_path, database):
source = tmp_path / "rows.csv"
source.write_text("item_id,quantity\nA,2\n", encoding="utf-8")
import_csv(source, database)
source.write_text("item_id,quantity\nB,3\nA,9\n", encoding="utf-8")
with pytest.raises(sqlite3.IntegrityError):
import_csv(source, database)
assert stored_rows(database) == [("A", 2)]
def test_malformed_late_row_rolls_back(tmp_path, database):
source = tmp_path / "bad.csv"
source.write_text("item_id,quantity\nA,2\nB,many\n", encoding="utf-8")
with pytest.raises(ValueError):
import_csv(source, database)
assert stored_rows(database) == []python -m pytest -q test_importer.pyExpected result: three passing tests. The duplicate test deliberately inserts B before encountering existing A. Therefore its final assertion detects a partial-commit bug; putting the duplicate first would not establish rollback of an earlier successful insert.
Extend the suite with a header-only file, wrong columns and an empty ID. Inspect stored rows through a new connection each time. Do not assert insertion order without ORDER BY; database row order is not a contract unless requested explicitly. To demonstrate the test's strength, temporarily commit after each inserted row. The rollback test should fail or encounter a transaction-state error. Restore the all-or-nothing implementation.
A real importer may need batch sizing, resumability or duplicate-update semantics. Those features change the contract: an upsert is not a harmless implementation substitution for rejecting duplicates. Write the expected behavior first and update both database schema and tests deliberately.
Questions worth asking
Why test with real SQLite instead of a dictionary fake?
A dictionary cannot establish SQL syntax, primary-key enforcement, transaction boundaries or cross-connection visibility. A fake is useful for logic isolated from storage, while this lesson specifically needs evidence about the real storage boundary.
Why place the malformed row second?
The importer must have something to undo. If the first row fails, an empty database afterward proves rejection but says little about rollback. A valid early row followed by an invalid row exposes partial-commit mistakes.
Does leaving with connection close it?
A SQLite connection context manager manages transaction completion under its configured mode; it is not a general guarantee of closing the connection. This example closes explicitly in finally, making resource lifetime easy to audit across Python versions.
Why preserve an old row during the duplicate test?
Rollback should undo only the current transaction. The test establishes that a rejected file neither leaves its earlier new row nor destroys previously committed data. Those are separate aspects of the all-or-nothing import contract.
Can I rely on the order returned by SELECT?
Only when the query specifies the required ordering. Tests that assume an incidental storage order can pass on one dataset and fail after a plan or schema change. ORDER BY item_id makes the expected list meaningful.
Is Python validation redundant with a CHECK constraint?
They protect different boundaries. Python can report useful row-level problems before executing SQL. The constraint applies regardless of which client writes to the table. Testing both helps prevent another code path from bypassing an application-only rule.
Practice, then compare your solution
1. Empty import
Specify the return value and database state for a header-only CSV.
Worked solution and reasoning
The return value is 0 and previously stored rows remain unchanged. The file has a valid schema but no data. This differs from an entirely empty file, whose header is missing and should be rejected.
2. Direct constraint check
How would you show the database rejects negative quantities independently of the importer?
Worked solution and reasoning
Open a temporary initialized database, attempt INSERT INTO stock VALUES (?, ?) with ("X", -1), and expect sqlite3.IntegrityError. Close the connection in finally. This test deliberately bypasses Python row validation to exercise the database contract.
Mastery checkpoint
Explain which behaviors belong to parsing, schema enforcement and transaction control. Show evidence from a fresh connection that valid imports commit and failed late rows roll back without damaging existing records. Keep all files temporary and describe unsupported concurrency or migration behavior honestly.
Official documentation and next steps
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.