---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"End-to-end test of the shared daily publish cap. Runs entirely against a THROWAWAY COPY of the production database so no production article is created, modified or deleted. \"\"\" import os."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-25T16:31:17Z"
site: "main"
source_path: "copecheck/test_publish_cap.py"
---

# !/usr/bin/env python3

Source path: `copecheck/test_publish_cap.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-25T16:31:17Z`

```py
#!/usr/bin/env python3
"""End-to-end test of the shared daily publish cap.

Runs entirely against a THROWAWAY COPY of the production database so no
production article is created, modified or deleted.
"""
import os
import shutil
import sqlite3
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

SRC = os.path.join(HERE, "data", "copecheck.db")
TMP = tempfile.mkdtemp(prefix="capttest-")
COPY = os.path.join(TMP, "copecheck.db")
print(f"cloning production db -> {COPY}")
src = sqlite3.connect(f"file:{SRC}?mode=ro", uri=True)
dst = sqlite3.connect(COPY)
src.backup(dst)
dst.close()
src.close()

os.environ["COPECHECK_DB"] = COPY
os.environ["DB_PATH"] = COPY

import db  # noqa: E402
import publish_gate as gate  # noqa: E402

db.DB_PATH = COPY

PASS, FAIL = [], []


def check(name, cond, detail=""):
    (PASS if cond else FAIL).append(name)
    print(f"  [{'PASS' if cond else 'FAIL'}] {name} {detail}")


def mkslug(c, n):
    """Create a throwaway pending article in the COPY."""
    slug = f"__captest_{n}"
    c.execute(
        """INSERT OR REPLACE INTO articles
             (slug, url, url_hash, canonical_url, canonical_url_hash, title,
              title_hash, source, status)
           VALUES (?,?,?,?,?,?,?,?, 'pending')""",
        (slug, f"https://example.invalid/{n}", f"h{n}",
         f"https://example.invalid/{n}", f"ch{n}", f"Test {n}",
         f"th{n}", "TestSource"),
    )
    return slug


print("\n=== TEST 1: cap blocks the 6th publish of a day ===")
with db.conn() as c:
    gate.ensure_schema(c)
    c.execute("BEGIN IMMEDIATE")
    day = "2030-01-01"
    granted = []
    for i in range(8):
        s = mkslug(c, i)
        ok = gate.claim_slot(c, s, channel="scanner", index_status="index",
                             priority=float(i), day=day)
        granted.append(ok)
    check("first 5 granted", granted[:5] == [True] * 5, granted[:5])
    check("6th through 8th blocked", granted[5:] == [False] * 3, granted[5:])
    check("ledger counts exactly 5 for the day",
          gate.published_today(c, day) == 5, gate.published_today(c, day))
    check("remaining_today is 0", gate.remaining_today(c, day) == 0)

print("\n=== TEST 2: counter resets on the next day ===")
with db.conn() as c:
    c.execute("BEGIN IMMEDIATE")
    check("next day starts at 0 used",
          gate.published_today(c, "2030-01-02") == 0)
    check("next day has 5 slots",
          gate.remaining_today(c, "2030-01-02") == 5)
    s = mkslug(c, 100)
    check("publish succeeds on the new day",
          gate.claim_slot(c, s, day="2030-01-02") is True)
    check("previous day still capped at 5",
          gate.published_today(c, "2030-01-01") == 5)

print("\n=== TEST 3: blocked candidates are QUEUED, not dropped ===")
with db.conn() as c:
    c.execute("BEGIN IMMEDIATE")
    day = "2030-02-01"
    for i in range(5):
        gate.claim_slot(c, mkslug(c, 200 + i), day=day)
    s = mkslug(c, 250)
    blocked = gate.claim_slot(c, s, day=day)
    check("6th blocked", blocked is False)
    gate.enqueue(c, s, desired_status="index", desired_reason="test",
                 desired_source="rss", channel="scanner", priority=88.0)
    row = c.execute("SELECT * FROM publish_queue WHERE slug=?", (s,)).fetchone()
    check("queued row exists", row is not None)
    check("queue keeps desired status", row and row["desired_status"] == "index")
    check("queue keeps priority", row and row["priority"] == 88.0)

print("\n=== TEST 4: manual override bypasses the cap ===")
with db.conn() as c:
    c.execute("BEGIN IMMEDIATE")
    day = "2030-03-01"
    for i in range(5):
        gate.claim_slot(c, mkslug(c, 300 + i), day=day)
    check("cap full", gate.remaining_today(c, day) == 0)
    s = mkslug(c, 350)
    check("manual=True publishes anyway",
          gate.claim_slot(c, s, manual=True, day=day) is True)
    check("manual did NOT consume a slot",
          gate.published_today(c, day) == 5, gate.published_today(c, day))
    os.environ["COPECHECK_PUBLISH_MANUAL"] = "1"
    s2 = mkslug(c, 351)
    check("COPECHECK_PUBLISH_MANUAL=1 publishes anyway",
          gate.claim_slot(c, s2, day=day) is True)
    check("env manual did NOT consume a slot",
          gate.published_today(c, day) == 5)
    os.environ.pop("COPECHECK_PUBLISH_MANUAL")

print("\n=== TEST 5: re-publishing the same slug is idempotent ===")
with db.conn() as c:
    c.execute("BEGIN IMMEDIATE")
    day = "2030-04-01"
    s = mkslug(c, 400)
    gate.claim_slot(c, s, day=day)
    used = gate.published_today(c, day)
    for _ in range(4):
        gate.claim_slot(c, s, day=day)
    check("repeat claims free", gate.published_today(c, day) == used, used)
    for i in range(4):
        gate.claim_slot(c, mkslug(c, 410 + i), day=day)
    check("4 more distinct slugs fit (5 total)",
          gate.published_today(c, day) == 5)
    check("6th distinct slug blocked",
          gate.claim_slot(c, mkslug(c, 499), day=day) is False)

print("\n=== TEST 6: grandfathered articles never consume a slot ===")
with db.conn() as c:
    c.execute("BEGIN IMMEDIATE")
    day = "2030-05-01"
    existing = c.execute(
        "SELECT slug FROM articles WHERE index_status='index' "
        "AND slug NOT LIKE '__captest%' LIMIT 3"
    ).fetchall()
    for r in existing:
        gate.claim_slot(c, r["slug"], day=day)
    check("re-promoting 3 existing articles used 0 slots",
          gate.published_today(c, day) == 0, gate.published_today(c, day))
    check("full 5 slots still free for new content",
          gate.remaining_today(c, day) == 5)

print("\n=== TEST 7: cap is GLOBAL across pipelines, not per-script ===")
with db.conn() as c:
    c.execute("BEGIN IMMEDIATE")
    day = "2030-06-01"
    results = []
    for i, chan in enumerate(["scanner", "curated", "rss",
                              "scanner", "curated", "rss", "curated"]):
        results.append(
            (chan, gate.claim_slot(c, mkslug(c, 600 + i),
                                   channel=chan, day=day)))
    granted = [r for r in results if r[1]]
    check("exactly 5 granted across 3 different channels",
          len(granted) == 5, [r[0] for r in granted])
    check("2 later ones blocked regardless of channel",
          [r[1] for r in results[5:]] == [False, False])

print("\n=== TEST 8: production DB untouched ===")
prod = sqlite3.connect(f"file:{SRC}?mode=ro", uri=True)
n = prod.execute("SELECT COUNT(*) FROM articles").fetchone()[0]
t = prod.execute(
    "SELECT COUNT(*) FROM articles WHERE slug LIKE '__captest%'").fetchone()[0]
check("no test articles leaked into production", t == 0, f"found {t}")
print(f"  production article count: {n}")
prod.close()

shutil.rmtree(TMP, ignore_errors=True)
print(f"\n{'='*52}\nPASSED {len(PASS)}   FAILED {len(FAIL)}")
if FAIL:
    print("FAILURES:", FAIL)
sys.exit(1 if FAIL else 0)
```
