#!/usr/bin/env python3 """Run the fictional SQL-report acceptance fixture using only Python's stdlib.""" import csv import sqlite3 import sys import unittest from pathlib import Path FIXTURE_DIR = Path(__file__).absolute().parent START_INCLUSIVE = "2026-10-01 00:00" END_EXCLUSIVE = "2026-11-01 00:00" OPEN_STATUS = "Open" def _fixture_rows(filename, expected_fields): with (FIXTURE_DIR / filename).open("r", encoding="utf-8", newline="") as handle: reader = csv.DictReader(handle) if reader.fieldnames != expected_fields: raise ValueError(f"Unexpected header in bundled fixture: {filename}") return [tuple(row[field] for field in expected_fields) for row in reader] def build_database(): """Load only the three named CSV files into a fresh in-memory database.""" connection = sqlite3.connect(":memory:") connection.executescript( """ CREATE TABLE requests ( request_id TEXT PRIMARY KEY, created_at_myt TEXT NOT NULL, status_at_snapshot TEXT NOT NULL, assigned_staff_id TEXT NOT NULL ); CREATE TABLE notes ( note_id TEXT PRIMARY KEY, request_id TEXT NOT NULL ); CREATE TABLE staff ( staff_id TEXT PRIMARY KEY, staff_label TEXT NOT NULL ); """ ) connection.executemany( "INSERT INTO requests (request_id, created_at_myt, status_at_snapshot, assigned_staff_id) VALUES (?, ?, ?, ?)", _fixture_rows("requests.csv", ["request_id", "created_at_myt", "status_at_snapshot", "assigned_staff_id"]), ) connection.executemany( "INSERT INTO notes (note_id, request_id) VALUES (?, ?)", _fixture_rows("notes.csv", ["note_id", "request_id"]), ) connection.executemany( "INSERT INTO staff (staff_id, staff_label) VALUES (?, ?)", _fixture_rows("staff.csv", ["staff_id", "staff_label"]), ) return connection CORRECT_QUERY = """ SELECT CASE WHEN s.staff_id IS NULL THEN 'UNRESOLVED' ELSE r.assigned_staff_id END AS report_group, COUNT(*) AS request_count FROM requests AS r LEFT JOIN staff AS s ON s.staff_id = r.assigned_staff_id WHERE r.created_at_myt >= ? AND r.created_at_myt < ? AND r.status_at_snapshot = ? GROUP BY report_group ORDER BY CASE WHEN report_group = 'UNRESOLVED' THEN 1 ELSE 0 END, report_group """ NAIVE_JOIN_QUERY = """ SELECT s.staff_id AS report_group, COUNT(*) AS request_count FROM requests AS r JOIN notes AS n ON n.request_id = r.request_id JOIN staff AS s ON s.staff_id = r.assigned_staff_id WHERE r.created_at_myt >= ? AND r.created_at_myt < ? AND r.status_at_snapshot = ? GROUP BY report_group ORDER BY report_group """ NAIVE_DISTINCT_QUERY = """ SELECT s.staff_id AS report_group, COUNT(DISTINCT r.request_id) AS request_count FROM requests AS r JOIN notes AS n ON n.request_id = r.request_id JOIN staff AS s ON s.staff_id = r.assigned_staff_id WHERE r.created_at_myt >= ? AND r.created_at_myt < ? AND r.status_at_snapshot = ? GROUP BY report_group ORDER BY report_group """ def _report_parameters(): return (START_INCLUSIVE, END_EXCLUSIVE, OPEN_STATUS) def group_counts(connection, query): return dict(connection.execute(query, _report_parameters()).fetchall()) def eligible_request_ids(connection): rows = connection.execute( """ SELECT request_id FROM requests WHERE created_at_myt >= ? AND created_at_myt < ? AND status_at_snapshot = ? ORDER BY request_id """, _report_parameters(), ).fetchall() return [row[0] for row in rows] class ReportAcceptanceTests(unittest.TestCase): def setUp(self): self.connection = build_database() def tearDown(self): self.connection.close() def test_start_boundary_is_inclusive(self): self.connection.execute( "INSERT INTO requests (request_id, created_at_myt, status_at_snapshot, assigned_staff_id) VALUES (?, ?, ?, ?)", ("R000", START_INCLUSIVE, OPEN_STATUS, "A"), ) self.assertIn("R000", eligible_request_ids(self.connection)) def test_end_boundary_is_exclusive(self): self.assertNotIn("R105", eligible_request_ids(self.connection)) def test_closed_request_is_excluded(self): self.assertNotIn("R104", eligible_request_ids(self.connection)) def test_correct_groups_preserve_unmatched_staff(self): counts = group_counts(self.connection, CORRECT_QUERY) self.assertEqual(counts, {"A": 1, "B": 1, "UNRESOLVED": 1}) self.assertEqual(sum(counts.values()), 3) def test_note_join_duplicates_rows_and_equal_total_hides_error(self): correct = group_counts(self.connection, CORRECT_QUERY) naive = group_counts(self.connection, NAIVE_JOIN_QUERY) self.assertEqual(naive, {"A": 2, "B": 1}) self.assertEqual(sum(naive.values()), 3) self.assertEqual(sum(naive.values()), sum(correct.values())) self.assertNotEqual(naive, correct) def test_distinct_after_inner_staff_join_still_drops_unmatched_request(self): distinct = group_counts(self.connection, NAIVE_DISTINCT_QUERY) self.assertEqual(distinct, {"A": 1, "B": 1}) self.assertEqual(sum(distinct.values()), 2) self.assertNotIn("UNRESOLVED", distinct) def _print_groups(counts): if not counts: print(" (no groups)") return for group in sorted(counts, key=lambda value: (value == "UNRESOLVED", value)): print(f" {group}: {counts[group]}") def print_examples(): connection = build_database() try: correct = group_counts(connection, CORRECT_QUERY) naive = group_counts(connection, NAIVE_JOIN_QUERY) distinct = group_counts(connection, NAIVE_DISTINCT_QUERY) print("Correct one-request result:") _print_groups(correct) print(f" total: {sum(correct.values())}") print("Naive notes + inner staff join:") _print_groups(naive) print(f" total: {sum(naive.values())} (same grand total, wrong groups)") print("COUNT(DISTINCT request_id) after that bad inner join:") _print_groups(distinct) print(f" total: {sum(distinct.values())} (unmatched S99 was already dropped)") finally: connection.close() def run_tests(): suite = unittest.defaultTestLoader.loadTestsFromTestCase(ReportAcceptanceTests) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=0).run(suite) if not result.wasSuccessful(): raise SystemExit(1) return result.testsRun def main(): print(f"Python: {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}") print(f"SQLite: {sqlite3.sqlite_version}") test_count = run_tests() print(f"Tests: {test_count} passed") print_examples() if __name__ == "__main__": main()