-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth_test.go
67 lines (59 loc) · 1.81 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
// Copyright 2020 CleverGo. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
var testValidate = func(username, password string) bool {
return username == "foo" && password == "bar"
}
func TestBasicAuth(t *testing.T) {
handled := false
username := ""
var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handled = true
username = GetBasicAuthUser(r)
})
h = BasicAuth(testValidate)(h)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/", nil)
h.ServeHTTP(w, r)
if handled {
t.Error("basic auth failed")
}
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/", nil)
r.SetBasicAuth("foo", "bar")
h.ServeHTTP(w, r)
if !handled {
t.Error("basic auth failed")
}
if username != "foo" {
t.Errorf("expected username %q, got %q", "foo", username)
}
}
func TestBasicAuthRealm(t *testing.T) {
tests := []string{"foo", "bar"}
var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
for _, realm := range tests {
m := BasicAuthHandler(h, testValidate, BasicAuthRealm(realm))
if ba, _ := m.(*basicAuth); realm != ba.realm {
t.Errorf("expected realm %q, got %q", realm, ba.realm)
}
}
}
func TestBasicAuthErrorHandler(t *testing.T) {
handled := false
errorHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handled = true
})
var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
h = BasicAuthHandler(h, testValidate, BasicAuthErrorHandler(errorHandler))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
if !handled {
t.Error("failed to set up error handler")
}
}