| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/hostedctl" |
| 11 | "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" |
| 12 | "github.com/aws/aws-sdk-go-v2/service/sns" |
| 13 | ) |
| 14 | |
| 15 | // recordingSNS records each Publish call and whether its context had a |
| 16 | // deadline. |
| 17 | type recordingSNS struct { |
| 18 | inputs []*sns.PublishInput |
| 19 | deadlines []time.Duration |
| 20 | fail error |
| 21 | } |
| 22 | |
| 23 | func (r *recordingSNS) Publish(ctx context.Context, in *sns.PublishInput, _ ...func(*sns.Options)) (*sns.PublishOutput, error) { |
| 24 | r.inputs = append(r.inputs, in) |
| 25 | d := time.Duration(-1) |
| 26 | if dl, ok := ctx.Deadline(); ok { |
| 27 | d = time.Until(dl) |
| 28 | } |
| 29 | r.deadlines = append(r.deadlines, d) |
| 30 | return &sns.PublishOutput{}, r.fail |
| 31 | } |
| 32 | |
| 33 | func TestAlerterWrapsPublisher(t *testing.T) { |
| 34 | t.Parallel() |
| 35 | rec := &recordingSNS{} |
| 36 | a := snsAlerter{pub: awsjob.SNSPublisher{TopicARN: "arn:aws:sns:eu-west-1:1:t", Client: rec}} |
| 37 | // A context with no deadline, as New uses for startup alerts. |
| 38 | if err := a.Alert(context.Background(), hostedctl.Alert{Kind: hostedctl.AlertOrphanStopped, Detail: "vm-1 stopped"}); err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | if len(rec.inputs) != 1 { |
| 42 | t.Fatalf("%d publishes, want 1", len(rec.inputs)) |
| 43 | } |
| 44 | in := rec.inputs[0] |
| 45 | if *in.TopicArn != "arn:aws:sns:eu-west-1:1:t" || !strings.Contains(*in.Subject, hostedctl.AlertOrphanStopped) || |
| 46 | *in.Message != hostedctl.AlertOrphanStopped+"\n\nvm-1 stopped" { |
| 47 | t.Fatalf("publish input = topic %q subject %q message %q", *in.TopicArn, *in.Subject, *in.Message) |
| 48 | } |
| 49 | if d := rec.deadlines[0]; d <= 0 || d > alertTimeout { |
| 50 | t.Fatalf("publish context deadline in %v, want within %v", d, alertTimeout) |
| 51 | } |
| 52 | |
| 53 | // A shorter deadline from the caller is kept, and a failure is returned. |
| 54 | rec.fail = errors.New("sns down") |
| 55 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 56 | defer cancel() |
| 57 | if err := a.Alert(ctx, hostedctl.Alert{Kind: "k"}); err == nil { |
| 58 | t.Fatal("a failed publish returned nil") |
| 59 | } |
| 60 | if d := rec.deadlines[1]; d <= 0 || d > time.Second { |
| 61 | t.Fatalf("publish context deadline in %v, want the caller's 1s", d) |
| 62 | } |
| 63 | } |
| 64 | |