Files
warmbly/internal/app/advisor/detect_test.go
T

1287 lines
50 KiB
Go

package advisor
import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/warmbly/warmbly/internal/models"
"github.com/warmbly/warmbly/internal/repository"
)
// The detectors ARE the product here, so what is worth pinning is not that the
// code runs but that the thresholds hold: silence below the sample floor,
// escalation at the documented bands, and no advice invented from thin data.
func defaults() *models.AdvisorSettings {
return models.DefaultAdvisorSettings(uuid.New())
}
// healthyMailbox is a mailbox nothing should fire on: proven volume, clean
// rates, authenticated, warming, at the default cap and gap.
func healthyMailbox() repository.AdvisorMailbox {
return repository.AdvisorMailbox{
ID: uuid.New(),
Email: "sender@acme.com",
Status: "active",
Provider: "google",
AgeDays: 120,
CampaignLimit: defaultColdCap,
MinWaitTime: defaultMinGap,
TrackingDomain: "track.acme.com",
TrackingDomainVerified: true,
AuthState: "passing",
AuthSPF: true,
AuthDKIM: true,
AuthDMARC: true,
WarmupActive: true,
WarmupBase: defaultWarmupBase,
WarmupMax: defaultWarmupMax,
WarmupReplyRate: 30,
WarmupPoolType: "premium",
PoolHealth: "healthy",
ColdSent30d: 1000,
ColdSent7d: 230,
WarmupSent7d: 200,
InActiveCampaign: true,
}
}
func snapshotOf(mailboxes ...repository.AdvisorMailbox) *repository.AdvisorSnapshot {
return &repository.AdvisorSnapshot{
OrganizationID: uuid.New(),
Now: time.Now(),
Mailboxes: mailboxes,
Lists: map[uuid.UUID]repository.AdvisorListStats{},
}
}
// findingsByKey indexes a detection pass for assertions.
func findingsByKey(findings []Finding) map[string]Finding {
out := map[string]Finding{}
for _, f := range findings {
out[f.Key] = f
}
return out
}
func TestHealthyMailboxProducesNoFindings(t *testing.T) {
got := Detect(snapshotOf(healthyMailbox()), defaults())
if len(got) != 0 {
for _, f := range got {
t.Errorf("unexpected finding on a healthy mailbox: %s (%s) — %s", f.Key, f.Severity, f.Title)
}
}
}
func TestComplaintRateRespectsSampleFloor(t *testing.T) {
// Two complaints out of 40 sends is a 5% complaint rate, which would be
// catastrophic if it were real. It is not real: it is 40 sends. Advice on
// that sample would be wrong more often than right.
m := healthyMailbox()
m.ColdSent30d = minSendsForComplaintRate - 1
m.Complaints30d = 2
if _, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_complaint_rate"]; fired {
t.Fatalf("complaint detector fired below its %d-send sample floor", minSendsForComplaintRate)
}
// Same rate, enough volume to mean something.
m.ColdSent30d = 2000
m.Complaints30d = 4 // 0.2%: above Google's 0.1% ceiling.
f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_complaint_rate"]
if !fired {
t.Fatal("complaint detector did not fire at 0.2% over 2000 sends")
}
if f.Severity != models.AdvisorCritical {
t.Errorf("complaint rate past the 0.10%% band should be critical, got %s", f.Severity)
}
if f.Action == nil {
t.Error("a complaint-rate finding should offer a one-click volume cut")
}
}
func TestComplaintRateWarnBandIsHighNotCritical(t *testing.T) {
m := healthyMailbox()
m.ColdSent30d = 2000
m.Complaints30d = 1 // 0.05%: over the 0.03% watch line, under 0.10%.
f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_complaint_rate"]
if !fired {
t.Fatal("complaint detector did not fire in the warning band")
}
if f.Severity != models.AdvisorHigh {
t.Errorf("warning band should be high, got %s", f.Severity)
}
}
func TestBounceRateEscalatesAtTheSESBand(t *testing.T) {
m := healthyMailbox()
m.ColdSent30d = 1000
m.Bounces30d = 35 // 3.5%: over the watch line, under SES's 5% review band.
if f := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_bounce_rate"]; f.Severity != models.AdvisorHigh {
t.Errorf("3.5%% bounce should be high, got %q", f.Severity)
}
m.Bounces30d = 80 // 8%: past the review band, heading for the pause band.
if f := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_bounce_rate"]; f.Severity != models.AdvisorCritical {
t.Errorf("8%% bounce should be critical, got %q", f.Severity)
}
}
func TestUnknownAuthStateIsNotReportedAsFailing(t *testing.T) {
// A freshly connected mailbox has not been swept yet. Telling someone their
// DNS is broken when we simply have not looked is the fastest way to make
// the whole feature untrustworthy.
m := healthyMailbox()
m.AuthState = "unknown"
m.AuthSPF, m.AuthDKIM, m.AuthDMARC = false, false, false
if _, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_domain_auth"]; fired {
t.Fatal("auth detector fired on an unchecked domain")
}
m.AuthState = "failing"
f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_domain_auth"]
if !fired {
t.Fatal("auth detector did not fire on a domain known to be failing")
}
if f.Severity != models.AdvisorCritical {
t.Errorf("unauthenticated mail on a sending mailbox should be critical, got %s", f.Severity)
}
}
func TestUnverifiedDKIMAloneIsNotAFinding(t *testing.T) {
// A DKIM selector is not discoverable from DNS, so auth_dkim=false means
// "no key answered at the selectors we probed", not "this domain has none".
// A domain with SPF and DMARC in place is passing, and telling its owner
// they are missing DKIM is a false alarm they cannot act on.
m := healthyMailbox()
m.AuthState = "passing"
m.AuthSPF, m.AuthDMARC = true, true
m.AuthDKIM = false
if f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_domain_auth"]; fired {
t.Fatalf("auth detector fired on unverified DKIM alone: %q", f.Title)
}
}
func TestUnverifiedDKIMIsNotNamedAsMissing(t *testing.T) {
// It still gets a step and the host to publish at, because the owner is
// already in their DNS panel for the record that IS missing. It just must
// not be counted among the missing records.
m := healthyMailbox()
m.AuthState = "failing"
m.AuthSPF, m.AuthDMARC, m.AuthDKIM = true, false, false
f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_domain_auth"]
if !fired {
t.Fatal("auth detector did not fire on a domain with no DMARC record")
}
if strings.Contains(f.Title, "DKIM") {
t.Errorf("Title = %q, must not name DKIM as missing", f.Title)
}
if !strings.Contains(f.Detail, "DMARC") || strings.Contains(f.Detail, "DKIM record") {
t.Errorf("Detail = %q", f.Detail)
}
var hasDKIMHost bool
for _, s := range f.Snippets {
if s.Label == "DKIM host" {
hasDKIMHost = true
}
}
if !hasDKIMHost {
t.Error("an unverified DKIM should still offer the host to publish at")
}
}
func TestNewMailboxIsFlaggedOnVolumeNotOnItsCap(t *testing.T) {
m := healthyMailbox()
m.AgeDays = 3
m.ColdSent30d, m.ColdSent7d, m.ColdSent1d = 0, 0, 0
if _, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_new_ramping_fast"]; fired {
t.Fatal("a new mailbox the graduation ramp is holding back is not sending at full volume")
}
m.ColdSent30d, m.ColdSent7d, m.ColdSent1d = 120, 120, 45
f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_new_ramping_fast"]
if !fired {
t.Fatal("a three-day-old mailbox that sent 45 cold emails in a day should be flagged")
}
if f.Action == nil || f.Action.Undo == nil {
t.Fatal("the ramp fix should be applyable and undoable")
}
}
func TestWarmupOffWhileSendingIsCriticalOnANewMailbox(t *testing.T) {
m := healthyMailbox()
m.WarmupActive = false
m.AgeDays = 10
m.CampaignLimit = newMailboxSafeCap // isolate from the ramp detector
got := findingsByKey(Detect(snapshotOf(m), defaults()))
f, fired := got["warmup_off_while_sending"]
if !fired {
t.Fatal("cold sending with warmup off should be flagged")
}
if f.Severity != models.AdvisorCritical {
t.Errorf("no warmup on a new sending mailbox should be critical, got %s", f.Severity)
}
// An idle mailbox with warmup off is a setup choice, not a problem.
m.InActiveCampaign = false
if _, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["warmup_off_while_sending"]; fired {
t.Error("warmup-off fired on a mailbox that is not sending cold mail")
}
}
// Warmbly Cloud manages an enrolled mailbox's warmup, so its local columns being off is not evidence.
func TestCloudEnrolledMailboxIsNotJudgedOnLocalWarmup(t *testing.T) {
m := healthyMailbox()
m.WarmupActive = false
m.CampaignLimit = newMailboxSafeCap
m.CloudOwnsWarmup = true
got := findingsByKey(Detect(snapshotOf(m), defaults()))
if _, fired := got["warmup_off_while_sending"]; fired {
t.Error("warmup-off fired on a mailbox enrolled in Warmbly Cloud")
}
m.WarmupPaused = true
if _, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["warmup_paused"]; fired {
t.Error("warmup-paused fired on a mailbox enrolled in Warmbly Cloud")
}
// The ramp finding names Cloud as the owner rather than reporting the local columns as warmup not running.
m.AgeDays, m.CampaignLimit = 3, 50
m.ColdSent30d, m.ColdSent7d, m.ColdSent1d = 120, 120, 45
f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_new_ramping_fast"]
if !fired {
t.Fatal("a new Cloud mailbox sending at full volume should still be flagged")
}
if _, ok := f.Evidence["warmup_running"]; ok || f.Evidence["warmup_managed_by_cloud"] != true {
t.Errorf("ramp evidence on a Cloud mailbox = %v, want Cloud ownership and no local warmup reading", f.Evidence)
}
}
func TestSpamPlacementRespectsItsSampleFloorAndBands(t *testing.T) {
m := healthyMailbox()
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: minWarmupDeliveriesForPlacement - 1, MajorSpam: 5}
if _, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_spam_placement"]; fired {
t.Fatal("placement detector fired below its delivery floor")
}
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 100, MajorSpam: 55} // past the quarantine line
f := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_spam_placement"]
if f.Severity != models.AdvisorCritical {
t.Errorf("55%% spam placement should be critical, got %q", f.Severity)
}
if f.Action == nil {
t.Fatal("a mailbox this deep in spam while sending cold should offer to stop")
}
// Stopping cold sending must leave warmup running, so the fix is the hold, never status.
if f.Action.Tool != "set_mailbox_send_hold" || f.Action.Undo == nil || f.Action.Undo.Tool != "set_mailbox_send_hold" {
t.Errorf("spam placement fix should hold the mailbox and undo by releasing it, got %q", f.Action.Tool)
}
if strings.Contains(string(f.Action.Args), "status") {
t.Errorf("spam placement fix must not switch the mailbox off: %s", f.Action.Args)
}
}
func TestPlacementSlowdownDoesNotOfferACampaignHold(t *testing.T) {
for _, tc := range []struct {
spam int
severity models.AdvisorSeverity
}{
{10, models.AdvisorMedium},
{19, models.AdvisorMedium},
{20, models.AdvisorHigh},
{49, models.AdvisorHigh},
{50, models.AdvisorCritical},
} {
t.Run(fmt.Sprintf("%d percent", tc.spam), func(t *testing.T) {
m := healthyMailbox()
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 100, MajorSpam: tc.spam}
f := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_spam_placement"]
if f.Severity != tc.severity {
t.Fatalf("severity = %s, want %s", f.Severity, tc.severity)
}
if tc.spam >= 50 {
if f.Action == nil || f.Action.Tool != "set_mailbox_send_hold" || !strings.Contains(f.Remedy, "Stop cold sending") {
t.Fatalf("severe placement lost its campaign hold: %+v", f)
}
return
}
if f.Action != nil || !strings.Contains(f.Remedy, "automatically") {
t.Fatalf("recoverable placement should advise automatic slowdown without a hold: %+v", f)
}
if f.Evidence["recommended_action"] != f.Remedy {
t.Fatal("narration evidence does not carry the current recovery guidance")
}
})
}
}
func TestThrottledMailboxAdviceKeepsItInThePool(t *testing.T) {
for _, reason := range []string{
"27.3% of 22 major-provider deliveries landed in spam",
"re-entry probation after block expiry",
} {
t.Run(reason, func(t *testing.T) {
m := healthyMailbox()
m.PoolHealth, m.PoolHealthReason = "throttled", reason
m.PoolBlocked = true // A throttle's future blocked_until is not pool exclusion.
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 22, MajorSpam: 6}
byKey := findingsByKey(Detect(snapshotOf(m), defaults()))
if _, ok := byKey["warmup_pool_blocked"]; ok {
t.Fatal("a throttled mailbox is still described as excluded from the pool")
}
f, ok := byKey["warmup_pool_throttled"]
if !ok || f.Severity != models.AdvisorHigh || f.Action != nil {
t.Fatalf("expected a non-critical slowdown finding without a hold: %+v", f)
}
if !strings.Contains(f.Detail, reason) || !strings.Contains(f.Remedy, "Warmbly manage") {
t.Fatalf("throttle advice does not explain the reason and automatic recovery: %+v", f)
}
for _, key := range []string{"warmup_pool_throttled", "mailbox_spam_placement"} {
f := byKey[key]
copy := strings.ToLower(f.Remedy + " " + strings.Join(f.Steps, " "))
for _, old := range []string{"stop cold sending", "take the mailbox off", "out of cold rotation for a week", "until it requalifies", "bring it back at 5"} {
if strings.Contains(copy, old) {
t.Errorf("%s still recommends unnecessary exclusion: %s", key, copy)
}
}
if f.Action != nil || f.Evidence["recommended_action"] != f.Remedy {
t.Errorf("%s carries a hold or stale narration guidance", key)
}
}
settings := defaults()
settings.MutedDetectors = []string{"warmup_pool_throttled"}
if _, ok := findingsByKey(Detect(snapshotOf(m), settings))["warmup_pool_throttled"]; ok {
t.Fatal("the slowdown finding ignored its own mute setting")
}
})
}
}
func TestPoolExclusionIsSeparateFromRecoverableBands(t *testing.T) {
for _, state := range []string{"healthy", "watch", "quarantined", "blocked", ""} {
t.Run(state, func(t *testing.T) {
m := healthyMailbox()
m.PoolHealth, m.PoolBlocked = state, true
byKey := findingsByKey(Detect(snapshotOf(m), defaults()))
if _, ok := byKey["warmup_pool_throttled"]; ok {
t.Fatal("a non-throttled mailbox produced a throttle finding")
}
f, blocked := byKey["warmup_pool_blocked"]
if state == "healthy" || state == "watch" {
if blocked {
t.Fatalf("%s was treated as pool exclusion solely for its timer", state)
}
return
}
if !blocked || f.Severity != models.AdvisorCritical || f.Action == nil || f.Action.Tool != "set_mailbox_send_hold" {
t.Fatalf("real pool exclusion lost its severe guidance or hold: %+v", f)
}
if !strings.Contains(f.Remedy, "Stop cold sending") || f.Action.Undo == nil || strings.Contains(string(f.Action.Args), "status") {
t.Fatalf("pool exclusion must offer a reversible campaign hold without disabling warmup: %+v", f)
}
})
}
}
func TestThrottleDoesNotSuppressIndependentSafetyFindings(t *testing.T) {
m := healthyMailbox()
m.PoolHealth = "throttled"
m.AuthState, m.AuthSPF, m.AuthDMARC = "failing", false, false
m.Complaints30d, m.Bounces30d = 2, 80
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 100, MajorSpam: 50}
byKey := findingsByKey(Detect(snapshotOf(m), defaults()))
for _, key := range []string{"mailbox_domain_auth", "mailbox_complaint_rate", "mailbox_bounce_rate", "mailbox_spam_placement"} {
if f, ok := byKey[key]; !ok || f.Severity != models.AdvisorCritical {
t.Errorf("throttling suppressed independent safety finding %s: %+v", key, f)
}
}
if f := byKey["mailbox_spam_placement"]; f.Action == nil || f.Action.Tool != "set_mailbox_send_hold" {
t.Fatal("severe placement lost its hold action on a throttled mailbox")
}
}
func TestUpdatedPlacementGuidanceInvalidatesOldNarration(t *testing.T) {
m := healthyMailbox()
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 22, MajorSpam: 6}
f := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_spam_placement"]
current := f.toModel(uuid.New())
legacy := *current
var err error
legacy.Evidence, err = json.Marshal(map[string]any{
"mailbox": m.Email,
"major_provider_spam_7d": 6,
"major_provider_delivered_7d": 22,
"spam_placement_percent": band(100.0 * 6 / 22),
"quarantine_band_percent": 20.0,
"currently_sending_cold": m.SendingCold(),
"current_daily_cap": m.CampaignLimit,
})
if err != nil {
t.Fatal(err)
}
if current.EvidenceHash() == legacy.EvidenceHash() || cacheKey(current) == cacheKey(&legacy) {
t.Fatal("unchanged placement numbers would retain the old stop-sending narration after an upgrade")
}
}
// A mailbox already out of rotation gets no hold, so Undo can never release a hold someone else set.
func TestHoldFixIsOfferedOnlyWhileSendingCold(t *testing.T) {
for _, tc := range []struct {
name string
lifecycle string
status string
}{
{"held by its owner", "reserve", "active"},
{"resting", "resting", "active"},
{"switched off", "active", "inactive"},
} {
m := healthyMailbox()
m.SendLifecycle = tc.lifecycle
m.Status = tc.status
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 100, MajorSpam: 55}
m.PoolHealth = "quarantined"
found := findingsByKey(Detect(snapshotOf(m), defaults()))
for _, key := range []string{"mailbox_spam_placement", "warmup_pool_blocked"} {
if f, ok := found[key]; ok && f.Action != nil {
t.Errorf("%s: %s offered %q on a mailbox that is not sending cold", tc.name, key, f.Action.Label)
}
}
}
}
func TestMinSeveritySettingFiltersFindings(t *testing.T) {
m := healthyMailbox()
m.CampaignLimit = 80 // low-severity on a proven mailbox
m.MinWaitTime = 60 // medium-severity burst gap
settings := defaults()
settings.MinSeverity = models.AdvisorHigh
for _, f := range Detect(snapshotOf(m), settings) {
if !f.Severity.AtLeast(models.AdvisorHigh) {
t.Errorf("finding %s (%s) survived a min_severity of high", f.Key, f.Severity)
}
}
}
func TestMutedCategoryIsSkipped(t *testing.T) {
m := healthyMailbox()
m.WarmupActive = false
settings := defaults()
settings.MutedCategories = []string{string(models.AdvisorCategoryWarmup)}
for _, f := range Detect(snapshotOf(m), settings) {
if f.Category == models.AdvisorCategoryWarmup {
t.Errorf("warmup finding %s survived a muted warmup category", f.Key)
}
}
}
func TestFingerprintIsStablePerDetectorAndEntity(t *testing.T) {
// The fingerprint is what makes a re-run update the same row instead of
// duplicating advice, and what makes a dismissal stick.
id := uuid.New()
a := Finding{Key: "mailbox_cap_too_high", EntityType: "email_account", EntityID: &id}
b := Finding{Key: "mailbox_cap_too_high", EntityType: "email_account", EntityID: &id, Severity: models.AdvisorCritical}
if a.Fingerprint() != b.Fingerprint() {
t.Error("fingerprint changed when only the severity did")
}
other := uuid.New()
c := Finding{Key: "mailbox_cap_too_high", EntityType: "email_account", EntityID: &other}
if a.Fingerprint() == c.Fingerprint() {
t.Error("two mailboxes with the same problem share a fingerprint")
}
orgWide := Finding{Key: "org_check"}
if orgWide.Fingerprint() != "org_check|org" {
t.Errorf("org-scoped fingerprint is %q", orgWide.Fingerprint())
}
}
func TestEveryDetectorHasAKeyAndDescription(t *testing.T) {
// The description is what the narrator is grounded in. A detector without
// one produces advice the model has to guess the reasoning for.
seen := map[string]bool{}
for _, d := range AllDetectors() {
if d.Key == "" {
t.Fatal("detector with an empty key")
}
if seen[d.Key] {
t.Errorf("duplicate detector key %q", d.Key)
}
seen[d.Key] = true
if len(d.About) < 40 {
t.Errorf("detector %q has no usable description for the narrator", d.Key)
}
if d.Category == "" {
t.Errorf("detector %q has no category, so it cannot be muted", d.Key)
}
if d.Run == nil {
t.Errorf("detector %q has no implementation", d.Key)
}
}
}
func TestDetectorsTolerateAnEmptySnapshot(t *testing.T) {
// A partial snapshot load must not panic a whole org's evaluation.
empty := &repository.AdvisorSnapshot{
OrganizationID: uuid.New(),
Now: time.Now(),
Lists: map[uuid.UUID]repository.AdvisorListStats{},
}
if got := Detect(empty, defaults()); len(got) != 0 {
t.Errorf("an empty workspace produced %d findings", len(got))
}
}
func TestFindingsAreOrderedMostUrgentFirst(t *testing.T) {
broken := healthyMailbox()
broken.AuthSPF, broken.AuthDKIM, broken.AuthDMARC = false, false, false
broken.AuthState = "failing"
broken.MinWaitTime = 60
broken.CampaignLimit = 90
got := Detect(snapshotOf(broken), defaults())
if len(got) < 2 {
t.Fatalf("expected several findings, got %d", len(got))
}
for i := 1; i < len(got); i++ {
if got[i-1].Severity.Rank() < got[i].Severity.Rank() {
t.Fatalf("findings out of order: %s(%s) before %s(%s)",
got[i-1].Key, got[i-1].Severity, got[i].Key, got[i].Severity)
}
}
}
func TestCopyDetectorsIgnoreDraftCampaigns(t *testing.T) {
campaignID := uuid.New()
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Draft", Status: "draft"}}
snap.Steps = []repository.AdvisorStep{{
ID: uuid.New(), CampaignID: campaignID, Kind: "email",
Subject: "ACT NOW!! LIMITED TIME!!",
BodyPlain: "click here to buy now, this is not spam, 100% free",
}}
for _, f := range Detect(snap, defaults()) {
if f.Category == models.AdvisorCategoryCopy {
t.Errorf("copy detector %q fired on an unfinished draft", f.Key)
}
}
}
func TestCopyFindingsAttachToTheirCampaign(t *testing.T) {
// A copy problem lives on a step, but someone looking for it is on the
// campaign page, so the finding has to carry its campaign as a parent.
campaignID := uuid.New()
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Q3 outbound", Status: "active"}}
snap.Steps = []repository.AdvisorStep{{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1,
Name: "Opener",
Subject: "quick question",
BodyPlain: "Act now, this is a limited time offer with no obligation.",
}}
found := false
for _, f := range Detect(snap, defaults()) {
if f.Category != models.AdvisorCategoryCopy {
continue
}
found = true
if f.ParentType != "campaign" || f.ParentID == nil || *f.ParentID != campaignID {
t.Errorf("copy finding %q is not attached to its campaign", f.Key)
}
}
if !found {
t.Error("expected a copy finding on obvious bulk-mail phrasing")
}
}
func TestSingleSpamPhraseIsNotAFinding(t *testing.T) {
// One borderline word in otherwise fine copy is not evidence of anything,
// and firing on it is how a linter loses its audience.
campaignID := uuid.New()
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Outbound", Status: "active"}}
snap.Steps = []repository.AdvisorStep{{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1,
Subject: "quick question about your onboarding",
BodyPlain: "We guarantee delivery within a day. Worth a chat?",
}}
for _, f := range Detect(snap, defaults()) {
if f.Key == "copy_spam_phrases" {
t.Error("spam-phrase detector fired on a single ordinary word")
}
}
}
func TestActionsCarryARenderedPreview(t *testing.T) {
// Nothing is applied sight-unseen: an action with no preview would put a
// confirm dialog on screen with nothing to confirm.
m := healthyMailbox()
m.CampaignLimit = 90
m.MinWaitTime = 60
m.WarmupMax = 5
for _, f := range Detect(snapshotOf(m), defaults()) {
if f.Action == nil {
continue
}
if f.Action.Tool == "" {
t.Errorf("finding %q has an action with no tool", f.Key)
}
if len(f.Action.Args) == 0 {
t.Errorf("finding %q has an action with no arguments", f.Key)
}
if len(f.Action.Preview) == 0 {
t.Errorf("finding %q has an action the user cannot preview", f.Key)
}
if f.Action.Label == "" {
t.Errorf("finding %q has an unlabelled action button", f.Key)
}
}
}
func TestEveryFindingIsSelfContained(t *testing.T) {
// The narrator only ever sees the evidence map. A finding that leans on
// context outside it would produce copy that quietly drops the specifics.
m := healthyMailbox()
m.CampaignLimit = 120
m.MinWaitTime = 30
m.AuthDMARC = false
m.AuthState = "failing"
m.Complaints30d = 5
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 60, MajorSpam: 20}
for _, f := range Detect(snapshotOf(m), defaults()) {
if f.Title == "" || f.Detail == "" || f.Remedy == "" {
t.Errorf("finding %q ships incomplete fallback copy", f.Key)
}
if len(f.Evidence) == 0 {
t.Errorf("finding %q carries no evidence", f.Key)
}
if f.Surface == "" {
t.Errorf("finding %q has no surface, so it cannot be shown anywhere", f.Key)
}
}
}
func TestScoreFallsWithSeverity(t *testing.T) {
if got := models.AdvisorScore(0, 0, 0, 0); got != 100 {
t.Errorf("a clean workspace should score 100, got %d", got)
}
if clean, one := models.AdvisorScore(0, 0, 0, 0), models.AdvisorScore(1, 0, 0, 0); one >= clean {
t.Error("a critical finding should lower the score")
}
// One critical has to outweigh a pile of suggestions, or the score stops
// meaning anything.
if models.AdvisorScore(1, 0, 0, 0) >= models.AdvisorScore(0, 0, 0, 10) {
t.Error("one critical finding should cost more than ten low-severity ones")
}
// The penalty saturates rather than accumulating linearly, so a badly
// broken workspace still gets a number that moves when it fixes something.
// A linear score pins at 0 after about four high-severity findings, after
// which fixing three of them changes nothing on screen.
bad, worse := models.AdvisorScore(6, 0, 0, 0), models.AdvisorScore(20, 0, 0, 0)
if worse >= bad {
t.Error("more critical findings should still score worse")
}
if worse < 1 {
t.Errorf("the score should never reach 0, got %d", worse)
}
// Across the range a workspace actually lives in, every fix moves the
// number. (Far out in the tail the curve flattens into the floor, which is
// the correct behaviour: at twenty critical findings the score has already
// said everything it can.)
if before, after := models.AdvisorScore(0, 6, 9, 8), models.AdvisorScore(0, 5, 9, 8); after <= before {
t.Error("fixing one high-severity finding should raise the score")
}
}
func TestValidGoTemplatesAreNotFlagged(t *testing.T) {
// The copy in this product is a Go template. Conditionals, pipelines, and
// the index form for spaced custom fields are all correct, and a detector
// that flags them would fire on most well-written campaigns in the product.
campaignID := uuid.New()
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Outbound", Status: "active"}}
snap.Steps = []repository.AdvisorStep{{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1,
Subject: "quick question about {{.Company}}",
BodyPlain: "Hi {{.FirstName}},\n\n" +
`{{if .Company}}Saw {{.Company}} is hiring.{{else}}Saw your team is hiring.{{end}}` +
"\n{{index . \"city\"}} came up too.\n\nWorth a chat?",
}}
for _, f := range Detect(snap, defaults()) {
if f.Key == "copy_broken_template" {
t.Errorf("valid Go template flagged as broken: %s", f.Detail)
}
}
}
func TestUnparseableTemplateIsFlagged(t *testing.T) {
campaignID := uuid.New()
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Outbound", Status: "active"}}
snap.Steps = []repository.AdvisorStep{{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1,
Name: "Opener",
Subject: "quick question",
BodyPlain: "Hi {{.FirstName}},\n\n{{if .Company}}Saw you are hiring.\n\nWorth a chat?",
}}
f, fired := findingsByKey(Detect(snap, defaults()))["copy_broken_template"]
if !fired {
t.Fatal("an {{if}} with no {{end}} should be flagged: it ships as literal text")
}
if f.Severity != models.AdvisorHigh {
t.Errorf("broken copy in a sending campaign should be high, got %s", f.Severity)
}
}
func TestUnparseableHTMLBodyIsFlagged(t *testing.T) {
campaignID := uuid.New()
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Outbound", Status: "paused"}}
snap.Steps = []repository.AdvisorStep{{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1,
Subject: "quick question",
BodyPlain: "Hi {{.FirstName}}",
BodyHTML: "<p>Hi {{if .FirstName}}{{.FirstName}}</p>",
}}
if _, fired := findingsByKey(Detect(snap, defaults()))["copy_broken_template"]; !fired {
t.Fatal("a broken HTML body should be flagged: it is the part most clients show")
}
}
func TestMissingFirstNameOnlyFiresWhenTheCopyLeavesAGap(t *testing.T) {
campaignID := uuid.New()
build := func(body string, followUps ...repository.AdvisorStep) *repository.AdvisorSnapshot {
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Outbound", Status: "active"}}
snap.Steps = append([]repository.AdvisorStep{{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Subject: "hello", BodyPlain: body,
}}, followUps...)
snap.Lists = map[uuid.UUID]repository.AdvisorListStats{
campaignID: {CampaignID: campaignID, Total: 200, MissingFirstName: 60},
}
return snap
}
if _, fired := findingsByKey(Detect(build("Hi there, worth a chat?"), defaults()))["list_missing_personalization_data"]; fired {
t.Error("missing-first-name fired on copy that never greets by name")
}
for _, body := range []string{"Hi {{.FirstName}}, worth a chat?", "Hi {{first_name}}, worth a chat?", "Hi {{if .Company}}{{.FirstName}}{{end}}"} {
if _, fired := findingsByKey(Detect(build(body), defaults()))["list_missing_personalization_data"]; !fired {
t.Errorf("missing-first-name did not fire on copy that prints a missing name: %q", body)
}
}
for _, body := range []string{
"{{if .FirstName}}Bonjour {{.FirstName}},{{else}}Bonjour,{{end}}",
"Hi {{.firstName | default \"there\"}}",
"{{with .FirstName}}Hi {{.}},{{else}}Hi,{{end}}",
} {
if _, fired := findingsByKey(Detect(build(body), defaults()))["list_missing_personalization_data"]; fired {
t.Errorf("missing-first-name fired on copy with a fallback for the name: %q", body)
}
}
threaded := repository.AdvisorStep{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1, ThreadReply: true,
Subject: "Quick one, {{.FirstName}}", BodyPlain: "Following up.",
}
if _, fired := findingsByKey(Detect(build("Hi there,", threaded), defaults()))["list_missing_personalization_data"]; fired {
t.Error("missing-first-name fired on the subject of a follow-up that is sent under the conversation's subject")
}
if _, fired := findingsByKey(Detect(build("Update the firstname on file, or first_name in your CRM."), defaults()))["list_missing_personalization_data"]; fired {
t.Error("missing-first-name fired on prose that only mentions the field")
}
}
func TestAutopilotOnlyGetsReversibleSafeFixes(t *testing.T) {
// Autopilot applies changes with nobody watching, so the set of fixes it is
// allowed to touch is a safety boundary, not a convenience. This pins it:
// an auto fix must be undoable, and the checks that stop a customer's
// sending or edit their copy must never drift into the set.
m := healthyMailbox()
m.CampaignLimit = 120
m.MinWaitTime = 30
m.Complaints30d = 5
m.ColdSent30d = 4000
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 60, MajorSpam: 30}
m.InActiveCampaign = true
// Detectors whose one-click fix is deliberately hand-only: each either
// halts sending or generates new outbound mail the member did not ask for.
handOnly := map[string]bool{
"mailbox_spam_placement": true,
"warmup_pool_blocked": true,
"warmup_off": true,
"warmup_paused": true,
"warmup_ceiling_low": true,
}
autos := 0
for _, f := range Detect(snapshotOf(m), defaults()) {
if f.Action == nil || !f.Action.Auto {
continue
}
autos++
if f.Action.Undo == nil {
t.Errorf("finding %q is auto-applied but cannot be undone", f.Key)
}
if handOnly[f.Key] {
t.Errorf("finding %q must not be auto-applied: it changes sending without asking", f.Key)
}
}
if autos == 0 {
t.Fatal("no auto-safe fix fired, so this test is not checking anything")
}
}
func TestEveryFindingOffersAWayForward(t *testing.T) {
// The gap this closes: a finding with no one-click fix, no agent, and no
// steps leaves the reader a paragraph of prose and no instruction. That is
// how a missing DMARC record ended up as a dead end, and it was not the
// only one.
//
// Every finding must offer at least one of: a fix to apply, an agent that
// can do it, or ordered steps to do it by hand.
m := healthyMailbox()
m.CampaignLimit = 120
m.MinWaitTime = 30
m.AuthDMARC = false
m.AuthSPF = false
m.AuthState = "failing"
m.Complaints30d = 5
m.ColdSent30d = 4000
m.Bounces30d = 300
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 60, MajorSpam: 30}
m.UnresolvedErrs = 5
m.TrackingDomain = ""
m.InActiveCampaign = true
m.PoolBlocked = true
m.PoolHealthScore = 80
m.PoolHealthReason = "warmup spam placement 50.0% exceeded block threshold"
findings := Detect(snapshotOf(m), defaults())
if len(findings) < 5 {
t.Fatalf("this mailbox should trip most of the detectors, got %d findings", len(findings))
}
for _, f := range findings {
hasFix := f.Action != nil
hasAgent := agentFixable[f.Key]
hasSteps := len(f.Steps) > 0
if !hasFix && !hasAgent && !hasSteps {
t.Errorf("finding %q offers no way forward: no fix, no agent, no steps", f.Key)
}
}
}
func TestDNSFindingsShipThePasteableRecord(t *testing.T) {
// Telling somebody to "add an SPF record" is where most people stop. The
// record itself is the fix, so a finding whose remedy lives in DNS has to
// carry the value to paste.
m := healthyMailbox()
m.Email = "sender@acme.test"
m.Provider = "gmail"
m.AuthSPF = false
m.AuthDMARC = false
m.AuthState = "failing"
byKey := findingsByKey(Detect(snapshotOf(m), defaults()))
auth, ok := byKey["mailbox_domain_auth"]
if !ok {
t.Fatal("domain auth did not fire on a mailbox missing SPF and DMARC")
}
if len(auth.Snippets) == 0 {
t.Fatal("domain auth carries no records to paste")
}
joined := ""
for _, s := range auth.Snippets {
if s.Label == "" {
t.Error("a snippet has no label, so it is unclear what field it goes in")
}
joined += s.Label + "=" + s.Value + "\n"
}
// The provider-specific include and the domain-specific DMARC host are the
// two values a generic template gets wrong.
if !strings.Contains(joined, "include:_spf.google.com") {
t.Errorf("SPF record does not carry the Google include for a gmail mailbox:\n%s", joined)
}
if !strings.Contains(joined, "_dmarc.acme.test") {
t.Errorf("DMARC host is not scoped to the sending domain:\n%s", joined)
}
if !strings.Contains(joined, "p=none") {
t.Errorf("DMARC record should start in monitor-only mode:\n%s", joined)
}
}
// The finding used to print a spam score that had not caused the state it
// described: nothing read that number, and it grew with volume rather than
// with misbehaviour (#491). It now prints the band's own reason.
func TestWarmupPoolFindingExplainsItselfWithTheBandsReason(t *testing.T) {
m := healthyMailbox()
m.PoolHealth = "blocked"
m.PoolBlocked = true
m.PoolHealthScore = 62
m.PoolHealthReason = "warmup spam placement 44.0% exceeded block threshold"
var found *Finding
findings := Detect(snapshotOf(m), defaults())
for i := range findings {
if findings[i].Key == "warmup_pool_blocked" {
found = &findings[i]
break
}
}
if found == nil {
t.Fatal("a blocked mailbox produced no warmup_pool_blocked finding")
}
if !strings.Contains(found.Detail, m.PoolHealthReason) {
t.Fatalf("detail does not say why the band acted: %q", found.Detail)
}
if strings.Contains(strings.ToLower(found.Detail), "spam score") {
t.Fatalf("detail still quotes a spam score: %q", found.Detail)
}
if got := found.Evidence["pool_health_reason"]; got != m.PoolHealthReason {
t.Fatalf("evidence pool_health_reason = %v, want the band's reason", got)
}
if _, ok := found.Evidence["spam_score"]; ok {
t.Fatal("evidence still carries a spam score")
}
}
func TestUnavailableCloudStandingDoesNotInventAReputationBan(t *testing.T) {
m := healthyMailbox()
m.PoolHealth, m.PoolHealthReason = "blocked", "cloud_evidence_unavailable"
byKey := findingsByKey(Detect(snapshotOf(m), defaults()))
if _, ok := byKey["warmup_pool_blocked"]; ok {
t.Fatal("unavailable Cloud evidence was described as lost pool standing")
}
f, ok := byKey["cloud_standing_unavailable"]
if !ok || !strings.Contains(f.Remedy, "cloud_standing_sync") || len(f.Steps) == 0 || f.Action != nil {
t.Fatalf("availability finding does not offer a safe status refresh: %+v", f)
}
settings := defaults()
settings.MutedDetectors = []string{"cloud_standing_unavailable"}
if _, ok := findingsByKey(Detect(snapshotOf(m), settings))["cloud_standing_unavailable"]; ok {
t.Fatal("Cloud availability detector ignored its own mute setting")
}
m.PoolHealthReason = "complaints"
byKey = findingsByKey(Detect(snapshotOf(m), defaults()))
if _, ok := byKey["warmup_pool_blocked"]; !ok {
t.Fatal("a real Cloud block stopped being reported")
}
}
// The no-senders finding names the way the campaign actually picks mailboxes,
// so a campaign on "every active mailbox" is never sent to check its tags (#661).
func TestNoSendersNamesHowTheCampaignPicksMailboxes(t *testing.T) {
cases := []struct {
name string
camp repository.AdvisorCampaign
selection string
mentionTag bool
}{
{"all", repository.AdvisorCampaign{SenderStrategy: "tags"}, "every active mailbox", false},
{"explicit empty", repository.AdvisorCampaign{SenderStrategy: "explicit"}, "picked by hand", false},
{"picked", repository.AdvisorCampaign{SenderStrategy: "tags", PickedSenders: 3}, "picked by hand", false},
{"tags", repository.AdvisorCampaign{SenderStrategy: "tags", SenderTags: 1}, "by tag", true},
{"both", repository.AdvisorCampaign{SenderStrategy: "tags", PickedSenders: 2, SenderTags: 1}, "picked by hand and by tag", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
camp := tc.camp
camp.ID, camp.Name, camp.Status, camp.LeadsRemaining = uuid.New(), "Q4", "active", 274
found := detectNoSenders(&repository.AdvisorSnapshot{Campaigns: []repository.AdvisorCampaign{camp}})
if len(found) != 1 {
t.Fatalf("got %d findings, want 1", len(found))
}
f := found[0]
if got := f.Evidence["sender_selection"]; got != tc.selection {
t.Fatalf("sender_selection = %v, want %q", got, tc.selection)
}
if _, ok := f.Evidence["sender_strategy"]; ok {
t.Fatal("evidence still carries sender_strategy, which reads 'tags' for a campaign that picks nothing")
}
copy := strings.ToLower(f.Detail + " " + f.Remedy + " " + strings.Join(f.Steps, " "))
if got := strings.Contains(copy, "tag"); got != tc.mentionTag {
t.Fatalf("copy mentions tags = %v, want %v: %s", got, tc.mentionTag, copy)
}
})
}
}
// Everything junked at small hosts while Google and Microsoft inbox all of it
// is not a mailbox landing in spam.
func TestSpamPlacementAtSmallHostsAloneDoesNotAlarm(t *testing.T) {
m := healthyMailbox()
m.InActiveCampaign = true
m.WarmupPlacement = models.WarmupPlacementEvidence{MajorDelivered: 40, OtherDelivered: 40, OtherSpam: 40}
if f, fired := findingsByKey(Detect(snapshotOf(m), defaults()))["mailbox_spam_placement"]; fired {
t.Fatalf("small-host spam alone raised %q: %s", f.Severity, f.Title)
}
}
// A warming mailbox the pool has stopped reaching is told why, and the finding
// goes away the moment one warmup email arrives or warmup is off.
func TestDetectWarmupMailNotArriving(t *testing.T) {
fires := func(m repository.AdvisorMailbox) bool {
t.Helper()
for _, f := range Detect(snapshotOf(m), defaults()) {
if f.Key == "warmup_mail_not_arriving" {
return true
}
}
return false
}
m := healthyMailbox()
m.WarmupDelivered7d, m.WarmupLostBy7d = 12, 3
if !fires(m) {
t.Fatal("an unreachable warming mailbox produced no finding")
}
arrived := m
arrived.WarmupArrived7d = 1
if fires(arrived) {
t.Fatal("a mailbox that verified an arrival is still reported")
}
oneSender := m
oneSender.WarmupLostBy7d = 1
if fires(oneSender) {
t.Fatal("losses from one workspace are blamed on the recipient")
}
off := m
off.WarmupActive = false
if fires(off) {
t.Fatal("a mailbox with warmup off is reported")
}
if fires(healthyMailbox()) {
t.Fatal("a healthy mailbox is reported")
}
}
// busySnapshot fires as many section-reading detectors as one fixture can.
func busySnapshot() *repository.AdvisorSnapshot {
campaignID, otherID := uuid.New(), uuid.New()
heavy := healthyMailbox()
heavy.ColdSent7d, heavy.ColdSent30d = 5000, 20000
snap := snapshotOf(heavy, healthyMailbox())
snap.Campaigns = []repository.AdvisorCampaign{
{
ID: campaignID, Name: "Outbound", Status: "active",
DailyLimit: 900, StartTime: "09:00", EndTime: "09:30",
SenderCount: 1, SenderCapacity: 50, PickedSenders: 1, SenderStrategy: "explicit",
StepCount: 2, EmailStepCount: 2, VariantCount: 1,
Sent: 3000, Opened: 300, Replied: 1, Bounced: 10,
LeadsTotal: 1000, LeadsRemaining: 5,
},
{ID: otherID, Name: "Solo", Status: "active", StepCount: 1, EmailStepCount: 1, DailyLimit: 10, Sent: 10},
}
snap.Steps = []repository.AdvisorStep{
{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1, Name: "Opener", WaitAfter: 1,
Subject: "ACT NOW!! LIMITED TIME OFFER, THIS IS NOT SPAM AND IT IS 100% FREE FOR YOU AND YOUR WHOLE TEAM TODAY",
BodyPlain: "Hi {{.FirstName}},\n\n{{if .Company}}Act now, click here, buy now, limited time, no obligation, 100% free, risk free. https://a.example https://b.example https://c.example " + strings.Repeat("More words here. ", 200),
Sent: 2000, Replied: 40,
},
{
ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 2, Name: "Bump",
Subject: "re", BodyPlain: "Hi {{.FirstName}}, any thoughts?",
Sent: 1000, Replied: 0,
},
}
snap.Lists = map[uuid.UUID]repository.AdvisorListStats{
campaignID: {CampaignID: campaignID, Total: 1000, RoleAddresses: 400, FreeMail: 700, Suppressed: 200, Unsubscribed: 30, MissingFirstName: 500},
}
snap.Org = repository.AdvisorOrgStats{Mailboxes: 2, ActiveMailboxes: 2, RunningCampaigns: 2, DuplicateContacts: 150}
return snap
}
// A detector that reads a section it does not declare would resolve its
// findings on a run where that section failed to load.
func TestDetectorsDeclareEverySectionTheyRead(t *testing.T) {
blank := map[repository.AdvisorSection]func(*repository.AdvisorSnapshot){
repository.AdvisorSectionCampaigns: func(s *repository.AdvisorSnapshot) { s.Campaigns = nil },
repository.AdvisorSectionSteps: func(s *repository.AdvisorSnapshot) { s.Steps = nil },
repository.AdvisorSectionLists: func(s *repository.AdvisorSnapshot) { s.Lists = map[uuid.UUID]repository.AdvisorListStats{} },
repository.AdvisorSectionOrg: func(s *repository.AdvisorSnapshot) { s.Org = repository.AdvisorOrgStats{} },
}
fingerprints := func(fs []Finding) string {
out := make([]string, 0, len(fs))
for _, f := range fs {
out = append(out, f.Fingerprint())
}
return strings.Join(out, ",")
}
base := busySnapshot()
for _, d := range AllDetectors() {
full := d.Run(base)
if len(d.Reads) > 0 && len(full) == 0 {
t.Errorf("detector %q reads a section but does not fire on the fixture, so this check cannot see it", d.Key)
}
for sec, clear := range blank {
declared := false
for _, r := range d.Reads {
declared = declared || r == sec
}
if declared {
continue
}
s := *base
clear(&s)
if fingerprints(d.Run(&s)) != fingerprints(full) {
t.Errorf("detector %q reads the %s section but does not declare it", d.Key, sec)
}
}
}
}
func TestFailedSectionHoldsItsDetectors(t *testing.T) {
snap := busySnapshot()
snap.Failed = map[repository.AdvisorSection]error{repository.AdvisorSectionLists: errors.New("statement timeout")}
settings := defaults()
for _, f := range Detect(snap, settings) {
if strings.HasPrefix(f.Key, "list_") {
t.Errorf("%s opened from a list section that did not load", f.Key)
}
}
held := map[string]bool{}
for _, k := range heldDetectors(snap, settings) {
held[k] = true
}
for _, d := range AllDetectors() {
if want := strings.HasPrefix(d.Key, "list_"); held[d.Key] != want {
t.Errorf("detector %q held = %v, want %v", d.Key, held[d.Key], want)
}
}
// A muted detector is not held, so its findings still close as before.
settings.MutedDetectors = []string{"list_role_addresses"}
for _, k := range heldDetectors(snap, settings) {
if k == "list_role_addresses" {
t.Error("a muted detector was held open")
}
}
snap.Failed = nil
if got := heldDetectors(snap, settings); len(got) != 0 {
t.Errorf("a complete snapshot held %v", got)
}
}
func TestCopyIsMeasuredAsTheRecipientReadsIt(t *testing.T) {
campaignID := uuid.New()
run := func(st repository.AdvisorStep) map[string]Finding {
snap := snapshotOf()
snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Outbound", Status: "active"}}
st.ID, st.CampaignID, st.Kind = uuid.New(), campaignID, "email"
snap.Steps = []repository.AdvisorStep{st}
return findingsByKey(Detect(snap, defaults()))
}
got := run(repository.AdvisorStep{
Subject: "{{if .Company}}Une question pour {{.Company}}{{else}}Une question rapide{{end}}, équipe",
BodyHTML: `<p>Voir <a href="https://example.com/a">https://example.com/a</a> et <a href="https://example.com/b">ici</a>.</p><img src="https://cdn.example.com/logo.png">`,
})
for _, key := range []string{"copy_shouty_subject", "copy_too_many_links"} {
if _, fired := got[key]; fired {
t.Errorf("%s fired on template syntax or markup rather than on what is sent", key)
}
}
spun := "{Book https://cal.example/x|Grab https://cal.example/x|Meet https://cal.example/x} or {see https://a.example/{one|two}|read https://a.example/one}."
if _, fired := run(repository.AdvisorStep{Subject: "hello", BodyPlain: spun})["copy_too_many_links"]; fired {
t.Error("spintax options naming the same address counted as several links")
}
if _, fired := run(repository.AdvisorStep{Subject: "hello", BodyPlain: "{https://a.example https://b.example https://c.example|thanks}"})["copy_too_many_links"]; !fired {
t.Error("an option some recipients get with three links was not flagged")
}
if _, fired := run(repository.AdvisorStep{Subject: "hello", BodyPlain: "I will contact now and then. We are not insurgent."})["copy_spam_phrases"]; fired {
t.Error("spam phrases matched inside other words")
}
if _, fired := run(repository.AdvisorStep{Subject: "hello", BodyPlain: "It is guaranteed. Act now."})["copy_spam_phrases"]; !fired {
t.Error("spam phrases missed whole phrases")
}
}
func TestMailboxFindingsOnlyClaimWhatIsHappening(t *testing.T) {
cases := []struct {
name, key string
state func(*repository.AdvisorMailbox, *repository.AdvisorSnapshot)
fires bool
}{
{"untracked campaign", "mailbox_shared_tracking_domain", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.TrackingDomain = ""
}, false},
{"tracked campaign", "mailbox_shared_tracking_domain", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.TrackingDomain, m.TrackedOnMailboxHost = "", true
}, true},
{"disconnected mailbox's stale DNS", "mailbox_domain_auth", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.Status, m.AuthState, m.AuthDMARC = "inactive", models.AuthStateFailing, false
}, false},
{"warmup off, plan cannot warm", "warmup_off_while_sending", func(m *repository.AdvisorMailbox, s *repository.AdvisorSnapshot) {
m.WarmupActive, s.WarmupUnavailable = false, true
}, false},
{"warmup off, nothing sent", "warmup_off_while_sending", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.WarmupActive, m.ColdSent7d = false, 0
}, false},
{"warmup off while sending", "warmup_off_while_sending", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.WarmupActive = false
}, true},
{"paused after the trial", "warmup_paused", func(m *repository.AdvisorMailbox, s *repository.AdvisorSnapshot) {
m.WarmupActive, m.WarmupPaused, s.WarmupUnavailable = false, true, true
}, false},
{"paused on a mailbox sending nothing", "warmup_paused", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.WarmupActive, m.WarmupPaused, m.ColdSent7d = false, true, 0
}, false},
{"paused while sending cold", "warmup_paused", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.WarmupActive, m.WarmupPaused = false, true
}, true},
{"high cap on a clean mailbox", "mailbox_cap_too_high", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.CampaignLimit, m.ColdSent1d = 120, 110
}, false},
{"high cap, new and sending under the band", "mailbox_cap_too_high", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.CampaignLimit, m.ColdSent30d, m.ColdSent1d = 120, 40, 30
}, false},
{"high cap, new and sending above the band", "mailbox_cap_too_high", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.CampaignLimit, m.ColdSent30d, m.ColdSent1d = 120, 80, 80
}, true},
{"high cap while complaining", "mailbox_cap_too_high", func(m *repository.AdvisorMailbox, _ *repository.AdvisorSnapshot) {
m.CampaignLimit, m.Complaints30d = 120, 5
}, true},
}
for _, tc := range cases {
m := healthyMailbox()
m.CampaignLimit = newMailboxSafeCap
s := snapshotOf()
tc.state(&m, s)
s.Mailboxes = []repository.AdvisorMailbox{m}
if _, fired := findingsByKey(Detect(s, defaults()))[tc.key]; fired != tc.fires {
t.Errorf("%s: %s fired=%v, want %v", tc.name, tc.key, fired, tc.fires)
}
}
}