网页身份改由 auth-hub 做 OAuth2 + PKCE 单点登录,本地邮箱/密码登录与注册整条链路删除 (routes/auth.py、auth.py 的密码哈希、config.py 的 ALLOW_REGISTRATION)。Garmin 账号绑定/ 同步保持完全独立、可选:routes/garmin.py 不再直接查 users 表,Garmin 邮箱回退统一走新增 的 services/garmin.py::get_remembered_email()(优先读 garmin_tokens 当前绑定,兼容早期账号 落在 users.garmin_email 的历史值),彻底把「你是谁」和「你绑没绑 Garmin」两件事拆开。 - db.py: users 表新增 auth_hub_sub/auth_hub_username,MIGRATIONS 补上这两列(此前遗漏导致 已存在的生产 MariaDB 表永远不会自动加列);同时把历史遗留的 garmin_email/ garmin_password_hash NOT NULL 约束在线迁移为可空,因为新账号不再在注册时收集这些字段。 - routes/auth.py: 修掉 /callback 路由重复拼接 /api/auth 前缀导致 404 的 bug。 - client: LoginPage 去掉本地登录/注册标签页,只保留 auth-hub 统一登录;登录成功/失败后都 用 history.replaceState 清理地址栏,修掉 Framework7 browserHistory 读取 /auth/callback?code=... 导致「找不到页面」的问题。 - 新增 test_auth_hub_client.py 锁定 find_or_create_user 按 auth_hub_sub 幂等——生产上曾经因为 这个函数在没有该测试保护时被测试触发,误建过一个空账号,靠手工核对 health_data 计数才发现。 - 生产 auth-hub 侧另行为该项目注册了正式 client(未随本次提交变更,凭证只存在服务器 .env)。 Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
122 lines
4.4 KiB
Python
122 lines
4.4 KiB
Python
"""
|
|
Smoke test for the Flask backend (SQLite).
|
|
|
|
Exercises the full request path: a user account (as if signed in through
|
|
auth-hub) -> authenticated reads for health summary/steps/heart-rate/sleep/
|
|
activities, analysis trends + recommendations, and Garmin sync status.
|
|
Run: `python tests/smoke.py`.
|
|
"""
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import uuid
|
|
|
|
# Configure the backend BEFORE importing app/config.
|
|
_TMP_DB = os.path.join(tempfile.mkdtemp(), "smoke.db")
|
|
os.environ["DB_TYPE"] = "sqlite"
|
|
os.environ["DATABASE_PATH"] = _TMP_DB
|
|
os.environ["JWT_SECRET"] = "smoke_test_secret"
|
|
os.environ["CORS_ORIGIN"] = "http://localhost:3000"
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
from app import create_app # noqa: E402
|
|
from db import execute # noqa: E402
|
|
from auth import sign_token # noqa: E402
|
|
|
|
app = create_app()
|
|
client = app.test_client()
|
|
PASS = 0
|
|
FAIL = 0
|
|
|
|
|
|
def check(name, cond, detail=""):
|
|
global PASS, FAIL
|
|
if cond:
|
|
PASS += 1
|
|
print(f" PASS {name}")
|
|
else:
|
|
FAIL += 1
|
|
print(f" FAIL {name} {detail}")
|
|
|
|
|
|
def auth_headers(token):
|
|
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
|
|
|
|
|
print("\n[1] Auth: user account (as if signed in through auth-hub)")
|
|
uid = str(uuid.uuid4())
|
|
token = sign_token(uid)
|
|
execute(
|
|
"INSERT INTO users (id, email, auth_hub_username, jwt_token) VALUES (?, ?, ?, ?)",
|
|
[uid, "tester@example.com", "tester@example.com", token],
|
|
)
|
|
check("user created", bool(uid))
|
|
|
|
r = client.get("/api/health/summary")
|
|
check("unauthenticated read 401", r.status_code == 401)
|
|
|
|
print("\n[2] Seed health data (3 days)")
|
|
for i, (steps, hr, sleep, stress) in enumerate([(6500, 70, 6.2, 55), (9000, 62, 7.5, 40), (7500, 68, 6.8, 48)]):
|
|
date = f"2026-08-{20 + i}"
|
|
execute(
|
|
"INSERT INTO health_data (id, user_id, date, steps, heart_rate, "
|
|
"heart_rate_variability, sleep_duration, sleep_quality, stress, calories_burned) "
|
|
"VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
[f"{uid}-{date}", uid, date, steps, hr, 45 + i, sleep, 80 - i, stress, steps * 0.04],
|
|
)
|
|
execute(
|
|
"INSERT INTO activities (id, user_id, activity_type, start_time, end_time, duration, distance, calories, heart_rate_average, heart_rate_max) "
|
|
"VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
["act-1", uid, "running", "2026-08-20T07:00:00", "2026-08-20T07:30:00", 1800, 5.0, 320, 140, 165],
|
|
)
|
|
|
|
print("\n[3] Authenticated health reads")
|
|
h = auth_headers(token)
|
|
r = client.get("/api/health/summary", headers=h)
|
|
check("summary 200", r.status_code == 200, r.get_data(as_text=True))
|
|
body = r.get_json()
|
|
check("summary 3 days", len(body) == 3, f"got {len(body)}")
|
|
check("summary camelCase sleep", "sleep" in body[0] and isinstance(body[0]["sleep"], dict))
|
|
|
|
r = client.get("/api/health/steps", headers=h)
|
|
check("steps 200 + non-null", r.status_code == 200 and len(r.get_json()) == 3)
|
|
|
|
r = client.get("/api/health/heart-rate", headers=h)
|
|
check("heart-rate 200", r.status_code == 200 and len(r.get_json()) == 3)
|
|
|
|
r = client.get("/api/health/sleep", headers=h)
|
|
check("sleep 200", r.status_code == 200 and len(r.get_json()) == 3)
|
|
|
|
r = client.get("/api/health/activities", headers=h)
|
|
check("activities 200", r.status_code == 200 and len(r.get_json()) == 1)
|
|
|
|
print("\n[4] Analysis")
|
|
r = client.get("/api/analysis/trends?metricType=steps", headers=h)
|
|
check("trends 200", r.status_code == 200, r.get_data(as_text=True))
|
|
check("trends values", len(r.get_json()) == 3)
|
|
|
|
r = client.get("/api/analysis/recommendations", headers=h)
|
|
check("recommendations 200", r.status_code == 200)
|
|
recs = r.get_json()
|
|
check("recommendations non-empty", len(recs) > 0)
|
|
check("recommendations sorted by priority", [x["priority"] for x in recs] == sorted([x["priority"] for x in recs], key=lambda p: {"high": 0, "medium": 1, "low": 2}[p]))
|
|
|
|
print("\n[5] Garmin status + sync (no creds -> clear 400)")
|
|
r = client.get("/api/garmin/status", headers=h)
|
|
check("garmin status 200", r.status_code == 200, r.get_data(as_text=True))
|
|
check("garmin status idle", (r.get_json() or {}).get("status") == "idle")
|
|
|
|
r = client.post("/api/garmin/sync", headers=h, json={})
|
|
check("sync without creds 400", r.status_code == 400, r.get_data(as_text=True))
|
|
|
|
print("\n[6] Health check + logout")
|
|
r = client.get("/api/health/status")
|
|
check("health/status 200", r.status_code == 200 and (r.get_json() or {}).get("status") == "ok")
|
|
|
|
r = client.post("/api/auth/logout", headers=h)
|
|
check("logout 200", r.status_code == 200)
|
|
|
|
print(f"\nRESULT: {PASS} passed, {FAIL} failed")
|
|
sys.exit(1 if FAIL else 0)
|