package middleware import ( "context" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) func TestIPCheck(t *testing.T) { gin.SetMode(gin.TestMode) allowAll := func(ctx context.Context, id int64, ip string) (bool, error) { return true, nil } denyAll := func(ctx context.Context, id int64, ip string) (bool, error) { return false, nil } setup := func(checker func(ctx context.Context, id int64, ip string) (bool, error)) *httptest.ResponseRecorder { r := gin.New() r.Use(func(c *gin.Context) { c.Set(ContextKeyClaims, &Claims{AccountID: 42, Username: "u"}) }) r.Use(IPCheck(checker)) r.GET("/x", func(c *gin.Context) { c.Status(http.StatusOK) }) w := httptest.NewRecorder() r.ServeHTTP(w, httptest.NewRequest("GET", "/x", nil)) return w } if w := setup(allowAll); w.Code != 200 { t.Errorf("allow-all: code = %d, want 200", w.Code) } if w := setup(denyAll); w.Code != 403 { t.Errorf("deny-all: code = %d, want 403", w.Code) } // checker == nil → 直接放行 if w := setup(nil); w.Code != 200 { t.Errorf("nil checker: code = %d, want 200", w.Code) } }