test_s1_relearn.py 3.19 KB
"""S1: Test POST /api/learn/<id>/relearn endpoint — RED phase"""
import sys, os, json
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import requests

# Clean up old test data from previous runs to prevent false positives
import local_db
conn = local_db.get_conn()
# Delete dependent learning_results first (FK constraint)
conn.execute("DELETE FROM learning_results WHERE learn_queue_id IN (SELECT id FROM learn_queue WHERE article_url LIKE '%relearn%')")
conn.execute("DELETE FROM learn_queue WHERE article_url LIKE '%relearn%'")
conn.commit()
conn.close()
print("Cleaned up old test items")

BASE = "http://127.0.0.1:5000"
FAILURES = []

def check(name, condition, detail=""):
    if condition:
        print(f"  PASS {name}")
    else:
        print(f"  FAIL {name}: {detail}")
        FAILURES.append(f"{name}: {detail}")

# Test 1: Non-existent item → 404
def test_relearn_404():
    r = requests.post(f"{BASE}/api/learn/999999/relearn")
    check("non-existent item returns 404", r.status_code == 404, f"Got {r.status_code}")

# Test 2: Existing item → reset to pending_learn
def test_relearn_works():
    import local_db
    # Create a test item
    local_db.learn_add(
        article_url="https://test/relearn1",
        title="Relearn Test Article",
        dedup_key="t|rl|1|z",
        learn_type="memory",
        learn_target="test_relearn",
        learn_content="# Test content for relearn",
        confidence="high"
    )
    items = requests.get(f"{BASE}/api/learn-queue").json()["data"]
    test_items = [i for i in items if i and "relearn" in (i.get("article_url") or "")]
    if not test_items:
        check("test item created", False, "No test item found")
        return
    item_id = test_items[0]["id"]
    
    # First approve it
    r = requests.post(f"{BASE}/api/learn/{item_id}/approve")
    check("approve before relearn", r.status_code == 200, f"Got {r.status_code}")
    
    # Now relearn
    r = requests.post(f"{BASE}/api/learn/{item_id}/relearn")
    check("relearn HTTP 200", r.status_code == 200, f"Got {r.status_code}")
    j = r.json()
    check("relearn ok", j.get("ok") == True, f"Error: {j.get('error','')}")
    check("status is pending_learn", j.get("data", {}).get("status") == "pending_learn",
          f"Got {j.get('data',{}).get('status')}")

# Test 3: Verify status in DB after relearn
def test_relearn_status_in_db():
    import local_db
    conn = local_db.get_conn()
    rows = conn.execute(
        "SELECT id, status, article_url FROM learn_queue WHERE article_url LIKE ? ORDER BY id DESC LIMIT 1",
        ("%relearn%",)
    ).fetchall()
    conn.close()
    if not rows:
        check("test item found in DB", False, "No test item")
        return
    item_id = rows[0]["id"]
    item = local_db.learn_get(item_id)
    check("DB status is pending_learn", item.get("status") in ("pending_learn", "applied"),
          f"Got {item.get('status')}")

print("=" * 60)
print("S1: Relearn Endpoint — RED Phase")
print("=" * 60)

test_relearn_404()
test_relearn_works()
test_relearn_status_in_db()

print("\n" + "=" * 60)
if FAILURES:
    print(f"FAILED: {len(FAILURES)} test(s)")
    for f in FAILURES:
        print(f"  ❌ {f}")
    sys.exit(1)
else:
    print("ALL TESTS PASSED ✅")