git.sr.ht/~sircmpwn/gqlgen@v0.0.0-20200522192042-c84d29a1c940/codegen/testserver/middleware_test.go (about) 1 package testserver 2 3 import ( 4 "context" 5 "testing" 6 7 "git.sr.ht/~sircmpwn/gqlgen/client" 8 "git.sr.ht/~sircmpwn/gqlgen/graphql" 9 "git.sr.ht/~sircmpwn/gqlgen/graphql/handler" 10 11 "github.com/stretchr/testify/assert" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestMiddleware(t *testing.T) { 16 resolvers := &Stub{} 17 resolvers.QueryResolver.ErrorBubble = func(ctx context.Context) (i *Error, e error) { 18 return &Error{ID: "E1234"}, nil 19 } 20 21 resolvers.QueryResolver.User = func(ctx context.Context, id int) (user *User, e error) { 22 return &User{ID: 1}, nil 23 } 24 25 resolvers.UserResolver.Friends = func(ctx context.Context, obj *User) (users []*User, e error) { 26 return []*User{{ID: 1}}, nil 27 } 28 29 areMethods := []bool{} 30 srv := handler.NewDefaultServer( 31 NewExecutableSchema(Config{Resolvers: resolvers}), 32 ) 33 srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { 34 path, _ := ctx.Value("path").([]int) 35 return next(context.WithValue(ctx, "path", append(path, 1))) 36 }) 37 38 srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { 39 path, _ := ctx.Value("path").([]int) 40 return next(context.WithValue(ctx, "path", append(path, 2))) 41 }) 42 43 srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { 44 areMethods = append(areMethods, graphql.GetFieldContext(ctx).IsMethod) 45 return next(ctx) 46 }) 47 48 c := client.New(srv) 49 50 var resp struct { 51 User struct { 52 ID int 53 Friends []struct { 54 ID int 55 } 56 } 57 } 58 59 called := false 60 resolvers.UserResolver.Friends = func(ctx context.Context, obj *User) ([]*User, error) { 61 assert.Equal(t, []int{1, 2, 1, 2}, ctx.Value("path")) 62 called = true 63 return []*User{}, nil 64 } 65 66 err := c.Post(`query { user(id: 1) { id, friends { id } } }`, &resp) 67 68 // First resolves user which is a method 69 // Next resolves id which is not a method 70 // Finally resolves friends which is a method 71 assert.Equal(t, []bool{true, false, true}, areMethods) 72 73 require.NoError(t, err) 74 require.True(t, called) 75 76 }