Module: GraphQL::Compatibility::ExecutionSpecification

Defined in:
lib/graphql/compatibility/execution_specification.rb

Overview

Test an execution strategy. This spec is not meant as a development aid. Rather, when the strategy works, run it here to see if it has any differences from the built-in strategy.

  • Custom scalar input / output
  • Null propagation
  • Query-level masking
  • Directive support
  • Typecasting
  • Error handling (raise / return GraphQL::ExecutionError)
  • Provides Irep & AST node to resolve fn

Some things are explicitly not tested here, because they're handled by other parts of the system:

  • Schema definition (including types and fields)
  • Parsing & parse errors
  • AST -> IRep transformation (eg, fragment merging)
  • Query validation and analysis
  • Relay features

Constant Summary collapse

DATA =
{
  "1001" => OpenStruct.new({
    name: "Fannie Lou Hamer",
    birthdate: Time.new(1917, 10, 6),
    organization_ids: [],
  }),
  "1002" => OpenStruct.new({
    name: "John Lewis",
    birthdate: Time.new(1940, 2, 21),
    organization_ids: ["2001"],
  }),
  "1003" => OpenStruct.new({
    name: "Diane Nash",
    birthdate: Time.new(1938, 5, 15),
    organization_ids: ["2001", "2002"],
  }),
  "1004" => OpenStruct.new({
    name: "Ralph Abernathy",
    birthdate: Time.new(1926, 3, 11),
    organization_ids: ["2002"],
  }),
  "2001" => OpenStruct.new({
    name: "SNCC",
    leader_id: nil, # fail on purpose
  }),
  "2002" => OpenStruct.new({
    name: "SCLC",
    leader_id: "1004",
  }),
}

Class Method Summary collapse

Class Method Details

.build_suite(execution_strategy) ⇒ Class<Minitest::Test>

Make a minitest suite for this execution strategy, making sure it fulfills all the requirements of this library.

Parameters:

  • execution_strategy (<#new, #execute>)

    An execution strategy class

Returns:

  • (Class<Minitest::Test>)

    A test suite for this execution strategy


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
# File 'lib/graphql/compatibility/execution_specification.rb', line 60

def self.build_suite(execution_strategy)
  Class.new(Minitest::Test) do
    def self.build_schema(execution_strategy)
      organization_type = nil

      timestamp_type = GraphQL::ScalarType.define do
        name "Timestamp"
        coerce_input ->(value) { Time.at(value.to_i) }
        coerce_result ->(value) { value.to_i }
      end

      named_entity_interface_type = GraphQL::InterfaceType.define do
        name "NamedEntity"
        field :name, !types.String
      end

      person_type = GraphQL::ObjectType.define do
        name "Person"
        interfaces [named_entity_interface_type]
        field :name, !types.String
        field :birthdate, timestamp_type
        field :age, types.Int do
          argument :on, !timestamp_type
          resolve ->(obj, args, ctx) {
            if obj.birthdate.nil?
              nil
            else
              age_on = args[:on]
              age_years = age_on.year - obj.birthdate.year
              this_year_birthday = Time.new(age_on.year, obj.birthdate.month, obj.birthdate.day)
              if this_year_birthday > age_on
                age_years -= 1
              end
            end
            age_years
          }
        end
        field :organizations, types[organization_type] do
          resolve ->(obj, args, ctx) {
            obj.organization_ids.map { |id| DATA[id] }
          }
        end
        field :first_organization, !organization_type do
          resolve ->(obj, args, ctx) {
            DATA[obj.organization_ids.first]
          }
        end
      end

      organization_type = GraphQL::ObjectType.define do
        name "Organization"
        interfaces [named_entity_interface_type]
        field :name, !types.String
        field :leader, !person_type do
          resolve ->(obj, args, ctx) {
            DATA[obj.leader_id] || (ctx[:return_error] ? ExecutionError.new("Error on Nullable") : nil)
          }
        end
        field :returnedError, types.String do
          resolve ->(o, a, c) {
            GraphQL::ExecutionError.new("This error was returned")
          }
        end
        field :raisedError, types.String do
          resolve ->(o, a, c) {
            raise GraphQL::ExecutionError.new("This error was raised")
          }
        end

        field :nodePresence, !types[!types.Boolean] do
          resolve ->(o, a, ctx) {
            [
              ctx.irep_node.is_a?(GraphQL::InternalRepresentation::Node),
              ctx.ast_node.is_a?(GraphQL::Language::Nodes::AbstractNode),
              false, # just testing
            ]
          }
        end
      end

      node_union_type = GraphQL::UnionType.define do
        name "Node"
        possible_types [person_type, organization_type]
      end

      query_type = GraphQL::ObjectType.define do
        name "Query"
        field :node, node_union_type do
          argument :id, !types.ID
          resolve ->(obj, args, ctx) {
            obj[args[:id]]
          }
        end

        field :organization, !organization_type do
          argument :id, !types.ID
          resolve ->(obj, args, ctx) {
            args[:id].start_with?("2") && obj[args[:id]]
          }
        end

        field :organizations, types[organization_type] do
          resolve ->(obj, args, ctx) {
            [obj["2001"], obj["2002"]]
          }
        end
      end

      GraphQL::Schema.define do
        query_execution_strategy execution_strategy
        query query_type

        resolve_type ->(obj, ctx) {
          obj.respond_to?(:birthdate) ? person_type : organization_type
        }
      end
    end

    @@schema = build_schema(execution_strategy)

    def execute_query(query_string, **kwargs)
      kwargs[:root_value] = DATA
      @@schema.execute(query_string, **kwargs)
    end

    def test_it_fetches_data
      query_string = %|
      query getData($nodeId: ID = "1001") {
        flh: node(id: $nodeId) {
          __typename
          ... on Person {
            name @include(if: true)
            skippedName: name @skip(if: true)
            birthdate
            age(on: 1477660133)
          }

          ... on NamedEntity {
            ne_tn: __typename
            ne_n: name
          }

          ... on Organization {
            org_n: name
          }
        }
      }
      |
      res = execute_query(query_string)

      assert_equal nil, res["errors"], "It doesn't have an errors key"

      flh = res["data"]["flh"]
      assert_equal "Fannie Lou Hamer", flh["name"], "It returns values"
      assert_equal Time.new(1917, 10, 6).to_i, flh["birthdate"], "It returns custom scalars"
      assert_equal 99, flh["age"], "It runs resolve functions"
      assert_equal "Person", flh["__typename"], "It serves __typename"
      assert_equal "Person", flh["ne_tn"], "It serves __typename on interfaces"
      assert_equal "Fannie Lou Hamer", flh["ne_n"], "It serves interface fields"
      assert_equal false, flh.key?("skippedName"), "It obeys @skip"
      assert_equal false, flh.key?("org_n"), "It doesn't apply other type fields"
    end

    def test_it_propagates_nulls_to_field
      query_string = %|
      query getOrg($id: ID = "2001"){
        failure: node(id: $id) {
          ... on Organization {
            name
            leader { name }
          }
        }
        success: node(id: $id) {
          ... on Organization {
            name
          }
        }
      }
      |
      res = execute_query(query_string)

      failure = res["data"]["failure"]
      success = res["data"]["success"]

      assert_equal nil, failure, "It propagates nulls to the next nullable field"
      assert_equal({"name" => "SNCC"}, success, "It serves the same object if no invalid null is encountered")
      assert_equal 1, res["errors"].length , "It returns an error for the invalid null"
    end

    def test_it_propages_nulls_to_operation
      query_string = %|
        {
          foundOrg: organization(id: "2001") {
            name
          }
          organization(id: "2999") {
            name
          }
        }
      |

      res = execute_query(query_string)
      assert_equal nil, res["data"]
      assert_equal 1, res["errors"].length
    end

    def test_it_exposes_raised_and_returned_user_execution_errors
      query_string = %|
        {
          organization(id: "2001") {
            name
            returnedError
            raisedError
          }
          organizations {
            returnedError
            raisedError
          }
        }
      |

      res = execute_query(query_string)

      assert_equal "SNCC", res["data"]["organization"]["name"], "It runs the rest of the query"

      expected_errors = [
        {
          "message"=>"This error was returned",
          "locations"=>[{"line"=>5, "column"=>19}],
          "path"=>["organization", "returnedError"]
        },
        {
          "message"=>"This error was raised",
          "locations"=>[{"line"=>6, "column"=>19}],
          "path"=>["organization", "raisedError"]
        },
        {
          "message"=>"This error was raised",
          "locations"=>[{"line"=>10, "column"=>19}],
          "path"=>["organizations", 0, "raisedError"]
        },
        {
          "message"=>"This error was raised",
          "locations"=>[{"line"=>10, "column"=>19}],
          "path"=>["organizations", 1, "raisedError"]
        },
        {
          "message"=>"This error was returned",
          "locations"=>[{"line"=>9, "column"=>19}],
          "path"=>["organizations", 0, "returnedError"]
        },
        {
          "message"=>"This error was returned",
          "locations"=>[{"line"=>9, "column"=>19}],
          "path"=>["organizations", 1, "returnedError"]
        },
      ]

      expected_errors.each do |expected_err|
        assert_includes res["errors"], expected_err
      end
    end

    def test_it_applies_masking
      no_org = ->(member) { member.name == "Organization" }
      query_string = %|
      {
        node(id: "2001") {
          __typename
        }
      }|

      assert_raises(GraphQL::UnresolvedTypeError) {
        execute_query(query_string, except: no_org)
      }

      query_string = %|
      {
        organization(id: "2001") { name }
      }|

      res = execute_query(query_string, except: no_org)

      assert_equal nil, res["data"]
      assert_equal 1, res["errors"].length

      query_string = %|
      {
        __type(name: "Organization") { name }
      }|

      res = execute_query(query_string, except: no_org)

      assert_equal nil, res["data"]["__type"]
      assert_equal nil, res["errors"]
    end

    def test_it_provides_nodes_to_resolve
      query_string = %|
      {
        organization(id: "2001") {
          name
          nodePresence
        }
      }|

      res = execute_query(query_string)
      assert_equal "SNCC", res["data"]["organization"]["name"]
      assert_equal [true, true, false], res["data"]["organization"]["nodePresence"]
    end

    def test_it_runs_the_introspection_query
      execute_query(GraphQL::Introspection::INTROSPECTION_QUERY)
    end

    def test_it_propagates_deeply_nested_nulls
      query_string = %|
      {
        node(id: "1001") {
          ... on Person {
            name
            first_organization {
              leader {
                name
              }
            }
          }
        }
      }
      |
      res = execute_query(query_string)
      assert_equal nil, res["data"]["node"]
      assert_equal 1, res["errors"].length
    end

    def test_it_doesnt_add_errors_for_invalid_nulls_from_execution_errors
      query_string = %|
      query getOrg($id: ID = "2001"){
        failure: node(id: $id) {
          ... on Organization {
            name
            leader { name }
          }
        }
      }
      |
      res = execute_query(query_string, context: {return_error: true})
      error_messages = res["errors"].map { |e| e["message"] }
      assert_equal ["Error on Nullable"], error_messages
    end

    def test_it_only_resolves_fields_once_on_typed_fragments
      count = 0
      counter_type = nil

      has_count_interface = GraphQL::InterfaceType.define do
        name "HasCount"
        field :count, types.Int
        field :counter, ->{ counter_type }
      end

      counter_type = GraphQL::ObjectType.define do
        name "Counter"
        interfaces [has_count_interface]
        field :count, types.Int, resolve: ->(o,a,c) { count += 1 }
        field :counter, has_count_interface, resolve: ->(o,a,c) { :counter }
      end

      alt_counter_type = GraphQL::ObjectType.define do
        name "AltCounter"
        interfaces [has_count_interface]
        field :count, types.Int, resolve: ->(o,a,c) { count += 1 }
        field :counter, has_count_interface, resolve: ->(o,a,c) { :counter }
      end

      has_counter_interface = GraphQL::InterfaceType.define do
        name "HasCounter"
        field :counter, counter_type
      end

      query_type = GraphQL::ObjectType.define do
        name "Query"
        interfaces [has_counter_interface]
        field :counter, has_count_interface, resolve: ->(o,a,c) { :counter }
      end

      schema = GraphQL::Schema.define(
        query: query_type,
        resolve_type: ->(o, c) { o == :counter ? counter_type : nil },
        orphan_types: [alt_counter_type],
      )

      res = schema.execute("
      {
        counter { count }
        ... on HasCounter {
          counter { count }
        }
      }
      ")

      expected_data = {
        "counter" => { "count" => 1 }
      }
      assert_equal expected_data, res["data"]
      assert_equal 1, count

      # Deep typed children are correctly distinguished:
      res = schema.execute("
      {
        counter {
          ... on Counter {
            counter { count }
          }
          ... on AltCounter {
            counter { count, t: __typename }
          }
        }
      }
      ")

      expected_data = {
        "counter" => { "counter" => { "count" => 2 } }
      }
      assert_equal expected_data, res["data"]
    end
  end
end