| 22 | ) |
| 23 | |
| 24 | func TestRenderHTTPResponse(t *testing.T) { |
| 25 | type testStruct struct { |
| 26 | Name string `json:"name"` |
| 27 | Value int `json:"value"` |
| 28 | } |
| 29 | |
| 30 | tests := []struct { |
| 31 | name string |
| 32 | headers map[string]string |
| 33 | tmpl string |
| 34 | expectedOutput string |
| 35 | expectedContentType string |
| 36 | value testStruct |
| 37 | }{ |
| 38 | { |
| 39 | name: "Test Renders json", |
| 40 | headers: map[string]string{ |
| 41 | "Accept": "application/json", |
| 42 | }, |
| 43 | tmpl: "<html></html>", |
| 44 | expectedOutput: `{"name":"testName","value":42}`, |
| 45 | expectedContentType: "application/json", |
| 46 | value: testStruct{ |
| 47 | Name: "testName", |
| 48 | Value: 42, |
| 49 | }, |
| 50 | }, |
| 51 | { |
| 52 | name: "Test Renders html", |
| 53 | headers: map[string]string{}, |
| 54 | tmpl: "<html>{{ .Name }}</html>", |
| 55 | expectedOutput: "<html>testName</html>", |
| 56 | expectedContentType: "text/html; charset=utf-8", |
| 57 | value: testStruct{ |
| 58 | Name: "testName", |
| 59 | Value: 42, |
| 60 | }, |
| 61 | }, |
| 62 | } |
| 63 | |
| 64 | for _, tt := range tests { |
| 65 | t.Run(tt.name, func(t *testing.T) { |
| 66 | tmpl := template.Must(template.New("webpage").Parse(tt.tmpl)) |
| 67 | writer := httptest.NewRecorder() |
| 68 | request := httptest.NewRequest("GET", "/", nil) |
| 69 | |
| 70 | for k, v := range tt.headers { |
| 71 | request.Header.Add(k, v) |
| 72 | } |
| 73 | |
| 74 | util.RenderHTTPResponse(writer, tt.value, tmpl, request) |
| 75 | |
| 76 | assert.Equal(t, tt.expectedContentType, writer.Header().Get("Content-Type")) |
| 77 | assert.Equal(t, 200, writer.Code) |
| 78 | assert.Equal(t, tt.expectedOutput, writer.Body.String()) |
| 79 | }) |
| 80 | } |
| 81 | } |