|
| 1 | +import sqlite3 |
| 2 | +import sys |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) |
| 6 | + |
| 7 | +import analytics_db as adb |
| 8 | + |
| 9 | + |
| 10 | +def test_init_db_creates_all_expected_tables(tmp_path): |
| 11 | + db_path = str(tmp_path / "test.db") |
| 12 | + adb.init_db(db_path) |
| 13 | + |
| 14 | + conn = sqlite3.connect(db_path) |
| 15 | + tables = {r[0] for r in conn.execute( |
| 16 | + "SELECT name FROM sqlite_master WHERE type='table'")} |
| 17 | + conn.close() |
| 18 | + |
| 19 | + assert {"pins", "posts", "analytics", "sales"} <= tables |
| 20 | + |
| 21 | + |
| 22 | +def test_init_db_is_idempotent(tmp_path): |
| 23 | + db_path = str(tmp_path / "test.db") |
| 24 | + adb.init_db(db_path) |
| 25 | + adb.init_db(db_path) # must not raise on re-init |
| 26 | + |
| 27 | + conn = adb.connect(db_path) |
| 28 | + conn.execute("INSERT INTO pins (theme, idx) VALUES ('nature', 1)") |
| 29 | + conn.commit() |
| 30 | + row = conn.execute("SELECT theme, idx FROM pins").fetchone() |
| 31 | + conn.close() |
| 32 | + |
| 33 | + assert row["theme"] == "nature" and row["idx"] == 1 |
| 34 | + |
| 35 | + |
| 36 | +def test_pins_table_rejects_duplicate_theme_idx(tmp_path): |
| 37 | + db_path = str(tmp_path / "test.db") |
| 38 | + adb.init_db(db_path) |
| 39 | + conn = adb.connect(db_path) |
| 40 | + conn.execute("INSERT INTO pins (theme, idx) VALUES ('nature', 1)") |
| 41 | + conn.commit() |
| 42 | + try: |
| 43 | + conn.execute("INSERT INTO pins (theme, idx) VALUES ('nature', 1)") |
| 44 | + conn.commit() |
| 45 | + raised = False |
| 46 | + except sqlite3.IntegrityError: |
| 47 | + raised = True |
| 48 | + finally: |
| 49 | + conn.close() |
| 50 | + assert raised, "UNIQUE(theme, idx) constraint should reject the duplicate" |
0 commit comments