File: field_extension_spec.rb

package info (click to toggle)
ruby-graphql 2.2.17-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 9,584 kB
  • sloc: ruby: 67,505; ansic: 1,753; yacc: 831; javascript: 331; makefile: 6
file content (393 lines) | stat: -rw-r--r-- 12,993 bytes parent folder | download | duplicates (2)
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
# frozen_string_literal: true
require "spec_helper"

describe GraphQL::Schema::FieldExtension do
  module FilterTestSchema
    class DoubleFilter < GraphQL::Schema::FieldExtension
      def after_resolve(object:, value:, arguments:, context:, memo:)
        value * 2
      end
    end

    class PowerOfFilter < GraphQL::Schema::FieldExtension
      def after_resolve(object:, value:, arguments:, context:, memo:)
        value**options.fetch(:power, 2)
      end
    end

    class MultiplyByOption < GraphQL::Schema::FieldExtension
      def after_resolve(object:, value:, arguments:, context:, memo:)
        value * options[:factor]
      end
    end

    class MultiplyByArgument < GraphQL::Schema::FieldExtension
      def apply
        field.argument(:factor, Integer)
      end

      def resolve(object:, arguments:, context:)
        factor = arguments[:factor]
        yield(object, arguments, factor)
      end

      def after_resolve(object:, value:, arguments:, context:, memo:)
        value * memo
      end
    end

    class MultiplyByArgumentUsingResolve < GraphQL::Schema::FieldExtension
      def apply
        field.argument(:factor, Integer)
      end

      # `yield` returns the user-returned value
      # This method's return value is passed along
      def resolve(object:, arguments:, context:)
        factor = arguments[:factor]
        yield(object, arguments) * factor
      end
    end

    class MultiplyByArgumentUsingAfterResolve < GraphQL::Schema::FieldExtension
      def apply
        field.argument(:factor, Integer)
      end

      def resolve(object:, arguments:, context:)
        new_arguments = arguments.dup
        new_arguments.delete(:factor)
        yield(object, new_arguments, { original_arguments: arguments})
      end

      def after_resolve(object:, value:, arguments:, context:, memo:)
        value * memo[:original_arguments][:factor]
      end
    end

    class ExtendsArguments < GraphQL::Schema::FieldExtension
      def resolve(object:, arguments:, **_rest)
        new_args = arguments.dup
        new_args[:extended] = true
        yield(object, new_args)
      end

      def after_resolve(arguments:, context:, value:, **_rest)
        context[:extended_args] = arguments[:extended]
        value
      end
    end

    class ShortcutsResolve < GraphQL::Schema::FieldExtension
      def resolve(**_args)
        options[:shortcut_value]
      end
    end

    class ObjectClassExtension < GraphQL::Schema::FieldExtension
      def resolve(object:, **_args)
        object.class.name
      end

      def after_resolve(value:, object:, **_args)
        [object.class.name, value]
      end
    end

    class BaseObject < GraphQL::Schema::Object
    end

    class Query < BaseObject
      field :doubled, Integer, null: false, resolver_method: :pass_thru do
        extension(DoubleFilter)
        argument :input, Integer
      end

      field :square, Integer, null: false, resolver_method: :pass_thru, extensions: [PowerOfFilter] do
        argument :input, Integer
      end

      field :cube, Integer, null: false, resolver_method: :pass_thru do
        extension(PowerOfFilter, power: 3)
        argument :input, Integer
      end

      field :tripled_by_option, Integer, null: false, resolver_method: :pass_thru do
        extension(MultiplyByOption, factor: 3)
        argument :input, Integer
      end

      field :tripled_by_option2, Integer, null: false, resolver_method: :pass_thru,
        extensions: [{ MultiplyByOption => { factor: 3 } }] do
          argument :input, Integer
        end

      field :multiply_input, Integer, null: false, resolver_method: :pass_thru, extensions: [MultiplyByArgument] do
        argument :input, Integer
      end

      field :multiply_input2, Integer, null: false, resolver_method: :pass_thru, extensions: [MultiplyByArgumentUsingResolve] do
        argument :input, Integer
      end

      def pass_thru(input:, **args)
        input # return it as-is, it will be modified by extensions
      end

      field :multiply_input3, Integer, null: false, resolver_method: :pass_thru_without_splat, extensions: [MultiplyByArgumentUsingAfterResolve] do
        argument :input, Integer
      end

      # lack of kwargs splat demonstrates the extended arguments are passed to the resolver method
      def pass_thru_without_splat(input:)
        input
      end

      field :multiple_extensions, Integer, null: false, resolver_method: :pass_thru,
        extensions: [DoubleFilter, { MultiplyByOption => { factor: 3 } }] do
          argument :input, Integer
        end

      field :extended_then_shortcut, Integer do
        extension ExtendsArguments
        extension ShortcutsResolve, shortcut_value: 3
      end

      field :object_class_test, [String], null: false, extensions: [ObjectClassExtension]
    end

    class Schema < GraphQL::Schema
      query(Query)
    end
  end

  def exec_query(query_str, **kwargs)
    FilterTestSchema::Schema.execute(query_str, **kwargs)
  end

  describe "object" do
    it "is the schema type object" do
      res = exec_query("{ objectClassTest }")
      assert_equal ["FilterTestSchema::Query", "FilterTestSchema::Query"], res["data"]["objectClassTest"]
    end
  end

  describe "reading" do
    it "has a reader method" do
      field = FilterTestSchema::Query.fields["multiplyInput"]
      assert_equal 1, field.extensions.size
      assert_instance_of FilterTestSchema::MultiplyByArgument, field.extensions.first
    end
  end

  describe "passing along extended arguments" do
    it "works even when shortcut" do
      ctx = {}
      res =  exec_query("{ extendedThenShortcut }", context: ctx)
      assert_equal 3, res["data"]["extendedThenShortcut"]
      assert_equal true, ctx[:extended_args]
    end
  end

  describe "modifying return values" do
    it "returns the modified value" do
      res = exec_query("{ doubled(input: 5) }")
      assert_equal 10, res["data"]["doubled"]
    end

    it "returns the modified value from `yield`" do
      res = exec_query("{ multiplyInput2(input: 5, factor: 5) }")
      assert_equal 25, res["data"]["multiplyInput2"]
    end

    it "has access to config options" do
      # The factor of three came from an option
      res = exec_query("{ tripledByOption(input: 4) }")
      assert_equal 12, res["data"]["tripledByOption"]
    end

    it "supports extension with options via extensions kwarg" do
      # The factor of three came from an option
      res = exec_query("{ tripledByOption2(input: 4) }")
      assert_equal 12, res["data"]["tripledByOption2"]
    end

    it "provides an empty hash as default options" do
      res = exec_query("{ square(input: 4) }")
      assert_equal 16, res["data"]["square"]
      res = exec_query("{ cube(input: 4) }")
      assert_equal 64, res["data"]["cube"]
    end

    it "can hide arguments from resolve methods" do
      res = exec_query("{ multiplyInput(input: 3, factor: 5) }")
      assert_equal 15, res["data"]["multiplyInput"]
    end

    it "calls the resolver method with the extended arguments" do
      res = exec_query("{ multiplyInput3(input: 3, factor: 5) }")
      assert_equal 15, res["data"]["multiplyInput3"]
    end

    it "supports multiple extensions via extensions kwarg" do
      # doubled then multiplied by 3 specified via option
      res = exec_query("{ multipleExtensions(input: 3) }")
      assert_equal 18, res["data"]["multipleExtensions"]
    end
  end

  describe "after_define" do
    class AfterDefineThing < GraphQL::Schema::Object
      class AfterDefineExtension < GraphQL::Schema::FieldExtension
        attr_reader :apply_arguments_count, :after_define_arguments_count

        def apply
          @apply_arguments_count = field.all_argument_definitions.count
        end

        def after_define
          @after_define_arguments_count = field.all_argument_definitions.count
        end
      end

      field :with_extension, String, extensions: [AfterDefineExtension] do
        argument :something, ID
      end

      field :with_extension_2, String do
        extension(AfterDefineExtension)
        argument :something, ID
      end

      field :with_extension_3, String do
        argument :something, ID
        extension(AfterDefineExtension)
      end

      field :without_extension, String do
        argument :something, ID
      end
    end

    it "is applied after the define block when using `extensions: [...]`" do
      with_extension = AfterDefineThing.get_field("withExtension")
      ext = with_extension.extensions.first
      assert_equal 0, ext.apply_arguments_count
      assert_equal 1, ext.after_define_arguments_count
      assert ext.frozen?
    end

    it "applies in Ruby order when added in the define block" do
      with_extension_2_ext = AfterDefineThing.get_field("withExtension2").extensions.first
      assert_equal 0, with_extension_2_ext.apply_arguments_count
      assert_equal 1, with_extension_2_ext.after_define_arguments_count
      assert with_extension_2_ext.frozen?

      with_extension_3_ext = AfterDefineThing.get_field("withExtension3").extensions.first
      assert_equal 1, with_extension_3_ext.apply_arguments_count
      assert_equal 1, with_extension_3_ext.after_define_arguments_count
      assert with_extension_3_ext.frozen?
    end

    it "is called immediately when using `field.extension(...)`" do
      without_extension = AfterDefineThing.get_field("withoutExtension")
      without_extension.extension(AfterDefineThing::AfterDefineExtension)
      ext = without_extension.extensions.first
      assert_equal 1, ext.apply_arguments_count
      assert_equal 1, ext.after_define_arguments_count
      assert ext.frozen?
    end
  end

  describe ".default_argument" do
    class DefaultArgumentThing < GraphQL::Schema::Object
      class DefaultArgumentExtension < GraphQL::Schema::FieldExtension
        default_argument :query, String, required: false
      end

      field :search_1, String, extensions: [DefaultArgumentExtension]

      field :search_2, String, extensions: [DefaultArgumentExtension] do
        argument :query, String
      end
    end

    it "adds an argument if one wasn't given in the definition block" do
      search_1 = DefaultArgumentThing.get_field("search1")
      assert_equal [:query], search_1.extensions.first.added_default_arguments
      assert_equal GraphQL::Types::String, search_1.get_argument("query").type

      search_2 = DefaultArgumentThing.get_field("search2")
      assert_equal [], search_2.extensions.first.added_default_arguments
      assert_equal GraphQL::Types::String.to_non_null_type, search_2.get_argument("query").type
    end
  end

  describe ".extras" do
    class ExtensionExtrasSchema < GraphQL::Schema
      class AstNodeExtension < GraphQL::Schema::FieldExtension
        extras [:ast_node]
        def resolve(object:, arguments:, context:, **rest)
          context[:last_ast_node] = arguments[:ast_node]
          yield(object, arguments)
        end
      end

      class AnotherAstNodeExtension < AstNodeExtension
        def resolve(object:, arguments:, context:, **rest)
          context[:other_last_ast_node] = arguments[:ast_node]
          yield(object, arguments)
        end
      end

      class Query < GraphQL::Schema::Object
        field :f1, Int, extensions: [AstNodeExtension] do
          argument :i1, Int
        end

        def f1(i1:)
          i1
        end

        field :f2, Int, extensions: [AstNodeExtension], extras: [:ast_node]

        def f2(ast_node:)
          (ast_node.alias || "").size
        end

        field :f3, Int, extensions: [AstNodeExtension, AnotherAstNodeExtension] do
          argument :i1, Int
        end

        def f3(i1:)
          i1
        end
      end
      query(Query)
    end

    it "appends to the field's extras, but removes them when resolving" do
      assert_equal [:ast_node], ExtensionExtrasSchema::Query.get_field("f1").extras
      res = ExtensionExtrasSchema.execute("{ f1(i1: 1) }")
      assert_equal 1, res["data"]["f1"]
      assert_instance_of GraphQL::Language::Nodes::Field, res.context[:last_ast_node]
      assert_equal "f1", res.context[:last_ast_node].name
    end

    it "allows already-defined extras to pass thru" do
      res = ExtensionExtrasSchema.execute("{ something: f2 }")
      assert_equal 9, res["data"]["something"]
      assert_instance_of GraphQL::Language::Nodes::Field, res.context[:last_ast_node]
      assert_equal "f2", res.context[:last_ast_node].name
    end

    it "works with multiple extensions" do
      res = ExtensionExtrasSchema.execute("{ f3(i1: 3) }")
      assert_equal 3, res["data"]["f3"]
      assert_instance_of GraphQL::Language::Nodes::Field, res.context[:last_ast_node]
      assert_equal "f3", res.context[:last_ast_node].name
      assert_instance_of GraphQL::Language::Nodes::Field, res.context[:other_last_ast_node]
      assert_equal "f3", res.context[:other_last_ast_node].name
    end
  end
end