github.com/99designs/gqlgen@v0.17.45/graphql/context_response_test.go (about) 1 package graphql 2 3 import ( 4 "context" 5 "errors" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 "github.com/stretchr/testify/require" 10 "github.com/vektah/gqlparser/v2/ast" 11 "github.com/vektah/gqlparser/v2/gqlerror" 12 ) 13 14 func TestAddError(t *testing.T) { 15 ctx := WithResponseContext(context.Background(), DefaultErrorPresenter, nil) 16 17 root := &FieldContext{ 18 Field: CollectedField{ 19 Field: &ast.Field{ 20 Alias: "foo", 21 }, 22 }, 23 } 24 ctx = WithFieldContext(ctx, root) 25 AddError(ctx, errors.New("foo1")) 26 AddError(ctx, errors.New("foo2")) 27 28 index := 1 29 child := &FieldContext{ 30 Parent: root, 31 Index: &index, 32 } 33 userProvidedPath := &FieldContext{ 34 Parent: child, 35 Field: CollectedField{ 36 Field: &ast.Field{ 37 Alias: "works", 38 }, 39 }, 40 } 41 42 ctx = WithFieldContext(ctx, child) 43 AddError(ctx, errors.New("bar")) 44 AddError(ctx, &gqlerror.Error{ 45 Message: "foo3", 46 Path: append(child.Path(), ast.PathName("works")), 47 }) 48 49 specs := []struct { 50 Name string 51 RCtx *FieldContext 52 Messages []string 53 }{ 54 { 55 Name: "with root FieldContext", 56 RCtx: root, 57 Messages: []string{"foo1", "foo2"}, 58 }, 59 { 60 Name: "with child FieldContext", 61 RCtx: child, 62 Messages: []string{"bar"}, 63 }, 64 { 65 Name: "with user provided path", 66 RCtx: userProvidedPath, 67 Messages: []string{"foo3"}, 68 }, 69 } 70 71 for _, spec := range specs { 72 t.Run(spec.Name, func(t *testing.T) { 73 errList := GetFieldErrors(ctx, spec.RCtx) 74 require.Len(t, errList, len(spec.Messages)) 75 76 for idx, err := range errList { 77 assert.Equal(t, spec.Messages[idx], err.Message) 78 } 79 }) 80 } 81 } 82 83 func TestGetErrorFromPresenter(t *testing.T) { 84 ctx := WithResponseContext(context.Background(), func(ctx context.Context, err error) *gqlerror.Error { 85 errs := GetErrors(ctx) 86 87 // because we are still presenting the error it is not expected to be returned, but this should not deadlock. 88 require.Len(t, errs, 0) 89 return DefaultErrorPresenter(ctx, err) 90 }, nil) 91 92 ctx = WithFieldContext(ctx, &FieldContext{}) 93 AddError(ctx, errors.New("foo1")) 94 }