|
| 1 | +package cloudevents |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "reflect" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +func TestCloudEvent_Request(t *testing.T) { |
| 10 | + tests := []struct { |
| 11 | + name string |
| 12 | + request string |
| 13 | + headers http.Header |
| 14 | + expectedBody string |
| 15 | + expectedRuntimeContext map[string]string |
| 16 | + wantErr bool |
| 17 | + }{ |
| 18 | + { |
| 19 | + name: "Event of type application/cloudevents+json", |
| 20 | + request: `{"source":"test","data":{"foo":"bar"}}`, |
| 21 | + headers: http.Header{ |
| 22 | + "Content-Type": {"application/cloudevents+json"}, |
| 23 | + }, |
| 24 | + expectedBody: `{"foo":"bar"}`, |
| 25 | + expectedRuntimeContext: map[string]string{ |
| 26 | + CeContextKey: `{"source":"test"}`, |
| 27 | + ClientContextKey: `{"custom":{"source":"test"}}`, |
| 28 | + }, |
| 29 | + }, |
| 30 | + { |
| 31 | + name: "Event of type application/json", |
| 32 | + request: `{"foo":"bar"}`, |
| 33 | + headers: http.Header{ |
| 34 | + "Content-Type": {"application/json"}, |
| 35 | + "ce-source": {"test"}, |
| 36 | + }, |
| 37 | + expectedBody: `{"foo":"bar"}`, |
| 38 | + expectedRuntimeContext: map[string]string{ |
| 39 | + CeContextKey: `{"source":"test"}`, |
| 40 | + ClientContextKey: `{"custom":{"source":"test"}}`, |
| 41 | + }, |
| 42 | + }, |
| 43 | + { |
| 44 | + name: "Event of other type", |
| 45 | + request: `hello world`, |
| 46 | + headers: http.Header{ |
| 47 | + "Content-Type": {"text/plain"}, |
| 48 | + }, |
| 49 | + expectedBody: `hello world`, |
| 50 | + expectedRuntimeContext: nil, |
| 51 | + }, |
| 52 | + } |
| 53 | + |
| 54 | + for _, tt := range tests { |
| 55 | + t.Run(tt.name, func(t *testing.T) { |
| 56 | + ce := &CloudEvent{} |
| 57 | + body, runtimeContext, err := ce.Request([]byte(tt.request), tt.headers) |
| 58 | + |
| 59 | + if (err != nil) != tt.wantErr { |
| 60 | + t.Errorf("Request() error = %v, wantErr %v", err, tt.wantErr) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + if !reflect.DeepEqual(string(body), tt.expectedBody) { |
| 65 | + t.Errorf("Request() got = %v, want %v", string(body), tt.expectedBody) |
| 66 | + } |
| 67 | + |
| 68 | + if !reflect.DeepEqual(runtimeContext, tt.expectedRuntimeContext) { |
| 69 | + t.Errorf("Request() got1 = %v, want %v", runtimeContext, tt.expectedRuntimeContext) |
| 70 | + } |
| 71 | + }) |
| 72 | + } |
| 73 | +} |
0 commit comments