重构:完成架构一致性整改与生命周期收口

This commit is contained in:
Christ committed 2026-08-18 14:05:08 +08:00
1 parent 55904cc409
commit 9eb6be2875
344 files changed
+15961 -13926

No files matched your search

+149 -107
View File
@@ -12,6 +12,7 @@ import (
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/chat"
@@ -57,6 +58,8 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
chatDependencies := adapter.NewChatDependencies(store)
// systemDependencies 保存健康检查与补偿扫描测试使用的显式适配器工厂。
systemDependencies := adapter.NewSystemDependencies(store)
// databaseHealth 是测试进程组合根创建后注入 Server 的健康检查端口。
databaseHealth := systemDependencies.NewDatabaseHealth()
// automationDependencies 保存自动化测试使用的显式适配器工厂及构造错误。
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
if automationDependencyErr != nil {
@@ -69,9 +72,22 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
}
// adminSettingsDependencies 保存管理员和系统设置测试使用的显式适配器工厂。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
if chatDependencies == nil || systemDependencies == nil || databaseHealth == nil || adminSettingsDependencies == nil {
t.Fatal("显式 Server 依赖构造失败")
}
// transportApplications 是测试组合根构造的 transport-facing 应用服务集合。
transportApplications, transportApplicationsErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies,
MiscDependencies: miscDependencies,
AdminSettingsDependencies: adminSettingsDependencies,
AccountTaskRunner: adapter.NewAccountTaskRunner(nil),
ModelClient: adapter.NewAIModelClient(),
})
if transportApplicationsErr != nil {
t.Fatalf("NewTransportApplicationServices: %v", transportApplicationsErr)
}
// orderReconciliationRecovery 是按生产组合根路径创建的订单补偿扫描应用服务。
orderReconciliationRecovery := newTestOrderReconciliationRecovery(t, systemDependencies)
// platformDependencies 保存测试服务器显式注入的平台客户端集合。
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
if platformDependencyErr != nil {
@@ -80,11 +96,11 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
// authentication 保存测试 HTTP 会话中间件需要的认证服务。
authentication := &auth.Service{Store: store}
// srv、err 保存测试 HTTP 服务构造结果及失败原因。
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies))
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
if err != nil {
t.Fatalf("New: %v", err)
}
// mtopClient 保存mtopClient,供当前处理流程使用
// mtopClient 用于本次流程后续判断的mtopClient
mtopClient := mtop.NewClient()
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
@@ -116,10 +132,10 @@ func newTestServerWithChat(t *testing.T) (*Server, *db.Store, func()) {
return srv, store, cleanup
}
// newUninitializedTestServer 负责newUninitializedTestServer相关处理。
// newUninitializedTestServer 封装newUninitializedTestServer业务协调。
func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
// dbPath 用于本次流程后续判断的db路径
dbPath := filepath.Join(t.TempDir(), "test.db")
// d 是当前未初始化测试使用的数据库连接;err 是打开错误。
d, _, err := db.Open(context.Background(), dbPath)
@@ -150,6 +166,8 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
chatDependencies := adapter.NewChatDependencies(store)
// systemDependencies 保存未初始化测试使用的系统适配器工厂。
systemDependencies := adapter.NewSystemDependencies(store)
// databaseHealth 是测试进程组合根创建后注入 Server 的健康检查端口。
databaseHealth := systemDependencies.NewDatabaseHealth()
// automationDependencies 保存未初始化测试使用的自动化适配器工厂及构造错误。
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
if automationDependencyErr != nil {
@@ -162,9 +180,22 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
}
// adminSettingsDependencies 保存未初始化测试使用的管理员设置适配器工厂。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
if chatDependencies == nil || systemDependencies == nil || databaseHealth == nil || adminSettingsDependencies == nil {
t.Fatal("显式 Server 依赖构造失败")
}
// transportApplications 是未初始化测试组合根构造的 transport-facing 应用服务集合。
transportApplications, transportApplicationsErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies,
MiscDependencies: miscDependencies,
AdminSettingsDependencies: adminSettingsDependencies,
AccountTaskRunner: adapter.NewAccountTaskRunner(nil),
ModelClient: adapter.NewAIModelClient(),
})
if transportApplicationsErr != nil {
t.Fatalf("NewTransportApplicationServices: %v", transportApplicationsErr)
}
// orderReconciliationRecovery 是按生产组合根路径创建的订单补偿扫描应用服务。
orderReconciliationRecovery := newTestOrderReconciliationRecovery(t, systemDependencies)
// platformDependencies 保存未初始化测试服务器显式注入的平台客户端集合。
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
if platformDependencyErr != nil {
@@ -173,7 +204,7 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
// authentication 保存未初始化数据库上的会话中间件依赖。
authentication := &auth.Service{Store: store}
// srv、err 保存未初始化测试服务构造结果及失败原因。
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies))
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
if err != nil {
t.Fatalf("New: %v", err)
}
@@ -183,15 +214,26 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
}
}
// roundTripFunc 保存roundTripFunc,供当前处理流程使用
// newTestOrderReconciliationRecovery 以与进程组合根一致的路径构造订单补偿扫描应用服务。
func newTestOrderReconciliationRecovery(t *testing.T, dependencies *adapter.SystemDependencies) *orderapp.ReconciliationRecoveryCoordinator {
t.Helper()
// recovery 是订单补偿扫描应用服务;测试不启动它,因此无需额外关闭。
recovery, recoveryErr := orderapp.NewReconciliationRecoveryCoordinator(dependencies.NewReconciliationService(nil))
if recoveryErr != nil {
t.Fatalf("NewReconciliationRecoveryCoordinator: %v", recoveryErr)
}
return recovery
}
// roundTripFunc 用于本次流程后续判断的roundTripFunc
type roundTripFunc func(*http.Request) (*http.Response, error)
// RoundTrip 负责RoundTrip相关处理。
// RoundTrip 封装RoundTrip业务协调。
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
// noopHandler 保存noopHandler,供当前处理流程使用
// noopHandler 用于本次流程后续判断的noopHandler
type noopHandler struct{}
// HandleChatMessage 处理聊天消息。
@@ -200,37 +242,37 @@ func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error
// HandleSystemEvent 处理系统Event。
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
// OnPasswordLoginRefresh 封装On密码登录Refresh业务协调。
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// OnAccountAlert 负责On账号Alert相关处理。
// OnAccountAlert 封装On账号Alert业务协调。
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
// TestLoginVerifyLogout 登录→verify→登出 全链路。
func TestLoginVerifyLogout(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// 1) 登录(用户名密码)。
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
}
// lr 保存lr,供当前处理流程使用
// lr 用于本次流程后续判断的lr
var lr loginResponse
json.Unmarshal(rec.Body.Bytes(), &lr)
if !lr.Success || !lr.IsAdmin {
t.Fatalf("登录响应异常: %+v", lr)
}
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
if cookie.Name != "session" || cookie.Value == "" || !cookie.HttpOnly {
t.Fatalf("Cookie 异常: %+v", cookie)
@@ -239,10 +281,10 @@ func TestLoginVerifyLogout(t *testing.T) {
// 2) verify 带 cookie 应 authenticated。
req2 := httptest.NewRequest(http.MethodGet, "/verify", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// v 保存v,供当前处理流程使用
// v 用于本次流程后续判断的v
var v map[string]any
json.Unmarshal(rec2.Body.Bytes(), &v)
if v["authenticated"] != true || v["initialized"] != true {
@@ -251,7 +293,7 @@ func TestLoginVerifyLogout(t *testing.T) {
// 3) 无 cookie verify 应未认证。
req3 := httptest.NewRequest(http.MethodGet, "/verify", nil)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
json.Unmarshal(rec3.Body.Bytes(), &v)
@@ -262,12 +304,12 @@ func TestLoginVerifyLogout(t *testing.T) {
// 4) 登出。
req4 := httptest.NewRequest(http.MethodPost, "/logout", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// 登出后 cookie 应被清除(MaxAge=-1)。
dc := rec4.Result().Cookies()
// cleared 保存cleared,供当前处理流程使用
// cleared 用于本次流程后续判断的cleared
cleared := false
// c 表示当前遍历过程中的c
for _, c := range dc {
@@ -282,20 +324,20 @@ func TestLoginVerifyLogout(t *testing.T) {
// TestLoginWrongPassword 错误密码。
func TestLoginWrongPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"username":"admin","password":"wrong"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// lr 保存lr,供当前处理流程使用
// lr 用于本次流程后续判断的lr
var lr loginResponse
json.Unmarshal(rec.Body.Bytes(), &lr)
if lr.Success {
@@ -303,34 +345,34 @@ func TestLoginWrongPassword(t *testing.T) {
}
}
// TestInitializeFromWebUI 负责TestInitializeFromWebUI相关处理。
// TestInitializeFromWebUI 封装TestInitializeFromWebUI业务协调。
func TestInitializeFromWebUI(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newUninitializedTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// shortReq 保存shortReq,供当前处理流程使用
// shortReq 用于本次流程后续判断的shortReq
shortReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"short"}`))
// shortRec 保存shortRec,供当前处理流程使用
// shortRec 用于本次流程后续判断的shortRec
shortRec := httptest.NewRecorder()
h.ServeHTTP(shortRec, shortReq)
if shortRec.Code != http.StatusBadRequest {
t.Fatalf("短密码应返回 400,got %d body=%s", shortRec.Code, shortRec.Body.String())
}
// initReq 保存initReq,供当前处理流程使用
// initReq 用于本次流程后续判断的initReq
initReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"newpassword"}`))
// initRec 保存initRec,供当前处理流程使用
// initRec 用于本次流程后续判断的initRec
initRec := httptest.NewRecorder()
h.ServeHTTP(initRec, initReq)
if initRec.Code != http.StatusOK {
t.Fatalf("初始化 status=%d body=%s", initRec.Code, initRec.Body.String())
}
// initResult 保存init结果,供当前处理流程使用
// initResult 用于本次流程后续判断的init结果
var initResult loginResponse
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(initRec.Body.Bytes(), &initResult); err != nil {
t.Fatalf("解析初始化响应: %v", err)
}
@@ -338,30 +380,30 @@ func TestInitializeFromWebUI(t *testing.T) {
t.Fatalf("初始化响应异常: %+v", initResult)
}
// admin、err 保存admin、err,供当前处理流程使用
// admin、err 用于本次流程后续判断的admin、err
admin, err := store.Users.GetAdmin(context.Background())
if err != nil || admin == nil {
t.Fatalf("初始化后 admin 不存在: admin=%+v err=%v", admin, err)
}
if // ok、err 保存ok、err,供当前处理流程使用
if // ok、err 用于本次流程后续判断的ok、err
_, ok, err := store.Users.VerifyAndUpgrade(context.Background(), "admin", "newpassword"); err != nil || !ok {
t.Fatalf("初始化密码不可用: ok=%v err=%v", ok, err)
}
// cookies 保存cookies,供当前处理流程使用
// cookies 用于本次流程后续判断的cookies
cookies := initRec.Result().Cookies()
if len(cookies) == 0 || cookies[0].Name != "session" || cookies[0].Value == "" {
t.Fatalf("初始化后应自动建立会话: %+v", cookies)
}
// verifyReq 保存verifyReq,供当前处理流程使用
// verifyReq 用于本次流程后续判断的verifyReq
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(cookies[0])
// verifyRec 保存verifyRec,供当前处理流程使用
// verifyRec 用于本次流程后续判断的verifyRec
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verifyResult 保存verify结果,供当前处理流程使用
// verifyResult 用于本次流程后续判断的verify结果
var verifyResult map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult); err != nil {
t.Fatalf("解析 verify 响应: %v", err)
}
@@ -369,9 +411,9 @@ func TestInitializeFromWebUI(t *testing.T) {
t.Fatalf("初始化后 verify 异常: %+v", verifyResult)
}
// secondReq 保存secondReq,供当前处理流程使用
// secondReq 用于本次流程后续判断的secondReq
secondReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"anotherpw"}`))
// secondRec 保存secondRec,供当前处理流程使用
// secondRec 用于本次流程后续判断的secondRec
secondRec := httptest.NewRecorder()
h.ServeHTTP(secondRec, secondReq)
if secondRec.Code != http.StatusConflict {
@@ -379,71 +421,71 @@ func TestInitializeFromWebUI(t *testing.T) {
}
}
// TestUpdateCredentialsRenamesUserAndRevokesSessions 负责TestUpdateCredentialsRenames用户AndRevokesSessions相关处理。
// TestUpdateCredentialsRenamesUserAndRevokesSessions 封装TestUpdateCredentialsRenames用户AndRevokesSessions业务协调。
func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
// loginReq 用于本次流程后续判断的登录Req
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
// loginRec 用于本次流程后续判断的登录Rec
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
// sessionCookie 保存会话登录凭证,供当前处理流程使用
// sessionCookie 用于本次流程后续判断的会话登录凭证
sessionCookie := loginRec.Result().Cookies()[0]
// updateReq 保存updateReq,供当前处理流程使用
// updateReq 用于本次流程后续判断的updateReq
updateReq := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(
`{"current_password":"pw","new_username":"operator","new_password":"newpassword"}`,
))
updateReq.AddCookie(sessionCookie)
// updateRec 保存updateRec,供当前处理流程使用
// updateRec 用于本次流程后续判断的updateRec
updateRec := httptest.NewRecorder()
h.ServeHTTP(updateRec, updateReq)
if updateRec.Code != http.StatusOK {
t.Fatalf("update status=%d body=%s", updateRec.Code, updateRec.Body.String())
}
// updateResult 保存update结果,供当前处理流程使用
// updateResult 用于本次流程后续判断的update结果
var updateResult map[string]any
json.Unmarshal(updateRec.Body.Bytes(), &updateResult)
if updateResult["success"] != true || updateResult["requires_relogin"] != true {
t.Fatalf("update result=%+v", updateResult)
}
// verifyReq 保存verifyReq,供当前处理流程使用
// verifyReq 用于本次流程后续判断的verifyReq
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(sessionCookie)
// verifyRec 保存verifyRec,供当前处理流程使用
// verifyRec 用于本次流程后续判断的verifyRec
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verifyResult 保存verify结果,供当前处理流程使用
// verifyResult 用于本次流程后续判断的verify结果
var verifyResult map[string]any
json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult)
if verifyResult["authenticated"] == true || verifyResult["initialized"] != true {
t.Fatalf("旧会话应失效且系统仍已初始化: %+v", verifyResult)
}
// oldLoginReq 保存old登录Req,供当前处理流程使用
// oldLoginReq 用于本次流程后续判断的old登录Req
oldLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// oldLoginRec 保存old登录Rec,供当前处理流程使用
// oldLoginRec 用于本次流程后续判断的old登录Rec
oldLoginRec := httptest.NewRecorder()
h.ServeHTTP(oldLoginRec, oldLoginReq)
// oldLogin 保存old登录,供当前处理流程使用
// oldLogin 用于本次流程后续判断的old登录
var oldLogin loginResponse
json.Unmarshal(oldLoginRec.Body.Bytes(), &oldLogin)
if oldLogin.Success {
t.Fatal("旧用户名不应继续登录")
}
// newLoginReq 保存new登录Req,供当前处理流程使用
// newLoginReq 用于本次流程后续判断的new登录Req
newLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"operator","password":"newpassword"}`))
// newLoginRec 保存new登录Rec,供当前处理流程使用
// newLoginRec 用于本次流程后续判断的new登录Rec
newLoginRec := httptest.NewRecorder()
h.ServeHTTP(newLoginRec, newLoginReq)
// newLogin 保存new登录,供当前处理流程使用
// newLogin 用于本次流程后续判断的new登录
var newLogin loginResponse
json.Unmarshal(newLoginRec.Body.Bytes(), &newLogin)
if !newLogin.Success {
@@ -453,15 +495,15 @@ func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
// TestCookiesDetailsRequiresAuth 未登录访问受保护端点应 401。
func TestCookiesDetailsRequiresAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -471,32 +513,32 @@ func TestCookiesDetailsRequiresAuth(t *testing.T) {
// TestCookiesDetailsWithAuth 登录后能取账号详情。
func TestCookiesDetailsWithAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// 登录拿 cookie。
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
// 取详情。
req2 := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("status=%d body=%s", rec2.Code, rec2.Body.String())
}
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["id"] != "acc1" {
@@ -511,34 +553,34 @@ func TestCookiesDetailsWithAuth(t *testing.T) {
}
}
// TestCookieRuntimeStatusWithAuth 负责Test登录凭证Runtime状态WithAuth相关处理。
// TestCookieRuntimeStatusWithAuth 封装Test登录凭证Runtime状态WithAuth业务协调。
func TestCookieRuntimeStatusWithAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
// loginReq 用于本次流程后续判断的登录Req
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
// loginRec 用于本次流程后续判断的登录Rec
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginRec.Result().Cookies()[0]
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/cookies/runtime-status", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// statuses 保存statuses,供当前处理流程使用
// statuses 用于本次流程后续判断的statuses
var statuses map[string]engine.RuntimeStatus
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &statuses); err != nil {
t.Fatal(err)
}
@@ -549,28 +591,28 @@ func TestCookieRuntimeStatusWithAuth(t *testing.T) {
// TestAddAndDeleteCookie 添加/删除账号。
func TestAddAndDeleteCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
// 添加。
addBody := `{"id":"acc2","value":"unb=456; _m_h5_tk=tk2_2;"}`
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(addBody))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -580,7 +622,7 @@ func TestAddAndDeleteCookie(t *testing.T) {
// 删除。
req3 := httptest.NewRequest(http.MethodDelete, "/cookies/acc2", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -590,15 +632,15 @@ func TestAddAndDeleteCookie(t *testing.T) {
// TestHealth 健康检查无需认证。
func TestHealth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/health", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -609,28 +651,28 @@ func TestHealth(t *testing.T) {
}
}
// TestHealthReportsUnavailableDatabase 负责TestHealthReportsUnavailableDatabase相关处理。
// TestHealthReportsUnavailableDatabase 封装TestHealthReportsUnavailableDatabase业务协调。
func TestHealthReportsUnavailableDatabase(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.DB.Close(); err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/health", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("health status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
// response 用于本次流程后续判断的响应
var response map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}