Skip to content

Commit dddf19a

Browse files
committed
add ut cases for package ghttp_request
1 parent a810f00 commit dddf19a

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

net/ghttp/ghttp_z_unit_feature_request_ctx_test.go

+64
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ package ghttp_test
99
import (
1010
"context"
1111
"fmt"
12+
"github.com/gogf/gf/v2/encoding/gbase64"
13+
"net/http"
1214
"testing"
1315
"time"
1416

@@ -148,6 +150,68 @@ func Test_Request_GetServeHandler(t *testing.T) {
148150
})
149151
}
150152

153+
func Test_Request_BasicAuth(t *testing.T) {
154+
const (
155+
user = "root"
156+
pass = "123456"
157+
wrongPass = "12345"
158+
)
159+
160+
s := g.Server(guid.S())
161+
s.Group("/", func(group *ghttp.RouterGroup) {
162+
group.ALL("/auth1", func(r *ghttp.Request) {
163+
r.BasicAuth(user, pass, "tips")
164+
})
165+
group.ALL("/auth2", func(r *ghttp.Request) {
166+
r.BasicAuth(user, pass)
167+
})
168+
})
169+
s.SetDumpRouterMap(false)
170+
s.Start()
171+
defer s.Shutdown()
172+
173+
time.Sleep(100 * time.Millisecond)
174+
175+
gtest.C(t, func(t *gtest.T) {
176+
c := g.Client()
177+
c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort()))
178+
179+
rsp, err := c.Get(ctx, "/auth1")
180+
t.AssertNil(err)
181+
t.Assert(rsp.Header.Get("WWW-Authenticate"), "Basic realm=\"tips\"")
182+
t.Assert(rsp.StatusCode, http.StatusUnauthorized)
183+
184+
rsp, err = c.SetHeader("Authorization", user+pass).Get(ctx, "/auth1")
185+
t.AssertNil(err)
186+
t.Assert(rsp.StatusCode, http.StatusForbidden)
187+
188+
rsp, err = c.SetHeader("Authorization", "Test "+user+pass).Get(ctx, "/auth1")
189+
t.AssertNil(err)
190+
t.Assert(rsp.StatusCode, http.StatusForbidden)
191+
192+
rsp, err = c.SetHeader("Authorization", "Basic "+user+pass).Get(ctx, "/auth1")
193+
t.AssertNil(err)
194+
t.Assert(rsp.StatusCode, http.StatusForbidden)
195+
196+
rsp, err = c.SetHeader("Authorization", "Basic "+gbase64.EncodeString(user+pass)).Get(ctx, "/auth1")
197+
t.AssertNil(err)
198+
t.Assert(rsp.StatusCode, http.StatusForbidden)
199+
200+
rsp, err = c.SetHeader("Authorization", "Basic "+gbase64.EncodeString(user+":"+wrongPass)).Get(ctx, "/auth1")
201+
t.AssertNil(err)
202+
t.Assert(rsp.StatusCode, http.StatusUnauthorized)
203+
204+
rsp, err = c.BasicAuth(user, pass).Get(ctx, "/auth1")
205+
t.AssertNil(err)
206+
t.Assert(rsp.StatusCode, http.StatusOK)
207+
208+
rsp, err = c.Get(ctx, "/auth2")
209+
t.AssertNil(err)
210+
t.Assert(rsp.Header.Get("WWW-Authenticate"), "Basic realm=\"Need Login\"")
211+
t.Assert(rsp.StatusCode, http.StatusUnauthorized)
212+
})
213+
}
214+
151215
func Test_Request_SetCtx(t *testing.T) {
152216
s := g.Server(guid.S())
153217
s.Group("/", func(group *ghttp.RouterGroup) {

0 commit comments

Comments
 (0)