c9e266b89a
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (pull_request) Successful in 23s
ci-pangolin / Cleartext Scan — Android 禁明文 (pull_request) Successful in 20s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (pull_request) Successful in 20s
ci-pangolin / Lint — shellcheck (pull_request) Successful in 7s
ci-pangolin / OpenAPI Sync Check (pull_request) Successful in 33s
ci-pangolin / Flutter — analyze + test (pull_request) Failing after 16s
ci-pangolin / Codegen Drift — token 生成物未漂移 (pull_request) Successful in 4s
ci-pangolin / DS-flow — 原型/跨端同源/代码色单源闸 (pull_request) Successful in 5s
ci-pangolin / Go — build + test (pull_request) Successful in 8s
ci-pangolin / E2E Smoke — L4 进程级端到端 (pull_request) Successful in 8s
ci-pangolin / Go — integration (mysql/redis testcontainers) (pull_request) Successful in 4m33s
ci-pangolin / Golden — 视觉回归 (全量:components/auth/desktop/tablet) (pull_request) Successful in 19s
DinD 修复后暴露的两个 CI job,诊断: Go integration(真 test-drift bug,早前会话改动遗留): - auth/integration_test:Register/Login 补 ip + DeviceMeta 参数(sessions/ device-meta 改动后陈旧调用,构建失败)。 - usage/usage_integration_test:手写测试 schema 补 ad_bonus_minutes 列 (migration 000020 加的);重写 TestIntAdsUnlockAccumulates 断言对齐 ad-unlock 转累加式(UnlockAd→AddAdBonusMinutes,不再 stamp ad_unlocked_at)。 - devices/devices_integration_test:套餐种子 pro=5→3(migration 000019 改的)。 - devices/context.go(生产 1 行):CtxKeyUserID 别名到 codes.CtxKeyUserID——原为 独立 devices.ctxKey 类型,与 auth 注入的 codes.ctxKey 类型不同→context 取键 失配(休眠 bug,中间件目前仅测试接线)。go build 通过。 E2E(环境问题,非脚本):删 ci.yml 里多余的 apt-get(openssl/curl/python3 已在 golang:1.25 镜像内;原 apt 走 Docker Desktop 代理→本机死口,徒增脆性)。脚本 本身本机直跑通过。 验证:go test -tags integration -count=1 -p 1 ./... 全 ok;go build ./... clean。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
485 lines
16 KiB
Go
485 lines
16 KiB
Go
//go:build integration
|
|
|
|
package devices_test
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
_ "github.com/go-sql-driver/mysql"
|
|
"github.com/testcontainers/testcontainers-go"
|
|
tcmysql "github.com/testcontainers/testcontainers-go/modules/mysql"
|
|
|
|
"github.com/wangjia/pangolin/server/internal/devices"
|
|
)
|
|
|
|
// --------------------------------------------------------------------------
|
|
// Container + schema setup
|
|
// --------------------------------------------------------------------------
|
|
|
|
func setupMySQL(t *testing.T) *sql.DB {
|
|
t.Helper()
|
|
ctx := context.Background()
|
|
|
|
ctr, err := tcmysql.Run(ctx, "mysql:8.0",
|
|
tcmysql.WithDatabase("pangolin_test"),
|
|
tcmysql.WithUsername("root"),
|
|
tcmysql.WithPassword("test"),
|
|
)
|
|
testcontainers.CleanupContainer(t, ctr)
|
|
if err != nil {
|
|
t.Fatalf("mysql container: %v", err)
|
|
}
|
|
|
|
// time_zone 必须百分号编码:作为 URL query 透传时 '+' 会被解码成空格,
|
|
// MySQL 收到 " 00:00" → Error 1298。%27=' %2B=+ %3A=:
|
|
dsn, err := ctr.ConnectionString(ctx, "parseTime=true", "loc=UTC", "time_zone=%27%2B00%3A00%27")
|
|
if err != nil {
|
|
t.Fatalf("mysql dsn: %v", err)
|
|
}
|
|
|
|
db, err := sql.Open("mysql", dsn)
|
|
if err != nil {
|
|
t.Fatalf("open mysql: %v", err)
|
|
}
|
|
t.Cleanup(func() { db.Close() })
|
|
|
|
if err := applySchema(db); err != nil {
|
|
t.Fatalf("schema: %v", err)
|
|
}
|
|
return db
|
|
}
|
|
|
|
func applySchema(db *sql.DB) error {
|
|
stmts := []string{
|
|
`CREATE TABLE IF NOT EXISTS users (
|
|
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
|
uuid CHAR(36) NOT NULL UNIQUE,
|
|
email VARCHAR(255) NOT NULL UNIQUE,
|
|
pw_hash VARCHAR(255) NOT NULL DEFAULT '',
|
|
dp_uuid CHAR(36) NOT NULL,
|
|
status ENUM('active','banned') NOT NULL DEFAULT 'active',
|
|
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
|
|
`CREATE TABLE IF NOT EXISTS devices (
|
|
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
|
uuid CHAR(36) NOT NULL,
|
|
user_id BIGINT UNSIGNED NOT NULL,
|
|
name VARCHAR(64) NOT NULL,
|
|
platform ENUM('ios','android','windows','macos','linux') NOT NULL,
|
|
last_seen DATETIME(6) NULL,
|
|
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
|
client_version VARCHAR(32) NULL,
|
|
totp_trusted_until DATETIME(6) NULL,
|
|
dp_uuid CHAR(36) NULL,
|
|
UNIQUE KEY uniq_devices_user_uuid (user_id, uuid),
|
|
UNIQUE KEY idx_devices_dp_uuid (dp_uuid),
|
|
FOREIGN KEY (user_id) REFERENCES users(id),
|
|
INDEX idx_user (user_id)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
|
|
`CREATE TABLE IF NOT EXISTS plans (
|
|
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
|
code ENUM('free','pro','team') NOT NULL UNIQUE,
|
|
max_devices INT NOT NULL,
|
|
daily_minutes INT NULL,
|
|
ad_gate BOOLEAN NOT NULL DEFAULT FALSE
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
|
|
`CREATE TABLE IF NOT EXISTS subscriptions (
|
|
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
|
user_id BIGINT UNSIGNED NOT NULL,
|
|
plan_id BIGINT UNSIGNED NOT NULL,
|
|
expires_at DATETIME(6) NOT NULL,
|
|
source ENUM('trial','code') NOT NULL,
|
|
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
|
FOREIGN KEY (user_id) REFERENCES users(id),
|
|
FOREIGN KEY (plan_id) REFERENCES plans(id),
|
|
INDEX idx_user_exp (user_id, expires_at)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
|
|
`CREATE TABLE IF NOT EXISTS audit_log (
|
|
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
|
actor VARCHAR(64) NOT NULL,
|
|
action VARCHAR(64) NOT NULL,
|
|
target VARCHAR(128) NOT NULL,
|
|
meta JSON NULL,
|
|
at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
|
INDEX idx_at (at)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
|
|
`INSERT IGNORE INTO plans (code, max_devices, daily_minutes, ad_gate)
|
|
VALUES ('free', 1, 10, TRUE), ('pro', 3, NULL, FALSE), ('team', 10, NULL, FALSE)`,
|
|
}
|
|
for _, stmt := range stmts {
|
|
if _, err := db.Exec(stmt); err != nil {
|
|
return fmt.Errorf("schema exec: %w\nSQL: %s", err, stmt)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// createUser inserts a user (status active) and returns its id.
|
|
func createUser(t *testing.T, db *sql.DB, email, status string) int64 {
|
|
t.Helper()
|
|
res, err := db.Exec(
|
|
`INSERT INTO users (uuid, email, pw_hash, dp_uuid, status)
|
|
VALUES (UUID(), ?, 'x', UUID(), ?)`, email, status)
|
|
if err != nil {
|
|
t.Fatalf("createUser: %v", err)
|
|
}
|
|
id, _ := res.LastInsertId()
|
|
return id
|
|
}
|
|
|
|
// giveSubscription inserts a subscription for the user.
|
|
func giveSubscription(t *testing.T, db *sql.DB, userID int64, plan, source string, expiresAt time.Time) {
|
|
t.Helper()
|
|
var planID int64
|
|
if err := db.QueryRow(`SELECT id FROM plans WHERE code=?`, plan).Scan(&planID); err != nil {
|
|
t.Fatalf("plan lookup: %v", err)
|
|
}
|
|
if _, err := db.Exec(
|
|
`INSERT INTO subscriptions (user_id, plan_id, expires_at, source) VALUES (?,?,?,?)`,
|
|
userID, planID, expiresAt.UTC(), source); err != nil {
|
|
t.Fatalf("giveSubscription: %v", err)
|
|
}
|
|
}
|
|
|
|
func newUUID(t *testing.T, db *sql.DB) string {
|
|
t.Helper()
|
|
var u string
|
|
if err := db.QueryRow(`SELECT UUID()`).Scan(&u); err != nil {
|
|
t.Fatalf("uuid: %v", err)
|
|
}
|
|
return u
|
|
}
|
|
|
|
// --------------------------------------------------------------------------
|
|
// Tests
|
|
// --------------------------------------------------------------------------
|
|
|
|
// TestFullChain exercises register → implicit re-register → list → delete and
|
|
// asserts credential revocation is triggered on delete.
|
|
func TestFullChain(t *testing.T) {
|
|
db := setupMySQL(t)
|
|
store := devices.NewStore(db)
|
|
revoker := &devices.NoopRevoker{}
|
|
svc := devices.NewService(store, revoker)
|
|
ctx := context.Background()
|
|
|
|
userID := createUser(t, db, "chain@example.com", "active")
|
|
// 7-day pro trial → effective plan pro (max 3).
|
|
giveSubscription(t, db, userID, "pro", "trial", time.Now().UTC().Add(7*24*time.Hour))
|
|
|
|
plan, apiErr := svc.ResolvePlan(ctx, userID)
|
|
if apiErr != nil {
|
|
t.Fatalf("ResolvePlan: %v", apiErr)
|
|
}
|
|
if plan.PlanCode != "pro" || plan.MaxDevices != 3 {
|
|
t.Fatalf("want pro/3, got %s/%d", plan.PlanCode, plan.MaxDevices)
|
|
}
|
|
|
|
devUUID := newUUID(t, db)
|
|
in := devices.RegisterInput{UserID: userID, DeviceUUID: devUUID, Name: "iPhone 15 Pro", Platform: "ios", MaxDevices: plan.MaxDevices}
|
|
|
|
// First sight → insert.
|
|
_, d1, apiErr := svc.RegisterIfAbsent(ctx, in)
|
|
if apiErr != nil {
|
|
t.Fatalf("RegisterIfAbsent: %v", apiErr)
|
|
}
|
|
if d1.UUID != devUUID || d1.LastSeen == nil {
|
|
t.Fatalf("unexpected device: %+v", d1)
|
|
}
|
|
|
|
// Second sight → idempotent (no new row), last_seen refreshed.
|
|
if _, _, apiErr := svc.RegisterIfAbsent(ctx, in); apiErr != nil {
|
|
t.Fatalf("re-register: %v", apiErr)
|
|
}
|
|
list, apiErr := svc.ListDevices(ctx, userID)
|
|
if apiErr != nil {
|
|
t.Fatalf("ListDevices: %v", apiErr)
|
|
}
|
|
if len(list) != 1 {
|
|
t.Fatalf("expected 1 device after re-register, got %d", len(list))
|
|
}
|
|
|
|
// Give the device a data-plane credential (normally minted at connect) so
|
|
// clear-login revokes it per-device.
|
|
if _, err := db.Exec(`UPDATE devices SET dp_uuid=? WHERE uuid=?`, "dp-test-uuid", devUUID); err != nil {
|
|
t.Fatalf("set dp_uuid: %v", err)
|
|
}
|
|
|
|
// Delete → list drops to 0, audit row exists, revoker called with dp_uuid.
|
|
if apiErr := svc.DeleteDevice(ctx, userID, devUUID); apiErr != nil {
|
|
t.Fatalf("DeleteDevice: %v", apiErr)
|
|
}
|
|
list, _ = svc.ListDevices(ctx, userID)
|
|
if len(list) != 0 {
|
|
t.Fatalf("expected 0 devices after delete, got %d", len(list))
|
|
}
|
|
|
|
var auditCount int
|
|
db.QueryRow(`SELECT COUNT(1) FROM audit_log WHERE action='device.delete' AND actor=? AND target=?`,
|
|
fmt.Sprintf("user:%d", userID), "device:"+devUUID).Scan(&auditCount)
|
|
if auditCount != 1 {
|
|
t.Errorf("expected 1 device.delete audit row, got %d", auditCount)
|
|
}
|
|
|
|
if len(revoker.Calls) != 1 {
|
|
t.Fatalf("expected 1 revoke call, got %d", len(revoker.Calls))
|
|
}
|
|
if revoker.Calls[0] != "dp-test-uuid" {
|
|
t.Errorf("unexpected revoke call: %q", revoker.Calls[0])
|
|
}
|
|
}
|
|
|
|
// TestDeviceLimitEnforced verifies RegisterIfAbsent rejects when the cap is hit.
|
|
func TestDeviceLimitEnforced(t *testing.T) {
|
|
db := setupMySQL(t)
|
|
svc := devices.NewService(devices.NewStore(db), nil)
|
|
ctx := context.Background()
|
|
|
|
userID := createUser(t, db, "free@example.com", "active")
|
|
// No subscription → free plan, max_devices 1.
|
|
plan, _ := svc.ResolvePlan(ctx, userID)
|
|
if plan.MaxDevices != 1 {
|
|
t.Fatalf("expected free max_devices 1, got %d", plan.MaxDevices)
|
|
}
|
|
|
|
first := devices.RegisterInput{UserID: userID, DeviceUUID: newUUID(t, db), Name: "Pixel", Platform: "android", MaxDevices: 1}
|
|
if _, _, apiErr := svc.RegisterIfAbsent(ctx, first); apiErr != nil {
|
|
t.Fatalf("first register: %v", apiErr)
|
|
}
|
|
|
|
second := devices.RegisterInput{UserID: userID, DeviceUUID: newUUID(t, db), Name: "iPad", Platform: "ios", MaxDevices: 1}
|
|
_, _, apiErr := svc.RegisterIfAbsent(ctx, second)
|
|
if apiErr == nil {
|
|
t.Fatal("expected second register to be rejected")
|
|
}
|
|
if apiErr.Code != "DEVICE_LIMIT_EXCEEDED" {
|
|
t.Errorf("want DEVICE_LIMIT_EXCEEDED, got %s", apiErr.Code)
|
|
}
|
|
}
|
|
|
|
// TestCheckDeviceLimit covers the login-gate helper: within-cap, over-cap (active
|
|
// devices exceed the plan cap), and stale-prune (churned rows dropped + excluded).
|
|
func TestCheckDeviceLimit(t *testing.T) {
|
|
db := setupMySQL(t)
|
|
svc := devices.NewService(devices.NewStore(db), nil)
|
|
ctx := context.Background()
|
|
userID := createUser(t, db, "cap@example.com", "active") // free plan, cap 1
|
|
|
|
// 1 device → within cap.
|
|
d1 := newUUID(t, db)
|
|
if _, _, e := svc.RegisterIfAbsent(ctx, devices.RegisterInput{UserID: userID, DeviceUUID: d1, Name: "P1", Platform: "android"}); e != nil {
|
|
t.Fatalf("register d1: %v", e)
|
|
}
|
|
st, apiErr := svc.CheckDeviceLimit(ctx, userID)
|
|
if apiErr != nil {
|
|
t.Fatalf("CheckDeviceLimit: %v", apiErr)
|
|
}
|
|
if st.Over || st.MaxDevices != 1 {
|
|
t.Fatalf("1 device should be within cap 1, got %+v", st)
|
|
}
|
|
|
|
// 2nd device (MaxDevices:0 bypasses the register-time cap) → over cap.
|
|
d2 := newUUID(t, db)
|
|
if _, _, e := svc.RegisterIfAbsent(ctx, devices.RegisterInput{UserID: userID, DeviceUUID: d2, Name: "P2", Platform: "ios"}); e != nil {
|
|
t.Fatalf("register d2: %v", e)
|
|
}
|
|
st, _ = svc.CheckDeviceLimit(ctx, userID)
|
|
if !st.Over || len(st.Devices) != 2 {
|
|
t.Fatalf("2 devices should exceed cap 1, got %+v", st)
|
|
}
|
|
|
|
// Age d1 past staleWindow → pruned + excluded → back within cap.
|
|
if _, err := db.Exec(`UPDATE devices SET last_seen=? WHERE uuid=?`,
|
|
time.Now().UTC().Add(-40*24*time.Hour), d1); err != nil {
|
|
t.Fatalf("age d1: %v", err)
|
|
}
|
|
st, _ = svc.CheckDeviceLimit(ctx, userID)
|
|
if st.Over {
|
|
t.Fatalf("stale device should be pruned/excluded → within cap, got %+v", st)
|
|
}
|
|
var n int
|
|
if err := db.QueryRow(`SELECT COUNT(1) FROM devices WHERE uuid=?`, d1).Scan(&n); err != nil {
|
|
t.Fatalf("count d1: %v", err)
|
|
}
|
|
if n != 0 {
|
|
t.Errorf("stale device should be pruned, still present")
|
|
}
|
|
}
|
|
|
|
// TestDeleteOthersDevice verifies ownership enforcement and not-found handling.
|
|
func TestDeleteOthersDevice(t *testing.T) {
|
|
db := setupMySQL(t)
|
|
svc := devices.NewService(devices.NewStore(db), nil)
|
|
ctx := context.Background()
|
|
|
|
owner := createUser(t, db, "owner@example.com", "active")
|
|
other := createUser(t, db, "other@example.com", "active")
|
|
|
|
devUUID := newUUID(t, db)
|
|
if _, _, apiErr := svc.RegisterIfAbsent(ctx, devices.RegisterInput{
|
|
UserID: owner, DeviceUUID: devUUID, Name: "Mac", Platform: "macos", MaxDevices: 5,
|
|
}); apiErr != nil {
|
|
t.Fatalf("register: %v", apiErr)
|
|
}
|
|
|
|
// Other user cannot delete it → 404 NOT_FOUND(查找按 (user,uuid) 作用域,
|
|
// 他人名下的行不可见,migration 21 起不再是 403)。
|
|
if apiErr := svc.DeleteDevice(ctx, other, devUUID); apiErr == nil || apiErr.Code != "NOT_FOUND" {
|
|
t.Errorf("want NOT_FOUND, got %v", apiErr)
|
|
}
|
|
// Non-existent device → 404 NOT_FOUND.
|
|
if apiErr := svc.DeleteDevice(ctx, owner, newUUID(t, db)); apiErr == nil || apiErr.Code != "NOT_FOUND" {
|
|
t.Errorf("want NOT_FOUND, got %v", apiErr)
|
|
}
|
|
}
|
|
|
|
// TestSameDeviceUUIDTwoAccounts:F3 回归——同一物理设备(同 device uuid)先后登录
|
|
// 两个账号,双方都能注册成功、各自成行,互不 403;各自的删除只影响自己名下的行。
|
|
func TestSameDeviceUUIDTwoAccounts(t *testing.T) {
|
|
db := setupMySQL(t)
|
|
svc := devices.NewService(devices.NewStore(db), nil)
|
|
ctx := context.Background()
|
|
|
|
userA := createUser(t, db, "a-shared@example.com", "active")
|
|
userB := createUser(t, db, "b-shared@example.com", "active")
|
|
devUUID := newUUID(t, db) // 同一台机器的持久 device_id
|
|
|
|
if _, _, apiErr := svc.RegisterIfAbsent(ctx, devices.RegisterInput{
|
|
UserID: userA, DeviceUUID: devUUID, Name: "Shared Mac", Platform: "macos", MaxDevices: 5,
|
|
}); apiErr != nil {
|
|
t.Fatalf("register user A: %v", apiErr)
|
|
}
|
|
// 换账号:同 uuid 注册到 user B —— 旧全局 UNIQUE(uuid) 下这里是 403 死结。
|
|
if _, _, apiErr := svc.RegisterIfAbsent(ctx, devices.RegisterInput{
|
|
UserID: userB, DeviceUUID: devUUID, Name: "Shared Mac", Platform: "macos", MaxDevices: 5,
|
|
}); apiErr != nil {
|
|
t.Fatalf("register user B (same device uuid): %v", apiErr)
|
|
}
|
|
|
|
// 各自名下都各有一行。
|
|
for _, uid := range []int64{userA, userB} {
|
|
list, apiErr := svc.ListDevices(ctx, uid)
|
|
if apiErr != nil {
|
|
t.Fatalf("list %d: %v", uid, apiErr)
|
|
}
|
|
n := 0
|
|
for _, d := range list {
|
|
if d.UUID == devUUID {
|
|
n++
|
|
}
|
|
}
|
|
if n != 1 {
|
|
t.Errorf("user %d: want 1 row for shared uuid, got %d", uid, n)
|
|
}
|
|
}
|
|
|
|
// A 删除自己的行,不影响 B 的行。
|
|
if apiErr := svc.DeleteDevice(ctx, userA, devUUID); apiErr != nil {
|
|
t.Fatalf("delete A: %v", apiErr)
|
|
}
|
|
listB, apiErr := svc.ListDevices(ctx, userB)
|
|
if apiErr != nil {
|
|
t.Fatalf("list B after A delete: %v", apiErr)
|
|
}
|
|
found := false
|
|
for _, d := range listB {
|
|
if d.UUID == devUUID {
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
t.Errorf("user B's row must survive user A's delete")
|
|
}
|
|
}
|
|
|
|
// TestBannedUserRejected verifies the resolver/middleware path rejects banned users.
|
|
func TestBannedUserRejected(t *testing.T) {
|
|
db := setupMySQL(t)
|
|
svc := devices.NewService(devices.NewStore(db), nil)
|
|
ctx := context.Background()
|
|
|
|
userID := createUser(t, db, "banned@example.com", "banned")
|
|
if _, apiErr := svc.ResolvePlan(ctx, userID); apiErr == nil || apiErr.Code != "ACCOUNT_BANNED" {
|
|
t.Errorf("want ACCOUNT_BANNED, got %v", apiErr)
|
|
}
|
|
}
|
|
|
|
// TestHTTPHandlers exercises the chi routes end-to-end through the subscription
|
|
// middleware (userID injected as the JWT middleware would).
|
|
func TestHTTPHandlers(t *testing.T) {
|
|
db := setupMySQL(t)
|
|
svc := devices.NewService(devices.NewStore(db), &devices.NoopRevoker{})
|
|
ctx := context.Background()
|
|
|
|
userID := createUser(t, db, "http@example.com", "active")
|
|
giveSubscription(t, db, userID, "pro", "code", time.Now().UTC().Add(30*24*time.Hour))
|
|
|
|
devUUID := newUUID(t, db)
|
|
if _, _, apiErr := svc.RegisterIfAbsent(ctx, devices.RegisterInput{
|
|
UserID: userID, DeviceUUID: devUUID, Name: "Win", Platform: "windows", MaxDevices: 5,
|
|
}); apiErr != nil {
|
|
t.Fatalf("register: %v", apiErr)
|
|
}
|
|
|
|
mw := devices.NewMiddleware(svc, nil, 0)
|
|
h := devices.NewHandler(svc)
|
|
|
|
r := chi.NewRouter()
|
|
// Simulate the JWT auth middleware setting the user ID.
|
|
r.Use(func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
|
next.ServeHTTP(w, req.WithContext(devices.WithUserID(req.Context(), userID)))
|
|
})
|
|
})
|
|
r.Route("/v1/me", func(r chi.Router) {
|
|
r.Use(mw.Handler)
|
|
h.RegisterRoutes(r)
|
|
})
|
|
|
|
// GET /v1/me/devices
|
|
req := httptest.NewRequest(http.MethodGet, "/v1/me/devices", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("GET devices: want 200, got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
var listResp struct {
|
|
Devices []devices.Device `json:"devices"`
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &listResp); err != nil {
|
|
t.Fatalf("decode list: %v", err)
|
|
}
|
|
if len(listResp.Devices) != 1 || listResp.Devices[0].UUID != devUUID {
|
|
t.Fatalf("unexpected list: %+v", listResp.Devices)
|
|
}
|
|
|
|
// DELETE /v1/me/devices/{id}
|
|
req = httptest.NewRequest(http.MethodDelete, "/v1/me/devices/"+devUUID, nil)
|
|
w = httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusNoContent {
|
|
t.Fatalf("DELETE device: want 204, got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
|
|
// DELETE a non-existent device → 404.
|
|
req = httptest.NewRequest(http.MethodDelete, "/v1/me/devices/"+newUUID(t, db), nil)
|
|
w = httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusNotFound {
|
|
t.Fatalf("DELETE missing device: want 404, got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
}
|