Files
phishingclub/backend/repository/programLifecycle_db_test.go
2026-12-01 21:25:01 +01:00

249 lines
10 KiB
Go

package repository
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/testdb"
"github.com/phishingclub/phishingclub/utils"
"gorm.io/gorm"
)
// TestStopEnrollmentsInChunks checks every active person of a program is
// stopped and every pending send time cleared over more than one chunk, and
// other programs are left alone
func TestStopEnrollmentsInChunks(t *testing.T) {
db := newProgramTestDB(t)
ctx := context.Background()
r := &Program{DB: db}
programID := createProgram(t, db, "p", nil)
other := createProgram(t, db, "other", nil)
due := time.Now().Add(time.Hour)
rows := []*database.ProgramEnrollment{}
for i := 0; i < ProgramWriteChunk*2+3; i++ {
rows = append(rows, &database.ProgramEnrollment{ProgramID: programID, RecipientID: ptrUUID(), Status: model.ProgramEnrollmentActive, NextDueAt: &due})
}
// a person who left but still has a due time
rows = append(rows, &database.ProgramEnrollment{ProgramID: programID, RecipientID: ptrUUID(), Status: model.ProgramEnrollmentExited, NextDueAt: &due})
rows = append(rows, &database.ProgramEnrollment{ProgramID: other, RecipientID: ptrUUID(), Status: model.ProgramEnrollmentActive, NextDueAt: &due})
if err := r.InsertEnrollments(ctx, rows); err != nil {
t.Fatalf("enroll: %v", err)
}
if err := r.StopEnrollments(ctx, programID); err != nil {
t.Fatalf("stop: %v", err)
}
var active, pending, stopped int64
db.Model(&database.ProgramEnrollment{}).Where("program_id = ? AND status = ?", programID, model.ProgramEnrollmentActive).Count(&active)
db.Model(&database.ProgramEnrollment{}).Where("program_id = ? AND next_due_at IS NOT NULL", programID).Count(&pending)
db.Model(&database.ProgramEnrollment{}).Where("program_id = ? AND status = ?", programID, model.ProgramEnrollmentStopped).Count(&stopped)
if active != 0 || pending != 0 || stopped != int64(ProgramWriteChunk*2+3) {
t.Fatalf("active %d pending %d stopped %d", active, pending, stopped)
}
var untouched int64
db.Model(&database.ProgramEnrollment{}).Where("program_id = ? AND status = ? AND next_due_at IS NOT NULL", other, model.ProgramEnrollmentActive).Count(&untouched)
if untouched != 1 {
t.Fatal("another program must be left alone")
}
}
// TestGetGoneWithUnsentSends checks only people who left the program and still
// have an unsent send of it are found, each once, and that the limit holds
func TestGetGoneWithUnsentSends(t *testing.T) {
db := newProgramTestDB(t)
ctx := context.Background()
r := &Program{DB: db}
programID := createProgram(t, db, "gone", nil)
otherProgram := createProgram(t, db, "other", nil)
campaigns := []*uuid.UUID{ptrUUID(), ptrUUID()}
for _, id := range campaigns {
createHiddenCampaign(t, db, id, programID)
}
otherCampaign := ptrUUID()
createHiddenCampaign(t, db, otherCampaign, otherProgram)
now := time.Now()
cutoff := now.Add(-24 * time.Hour)
enroll := func(program *uuid.UUID, status string, missingSince *time.Time) *uuid.UUID {
rid := ptrUUID()
e := &database.ProgramEnrollment{
ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(),
ProgramID: program, RecipientID: rid, Status: status, MissingSince: missingSince,
}
if err := db.Create(e).Error; err != nil {
t.Fatalf("enroll: %v", err)
}
return rid
}
long, recent := now.Add(-48*time.Hour), now.Add(-time.Hour)
exited := enroll(programID, model.ProgramEnrollmentExited, nil)
missing := enroll(programID, model.ProgramEnrollmentCompleted, &long)
recentlyMissing := enroll(programID, model.ProgramEnrollmentCompleted, &recent)
completed := enroll(programID, model.ProgramEnrollmentCompleted, nil)
active := enroll(programID, model.ProgramEnrollmentActive, &long)
exitedDone := enroll(programID, model.ProgramEnrollmentExited, nil)
exitedElsewhere := enroll(otherProgram, model.ProgramEnrollmentExited, nil)
for _, rid := range []*uuid.UUID{exited, missing, recentlyMissing, completed, active, exitedElsewhere} {
for _, c := range campaigns {
addCampaignRecipient(t, db, c, rid, nil, false)
}
}
addCampaignRecipient(t, db, otherCampaign, exitedElsewhere, nil, false)
// a person who left with only a sent and a cancelled send
addCampaignRecipient(t, db, campaigns[0], exitedDone, nil, true)
cancelled := addCampaignRecipient(t, db, campaigns[1], exitedDone, nil, false)
db.Model(&database.CampaignRecipient{}).Where("id = ?", cancelled).Update("cancelled_at", utils.NowRFC3339UTC())
ids, err := r.GetGoneWithUnsentSends(ctx, programID, cutoff, 10)
if err != nil {
t.Fatalf("gone: %v", err)
}
got := map[uuid.UUID]int{}
for _, id := range ids {
got[*id]++
}
if len(ids) != 2 || got[*exited] != 1 || got[*missing] != 1 {
t.Fatalf("expected the person who exited and the one missing past the grace once each, got %v", ids)
}
ids, err = r.GetGoneWithUnsentSends(ctx, programID, cutoff, 1)
if err != nil || len(ids) != 1 {
t.Fatalf("limit: %v %v", ids, err)
}
}
// TestIsCampaignStepRemoved checks a hidden campaign whose step is still in its
// program is not reported, and one whose step was removed is
func TestIsCampaignStepRemoved(t *testing.T) {
db := newProgramTestDB(t)
ctx := context.Background()
r := &Program{DB: db}
programID := createProgram(t, db, "steps", nil)
stepID := createStep(t, db, programID, ptrUUID(), 0)
campaignID := linkCampaign(t, db, programID, stepID, 0)
if removed, err := r.IsCampaignStepRemoved(ctx, campaignID); err != nil || removed {
t.Fatalf("a step still in the program: %v %v", removed, err)
}
if err := db.Where("id = ?", stepID).Delete(&database.ProgramStep{}).Error; err != nil {
t.Fatalf("remove step: %v", err)
}
if removed, err := r.IsCampaignStepRemoved(ctx, campaignID); err != nil || !removed {
t.Fatalf("a removed step: %v %v", removed, err)
}
if removed, err := r.IsCampaignStepRemoved(ctx, ptrUUID()); err != nil || removed {
t.Fatalf("a campaign of no program: %v %v", removed, err)
}
}
// TestStopEnrollmentsKeepsConcurrentCompletion checks a program close that
// stops the active enrollments leaves the enrollments the scheduler completed
// while the close waited for them as completed, and stops every other one
func TestStopEnrollmentsKeepsConcurrentCompletion(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newProgramTestDB(t)
ctx := context.Background()
r := &Program{DB: db}
programID := createProgram(t, db, "p", nil)
addEnrollments(t, db, programID, 20)
done := everySecond(t, db, &database.ProgramEnrollment{}, "program_id", programID)
err := whileHeld(t, db, func(tx *gorm.DB) error {
return tx.Model(&database.ProgramEnrollment{}).Where("id IN ?", done).
Updates(map[string]any{"status": model.ProgramEnrollmentCompleted, "completed_at": utils.NowRFC3339UTC()}).Error
}, func() error {
return r.StopEnrollments(ctx, programID)
})
if err != nil {
t.Fatalf("stop: %v", err)
}
var completed int64
if err := db.Model(&database.ProgramEnrollment{}).
Where("id IN ? AND status = ?", done, model.ProgramEnrollmentCompleted).Count(&completed).Error; err != nil {
t.Fatalf("count: %v", err)
}
if completed != int64(len(done)) {
t.Fatalf("%d of %d completed enrollments are still completed", completed, len(done))
}
var active int64
if err := db.Model(&database.ProgramEnrollment{}).
Where("program_id = ? AND status = ?", programID, model.ProgramEnrollmentActive).Count(&active).Error; err != nil {
t.Fatalf("count: %v", err)
}
if active != 0 {
t.Fatalf("%d enrollments still active", active)
}
}
// TestCancelAllUnsentSkipsConcurrentClaim checks a program close that
// cancels the unsent sends does not cancel the sends the sender took while
// the cancel waited for them, so no row ends both sent and cancelled, and
// still cancels every other one
func TestCancelAllUnsentSkipsConcurrentClaim(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newProgramTestDB(t)
ctx := context.Background()
r := &Program{DB: db}
programID := createProgram(t, db, "p", nil)
camp := addProgramCampaign(t, db, programID)
addSends(t, db, camp, 1200)
taken := everySecond(t, db, &database.CampaignRecipient{}, "campaign_id", camp)
err := whileHeld(t, db, func(tx *gorm.DB) error {
now := utils.NowRFC3339UTC()
return tx.Model(&database.CampaignRecipient{}).Where("id IN ?", taken).
Updates(map[string]any{"last_attempt_at": now, "sent_at": now}).Error
}, func() error {
return r.CancelAllUnsent(ctx, programID)
})
if err != nil {
t.Fatalf("cancel: %v", err)
}
var both int64
if err := db.Model(&database.CampaignRecipient{}).
Where("sent_at IS NOT NULL AND cancelled_at IS NOT NULL").Count(&both).Error; err != nil {
t.Fatalf("count: %v", err)
}
if both != 0 {
t.Fatalf("%d sends are both sent and cancelled", both)
}
var open int64
if err := db.Model(&database.CampaignRecipient{}).
Where("campaign_id = ? AND sent_at IS NULL AND cancelled_at IS NULL", camp).Count(&open).Error; err != nil {
t.Fatalf("count: %v", err)
}
if open != 0 {
t.Fatalf("%d unsent sends not cancelled", open)
}
}
// TestReconcileWaitsForProgramPause runs the pause backstop while a pause of
// the program is open: the resume of a paused hidden campaign waits for the
// pause and then leaves the campaign paused
func TestReconcileWaitsForProgramPause(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newProgramTestDB(t)
ctx := context.Background()
program := createProgram(t, db, "p", nil)
camp := ptrUUID()
createHiddenCampaign(t, db, camp, program)
if err := db.Model(&database.Campaign{}).Where("id = ?", camp).
Update("paused_at", utils.NowRFC3339UTC()).Error; err != nil {
t.Fatalf("pause campaign: %v", err)
}
err := whileHeld(t, db, func(tx *gorm.DB) error {
return (&Program{DB: tx}).SetFieldsAndCampaignPause(ctx, program, map[string]any{"paused_at": utils.NowRFC3339UTC()}, true)
}, func() error {
_, err := (&Program{DB: db}).ReconcileCampaignPause(ctx)
return err
})
if err != nil {
t.Fatalf("reconcile: %v", err)
}
var row database.Campaign
if err := db.Where("id = ?", camp).First(&row).Error; err != nil {
t.Fatalf("read campaign: %v", err)
}
if row.PausedAt == nil {
t.Fatal("the backstop resumed a campaign of a program paused at the same time")
}
}