File: union_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 (407 lines) | stat: -rw-r--r-- 10,418 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
# frozen_string_literal: true
require "spec_helper"

describe GraphQL::Schema::Union do
  let(:union) { Jazz::PerformingAct }

  describe ".path" do
    it "is the name" do
      assert_equal "PerformingAct", union.path
    end
  end

  describe "type info" do
    it "has some" do
      assert_equal 2, union.possible_types.size
    end
  end

  describe "filter_possible_types" do
    it "filters types" do
      assert_equal [Jazz::Musician], union.possible_types(context: { hide_ensemble: true })
    end
  end

  describe "in queries" do
    it "works" do
      query_str = <<-GRAPHQL
      {
        nowPlaying {
          ... on Musician {
            name
            instrument {
              family
            }
          }
          ... on Ensemble {
            name
          }
        }
      }
      GRAPHQL

      res = Jazz::Schema.execute(query_str)
      expected_data = { "name" => "Bela Fleck and the Flecktones" }
      assert_equal expected_data, res["data"]["nowPlaying"]
    end

    it "does not allow querying filtered types" do
      query_str = <<-GRAPHQL
      {
        nowPlaying {
          ... on Musician {
            name
            instrument {
              family
            }
          }
          ... on Ensemble {
            name
          }
        }
      }
      GRAPHQL

      res = Jazz::Schema.execute(query_str, context: { hide_ensemble: true })
      assert_equal 1, res.to_h["errors"].count
      assert_equal "Fragment on Ensemble can't be spread inside PerformingAct", res.to_h["errors"].first["message"]
    end

    describe "type resolution" do
      Box = Struct.new(:value)

      class Schema < GraphQL::Schema
        class A < GraphQL::Schema::Object
          field :a, String, null: false, method: :itself
        end

        class B < GraphQL::Schema::Object
          field :b, String, method: :itself
        end

        class C < GraphQL::Schema::Object
          field :c, Boolean, method: :itself
        end

        class UnboxedUnion < GraphQL::Schema::Union
          possible_types A, C

          def self.resolve_type(object, ctx)
            case object
            when FalseClass
              C
            else
              A
            end
          end
        end

        class BoxedUnion < GraphQL::Schema::Union
          possible_types A, B, C

          def self.resolve_type(object, ctx)
            case object.value
            when "return-nil"
              [B, nil]
            when FalseClass
              [C, object.value]
            else
              [A, object.value]
            end
          end
        end

        class Query < GraphQL::Schema::Object
          field :boxed_union, BoxedUnion

          def boxed_union
            Box.new(context[:value])
          end

          field :unboxed_union, UnboxedUnion

          def unboxed_union
            context[:value]
          end
        end

        query(Query)
      end

      describe "two-value resolution" do
        it "can cast the object after resolving the type" do

          query_str = <<-GRAPHQL
          {
            boxedUnion {
              ... on A { a }
            }
          }
          GRAPHQL

          res = Schema.execute(query_str, context: { value: "unwrapped" })

          assert_equal({
            'data' => { 'boxedUnion' => { 'a' => 'unwrapped' } }
          }, res.to_h)
        end

        it "uses `false` when returned from resolve_type" do
          query_str = <<-GRAPHQL
          {
            boxedUnion {
              ... on C { c }
            }
          }
          GRAPHQL

          res = Schema.execute(query_str, context: { value: false })

          assert_equal({
            'data' => { 'boxedUnion' => { 'c' => false } }
          }, res.to_h)
        end

        it "uses `nil` when returned from resolve_type" do
          query_str = <<-GRAPHQL
          {
            boxedUnion {
              ... on B { b }
            }
          }
          GRAPHQL

          res = Schema.execute(query_str, context: { value: "return-nil" })

          assert_equal({
            'data' => { 'boxedUnion' => { 'b' => nil } }
          }, res.to_h)
        end
      end

      describe "single-value resolution" do
        it "can cast the object after resolving the type" do

          query_str = <<-GRAPHQL
          {
            unboxedUnion {
              ... on A { a }
            }
          }
          GRAPHQL

          res = Schema.execute(query_str, context: { value: "string" })

          assert_equal({
            'data' => { 'unboxedUnion' => { 'a' => 'string' } }
          }, res.to_h)
        end

        it "works with literal false values" do
          query_str = <<-GRAPHQL
          {
            unboxedUnion {
              ... on C { c }
            }
          }
          GRAPHQL

          res = Schema.execute(query_str, context: { value: false })

          assert_equal({
            'data' => { 'unboxedUnion' => { 'c' => false } }
          }, res.to_h)
        end
      end
    end
  end

  it "doesn't allow adding non-object types" do
    object_type = Class.new(GraphQL::Schema::Object) do
      graphql_name "SomeObject"
    end

    err = assert_raises ArgumentError do
      Class.new(GraphQL::Schema::Union) do
        graphql_name "SomeUnion"
        possible_types object_type, GraphQL::Types::Int
      end
    end
    expected_message = "Union possible_types can only be object types (not SCALAR, "
    assert_includes err.message, expected_message

    input_type = Class.new(GraphQL::Schema::InputObject) do
      graphql_name "SomeInput"
      argument :arg, GraphQL::Types::Int
    end

    err = assert_raises ArgumentError do
      Class.new(GraphQL::Schema::Union) do
        graphql_name "SomeUnion"
        possible_types object_type, input_type
      end
    end

    expected_message = "Union possible_types can only be object types (not INPUT_OBJECT, "
    assert_includes err.message, expected_message

    err = assert_raises ArgumentError do
      Class.new(GraphQL::Schema::Union) do
        graphql_name "SomeUnion"
        possible_types object_type, 1234
      end
    end

    expected_message = "Union possible_types can only be class-based GraphQL types (not 1234 (Integer))."
    assert_includes err.message, expected_message
  end

  it "doesn't allow adding interface" do
    object_type = Class.new(GraphQL::Schema::Object) do
      graphql_name "SomeObject"
    end

    interface_type = Module.new {
      include GraphQL::Schema::Interface
      graphql_name "SomeInterface"
    }

    err = assert_raises ArgumentError do
      Class.new(GraphQL::Schema::Union) do
        graphql_name "SomeUnion"
        possible_types object_type, interface_type
      end
    end

    expected_message = /Union possible_types can only be object types \(not interface types\), remove SomeInterface \(#<Module:0x[a-f0-9]+>\)/

    assert_match expected_message, err.message

    union_type = Class.new(GraphQL::Schema::Union) do
      graphql_name "SomeUnion"
      possible_types object_type, GraphQL::Schema::LateBoundType.new("SomeInterface")
    end

    err2 = assert_raises ArgumentError do
      Class.new(GraphQL::Schema) do
        query(object_type)
        orphan_types(union_type, interface_type)
      end
    end

    assert_match expected_message, err2.message
  end

  describe "migrate legacy tests" do
    describe "#resolve_type" do
      let(:result) { Dummy::Schema.execute(query_string) }
      let(:query_string) {%|
        {
          allAnimal {
            type: __typename
            ... on Cow {
              cowName: name
            }
            ... on Goat {
              goatName: name
            }
          }

          allAnimalAsCow {
            type: __typename
            ... on Cow {
              name
            }
          }
        }
      |}

      it 'returns correct types for general schema and specific union' do
        expected_result = {
          # When using Query#resolve_type
          "allAnimal" => [
            { "type" => "Cow", "cowName" => "Billy" },
            { "type" => "Goat", "goatName" => "Gilly" }
          ],

          # When using UnionType#resolve_type
          "allAnimalAsCow" => [
            { "type" => "Cow", "name" => "Billy" },
            { "type" => "Cow", "name" => "Gilly" }
          ]
        }
        assert_equal expected_result, result["data"]
      end
    end

    describe "typecasting from union to union" do
      let(:result) { Dummy::Schema.execute(query_string) }
      let(:query_string) {%|
        {
          allDairy {
            dairyName: __typename
            ... on Beverage {
              bevName: __typename
              ... on Milk {
                flavors
              }
            }
          }
        }
      |}

      it "casts if the object belongs to both unions" do
        expected_result = [
          {"dairyName"=>"Cheese"},
          {"dairyName"=>"Cheese"},
          {"dairyName"=>"Cheese"},
          {"dairyName"=>"Milk", "bevName"=>"Milk", "flavors"=>["Natural", "Chocolate", "Strawberry"]},
        ]
        assert_equal expected_result, result["data"]["allDairy"]
      end
    end

    describe "list of union type" do
      describe "fragment spreads" do
        let(:result) { Dummy::Schema.execute(query_string) }
        let(:query_string) {%|
          {
            allDairy {
              __typename
              ... milkFields
              ... cheeseFields
            }
          }
          fragment milkFields on Milk {
            id
            source
            origin
            flavors
          }

          fragment cheeseFields on Cheese {
            id
            source
            origin
            flavor
          }
        |}

        it "resolves the right fragment on the right item" do
          all_dairy = result["data"]["allDairy"]
          cheeses = all_dairy.first(3)
          cheeses.each do |cheese|
            assert_equal "Cheese", cheese["__typename"]
            assert_equal ["__typename", "id", "source", "origin", "flavor"], cheese.keys
          end

          milks = all_dairy.last(1)
          milks.each do |milk|
            assert_equal "Milk", milk["__typename"]
            assert_equal ["__typename", "id", "source", "origin", "flavors"], milk.keys
          end
        end
      end
    end
  end
end