forked from nautilus/gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway_test.go
617 lines (548 loc) · 14.6 KB
/
gateway_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
package gateway
import (
"context"
"errors"
"strings"
"testing"
"github.com/nautilus/graphql"
"github.com/stretchr/testify/assert"
"github.com/vektah/gqlparser/v2/ast"
)
type schemaTableRow struct {
location string
query string
}
func TestGateway(t *testing.T) {
schemas := []schemaTableRow{
{
"url1",
`
type Query {
allUsers: [User!]!
}
type User {
firstName: String!
lastName: String!
}
`,
},
{
"url2",
`
type User {
lastName: String!
}
`,
},
}
// the list of remote schemas
sources := []*graphql.RemoteSchema{}
for _, source := range schemas {
// turn the combo into a remote schema
schema, _ := graphql.LoadSchema(source.query)
// add the schema to list of sources
sources = append(sources, &graphql.RemoteSchema{Schema: schema, URL: source.location})
}
t.Run("Compute Field URLs", func(t *testing.T) {
locations := fieldURLs(sources, false)
allUsersURL, err := locations.URLFor("Query", "allUsers")
assert.Nil(t, err)
assert.Equal(t, []string{"url1"}, allUsersURL)
lastNameURL, err := locations.URLFor("User", "lastName")
assert.Nil(t, err)
assert.Equal(t, []string{"url1", "url2"}, lastNameURL)
firstNameURL, err := locations.URLFor("User", "firstName")
assert.Nil(t, err)
assert.Equal(t, []string{"url1"}, firstNameURL)
// make sure we can look up the url for internal
_, ok := locations["__Schema.types"]
if !ok {
t.Error("Could not find internal type __Schema.types")
return
}
_, ok = locations["Query.__schema"]
if !ok {
t.Error("Could not find internal field Query.__schema")
return
}
})
t.Run("Options", func(t *testing.T) {
// create a new schema with the sources and some configuration
gateway, err := New([]*graphql.RemoteSchema{sources[0]}, func(schema *Gateway) {
schema.sources = append(schema.sources, sources[1])
})
if err != nil {
t.Error(err.Error())
return
}
// make sure that the schema has both sources
assert.Len(t, gateway.sources, 2)
})
t.Run("WithPlanner", func(t *testing.T) {
// the planner we will assign
planner := &MockPlanner{}
gateway, err := New(sources, WithPlanner(planner))
if err != nil {
t.Error(err.Error())
return
}
assert.Equal(t, planner, gateway.planner)
})
t.Run("WithQueryerFactory", func(t *testing.T) {
// the planner we will assign
planner := &MinQueriesPlanner{}
factory := QueryerFactory(func(ctx *PlanningContext, url string) graphql.Queryer {
return ctx.Gateway
})
// instantiate the gateway
gateway, err := New(sources, WithPlanner(planner), WithQueryerFactory(&factory))
if err != nil {
t.Error(err.Error())
return
}
assert.Equal(t, &factory, gateway.planner.(*MinQueriesPlanner).QueryerFactory)
})
t.Run("WithLocationPriorities", func(t *testing.T) {
priorities := []string{"url1", "url2"}
gateway, err := New(sources, WithLocationPriorities(priorities))
if err != nil {
t.Error(err.Error())
return
}
assert.Equal(t, priorities, gateway.locationPriorities)
})
t.Run("fieldURLs ignore introspection", func(t *testing.T) {
locations := fieldURLs(sources, true)
for key := range locations {
if strings.HasPrefix(key, "__") {
t.Errorf("Found type starting with __: %s", key)
}
}
if _, ok := locations["Query.__schema"]; ok {
t.Error("Encountered introspection value Query.__schema")
return
}
})
t.Run("Response Middleware Error", func(t *testing.T) {
// create a new schema with the sources and some configuration
gateway, err := New(sources,
WithExecutor(ExecutorFunc(func(ctx *ExecutionContext) (map[string]interface{}, error) {
return map[string]interface{}{"goodbye": "moon"}, nil
})),
WithMiddlewares(
ResponseMiddleware(func(ctx *ExecutionContext, response map[string]interface{}) error {
return errors.New("this string")
}),
))
if err != nil {
t.Error(err.Error())
return
}
// build a query plan that the executor will follow
reqCtx := &RequestContext{
Context: context.Background(),
Query: "{ allUsers { firstName } }",
}
plans, err := gateway.GetPlans(reqCtx)
if err != nil {
t.Errorf("Encountered error building plan.")
}
_, err = gateway.Execute(reqCtx, plans)
if err == nil {
t.Errorf("Did not encounter error executing plan.")
}
})
t.Run("Response Middleware Success", func(t *testing.T) {
// create a new schema with the sources and some configuration
gateway, err := New(sources,
WithExecutor(ExecutorFunc(func(ctx *ExecutionContext) (map[string]interface{}, error) {
return map[string]interface{}{"goodbye": "moon"}, nil
})),
WithMiddlewares(
ResponseMiddleware(func(ctx *ExecutionContext, response map[string]interface{}) error {
// clear the previous value
for k := range response {
delete(response, k)
}
// set something we can test against
response["hello"] = "world"
// no errors
return nil
}),
))
if err != nil {
t.Error(err.Error())
return
}
reqCtx := &RequestContext{
Context: context.Background(),
Query: "{ allUsers { firstName } }",
}
plan, err := gateway.GetPlans(reqCtx)
if err != nil {
t.Errorf("Encountered error building plan: %s", err.Error())
return
}
// build a query plan that the executor will follow
response, err := gateway.Execute(reqCtx, plan)
if err != nil {
t.Errorf("Encountered error executing plan: %s", err.Error())
return
}
// make sure our middleware changed the response
assert.Equal(t, map[string]interface{}{"hello": "world"}, response)
})
t.Run("filter out automatically inserted ids", func(t *testing.T) {
// the query we're going to fire. Query.allUsers comes from service one. User.lastName
// from service two.
query := `
{
allUsers {
lastName
}
}
`
// create a new schema with the sources and a planner that will respond with
// values that have ids
gateway, err := New(sources, WithPlanner(&MockPlanner{
QueryPlanList{
&QueryPlan{
FieldsToScrub: map[string][][]string{
"id": {
{"allUsers"},
},
},
Operation: &ast.OperationDefinition{
Operation: ast.Query,
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "allUsers",
Definition: &ast.FieldDefinition{
Type: ast.ListType(ast.NamedType("User", &ast.Position{}), &ast.Position{}),
},
},
},
},
RootStep: &QueryPlanStep{
Then: []*QueryPlanStep{
{
// this is equivalent to
// query { allUsers }
ParentType: "Query",
InsertionPoint: []string{},
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "allUsers",
Definition: &ast.FieldDefinition{
Type: ast.ListType(ast.NamedType("User", &ast.Position{}), &ast.Position{}),
},
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "id",
Definition: &ast.FieldDefinition{
Type: ast.NamedType("ID", &ast.Position{}),
},
},
},
},
},
// return a known value we can test against
Queryer: &graphql.MockSuccessQueryer{map[string]interface{}{
"allUsers": []interface{}{
map[string]interface{}{
"id": "1",
},
},
}},
// then we have to ask for the users favorite cat photo and its url
Then: []*QueryPlanStep{
{
ParentType: "User",
InsertionPoint: []string{"allUsers"},
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "lastName",
Definition: &ast.FieldDefinition{
Type: ast.NamedType("String", &ast.Position{}),
},
},
},
Queryer: &graphql.MockSuccessQueryer{map[string]interface{}{
"node": map[string]interface{}{
"lastName": "Hello",
},
}},
},
},
},
},
},
},
},
}))
if err != nil {
t.Error(err.Error())
return
}
reqCtx := &RequestContext{
Context: context.Background(), Query: query,
}
plan, err := gateway.GetPlans(reqCtx)
if err != nil {
t.Error(err.Error())
return
}
// execute the query
res, err := gateway.Execute(reqCtx, plan)
if err != nil {
t.Error(err.Error())
return
}
// make sure we didn't get any ids
assert.Equal(t, map[string]interface{}{
"allUsers": []interface{}{
map[string]interface{}{
"lastName": "Hello",
},
},
}, res)
})
t.Run("Introspection field on services", func(t *testing.T) {
// compute the location of each field
locations := fieldURLs(sources, false)
// make sure we have entries for __typename at each service
userTypenameURLs, err := locations.URLFor("User", "__typename")
assert.Nil(t, err)
assert.Equal(t, []string{"url1", "url2"}, userTypenameURLs)
})
t.Run("Gateway fields", func(t *testing.T) {
// define a gateway field
viewerField := &QueryField{
Name: "viewer",
Type: ast.NamedType("User", &ast.Position{}),
Arguments: ast.ArgumentDefinitionList{
&ast.ArgumentDefinition{
Name: "id",
Type: ast.NamedType("ID", &ast.Position{}),
},
},
Resolver: func(ctx context.Context, args map[string]interface{}) (string, error) {
return args["id"].(string), nil
},
}
// create a gateway with the viewer field
gateway, err := New(sources, WithQueryFields(viewerField))
// execute the query
query := `
query($id: ID!){
viewer(id: $id) {
firstName
}
}
`
plans, err := gateway.planner.Plan(&PlanningContext{
Query: query,
Locations: gateway.fieldURLs,
Schema: gateway.schema,
Gateway: gateway,
})
if err != nil {
t.Error(err.Error())
return
}
if !assert.Len(t, plans[0].RootStep.Then, 1) {
return
}
// invoke the first step
res := map[string]interface{}{}
err = plans[0].RootStep.Then[0].Queryer.Query(context.Background(), &graphql.QueryInput{
Query: query,
QueryDocument: &ast.QueryDocument{
Operations: ast.OperationList{
{
Operation: "Query",
SelectionSet: ast.SelectionSet{
&ast.Field{
Alias: "viewer",
Name: "viewer",
Arguments: ast.ArgumentList{
&ast.Argument{
Name: "id",
Value: &ast.Value{
Kind: ast.Variable,
Raw: "id",
},
},
},
},
},
},
},
},
Variables: map[string]interface{}{"id": "1"},
}, &res)
if err != nil {
t.Error(err.Error())
return
}
// make sure the result of the queryer matches exepctations
assert.Equal(t, map[string]interface{}{"viewer": map[string]interface{}{"id": "1"}}, res)
})
}
func TestGatewayExecuteRespectsOperationName(t *testing.T) {
// define a schema source
schema, _ := graphql.LoadSchema(`
type Query {
foo: String!
bar: String!
}
`)
sources := []*graphql.RemoteSchema{{Schema: schema, URL: "a"}}
// the query we're going to fire should have two defined operations
query := `
query Foo {
foo
}
query Bar {
bar
}
`
// create a new schema with the sources and a planner that will respond with
// values that have ids
gateway, err := New(sources, WithPlanner(&MockPlanner{
QueryPlanList{
// the plan for the Foo operation
&QueryPlan{
FieldsToScrub: map[string][][]string{},
Operation: &ast.OperationDefinition{
Name: "Foo",
Operation: ast.Query,
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "foo",
Definition: &ast.FieldDefinition{
Type: ast.NamedType("String", &ast.Position{}),
},
},
},
},
RootStep: &QueryPlanStep{
Then: []*QueryPlanStep{
{
// this is equivalent to
// query { allUsers }
ParentType: "Query",
InsertionPoint: []string{},
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "foo",
Definition: &ast.FieldDefinition{
Type: ast.NamedType("String", &ast.Position{}),
},
},
},
// return a known value we can test against
Queryer: &graphql.MockSuccessQueryer{map[string]interface{}{
"foo": "foo",
}},
},
},
},
},
// the plan for the Bar operation
&QueryPlan{
FieldsToScrub: map[string][][]string{},
Operation: &ast.OperationDefinition{
Name: "Bar",
Operation: ast.Query,
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "bar",
Definition: &ast.FieldDefinition{
Type: ast.NamedType("String", &ast.Position{}),
},
},
},
},
RootStep: &QueryPlanStep{
Then: []*QueryPlanStep{
{
// this is equivalent to
// query { allUsers }
ParentType: "Query",
InsertionPoint: []string{},
SelectionSet: ast.SelectionSet{
&ast.Field{
Name: "bar",
Definition: &ast.FieldDefinition{
Type: ast.NamedType("String", &ast.Position{}),
},
},
},
// return a known value we can test against
Queryer: &graphql.MockSuccessQueryer{map[string]interface{}{
"bar": "bar",
}},
},
},
},
},
},
}))
if err != nil {
t.Error(err.Error())
return
}
reqCtx := &RequestContext{
Context: context.Background(), Query: query,
OperationName: "Bar",
}
plan, err := gateway.GetPlans(reqCtx)
if err != nil {
t.Error(err.Error())
return
}
// execute the query
res, err := gateway.Execute(reqCtx, plan)
if err != nil {
t.Error(err.Error())
return
}
// make sure we didn't get any ids
assert.Equal(t, map[string]interface{}{
"bar": "bar",
}, res)
}
func TestFieldURLs_concat(t *testing.T) {
// create a field url map
first := FieldURLMap{}
first.RegisterURL("Parent", "field1", "url1")
first.RegisterURL("Parent", "field2", "url1")
// create a second url map
second := FieldURLMap{}
second.RegisterURL("Parent", "field2", "url2")
second.RegisterURL("Parent", "field3", "url2")
// concatenate the 2
sum := first.Concat(second)
// make sure that that there is one entry for Parent.field1
urlLocations1, err := sum.URLFor("Parent", "field1")
if err != nil {
t.Error(err.Error())
return
}
assert.Equal(t, []string{"url1"}, urlLocations1)
// look up the locations for Parent.field2
urlLocations2, err := sum.URLFor("Parent", "field2")
if err != nil {
t.Error(err.Error())
return
}
assert.Equal(t, []string{"url1", "url2"}, urlLocations2)
// look up the locations for Parent.field3
urlLocations3, err := sum.URLFor("Parent", "field3")
if err != nil {
t.Error(err.Error())
return
}
assert.Equal(t, []string{"url2"}, urlLocations3)
}