Skip to content

Commit d3b4a64

Browse files
committed
Test for BasicAuth.NewContext.
1 parent 6d6ca8f commit d3b4a64

File tree

1 file changed

+49
-7
lines changed

1 file changed

+49
-7
lines changed

basic_test.go

Lines changed: 49 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package auth
33
import (
44
"fmt"
55
"net/http"
6+
"net/http/httptest"
67
"testing"
78
)
89

@@ -13,6 +14,17 @@ var basicSecrets = map[string]string{
1314
"test3": "$2y$05$ih3C91zUBSTFcAh2mQnZYuob0UOZVEf16wl/ukgjDhjvj.xgM1WwS",
1415
}
1516

17+
type credentials struct {
18+
username, password string
19+
}
20+
21+
var basicCredentials = []credentials{
22+
{"test", "hello"},
23+
{"test2", "hello2"},
24+
{"test3", "hello3"},
25+
{"test16", "topsecret"},
26+
}
27+
1628
func basicProvider(user, realm string) string {
1729
return basicSecrets[user]
1830
}
@@ -41,21 +53,51 @@ func TestBasicCheckAuthFailsOnBadHeaders(t *testing.T) {
4153
func TestBasicCheckAuth(t *testing.T) {
4254
t.Parallel()
4355
a := &BasicAuth{Realm: "example.com", Secrets: basicProvider}
56+
for _, creds := range basicCredentials {
57+
r, err := http.NewRequest("GET", "http://example.com", nil)
58+
if err != nil {
59+
t.Fatal(err)
60+
}
61+
r.SetBasicAuth(creds.username, creds.password)
62+
if a.CheckAuth(r) != creds.username {
63+
t.Fatalf("CheckAuth failed for user '%s'", creds.username)
64+
}
65+
}
66+
}
67+
68+
func TestBasicAuthContext(t *testing.T) {
69+
t.Parallel()
70+
a := &BasicAuth{Realm: "example.com", Secrets: basicProvider}
71+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
72+
ctx := a.NewContext(r.Context(), r)
73+
authInfo := FromContext(ctx)
74+
authInfo.UpdateHeaders(w.Header())
75+
if authInfo == nil || !authInfo.Authenticated {
76+
http.Error(w, "error", http.StatusUnauthorized)
77+
return
78+
}
79+
fmt.Fprint(w, authInfo.Username)
80+
}))
81+
defer ts.Close()
82+
client := ts.Client()
4483
for _, tt := range []struct {
4584
username, password string
85+
want int
4686
}{
47-
{"test", "hello"},
48-
{"test2", "hello2"},
49-
{"test3", "hello3"},
50-
{"test16", "topsecret"},
87+
{"", "", http.StatusUnauthorized},
88+
{"test", "hello", http.StatusOK},
5189
} {
52-
r, err := http.NewRequest("GET", "http://example.com", nil)
90+
r, err := http.NewRequest("GET", ts.URL, nil)
5391
if err != nil {
5492
t.Fatal(err)
5593
}
5694
r.SetBasicAuth(tt.username, tt.password)
57-
if a.CheckAuth(r) != tt.username {
58-
t.Fatalf("CheckAuth failed for user '%s'", tt.username)
95+
resp, err := client.Do(r)
96+
if err != nil {
97+
t.Fatalf("HTTP request failed: %v", err)
98+
}
99+
if resp.StatusCode != tt.want {
100+
t.Errorf("user %q, password %q: got status %d, want %d", tt.username, tt.password, resp.StatusCode, tt.want)
59101
}
60102
}
61103
}

0 commit comments

Comments
 (0)