mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
chore(api): rename test function for clarity on enrollment behavior
This commit is contained in:
@@ -126,8 +126,17 @@ export default function App() {
|
||||
setStep('workshop')
|
||||
}
|
||||
|
||||
const handleGenerate = () => {
|
||||
const handleGenerate = async () => {
|
||||
setStep('result')
|
||||
// Fire-and-forget: the backend renders the composite SVG from the
|
||||
// fetcher's cached payload + current settings and persists it to
|
||||
// widgets.db for README embeds. The Result screen itself still
|
||||
// renders client-side from widgetData for immediate feedback.
|
||||
try {
|
||||
await fetch(`/api/${encodeURIComponent(username)}/generate`, { method: 'POST' })
|
||||
} catch (e) {
|
||||
console.warn('generate call failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
|
||||
+61
-27
@@ -4,6 +4,15 @@ Serves:
|
||||
/ -> React SPA (static/index.html)
|
||||
/assets/<p> -> SPA bundles
|
||||
/api/* -> JSON/SVG API
|
||||
|
||||
Two-phase pipeline:
|
||||
* Enrollment / settings change enqueues a prefetch job and kicks it off
|
||||
in a background thread so the fetcher starts pulling GitHub data the
|
||||
instant the user submits a username. The thread only hydrates
|
||||
widget_data for the client-side Workshop preview — it does not render
|
||||
SVGs.
|
||||
* POST /api/<u>/generate synchronously renders and persists the composite
|
||||
SVG. This is what the user's "Generate" button calls.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
@@ -16,21 +25,19 @@ from . import config, db, fetcher_client, placeholder
|
||||
log = logging.getLogger("generator.api")
|
||||
|
||||
|
||||
def _kickoff_build():
|
||||
"""Run one build cycle in a background thread. Eliminates the worker's
|
||||
poll latency for users who just enrolled or patched settings. The worker
|
||||
container still drains the queue; this just gives interactive requests
|
||||
a head start so the build runs concurrently with the user filling out
|
||||
the workshop page."""
|
||||
def _kickoff_prefetch():
|
||||
"""Run one prefetch cycle in a background thread. Starts the fetcher
|
||||
immediately on enrollment / settings-change so the raw GitHub payload
|
||||
is hot by the time the user clicks Generate."""
|
||||
try:
|
||||
from . import worker
|
||||
worker.process_one()
|
||||
except Exception:
|
||||
log.exception("background build kickoff failed")
|
||||
log.exception("background prefetch kickoff failed")
|
||||
|
||||
|
||||
def _kickoff_build_async():
|
||||
Thread(target=_kickoff_build, daemon=True).start()
|
||||
def _kickoff_prefetch_async():
|
||||
Thread(target=_kickoff_prefetch, daemon=True).start()
|
||||
|
||||
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||
|
||||
@@ -94,7 +101,7 @@ def get_user_data(username: str):
|
||||
"widget_order": config.WIDGET_ORDER,
|
||||
}
|
||||
db.enroll(username, defaults)
|
||||
_kickoff_build_async()
|
||||
_kickoff_prefetch_async()
|
||||
return jsonify({"status": "building"}), 202
|
||||
|
||||
db.touch_last_requested(username)
|
||||
@@ -112,29 +119,30 @@ def get_user_data(username: str):
|
||||
|
||||
|
||||
def _serve(username: str, widget_name: str) -> Response:
|
||||
settings_row = db.get_settings(username)
|
||||
"""Serves a cached SVG for README embeds.
|
||||
|
||||
SVGs are only produced by POST /api/<u>/generate. Before that the
|
||||
endpoint returns a "building" placeholder; enrollment is frontend-
|
||||
driven (via /api/<u>/data or /api/enroll) so this path never auto-
|
||||
enrolls on its own.
|
||||
"""
|
||||
settings_row = db.get_settings(username)
|
||||
if settings_row is None:
|
||||
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||
return _placeholder_response("rate_limited", username)
|
||||
defaults = {
|
||||
"theme": "dark",
|
||||
"enabled": config.ENABLED_WIDGETS,
|
||||
"widget_order": config.WIDGET_ORDER,
|
||||
}
|
||||
db.enroll(username, defaults)
|
||||
_kickoff_build_async()
|
||||
return _placeholder_response("building", username)
|
||||
|
||||
db.touch_last_requested(username)
|
||||
svg = db.get_current_widget(username, widget_name)
|
||||
if svg is None:
|
||||
return _placeholder_response("building", username, theme=settings_row["settings"].get("theme", "dark"))
|
||||
current_hash = db.get_current_widget_hash(username)
|
||||
theme = settings_row["settings"].get("theme", "dark")
|
||||
|
||||
if settings_row.get("settings_hash") == "not_found":
|
||||
if current_hash == "not_found":
|
||||
svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme)
|
||||
return Response(svg, mimetype="image/svg+xml",
|
||||
headers={"X-Widget-Status": "not_found", "Cache-Control": "no-store"})
|
||||
|
||||
svg = db.get_current_widget(username, widget_name)
|
||||
if svg is None:
|
||||
return _placeholder_response("building", username, theme=theme)
|
||||
|
||||
return Response(svg, mimetype="image/svg+xml",
|
||||
headers={"X-Widget-Status": "ready",
|
||||
"Cache-Control": "public, max-age=3600"})
|
||||
@@ -158,7 +166,7 @@ def enroll_endpoint():
|
||||
return jsonify({"error": "rate_limited"}), 429
|
||||
defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER}
|
||||
job_id = db.enroll(username, defaults)
|
||||
_kickoff_build_async()
|
||||
_kickoff_prefetch_async()
|
||||
return jsonify({"enrolled": True, "job_id": job_id})
|
||||
|
||||
|
||||
@@ -180,10 +188,36 @@ def patch_settings(username: str):
|
||||
body = request.get_json(silent=True) or {}
|
||||
merged = {**current["settings"], **body}
|
||||
job_id = db.update_settings(username, merged)
|
||||
_kickoff_build_async()
|
||||
_kickoff_prefetch_async()
|
||||
return jsonify({"updated": True, "job_id": job_id})
|
||||
|
||||
|
||||
@app.route("/api/<username>/generate", methods=["POST"])
|
||||
def generate(username: str):
|
||||
"""Render the composite SVG from the cached fetcher payload + current
|
||||
settings, persist it to widgets.db, and return status. Called by the
|
||||
Generate button; safe to call repeatedly (each call re-renders with
|
||||
the latest settings)."""
|
||||
from . import worker
|
||||
if db.get_settings(username) is None:
|
||||
return jsonify({"error": "not_enrolled"}), 404
|
||||
try:
|
||||
widgets = worker.render_widgets_now(username)
|
||||
except LookupError:
|
||||
return jsonify({"error": "not_enrolled"}), 404
|
||||
except Exception as e:
|
||||
log.exception("generate failed for %s", username)
|
||||
return jsonify({"error": f"render_failed: {e}"}), 502
|
||||
current_hash = db.get_current_widget_hash(username)
|
||||
if current_hash == "not_found":
|
||||
return jsonify({"status": "not_found"}), 404
|
||||
return jsonify({
|
||||
"status": "ready",
|
||||
"composite_url": f"/api/{username}",
|
||||
"widgets": list(widgets.keys()),
|
||||
})
|
||||
|
||||
|
||||
@app.route("/api/<username>/refresh", methods=["POST"])
|
||||
@require_auth
|
||||
def refresh(username: str):
|
||||
@@ -197,7 +231,7 @@ def refresh(username: str):
|
||||
except Exception as e:
|
||||
return jsonify({"error": f"fetch failed: {e}"}), 502
|
||||
job_id = db.enqueue_build(username)
|
||||
_kickoff_build_async()
|
||||
_kickoff_prefetch_async()
|
||||
return jsonify({"refreshed": True, "job_id": job_id})
|
||||
|
||||
|
||||
|
||||
@@ -290,6 +290,33 @@ def put_widgets(username: str, hash_: str, widgets: dict[str, str]) -> None:
|
||||
c.commit()
|
||||
|
||||
|
||||
def get_current_widget_hash(username: str) -> Optional[str]:
|
||||
"""The settings_hash that current_widget points at (or None if nothing
|
||||
has been prefetched/rendered yet). Distinct from users.settings_hash,
|
||||
which is the hash of the *currently configured* settings."""
|
||||
with _widgets_conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT settings_hash FROM current_widget WHERE username=?",
|
||||
(username,),
|
||||
).fetchone()
|
||||
return row["settings_hash"] if row else None
|
||||
|
||||
|
||||
def point_current_widget(username: str, hash_: str) -> None:
|
||||
"""Flip the current_widget pointer to a settings_hash. Used by the
|
||||
prefetch worker (which writes only widget_data, not SVG rows) and by
|
||||
the render path (which writes both, but calls this too for clarity)."""
|
||||
now = _now()
|
||||
with _widgets_conn() as c:
|
||||
c.execute(
|
||||
"""INSERT INTO current_widget(username, settings_hash, updated_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash, updated_at=excluded.updated_at""",
|
||||
(username, hash_, now),
|
||||
)
|
||||
c.commit()
|
||||
|
||||
|
||||
def get_current_widget(username: str, widget_name: str) -> Optional[str]:
|
||||
with _widgets_conn() as c:
|
||||
row = c.execute(
|
||||
|
||||
+46
-12
@@ -1,4 +1,15 @@
|
||||
"""Build worker. Pulls pending jobs and renders widgets.
|
||||
"""Prefetch worker. Pulls pending jobs and populates widget data.
|
||||
|
||||
Two-phase pipeline:
|
||||
* Phase 1 (this module): on enroll/settings-change, fetch the raw GitHub
|
||||
payload from the fetcher and compute widget data for the client-side
|
||||
Workshop preview. No SVG rendering.
|
||||
* Phase 2 (render_widgets_now, called from the API's Generate endpoint):
|
||||
synchronously render composite SVG from the cached raw + current
|
||||
settings and persist to widgets.db.
|
||||
|
||||
This split keeps the fetcher hot while the user edits settings and defers
|
||||
expensive SVG composition until the user clicks Generate.
|
||||
|
||||
Run as its own container: CMD python -m src.worker
|
||||
"""
|
||||
@@ -14,8 +25,7 @@ MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
def _compute_widget_data(payload: dict, settings: dict) -> dict:
|
||||
"""Compute raw widget data dict for client-side rendering. Written
|
||||
alongside SVGs so the /api/<u>/data endpoint is a precomputed lookup."""
|
||||
"""Compute raw widget data dict for client-side rendering."""
|
||||
custom_tags = settings.get("custom_tags")
|
||||
hidden_languages = settings.get("hidden_languages")
|
||||
return {
|
||||
@@ -50,6 +60,7 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
|
||||
|
||||
|
||||
def process_one() -> bool:
|
||||
"""Phase 1: claim a pending job and populate widget data (no SVG)."""
|
||||
job = db.claim_next_job()
|
||||
if job is None:
|
||||
return False
|
||||
@@ -58,10 +69,8 @@ def process_one() -> bool:
|
||||
result = fetcher_client.get_data(username)
|
||||
payload = result.get("data") or {}
|
||||
if payload.get("error") == "not_found":
|
||||
svg = placeholder.render("not_found", username, theme="dark")
|
||||
db.put_widgets(username, "not_found", {"composite": svg})
|
||||
db.put_widget_data(username, "not_found", {"not_found": True})
|
||||
cache.Cache().delete(f"widget:composite:{username}")
|
||||
db.point_current_widget(username, "not_found")
|
||||
db.complete_job(job["id"])
|
||||
log.info("not_found marker persisted for %s", username)
|
||||
return True
|
||||
@@ -71,24 +80,49 @@ def process_one() -> bool:
|
||||
db.fail_job(job["id"], "settings missing", retry=False)
|
||||
return True
|
||||
|
||||
widgets = _render_widgets(username, payload, settings_row["settings"])
|
||||
widget_data = _compute_widget_data(payload, settings_row["settings"])
|
||||
db.put_widgets(username, settings_row["settings_hash"], widgets)
|
||||
db.put_widget_data(username, settings_row["settings_hash"], widget_data)
|
||||
db.point_current_widget(username, settings_row["settings_hash"])
|
||||
db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
|
||||
db.lru_trim(username, config.WIDGET_LRU_PER_USER)
|
||||
c = cache.Cache()
|
||||
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
|
||||
db.complete_job(job["id"])
|
||||
log.info("built widgets for %s", username)
|
||||
log.info("prefetched data for %s", username)
|
||||
return True
|
||||
except Exception as e:
|
||||
retry = job["attempts"] < MAX_ATTEMPTS
|
||||
db.fail_job(job["id"], str(e)[:500], retry=retry)
|
||||
log.warning("build failed for %s (retry=%s): %s", username, retry, e)
|
||||
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
|
||||
return True
|
||||
|
||||
|
||||
def render_widgets_now(username: str) -> dict[str, str]:
|
||||
"""Phase 2: synchronously render composite SVG and persist it.
|
||||
|
||||
Called from POST /api/<u>/generate. Reuses the fetcher's cached payload
|
||||
(a cheap internal HTTP lookup) so the user-facing render is fast even
|
||||
if the prefetch job hasn't drained from the queue yet.
|
||||
"""
|
||||
settings_row = db.get_settings(username)
|
||||
if settings_row is None:
|
||||
raise LookupError("not_enrolled")
|
||||
result = fetcher_client.get_data(username)
|
||||
payload = result.get("data") or {}
|
||||
if payload.get("error") == "not_found":
|
||||
svg = placeholder.render("not_found", username, theme=settings_row["settings"].get("theme", "dark"))
|
||||
db.put_widgets(username, "not_found", {"composite": svg})
|
||||
db.point_current_widget(username, "not_found")
|
||||
cache.Cache().delete(f"widget:composite:{username}")
|
||||
return {"composite": svg}
|
||||
|
||||
widgets = _render_widgets(username, payload, settings_row["settings"])
|
||||
db.put_widgets(username, settings_row["settings_hash"], widgets)
|
||||
db.point_current_widget(username, settings_row["settings_hash"])
|
||||
c = cache.Cache()
|
||||
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
|
||||
log.info("rendered widgets on-demand for %s", username)
|
||||
return widgets
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
db.init_dbs()
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user