-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauthentication_test.go
76 lines (68 loc) · 1.63 KB
/
authentication_test.go
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
68
69
70
71
72
73
74
75
76
package lolp
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func authenticateHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err.Error())
}
l := struct {
Username string `json:"username"`
Password string `json:"password"`
}{}
if err := json.Unmarshal(body, &l); err != nil {
panic(err.Error())
}
var ctx string
if l.Username == "foo@example.com" && l.Password == "Secret#Gopher123?" {
ctx = "ok"
w.WriteHeader(http.StatusOK)
} else {
ctx = "ng"
w.WriteHeader(http.StatusUnauthorized)
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, fixture(ctx+".response", r))
}
}
func TestAuthenticate(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(authenticateHandler(t)))
defer s.Close()
c, err := NewClient(s.URL)
if err != nil {
t.Fatal(err)
}
cases := []struct {
username string
password string
expectedErr bool
}{
{"foo@example.com", "Secret#Gopher123?", false},
{"foo@example.com", "Secret#Gopher999?", true},
}
for _, cc := range cases {
token, err := c.Authenticate(cc.username, cc.password)
if cc.expectedErr {
if err == nil {
t.Errorf("expect authentication failure but succeeded")
}
if token != "" {
t.Errorf("expect token empty but it returns as (%s)", token)
}
} else {
if err != nil {
t.Errorf("expect to succeed in authentication, but failed: %s", err)
}
if token == "" {
t.Errorf("expect token but it is empty")
}
}
}
}