mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(admin dashboard): add admin dashboard
This commit is contained in:
@@ -15,6 +15,7 @@ def client(monkeypatch):
|
||||
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"))
|
||||
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
|
||||
dbmod.init_dbs()
|
||||
# Configure OAuth fixture with allowed origins and insecure cookies for testing.
|
||||
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
|
||||
@@ -536,3 +537,90 @@ def test_per_login_mutate_rate_limit(client, monkeypatch):
|
||||
# Third request should be rate-limited.
|
||||
r3 = client.patch("/api/alice/settings", json={}, headers=h)
|
||||
assert r3.status_code == 429
|
||||
|
||||
|
||||
def test_internal_analytics_events_requires_token(client, monkeypatch):
|
||||
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
|
||||
r = client.post("/internal/analytics/events", json={"events": []})
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_internal_analytics_events_ingests(client, monkeypatch):
|
||||
from src import analytics
|
||||
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
|
||||
analytics._reset_for_tests()
|
||||
body = {
|
||||
"events": [
|
||||
{"ts": 1700000000, "service": "edge", "kind": "request",
|
||||
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||
"status": 200, "latency_ms": 12, "cache_hit": 1}
|
||||
]
|
||||
}
|
||||
r = client.post("/internal/analytics/events",
|
||||
headers={"X-Internal-Token": "secret"},
|
||||
json=body)
|
||||
assert r.status_code == 200
|
||||
assert r.get_json()["ingested"] == 1
|
||||
|
||||
|
||||
def _basic(user="admin", pw="pw"):
|
||||
import base64
|
||||
return {"Authorization": "Basic " + base64.b64encode(f"{user}:{pw}".encode()).decode()}
|
||||
|
||||
|
||||
def test_dev_summary_requires_auth(client, monkeypatch):
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||
r = client.get("/api/dev/summary")
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_dev_summary_returns_shape(client, monkeypatch):
|
||||
from src import analytics
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||
analytics._reset_for_tests()
|
||||
import time as _time
|
||||
analytics.ingest_batch([
|
||||
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
|
||||
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||
"status": 200, "latency_ms": 11, "cache_hit": 1},
|
||||
])
|
||||
r = client.get("/api/dev/summary", headers=_basic())
|
||||
assert r.status_code == 200
|
||||
body = r.get_json()
|
||||
for key in ("requests_7d", "active_users_7d", "p50_ms", "p95_ms",
|
||||
"renders_7d", "avg_render_ms", "daily_requests"):
|
||||
assert key in body
|
||||
assert len(body["daily_requests"]) == 7
|
||||
|
||||
|
||||
def test_dev_users_endpoint(client, monkeypatch):
|
||||
from src import analytics
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||
analytics._reset_for_tests()
|
||||
import time as _time
|
||||
analytics.ingest_batch([
|
||||
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
|
||||
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||
"status": 200, "latency_ms": 11, "cache_hit": 1},
|
||||
])
|
||||
r = client.get("/api/dev/users", headers=_basic())
|
||||
assert r.status_code == 200
|
||||
rows = r.get_json()
|
||||
assert any(u["username"] == "alice" for u in rows)
|
||||
|
||||
|
||||
def test_dev_latency_and_health(client, monkeypatch):
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||
r = client.get("/api/dev/latency", headers=_basic())
|
||||
assert r.status_code == 200
|
||||
assert isinstance(r.get_json(), list)
|
||||
r2 = client.get("/api/dev/health", headers=_basic())
|
||||
assert r2.status_code == 200
|
||||
body = r2.get_json()
|
||||
for key in ("edge_cache_hit_rate", "fetcher_error_rate",
|
||||
"events_dropped_24h"):
|
||||
assert key in body
|
||||
|
||||
@@ -181,3 +181,67 @@ def test_callback_happy_path_sets_session(api_client, monkeypatch):
|
||||
assert s["gh_avatar_url"] == "https://x/a.png"
|
||||
# Row should now exist with github profile populated.
|
||||
assert dbmod.get_settings("alice") is not None
|
||||
|
||||
|
||||
def test_require_basic_auth_503_when_unset(monkeypatch):
|
||||
from flask import Flask, jsonify
|
||||
from src import auth as authmod
|
||||
from src import config as cfg
|
||||
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "")
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "")
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route("/x")
|
||||
@authmod.require_basic_auth
|
||||
def x():
|
||||
return jsonify({"ok": True})
|
||||
|
||||
with app.test_client() as c:
|
||||
r = c.get("/x")
|
||||
assert r.status_code == 503
|
||||
|
||||
|
||||
def test_require_basic_auth_401_on_bad(monkeypatch):
|
||||
import base64
|
||||
from flask import Flask, jsonify
|
||||
from src import auth as authmod
|
||||
from src import config as cfg
|
||||
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route("/x")
|
||||
@authmod.require_basic_auth
|
||||
def x():
|
||||
return jsonify({"ok": True})
|
||||
|
||||
with app.test_client() as c:
|
||||
r = c.get("/x")
|
||||
assert r.status_code == 401
|
||||
assert r.headers.get("WWW-Authenticate", "").startswith("Basic")
|
||||
bad = base64.b64encode(b"admin:wrong").decode()
|
||||
r2 = c.get("/x", headers={"Authorization": f"Basic {bad}"})
|
||||
assert r2.status_code == 401
|
||||
|
||||
|
||||
def test_require_basic_auth_200_on_good(monkeypatch):
|
||||
import base64
|
||||
from flask import Flask, jsonify
|
||||
from src import auth as authmod
|
||||
from src import config as cfg
|
||||
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route("/x")
|
||||
@authmod.require_basic_auth
|
||||
def x():
|
||||
return jsonify({"ok": True})
|
||||
|
||||
with app.test_client() as c:
|
||||
good = base64.b64encode(b"admin:pw").decode()
|
||||
r = c.get("/x", headers={"Authorization": f"Basic {good}"})
|
||||
assert r.status_code == 200
|
||||
|
||||
@@ -35,3 +35,24 @@ def test_tick_skips_when_hash_unchanged(tmp_dbs):
|
||||
return_value={"data": {}, "payload_hash": "same"}):
|
||||
stats = cronmod.tick()
|
||||
assert stats["enqueued"] == 0
|
||||
|
||||
|
||||
def test_cron_tick_prunes_old_analytics(tmp_path, monkeypatch):
|
||||
import os, time
|
||||
from src import db as dbmod, analytics, cron
|
||||
|
||||
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(tmp_path, "s.db"))
|
||||
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(tmp_path, "w.db"))
|
||||
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(tmp_path, "a.db"))
|
||||
dbmod.init_dbs()
|
||||
analytics.ingest_batch([
|
||||
{"ts": int(time.time()) - 30 * 86400, "service": "edge", "kind": "request",
|
||||
"username": "u", "endpoint": "/<u>", "widget": "composite",
|
||||
"status": 200, "latency_ms": 1, "cache_hit": 1},
|
||||
])
|
||||
# tick() iterates enrolled users but there are none, so it returns
|
||||
# immediately — we only care that the prune call ran.
|
||||
cron.tick()
|
||||
with dbmod.analytics_conn() as c:
|
||||
n = c.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
|
||||
assert n == 0
|
||||
|
||||
@@ -9,6 +9,7 @@ def tmp_dbs(monkeypatch):
|
||||
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"))
|
||||
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
|
||||
dbmod.init_dbs()
|
||||
yield d
|
||||
|
||||
@@ -172,3 +173,15 @@ def test_put_user_streak_upserts(tmp_dbs):
|
||||
assert row["current_streak"] == 2
|
||||
assert row["max_streak"] == 5
|
||||
assert row["max_start"] == "2024-01-01"
|
||||
|
||||
|
||||
def test_init_dbs_creates_analytics_schema(tmp_path, monkeypatch):
|
||||
from src import db as dbmod
|
||||
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
|
||||
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
|
||||
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", str(tmp_path / "a.db"))
|
||||
dbmod.init_dbs()
|
||||
with dbmod.analytics_conn() as c:
|
||||
cols = {r["name"] for r in c.execute("PRAGMA table_info(events)").fetchall()}
|
||||
assert cols == {"id", "ts", "service", "kind", "username",
|
||||
"endpoint", "widget", "status", "latency_ms", "cache_hit"}
|
||||
|
||||
@@ -178,3 +178,27 @@ def test_process_one_merges_stored_max(tmp_dbs):
|
||||
assert row["max_streak"] == 50
|
||||
assert row["max_start"] == "2023-01-01"
|
||||
assert row["current_streak"] == 2
|
||||
|
||||
|
||||
def test_process_one_records_render_event(monkeypatch, tmp_path):
|
||||
import os
|
||||
from src import db as dbmod, worker, analytics, fetcher_client
|
||||
|
||||
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(tmp_path, "s.db"))
|
||||
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(tmp_path, "w.db"))
|
||||
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(tmp_path, "a.db"))
|
||||
dbmod.init_dbs()
|
||||
analytics._reset_for_tests()
|
||||
|
||||
dbmod.enroll("alice", {"theme": "dark",
|
||||
"enabled": ["grade"], "widget_order": ["grade"]})
|
||||
monkeypatch.setattr(fetcher_client, "get_data",
|
||||
lambda u: {"data": {"user": {"login": "alice"}, "repos": [], "events": []},
|
||||
"payload_hash": "h"})
|
||||
monkeypatch.setattr(worker, "_render_widgets",
|
||||
lambda *a, **kw: {"composite": "<svg/>", "grade": "<svg/>"})
|
||||
assert worker.process_one() is True
|
||||
analytics.ingest_batch(analytics._drain_queue())
|
||||
with dbmod.analytics_conn() as c:
|
||||
rows = c.execute("SELECT username, widget, kind FROM events").fetchall()
|
||||
assert ("alice", "composite", "render") in [(r["username"], r["widget"], r["kind"]) for r in rows]
|
||||
|
||||
Reference in New Issue
Block a user