1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
package main
import (
"encoding/json"
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
)
func getTestUserCredentials() (string, string) {
viper.SetConfigFile("../.env")
viper.AddConfigPath(".")
viper.AutomaticEnv()
err := viper.ReadInConfig()
if err != nil {
log.Fatalf("Error while reading config file %s", err)
}
testUser := viper.GetString("TEST_USER")
testPass := viper.GetString("TEST_PASS")
return testUser, testPass
}
func TestAuthRoute(t *testing.T) {
router := setupRouter()
username, password := getTestUserCredentials()
log.Println("username", username)
log.Println("password", password)
w := httptest.NewRecorder()
req, err := http.NewRequest("POST", "/api/v1/auth", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth(username, password)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, "response should return a 200 code")
var response map[string]interface{}
err = json.Unmarshal(w.Body.Bytes(), &response)
if err != nil {
t.Fatalf("Failed to unmarshal response: %v", err)
}
_, exists := response["token"]
assert.True(t, exists, "response should return a token")
if !exists {
t.Fatalf("response did not contain token")
}
}
func TestAuthRouteFailure(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/auth", nil)
req.SetBasicAuth("asdf", "asdf")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code, "should return a 401 code")
}
|