package api import ( "errors" "fmt" "net/http" "net/http/httptest" "syscall" "testing" "time" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/puddle/v2" "booklib/internal/config" "booklib/internal/redispkg" ) func testCfg() *config.Config { return &config.Config{Addr: ":8080", JWTSecret: []byte("s3cret"), ScanInterval: time.Minute, UploadMaxMB: 200, TrustedProxies: []string{"172.16.0.0/12"}} // 与 prod 默认一致: 只有 compose 网段内代理才可信 } func TestHealthz(t *testing.T) { r := NewRouter(testCfg(), nil, redispkg.New(""), nil) req := httptest.NewRequest(http.MethodGet, "/api/healthz", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("healthz = %d, want 200", w.Code) } } func TestDBErrStatus(t *testing.T) { for _, tc := range []struct { e error want int }{ {&pgconn.PgError{Code: "57P01"}, http.StatusServiceUnavailable}, // PG 停机:池内连接被服务端断 {&pgconn.PgError{Code: "08006"}, http.StatusServiceUnavailable}, {fmt.Errorf("dial: %w", syscall.ECONNREFUSED), http.StatusServiceUnavailable}, {puddle.ErrClosedPool, http.StatusServiceUnavailable}, {errors.New("boom"), http.StatusInternalServerError}, } { w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) dbErr(c, tc.e) if w.Code != tc.want { t.Errorf("dbErr(%v) = %d, want %d", tc.e, w.Code, tc.want) } } }