Python Master Course V2 — 120. Production Python Capstone: A Tested Data Package
What you will be able to do
- Integrate test layers, build metadata and release checks
- Document public contracts and failure behavior
- Produce a reproducible local release with a verification checklist
Prerequisites: 111–119: testing and release engineering.
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 lesson120, 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 build setuptools wheel 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.
Capstone brief: a small package with an honest release contract
Build rowguard, a local CSV-validation package and command-line tool. It accepts files with exactly item_id,quantity columns, rejects missing or duplicate IDs, and requires nonnegative integer quantities. Validating a file returns structured records; an optional storage function writes those records to a local SQLite database in one transaction. The command-line interface validates and prints a compact JSON summary. It does not upload data or publish a package.
The important deliverable is a chain of evidence: written contract, implementation, tests, built artifact, clean-install check and limitations. A large feature list is less valuable than a small complete path that another learner can reproduce. Keep parsing, storage and command-line presentation separate so a failed test points to the relevant boundary.
Failure behavior is part of the API. Invalid content raises ValueError, missing files raise OSError subclasses and duplicate database identities raise sqlite3.IntegrityError. A failed database batch must leave prior committed rows intact. The CLI translates expected user-input problems into status 2 and a readable message; it does not hide unexpected programmer errors.
Use only synthetic IDs such as A and B. The database is a local educational artifact, not a production inventory system. The package does not implement concurrent reservation control, schema migrations, streaming of enormous files or security-grade CSV sanitization for spreadsheets. Stating these limits is professional documentation, not a weakness.
Create a complete minimal release candidate
Create src/rowguard and tests in the lesson120 folder. Save the following exact files. The validator parses the entire small input before storage; the database still enforces its own constraints in case another caller supplies records directly.
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "smartyfy-rowguard"
version = "0.1.0"
description = "Educational local CSV validation"
requires-python = ">=3.11"
[project.scripts]
rowguard = "rowguard.cli:main"
[tool.setuptools.packages.find]
where = ["src"]import csv
import sqlite3
from pathlib import Path
def load_records(path):
records = []
seen = set()
with Path(path).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()
try:
quantity = int(row["quantity"])
except ValueError as error:
raise ValueError(f"invalid quantity on line {line}") from error
if not item_id or item_id in seen or quantity < 0:
raise ValueError(f"invalid or duplicate record on line {line}")
seen.add(item_id)
records.append((item_id, quantity))
return records
def store_records(records, database):
connection = sqlite3.connect(database, isolation_level=None)
try:
connection.execute(
"CREATE TABLE IF NOT EXISTS items (item_id TEXT PRIMARY KEY, "
"quantity INTEGER NOT NULL CHECK(quantity >= 0))"
)
connection.execute("BEGIN")
try:
connection.executemany("INSERT INTO items VALUES (?, ?)", records)
connection.execute("COMMIT")
except Exception:
connection.execute("ROLLBACK")
raise
finally:
connection.close()import argparse
import json
from . import load_records
def main():
parser = argparse.ArgumentParser(description="Validate local item CSV")
parser.add_argument("path")
args = parser.parse_args()
try:
records = load_records(args.path)
except (OSError, ValueError) as error:
parser.exit(2, f"rowguard: {error}\n")
result = {"rows": len(records), "quantity": sum(q for _, q in records)}
print(json.dumps(result, sort_keys=True))
if __name__ == "__main__":
main()Test values, failures, storage and the actual CLI
import json
import sqlite3
import subprocess
import sys
import pytest
from rowguard import load_records, store_records
@pytest.fixture
def valid_csv(tmp_path):
path = tmp_path / "items.csv"
path.write_text("item_id,quantity\nA,2\nB,3\n", encoding="utf-8")
return path
def test_load(valid_csv):
assert load_records(valid_csv) == [("A", 2), ("B", 3)]
@pytest.mark.parametrize("body", ["A,-1", "A,many", "A,1\nA,2", ",1"])
def test_rejected_rows(tmp_path, body):
path = tmp_path / "bad.csv"
path.write_text("item_id,quantity\n" + body + "\n", encoding="utf-8")
with pytest.raises(ValueError):
load_records(path)
def test_storage_rollback(tmp_path):
database = tmp_path / "items.sqlite"
store_records([("A", 2)], database)
with pytest.raises(sqlite3.IntegrityError):
store_records([("B", 3), ("A", 9)], database)
connection = sqlite3.connect(database)
try:
assert connection.execute(
"SELECT item_id, quantity FROM items ORDER BY item_id"
).fetchall() == [("A", 2)]
finally:
connection.close()
def test_cli(valid_csv):
result = subprocess.run(
[sys.executable, "-m", "rowguard.cli", str(valid_csv)],
text=True, capture_output=True, check=True,
)
assert json.loads(result.stdout) == {"quantity": 5, "rows": 2}
assert result.stderr == ""python -m pip install -e .
python -m pytest -q
python -m buildExpected suite outcome: seven collected cases pass. The four parametrized invalid-row cases count separately. Save the following sample at the root and run the module to inspect its user-facing output.
item_id,quantity
A,2
B,3python -m rowguard.cli sample.csvExpected output
{"quantity": 5, "rows": 2}Guided release lab and acceptance rubric
Install the produced wheel in a new virtual environment, then run outside the checkout. Use the verification pattern from Lesson 118, replacing csvbrief with rowguard and the input header with item_id,quantity. Copy the tests into the temporary working directory and run them using that environment's Python. Install pytest there explicitly. Check both the module invocation and the installed rowguard console command; they should agree.
Write README.md in your project with five concrete sections: supported Python and installation, exact CSV schema, command examples, error behavior and known limits. Include the sample CSV above. Explain that duplicate IDs are rejected after trimming surrounding whitespace, while letter case remains significant. Explain that quantity parsing uses Python int, which permits surrounding whitespace and signed integer text; if your domain requires a stricter textual grammar, that is a new validation requirement.
Assess your deliverable using four equal areas. Contract clarity earns credit when valid, invalid and empty inputs are defined. Test quality earns credit for boundary cases, unchanged state after rollback and independent temporary resources. Release quality earns credit for a wheel that works in a fresh environment. Evidence quality earns credit for actual commands, versions and results rather than a copied expected transcript.
Before declaring completion, add tests for a header-only file, missing file, wrong header and the CLI failure status. Record a deliberate failure you introduced and restored. Retain the artifact checksum and source snapshot. If a step fails, describe the exact observed result and repair it before claiming that gate passed. Publishing to an index or deploying a service is optional future work requiring a separate decision.
Questions worth asking
Why validate before starting storage?
For this small file, full validation keeps parsing errors separate from database writes and simplifies diagnostics. The transaction remains necessary because constraints or storage failures can still occur during insertion. Very large files would require a different memory and streaming design.
Does SQLite rollback remove the table too?
The table is created before the explicit import transaction in this implementation. A rejected batch leaves the schema available and restores the prior rows. Tests should assert the intended data guarantee rather than assuming every earlier setup action is rolled back.
Why test the CLI as a subprocess?
It exercises argument parsing, module execution, output channels and process status through the interface a user runs. Calling load_records alone cannot establish those behaviors. The subprocess still uses only local synthetic data and the active interpreter.
Is a seven-case suite enough for release?
It is a starting suite with useful layers, not a claim of exhaustive coverage. The acceptance lab adds missing boundaries and failure statuses. Required assurance should reflect the contract and consequences of defects, not a fixed test count.
What is the difference between expected and observed output?
Expected output is the result predicted from the specification and code. Observed output comes from an actual run in a stated environment. A release report must identify which is which and must not present copied examples as executed evidence.
Why document limits alongside successful checks?
Readers need to know where evidence stops. A local single-process educational importer does not automatically provide concurrency control, giant-file support or operational monitoring. Clear boundaries help future maintainers choose the next tests and features responsibly.
Practice, then compare your solution
1. CLI rejection
Test a missing input path through the CLI.
Worked solution and reasoning
Run the subprocess with capture_output=True and without check=True so you can inspect the failure. Assert returncode == 2, stdout == "", and a useful rowguard-prefixed stderr message. Avoid matching an operating-system-specific full filename message.
2. Empty valid file
Specify load_records for a header-only file and its CLI summary.
Worked solution and reasoning
load_records returns an empty list. The summary is {"quantity": 0, "rows": 0}. A missing header is different and should raise ValueError. Add both tests to prevent conflating a valid empty dataset with malformed input.
Capstone completion checkpoint
Your release candidate is complete when another learner can build it, install its wheel away from the checkout, reproduce the tests and understand its limits from the README. Keep your actual verification record with the artifact. The next module builds on these habits while introducing numerical and statistical tools.
Official documentation and next steps
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.