github.com/maeglindeveloper/gqlgen@v0.13.1-0.20210413081235-57808b12a0a0/example/scalars/scalar_test.go (about) 1 package scalars 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/99designs/gqlgen/client" 8 "github.com/99designs/gqlgen/graphql/handler" 9 "github.com/99designs/gqlgen/graphql/introspection" 10 "github.com/stretchr/testify/require" 11 ) 12 13 type RawUser struct { 14 ID string 15 Name string 16 Created int64 17 Address struct{ Location string } 18 PrimitiveResolver string 19 CustomResolver string 20 Tier string 21 } 22 23 func TestScalars(t *testing.T) { 24 c := client.New(handler.NewDefaultServer(NewExecutableSchema(Config{Resolvers: &Resolver{}}))) 25 26 t.Run("marshaling", func(t *testing.T) { 27 var resp struct { 28 User RawUser 29 Search []RawUser 30 } 31 c.MustPost(`{ 32 user(id:"=1=") { 33 ...UserData 34 } 35 search(input:{location:"6,66", createdAfter:666}) { 36 ...UserData 37 } 38 } 39 fragment UserData on User { id name created tier address { location } }`, &resp) 40 41 require.Equal(t, "1,2", resp.User.Address.Location) 42 // There can be a delay between creation and test assertion, so we 43 // give some leeway to eliminate false positives. 44 require.WithinDuration(t, time.Now(), time.Unix(resp.User.Created, 0), 5*time.Second) 45 require.Equal(t, "6,66", resp.Search[0].Address.Location) 46 require.Equal(t, int64(666), resp.Search[0].Created) 47 require.Equal(t, "A", resp.Search[0].Tier) 48 }) 49 50 t.Run("default search location", func(t *testing.T) { 51 var resp struct{ Search []RawUser } 52 53 err := c.Post(`{ search { address { location } } }`, &resp) 54 require.NoError(t, err) 55 require.Equal(t, "37,144", resp.Search[0].Address.Location) 56 }) 57 58 t.Run("custom error messages", func(t *testing.T) { 59 var resp struct{ Search []RawUser } 60 61 err := c.Post(`{ search(input:{createdAfter:"2014"}) { id } }`, &resp) 62 require.EqualError(t, err, `[{"message":"time should be a unix timestamp","path":["search","input","createdAfter"]}]`) 63 }) 64 65 t.Run("scalar resolver methods", func(t *testing.T) { 66 var resp struct{ User RawUser } 67 c.MustPost(`{ user(id: "=1=") { primitiveResolver, customResolver } }`, &resp) 68 69 require.Equal(t, "test", resp.User.PrimitiveResolver) 70 require.Equal(t, "5,1", resp.User.CustomResolver) 71 }) 72 73 t.Run("introspection", func(t *testing.T) { 74 // Make sure we can run the graphiql introspection query without errors 75 var resp interface{} 76 c.MustPost(introspection.Query, &resp) 77 }) 78 }