package captureintake import ( "context" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "github.com/samcharles93/archie-core/internal/domain/source" "github.com/samcharles93/archie-core/internal/domain/storecontract" ) func TestFormPayload(t *testing.T) { object := `{"ref":"refs/heads/main"}` tests := []struct { name, contentType, body, want string ok bool }{ {"json field nests", "application/x-www-form-urlencoded", "payload=" + url.QueryEscape(object), `{"payload":{"ref":"refs/heads/main"}}`, true}, {"charset parameter", "application/x-www-form-urlencoded; charset=utf-8", "a=b", `{"a":"b"}`, true}, {"first value per name", "application/x-www-form-urlencoded", "a=b&a=c&n=1", `{"a":"b","n":"1"}`, true}, {"invalid json stays text", "application/x-www-form-urlencoded", "a=%7Bnope", `{"a":"{nope"}`, true}, {"json passes through", "application/json", object, "", false}, {"malformed form", "application/x-www-form-urlencoded", "a=%zz", "", false}, } for _, tt := range tests { got, ok := formPayload(tt.contentType, []byte(tt.body)) if ok != tt.ok || string(got) != tt.want { t.Errorf("%s: got %q %v, want %q %v", tt.name, got, ok, tt.want, tt.ok) } } } type recordingCaptures struct{ sources []string } func (c *recordingCaptures) InsertCapture(_ context.Context, e storecontract.CapturedEvent, _ time.Duration, _ int) (string, error) { c.sources = append(c.sources, e.Source) return "id", nil } func (c *recordingCaptures) ListCaptures(context.Context, int) ([]storecontract.CapturedEvent, error) { return nil, nil } // An outside post must never land on the schedule source, where it would // pose as a schedule firing. func TestReceiverReservesScheduleSource(t *testing.T) { tests := []struct { path string status int stored bool }{ {source.SchedulePath, http.StatusNotFound, false}, {"hooks", http.StatusAccepted, true}, } for _, tt := range tests { captures := &recordingCaptures{} mux := http.NewServeMux() (&Receiver{Captures: captures}).Register(mux) rec := httptest.NewRecorder() mux.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/"+tt.path, strings.NewReader(`{"schedule_id":"x"}`))) if rec.Code != tt.status || (len(captures.sources) == 1) != tt.stored { t.Errorf("%s: status %d stored %v, want %d %v", tt.path, rec.Code, captures.sources, tt.status, tt.stored) } } }