package hub import ( "context" "encoding/json" "net/http" "net/http/httptest" "testing" "time" ) func TestNotifyPostsContractPayload(t *testing.T) { var ( gotReq NotifyRequest gotAuth string hits int ) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits++ if r.URL.Path != "/notify" { t.Errorf("path = %q, want /notify", r.URL.Path) } gotAuth = r.Header.Get("Authorization") if err := json.NewDecoder(r.Body).Decode(&gotReq); err != nil { t.Errorf("decode body: %v", err) } w.WriteHeader(http.StatusOK) })) defer srv.Close() n := NewNotifier(srv.URL, "hub-token", time.Second, nil) if err := n.NotifyImportantCount(context.Background(), 3); err != nil { t.Fatalf("NotifyImportantCount() error = %v", err) } if hits != 1 { t.Fatalf("server hits = %d, want 1", hits) } if gotAuth != "Bearer hub-token" { t.Errorf("Authorization = %q", gotAuth) } if gotReq.From != ProjectName { t.Errorf("from = %q, want %q", gotReq.From, ProjectName) } if gotReq.Level != "important" { t.Errorf("level = %q, want important", gotReq.Level) } if gotReq.Person != "sam" { t.Errorf("person = %q, want sam", gotReq.Person) } if gotReq.Message != "3 emails need a decision." { t.Errorf("message = %q", gotReq.Message) } } func TestNotifyImportantCountZeroIsNoop(t *testing.T) { hits := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits++ })) defer srv.Close() n := NewNotifier(srv.URL, "", time.Second, nil) if err := n.NotifyImportantCount(context.Background(), 0); err != nil { t.Fatalf("error = %v", err) } if hits != 0 { t.Errorf("server hits = %d, want 0", hits) } } func TestNotifyErrorStatus(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "nope", http.StatusNotFound) })) defer srv.Close() n := NewNotifier(srv.URL, "", time.Second, nil) if err := n.NotifySummaryReady(context.Background(), "x"); err == nil { t.Fatal("expected an error for a 404 reply") } } func TestNotifierNotConfigured(t *testing.T) { n := NewNotifier("", "", time.Second, nil) if n.Configured() { t.Error("empty notifier reports configured") } if err := n.NotifySummaryReady(context.Background(), "x"); err == nil { t.Fatal("expected an error when the notifier is not configured") } }