Skip to content

Commit 6d9034d

Browse files
committed
test: Add test suite for logging in
1 parent 7940272 commit 6d9034d

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

internal/application/nethttp_test.go

+67
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,70 @@ func TestDecodeJSONBody(t *testing.T) {
189189
})
190190
}
191191
}
192+
193+
func TestAuthenticationHandler(t *testing.T) {
194+
handler := Configure()
195+
ts := httptest.NewServer(handler)
196+
defer ts.Close()
197+
198+
failureTests := []struct {
199+
name string
200+
method string
201+
route string
202+
input string
203+
expectedBody *FailureResponse
204+
}{
205+
{
206+
name: "test_wrong_username_and_password",
207+
method: http.MethodPost,
208+
route: "/api/v1",
209+
input: `{"username":"kimura","password":"kaori"}`,
210+
expectedBody: NewFailureResponse(http.StatusUnauthorized, "Username or password do not match!"),
211+
},
212+
{
213+
name: "test_bad_json",
214+
method: http.MethodPost,
215+
route: "/api/v1",
216+
input: "{}{}",
217+
expectedBody: NewFailureResponse(http.StatusBadRequest, "Request body must only contain a single JSON object!"),
218+
},
219+
}
220+
221+
successTests := []struct {
222+
name string
223+
method string
224+
route string
225+
input string
226+
expectedStatus int
227+
}{
228+
{
229+
name: "test_success_login",
230+
method: http.MethodPost,
231+
route: "/api/v1",
232+
input: `{"username":"kaede","password":"kaede"}`,
233+
expectedStatus: http.StatusOK,
234+
},
235+
}
236+
237+
for _, tt := range failureTests {
238+
t.Run(tt.name, func(t *testing.T) {
239+
r := httptest.NewRequest(tt.method, tt.route, strings.NewReader(tt.input))
240+
w := httptest.NewRecorder()
241+
r.Header.Set("Content-Type", "application/json")
242+
handler.ServeHTTP(w, r)
243+
244+
assert.JSONEq(t, structToJSON(tt.expectedBody), w.Body.String())
245+
})
246+
}
247+
248+
for _, tt := range successTests {
249+
t.Run(tt.name, func(t *testing.T) {
250+
r := httptest.NewRequest(tt.method, tt.route, strings.NewReader(tt.input))
251+
w := httptest.NewRecorder()
252+
r.Header.Set("Content-Type", "application/json")
253+
handler.ServeHTTP(w, r)
254+
255+
assert.Equal(t, tt.expectedStatus, w.Code)
256+
})
257+
}
258+
}

0 commit comments

Comments
 (0)