package repository import ( "context" "path/filepath" "sort" "testing" "time" "github.com/google/uuid" "github.com/oapi-codegen/nullable" "github.com/phishingclub/phishingclub/database" "github.com/phishingclub/phishingclub/model" "github.com/phishingclub/phishingclub/testdb" "github.com/phishingclub/phishingclub/utils" "github.com/phishingclub/phishingclub/vo" "gorm.io/gorm" "gorm.io/gorm/clause" ) func newProgramTestDB(t *testing.T, more ...testdb.Step) *gorm.DB { t.Helper() return newProgramTestDBExecMode(t, "", more...) } // newProgramTestDBExecMode is newProgramTestDB with the pgx query exec mode // on postgres, see testdb.OpenWithExecMode func newProgramTestDBExecMode(t *testing.T, execMode string, more ...testdb.Step) *gorm.DB { t.Helper() dsn := filepath.Join(t.TempDir(), "program.db") + "?_foreign_keys=OFF&_busy_timeout=5000" db, err := testdb.OpenMigratedWithExecMode(t, dsn, execMode, testdb.Migration{Steps: []testdb.Step{ testdb.AutoMigrate( &database.Campaign{}, &database.CampaignLanguageRoute{}, &database.CampaignRecipient{}, &database.CampaignEvent{}, &database.Program{}, &database.ProgramLanguageRoute{}, &database.ProgramStep{}, &database.ProgramCampaign{}, &database.ProgramRecipientGroup{}, &database.ProgramEnrollment{}, &database.ProgramAllowDeny{}, &database.ProgramWebhook{}, &database.CampaignTemplate{}, &database.CampaignTemplateLanguage{}, &database.ResourceTag{}, &database.Recipient{}, &database.Event{}, ), }}.With(more...)) if err != nil { t.Fatalf("open sqlite: %v", err) } return db } func ptrUUID() *uuid.UUID { id := uuid.New() return &id } func ptrNow() *time.Time { now := time.Now() return &now } func createProgram(t *testing.T, db *gorm.DB, name string, companyID *uuid.UUID) *uuid.UUID { t.Helper() id := ptrUUID() started := time.Now().Add(-time.Hour).UTC() row := &database.Program{ID: id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: name, CompanyID: companyID, StartAt: &started} if err := db.Create(row).Error; err != nil { t.Fatalf("create program: %v", err) } return id } func createStep(t *testing.T, db *gorm.DB, programID, templateID *uuid.UUID, position int) *uuid.UUID { t.Helper() id := ptrUUID() row := &database.ProgramStep{ ID: id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), ProgramID: programID, CampaignTemplateID: templateID, Position: position, } if err := db.Create(row).Error; err != nil { t.Fatalf("create step: %v", err) } return id } func linkCampaign(t *testing.T, db *gorm.DB, programID, stepID *uuid.UUID, loop int) *uuid.UUID { t.Helper() campaignID := ptrUUID() row := &database.ProgramCampaign{ ID: ptrUUID(), CreatedAt: ptrNow(), ProgramID: programID, ProgramStepID: stepID, LoopIndex: loop, CampaignID: campaignID, } if err := db.Create(row).Error; err != nil { t.Fatalf("link campaign: %v", err) } return campaignID } func createHiddenCampaign(t *testing.T, db *gorm.DB, id, programID *uuid.UUID) { t.Helper() row := &database.Campaign{ ID: id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: "campaign " + id.String(), ProgramID: programID, } if err := db.Create(row).Error; err != nil { t.Fatalf("create campaign: %v", err) } } func addCampaignRecipient(t *testing.T, db *gorm.DB, campaignID, recipientID, anonymizedID *uuid.UUID, sent bool) *uuid.UUID { t.Helper() id := ptrUUID() row := &database.CampaignRecipient{ ID: id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), CampaignID: campaignID, RecipientID: recipientID, AnonymizedID: anonymizedID, } if err := db.Create(row).Error; err != nil { t.Fatalf("add campaign recipient: %v", err) } // the app stores sent_at as RFC 3339 UTC text, so write it the same way if sent { if err := db.Model(&database.CampaignRecipient{}).Where("id = ?", id). Update("sent_at", utils.NowRFC3339UTC()).Error; err != nil { t.Fatalf("set sent_at: %v", err) } } return id } func addEvent(t *testing.T, db *gorm.DB, campaignID, recipientID, anonymizedID, eventID *uuid.UUID) { t.Helper() row := &database.CampaignEvent{ ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(), CampaignID: campaignID, RecipientID: recipientID, AnonymizedID: anonymizedID, EventID: eventID, } if err := db.Create(row).Error; err != nil { t.Fatalf("add event: %v", err) } } // addEvents stores n events of one type for a campaign, each for a new person func addEvents(t *testing.T, db *gorm.DB, campaignID, eventID *uuid.UUID, n int) { t.Helper() rows := make([]*database.CampaignEvent, 0, n) for i := 0; i < n; i++ { rows = append(rows, &database.CampaignEvent{ ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(), CampaignID: campaignID, RecipientID: ptrUUID(), EventID: eventID, }) } if err := db.CreateInBatches(rows, 500).Error; err != nil { t.Fatalf("add events: %v", err) } } // addSends stores n sends not yet sent for a campaign and returns their ids func addSends(t *testing.T, db *gorm.DB, campaignID *uuid.UUID, n int) []*uuid.UUID { t.Helper() rows := make([]*database.CampaignRecipient, 0, n) ids := make([]*uuid.UUID, 0, n) for i := 0; i < n; i++ { id := ptrUUID() ids = append(ids, id) rows = append(rows, &database.CampaignRecipient{ ID: id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), CampaignID: campaignID, RecipientID: ptrUUID(), }) } if err := db.CreateInBatches(rows, 500).Error; err != nil { t.Fatalf("add sends: %v", err) } return ids } func countWhere(t *testing.T, db *gorm.DB, table any, column string, value any) int64 { t.Helper() var n int64 if err := db.Model(table).Where(clause.Eq{Column: clause.Column{Name: column}, Value: value}).Count(&n).Error; err != nil { t.Fatalf("count: %v", err) } return n } // TestProgramIDEqNilMatchesNothing checks a nil program id matches no row, so // it can never select the campaigns that belong to no program func TestProgramIDEqNilMatchesNothing(t *testing.T) { db := newProgramTestDB(t) now := time.Now().UTC() id := uuid.New() if err := db.Create(&database.Campaign{ID: &id, CreatedAt: &now, UpdatedAt: &now, Name: "normal"}).Error; err != nil { t.Fatalf("create campaign: %v", err) } var n int64 if err := db.Model(&database.Campaign{}). Where(programIDEq(clause.Column{Name: "program_id"}, nil)).Count(&n).Error; err != nil { t.Fatalf("count: %v", err) } if n != 0 { t.Fatalf("a nil program id matched %d campaigns", n) } ids, err := (&Program{DB: db}).GetCampaignIDs(t.Context(), nil) if err != nil || len(ids) != 0 { t.Fatalf("campaigns of a nil program: %v %v", ids, err) } } // TestProgramSearchMatchesWildcardsAsText checks the program search matches // an underscore, a percent sign and a backslash as written func TestProgramSearchMatchesWildcardsAsText(t *testing.T) { db := newProgramTestDB(t) ctx := context.Background() r := &Program{DB: db} now := time.Now().UTC() names := []string{"Q1_2026", "Q1 2026", "Q1X2026", "100% done", "1000 done", `a\b`, "ab"} byName := map[string]bool{} for _, n := range names { statusProgram(t, db, n, nil, nil, nil, nil) } for search, want := range map[string][]string{ "Q1_2026": {"Q1_2026"}, "100%": {"100% done"}, `a\b`: {`a\b`}, "Q1": {"Q1_2026", "Q1 2026", "Q1X2026"}, } { list, err := r.GetAll(ctx, nil, &ProgramOption{QueryArgs: &vo.QueryArgs{Search: search}}, now) if err != nil { t.Fatalf("%s: %v", search, err) } clear(byName) for _, p := range list.Rows { byName[p.Name.MustGet().String()] = true } if len(byName) != len(want) { t.Fatalf("%q: got %v, want %v", search, byName, want) } for _, n := range want { if !byName[n] { t.Fatalf("%q: got %v, want %v", search, byName, want) } } } } // stepRows returns the step rows of a program by position func stepRows(t *testing.T, db *gorm.DB, programID *uuid.UUID) []database.ProgramStep { t.Helper() rows := []database.ProgramStep{} if err := db.Where("program_id = ?", programID).Order("position").Find(&rows).Error; err != nil { t.Fatalf("steps: %v", err) } return rows } // TestProgramReplaceSteps checks a step keeps its id while it keeps its // template, steps may swap places under the unique position index, a new // template is a new step and a step left out is removed func TestProgramReplaceSteps(t *testing.T) { db := newProgramTestDB(t) ctx := context.Background() r := &Program{DB: db} programID := createProgram(t, db, "replace", nil) tA, tB, tC := ptrUUID(), ptrUUID(), ptrUUID() stepA := createStep(t, db, programID, tA, 0) stepB := createStep(t, db, programID, tB, 1) keep := func(id, template *uuid.UUID, position int) *model.ProgramStep { s := &model.ProgramStep{ CampaignTemplateID: nullable.NewNullableWithValue(*template), Position: nullable.NewNullableWithValue(position), } if id != nil { s.ID = nullable.NewNullableWithValue(*id) } return s } // swap A and B if err := r.ReplaceSteps(ctx, programID, []*model.ProgramStep{keep(stepB, tB, 0), keep(stepA, tA, 1)}); err != nil { t.Fatalf("swap: %v", err) } rows := stepRows(t, db, programID) if len(rows) != 2 || *rows[0].ID != *stepB || *rows[1].ID != *stepA { t.Fatalf("swap kept ids in new order: %+v", rows) } // keep B, drop A, add C, and give B's id with A's template, which is a new step if err := r.ReplaceSteps(ctx, programID, []*model.ProgramStep{ keep(stepB, tB, 0), keep(nil, tC, 1), keep(stepB, tA, 2), }); err != nil { t.Fatalf("replace: %v", err) } rows = stepRows(t, db, programID) if len(rows) != 3 { t.Fatalf("expected 3 steps, got %d", len(rows)) } if *rows[0].ID != *stepB || *rows[1].CampaignTemplateID != *tC || *rows[2].CampaignTemplateID != *tA { t.Fatalf("unexpected steps: %+v", rows) } if *rows[2].ID == *stepA || *rows[2].ID == *stepB { t.Fatal("a step id given with another template must be a new step") } for _, row := range rows { if row.Position < 0 { t.Fatalf("a position was left out of the way: %+v", row) } } // an empty list removes every step if err := r.ReplaceSteps(ctx, programID, []*model.ProgramStep{}); err != nil { t.Fatalf("clear: %v", err) } if rows := stepRows(t, db, programID); len(rows) != 0 { t.Fatalf("steps left: %d", len(rows)) } } // TestProgramInsertWithChildren checks a program is stored with its steps, // groups and settings, and nothing is stored when a child write fails func TestProgramInsertWithChildren(t *testing.T) { db := newProgramTestDB(t) ctx := context.Background() r := &Program{DB: db} template, group, filter, hook := ptrUUID(), ptrUUID(), ptrUUID(), uuid.New() program := &model.Program{Name: nullable.NewNullableWithValue(*vo.NewString64Must("with children"))} children := &ProgramChildren{ Steps: []*model.ProgramStep{{ CampaignTemplateID: nullable.NewNullableWithValue(*template), }}, RecipientGroupIDs: []*uuid.UUID{group, group}, AllowDenyIDs: []*uuid.UUID{filter}, Webhooks: []*model.CampaignWebhook{{WebhookID: nullable.NewNullableWithValue(hook)}}, } id, err := r.Insert(ctx, program, children) if err != nil { t.Fatalf("insert: %v", err) } groups, _ := r.GetRecipientGroupIDs(ctx, id) filters, _ := r.GetAllowDenyIDs(ctx, id) hooks, _ := r.GetWebhooks(ctx, id) if len(stepRows(t, db, id)) != 1 || len(groups) != 1 || len(filters) != 1 || len(hooks) != 1 { t.Fatalf("children: groups %d filters %d hooks %d", len(groups), len(filters), len(hooks)) } // a failing child write rolls the program row back if err := db.Migrator().DropTable(&database.ProgramWebhook{}); err != nil { t.Fatalf("drop: %v", err) } program.Name = nullable.NewNullableWithValue(*vo.NewString64Must("rolled back")) if _, err := r.Insert(ctx, program, children); err == nil { t.Fatal("expected the insert to fail") } var count int64 db.Model(&database.Program{}).Where("name = ?", "rolled back").Count(&count) if count != 0 { t.Fatal("a program must not be stored without its children") } var stepCount int64 db.Model(&database.ProgramStep{}).Count(&stepCount) if stepCount != 1 { t.Fatalf("steps of the failed insert must be rolled back, got %d", stepCount) } } // TestProgramClosedReleasesGroupsAndTemplates checks a closed program does not // block deleting its group or template, and the removal helpers only touch // closed programs func TestProgramClosedReleasesGroupsAndTemplates(t *testing.T) { db := newProgramTestDB(t) ctx := context.Background() r := &Program{DB: db} now := time.Now() past := now.Add(-time.Hour) open := statusProgram(t, db, "open", &past, &past, nil, nil) closed := statusProgram(t, db, "closed", &past, &past, nil, &now) group, template := ptrUUID(), ptrUUID() for _, id := range []*uuid.UUID{open, closed} { createStep(t, db, id, template, 0) if err := db.Create(&database.ProgramRecipientGroup{ProgramID: id, RecipientGroupID: group}).Error; err != nil { t.Fatalf("group: %v", err) } } names, _ := r.GetNamesByRecipientGroupID(ctx, group) if len(names) != 1 || names[0] != "open" { t.Fatalf("group users: %v", names) } names, _ = r.GetNamesByCampaignTemplateID(ctx, template) if len(names) != 1 || names[0] != "open" { t.Fatalf("template users: %v", names) } if err := r.RemoveRecipientGroupFromClosedPrograms(ctx, group); err != nil { t.Fatalf("remove group: %v", err) } if err := r.RemoveCampaignTemplateFromClosedPrograms(ctx, template); err != nil { t.Fatalf("remove template: %v", err) } if ids, _ := r.GetRecipientGroupIDs(ctx, closed); len(ids) != 0 { t.Fatal("the closed program must lose the group") } if ids, _ := r.GetRecipientGroupIDs(ctx, open); len(ids) != 1 { t.Fatal("the open program must keep the group") } if len(stepRows(t, db, closed)) != 0 || len(stepRows(t, db, open)) != 1 { t.Fatal("only the closed program loses the step") } } // TestProgramAllowedColumnsExist checks every allowlisted sort column of the // program list and the people table exists, and a column outside the list is // refused func TestProgramAllowedColumnsExist(t *testing.T) { db := newProgramTestDB(t) ctx := context.Background() r := &Program{DB: db} programID := createProgram(t, db, "columns", nil) for _, col := range allowedProgramColumns { bare := col.Name if _, err := r.GetAll(ctx, nil, &ProgramOption{QueryArgs: &vo.QueryArgs{OrderBy: bare, Search: "x"}}, time.Now()); err != nil { t.Fatalf("order by %s: %v", bare, err) } } if _, err := r.GetAll(ctx, nil, &ProgramOption{QueryArgs: &vo.QueryArgs{OrderBy: "is_anonymous"}}, time.Now()); err == nil { t.Fatal("order by a column outside the allowlist must fail") } if err := db.AutoMigrate(&database.Recipient{}); err != nil { t.Fatalf("migrate: %v", err) } for _, col := range ProgramEnrollmentSortColumns { if _, _, err := r.GetEnrollmentPage(ctx, programID, &vo.QueryArgs{OrderBy: col, Search: "x"}); err != nil { t.Fatalf("people order by %s: %v", col, err) } } if _, _, err := r.GetEnrollmentPage(ctx, programID, &vo.QueryArgs{OrderBy: "`program_enrollments`.`anonymized_id`"}); err == nil { t.Fatal("people order by a column outside the allowlist must fail") } } // TestProgramListAllCompanies checks no company lists only the programs // without a company, unless AllCompanies is set, and that WithCompany loads // the company of each program func TestProgramListAllCompanies(t *testing.T) { db := newProgramTestDB(t) if err := db.AutoMigrate(&database.Company{}); err != nil { t.Fatalf("migrate company: %v", err) } ctx := context.Background() r := &Program{DB: db} company := &database.Company{ID: uuid.New(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: "acme", AssetsKey: "acme"} if err := db.Create(company).Error; err != nil { t.Fatalf("company: %v", err) } statusProgram(t, db, "shared", nil, nil, nil, nil) owned := statusProgram(t, db, "owned", nil, nil, nil, nil) if err := db.Model(&database.Program{}).Where("id = ?", owned).Update("company_id", company.ID).Error; err != nil { t.Fatalf("set company: %v", err) } now := time.Now() got, err := r.GetAll(ctx, nil, &ProgramOption{QueryArgs: &vo.QueryArgs{}}, now) if err != nil || len(got.Rows) != 1 || got.Rows[0].Name.MustGet().String() != "shared" { t.Fatalf("no company: %v %d", err, len(got.Rows)) } got, err = r.GetAll(ctx, nil, &ProgramOption{QueryArgs: &vo.QueryArgs{}, AllCompanies: true, WithCompany: true}, now) if err != nil || len(got.Rows) != 2 { t.Fatalf("all companies: %v", err) } for _, p := range got.Rows { if p.ID.MustGet() == *owned && (p.Company == nil || p.Company.Name.MustGet().String() != "acme") { t.Fatalf("company not loaded") } } // a given company is never widened by AllCompanies got, err = r.GetAll(ctx, &company.ID, &ProgramOption{QueryArgs: &vo.QueryArgs{}, AllCompanies: true}, now) if err != nil || len(got.Rows) != 1 || got.Rows[0].ID.MustGet() != *owned { t.Fatalf("one company: %v", err) } } // TestProgramLookups checks the id and name lookups used by program, company // and template deletion func TestProgramLookups(t *testing.T) { db := newProgramTestDB(t) ctx := context.Background() r := &Program{DB: db} companyID := ptrUUID() templateID := ptrUUID() p1 := createProgram(t, db, "beta", companyID) p2 := createProgram(t, db, "alpha", companyID) p3 := createProgram(t, db, "global", nil) s1 := createStep(t, db, p1, templateID, 0) createStep(t, db, p1, templateID, 1) createStep(t, db, p2, templateID, 0) createStep(t, db, p3, ptrUUID(), 0) c1 := linkCampaign(t, db, p1, s1, 0) c2 := linkCampaign(t, db, p1, s1, 1) createHiddenCampaign(t, db, c1, p1) createHiddenCampaign(t, db, c2, p1) // a plain campaign and another program's campaign are not returned createHiddenCampaign(t, db, ptrUUID(), nil) createHiddenCampaign(t, db, ptrUUID(), p3) names, err := r.GetNamesByCampaignTemplateID(ctx, templateID) if err != nil { t.Fatalf("names: %v", err) } if len(names) != 2 || names[0] != "alpha" || names[1] != "beta" { t.Errorf("names = %v, want [alpha beta]", names) } unused, err := r.GetNamesByCampaignTemplateID(ctx, ptrUUID()) if err != nil || len(unused) != 0 { t.Errorf("unused template names = %v, err %v, want none", unused, err) } ids, err := r.GetIDsByCompanyID(ctx, companyID) if err != nil { t.Fatalf("company ids: %v", err) } if len(ids) != 2 { t.Errorf("company program ids = %d, want 2", len(ids)) } campaignIDs, err := r.GetCampaignIDs(ctx, p1) if err != nil { t.Fatalf("campaign ids: %v", err) } got := map[uuid.UUID]bool{} for _, id := range campaignIDs { got[*id] = true } if len(got) != 2 || !got[*c1] || !got[*c2] { t.Errorf("campaign ids = %v, want %v and %v", campaignIDs, c1, c2) } if err := r.DeleteProgramCampaignByCampaignID(ctx, c1); err != nil { t.Fatalf("unlink: %v", err) } var remaining int64 db.Model(&database.ProgramCampaign{}).Count(&remaining) if remaining != 1 { t.Errorf("program campaign links after unlink = %d, want 1", remaining) } groupID := ptrUUID() link := &database.ProgramRecipientGroup{ProgramID: p2, RecipientGroupID: groupID} if err := db.Create(link).Error; err != nil { t.Fatalf("assign group: %v", err) } groupNames, err := r.GetNamesByRecipientGroupID(ctx, groupID) if err != nil || len(groupNames) != 1 || groupNames[0] != "alpha" { t.Errorf("group names = %v, err %v, want [alpha]", groupNames, err) } recipientID := ptrUUID() enrollment := &database.ProgramEnrollment{ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(), ProgramID: p2, RecipientID: recipientID} if err := db.Create(enrollment).Error; err != nil { t.Fatalf("enroll: %v", err) } if err := r.UnlinkEnrollmentsOfRecipient(ctx, recipientID); err != nil { t.Fatalf("unlink enrollments: %v", err) } var enrollments int64 db.Model(&database.ProgramEnrollment{}).Where("recipient_id IS NOT NULL").Count(&enrollments) if enrollments != 0 { t.Errorf("linked enrollments after unlink = %d, want 0", enrollments) } // delete removes the campaign links with the program if err := r.DeleteByID(ctx, p1); err != nil { t.Fatalf("delete: %v", err) } var links int64 db.Model(&database.ProgramCampaign{}).Count(&links) if links != 0 { t.Errorf("program campaign links after delete = %d, want 0", links) } } func TestGetListSummaries(t *testing.T) { db := newProgramTestDB(t) if err := db.AutoMigrate(&database.CampaignTemplate{}); err != nil { t.Fatalf("migrate templates: %v", err) } ctx := context.Background() r := &Program{DB: db} a := createProgram(t, db, "a", nil) b := createProgram(t, db, "b", nil) empty := createProgram(t, db, "empty", nil) good, broken, gone := ptrUUID(), ptrUUID(), ptrUUID() for _, tpl := range []struct { id *uuid.UUID usable bool }{{good, true}, {broken, false}} { row := &database.CampaignTemplate{ID: tpl.id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: tpl.id.String(), URLIdentifierID: ptrUUID(), IsUsable: tpl.usable} if err := db.Create(row).Error; err != nil { t.Fatalf("create template: %v", err) } } createStep(t, db, a, good, 0) createStep(t, db, a, broken, 1) createStep(t, db, b, gone, 0) soon := time.Now().Add(time.Hour).UTC().Truncate(time.Second) later := soon.Add(24 * time.Hour) enroll := func(p *uuid.UUID, due *time.Time, status string) { e := &database.ProgramEnrollment{ ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(), ProgramID: p, RecipientID: ptrUUID(), NextDueAt: due, Status: status, } if err := db.Create(e).Error; err != nil { t.Fatalf("enroll: %v", err) } } enroll(a, &later, "active") enroll(a, &soon, "active") enroll(a, nil, "active") enroll(a, &soon, "exited") enroll(b, &later, "active") got, err := r.GetListSummaries(ctx, []*uuid.UUID{a, b, empty}) if err != nil { t.Fatalf("summaries: %v", err) } if got[*a].Enrolled != 3 || got[*b].Enrolled != 1 || got[*empty].Enrolled != 0 { t.Fatalf("enrolled a=%d b=%d empty=%d", got[*a].Enrolled, got[*b].Enrolled, got[*empty].Enrolled) } // the total also counts the person who was removed if got[*a].Total != 4 || got[*b].Total != 1 || got[*empty].Total != 0 { t.Fatalf("total a=%d b=%d empty=%d", got[*a].Total, got[*b].Total, got[*empty].Total) } if got[*a].NextDueAt == nil || !got[*a].NextDueAt.Equal(soon) { t.Fatalf("next due a = %v, want %v", got[*a].NextDueAt, soon) } if got[*empty].NextDueAt != nil { t.Fatalf("empty program should have no next due") } if len(got[*a].StepTemplateIDs) != 2 || len(got[*b].StepTemplateIDs) != 1 { t.Fatalf("step templates a=%d b=%d", len(got[*a].StepTemplateIDs), len(got[*b].StepTemplateIDs)) } usable, err := r.GetTemplateUsability(ctx, []uuid.UUID{*good, *broken, *gone}) if err != nil { t.Fatalf("usability: %v", err) } if !usable[*good] || usable[*broken] { t.Fatalf("usability = %v", usable) } if _, ok := usable[*gone]; ok { t.Fatalf("a deleted template must be missing from the result") } } // TestProgramListSearch checks the program list search matches the name only, // not the date columns, and reads LIKE wildcards in the text as spaces func TestProgramListSearch(t *testing.T) { db := newProgramTestDB(t) ctx := context.Background() r := &Program{DB: db} createProgram(t, db, "Phishing quarter", nil) createProgram(t, db, "Awareness", nil) createProgram(t, db, "100% done", nil) search := func(text string) []string { t.Helper() got, err := r.GetAll(ctx, nil, &ProgramOption{QueryArgs: &vo.QueryArgs{Search: text}, AllCompanies: true}, time.Now()) if err != nil { t.Fatalf("search %q: %v", text, err) } names := []string{} for _, p := range got.Rows { names = append(names, p.Name.MustGet().String()) } sort.Strings(names) return names } if got := search("quarter"); len(got) != 1 || got[0] != "Phishing quarter" { t.Fatalf("name search: %v", got) } // every program was created this year, a date column would match year := time.Now().UTC().Format("2006") if got := search(year); len(got) != 0 { t.Fatalf("a search must not match the date columns: %v", got) } // the underscore is no wildcard, read as a space if got := search("x_done"); len(got) != 0 { t.Fatalf("an underscore is no wildcard: %v", got) } if got := search("100"); len(got) != 1 { t.Fatalf("search 100: %v", got) } } // TestClearReplanPendingKeepsNewerMark clears an older replan mark after a // newer edit set its own: the newer mark stays, the matching one is cleared func TestClearReplanPendingKeepsNewerMark(t *testing.T) { db := newWriteLockDB(t) ctx := context.Background() repo := &Program{DB: db} id := ptrUUID() if err := db.Create(&database.Program{ID: id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: "p"}).Error; err != nil { t.Fatalf("program: %v", err) } older := time.Now().UTC() newer := older.Add(time.Millisecond) set := func(mark time.Time) { t.Helper() if err := db.Model(&database.Program{}).Where("id = ?", id).UpdateColumn("replan_pending_at", mark).Error; err != nil { t.Fatalf("mark: %v", err) } } read := func() *time.Time { t.Helper() var row database.Program if err := db.Where("id = ?", id).First(&row).Error; err != nil { t.Fatalf("read: %v", err) } return row.ReplanPendingAt } set(older) set(newer) if err := repo.ClearReplanPending(ctx, id, older); err != nil { t.Fatalf("clear older: %v", err) } if read() == nil { t.Fatal("the newer mark was cleared by the older one") } // the Go value the edit wrote, nanoseconds and all, clears it if err := repo.ClearReplanPending(ctx, id, newer); err != nil { t.Fatalf("clear newer: %v", err) } if read() != nil { t.Fatal("the written mark did not match") } // and so does the value read back from the row set(newer) if err := repo.ClearReplanPending(ctx, id, *read()); err != nil { t.Fatalf("clear read back: %v", err) } if read() != nil { t.Fatal("the read back mark did not match") } } // TestTimeCompareAndSwapPrecision checks how a stored time compares with a // Go time on each engine. postgres keeps microseconds: pgx sends a time.Time // in binary and drops the nanoseconds, the server rounds a time written as // text. So a compare and swap matches when the stored value and the compared // value are both a time.Time, or the compared value was read back from the // row, and misses when the row was written as nanosecond text and compared // with the time.Time it was made from. func TestTimeCompareAndSwapPrecision(t *testing.T) { db := newProgramTestDB(t) // 999 ns past a whole microsecond: truncating and rounding differ at := time.Date(2026, 3, 4, 5, 6, 7, 123456999, time.UTC) add := func(value any) *uuid.UUID { t.Helper() id := uuid.New() if err := db.Create(&database.Program{ID: &id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: "p " + id.String()}).Error; err != nil { t.Fatalf("program: %v", err) } if err := db.Model(&database.Program{}).Where("id = ?", id). UpdateColumn("replan_pending_at", value).Error; err != nil { t.Fatalf("mark: %v", err) } return &id } matches := func(id *uuid.UUID, value any) bool { t.Helper() var n int64 if err := db.Model(&database.Program{}). Where(clause.Eq{Column: clause.Column{Name: "id"}, Value: id}). Where(clause.Eq{Column: clause.Column{Name: "replan_pending_at"}, Value: value}). Count(&n).Error; err != nil { t.Fatalf("count: %v", err) } return n == 1 } readBack := func(id *uuid.UUID) time.Time { t.Helper() var row database.Program if err := db.Where("id = ?", id).First(&row).Error; err != nil { t.Fatalf("read: %v", err) } return *row.ReplanPendingAt } // a time written and compared as a time.Time byTime := add(at) if !matches(byTime, at) { t.Fatal("a time.Time written and compared does not match") } if !matches(byTime, readBack(byTime)) { t.Fatal("the read back value does not match") } // text written, compared with the read back value: postgres compares // instants and matches, sqlite compares the RFC 3339 text with the text // the driver makes of a time.Time and never matches byText := add(utils.RFC3339UTC(at)) if matches(byText, readBack(byText)) != testdb.IsPostgres() { t.Fatal("text written, compare with the read back value") } // text written and compared as the same text matches on both if !matches(byText, utils.RFC3339UTC(at)) { t.Fatal("text written and compared as text does not match") } if testdb.IsPostgres() { // text is rounded by the server, a time.Time truncated by pgx if matches(byText, at) { t.Fatal("expected postgres to round text and truncate time.Time") } if !matches(byText, at.Truncate(time.Microsecond).Add(time.Microsecond)) { t.Fatal("expected the text to be rounded up") } } // a value truncated to microseconds and written as text matches the // truncated time.Time on postgres us := at.Truncate(time.Microsecond) byTextUS := add(utils.RFC3339UTC(us)) if testdb.IsPostgres() && !matches(byTextUS, us) { t.Fatal("truncated text does not match the truncated time on postgres") } }