Files
go-sip/internal/daily/midnight_test.go
T

73 lines
2.3 KiB
Go

package daily
import (
"context"
"errors"
"testing"
"time"
)
func TestNextMidnightUsesShanghaiCalendarNotNoonOrElapsed24Hours(t *testing.T) {
for _, test := range []struct{ now, want string }{
{"2026-10-10T03:59:00Z", "2026-10-11T00:00:00+08:00"},
{"2026-10-10T04:00:00Z", "2026-10-11T00:00:00+08:00"},
{"2026-10-10T15:59:59Z", "2026-10-11T00:00:00+08:00"},
{"2026-10-10T16:00:00Z", "2026-10-12T00:00:00+08:00"},
} {
now, _ := time.Parse(time.RFC3339, test.now)
got, err := NextMidnight(now)
if err != nil || got.Format(time.RFC3339) != test.want {
t.Fatalf("now=%s got=%s want=%s err=%v", test.now, got, test.want, err)
}
}
}
func TestWallClockRollbackDoesNotTriggerEarlyCleanup(t *testing.T) {
now, _ := time.Parse(time.RFC3339, "2026-10-10T15:59:00Z")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls, waits := 0, []time.Duration{}
err := run(ctx, func(context.Context) error { calls++; return nil }, func() time.Time { return now }, func(delay time.Duration) (<-chan time.Time, func()) {
waits = append(waits, delay)
ch := make(chan time.Time, 1)
switch len(waits) {
case 1:
now = now.Add(delay - time.Hour)
ch <- now
case 2:
now = now.Add(delay)
ch <- now
default:
cancel()
}
return ch, func() {}
})
if err != nil || calls != 1 || len(waits) != 3 || waits[1] != time.Hour {
t.Fatalf("rollback ran early: calls=%d waits=%v err=%v", calls, waits, err)
}
}
func TestMidnightFailureRetriesOnlyTomorrowAndCancellationStopsTimer(t *testing.T) {
now, _ := time.Parse(time.RFC3339, "2026-10-10T15:59:00Z")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls, stopped := 0, 0
durations := []time.Duration{}
clock := func() time.Time { return now }
timer := func(delay time.Duration) (<-chan time.Time, func()) {
durations = append(durations, delay)
ch := make(chan time.Time, 1)
if len(durations) <= 2 {
now = now.Add(delay)
ch <- now
} else {
cancel()
}
return ch, func() { stopped++ }
}
err := run(ctx, func(context.Context) error { calls++; return errors.New("one record failed") }, clock, timer)
if err != nil || calls != 2 || stopped != 3 || len(durations) != 3 || durations[0] != time.Minute || durations[1] != 24*time.Hour {
t.Fatalf("unexpected daily behavior: calls=%d stopped=%d delays=%v err=%v", calls, stopped, durations, err)
}
}