File: schema_spec.rb

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

describe GraphQL::Schema do
  describe "inheritance" do
    class DummyFeature1 < GraphQL::Schema::Directive::Feature

    end

    class DummyFeature2 < GraphQL::Schema::Directive::Feature

    end

    class Query < GraphQL::Schema::Object
      field :some_field, String
    end

    class Mutation < GraphQL::Schema::Object
      field :some_field, String
    end

    class Subscription < GraphQL::Schema::Object
      field :some_field, String
    end

    class ExtraType < GraphQL::Schema::Object
    end

    class CustomSubscriptions < GraphQL::Subscriptions::ActionCableSubscriptions
    end

    let(:base_schema) do
      Class.new(GraphQL::Schema) do
        query Query
        mutation Mutation
        subscription Subscription
        max_complexity 1
        max_depth 2
        default_max_page_size 3
        default_page_size 2
        disable_introspection_entry_points
        orphan_types Jazz::Ensemble
        introspection Module.new
        cursor_encoder Object.new
        context_class Class.new
        directives [DummyFeature1]
        tracer GraphQL::Tracing::DataDogTracing
        extra_types ExtraType
        query_analyzer Object.new
        multiplex_analyzer Object.new
        rescue_from(StandardError) { }
        use GraphQL::Backtrace
        use GraphQL::Subscriptions::ActionCableSubscriptions, action_cable: nil, action_cable_coder: JSON
      end
    end

    it "inherits configuration from its superclass" do
      schema = Class.new(base_schema)
      assert_equal base_schema.query, schema.query
      assert_equal base_schema.mutation, schema.mutation
      assert_equal base_schema.subscription, schema.subscription
      assert_equal base_schema.introspection, schema.introspection
      assert_equal base_schema.cursor_encoder, schema.cursor_encoder
      assert_equal base_schema.validate_timeout, schema.validate_timeout
      assert_equal base_schema.max_complexity, schema.max_complexity
      assert_equal base_schema.max_depth, schema.max_depth
      assert_equal base_schema.default_max_page_size, schema.default_max_page_size
      assert_equal base_schema.default_page_size, schema.default_page_size
      assert_equal base_schema.orphan_types, schema.orphan_types
      assert_equal base_schema.context_class, schema.context_class
      assert_equal base_schema.directives, schema.directives
      assert_equal base_schema.tracers, schema.tracers
      assert_equal base_schema.query_analyzers, schema.query_analyzers
      assert_equal base_schema.multiplex_analyzers, schema.multiplex_analyzers
      assert_equal base_schema.disable_introspection_entry_points?, schema.disable_introspection_entry_points?
      assert_equal [GraphQL::Backtrace, GraphQL::Subscriptions::ActionCableSubscriptions], schema.plugins.map(&:first)
      assert_equal [ExtraType], base_schema.extra_types
      assert_equal [ExtraType], schema.extra_types
      assert_instance_of GraphQL::Subscriptions::ActionCableSubscriptions, schema.subscriptions
      assert_equal GraphQL::Query, schema.query_class
    end

    it "can override configuration from its superclass" do
      custom_query_class = Class.new(GraphQL::Query)
      extra_type_2 = Class.new(GraphQL::Schema::Enum)
      schema = Class.new(base_schema) do
        use CustomSubscriptions, action_cable: nil, action_cable_coder: JSON
        query_class(custom_query_class)
        extra_types [extra_type_2]
      end

      query = Class.new(GraphQL::Schema::Object) do
        graphql_name 'Query'
        field :some_field, String
      end
      schema.query(query)
      mutation = Class.new(GraphQL::Schema::Object) do
        graphql_name 'Mutation'
        field :some_field, String
      end
      schema.mutation(mutation)
      subscription = Class.new(GraphQL::Schema::Object) do
        graphql_name 'Subscription'
        field :some_field, String
      end
      schema.subscription(subscription)
      introspection = Module.new
      schema.introspection(introspection)
      cursor_encoder = Object.new
      schema.cursor_encoder(cursor_encoder)

      context_class = Class.new
      schema.context_class(context_class)
      schema.validate_timeout(10)
      schema.max_complexity(10)
      schema.max_depth(20)
      schema.default_max_page_size(30)
      schema.default_page_size(15)
      schema.orphan_types(Jazz::InstrumentType)
      schema.directives([DummyFeature2])
      query_analyzer = Object.new
      schema.query_analyzer(query_analyzer)
      multiplex_analyzer = Object.new
      schema.multiplex_analyzer(multiplex_analyzer)
      schema.rescue_from(GraphQL::ExecutionError)
      schema.tracer(GraphQL::Tracing::NewRelicTracing)

      assert_equal query, schema.query
      assert_equal mutation, schema.mutation
      assert_equal subscription, schema.subscription
      assert_equal introspection, schema.introspection
      assert_equal cursor_encoder, schema.cursor_encoder

      assert_equal context_class, schema.context_class
      assert_equal 10, schema.validate_timeout
      assert_equal 10, schema.max_complexity
      assert_equal 20, schema.max_depth
      assert_equal 30, schema.default_max_page_size
      assert_equal 15, schema.default_page_size
      assert_equal [Jazz::Ensemble, Jazz::InstrumentType], schema.orphan_types
      assert_equal schema.directives, GraphQL::Schema.default_directives.merge(DummyFeature1.graphql_name => DummyFeature1, DummyFeature2.graphql_name => DummyFeature2)
      assert_equal base_schema.query_analyzers + [query_analyzer], schema.query_analyzers
      assert_equal base_schema.multiplex_analyzers + [multiplex_analyzer], schema.multiplex_analyzers
      assert_equal [GraphQL::Backtrace, GraphQL::Subscriptions::ActionCableSubscriptions, CustomSubscriptions], schema.plugins.map(&:first)
      assert_equal [GraphQL::Tracing::DataDogTracing], base_schema.tracers
      assert_includes base_schema.new_trace.class.ancestors, GraphQL::Tracing::CallLegacyTracers
      assert_equal [GraphQL::Tracing::DataDogTracing, GraphQL::Tracing::NewRelicTracing], schema.tracers
      assert_includes schema.new_trace.class.ancestors, GraphQL::Tracing::CallLegacyTracers
      assert_equal custom_query_class, schema.query_class
      assert_equal [ExtraType, extra_type_2], schema.extra_types
      assert_instance_of CustomSubscriptions, schema.subscriptions
    end
  end

  describe "merged, inherited caches" do
    METHODS_TO_CACHE = {
      types: 1,
      union_memberships: 1,
      possible_types: 5, # The number of types with fields accessed in the query
    }

    let(:schema) do
      Class.new(Dummy::Schema) do
        def self.reset_calls
          @calls = Hash.new(0)
          @callers = Hash.new { |h, k| h[k] = [] }
        end

        METHODS_TO_CACHE.each do |method_name, allowed_calls|
          define_singleton_method(method_name) do |*args, &block|
            if @calls
              call_count = @calls[method_name] += 1
              @callers[method_name] << caller
            else
              call_count = 0
            end
            if call_count > allowed_calls
              raise "Called #{method_name} more than #{allowed_calls} times, previous caller: \n#{@callers[method_name].first.join("\n")}"
            end
            super(*args, &block)
          end
        end
      end
    end

    it "caches #{METHODS_TO_CACHE.keys} at runtime" do
      query_str = "
        query getFlavor($cheeseId: Int!) {
          brie: cheese(id: 1)   { ...cheeseFields, taste: flavor },
          cheese(id: $cheeseId)  {
            __typename,
            id,
            ...cheeseFields,
            ... edibleFields,
            ... on Cheese { cheeseKind: flavor },
          }
          fromSource(source: COW) { id }
          fromSheep: fromSource(source: SHEEP) { id }
          firstSheep: searchDairy(product: [{source: SHEEP}]) {
            __typename,
            ... dairyFields,
            ... milkFields
          }
          favoriteEdible { __typename, fatContent }
        }
        fragment cheeseFields on Cheese { flavor }
        fragment edibleFields on Edible { fatContent }
        fragment milkFields on Milk { source }
        fragment dairyFields on AnimalProduct {
           ... on Cheese { flavor }
           ... on Milk   { source }
        }
      "
      schema.reset_calls
      res = schema.execute(query_str,  variables: { cheeseId: 2 })
      assert_equal "Brie", res["data"]["brie"]["flavor"]
    end
  end

  describe "`use` works with plugins that attach instrumentation, tracers, query analyzers" do
    class NoOpTracer
      def trace(_key, data)
        if (query = data[:query])
          query.context[:no_op_tracer_ran] = true
        end
        yield
      end
    end

    module NoOpTrace
      def execute_query(query:)
        query.context[:no_op_trace_ran_before_query] = true
        super
      ensure
        query.context[:no_op_trace_ran_after_query] = true
      end
    end

    class NoOpAnalyzer < GraphQL::Analysis::AST::Analyzer
      def initialize(query_or_multiplex)
        query_or_multiplex.context[:no_op_analyzer_ran_initialize] = true
        super
      end

      def on_leave_field(_node, _parent, visitor)
        visitor.query.context[:no_op_analyzer_ran_on_leave_field] = true
      end

      def result
        query.context[:no_op_analyzer_ran_result] = true
      end
    end

    module PluginWithInstrumentationTracingAndAnalyzer
      def self.use(schema_defn)
        schema_defn.trace_with(NoOpTrace)
        schema_defn.tracer NoOpTracer.new
        schema_defn.query_analyzer NoOpAnalyzer
      end
    end

    query_type = Class.new(GraphQL::Schema::Object) do
      graphql_name 'Query'
      field :foobar, Integer, null: false
      def foobar; 1337; end
    end

    describe "when called on class definitions" do
      let(:schema) do
        Class.new(GraphQL::Schema) do
          query query_type
          use PluginWithInstrumentationTracingAndAnalyzer
        end
      end

      let(:query) { GraphQL::Query.new(schema, "query { foobar }") }

      it "attaches plugins correctly, runs all of their callbacks" do
        res = query.result
        assert res.key?("data")

        assert_equal true, query.context[:no_op_trace_ran_before_query]
        assert_equal true, query.context[:no_op_trace_ran_after_query]
        assert_equal true, query.context[:no_op_tracer_ran]
        assert_equal true, query.context[:no_op_analyzer_ran_initialize]
        assert_equal true, query.context[:no_op_analyzer_ran_on_leave_field]
        assert_equal true, query.context[:no_op_analyzer_ran_result]
      end
    end

    describe "when called on schema subclasses" do
      let(:schema) do
        schema = Class.new(GraphQL::Schema) do
          query query_type
        end

        # return a subclass
        Class.new(schema) do
          use PluginWithInstrumentationTracingAndAnalyzer
        end
      end

      let(:query) { GraphQL::Query.new(schema, "query { foobar }") }

      it "attaches plugins correctly, runs all of their callbacks" do
        res = query.result
        assert res.key?("data")

        assert_equal true, query.context[:no_op_trace_ran_before_query]
        assert_equal true, query.context[:no_op_trace_ran_after_query]
        assert_equal true, query.context[:no_op_tracer_ran]
        assert_equal true, query.context[:no_op_analyzer_ran_initialize]
        assert_equal true, query.context[:no_op_analyzer_ran_on_leave_field]
        assert_equal true, query.context[:no_op_analyzer_ran_result]
      end
    end
  end

  describe ".new_trace" do
    module NewTrace1
      def initialize(**opts)
        @trace_opts = opts
      end

      attr_reader :trace_opts
    end

    module NewTrace2
    end

    it "returns an instance of the configured trace_class with trace_options" do
      parent_schema = Class.new(GraphQL::Schema) do
        trace_with NewTrace1, a: 1
      end

      child_schema = Class.new(parent_schema) do
        trace_with NewTrace2, b: 2
      end

      parent_trace = parent_schema.new_trace
      assert_equal({a: 1}, parent_trace.trace_opts)
      assert_kind_of NewTrace1, parent_trace
      refute_kind_of NewTrace2, parent_trace
      assert_kind_of GraphQL::Tracing::Trace, parent_trace

      child_trace = child_schema.new_trace
      assert_equal({a: 1, b: 2}, child_trace.trace_opts)
      assert_kind_of NewTrace1, child_trace
      assert_kind_of NewTrace2, child_trace
      assert_kind_of GraphQL::Tracing::Trace, child_trace
    end

    it "returns an instance of the parent configured trace_class with trace_options" do
      parent_schema = Class.new(GraphQL::Schema) do
        trace_with NewTrace1, a: 1
      end

      child_schema = Class.new(parent_schema) do
      end

      child_trace = child_schema.new_trace
      assert_equal({a: 1}, child_trace.trace_opts)
      assert_kind_of NewTrace1, child_trace
      assert_kind_of GraphQL::Tracing::Trace, child_trace
    end
  end

  describe ".possible_types" do
    it "returns a single item for objects" do
      assert_equal [Dummy::Cheese], Dummy::Schema.possible_types(Dummy::Cheese)
    end

    it "returns empty for abstract types without any possible types" do
      unknown_union = Class.new(GraphQL::Schema::Union) { graphql_name("Unknown") }
      assert_equal [], Dummy::Schema.possible_types(unknown_union)
    end

    it "returns correct types for interfaces based on the context" do
      assert_equal [], Jazz::Schema.possible_types(Jazz::PrivateNameEntity, { private: false })
      assert_equal [Jazz::Ensemble], Jazz::Schema.possible_types(Jazz::PrivateNameEntity, { private: true })
    end

    it "returns correct types for unions based on the context" do
      assert_equal [Jazz::Musician], Jazz::Schema.possible_types(Jazz::PerformingAct, { hide_ensemble: true })
      assert_equal [Jazz::Musician, Jazz::Ensemble], Jazz::Schema.possible_types(Jazz::PerformingAct, { hide_ensemble: false })
    end
  end

  describe 'validate' do
    let(:schema) { Dummy::Schema}

    describe 'validate' do
      it 'validates valid query ' do
        query = "query sample { root }"

        errors = schema.validate(query)

        assert_empty errors
      end

      it 'validates invalid query ' do
        query = "query sample { invalid }"

        errors = schema.validate(query)

        assert_equal(1, errors.size)
      end
    end
  end

  describe "requiring query" do
    class QueryRequiredSchema < GraphQL::Schema
    end
    it "returns an error if no query type is defined" do
      res = QueryRequiredSchema.execute("{ blah }")
      assert_equal ["Schema is not configured for queries"], res["errors"].map { |e| e["message"] }
    end
  end

  describe ".as_json" do
    it "accepts options for the introspection query" do
      introspection_schema = Class.new(Dummy::Schema) do
        max_depth 20
      end
      default_res = introspection_schema.as_json
      refute default_res["data"]["__schema"].key?("description")
      directives = default_res["data"]["__schema"]["directives"]
      refute directives.first.key?("isRepeatable")
      refute default_res["data"]["__schema"]["types"].find { |t| t["kind"] == "SCALAR" }.key?("specifiedByURL")
      refute default_res["data"]["__schema"]["types"].find { |t| t["kind"] == "INPUT_OBJECT" }.key?("isOneOf")
      assert_includes default_res.to_s, "oldSource"

      full_res = introspection_schema.as_json(
        include_deprecated_args: false,
        include_is_one_of: true,
        include_is_repeatable: true,
        include_schema_description: true,
        include_specified_by_url: true,
      )

      assert full_res["data"]["__schema"].key?("description")
      directives = full_res["data"]["__schema"]["directives"]
      assert directives.first.key?("isRepeatable")
      assert full_res["data"]["__schema"]["types"].find { |t| t["kind"] == "SCALAR" }.key?("specifiedByURL")
      assert full_res["data"]["__schema"]["types"].find { |t| t["kind"] == "INPUT_OBJECT" }.key?("isOneOf")
      refute_includes full_res.to_s, "oldSource"
    end
  end

  it "starts with no references_to" do
    assert_equal({}, GraphQL::Schema.references_to)
  end
end