package main import ( "context" "errors" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/hostedctl" "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" "github.com/aws/aws-sdk-go-v2/service/sns" ) // recordingSNS records each Publish call and whether its context had a // deadline. type recordingSNS struct { inputs []*sns.PublishInput deadlines []time.Duration fail error } func (r *recordingSNS) Publish(ctx context.Context, in *sns.PublishInput, _ ...func(*sns.Options)) (*sns.PublishOutput, error) { r.inputs = append(r.inputs, in) d := time.Duration(-1) if dl, ok := ctx.Deadline(); ok { d = time.Until(dl) } r.deadlines = append(r.deadlines, d) return &sns.PublishOutput{}, r.fail } func TestAlerterWrapsPublisher(t *testing.T) { t.Parallel() rec := &recordingSNS{} a := snsAlerter{pub: awsjob.SNSPublisher{TopicARN: "arn:aws:sns:eu-west-1:1:t", Client: rec}} // A context with no deadline, as New uses for startup alerts. if err := a.Alert(context.Background(), hostedctl.Alert{Kind: hostedctl.AlertOrphanStopped, Detail: "vm-1 stopped"}); err != nil { t.Fatal(err) } if len(rec.inputs) != 1 { t.Fatalf("%d publishes, want 1", len(rec.inputs)) } in := rec.inputs[0] if *in.TopicArn != "arn:aws:sns:eu-west-1:1:t" || !strings.Contains(*in.Subject, hostedctl.AlertOrphanStopped) || *in.Message != hostedctl.AlertOrphanStopped+"\n\nvm-1 stopped" { t.Fatalf("publish input = topic %q subject %q message %q", *in.TopicArn, *in.Subject, *in.Message) } if d := rec.deadlines[0]; d <= 0 || d > alertTimeout { t.Fatalf("publish context deadline in %v, want within %v", d, alertTimeout) } // A shorter deadline from the caller is kept, and a failure is returned. rec.fail = errors.New("sns down") ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := a.Alert(ctx, hostedctl.Alert{Kind: "k"}); err == nil { t.Fatal("a failed publish returned nil") } if d := rec.deadlines[1]; d <= 0 || d > time.Second { t.Fatalf("publish context deadline in %v, want the caller's 1s", d) } }