Files
GarminHealthLab/backend/tests/test_scheduler.py
ericwyuan 9503fca370 feat(auth): 接入 auth-hub 统一登录,网页登录与 Garmin 同步彻底分离
网页身份改由 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>
2026-08-31 23:12:17 +08:00

187 lines
6.5 KiB
Python

"""
Unit tests for the auto-sync scheduler.
The interesting behaviour is the claim: gunicorn runs several workers, each of
which starts its own timer, so without coordination one hourly tick would fire
a sync per worker.
"""
import datetime
import pytest
from services import scheduler
@pytest.fixture(autouse=True)
def _clean(db):
db.execute("DELETE FROM job_locks")
def set_last_run(db, when):
db.execute(
"UPDATE job_locks SET last_run_at = ? WHERE name = ?",
[when.isoformat(timespec="seconds"), scheduler.JOB_NAME],
)
class TestClaim:
def test_first_caller_gets_the_job(self, db):
assert scheduler.claim() is True
def test_second_caller_is_turned_away_while_the_first_holds_it(self, db, monkeypatch):
monkeypatch.setattr(scheduler.os, "getpid", lambda: 111)
assert scheduler.claim() is True
# A different worker, same instant.
monkeypatch.setattr(scheduler.os, "getpid", lambda: 222)
assert scheduler.claim() is False, "two workers must not run the same tick"
def test_not_due_again_within_the_interval(self, db):
scheduler.claim()
scheduler.release()
assert scheduler.claim() is False
def test_due_again_after_the_interval(self, db):
scheduler.claim()
scheduler.release()
set_last_run(db, datetime.datetime.utcnow() - datetime.timedelta(seconds=7200))
assert scheduler.claim() is True
def test_abandoned_claim_expires(self, db, monkeypatch):
"""A worker that dies mid-run must not block the job forever."""
monkeypatch.setattr(scheduler.os, "getpid", lambda: 111)
scheduler.claim()
stale = datetime.datetime.utcnow() - datetime.timedelta(
seconds=scheduler.CLAIM_TIMEOUT_SECONDS + 60
)
db.execute(
"UPDATE job_locks SET claimed_at = ? WHERE name = ?",
[stale.isoformat(timespec="seconds"), scheduler.JOB_NAME],
)
monkeypatch.setattr(scheduler.os, "getpid", lambda: 222)
assert scheduler.claim() is True
def test_release_without_running_leaves_it_due(self, db):
scheduler.claim()
scheduler.release(ran=False)
assert scheduler.claim() is True
def test_release_after_running_records_the_time(self, db):
scheduler.claim()
scheduler.release()
assert scheduler.status()["lastRunAt"] is not None
class TestSyncAllAccounts:
def test_no_accounts_is_a_no_op(self, db, user):
assert scheduler.sync_all_accounts() == []
def test_syncs_every_account_holding_a_token(self, db, user, monkeypatch, make_user):
from services import garmin as garmin_svc
other = make_user("b@example.com")
garmin_svc.save_token(user["id"], "t1", "a@example.com")
garmin_svc.save_token(other["id"], "t2", "b@example.com")
seen = []
monkeypatch.setattr(
garmin_svc, "sync_data",
lambda uid, creds, days=None, client=None: seen.append(uid)
or {"status": "success", "recordsSynced": days},
)
results = scheduler.sync_all_accounts(days=2)
assert set(seen) == {user["id"], other["id"]}
assert all(r["status"] == "success" for r in results)
def test_one_failing_account_does_not_stop_the_others(
self, db, user, monkeypatch, make_user
):
from services import garmin as garmin_svc
other = make_user("c@example.com")
garmin_svc.save_token(user["id"], "t1")
garmin_svc.save_token(other["id"], "t2")
def flaky(uid, creds, days=None, client=None):
if uid == user["id"]:
raise RuntimeError("token expired")
return {"status": "success", "recordsSynced": 2}
monkeypatch.setattr(garmin_svc, "sync_data", flaky)
results = scheduler.sync_all_accounts()
assert len(results) == 2
assert {r["status"] for r in results} == {"error", "success"}
def test_accounts_without_a_token_are_skipped(self, db, user, monkeypatch):
from services import garmin as garmin_svc
called = []
monkeypatch.setattr(
garmin_svc, "sync_data",
lambda *a, **k: called.append(1) or {"status": "success"},
)
scheduler.sync_all_accounts()
assert called == [], "an account with no token cannot be synced"
class TestStatus:
def test_reports_configuration(self, db):
s = scheduler.status()
assert s["intervalSeconds"] == scheduler.INTERVAL_SECONDS
assert s["days"] == scheduler.SYNC_DAYS
def test_next_run_follows_the_last(self, db):
scheduler.claim()
scheduler.release()
s = scheduler.status()
assert s["lastRunAt"] and s["nextRunAt"]
assert s["nextRunAt"] > s["lastRunAt"]
def test_no_run_yet(self, db):
s = scheduler.status()
assert s["lastRunAt"] is None
assert s["nextRunAt"] is None
class TestEndpoints:
def test_sync_latest_requires_auth(self, client):
assert client.post("/api/garmin/sync-latest", json={}).status_code == 401
def test_sync_latest_needs_a_bound_account(self, client, auth):
r = client.post("/api/garmin/sync-latest", headers=auth, json={})
assert r.status_code == 400
assert "绑定" in r.get_json()["error"]
def test_sync_latest_runs_inline(self, client, auth, user, db, monkeypatch):
from services import garmin as garmin_svc
garmin_svc.save_token(user["id"], "blob")
monkeypatch.setattr(
garmin_svc, "sync_data",
lambda uid, creds, days=None, client=None: {
"status": "success", "recordsSynced": days, "message": "ok",
},
)
r = client.post("/api/garmin/sync-latest", headers=auth, json={"days": 3})
assert r.status_code == 200
assert r.get_json()["recordsSynced"] == 3
def test_sync_latest_window_is_clamped(self, client, auth, user, db, monkeypatch):
from services import garmin as garmin_svc
garmin_svc.save_token(user["id"], "blob")
monkeypatch.setattr(
garmin_svc, "sync_data",
lambda uid, creds, days=None, client=None: {
"status": "success", "recordsSynced": days,
},
)
r = client.post("/api/garmin/sync-latest", headers=auth, json={"days": 999})
assert r.get_json()["recordsSynced"] == 7
def test_auto_sync_status_endpoint(self, client, auth):
r = client.get("/api/garmin/auto-sync", headers=auth)
assert r.status_code == 200
assert "intervalSeconds" in r.get_json()