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

145 lines
5.2 KiB
Go

package repository
import (
"context"
"strings"
"testing"
"time"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/testdb"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
)
// TestDialectTimelineDay checks the day and week of a stored UTC time moved
// by an offset are the same on each engine and as computed in Go
func TestDialectTimelineDay(t *testing.T) {
offsets := []int{0, 3600, -18000, 45 * 60}
at := clause.Column{Name: "seen_at"}
for _, db := range openDialectDBs(t) {
for _, offset := range offsets {
for _, week := range []bool{false, true} {
var rows []struct {
ID int
Day *string
}
move := func(d Dialect) any { return d.timelineOffset(offset) }
err := db.Table("dialect_rows").
Select("id, ? AS day", timelineDay(at, move, week)).
Order("id").Scan(&rows).Error
if err != nil {
t.Fatalf("%s: %v", db.Dialector.Name(), err)
}
for _, r := range rows {
stored, ok := dialectTimes[r.ID]
if !ok {
if r.Day != nil {
t.Fatalf("%s: null time gave %q", db.Dialector.Name(), *r.Day)
}
continue
}
local := stored.Add(time.Duration(offset) * time.Second)
if week {
back := (int(local.Weekday()) + 6) % 7
local = local.AddDate(0, 0, -back)
}
want := local.Format("2006-01-02")
if r.Day == nil || *r.Day != want {
t.Fatalf("%s row %d offset %d week %v: day %v, want %s", db.Dialector.Name(), r.ID, offset, week, r.Day, want)
}
}
}
}
// the offset picked per span by a CASE, as the outcome counts do
spans := []ProgramTimelineSpan{
{From: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), To: time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC), Offset: 3600},
{From: time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC), To: time.Date(2028, 1, 1, 0, 0, 0, 0, time.UTC), Offset: 7200},
}
var rows []struct {
ID int
Day string
}
err := db.Table("dialect_rows").
Select("id, ? AS day", timelineDay(at, timelineModifier(at, spans), false)).
Where(clause.Expr{SQL: "? IS NOT NULL", Vars: []any{at}}).
Order("id").Scan(&rows).Error
if err != nil {
t.Fatalf("%s: %v", db.Dialector.Name(), err)
}
for _, r := range rows {
stored := dialectTimes[r.ID]
offset := 7200
if stored.Before(spans[0].To) {
offset = 3600
}
want := stored.Add(time.Duration(offset) * time.Second).Format("2006-01-02")
if r.Day != want {
t.Fatalf("%s row %d spans: day %s, want %s", db.Dialector.Name(), r.ID, r.Day, want)
}
}
}
}
// TestTimelineSentCoveringIndex checks the timeline sent count reads each
// program campaign within the range of the campaign and sent time index, and
// not the sent_at index of every campaign. A send that names nobody is not
// counted, as in the facts of the program.
func TestTimelineSentCoveringIndex(t *testing.T) {
db := newProgramTestDB(t)
if err := (database.CampaignRecipient{}).Migrate(db); err != nil {
t.Fatalf("migrate: %v", err)
}
ctx := context.Background()
programID := createProgram(t, db, "p", nil)
campaign := ptrUUID()
createHiddenCampaign(t, db, campaign, programID)
other := ptrUUID()
createHiddenCampaign(t, db, other, nil)
addCampaignRecipient(t, db, campaign, ptrUUID(), nil, true)
addCampaignRecipient(t, db, campaign, nil, ptrUUID(), true)
addCampaignRecipient(t, db, campaign, nil, nil, true)
addCampaignRecipient(t, db, campaign, ptrUUID(), nil, false)
addCampaignRecipient(t, db, other, ptrUUID(), nil, true)
now := time.Now().UTC()
spans := []ProgramTimelineSpan{{From: now.Add(-24 * time.Hour), To: now.Add(time.Hour)}}
var stmt string
traced := db.Session(&gorm.Session{Logger: planLogger{Interface: logger.Default.LogMode(logger.Silent), sql: &stmt}})
rows, err := (&Program{DB: traced}).GetTimelineSent(ctx, programID, spans)
if err != nil {
t.Fatalf("timeline: %v", err)
}
total := 0
for _, row := range rows {
total += row.Count
}
if total != 2 {
t.Fatalf("sent %d, want 2", total)
}
plan := explainPlan(t, db, stmt)
if !strings.Contains(plan, "campaign_recipients USING INDEX idx_campaign_recipients_campaign_sent_at (campaign_id=? AND sent_at>? AND sent_at<?)") &&
!strings.Contains(plan, "campaign_recipients USING COVERING INDEX idx_campaign_recipients_campaign_sent_at (campaign_id=? AND sent_at>? AND sent_at<?)") {
t.Fatalf("the count must read the campaign and sent time index within the range, plan: %s", plan)
}
}
// TestCampaignSentIndexReplaced checks the migration drops the campaign only
// sent index and creates the campaign and sent time index
func TestCampaignSentIndexReplaced(t *testing.T) {
db := newProgramTestDB(t)
if err := db.Exec(`CREATE INDEX idx_campaign_recipients_campaign_sent ON campaign_recipients (campaign_id) WHERE sent_at IS NOT NULL`).Error; err != nil {
t.Fatalf("old index: %v", err)
}
if err := (database.CampaignRecipient{}).Migrate(db); err != nil {
t.Fatalf("migrate: %v", err)
}
names, err := testdb.IndexNames(db, "idx_campaign_recipients_campaign_sent%")
if err != nil {
t.Fatalf("indexes: %v", err)
}
if len(names) != 1 || names[0] != "idx_campaign_recipients_campaign_sent_at" {
t.Fatalf("indexes %v, want only idx_campaign_recipients_campaign_sent_at", names)
}
}