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
|
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.SetConfigName(".env")
viper.AddConfigPath(".")
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()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/auth", nil)
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{}
_ = json.Unmarshal(w.Body.Bytes(), &response)
_, exists := response["token"]
assert.True(t, exists, "response should return a 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")
}
func Test
|