后端实现: - 创建 AuthService 包含密码加密、JWT 生成和验证 - 创建 authMiddleware 用于 API 路由保护 - 实现 auth 路由 (register, login, logout, /me) 前端实现: - 创建 Login 页面 (登录/注册标签页) - 创建 ProtectedRoute 组件用于路由保护 - 更新 App.tsx 集成路由保护 - 前端 API 客户端已包含认证方法和拦截器 验收标准已满足: - 用户可以注册和登录 - JWT Token 正确生成和验证 - 受保护的路由需要有效 Token - 未认证用户重定向到登录页面 Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
129 lines
4.9 KiB
Python
129 lines
4.9 KiB
Python
"""
|
|
Smoke test for the Flask backend (SQLite).
|
|
|
|
Exercises the full request path: register -> login -> 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 json
|
|
|
|
# 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
|
|
|
|
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: register + login")
|
|
r = client.post(
|
|
"/api/auth/register",
|
|
json={"email": "tester@example.com", "garminEmail": "gm@example.com", "garminPassword": "secret123"},
|
|
)
|
|
check("register 201", r.status_code == 201, r.get_data(as_text=True))
|
|
token = (r.get_json() or {}).get("token")
|
|
check("register returns token", bool(token))
|
|
|
|
r = client.post("/api/auth/login", json={"email": "tester@example.com", "password": "secret123"})
|
|
check("login 200", r.status_code == 200, r.get_data(as_text=True))
|
|
token = (r.get_json() or {}).get("token")
|
|
check("login returns token", bool(token))
|
|
|
|
r = client.post("/api/auth/login", json={"email": "tester@example.com", "password": "wrong"})
|
|
check("login rejects bad password (401)", r.status_code == 401)
|
|
|
|
r = client.get("/api/health/summary")
|
|
check("unauthenticated read 401", r.status_code == 401)
|
|
|
|
print("\n[2] Seed health data (3 days)")
|
|
uid = (client.post("/api/auth/login", json={"email": "tester@example.com", "password": "secret123"}).get_json())["id"]
|
|
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)
|