chore(api): rename test function for clarity on enrollment behavior

This commit is contained in:
shay
2026-04-18 11:58:02 -04:00
parent f9c59d934d
commit 7b2301cec0
7 changed files with 239 additions and 71 deletions
+25 -9
View File
@@ -17,7 +17,12 @@ def env(monkeypatch):
@responses.activate
def test_first_request_builds_then_serves_ready(env):
def test_full_flow_data_then_generate_then_serve(env):
"""End-to-end of the new two-phase pipeline:
1. /data enrolls + kicks off prefetch (worker populates widget_data)
2. /generate renders SVG from the cached payload + settings
3. /api/<u> serves the stored SVG to README consumers
"""
responses.add(
responses.GET, "http://fetcher-mock/data/alice",
json={"data": {"user": {"login": "alice"}, "repos": [], "events": [],
@@ -27,20 +32,31 @@ def test_first_request_builds_then_serves_ready(env):
)
client = apimod.app.test_client()
r1 = client.get("/api/alice")
assert r1.headers["X-Widget-Status"] == "building"
# Phase 1: prefetch via /data (enrolls + kicks off background thread).
r_data = client.get("/api/alice/data")
assert r_data.status_code == 202
# First request kicks off a background build thread; drain any residual
# job in case of races, then poll the API for readiness.
# Drain any residual job synchronously in case the kickoff thread lost
# the race (and to make the assertion deterministic).
for _ in range(5):
if not worker.process_one():
break
# Widget data should now be available for client-side preview.
deadline = time.time() + 2.0
while time.time() < deadline:
r2 = client.get("/api/alice")
if r2.headers["X-Widget-Status"] == "ready":
r = client.get("/api/alice/data")
if r.status_code == 200 and r.get_json().get("status") == "ready":
break
time.sleep(0.05)
assert r2.headers["X-Widget-Status"] == "ready"
assert r2.data.startswith(b"<svg") or r2.data.startswith(b"<?xml")
assert r.status_code == 200 and r.get_json()["status"] == "ready"
# Phase 2: Generate button → render SVG.
r_gen = client.post("/api/alice/generate")
assert r_gen.status_code == 200
assert r_gen.get_json()["status"] == "ready"
# Phase 3: SVG is served from DB.
r_svg = client.get("/api/alice")
assert r_svg.headers["X-Widget-Status"] == "ready"
assert r_svg.data.startswith(b"<svg") or r_svg.data.startswith(b"<?xml")
+43 -13
View File
@@ -6,6 +6,9 @@ from src import api as apimod
@pytest.fixture
def client(monkeypatch):
# No-op the kickoff so tests don't spawn background threads that
# would try to reach the (unmocked) fetcher and race tempdir teardown.
monkeypatch.setattr(apimod, "_kickoff_prefetch_async", lambda: None)
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
@@ -22,27 +25,28 @@ def test_health(client):
assert r.get_json()["service"] == "generator"
def test_get_unknown_user_auto_enrolls_and_returns_placeholder(client):
def test_get_unknown_user_returns_building_placeholder_without_enrolling(client):
"""The SVG endpoint is for README embeds — enrollment is frontend-driven
through /data or /api/enroll, so GET /api/<u> does not auto-enroll."""
r = client.get("/api/alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "building"
assert "Building" in r.data.decode()
assert dbmod.get_settings("alice") is not None
assert dbmod.get_settings("alice") is None
def test_rate_limit_returns_rate_limited_placeholder(client, monkeypatch):
monkeypatch.setattr(apimod.config, "ENROLLMENT_DAILY_CAP", 1)
client.get("/api/alice")
r = client.get("/api/bob")
assert r.headers["X-Widget-Status"] == "rate_limited"
def test_enrolled_but_not_generated_returns_building(client):
"""After enrollment (via /data) but before /generate is clicked the SVG
endpoint returns a building placeholder."""
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice")
assert r.headers["X-Widget-Status"] == "building"
def test_enrolled_user_with_built_widget_returns_ready(client):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>ready</svg>"})
with dbmod._settings_conn() as c:
c.execute("UPDATE users SET settings_hash='h1' WHERE username='alice'")
c.commit()
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
@@ -68,13 +72,39 @@ def test_refresh_is_one_shot(client):
def test_not_found_status_header(client):
dbmod.enroll("ghost", {"theme": "dark"})
dbmod.put_widgets("ghost", "not_found", {"composite": "<svg>404</svg>"})
with dbmod._settings_conn() as c:
c.execute("UPDATE users SET settings_hash='not_found' WHERE username='ghost'")
c.commit()
dbmod.point_current_widget("ghost", "not_found")
r = client.get("/api/ghost")
assert r.headers["X-Widget-Status"] == "not_found"
def test_generate_endpoint_renders_and_stores_svg(client):
"""POST /api/<u>/generate invokes the on-demand render path and caches
the composite SVG for subsequent README embeds."""
dbmod.enroll("alice", {"theme": "dark"})
with patch("src.worker.render_widgets_now",
return_value={"composite": "<svg>r</svg>", "grade": "<svg>g</svg>"}):
# Simulate the render path also updating current_widget so the
# follow-up GET sees ready.
def fake_render(username):
dbmod.put_widgets(username, "h1", {"composite": "<svg>r</svg>"})
dbmod.point_current_widget(username, "h1")
return {"composite": "<svg>r</svg>"}
with patch("src.worker.render_widgets_now", side_effect=fake_render):
r = client.post("/api/alice/generate")
assert r.status_code == 200
body = r.get_json()
assert body["status"] == "ready"
assert body["composite_url"] == "/api/alice"
r2 = client.get("/api/alice")
assert r2.headers["X-Widget-Status"] == "ready"
assert b"<svg>r</svg>" in r2.data
def test_generate_endpoint_rejects_unenrolled(client):
r = client.post("/api/bob/generate")
assert r.status_code == 404
# ---- GET /api/<username>/data: precomputed widget data for client-side rendering ----
# Pure DB lookup — fetcher is never touched on the hot path.
+27 -9
View File
@@ -13,7 +13,9 @@ def tmp_dbs(monkeypatch):
yield d
def test_process_one_renders_and_stores_widgets(tmp_dbs):
def test_process_one_stores_widget_data_without_rendering_svg(tmp_dbs):
"""Phase 1 worker only hydrates widget_data; SVGs are rendered by the
/generate endpoint."""
dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]})
fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [], "total_commits": 0, "recent_commits": 0,
@@ -21,24 +23,40 @@ def test_process_one_renders_and_stores_widgets(tmp_dbs):
fake_data = {"grade": {"grade": "A", "score": 80, "stats": {}, "tags": [], "breakdown": {}}}
with patch("src.worker.fetcher_client.get_data",
return_value={"data": fake_payload, "payload_hash": "h1"}), \
patch("src.worker._render_widgets",
return_value={"composite": "<svg>c</svg>", "grade": "<svg>g</svg>"}), \
patch("src.worker._compute_widget_data", return_value=fake_data):
worker.process_one()
svg = dbmod.get_current_widget("alice", "composite")
assert svg == "<svg>c</svg>"
# Data JSON is written alongside the SVGs so the /data endpoint is a lookup.
# Widget data is stored for the client-side preview.
row = dbmod.get_current_widget_data("alice")
assert row is not None and row["data"] == fake_data
# SVGs are NOT rendered yet — /generate hasn't been called.
assert dbmod.get_current_widget("alice", "composite") is None
def test_not_found_payload_renders_not_found_placeholder(tmp_dbs):
def test_render_widgets_now_produces_svg(tmp_dbs):
"""Phase 2: /generate endpoint path renders composite SVG on demand."""
dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]})
fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [], "total_commits": 0, "recent_commits": 0,
"total_prs": 0, "collaborators_data": [], "avatar_b64": ""}
with patch("src.worker.fetcher_client.get_data",
return_value={"data": fake_payload, "payload_hash": "h1"}), \
patch("src.worker._render_widgets",
return_value={"composite": "<svg>c</svg>", "grade": "<svg>g</svg>"}):
widgets = worker.render_widgets_now("alice")
assert widgets["composite"] == "<svg>c</svg>"
assert dbmod.get_current_widget("alice", "composite") == "<svg>c</svg>"
def test_not_found_payload_marks_not_found_in_data(tmp_dbs):
"""Worker records a not_found sentinel in widget_data; SVG placeholder
is rendered at request time by /api/<u>, not by the worker."""
dbmod.enroll("ghost", {"theme": "dark"})
with patch("src.worker.fetcher_client.get_data",
return_value={"data": {"error": "not_found"}, "payload_hash": "x"}):
worker.process_one()
svg = dbmod.get_current_widget("ghost", "composite")
assert svg and "ghost" in svg
assert dbmod.get_current_widget_hash("ghost") == "not_found"
row = dbmod.get_current_widget_data("ghost")
assert row is not None and row["data"] == {"not_found": True}
def test_worker_retries_on_fetcher_failure(tmp_dbs):