MCPcopy Create free account
hub / github.com/TheThingsNetwork/lorawan-stack / TestBasicAuth

Function TestBasicAuth

pkg/webmiddleware/basic_auth_test.go:28–108  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

26)
27
28func TestBasicAuth(t *testing.T) {
29 m := BasicAuth("Password Protected", AuthUser("username", "password"))
30
31 t.Run("No Auth", func(t *testing.T) {
32 a := assertions.New(t)
33 r := httptest.NewRequest(http.MethodGet, "/", nil)
34 rec := httptest.NewRecorder()
35 m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
36 t.Error("Handler was called when it shouldn't have")
37 })).ServeHTTP(rec, r)
38 res := rec.Result()
39 a.So(res.StatusCode, should.Equal, http.StatusUnauthorized)
40 a.So(res.Header.Get("WWW-Authenticate"), should.ContainSubstring, "Password Protected")
41 })
42
43 t.Run("No Username or Password", func(t *testing.T) {
44 a := assertions.New(t)
45 r := httptest.NewRequest(http.MethodGet, "/", nil)
46 r.SetBasicAuth("", "")
47 rec := httptest.NewRecorder()
48 m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
49 t.Error("Handler was called when it shouldn't have")
50 })).ServeHTTP(rec, r)
51 res := rec.Result()
52 a.So(res.StatusCode, should.Equal, http.StatusUnauthorized)
53 a.So(res.Header.Get("WWW-Authenticate"), should.ContainSubstring, "Password Protected")
54 })
55
56 t.Run("No Username", func(t *testing.T) {
57 a := assertions.New(t)
58 r := httptest.NewRequest(http.MethodGet, "/", nil)
59 r.SetBasicAuth("", "password")
60 rec := httptest.NewRecorder()
61 m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
62 t.Error("Handler was called when it shouldn't have")
63 })).ServeHTTP(rec, r)
64 res := rec.Result()
65 a.So(res.StatusCode, should.Equal, http.StatusUnauthorized)
66 a.So(res.Header.Get("WWW-Authenticate"), should.ContainSubstring, "Password Protected")
67 })
68
69 t.Run("No Password", func(t *testing.T) {
70 a := assertions.New(t)
71 r := httptest.NewRequest(http.MethodGet, "/", nil)
72 r.SetBasicAuth("username", "")
73 rec := httptest.NewRecorder()
74 m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
75 t.Error("Handler was called when it shouldn't have")
76 })).ServeHTTP(rec, r)
77 res := rec.Result()
78 a.So(res.StatusCode, should.Equal, http.StatusUnauthorized)
79 a.So(res.Header.Get("WWW-Authenticate"), should.ContainSubstring, "Password Protected")
80 })
81
82 t.Run("Wrong Auth", func(t *testing.T) {
83 a := assertions.New(t)
84 r := httptest.NewRequest(http.MethodGet, "/", nil)
85 r.SetBasicAuth("username", "wrong-password")

Callers

nothing calls this directly

Calls 9

BasicAuthFunction · 0.85
AuthUserFunction · 0.85
RunMethod · 0.65
NewMethod · 0.65
ErrorMethod · 0.65
ResultMethod · 0.65
GetMethod · 0.65
ServeHTTPMethod · 0.45
WriteMethod · 0.45

Tested by

no test coverage detected