|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "html/template" |
| 5 | + "net/http/httptest" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | +) |
| 10 | + |
| 11 | +func TestRenderHTTPResponse(t *testing.T) { |
| 12 | + type testStruct struct { |
| 13 | + Name string `json:"name"` |
| 14 | + Value int `json:"value"` |
| 15 | + } |
| 16 | + |
| 17 | + tests := []struct { |
| 18 | + name string |
| 19 | + headers map[string]string |
| 20 | + tmpl string |
| 21 | + expected string |
| 22 | + value testStruct |
| 23 | + }{ |
| 24 | + { |
| 25 | + name: "Test Renders json", |
| 26 | + headers: map[string]string{ |
| 27 | + "Accept": "application/json", |
| 28 | + }, |
| 29 | + tmpl: "<html></html>", |
| 30 | + expected: `{"name":"testName","value":42}`, |
| 31 | + value: testStruct{ |
| 32 | + Name: "testName", |
| 33 | + Value: 42, |
| 34 | + }, |
| 35 | + }, |
| 36 | + { |
| 37 | + name: "Test Renders html", |
| 38 | + headers: map[string]string{}, |
| 39 | + tmpl: "<html>{{ .Name }}</html>", |
| 40 | + expected: "<html>testName</html>", |
| 41 | + value: testStruct{ |
| 42 | + Name: "testName", |
| 43 | + Value: 42, |
| 44 | + }, |
| 45 | + }, |
| 46 | + } |
| 47 | + |
| 48 | + for _, tt := range tests { |
| 49 | + t.Run(tt.name, func(t *testing.T) { |
| 50 | + tmpl := template.Must(template.New("webpage").Parse(tt.tmpl)) |
| 51 | + writer := httptest.NewRecorder() |
| 52 | + request := httptest.NewRequest("GET", "/", nil) |
| 53 | + |
| 54 | + for k, v := range tt.headers { |
| 55 | + request.Header.Add(k, v) |
| 56 | + } |
| 57 | + |
| 58 | + RenderHTTPResponse(writer, tt.value, tmpl, request) |
| 59 | + |
| 60 | + assert.Equal(t, tt.expected, writer.Body.String()) |
| 61 | + }) |
| 62 | + } |
| 63 | +} |
0 commit comments