post_billing_platform_test.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //go:build unit
  2. package service
  3. import (
  4. "context"
  5. "testing"
  6. "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
  7. )
  8. func TestPlatformFromAPIKey_NilSafe(t *testing.T) {
  9. if got := PlatformFromAPIKey(nil); got != "" {
  10. t.Errorf("nil APIKey should yield empty string, got %q", got)
  11. }
  12. }
  13. func TestPlatformFromAPIKey_NilGroup(t *testing.T) {
  14. k := &APIKey{Group: nil}
  15. if got := PlatformFromAPIKey(k); got != "" {
  16. t.Errorf("APIKey with nil Group should yield empty string, got %q", got)
  17. }
  18. }
  19. func TestPlatformFromAPIKey_DerivesFromGroup(t *testing.T) {
  20. tests := []struct {
  21. name string
  22. platform string
  23. }{
  24. {"anthropic", "anthropic"},
  25. {"openai", "openai"},
  26. {"gemini", "gemini"},
  27. {"antigravity", "antigravity"},
  28. {"empty", ""},
  29. }
  30. for _, tt := range tests {
  31. t.Run(tt.name, func(t *testing.T) {
  32. k := &APIKey{
  33. Group: &Group{Platform: tt.platform},
  34. }
  35. got := PlatformFromAPIKey(k)
  36. if got != tt.platform {
  37. t.Errorf("PlatformFromAPIKey(%q) = %q, want %q", tt.platform, got, tt.platform)
  38. }
  39. })
  40. }
  41. }
  42. // TestQuotaPlatform 锁定配额计量口径:ForcePlatform 路由(如 /antigravity)按 ForcePlatform 计,
  43. // 否则回退到 Group 平台。preflight 与 post-billing 共用此口径,保证一致。
  44. func TestQuotaPlatform(t *testing.T) {
  45. apiKey := &APIKey{Group: &Group{Platform: PlatformAnthropic}}
  46. t.Run("no force platform falls back to group platform", func(t *testing.T) {
  47. if got := QuotaPlatform(context.Background(), apiKey); got != PlatformAnthropic {
  48. t.Errorf("QuotaPlatform without force = %q, want %q", got, PlatformAnthropic)
  49. }
  50. })
  51. t.Run("force platform overrides group platform", func(t *testing.T) {
  52. ctx := context.WithValue(context.Background(), ctxkey.ForcePlatform, PlatformAntigravity)
  53. if got := QuotaPlatform(ctx, apiKey); got != PlatformAntigravity {
  54. t.Errorf("QuotaPlatform with force = %q, want %q", got, PlatformAntigravity)
  55. }
  56. })
  57. t.Run("empty force platform falls back to group platform", func(t *testing.T) {
  58. ctx := context.WithValue(context.Background(), ctxkey.ForcePlatform, "")
  59. if got := QuotaPlatform(ctx, apiKey); got != PlatformAnthropic {
  60. t.Errorf("QuotaPlatform with empty force = %q, want %q", got, PlatformAnthropic)
  61. }
  62. })
  63. t.Run("nil api key with force platform returns force platform", func(t *testing.T) {
  64. ctx := context.WithValue(context.Background(), ctxkey.ForcePlatform, PlatformAntigravity)
  65. if got := QuotaPlatform(ctx, nil); got != PlatformAntigravity {
  66. t.Errorf("QuotaPlatform(nil) with force = %q, want %q", got, PlatformAntigravity)
  67. }
  68. })
  69. }