Files
phishingclub/backend/service/programSchedule_test.go
2026-12-01 21:25:01 +01:00

644 lines
26 KiB
Go

package service
import (
"math/rand"
"testing"
"time"
"github.com/google/uuid"
"github.com/oapi-codegen/nullable"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/vo"
)
func TestMinNextSendIsHalfAnInterval(t *testing.T) {
p := &model.Program{StepIntervalMinutes: nullable.NewNullableWithValue(7 * 24 * 60)}
if got := programMinNextSend(p, nil); !got.IsZero() {
t.Fatalf("no last send should set no bound, got %v", got)
}
last := time.Date(2024, 1, 1, 10, 0, 0, 0, time.UTC)
want := last.Add(84 * time.Hour)
if got := programMinNextSend(p, &last); !got.Equal(want) {
t.Fatalf("expected %v, got %v", want, got)
}
}
func TestPickSendTimeAfterKeepsGap(t *testing.T) {
// one week interval with a full week spread: without the bound the pick
// could land right after the round start
p := &model.Program{
StepIntervalMinutes: nullable.NewNullableWithValue(7 * 24 * 60),
SpreadMinutes: nullable.NewNullableWithValue(7 * 24 * 60),
}
roundStart := time.Date(2024, 1, 8, 0, 0, 0, 0, time.UTC)
lastSend := time.Date(2024, 1, 7, 23, 0, 0, 0, time.UTC)
notBefore := programMinNextSend(p, &lastSend)
rng := rand.New(rand.NewSource(1))
for i := 0; i < 200; i++ {
got := programPickSendTimeAfter(p, roundStart, roundStart, notBefore, rng)
if got.Before(notBefore) {
t.Fatalf("pick %v is before the minimum gap %v", got, notBefore)
}
if !got.Before(roundStart.Add(7 * 24 * time.Hour)) {
t.Fatalf("pick %v is past the spread", got)
}
}
}
func TestPickSendTimeAfterGapBeyondSpreadUsesNextSlot(t *testing.T) {
p := windowProgram(t)
p.StepIntervalMinutes = nullable.NewNullableWithValue(7 * 24 * 60)
p.SpreadMinutes = nullable.NewNullableWithValue(60)
// Monday 2024-01-08 09:00 round start, gap ends on Tuesday 12:00
roundStart := time.Date(2024, 1, 8, 9, 0, 0, 0, time.UTC)
notBefore := time.Date(2024, 1, 9, 12, 0, 0, 0, time.UTC)
got := programPickSendTimeAfter(p, roundStart, roundStart, notBefore, rand.New(rand.NewSource(1)))
// only Mondays are allowed, so the next opening is the Monday after
want := time.Date(2024, 1, 15, 9, 0, 0, 0, time.UTC)
if !got.Equal(want) {
t.Fatalf("expected %v, got %v", want, got)
}
}
// TestBlackoutNextWindowSlot checks the next window opening skips blackout
// days, with and without a window, also a blackout longer than the first
// search, and leaves a day outside the blackout alone
func TestBlackoutNextWindowSlot(t *testing.T) {
blackout := func(p *model.Program, from, to string) *model.Program {
p.BlackoutDates = nullable.NewNullableWithValue([]model.ProgramBlackout{{From: from, To: to}})
return p
}
cases := []struct {
name string
program *model.Program
now time.Time
want time.Time
}{
{"no window", blackout(&model.Program{}, "2024-12-24", "2024-12-26"),
time.Date(2024, 12, 24, 10, 0, 0, 0, time.UTC), time.Date(2024, 12, 27, 0, 0, 0, 0, time.UTC)},
{"day outside the blackout", blackout(&model.Program{}, "2024-12-24", "2024-12-26"),
time.Date(2024, 12, 23, 10, 0, 0, 0, time.UTC), time.Date(2024, 12, 23, 10, 0, 0, 0, time.UTC)},
// Monday 2024-01-08 is blacked out, so Monday 2024-01-15 is next
{"window day", blackout(windowProgram(t), "2024-01-08", "2024-01-08"),
time.Date(2024, 1, 2, 10, 0, 0, 0, time.UTC), time.Date(2024, 1, 15, 9, 0, 0, 0, time.UTC)},
{"longer than the first search", blackout(&model.Program{}, "2024-07-01", "2024-08-31"),
time.Date(2024, 7, 2, 10, 0, 0, 0, time.UTC), time.Date(2024, 9, 1, 0, 0, 0, 0, time.UTC)},
}
for _, c := range cases {
if got := programNextWindowSlot(c.program, c.now); !got.Equal(c.want) {
t.Fatalf("%s: expected %v, got %v", c.name, c.want, got)
}
}
}
func TestBlackoutPickNeverLandsOnBlockedDay(t *testing.T) {
p := &model.Program{
StepIntervalMinutes: nullable.NewNullableWithValue(7 * 24 * 60),
SpreadMinutes: nullable.NewNullableWithValue(7 * 24 * 60),
BlackoutDates: nullable.NewNullableWithValue([]model.ProgramBlackout{{From: "2024-01-09", To: "2024-01-12"}}),
}
roundStart := time.Date(2024, 1, 8, 0, 0, 0, 0, time.UTC)
rng := rand.New(rand.NewSource(3))
for i := 0; i < 300; i++ {
got := programPickSendTime(p, roundStart, roundStart, rng)
if p.IsBlackoutDay(got.Format(model.ProgramDateLayout)) {
t.Fatalf("pick %v is on a blackout day", got)
}
}
}
func TestYearlyBlackoutRepeats(t *testing.T) {
p := &model.Program{
BlackoutDates: nullable.NewNullableWithValue([]model.ProgramBlackout{
{From: "2024-12-25", To: "2024-12-25", Yearly: true},
}),
}
for _, year := range []int{2024, 2026, 2031} {
now := time.Date(year, 12, 25, 10, 0, 0, 0, time.UTC)
want := time.Date(year, 12, 26, 0, 0, 0, 0, time.UTC)
if got := programNextWindowSlot(p, now); !got.Equal(want) {
t.Fatalf("%d: expected %v, got %v", year, want, got)
}
}
// the same day of a year before the range was made is skipped too
if !p.IsBlackoutDay("2020-12-25") || p.IsBlackoutDay("2027-12-24") {
t.Fatalf("a yearly range must match on month and day only")
}
// a range that is not yearly does not repeat
p.BlackoutDates = nullable.NewNullableWithValue([]model.ProgramBlackout{{From: "2024-12-25", To: "2024-12-25"}})
if p.IsBlackoutDay("2026-12-25") {
t.Fatalf("a one time range must not repeat")
}
}
func TestYearlyBlackoutAcrossNewYear(t *testing.T) {
p := &model.Program{
BlackoutDates: nullable.NewNullableWithValue([]model.ProgramBlackout{
{From: "2024-12-24", To: "2025-01-01", Yearly: true},
}),
}
for _, d := range []string{"2026-12-24", "2026-12-31", "2027-01-01", "2030-12-28"} {
if !p.IsBlackoutDay(d) {
t.Errorf("%s should be skipped", d)
}
}
for _, d := range []string{"2026-12-23", "2027-01-02", "2027-06-15"} {
if p.IsBlackoutDay(d) {
t.Errorf("%s should not be skipped", d)
}
}
// a send on Dec 27 moves past the new year to Jan 2
now := time.Date(2026, 12, 27, 10, 0, 0, 0, time.UTC)
want := time.Date(2027, 1, 2, 0, 0, 0, 0, time.UTC)
if got := programNextWindowSlot(p, now); !got.Equal(want) {
t.Fatalf("expected %v, got %v", want, got)
}
// with a Monday only window, Monday Dec 28 2026 is skipped and Monday
// Jan 4 2027 is next
w := windowProgram(t)
w.BlackoutDates = p.BlackoutDates
got := programNextWindowSlot(w, time.Date(2026, 12, 22, 10, 0, 0, 0, time.UTC))
if want := time.Date(2027, 1, 4, 9, 0, 0, 0, time.UTC); !got.Equal(want) {
t.Fatalf("expected %v, got %v", want, got)
}
// picks over a spread across the holidays never land on a skipped day
w.StepIntervalMinutes = nullable.NewNullableWithValue(21 * 24 * 60)
w.SpreadMinutes = nullable.NewNullableWithValue(21 * 24 * 60)
roundStart := time.Date(2026, 12, 20, 0, 0, 0, 0, time.UTC)
rng := rand.New(rand.NewSource(5))
for i := 0; i < 200; i++ {
got := programPickSendTime(w, roundStart, roundStart, rng)
if w.IsBlackoutDay(got.Format(model.ProgramDateLayout)) {
t.Fatalf("pick %v is on a skipped day", got)
}
}
}
func TestBlackoutValidation(t *testing.T) {
name := nullable.NewNullableWithValue(*vo.NewString64Must("p"))
cases := []struct {
ranges []model.ProgramBlackout
ok bool
}{
{[]model.ProgramBlackout{{From: "2024-01-01", To: "2024-01-02"}}, true},
{[]model.ProgramBlackout{{From: "2024-01-02", To: "2024-01-02"}}, true},
{[]model.ProgramBlackout{{From: "2024-01-03", To: "2024-01-02"}}, false},
{[]model.ProgramBlackout{{From: "2024-1-3", To: "2024-01-04"}}, false},
{[]model.ProgramBlackout{{From: "", To: "2024-01-04"}}, false},
{[]model.ProgramBlackout{{From: "2024-12-24", To: "2025-01-01", Yearly: true}}, true},
{[]model.ProgramBlackout{{From: "2024-01-01", To: "2024-12-30", Yearly: true}}, true},
// a yearly range that covers every day of the year is refused
{[]model.ProgramBlackout{{From: "2024-01-01", To: "2024-12-31", Yearly: true}}, false},
{[]model.ProgramBlackout{{From: "2024-06-01", To: "2025-06-01", Yearly: true}}, false},
{[]model.ProgramBlackout{{From: "2024-12-26", To: "2024-12-25", Yearly: true}}, false},
// shorter than a year only because the next year has Feb 29, every other
// year it covers every day
{[]model.ProgramBlackout{{From: "2023-03-01", To: "2024-02-28", Yearly: true}}, false},
// Feb 28 stays free every year
{[]model.ProgramBlackout{{From: "2023-03-01", To: "2024-02-27", Yearly: true}}, true},
// a one off range covers at most a year
{[]model.ProgramBlackout{{From: "2027-01-01", To: "2027-12-31"}}, true},
{[]model.ProgramBlackout{{From: "2028-01-01", To: "2028-12-31"}}, true},
{[]model.ProgramBlackout{{From: "2027-01-01", To: "2028-01-01"}}, false},
{[]model.ProgramBlackout{{From: "2027-01-01", To: "2029-12-31"}}, false},
}
for i, c := range cases {
p := &model.Program{Name: name, BlackoutDates: nullable.NewNullableWithValue(c.ranges)}
if err := p.Validate(); (err == nil) != c.ok {
t.Errorf("case %d: err = %v, want ok = %v", i, err, c.ok)
}
}
tooMany := make([]model.ProgramBlackout, model.ProgramBlackoutMax+1)
for i := range tooMany {
tooMany[i] = model.ProgramBlackout{From: "2024-01-01", To: "2024-01-01"}
}
p := &model.Program{Name: name, BlackoutDates: nullable.NewNullableWithValue(tooMany)}
if err := p.Validate(); err == nil {
t.Fatal("more than the max blackout ranges should fail")
}
}
func TestLoopOpenersExcludeLastStep(t *testing.T) {
a, b, c := uuid.New(), uuid.New(), uuid.New()
steps := []*model.ProgramStep{
{ID: nullable.NewNullableWithValue(a), Position: nullable.NewNullableWithValue(0)},
{ID: nullable.NewNullableWithValue(b), Position: nullable.NewNullableWithValue(1)},
{ID: nullable.NewNullableWithValue(c), Position: nullable.NewNullableWithValue(2)},
}
shuffle := &model.Program{OrderMode: nullable.NewNullableWithValue(model.ProgramOrderShuffle)}
preferred, fallback := programLoopOpeners(shuffle, steps, &b)
if len(preferred) != 2 || len(fallback) != 1 || fallback[0].ID.MustGet() != b {
t.Fatalf("expected last step in fallback only, got %d preferred %d fallback", len(preferred), len(fallback))
}
for _, p := range preferred {
if p.ID.MustGet() == b {
t.Fatal("last step must not be preferred")
}
}
rng := rand.New(rand.NewSource(9))
for i := 0; i < 100; i++ {
if programPickStep(shuffle, preferred, rng).ID.MustGet() == b {
t.Fatal("a new loop opened with the step sent last")
}
}
// one step only: it is still sent
preferred, fallback = programLoopOpeners(shuffle, steps[:1], &a)
if len(preferred) != 1 || fallback != nil {
t.Fatal("a single step must stay preferred")
}
// sequential order keeps everything
sequential := &model.Program{OrderMode: nullable.NewNullableWithValue(model.ProgramOrderSequential)}
preferred, fallback = programLoopOpeners(sequential, steps, &b)
if len(preferred) != 3 || fallback != nil {
t.Fatal("sequential order must not exclude a step")
}
// no earlier send keeps everything
preferred, fallback = programLoopOpeners(shuffle, steps, nil)
if len(preferred) != 3 || fallback != nil {
t.Fatal("first loop must not exclude a step")
}
}
func TestProgramStatus(t *testing.T) {
now := time.Date(2024, 1, 8, 9, 0, 0, 0, time.UTC)
p := &model.Program{StartAt: nullable.NewNullNullable[time.Time]()}
if s := p.StatusAt(now); s != model.ProgramStatusDraft {
t.Fatalf("got %s", s)
}
p.StartAt = nullable.NewNullableWithValue(now.Add(time.Hour))
if s := p.StatusAt(now); s != model.ProgramStatusScheduled {
t.Fatalf("got %s", s)
}
p.StartAt = nullable.NewNullableWithValue(now)
if s := p.StatusAt(now); s != model.ProgramStatusActive {
t.Fatalf("got %s", s)
}
p.PausedAt = nullable.NewNullableWithValue(now)
if s := p.StatusAt(now); s != model.ProgramStatusPaused {
t.Fatalf("got %s", s)
}
p.ClosedAt = nullable.NewNullableWithValue(now)
if s := p.StatusAt(now); s != model.ProgramStatusClosed {
t.Fatalf("got %s", s)
}
}
// TestLongBlackoutHoldsUntilItEnds checks a send is held until skip ranges
// that run longer than one look ahead have ended, and never lands on a skip
// day: Monday to Friday 09:00 to 17:00 with 2027-01-01 to 2029-12-31 skipped,
// as one range saved before the one year cap and as three ranges of a year
func TestLongBlackoutHoldsUntilItEnds(t *testing.T) {
window := func(ranges []model.ProgramBlackout) *model.Program {
return &model.Program{
// weekday bitmask: monday 2 to friday 32
ConstraintWeekDays: nullable.NewNullableWithValue(*vo.NewCampaignWeekDaysMust(2 | 4 | 8 | 16 | 32)),
ConstraintStartTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("09:00")),
ConstraintEndTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("17:00")),
BlackoutDates: nullable.NewNullableWithValue(ranges),
}
}
programs := map[string]*model.Program{
"one range": window([]model.ProgramBlackout{{From: "2027-01-01", To: "2029-12-31"}}),
"three ranges": window([]model.ProgramBlackout{
{From: "2027-01-01", To: "2027-12-31"},
{From: "2028-01-01", To: "2028-12-31"},
{From: "2029-01-01", To: "2029-12-31"},
}),
}
// 2030-01-01 is a Tuesday
want := time.Date(2030, 1, 1, 9, 0, 0, 0, time.UTC)
for name, p := range programs {
for _, now := range []time.Time{
time.Date(2026, 12, 31, 18, 0, 0, 0, time.UTC),
time.Date(2027, 1, 4, 10, 0, 0, 0, time.UTC),
time.Date(2028, 6, 1, 10, 0, 0, 0, time.UTC),
} {
got := programNextWindowSlot(p, now)
if !got.Equal(want) {
t.Fatalf("%s from %v: expected %v, got %v", name, now, want, got)
}
}
rng := rand.New(rand.NewSource(7))
roundStart := time.Date(2026, 12, 28, 0, 0, 0, 0, time.UTC)
for i := 0; i < 50; i++ {
got := programPickSendTime(p, roundStart, time.Date(2027, 1, 2, 0, 0, 0, 0, time.UTC), rng)
if p.IsBlackoutDay(got.Format(model.ProgramDateLayout)) {
t.Fatalf("%s: pick %v is on a skip day", name, got)
}
}
}
}
// TestProgramSendDayLookAheadMatches checks the save check of the skip ranges
// looks as far ahead as the scheduler looks for a window opening
func TestProgramSendDayLookAheadMatches(t *testing.T) {
if programSlotMaxDays*programSlotMaxSearches != model.ProgramSendDayLookAheadDays {
t.Fatalf("look ahead %d days, the save check %d", programSlotMaxDays*programSlotMaxSearches, model.ProgramSendDayLookAheadDays)
}
}
// workWeekProgram sends Monday to Friday 09:00 to 17:00 UTC, a new template
// every two weeks spread over one day
func workWeekProgram() *model.Program {
return &model.Program{
// weekday bits: sunday 1, monday 2 ... saturday 64
ConstraintWeekDays: nullable.NewNullableWithValue(*vo.NewCampaignWeekDaysMust(2 + 4 + 8 + 16 + 32)),
ConstraintStartTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("09:00")),
ConstraintEndTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("17:00")),
StepIntervalMinutes: nullable.NewNullableWithValue(14 * 24 * 60),
SpreadMinutes: nullable.NewNullableWithValue(24 * 60),
}
}
// TestPickSendTimeSpreadsOverNextSendingHours checks a round that starts
// outside the sending hours or just before they end is spread over the next
// sending hours instead of sending everyone at the next opening
func TestPickSendTimeSpreadsOverNextSendingHours(t *testing.T) {
p := workWeekProgram()
rng := rand.New(rand.NewSource(7))
monday9 := time.Date(2024, 1, 8, 9, 0, 0, 0, time.UTC)
monday17 := time.Date(2024, 1, 8, 17, 0, 0, 0, time.UTC)
// resumed on Friday 18:00, after the sending hours
friday18 := time.Date(2024, 1, 5, 18, 0, 0, 0, time.UTC)
hours := map[int]bool{}
atOpening := 0
for i := 0; i < 500; i++ {
got := programPickSendTimeAfter(p, friday18, friday18, time.Time{}, rng)
if got.Before(monday9) || !got.Before(monday17) {
t.Fatalf("send %v is outside the Monday sending hours", got)
}
if got.Equal(monday9) {
atOpening++
}
hours[got.Hour()] = true
}
if len(hours) != 8 || atOpening > 5 {
t.Fatalf("sends are not spread over Monday: %d distinct hours, %d at the opening", len(hours), atOpening)
}
// resumed on Friday 16:50, ten minutes before the sending hours end
friday1650 := time.Date(2024, 1, 5, 16, 50, 0, 0, time.UTC)
friday17 := time.Date(2024, 1, 5, 17, 0, 0, 0, time.UTC)
onFriday, onMonday := 0, 0
for i := 0; i < 500; i++ {
got := programPickSendTimeAfter(p, friday1650, friday1650, time.Time{}, rng)
switch {
case !got.Before(friday1650) && got.Before(friday17):
onFriday++
case !got.Before(monday9) && got.Before(monday17):
onMonday++
default:
t.Fatalf("send %v is outside the sending hours", got)
}
}
// the round holds eight sending hours, ten minutes of them on Friday
if onFriday == 0 || onFriday > 40 || onMonday < 450 {
t.Fatalf("expected most sends on Monday, got %d on Friday and %d on Monday", onFriday, onMonday)
}
// a round that starts at the opening keeps its own day
tuesday9 := time.Date(2024, 1, 9, 9, 0, 0, 0, time.UTC)
for i := 0; i < 200; i++ {
got := programPickSendTimeAfter(p, tuesday9, tuesday9, time.Time{}, rng)
if got.Before(tuesday9) || !got.Before(tuesday9.Add(8*time.Hour)) {
t.Fatalf("send %v left the Tuesday sending hours", got)
}
}
}
// windowProgram builds a program with a Monday only 09:00-17:00 delivery window.
func windowProgram(t *testing.T) *model.Program {
t.Helper()
// weekday bitmask: monday = 2
return &model.Program{
ConstraintWeekDays: nullable.NewNullableWithValue(*vo.NewCampaignWeekDaysMust(2)),
ConstraintStartTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("09:00")),
ConstraintEndTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("17:00")),
}
}
// TestNextWindowSlot checks the next window opening of a Monday 09:00 to
// 17:00 window, and that a program without a window sends now
func TestNextWindowSlot(t *testing.T) {
cases := []struct {
name string
program *model.Program
now time.Time
want time.Time
}{
// no window returns now
{"no window", &model.Program{}, time.Date(2024, 6, 1, 12, 0, 0, 0, time.UTC), time.Date(2024, 6, 1, 12, 0, 0, 0, time.UTC)},
// 2024-01-01 is a Monday, 08:00 is before the 09:00 window opening
{"before the window", windowProgram(t), time.Date(2024, 1, 1, 8, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 9, 0, 0, 0, time.UTC)},
// Monday 18:00 is past the window, only Monday is allowed
{"after the window", windowProgram(t), time.Date(2024, 1, 1, 18, 0, 0, 0, time.UTC), time.Date(2024, 1, 8, 9, 0, 0, 0, time.UTC)},
{"inside the window", windowProgram(t), time.Date(2024, 1, 1, 10, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 10, 0, 0, 0, time.UTC)},
}
for _, c := range cases {
if got := programNextWindowSlot(c.program, c.now); !got.Equal(c.want) {
t.Fatalf("%s: expected slot at %v, got %v", c.name, c.want, got)
}
}
}
func TestWindowUsesProgramTimeZone(t *testing.T) {
p := windowProgram(t)
p.TimeZone = nullable.NewNullableWithValue("Europe/Copenhagen")
// Monday 07:30 UTC is 08:30 in Copenhagen (winter), before the 09:00 opening
now := time.Date(2024, 1, 1, 7, 30, 0, 0, time.UTC)
want := time.Date(2024, 1, 1, 8, 0, 0, 0, time.UTC)
if got := programNextWindowSlot(p, now); !got.Equal(want) {
t.Fatalf("expected 09:00 Copenhagen (%v), got %v", want, got)
}
// Sunday 23:30 UTC is already Monday 00:30 in Copenhagen
sunday := time.Date(2023, 12, 31, 23, 30, 0, 0, time.UTC)
if got := programNextWindowSlot(p, sunday); !got.Equal(want) {
t.Fatalf("weekday must be read in the program zone, got %v", got)
}
}
func TestPickSendTimeSpreadsInsideWindow(t *testing.T) {
p := windowProgram(t)
// a Monday only window and a one week spread leave exactly one 8 hour span
p.StepIntervalMinutes = nullable.NewNullableWithValue(7 * 24 * 60)
p.SpreadMinutes = nullable.NewNullableWithValue(7 * 24 * 60)
roundStart := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
rng := rand.New(rand.NewSource(1))
open := time.Date(2024, 1, 1, 9, 0, 0, 0, time.UTC)
close := time.Date(2024, 1, 1, 17, 0, 0, 0, time.UTC)
distinct := map[time.Time]bool{}
for i := 0; i < 200; i++ {
got := programPickSendTime(p, roundStart, roundStart, rng)
if got.Before(open) || !got.Before(close) {
t.Fatalf("send time %v outside the window", got)
}
distinct[got.Truncate(time.Hour)] = true
}
if len(distinct) < 6 {
t.Fatalf("send times are not spread over the window, %d distinct hours", len(distinct))
}
}
func TestPickSendTimeWithoutSpreadIsNextSlot(t *testing.T) {
p := windowProgram(t)
now := time.Date(2024, 1, 1, 8, 0, 0, 0, time.UTC)
got := programPickSendTime(p, now, now, rand.New(rand.NewSource(1)))
if want := time.Date(2024, 1, 1, 9, 0, 0, 0, time.UTC); !got.Equal(want) {
t.Fatalf("no spread should use the next window opening %v, got %v", want, got)
}
}
func TestNextRoundStartAfterLongPauseStartsNow(t *testing.T) {
p := &model.Program{
StepIntervalMinutes: nullable.NewNullableWithValue(60),
SpreadMinutes: nullable.NewNullableWithValue(30),
}
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
if got := programNextRoundStart(p, start, start.Add(10*time.Minute)); !got.Equal(start.Add(time.Hour)) {
t.Fatalf("next round should start one interval later, got %v", got)
}
late := start.Add(48 * time.Hour)
if got := programNextRoundStart(p, start, late); !got.Equal(late) {
t.Fatalf("an overdue round should start now, got %v", got)
}
}
func TestPickStepOrder(t *testing.T) {
mk := func(pos int) *model.ProgramStep {
return &model.ProgramStep{Position: nullable.NewNullableWithValue(pos)}
}
steps := []*model.ProgramStep{mk(2), mk(0), mk(1)}
seq := &model.Program{OrderMode: nullable.NewNullableWithValue(model.ProgramOrderSequential)}
if got := programPickStep(seq, steps, nil); got != steps[1] {
t.Fatalf("sequential should take the lowest position")
}
shuffle := &model.Program{OrderMode: nullable.NewNullableWithValue(model.ProgramOrderShuffle)}
rng := rand.New(rand.NewSource(7))
seen := map[*model.ProgramStep]bool{}
for i := 0; i < 50; i++ {
seen[programPickStep(shuffle, steps, rng)] = true
}
if len(seen) != 3 {
t.Fatalf("shuffle should reach every step, got %d", len(seen))
}
if programPickStep(shuffle, nil, rng) != nil {
t.Fatalf("no candidates should give nil")
}
}
// TestRoundStartKeepsWallClockOverClockChange checks an interval of whole days
// moves a round start by calendar days in the program zone
func TestRoundStartKeepsWallClockOverClockChange(t *testing.T) {
loc, err := time.LoadLocation("Europe/Copenhagen")
if err != nil {
t.Skip("no zone data")
}
program := &model.Program{}
program.TimeZone.Set("Europe/Copenhagen")
program.StepIntervalMinutes.Set(7 * 24 * 60)
start := time.Date(2026, 3, 23, 9, 0, 0, 0, loc).UTC()
next := programNextRoundStart(program, start, start)
if got := next.In(loc); got.Hour() != 9 || got.Day() != 30 {
t.Fatalf("expected 09:00 a week later, got %v", got)
}
program.StepIntervalMinutes.Set(36 * 60)
if got := programNextRoundStart(program, start, start); !got.Equal(start.Add(36 * time.Hour)) {
t.Fatalf("an interval that is not whole days is a fixed duration, got %v", got)
}
}
// copenhagenWindow is a program sending every day 09:00 to 17:00 in Copenhagen
func copenhagenWindow(t *testing.T) (*model.Program, *time.Location) {
t.Helper()
loc, err := time.LoadLocation("Europe/Copenhagen")
if err != nil {
t.Skip("no zone data")
}
return &model.Program{
TimeZone: nullable.NewNullableWithValue("Europe/Copenhagen"),
ConstraintWeekDays: nullable.NewNullableWithValue(*vo.NewCampaignWeekDaysMust(127)),
ConstraintStartTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("09:00")),
ConstraintEndTime: nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("17:00")),
}, loc
}
// TestProgramWindowAcrossDaylightSaving checks the window keeps its wall clock
// hours on the days the clocks change in spring and in autumn
func TestProgramWindowAcrossDaylightSaving(t *testing.T) {
p, loc := copenhagenWindow(t)
for _, day := range []time.Time{
// spring forward, 02:00 becomes 03:00
time.Date(2026, 3, 29, 0, 0, 0, 0, loc),
// fall back, 03:00 becomes 02:00
time.Date(2026, 10, 25, 0, 0, 0, 0, loc),
} {
spans := programWindowSpans(p, day, day.AddDate(0, 0, 1))
if len(spans) != 1 {
t.Fatalf("%v: expected one window, got %d", day, len(spans))
}
start, end := spans[0].start.In(loc), spans[0].end.In(loc)
if start.Hour() != 9 || start.Minute() != 0 || end.Hour() != 17 || end.Minute() != 0 {
t.Fatalf("%v: window %v to %v, want 09:00 to 17:00", day, start, end)
}
if spans[0].end.Sub(spans[0].start) != 8*time.Hour {
t.Fatalf("%v: the window must last 8 hours", day)
}
// a time before the window opens on that day moves to 09:00 local
early := time.Date(day.Year(), day.Month(), day.Day(), 4, 0, 0, 0, loc)
if got := programNextWindowSlot(p, early).In(loc); got.Hour() != 9 || got.Day() != day.Day() {
t.Fatalf("%v: next slot %v, want 09:00 that day", day, got)
}
// every drawn time over a spread across the change stays in the window
rng := rand.New(rand.NewSource(1))
p.SpreadMinutes = nullable.NewNullableWithValue(3 * 24 * 60)
roundStart := day.AddDate(0, 0, -1)
for i := 0; i < 200; i++ {
got := programPickSendTime(p, roundStart, roundStart, rng).In(loc)
if got.Hour() < 9 || got.Hour() >= 17 {
t.Fatalf("%v: drawn time %v is outside the window", day, got)
}
}
}
}
// TestProgramTimeZoneAllowlist checks a program takes the same zones as a
// campaign, so the server zone is refused
func TestProgramTimeZoneAllowlist(t *testing.T) {
for zone, ok := range map[string]bool{
"Europe/Copenhagen": true,
"UTC": true,
"Local": false,
"localtime": false,
"": false,
"Factory": false,
} {
p := &model.Program{}
p.Name.Set(*vo.NewString64Must("zone"))
p.TimeZone = nullable.NewNullableWithValue(zone)
if err := p.Validate(); (err == nil) != ok {
t.Fatalf("zone %q: accepted %v, want %v (%v)", zone, err == nil, ok, err)
}
}
}
// TestProgramWindowEndOfDay checks an end of 23:59 runs to midnight, so an all
// day window has no closed minute between days
func TestProgramWindowEndOfDay(t *testing.T) {
p, loc := copenhagenWindow(t)
p.ConstraintStartTime = nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("00:00"))
p.ConstraintEndTime = nullable.NewNullableWithValue(*vo.NewCampaignTimeConstraintMust("23:59"))
day := time.Date(2026, 6, 10, 0, 0, 0, 0, loc)
spans := programWindowSpans(p, day, day.AddDate(0, 0, 2))
if len(spans) != 2 {
t.Fatalf("expected two day spans, got %d", len(spans))
}
if !spans[0].end.Equal(day.AddDate(0, 0, 1)) || !spans[1].start.Equal(spans[0].end) {
t.Fatalf("days must meet at midnight: %v to %v, then %v", spans[0].start, spans[0].end, spans[1].start)
}
lastMinute := time.Date(2026, 6, 10, 23, 59, 30, 0, loc)
if got := programNextWindowSlot(p, lastMinute); !got.Equal(lastMinute) {
t.Fatalf("23:59:30 must be inside the window, next slot %v", got)
}
}