github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ginx/anyfn/middle_test.go (about) 1 package anyfn_test 2 3 import ( 4 "reflect" 5 "testing" 6 7 "github.com/bingoohuang/gg/pkg/ginx/adapt" 8 "github.com/bingoohuang/gg/pkg/ginx/anyfn" 9 "github.com/bingoohuang/gg/pkg/ginx/gintest" 10 "github.com/gin-gonic/gin" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 type AuthUser struct { 15 Name string 16 } 17 18 func TestMiddleware(t *testing.T) { 19 af := anyfn.NewAdapter() 20 r := adapt.Adapt(gin.New(), af) 21 22 r.Use(func(c *gin.Context) { 23 c.Set("AuthUser", AuthUser{Name: "TestAuthUser"}) 24 }) 25 26 doTest(t, r, af) 27 } 28 29 func TestMiddlewarePtr(t *testing.T) { 30 af := anyfn.NewAdapter() 31 r := adapt.Adapt(gin.New(), af) 32 33 r.Use(func(c *gin.Context) { 34 c.Set("AuthUser", &AuthUser{Name: "TestAuthUser"}) 35 }) 36 37 doTest(t, r, af) 38 } 39 40 func TestInSupport(t *testing.T) { 41 user := AuthUser{Name: "TestAuthUser"} 42 af := anyfn.NewAdapter() 43 af.PrependInSupport(anyfn.InSupportFn(func(argIn anyfn.ArgIn, argsIn []anyfn.ArgIn, c *gin.Context) (reflect.Value, error) { 44 if argIn.Type == reflect.TypeOf(AuthUser{}) { 45 return anyfn.ConvertPtr(argIn.Ptr, reflect.ValueOf(user)), nil 46 } 47 48 return reflect.Value{}, nil 49 })) 50 51 r := adapt.Adapt(gin.New(), af) 52 53 doTest(t, r, af) 54 } 55 56 func doTest(t *testing.T, r *adapt.Adaptee, af *anyfn.Adapter) { 57 r.GET("/GetAge1/:name", af.F(func(user AuthUser, name string) string { 58 return user.Name + "/" + name 59 })) 60 r.GET("/GetAge2/:name", af.F(func(name string, user AuthUser) string { 61 return user.Name + "/" + name 62 })) 63 r.GET("/GetAge3/:name", af.F(func(user *AuthUser, name string) string { 64 return user.Name + "/" + name 65 })) 66 r.GET("/GetAge4/:name", af.F(func(name string, user *AuthUser) string { 67 return user.Name + "/" + name 68 })) 69 70 // r.Run(":8080") 71 72 rr := gintest.Get("/GetAge1/bingoohuang", r) 73 assert.Equal(t, "TestAuthUser/bingoohuang", rr.Body()) 74 rr = gintest.Get("/GetAge2/bingoohuang", r) 75 assert.Equal(t, "TestAuthUser/bingoohuang", rr.Body()) 76 rr = gintest.Get("/GetAge3/bingoohuang", r) 77 assert.Equal(t, "TestAuthUser/bingoohuang", rr.Body()) 78 rr = gintest.Get("/GetAge4/bingoohuang", r) 79 assert.Equal(t, "TestAuthUser/bingoohuang", rr.Body()) 80 }