step_align_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package costmodel
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/opencost/opencost/core/pkg/util/timeutil"
  6. )
  7. func TestAlignStepStart(t *testing.T) {
  8. // Reference dates all in April 2026:
  9. // Sun Apr 5, Mon Apr 6, Tue Apr 7, ..., Sat Apr 11
  10. // Sun Apr 12, Mon Apr 13, Tue Apr 14
  11. sundayApr5 := time.Date(2026, time.April, 5, 0, 0, 0, 0, time.UTC)
  12. sundayApr12 := time.Date(2026, time.April, 12, 0, 0, 0, 0, time.UTC)
  13. tuesdayApr7 := time.Date(2026, time.April, 7, 0, 0, 0, 0, time.UTC)
  14. mondayApr13 := time.Date(2026, time.April, 13, 0, 0, 0, 0, time.UTC)
  15. tuesdayApr14MidDay := time.Date(2026, time.April, 14, 12, 30, 0, 0, time.UTC)
  16. tests := map[string]struct {
  17. start time.Time
  18. step time.Duration
  19. expected time.Time
  20. }{
  21. "weekly step from Sunday is unchanged": {
  22. start: sundayApr5,
  23. step: timeutil.Week,
  24. expected: sundayApr5,
  25. },
  26. "weekly step from Tuesday aligns back to preceding Sunday": {
  27. start: tuesdayApr7,
  28. step: timeutil.Week,
  29. expected: sundayApr5,
  30. },
  31. "weekly step from Monday aligns back one day to preceding Sunday": {
  32. start: mondayApr13,
  33. step: timeutil.Week,
  34. expected: sundayApr12,
  35. },
  36. "weekly step from Tuesday mid-day aligns to preceding Sunday midnight": {
  37. start: tuesdayApr14MidDay,
  38. step: timeutil.Week,
  39. expected: sundayApr12,
  40. },
  41. "daily step is unchanged on a Tuesday": {
  42. start: tuesdayApr7,
  43. step: 24 * time.Hour,
  44. expected: tuesdayApr7,
  45. },
  46. "hourly step is unchanged": {
  47. start: tuesdayApr14MidDay,
  48. step: time.Hour,
  49. expected: tuesdayApr14MidDay,
  50. },
  51. "arbitrary step close to but not equal to a week is unchanged": {
  52. start: tuesdayApr7,
  53. step: 7*24*time.Hour - time.Hour,
  54. expected: tuesdayApr7,
  55. },
  56. }
  57. for name, tc := range tests {
  58. t.Run(name, func(t *testing.T) {
  59. got := alignStepStart(tc.start, tc.step)
  60. if !got.Equal(tc.expected) {
  61. t.Errorf("alignStepStart(%s, %s) = %s; want %s", tc.start, tc.step, got, tc.expected)
  62. }
  63. })
  64. }
  65. }