master
1package proxyauth
2
3import (
4 "bytes"
5 "log"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "testing"
10
11 "github.com/gorilla/mux"
12)
13
14// We need access to the top level gorilla/mux router which, being a mux, also
15// implements the ServeHTTP(w,r) interface which we will call in the tests
16func routerInit() *mux.Router {
17 p, err := NewProxy("../users.json")
18 if err != nil {
19 log.Fatalf("Proxy init failed: %s", err)
20 }
21
22 r := mux.NewRouter()
23 // define the api method expectations, useful for future api handles
24 api := r.
25 Methods("POST").
26 Headers("Content-Type", "application/x-www-form-urlencoded").
27 Subrouter()
28
29 api.Handle("/api/2/domains/{domain}/proxyauth", p.Authenticate())
30 return r
31}
32
33func TestAuthenticate(t *testing.T) {
34
35 var tests = []struct {
36 domain string
37 username string
38 password string
39 code int
40 success bool
41 }{
42 // Case1 Success, topcoder.com domain, StatusCode 200
43 {"topcoder.com", "takumi", "{SHA256}2QJwb00iyNaZbsEbjYHUTTLyvRwkJZTt8yrj4qHWBTU=", 200, true},
44
45 // Case2 Success, appirio.com domain, StatusCode 200
46 {"appirio.com", "jun", "{SHA256}/Hnfw7FSM40NiUQ8cY2OFKV8ZnXWAvF3U7/lMKDwmso=", 200, true},
47
48 // Case3 Failure, password unmatch, StatusCode 200
49 {"topcoder.com", "takumi", "{SHA256}/Hnfw7FSM40NiUQ8cY2OFKV8ZnXWAvF3U7/lMKDwmso=", 200, false},
50
51 // Case4 Failure, username not found, StatusCode 200
52 {"topcoder.com", "bryfry", "{SHA256}2QJwb00iyNaZbsEbjYHUTTLyvRwkJZTt8yrj4qHWBTU=", 200, false},
53
54 // Case5 Failure, domain not found, StatusCode 404
55 {"bryfry.com", "takumi", "{SHA256}2QJwb00iyNaZbsEbjYHUTTLyvRwkJZTt8yrj4qHWBTU=", 404, false},
56 }
57
58 r := routerInit()
59
60 for _, test := range tests {
61
62 // setup request and parameters
63 data := url.Values{}
64 if test.username != "" {
65 data.Set("username", test.username)
66 }
67 if test.password != "" {
68 data.Set("password", test.password)
69 }
70 url := "/api/2/domains/" + test.domain + "/proxyauth"
71 req, _ := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))
72 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
73
74 // record request response
75 rw := httptest.NewRecorder()
76 rw.Body = new(bytes.Buffer)
77
78 // make request
79 r.ServeHTTP(rw, req)
80
81 // ensure got (g) equals want (w)
82 if g, w := rw.Code, test.code; g != w {
83 t.Errorf("%s: code = %d, want %d", url, g, w)
84 }
85 if rw.Code == 200 {
86 if g, w := rw.Body.String(), successBody(test.success); g != w {
87 t.Errorf("%s: body = %q, want %q", url, g, w)
88 }
89 }
90 }
91
92}