package middleware import ( "net/http" "net/http/httptest" "testing" "hfb_sys/backend/internal/database" "hfb_sys/backend/internal/model" "hfb_sys/backend/internal/tenancy" "github.com/gin-gonic/gin" ) func newTenantContextTestEngine(t *testing.T, appEnv string) (*gin.Engine, model.Tenant) { t.Helper() db := database.NewTestDB() tenant := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"} if err := db.Create(&tenant).Error; err != nil { t.Fatalf("create tenant: %v", err) } repo := tenancy.NewRepository(db) if err := repo.UpsertDomain(t.Context(), tenant.Code, "hao858.com", "storefront"); err != nil { t.Fatalf("create domain: %v", err) } gin.SetMode(gin.TestMode) engine := gin.New() engine.Use(TenantContext(repo, appEnv, nil)) engine.GET("/probe", func(c *gin.Context) { scope, ok := tenancy.FromContext(c.Request.Context()) if !ok { c.JSON(http.StatusNotFound, gin.H{"found": false}) return } c.JSON(http.StatusOK, gin.H{"tenant_id": scope.TenantID, "tenant_code": scope.TenantCode}) }) return engine, tenant } func TestTenantContextResolvesHost(t *testing.T) { engine, tenant := newTenantContextTestEngine(t, "production") req := httptest.NewRequest(http.MethodGet, "/probe", nil) req.Host = "hao858.com" rec := httptest.NewRecorder() engine.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String()) } if body := rec.Body.String(); body == "" || !contains(body, `"tenant_id":`) { t.Fatalf("unexpected body: %s", body) } if tenant.ID == 0 { t.Fatal("tenant ID should not be zero") } } func TestTenantContextAllowsDevelopmentCodeAndIgnoresItInProduction(t *testing.T) { engine, _ := newTenantContextTestEngine(t, "development") req := httptest.NewRequest(http.MethodGet, "/probe", nil) req.Host = "localhost" req.Header.Set(tenantCodeHeader, "dachui") rec := httptest.NewRecorder() engine.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("development code status = %d, body=%s", rec.Code, rec.Body.String()) } engine, _ = newTenantContextTestEngine(t, "production") req = httptest.NewRequest(http.MethodGet, "/probe", nil) req.Host = "localhost" req.Header.Set(tenantCodeHeader, "dachui") rec = httptest.NewRecorder() engine.ServeHTTP(rec, req) if rec.Code != http.StatusNotFound { t.Fatalf("production header status = %d, want 404", rec.Code) } } func contains(value, target string) bool { for i := 0; i+len(target) <= len(value); i++ { if value[i:i+len(target)] == target { return true } } return false }