Files
github-readme-stats/generator/tests/test_api.py
T

269 lines
11 KiB
Python

import os, tempfile, pytest
from unittest.mock import patch
from src import db as dbmod
from src import api as apimod
from src import config as cfg
@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 *_a, **_kw: 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"))
dbmod.init_dbs()
# Configure OAuth fixture with allowed origins and insecure cookies for testing.
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
app = apimod.app
app.config["TESTING"] = True
app.config["SESSION_COOKIE_SECURE"] = False
with app.test_client() as c:
yield c
# Clear rate limit state after each test to prevent pollution.
apimod._rate_hits.clear()
apimod._rate_hits_per_login.clear()
def test_health(client):
r = client.get("/api/health")
assert r.status_code == 200
assert r.get_json()["service"] == "generator"
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 None
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>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
assert b"ready" in r.data
def test_settings_patch_enqueues_rebuild(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch(
"/api/alice/settings",
json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"},
)
assert r.status_code == 200
assert dbmod.get_settings("alice")["settings"]["theme"] == "light"
def test_settings_patch_without_origin_is_unauthorized(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"})
assert r.status_code == 403
# Settings must not be mutated when the origin check fails.
assert dbmod.get_settings("alice")["settings"]["theme"] == "dark"
def test_patch_settings_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_patch_settings_wrong_login_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 403
def test_patch_settings_matching_login_succeeds(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 200
def test_patch_settings_bad_origin_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://evil.example"})
assert r.status_code == 403
def test_refresh_is_one_shot(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}):
r1 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r1.status_code == 200
r2 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r2.status_code == 409
def test_refresh_without_token_is_unauthorized(client):
"""Old test name; now tests without session but with proper Origin."""
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_not_found_status_header(client):
dbmod.enroll("ghost", {"theme": "dark"})
dbmod.put_widgets("ghost", "not_found", {"composite": "<svg>404</svg>"})
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 client.session_transaction() as s:
s["gh_login"] = "alice"
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", headers={"Origin": "https://gh-stats.com"})
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):
"""With OAuth, unenrolled means having a session but no profile."""
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.post("/api/bob/generate", headers={"Origin": "https://gh-stats.com"})
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.
def test_data_endpoint_enrolled_but_unbuilt_returns_building(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice/data")
assert r.status_code == 202
assert r.get_json() == {"status": "building"}
def test_data_endpoint_returns_ready_after_build(client):
dbmod.enroll("alice", {"theme": "dark"})
sample = {"grade": {"grade": "A", "score": 80, "stats": {}, "tags": [], "breakdown": {}}}
dbmod.put_widget_data("alice", "h1", sample)
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('alice', 'h1', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/alice/data")
assert r.status_code == 200
body = r.get_json()
assert body["status"] == "ready"
assert body["data"] == sample
def test_data_endpoint_returns_not_found_for_unknown_github_user(client):
dbmod.enroll("ghost", {"theme": "dark"})
dbmod.put_widget_data("ghost", "not_found", {"not_found": True})
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('ghost', 'not_found', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/ghost/data")
assert r.status_code == 404
assert r.get_json()["status"] == "not_found"
def test_generate_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_generate_wrong_login_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 403
def test_refresh_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_data_unknown_user_returns_404(client):
r = client.get("/api/testuser/data")
assert r.status_code == 404
def test_enroll_endpoint_is_gone(client):
r = client.post("/api/enroll", json={"username": "alice"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 405
def test_per_login_mutate_rate_limit(client, monkeypatch):
"""Per-login rate limit on mutate routes allows up to MAX requests,
then rejects with 429."""
monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_MAX", 2)
monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", 60)
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
h = {"Origin": "https://gh-stats.com"}
# First two requests should succeed.
r1 = client.patch("/api/alice/settings", json={}, headers=h)
assert r1.status_code == 200
r2 = client.patch("/api/alice/settings", json={}, headers=h)
assert r2.status_code == 200
# Third request should be rate-limited.
r3 = client.patch("/api/alice/settings", json={}, headers=h)
assert r3.status_code == 429