diff options
author | Julien Dessaux | 2021-04-21 17:23:07 +0200 |
---|---|---|
committer | Julien Dessaux | 2021-04-21 17:23:07 +0200 |
commit | 4a2fb7e82d5d617298cb28b66485fc6f30c55781 (patch) | |
tree | 4ae55d8208e3ebf603f3a17ac56f6efd0e011efc /internal/webui/utils_test.go | |
parent | Implemented the ResumeSession function (diff) | |
download | trains-4a2fb7e82d5d617298cb28b66485fc6f30c55781.tar.gz trains-4a2fb7e82d5d617298cb28b66485fc6f30c55781.tar.bz2 trains-4a2fb7e82d5d617298cb28b66485fc6f30c55781.zip |
Reworked the webui package, added authentication feature and tests
Diffstat (limited to '')
-rw-r--r-- | internal/webui/utils_test.go | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/internal/webui/utils_test.go b/internal/webui/utils_test.go new file mode 100644 index 0000000..1e07aa2 --- /dev/null +++ b/internal/webui/utils_test.go @@ -0,0 +1,71 @@ +package webui + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var simpleErrorMessage = fmt.Errorf("") + +type httpTestCase struct { + name string + input httpTestInput + expect httpTestExpect +} +type httpTestInput struct { + method string + path string + cookie *http.Cookie + data url.Values +} +type httpTestExpect struct { + code int + bodyString string + location string + setsCookie bool + err interface{} +} + +func runHttpTest(t *testing.T, e *env, h func(e *env, w http.ResponseWriter, r *http.Request) error, tc *httpTestCase) { + req, err := http.NewRequest(tc.input.method, tc.input.path, nil) + require.Nil(t, err) + if tc.input.data != nil { + req, err = http.NewRequest(tc.input.method, tc.input.path, strings.NewReader(tc.input.data.Encode())) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + } + if tc.input.cookie != nil { + req.AddCookie(tc.input.cookie) + } + t.Run(tc.name, func(t *testing.T) { + rr := httptest.NewRecorder() + err := h(e, rr, req) + if tc.expect.err != nil { + require.Error(t, err) + assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expect.err), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expect.err)) + } else { + require.NoError(t, err) + assert.Equal(t, tc.expect.code, rr.Code) + if tc.expect.bodyString != "" { + assert.Contains(t, rr.Body.String(), tc.expect.bodyString) + } + if tc.expect.location != "" { + assert.Contains(t, rr.HeaderMap, "Location") + assert.Len(t, rr.HeaderMap["Location"], 1) + assert.Equal(t, rr.HeaderMap["Location"][0], tc.expect.location) + } + if tc.expect.setsCookie { + assert.Contains(t, rr.HeaderMap, "Set-Cookie") + } else { + assert.NotContains(t, rr.HeaderMap, "Set-Cookie") + } + } + }) +} |