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

191 lines
7.0 KiB
Go

package service
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/errs"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/repository"
"github.com/phishingclub/phishingclub/vo"
)
// statsProgram creates a program in a company with the given start, started,
// paused and closed times, nil leaves a field empty
func (p *programTest) statsProgram(companyID *uuid.UUID, startAt, startedAt, pausedAt, closedAt *time.Time) uuid.UUID {
p.t.Helper()
id := uuid.New()
now := time.Now().UTC()
p.create(&database.Program{
ID: &id, CreatedAt: &now, UpdatedAt: &now, Name: "program " + id.String(),
CompanyID: companyID, LoopMode: model.ProgramLoopComplete, OrderMode: model.ProgramOrderSequential,
StartAt: startAt, StartedAt: startedAt, PausedAt: pausedAt, ClosedAt: closedAt,
})
return id
}
func TestProgramGetStats(t *testing.T) {
p := newProgramServiceTest(t)
session := authorizedSession(t)
past := time.Now().UTC().Add(-time.Hour)
future := time.Now().UTC().Add(24 * time.Hour)
companyA, companyB := uuid.New(), uuid.New()
alice := p.recipient("alice@example.com")
// company A
// running with a usable template and someone enrolled, sent through two
// hidden campaigns that must not make it count twice
healthy := p.statsProgram(&companyA, &past, &past, nil, nil)
healthyStep := p.step(healthy, 0, true)
p.stepCampaign(healthy, healthyStep, 0)
p.stepCampaign(healthy, healthyStep, 1)
p.enroll(healthy, alice, 0)
// running with a template that cannot be sent
broken := p.statsProgram(&companyA, &past, &past, nil, nil)
p.step(broken, 0, false)
p.enroll(broken, alice, 0)
// running with nobody enrolled
empty := p.statsProgram(&companyA, &past, &past, nil, nil)
p.step(empty, 0, true)
// paused, also with a broken template, counts as paused only
paused := p.statsProgram(&companyA, &past, &past, &past, nil)
p.step(paused, 0, false)
// paused and then closed counts as closed
p.statsProgram(&companyA, &past, &past, &past, &past)
// draft
p.statsProgram(&companyA, nil, nil, nil, nil)
// scheduled, one of them with a broken template
p.statsProgram(&companyA, &future, nil, nil, nil)
scheduledBroken := p.statsProgram(&companyA, &future, nil, nil, nil)
p.step(scheduledBroken, 0, false)
// closed
p.statsProgram(&companyA, &past, &past, nil, &past)
// company B, one running
other := p.statsProgram(&companyB, &past, &past, nil, nil)
p.step(other, 0, true)
p.enroll(other, alice, 0)
// shared, one running
shared := p.statsProgram(nil, &past, &past, nil, nil)
p.step(shared, 0, true)
p.enroll(shared, alice, 0)
cases := []struct {
name string
companyID *uuid.UUID
want model.ProgramsStatView
}{
{"company A", &companyA, model.ProgramsStatView{Active: 1, Scheduled: 2, Paused: 1, NeedsAttention: 2, Total: 9}},
{"company B", &companyB, model.ProgramsStatView{Active: 1, Total: 1}},
{"every company", nil, model.ProgramsStatView{Active: 3, Scheduled: 2, Paused: 1, NeedsAttention: 2, Total: 11}},
{"company without programs", ptrTo(uuid.New()), model.ProgramsStatView{}},
}
for _, c := range cases {
got, err := p.svc.GetStats(p.ctx, session, c.companyID)
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if *got != c.want {
t.Fatalf("%s: got %+v, want %+v", c.name, *got, c.want)
}
}
// the running programs split the same way the program list shows them
list, err := p.svc.GetAll(p.ctx, session, &companyA, &repository.ProgramOption{QueryArgs: &vo.QueryArgs{Limit: 100, OrderBy: "`programs`.`name`"}})
if err != nil {
t.Fatalf("list: %v", err)
}
attention := 0
for _, row := range list.Rows {
if row.Status == model.ProgramStatusActive && !row.IsPaused() && row.NeedsAttention {
attention++
}
}
if attention != 2 {
t.Fatalf("the list shows %d programs needing attention, the stats 2", attention)
}
// the hidden campaigns stay out of the dashboard campaign count
active, err := p.svc.CampaignRepository.GetActiveCounts(p.ctx, nil, true)
if err != nil {
t.Fatalf("campaign count: %v", err)
}
if active.Active != 0 || active.Paused != 0 {
t.Fatalf("hidden program campaigns counted as active campaigns: %+v", active)
}
if _, err := p.svc.GetStats(p.ctx, unauthorizedSession(t), nil); !errors.Is(err, errs.ErrAuthorizationFailed) {
t.Fatalf("expected a refused read, got %v", err)
}
}
func ptrTo[T any](v T) *T { return &v }
// TestStalledWithoutActivePeople checks the attention reason and the list
// filter agree: a queued send long overdue needs attention also when nobody
// is active, as the last send of a program that does not loop completes the
// person when it is queued, and a person whose advance keeps failing needs
// attention although their next try is ahead
func TestStalledWithoutActivePeople(t *testing.T) {
p := newProgramServiceTest(t)
now := time.Now().UTC()
day := 24 * time.Hour
person := func(programID uuid.UUID, email string, fields map[string]any) uuid.UUID {
rid := p.recipient(email)
e := p.enroll(programID, rid, 0)
p.setEnrollment(e.ID, fields)
return rid
}
completedFields := map[string]any{"status": model.ProgramEnrollmentCompleted, "next_due_at": nil}
running := func() (uuid.UUID, uuid.UUID) {
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
return programID, p.stepCampaign(programID, stepID, 0)
}
// one step, the sender never sent the last send
deadSender, deadCampaign := running()
rid := person(deadSender, "dead@example.com", completedFields)
p.sendAt(deadCampaign, rid, now.Add(-3*day), false)
// everyone completed and nothing queued
finished, _ := running()
person(finished, "done@example.com", completedFields)
// the advance keeps failing, the next try is ahead
failing, _ := running()
person(failing, "failing@example.com", map[string]any{"advance_failures": repository.ProgramStallFailures, "next_due_at": now.Add(day)})
// a few failures are not yet a stall
fewFailures, _ := running()
person(fewFailures, "few@example.com", map[string]any{"advance_failures": repository.ProgramStallFailures - 1, "next_due_at": now.Add(day)})
want := map[uuid.UUID]bool{deadSender: true, failing: true, finished: false, fewFailures: false}
ids := []*uuid.UUID{}
for id := range want {
ids = append(ids, &id)
}
sums, err := p.svc.ProgramRepository.GetListSummaries(p.ctx, ids)
if err != nil {
t.Fatalf("summaries: %v", err)
}
list, err := p.svc.ProgramRepository.GetAll(p.ctx, nil, &repository.ProgramOption{
QueryArgs: &vo.QueryArgs{}, Status: model.ProgramStatusNeedsAttention,
}, now)
if err != nil {
t.Fatalf("list: %v", err)
}
listed := map[uuid.UUID]bool{}
for _, row := range list.Rows {
listed[row.ID.MustGet()] = true
}
for id, stalled := range want {
reason := programStalledReason(p.loadProgram(id), sums[id], now)
if (reason != "") != stalled {
t.Errorf("program %s: reason %q, want stalled %v", id, reason, stalled)
}
if listed[id] != stalled {
t.Errorf("program %s: listed as needs attention %v, want %v", id, listed[id], stalled)
}
}
}