package controller import ( "testing" "ezops/model" "github.com/glebarez/sqlite" "gorm.io/gorm" ) // TestBillingDimensionAttribution 验证费用变化额和贡献度使用数据库完整数据计算。 // Logan.Li func TestBillingDimensionAttribution(t *testing.T) { db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) if err != nil { t.Fatalf("打开测试数据库失败: %v", err) } if err = db.AutoMigrate(&model.CloudBilling{}); err != nil { t.Fatalf("迁移账单表失败: %v", err) } records := []model.CloudBilling{ {BillingDate: "2026-06-01", Provider: "tencent", Service: "CVM", Region: "广州", AccountName: "预发", Currency: "CNY", Cost: 100}, {BillingDate: "2026-07-01", Provider: "tencent", Service: "CVM", Region: "广州", AccountName: "预发", Currency: "CNY", Cost: 180}, {BillingDate: "2026-07-01", Provider: "tencent", Service: "COS", Region: "广州", AccountName: "预发", Currency: "CNY", Cost: 20}, } if err = db.Create(&records).Error; err != nil { t.Fatalf("写入测试账单失败: %v", err) } handler := NewBillingHandler(db) items := handler.billingDimensionAttribution("service", "2026-06-01", "2026-06-30", "2026-07-01", "2026-07-31", "CNY", 100) if len(items) != 2 { t.Fatalf("归因项数量错误: got=%d want=2", len(items)) } result := map[string]billingAttribution{} for _, item := range items { result[item.Name] = item } if result["CVM"].Delta != 80 || result["CVM"].Contribution != 80 { t.Fatalf("CVM 归因错误: %+v", result["CVM"]) } if result["COS"].Delta != 20 || result["COS"].Contribution != 20 { t.Fatalf("COS 归因错误: %+v", result["COS"]) } }