forked from akrennmair/activitylog
/
auth_test.go
70 lines (56 loc) · 2.14 KB
/
auth_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
package main
import (
"bytes"
"code.google.com/p/gorilla/sessions"
"encoding/json"
"fmt"
"net/http"
"testing"
)
type MockCredentialsVerifierActivityTypesGetter struct {
}
func (db *MockCredentialsVerifierActivityTypesGetter) GetActivityTypesForUser(user_id int64) []ActivityType {
return []ActivityType{
{Id: 1, Name: "Foobar"},
{Id: 2, Name: "Quux"},
}
}
func (db *MockCredentialsVerifierActivityTypesGetter) VerifyCredentials(username, password string) (user_id int64, authenticated bool) {
return 42, (username == "foo" && password == "bar")
}
func TestAuthenticateHandler(t *testing.T) {
testdata := []struct {
auth_data string
http_code int
authenticated_result bool
}{
{"username=foo&password=bar", http.StatusOK, true},
{"username=invalid&password=invalid", http.StatusOK, false},
}
for _, td := range testdata {
req, _ := http.NewRequest("POST", "http://localhost/auth", bytes.NewBufferString(td.auth_data))
req.Header["Content-Length"] = []string{fmt.Sprintf("%d", len(td.auth_data))}
req.Header["Content-Type"] = []string{"application/x-www-form-urlencoded"}
mock_db := &MockCredentialsVerifierActivityTypesGetter{}
handler := &AuthenticateHandler{Db: mock_db, Store: sessions.NewCookieStore([]byte("")) }
resp := NewMockResponseWriter()
handler.ServeHTTP(resp, req)
if resp.StatusCode != td.http_code {
t.Errorf("AuthenticateHandler responded with %d (expected: %d)", resp.StatusCode, td.http_code)
}
if len(resp.Header()["Content-Type"]) < 1 || resp.Header()["Content-Type"][0] != "application/json" {
t.Errorf("AuthenticateHandler sends wrong Content-Type (%v)", resp.Header()["Content-Type"][0])
}
data := make(map[string]interface{})
if err := json.Unmarshal(resp.Buffer.Bytes(), &data); err != nil {
t.Errorf("AuthenticateHandler returned invalid JSON: %v", err)
}
if authenticated, ok := data["authenticated"].(bool); !ok {
t.Errorf("JSON authenticated field didn't contain bool")
} else {
if authenticated != td.authenticated_result {
t.Errorf("AuthenticateHandler authenticated returns %v (expected %v)", authenticated, td.authenticated_result)
}
}
}
}