diff options
Diffstat (limited to 'api/cmd/main_test.go')
-rw-r--r-- | api/cmd/main_test.go | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/api/cmd/main_test.go b/api/cmd/main_test.go new file mode 100644 index 0000000..a4db57a --- /dev/null +++ b/api/cmd/main_test.go | |||
@@ -0,0 +1,62 @@ | |||
1 | package main | ||
2 | |||
3 | import ( | ||
4 | "encoding/json" | ||
5 | "log" | ||
6 | "net/http" | ||
7 | "net/http/httptest" | ||
8 | "testing" | ||
9 | "water/api/internal/router" | ||
10 | |||
11 | "github.com/stretchr/testify/assert" | ||
12 | "water/api/internal/config" | ||
13 | ) | ||
14 | |||
15 | func getTestUserCredentials() (string, string) { | ||
16 | viper, err := config.Load() | ||
17 | if err != nil { | ||
18 | log.Fatalf("Error while reading config file %s", err) | ||
19 | } | ||
20 | |||
21 | testUser := viper.GetString("TEST_USER") | ||
22 | testPass := viper.GetString("TEST_PASS") | ||
23 | return testUser, testPass | ||
24 | } | ||
25 | |||
26 | func TestAuthRoute(t *testing.T) { | ||
27 | r := router.SetupRouter() | ||
28 | |||
29 | username, password := getTestUserCredentials() | ||
30 | |||
31 | w := httptest.NewRecorder() | ||
32 | req, err := http.NewRequest("POST", "/api/v1/auth", nil) | ||
33 | if err != nil { | ||
34 | t.Fatalf("Failed to create request: %v", err) | ||
35 | } | ||
36 | req.SetBasicAuth(username, password) | ||
37 | r.ServeHTTP(w, req) | ||
38 | |||
39 | assert.Equal(t, http.StatusOK, w.Code, "response should return a 200 code") | ||
40 | |||
41 | var response map[string]interface{} | ||
42 | err = json.Unmarshal(w.Body.Bytes(), &response) | ||
43 | if err != nil { | ||
44 | t.Fatalf("Failed to unmarshal response: %v", err) | ||
45 | } | ||
46 | _, exists := response["token"] | ||
47 | assert.True(t, exists, "response should return a token") | ||
48 | if !exists { | ||
49 | t.Fatalf("response did not contain token") | ||
50 | } | ||
51 | } | ||
52 | |||
53 | func TestAuthRouteFailure(t *testing.T) { | ||
54 | r := router.SetupRouter() | ||
55 | |||
56 | w := httptest.NewRecorder() | ||
57 | req, _ := http.NewRequest("POST", "/api/v1/auth", nil) | ||
58 | req.SetBasicAuth("asdf", "asdf") | ||
59 | r.ServeHTTP(w, req) | ||
60 | |||
61 | assert.Equal(t, http.StatusUnauthorized, w.Code, "should return a 401 code") | ||
62 | } | ||