gateway_handler_usage_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package handler
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "time"
  9. "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  10. "github.com/Wei-Shaw/sub2api/internal/service"
  11. "github.com/gin-gonic/gin"
  12. "github.com/stretchr/testify/require"
  13. )
  14. func TestUsageUnrestrictedIncludesWeeklyWindowStart(t *testing.T) {
  15. gin.SetMode(gin.TestMode)
  16. recorder := httptest.NewRecorder()
  17. c, _ := gin.CreateTestContext(recorder)
  18. c.Request = httptest.NewRequest(http.MethodGet, "/v1/usage", nil)
  19. weeklyWindowStart := time.Date(2026, time.July, 13, 0, 30, 0, 0, time.FixedZone("UTC+8", 8*60*60))
  20. c.Set(string(middleware.ContextKeySubscription), &service.UserSubscription{
  21. WeeklyWindowStart: &weeklyWindowStart,
  22. })
  23. handler := &GatewayHandler{}
  24. handler.usageUnrestricted(
  25. c,
  26. context.Background(),
  27. &service.APIKey{Group: &service.Group{
  28. Name: "Weekly plan",
  29. SubscriptionType: service.SubscriptionTypeSubscription,
  30. }},
  31. middleware.AuthSubject{},
  32. nil,
  33. nil,
  34. nil,
  35. )
  36. require.Equal(t, http.StatusOK, recorder.Code)
  37. var response struct {
  38. Subscription struct {
  39. WeeklyWindowStart *time.Time `json:"weekly_window_start"`
  40. } `json:"subscription"`
  41. }
  42. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &response))
  43. require.NotNil(t, response.Subscription.WeeklyWindowStart)
  44. require.True(t, weeklyWindowStart.Equal(*response.Subscription.WeeklyWindowStart))
  45. }