Skip to content

Commit

Permalink
simplify tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ProkopRandacek committed Apr 23, 2024
1 parent 57e2f5c commit 1f8a147
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 42 deletions.
73 changes: 32 additions & 41 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,29 +93,29 @@ func expectStringLooksLikeToken(t *testing.T, token string) {
}
}

func hit(srv http.Handler, method, target string, body io.Reader) *http.Response {
func hit(srv http.Handler, method, target, token string, body io.Reader) *http.Response {
req := httptest.NewRequest(method, target, body)
if token != "" {
req.Header.Add("Authorization", token)
}
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
return w.Result()
}

func hitPost(t *testing.T, srv http.Handler, target string, body any) *http.Response {
func hitPost(t *testing.T, srv http.Handler, target, token string, body any) *http.Response {
var buf bytes.Buffer

err := json.NewEncoder(&buf).Encode(body)
if err != nil {
t.Errorf("failed to encode post body: %v", err)
}

return hit(srv, http.MethodPost, "/api/v1/login", &buf)
return hit(srv, http.MethodPost, target, token, &buf)
}

func hitGet(srv http.Handler, target string) *http.Response {
req := httptest.NewRequest(http.MethodGet, target, strings.NewReader(""))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
return w.Result()
func hitGet(srv http.Handler, target, token string) *http.Response {
return hit(srv, http.MethodGet, target, token, strings.NewReader(""))
}

type loginRequest struct {
Expand All @@ -124,7 +124,7 @@ type loginRequest struct {
}

func loginHelper(t *testing.T, srv http.Handler, username, pwd string) string {
res := hitPost(t, srv, "/api/v1/login", loginRequest{Username: username, Password: hashPassword(pwd)})
res := hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: username, Password: hashPassword(pwd)})

type LoginResponse struct {
Ok bool `json:"ok"`
Expand All @@ -143,15 +143,15 @@ func TestWhoamiNeedsLogin(t *testing.T) {
t.Parallel()
srv := newTestServer(t)

res := hitGet(srv, "/api/v1/whoami")
res := hitGet(srv, "/api/v1/whoami", "")
expectFail(t, res, http.StatusUnauthorized, "401 unauthorized")
}

func TestRootReturnsNotFound(t *testing.T) {
t.Parallel()
srv := newTestServer(t)

res := hitGet(srv, "/")
res := hitGet(srv, "/", "")
assert.Equal(t, http.StatusNotFound, res.StatusCode)
assert.Equal(t, "404 page not found\n", getBody(t, res))
}
Expand All @@ -162,10 +162,10 @@ func TestLogin(t *testing.T) {
"prokop": hashPassword("catboy123"),
})

expectFail(t, hitPost(t, srv, "/api/v1/login", loginRequest{Username: "prokop", Password: hashPassword("eek")}), http.StatusForbidden, "wrong name or password")
expectFail(t, hitPost(t, srv, "/api/v1/login", loginRequest{Username: "prokop", Password: hashPassword("uuhk")}), http.StatusForbidden, "wrong name or password")
expectFail(t, hitPost(t, srv, "/api/v1/login", loginRequest{Username: "marek", Password: hashPassword("catboy123")}), http.StatusForbidden, "wrong name or password")
res := hitPost(t, srv, "/api/v1/login", loginRequest{Username: "prokop", Password: hashPassword("catboy123")})
expectFail(t, hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "prokop", Password: hashPassword("eek")}), http.StatusForbidden, "wrong name or password")
expectFail(t, hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "prokop", Password: hashPassword("uuhk")}), http.StatusForbidden, "wrong name or password")
expectFail(t, hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "marek", Password: hashPassword("catboy123")}), http.StatusForbidden, "wrong name or password")
res := hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "prokop", Password: hashPassword("catboy123")})
assert.Equal(t, http.StatusOK, res.StatusCode)
response := decodeResponse[struct {
Ok bool `json:"ok"`
Expand All @@ -178,18 +178,23 @@ func TestLogin(t *testing.T) {
expectStringLooksLikeToken(t, response.Data.Token)
}

func bodylessRequest(t *testing.T, srv http.Handler, method, target, token string) *http.Response {
req := httptest.NewRequest(http.MethodGet, target, strings.NewReader(""))
if token != "" {
req.Header.Add("Authorization", token)
}
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
return w.Result()
}

func TestWhoami(t *testing.T) {
t.Parallel()
srv := newTestServerWithUsers(t, map[string][64]byte{"matuush": hashPassword("kadit")})

token := loginHelper(t, srv, "matuush", "kadit")

req := httptest.NewRequest(http.MethodGet, "/api/v1/whoami", strings.NewReader(""))
req.Header.Add("Authorization", token)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
res := w.Result()

res := bodylessRequest(t, srv, http.MethodGet, "/api/v1/whoami", token)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true,\"data\":{\"name\":\"matuush\"}}\n", getBody(t, res))
}
Expand All @@ -201,36 +206,22 @@ func TestDelete(t *testing.T) {
"admin": hashPassword("heslo123")})

token := loginHelper(t, srv, "matuush", "kadit")
req := httptest.NewRequest(http.MethodGet, "/api/v1/whoami", strings.NewReader(""))
req.Header.Add("Authorization", token)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
res := w.Result()

res := hitGet(srv, "/api/v1/whoami", token)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true,\"data\":{\"name\":\"matuush\"}}\n", getBody(t, res))

adminToken := loginHelper(t, srv, "admin", "heslo123")
req = httptest.NewRequest(http.MethodGet, "/api/v1/whoami", strings.NewReader(""))
req.Header.Add("Authorization", adminToken)
w = httptest.NewRecorder()
srv.ServeHTTP(w, req)
res = w.Result()

res = hitGet(srv, "/api/v1/whoami", adminToken)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true,\"data\":{\"name\":\"admin\"}}\n", getBody(t, res))

req = httptest.NewRequest(http.MethodPost, "/api/v1/delete/matuush", strings.NewReader(""))
req.Header.Add("Authorization", token)
w = httptest.NewRecorder()
srv.ServeHTTP(w, req)
res = w.Result()
res = hitPost(t, srv, "/api/v1/delete/matuush", token, strings.NewReader(""))
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
assert.Equal(t, "{\"ok\":false,\"error\":\"401 unauthorized\"}\n", getBody(t, res))

req = httptest.NewRequest(http.MethodPost, "/api/v1/delete/matuush", strings.NewReader(""))
req.Header.Add("Authorization", adminToken)
w = httptest.NewRecorder()
srv.ServeHTTP(w, req)
res = w.Result()
res = hitPost(t, srv, "/api/v1/delete/matuush", adminToken, strings.NewReader(""))
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true}\n", getBody(t, res))
}
2 changes: 1 addition & 1 deletion routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func addRoutes(
mux.Handle("POST /api/v1/relogin", http.NotFoundHandler()) // generates a new session token given old token
mux.Handle("GET /api/v1/whoami", requireLogin(secret, log, handleWhoami(secret, log)))
mux.Handle("POST /api/v1/delete/{username}", adminOnly(secret, log, handleDeleteUser(secret, log, userStore)))
mux.Handle("POST /api/v1/create/{username}/{password}", http.NotFoundHandler())
mux.Handle("POST /api/v1/create/{username}/{password}", adminOnly(secret, log, http.NotFoundHandler()))

mux.Handle("/", http.NotFoundHandler())
}

0 comments on commit 1f8a147

Please sign in to comment.