|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/glimesh/broadcast-box/internal/environment" |
| 11 | +) |
| 12 | + |
| 13 | +type whepWebhookPayload struct { |
| 14 | + Action string `json:"action"` |
| 15 | + BearerToken string `json:"bearerToken"` |
| 16 | + QueryParams map[string]string `json:"queryParams"` |
| 17 | +} |
| 18 | + |
| 19 | +func TestWhepHandlerCallsWebhook(t *testing.T) { |
| 20 | + payloads := make(chan whepWebhookPayload, 1) |
| 21 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 22 | + defer r.Body.Close() |
| 23 | + |
| 24 | + var payload whepWebhookPayload |
| 25 | + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { |
| 26 | + t.Fatalf("failed to decode webhook payload: %v", err) |
| 27 | + } |
| 28 | + |
| 29 | + payloads <- payload |
| 30 | + w.WriteHeader(http.StatusUnauthorized) |
| 31 | + })) |
| 32 | + defer server.Close() |
| 33 | + |
| 34 | + t.Setenv(environment.WEBHOOK_URL, server.URL) |
| 35 | + |
| 36 | + req := httptest.NewRequest(http.MethodPost, "/api/whep?viewer=1", strings.NewReader("v=0")) |
| 37 | + req.Header.Set("Authorization", "Bearer test_stream_key") |
| 38 | + req.Header.Set("User-Agent", "whep-handler-test") |
| 39 | + req.RemoteAddr = "203.0.113.10:1234" |
| 40 | + |
| 41 | + resp := httptest.NewRecorder() |
| 42 | + WhepHandler(resp, req) |
| 43 | + |
| 44 | + if resp.Code != http.StatusUnauthorized { |
| 45 | + t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, resp.Code) |
| 46 | + } |
| 47 | + |
| 48 | + select { |
| 49 | + case payload := <-payloads: |
| 50 | + if payload.Action != "whep-connect" { |
| 51 | + t.Fatalf("expected action %q, got %q", "whep-connect", payload.Action) |
| 52 | + } |
| 53 | + |
| 54 | + if payload.BearerToken != "test_stream_key" { |
| 55 | + t.Fatalf("expected bearer token %q, got %q", "test_stream_key", payload.BearerToken) |
| 56 | + } |
| 57 | + |
| 58 | + if payload.QueryParams["viewer"] != "1" { |
| 59 | + t.Fatalf("expected query param %q, got %q", "1", payload.QueryParams["viewer"]) |
| 60 | + } |
| 61 | + default: |
| 62 | + t.Fatal("expected webhook to be called") |
| 63 | + } |
| 64 | +} |
0 commit comments