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

426 lines
16 KiB
Go

package service
import (
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/model"
)
var resultsNow = time.Date(2025, 6, 1, 12, 0, 0, 0, time.UTC)
// anonymousNow is a time the months of the sends near resultsNow have settled,
// so an anonymous program counts them
var anonymousNow = time.Date(2025, 7, 10, 12, 0, 0, 0, time.UTC)
func at(daysAgo int) time.Time {
return resultsNow.Add(-time.Duration(daysAgo) * 24 * time.Hour)
}
func tp(t time.Time) *time.Time {
return &t
}
// send builds a phishing send for a person, sent daysAgo
func send(person uuid.UUID, daysAgo int, outcome string) *programSend {
s := &programSend{Person: person, Campaign: uuid.New(), SentAt: at(daysAgo), Template: "t1"}
after := s.SentAt.Add(time.Hour)
switch outcome {
case "submitted":
s.ClickedAt, s.SubmittedAt = tp(after), tp(after)
case "clicked":
s.ClickedAt = tp(after)
case "clickedReported":
s.ClickedAt, s.ReportedAt = tp(after), tp(after.Add(time.Minute))
case "reported":
s.ReportedAt = tp(after)
}
return s
}
// results builds the results of facts at now in loc over [from, to)
func results(facts *programFacts, loc *time.Location, now time.Time, from, to *time.Time) *ProgramResults {
return buildProgramResults(facts, programResultsInput{loc: loc, now: now, from: from, to: to, repeatMonths: 12})
}
// TestProgramSummaryCountsRecipients checks the result tiles count each
// recipient once, and repeat offenders follow the repeat offender window
func TestProgramSummaryCountsRecipients(t *testing.T) {
facts := &programFacts{templateNames: map[string]string{}}
ps := people(4)
// p0 clicked twice within a year: a repeat offender
facts.sends = append(facts.sends, send(ps[0], 100, "clicked"), send(ps[0], 50, "submitted"), send(ps[0], 10, "reported"))
// p1 clicked twice, once over a year ago: not a repeat offender
facts.sends = append(facts.sends, send(ps[1], 400, "clicked"), send(ps[1], 20, "clicked"))
// p2 clicked once
facts.sends = append(facts.sends, send(ps[2], 20, "clickedReported"))
// p3 only got training, which is not a phishing send
facts.sends = append(facts.sends, &programSend{Person: ps[3], SentAt: at(5), Training: true,
TrainingStartedAt: tp(at(4)), TrainingCompletedAt: tp(at(4))})
r := buildProgramResults(facts, programResultsInput{loc: time.UTC, now: resultsNow, recipients: 9, repeatMonths: 12})
s := r.Summary
want := map[string]int{"sent": 3, "clicked": 3, "submitted": 1, "reported": 2, "offenders": 1, "trainingStarted": 1, "trainingCompleted": 1}
got := map[string]*int{"sent": s.Sent, "clicked": s.ClickedLink, "submitted": s.SubmittedData, "reported": s.Reported,
"offenders": s.RepeatOffenders, "trainingStarted": s.TrainingStarted, "trainingCompleted": s.TrainingCompleted}
for k, v := range want {
if got[k] == nil || *got[k] != v {
t.Fatalf("%s = %v, want %d", k, got[k], v)
}
}
if s.Recipients != 9 || s.SentTotal != 7 || !s.HasTraining || s.Suppressed || s.RepeatOffenderMonths != 12 {
t.Fatalf("summary wrong: %+v", s)
}
// a shorter window leaves out p0's click 100 days ago
r = buildProgramResults(facts, programResultsInput{loc: time.UTC, now: resultsNow, repeatMonths: 2})
if *r.Summary.RepeatOffenders != 0 {
t.Fatalf("2 months window: offenders = %d", *r.Summary.RepeatOffenders)
}
// without training the training counts stay empty
facts.sends = facts.sends[:6]
r = results(facts, time.UTC, resultsNow, nil, nil)
if r.Summary.HasTraining || r.Summary.TrainingStarted != nil {
t.Fatalf("no training: %+v", r.Summary)
}
}
// TestProgramPartialMonths checks the first month of a program started mid
// month and the running month are marked partial
func TestProgramPartialMonths(t *testing.T) {
facts := &programFacts{templateNames: map[string]string{}}
p := uuid.New()
for _, d := range []time.Time{
time.Date(2025, 3, 20, 9, 0, 0, 0, time.UTC),
time.Date(2025, 4, 10, 9, 0, 0, 0, time.UTC),
time.Date(2025, 6, 1, 9, 0, 0, 0, time.UTC),
} {
facts.sends = append(facts.sends, &programSend{Person: p, SentAt: d, Template: "t1"})
}
started := time.Date(2025, 3, 15, 0, 0, 0, 0, time.UTC)
r := buildProgramResults(facts, programResultsInput{loc: time.UTC, now: resultsNow, startedAt: &started})
partial := []bool{}
for _, m := range r.Months {
partial = append(partial, m.Partial)
}
if len(partial) != 3 || !partial[0] || partial[1] || !partial[2] {
t.Fatalf("partial months = %v, want first and last", partial)
}
// a program closed at the end of June has no partial last month
closed := time.Date(2025, 7, 1, 0, 0, 0, 0, time.UTC)
r = buildProgramResults(facts, programResultsInput{loc: time.UTC, now: closed.AddDate(0, 1, 0), startedAt: &started, closedAt: &closed})
if r.Months[2].Partial {
t.Fatalf("a whole month is not partial")
}
}
func TestProgramResultsSuppression(t *testing.T) {
ps := people(6)
facts := &programFacts{anonymous: true, templateNames: map[string]string{"t1": "Invoice", "t2": "Parcel"}}
for _, p := range ps {
facts.sends = append(facts.sends, send(p, 10, "clicked"))
}
// two sends of another template, too few to show
t2a, t2b := send(ps[0], 5, "reported"), send(ps[1], 50, "ignored")
t2a.Template, t2b.Template = "t2", "t2"
facts.sends = append(facts.sends, t2a, t2b)
// a training send is not a phishing result
facts.sends = append(facts.sends, &programSend{Person: ps[0], SentAt: at(9), Training: true, Template: "t3"})
r := results(facts, time.UTC, anonymousNow, nil, nil)
if !r.Anonymous {
t.Fatalf("expected anonymous results")
}
byKey := map[string]*ProgramResultRow{}
for _, row := range r.Templates {
byKey[row.Key] = row
}
// the row shows its size, never an outcome
if byKey["t1"].Suppressed || *byKey["t1"].Sent != 6 || byKey["t1"].Clicked != nil || byKey["t1"].Reported != nil {
t.Fatalf("t1 row wrong: %+v", byKey["t1"])
}
if !byKey["t2"].Suppressed || byKey["t2"].Sent != nil || byKey["t2"].Clicked != nil {
t.Fatalf("t2 row should be suppressed: %+v", byKey["t2"])
}
if _, ok := byKey["t3"]; ok {
t.Fatalf("training send must not be a template result")
}
// the same data for a normal program shows every count
facts.anonymous = false
r = results(facts, time.UTC, resultsNow, nil, nil)
// a training template row holds the training counts, not the phishing ones
for _, row := range r.Templates {
if row.Key == "t3" {
if row.Suppressed || row.Sent != nil || row.TrainingSent == nil || *row.TrainingSent != 1 {
t.Fatalf("training row wrong: %+v", row)
}
continue
}
if row.Suppressed || row.Sent == nil || row.Clicked == nil {
t.Fatalf("normal program rows must not be suppressed: %+v", row)
}
}
// a period keeps only the sends inside it
from, to := at(20), at(6)
r = results(facts, time.UTC, resultsNow, &from, &to)
// the 6 phishing sends of t1 and the training send of t3
if len(r.Templates) != 2 || *r.Templates[0].Sent != 6 || r.Templates[1].Key != "t3" || *r.Summary.Sent != 6 {
t.Fatalf("period filter wrong: %+v", r.Templates)
}
}
func TestWithholdGap(t *testing.T) {
cases := []struct {
a, b int
want bool
}{
{10, 10, true},
{10, 9, true},
{10, 6, true},
{10, 5, false},
{6, 10, true},
{0, 5, false},
{20, 0, false},
}
for _, c := range cases {
if got := withholdGap(c.a, c.b); got != c.want {
t.Fatalf("withholdGap(%d, %d) = %v, want %v", c.a, c.b, got, c.want)
}
}
}
func TestWithholdCount(t *testing.T) {
cases := []struct {
group, count int
want bool
}{
{10, 0, true}, // nobody
{10, 1, true},
{10, 4, true},
{10, 5, false},
{10, 6, true}, // 4 left out
{10, 10, true}, // everyone
{20, 15, false},
{20, 16, true},
}
for _, c := range cases {
if got := withholdCount(c.group, c.count); got != c.want {
t.Fatalf("withholdCount(%d, %d) = %v, want %v", c.group, c.count, got, c.want)
}
}
}
// people returns n new person keys
func people(n int) []uuid.UUID {
out := make([]uuid.UUID, n)
for i := range out {
out[i] = uuid.New()
}
return out
}
// trainingSend builds a training send of template for a person, sent daysAgo,
// started and completed as asked
func trainingSend(person uuid.UUID, daysAgo int, template string, started, completed bool) *programSend {
s := &programSend{Person: person, Campaign: uuid.New(), SentAt: at(daysAgo), Template: template, Training: true}
after := s.SentAt.Add(time.Hour)
if started {
s.TrainingStartedAt = tp(after)
}
if completed {
s.TrainingCompletedAt = tp(after.Add(time.Hour))
}
return s
}
// rowByKey finds a row by its key
func rowByKey(t *testing.T, rows []*ProgramResultRow, key string) *ProgramResultRow {
t.Helper()
for _, r := range rows {
if r.Key == key {
return r
}
}
t.Fatalf("no row %q", key)
return nil
}
func wantCount(t *testing.T, name string, got *int, want int) {
t.Helper()
if got == nil || *got != want {
t.Fatalf("%s = %v, want %d", name, got, want)
}
}
func wantNull(t *testing.T, name string, got *int) {
t.Helper()
if got != nil {
t.Fatalf("%s = %d, want null", name, *got)
}
}
// TestProgramRowsMixed checks a mixed program counts the training sends in
// the month and template rows next to the phishing counts, which stay
// phishing only: a training template row holds no phishing counts, a phishing
// template row no training counts, and a completed training counts as started
func TestProgramRowsMixed(t *testing.T) {
facts := &programFacts{templateNames: map[string]string{"t1": "Phish", "tr": "Course"}}
ps := people(3)
facts.sends = append(facts.sends,
send(ps[0], 3, "clicked"), send(ps[1], 3, "reported"), send(ps[2], 3, "ignored"),
trainingSend(ps[0], 3, "tr", true, true),
trainingSend(ps[1], 3, "tr", false, true),
trainingSend(ps[2], 3, "tr", true, false),
// a month with only training
trainingSend(ps[0], 60, "tr", false, false),
)
r := results(facts, time.UTC, resultsNow, nil, nil)
if !r.Summary.HasPhishing || !r.Summary.HasTraining {
t.Fatalf("a mixed program has phishing and training: %+v", r.Summary)
}
phish := rowByKey(t, r.Templates, "t1")
wantCount(t, "phishing sent", phish.Sent, 3)
wantCount(t, "phishing clicked", phish.Clicked, 1)
wantCount(t, "phishing reported", phish.Reported, 1)
wantNull(t, "phishing row training sent", phish.TrainingSent)
wantNull(t, "phishing row training started", phish.TrainingStarted)
course := rowByKey(t, r.Templates, "tr")
wantNull(t, "training row sent", course.Sent)
wantNull(t, "training row clicked", course.Clicked)
wantCount(t, "training sent", course.TrainingSent, 4)
wantCount(t, "training started", course.TrainingStarted, 3)
wantCount(t, "training completed", course.TrainingCompleted, 2)
// the most sent template comes first, phishing or training
if r.Templates[0].Key != "tr" {
t.Fatalf("the template with the most sends comes first, got %s", r.Templates[0].Key)
}
if len(r.Months) != 2 {
t.Fatalf("want 2 months, got %d", len(r.Months))
}
last := r.Months[1]
wantCount(t, "month sent", last.Sent, 3)
wantCount(t, "month clicked", last.Clicked, 1)
wantCount(t, "month training sent", last.TrainingSent, 3)
wantCount(t, "month training started", last.TrainingStarted, 3)
wantCount(t, "month training completed", last.TrainingCompleted, 2)
// a month of only training shows 0 phishing sends, the program has phishing
first := r.Months[0]
wantCount(t, "training month sent", first.Sent, 0)
wantCount(t, "training month clicked", first.Clicked, 0)
wantCount(t, "training month training sent", first.TrainingSent, 1)
wantCount(t, "training month training started", first.TrainingStarted, 0)
}
// TestProgramRowsPhishingOnly checks a program without training holds no
// training counts in its rows, as before training was counted per row
func TestProgramRowsPhishingOnly(t *testing.T) {
facts := &programFacts{templateNames: map[string]string{"t1": "Phish"}}
ps := people(2)
facts.sends = append(facts.sends, send(ps[0], 3, "clicked"), send(ps[1], 3, "submitted"))
r := results(facts, time.UTC, resultsNow, nil, nil)
if !r.Summary.HasPhishing || r.Summary.HasTraining {
t.Fatalf("a phishing program has phishing only: %+v", r.Summary)
}
for _, row := range append(append([]*ProgramResultRow{}, r.Months...), r.Templates...) {
wantCount(t, "sent", row.Sent, 2)
wantCount(t, "clicked", row.Clicked, 2)
wantCount(t, "submitted", row.Submitted, 1)
wantNull(t, "training sent", row.TrainingSent)
wantNull(t, "training started", row.TrainingStarted)
wantNull(t, "training completed", row.TrainingCompleted)
}
}
// TestProgramRowsTrainingOnly checks a program of only training holds no
// phishing counts in its rows and summary flags, and its report shows no
// phishing card, outcome chart, trend or phishing column
func TestProgramRowsTrainingOnly(t *testing.T) {
facts := &programFacts{templateNames: map[string]string{"tr": "Course"}}
ps := people(2)
facts.sends = append(facts.sends,
trainingSend(ps[0], 3, "tr", true, true),
trainingSend(ps[1], 40, "tr", true, false),
)
r := results(facts, time.UTC, resultsNow, nil, nil)
if r.Summary.HasPhishing || !r.Summary.HasTraining {
t.Fatalf("a training program has training only: %+v", r.Summary)
}
if len(r.Months) != 2 || len(r.Templates) != 1 {
t.Fatalf("want 2 months and 1 template, got %d and %d", len(r.Months), len(r.Templates))
}
for _, row := range append(append([]*ProgramResultRow{}, r.Months...), r.Templates...) {
wantNull(t, "sent", row.Sent)
wantNull(t, "clicked", row.Clicked)
wantNull(t, "submitted", row.Submitted)
wantNull(t, "reported", row.Reported)
if row.TrainingSent == nil || row.TrainingStarted == nil || row.TrainingCompleted == nil {
t.Fatalf("training counts must be set: %+v", row)
}
}
wantCount(t, "template training sent", r.Templates[0].TrainingSent, 2)
wantCount(t, "template training started", r.Templates[0].TrainingStarted, 2)
wantCount(t, "template training completed", r.Templates[0].TrainingCompleted, 1)
program := &model.Program{Status: model.ProgramStatusActive}
d := programReportFromResults(program, &programReportSetup{}, r, resultsNow, nil, nil)
for _, card := range d.Results {
switch card.Label {
case "Clicked link", "Data submitted", "Reported", "Repeat offenders":
t.Fatalf("a training program report shows no %s card", card.Label)
}
}
// Recipients, Sent from the training sends as on the program page, and the
// 2 training cards
if len(d.Results) != 4 || len(d.Outcome) != 0 || len(d.Trend) != 0 {
t.Fatalf("want Recipients, Sent and the 2 training cards, no outcome and no trend: %d %d %d", len(d.Results), len(d.Outcome), len(d.Trend))
}
if d.Results[1].Label != "Sent" || d.Results[1].Value != "2" {
t.Fatalf("want Sent from the training sends, got %s %s", d.Results[1].Label, d.Results[1].Value)
}
if d.Results[2].Sub != "100% of training sent" {
t.Fatalf("want Training started as a share of training sent, got %q", d.Results[2].Sub)
}
// name, training sent, started, completed
if cells := d.Templates[0].Cells; len(cells) != 4 || cells[1] != "2" || cells[2] != "2" || cells[3] != "1" {
t.Fatalf("template cells %v", cells)
}
if pcts := d.Templates[0].Pcts; pcts[2] != "100%" || pcts[3] != "50%" {
t.Fatalf("template percents %v", pcts)
}
html, err := renderProgramReportContent(defaultReportContentForKind(model.ReportKindProgram), d)
if err != nil {
t.Fatalf("render: %v", err)
}
for _, text := range []string{"Clicked link", "Repeat offenders", "Click Rate"} {
if strings.Contains(html, text) {
t.Fatalf("a training program report must not mention %q", text)
}
}
if !strings.Contains(html, "Training completed") {
t.Fatalf("a training program report shows the training columns")
}
// the export has no phishing lines either
for _, l := range programSummaryLines(r.Summary, false) {
switch l.Key {
case "sent", "clickedLink", "submittedData", "reported", "repeatOffenders":
t.Fatalf("a training program export has no %s line", l.Key)
}
}
}
// TestProgramSettleCutoffAcrossDaylightSaving checks the settle cutoff is three
// whole calendar days back, also across a clock change
func TestProgramSettleCutoffAcrossDaylightSaving(t *testing.T) {
_, loc := copenhagenWindow(t)
cases := []struct{ now, want time.Time }{
{time.Date(2026, 3, 30, 10, 0, 0, 0, loc), time.Date(2026, 3, 27, 0, 0, 0, 0, loc)},
{time.Date(2026, 10, 27, 23, 30, 0, 0, loc), time.Date(2026, 10, 24, 0, 0, 0, 0, loc)},
}
for _, c := range cases {
if got := programSettleCutoff(c.now, loc); !got.Equal(c.want) {
t.Fatalf("cutoff at %v = %v, want %v", c.now, got, c.want)
}
}
}