-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathauth_test.go
71 lines (63 loc) · 1.47 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
71
package auth
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/goburrow/melon/server/router"
)
type stubAuthenticator struct {
name string
}
func (s *stubAuthenticator) Authenticate(r *http.Request) (Principal, error) {
if s.name == "" {
return nil, nil
}
return NewPrincipal(s.name), nil
}
func TestFilter(t *testing.T) {
auth := &stubAuthenticator{}
f := NewFilter(auth)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, Must(r).Name())
})
rt := router.New()
rt.AddFilter(f)
rt.Handle("GET", "/echo", handler)
srv := httptest.NewServer(rt)
defer srv.Close()
rsp, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
if http.StatusUnauthorized != rsp.StatusCode {
t.Fatalf("unexpected status code: %v", rsp.StatusCode)
}
header := rsp.Header.Get("WWW-Authenticate")
if "Basic realm=\"Server\"" != header {
t.Fatalf("unexpected header: %v", header)
}
body, err := ioutil.ReadAll(rsp.Body)
if err != nil {
t.Fatal(err)
}
if "Credentials are required to access this resource.\n" != string(body) {
t.Fatalf("unexpected body: %s", body)
}
auth.name = "user"
rsp, err = http.Get(srv.URL + "/echo")
if err != nil {
t.Fatal(err)
}
if http.StatusOK != rsp.StatusCode {
t.Fatalf("unexpected status code: %v", rsp.StatusCode)
}
body, err = ioutil.ReadAll(rsp.Body)
if err != nil {
t.Fatal(err)
}
if "user" != string(body) {
t.Fatalf("unexpected body: %s", body)
}
}