github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/znet/auth/auth_test.go (about) 1 package auth_test 2 3 import ( 4 "encoding/base64" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 9 "github.com/sohaha/zlsgo" 10 "github.com/sohaha/zlsgo/znet" 11 "github.com/sohaha/zlsgo/znet/auth" 12 "github.com/sohaha/zlsgo/zutil" 13 ) 14 15 var authHandler = auth.New(auth.Accounts{ 16 "admin": "123", 17 "admin2": "456", 18 }) 19 20 func TestNew(t *testing.T) { 21 tt := zlsgo.NewTest(t) 22 r := server().(*znet.Engine) 23 24 w1 := newRequest(r, "/auth1", nil) 25 tt.Equal(http.StatusUnauthorized, w1.Code) 26 27 w2 := newRequest(r, "/auth2", []string{"admin", "123"}) 28 tt.Equal(http.StatusOK, w2.Code) 29 tt.Equal("admin", w2.Body.String()) 30 31 w3 := newRequest(r, "/auth3", []string{"admin2", "456"}) 32 tt.Equal(http.StatusOK, w3.Code) 33 tt.Equal("admin2", w3.Body.String()) 34 35 w4 := newRequest(r, "/auth4", []string{"admin3", "456"}) 36 tt.Equal(http.StatusUnauthorized, w4.Code) 37 tt.Equal("", w4.Body.String()) 38 39 } 40 41 var server = zutil.Once(func() interface{} { 42 r := znet.New() 43 // r.SetMode(znet.DebugMode) 44 return r 45 }) 46 47 func newRequest(r *znet.Engine, path string, account []string) *httptest.ResponseRecorder { 48 r.GET(path, func(c *znet.Context) { 49 c.String(200, c.MustValue(auth.UserKey, "").(string)) 50 }, authHandler) 51 w := httptest.NewRecorder() 52 req, _ := http.NewRequest("GET", path, nil) 53 if len(account) == 2 { 54 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(account[0]+":"+account[1]))) 55 } 56 r.ServeHTTP(w, req) 57 return w 58 }