period_test.go (2349B)
1 package utils 2 3 import ( 4 "testing" 5 "time" 6 ) 7 8 func month(s string) time.Time { 9 t, err := time.Parse("2006-01", s) 10 if err != nil { 11 panic(err) 12 } 13 return t 14 } 15 16 func monthPtr(s string) *time.Time { 17 t := month(s) 18 return &t 19 } 20 21 func pinNow(t *testing.T, s string) { 22 t.Helper() 23 old := now 24 now = func() time.Time { return month(s).AddDate(0, 0, 21) } 25 t.Cleanup(func() { now = old }) 26 } 27 28 func TestRangeAndDuration(t *testing.T) { 29 pinNow(t, "2026-10") 30 for _, c := range []struct { 31 start string 32 end *time.Time 33 current bool 34 rng, dur string 35 }{ 36 {"2026-02", nil, true, "feb 2026 – present", "9 mo"}, 37 {"2024-10", monthPtr("2026-02"), false, "oct 2024 – feb 2026", "1 yr 5 mo"}, 38 {"2024-06", monthPtr("2024-08"), false, "jun 2024 – aug 2024", "3 mo"}, 39 {"2024-01", monthPtr("2025-12"), false, "jan 2024 – dec 2025", "2 yr"}, 40 {"2026-03", monthPtr("2026-03"), false, "mar 2026 – mar 2026", "1 mo"}, 41 } { 42 s := month(c.start) 43 if got := FormatRange(s, c.end, c.current); got != c.rng { 44 t.Errorf("FormatRange(%s) = %q, want %q", c.start, got, c.rng) 45 } 46 if got := FormatDurationShort(s, c.end, c.current); got != c.dur { 47 t.Errorf("FormatDurationShort(%s) = %q, want %q", c.start, got, c.dur) 48 } 49 } 50 } 51 52 func TestAxis(t *testing.T) { 53 pinNow(t, "2026-10") 54 a := NewAxis([]Span{ 55 {Start: month("2026-02"), Current: true}, 56 {Start: month("2024-10"), End: monthPtr("2026-02")}, 57 {Start: month("2024-06"), End: monthPtr("2024-08")}, 58 }) 59 // jan 2024 .. oct 2026 inclusive = 34 months 60 if a.months != 34 { 61 t.Fatalf("months = %d, want 34", a.months) 62 } 63 if len(a.Ticks) != 3 || a.Ticks[0].Label != "2024" || a.Ticks[2].Label != "2026" { 64 t.Fatalf("ticks = %+v", a.Ticks) 65 } 66 if got := a.Ticks[1].At; got != 12.0/34 { 67 t.Errorf("2025 tick at %v", got) 68 } 69 if a.EndLabel != "now" { 70 t.Errorf("EndLabel = %q, want now", a.EndLabel) 71 } 72 if got := a.To(nil, true); got != 1 { 73 t.Errorf("current role ends at %v, want 1", got) 74 } 75 if from, to := a.From(month("2024-06")), a.To(monthPtr("2024-08"), false); from != 5.0/34 || to != 8.0/34 { 76 t.Errorf("amplifier spans %v..%v", from, to) 77 } 78 // mandolin ends the month hark starts: the bars meet, never overlap 79 if end, next := a.To(monthPtr("2026-02"), false), a.From(month("2026-02")); end != next { 80 t.Errorf("mandolin ends at %v, hark starts at %v", end, next) 81 } 82 }