File: query_complexity_spec.rb

package info (click to toggle)
ruby-graphql 2.5.19-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 13,868 kB
  • sloc: ruby: 80,420; ansic: 1,808; yacc: 845; javascript: 480; makefile: 6
file content (996 lines) | stat: -rw-r--r-- 25,745 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
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
# frozen_string_literal: true
require "spec_helper"

describe GraphQL::Analysis::QueryComplexity do
  let(:schema) { Class.new(Dummy::Schema) { complexity_cost_calculation_mode(:future) } }
  let(:reduce_result) { GraphQL::Analysis.analyze_query(query, [GraphQL::Analysis::QueryComplexity]) }
  let(:reduce_multiplex_result) {
    GraphQL::Analysis.analyze_multiplex(multiplex, [GraphQL::Analysis::QueryComplexity])
  }
  let(:variables) { {} }
  let(:query_context) { {} }
  let(:query) { GraphQL::Query.new(schema, query_string, context: query_context, variables: variables) }
  let(:multiplex) {
    GraphQL::Execution::Multiplex.new(
      schema: schema,
      queries: [query.dup, query.dup],
      context: {},
      max_complexity: 10
    )
  }

  describe "simple queries" do
    let(:query_string) {%|
      query cheeses {
        # complexity of 3
        cheese1: cheese(id: 1) {
          id
          flavor
          __typename
        }

        # complexity of 4
        cheese2: cheese(id: 2) {
          similarCheese(source: SHEEP) {
            ... on Cheese {
              similarCheese(source: SHEEP) {
                id
              }
            }
          }
        }
      }
    |}

    it "sums the complexity" do
      complexities = reduce_result.first
      assert_equal 8, complexities
    end
  end

  describe "with skip/include" do
    let(:query_string) {%|
      query cheeses($skip: Boolean = false, $include: Boolean = true) {
        fields: cheese(id: 1) {
          flavor
          origin @skip(if: $skip)
          source @include(if: $include)
        }
        inlineFragments: cheese(id: 1) {
          ...on Cheese { flavor }
          ...on Cheese @skip(if: $skip) { origin }
          ...on Cheese @include(if: $include) { source }
        }
        fragmentSpreads: cheese(id: 1) {
          ...Flavorful
          ...Original @skip(if: $skip)
          ...Sourced @include(if: $include)
        }
      }
      fragment Flavorful on Cheese { flavor }
      fragment Original on Cheese { origin }
      fragment Sourced on Cheese { source }
    |}

    it "sums up all included complexities" do
      assert_equal 12, reduce_result.first
    end

    describe "when skipped by directives" do
      let(:variables) { { "skip" => true, "include" => false } }
      it "doesn't include skipped fields and fragments" do
        assert_equal 6, reduce_result.first
      end
    end
  end

  describe "query with fragments" do
    let(:query_string) {%|
      {
        # complexity of 3
        cheese1: cheese(id: 1) {
          id
          flavor
        }

        # complexity of 7
        cheese2: cheese(id: 2) {
          ... cheeseFields1
          ... cheeseFields2
        }
      }

      fragment cheeseFields1 on Cheese {
        similarCow: similarCheese(source: COW) {
          id
          ... cheeseFields2
        }
      }

      fragment cheeseFields2 on Cheese {
        similarSheep: similarCheese(source: SHEEP) {
          id
        }
      }
    |}

    it "counts all fragment usages, not the definitions" do
      complexity = reduce_result.first
      assert_equal 10, complexity
    end

    describe "mutually exclusive types" do
      let(:query_string) {%|
        {
          favoriteEdible {
            # 1 for everybody
            fatContent

            # 1 for everybody
            ... on Edible {
              origin
            }

            # 1 for honey, aspartame
            ... on Sweetener {
              sweetness
            }

            # 2 for milk
            ... milkFields
            # 1 for cheese
            ... cheeseFields
            # 1 for honey
            ... honeyFields
            # 1 for milk + cheese
            ... dairyProductFields
          }
        }

        fragment milkFields on Milk {
          id
          source
        }

        fragment cheeseFields on Cheese {
          source
        }

        fragment honeyFields on Honey {
          flowerType
        }

        fragment dairyProductFields on DairyProduct {
          ... on Cheese {
            flavor
          }

          ... on Milk {
            flavors
          }
        }
      |}

      it "gets the max among options" do
        complexity = reduce_result.first
        assert_equal 6, complexity
      end
    end


    describe "when there are no selections on any object types" do
      let(:query_string) {%|
        {
          # 1 for everybody
          favoriteEdible {
            # 1 for everybody
            fatContent

            # 1 for everybody
            ... on Edible { origin }

            # 1 for honey, aspartame
            ... on Sweetener { sweetness }
          }
        }
      |}

      it "gets the max among interface types" do
        complexity = reduce_result.first
        assert_equal 4, complexity
      end
    end

    describe "redundant fields" do
      let(:query_string) {%|
      {
        favoriteEdible {
          fatContent
          # this is executed separately and counts separately:
          aliasedFatContent: fatContent

          ... on Edible {
            fatContent
          }

          ... edibleFields
        }
      }

      fragment edibleFields on Edible {
        fatContent
      }
      |}

      it "only counts them once" do
        complexity = reduce_result.first
        assert_equal 3, complexity
      end
    end

    describe "redundant fields not within a fragment" do
      let(:query_string) {%|
      {
        cheese {
          id
        }

        cheese {
          id
        }
      }
      |}

      it "only counts them once" do
        complexity = reduce_result.first
        assert_equal 2, complexity
      end
    end
  end

  describe "relay types" do
    let(:schema) { Class.new(StarWars::Schema) { complexity_cost_calculation_mode(:future) } }
    let(:query) { GraphQL::Query.new(schema, query_string) }
    let(:query_string) {%|
    {
      rebels {
        ships(first: 1) {
          edges {
            node {
              id
            }
          }
          nodes {
            id
          }
          pageInfo {
            hasNextPage
          }
        }
      }
    }
    |}

    it "gets the complexity" do
      complexity = reduce_result.first
      expected_complexity = 1 + # rebels
        1 + # ships
        1 + # edges
        1 + # nodes
        1 + 1 + # pageInfo, hasNextPage
        1 + 1 + 1 # node, id, id
      assert_equal expected_complexity, complexity
    end

    describe "first/last" do
      let(:query_string) {%|
      {
        rebels {
          s1: ships(first: 5) {
            edges {
              node {
                id
              }
            }
            pageInfo {
              hasNextPage
            }
          }

          s2: ships(last: 3) {
            nodes { id }
          }
        }
      }
      |}

      it "uses first/last for calculating complexity" do
        complexity = reduce_result.first

        expected_complexity = (
          1 + # rebels
          (1 + 1 + (5 * 2) + 2) + # s1
          (1 + 1 + (3 * 1) + 0) # s2
        )
        assert_equal expected_complexity, complexity
      end
    end

    describe "Field-level max_page_size" do
      let(:query_string) {%|
      {
        rebels {
          ships {
            nodes { id }
          }
        }
      }
      |}

      it "uses field max_page_size" do
        complexity = reduce_result.first
        assert_equal 1 + 1 + 1 + (1000 * 1), complexity
      end
    end

    describe "Schema-level default_max_page_size" do
      let(:query_string) {%|
      {
        rebels {
          bases {
            nodes { id }
            totalCount
          }
        }
      }
      |}

      it "uses schema default_max_page_size" do
        complexity = reduce_result.first
        assert_equal 1 + 1 + 1 + (3 * 1) + 1, complexity
      end
    end

    describe "Field-level default_page_size" do
      let(:query_string) {%|
      {
        rebels {
          shipsWithDefaultPageSize {
            nodes { id }
          }
        }
      }
      |}

      it "uses field default_page_size" do
        complexity = reduce_result.first
        assert_equal 1 + 1 + 1 + (500 * 1), complexity
      end
    end

    describe "Schema-level default_page_size" do
      let(:schema) { Class.new(StarWars::SchemaWithDefaultPageSize) { complexity_cost_calculation_mode(:future) } }
      let(:query) { GraphQL::Query.new(schema, query_string) }
      let(:query_string) {%|
      {
        rebels {
          bases {
            nodes { id }
            totalCount
          }
        }
      }
      |}

      it "uses schema default_page_size" do
        complexity = reduce_result.first
        assert_equal 1 + 1 + 1 + (2 * 1) + 1, complexity
      end
    end
  end

  describe "calculation complexity for a multiplex" do
    let(:query_string) {%|
      query cheeses {
        cheese(id: 1) {
          id
          flavor
          source
        }
      }
    |}


    it "sums complexity for both queries" do
      complexity = reduce_multiplex_result.first
      assert_equal 8, complexity
    end

    describe "abstract type" do
      let(:query_string) {%|
        query Edible {
          allEdible {
            origin
            fatContent
          }
        }
      |}
      it "sums complexity for both queries" do
        complexity = reduce_multiplex_result.first
        assert_equal 6, complexity
      end
    end
  end

  describe "custom complexities" do
    class CustomComplexitySchema < GraphQL::Schema
      module ComplexityInterface
        include GraphQL::Schema::Interface
        field :value, Int
      end

      class SingleComplexity < GraphQL::Schema::Object
        field :value, Int, complexity: 0.1
        field :complexity, SingleComplexity do
          argument :int_value, Int, required: false
          complexity(->(ctx, args, child_complexity) { args[:int_value] + child_complexity })
        end
        implements ComplexityInterface
      end

      class DoubleComplexity < GraphQL::Schema::Object
        field :value, Int, complexity: 4
        implements ComplexityInterface
      end

      class Query < GraphQL::Schema::Object
        field :complexity, SingleComplexity do
          argument :int_value, Int, required: false, prepare: ->(val, ctx) {
            if ctx[:raise_prepare_error]
              raise GraphQL::ExecutionError, "Boom"
            else
              val
            end
          }
          complexity ->(ctx, args, child_complexity) { args[:int_value] + child_complexity }
        end

        def complexity(int_value:)
          { value: int_value }
        end

        field :inner_complexity, ComplexityInterface do
          argument :value, Int, required: false
        end
      end

      query(Query)
      orphan_types(DoubleComplexity)
      complexity_cost_calculation_mode(:future)

      module CustomIntrospection
        class DynamicFields < GraphQL::Introspection::DynamicFields
          field :__typename, String, complexity: 100
        end

        class EntryPoints < GraphQL::Introspection::EntryPoints
          class CustomIntrospectionField < GraphQL::Schema::Field
            def calculate_complexity(query:, nodes:, child_complexity:)
              child_complexity + 0.6
            end
          end
          field_class CustomIntrospectionField
          field :__schema, GraphQL::Schema::LateBoundType.new("__Schema")
        end
      end

      introspection(CustomIntrospection)
    end

    let(:query) { GraphQL::Query.new(complexity_schema, query_string, context: query_context) }
    let(:complexity_schema) { CustomComplexitySchema }
    let(:query_string) {%|
      {
        a: complexity(intValue: 3) { value }
        b: complexity(intValue: 6) {
          value
          complexity(intValue: 1) {
            value
          }
        }
      }
    |}

    it "sums the complexity" do
      complexity = reduce_result.first
      # 10 from `complexity`, `0.3` from `value`
      assert_equal 10.3, complexity
    end

    describe "introspection" do
      let(:query_string) { "{ __typename __schema { queryType } }"}

      it "does custom complexity for introspection" do
        complexity = reduce_result.first
        # 100 + 1 + 0.6
        assert_equal 101.6, complexity
      end
    end

    describe "same field on multiple types" do
      let(:query_string) {%|
      {
        innerComplexity(intValue: 2) {
          ... on SingleComplexity { value }
          ... on DoubleComplexity { value }
        }
      }
      |}

      it "picks them max for those fields" do
        complexity = reduce_result.first
        # 1 for innerComplexity + 4 for DoubleComplexity.value
        assert_equal 5, complexity
      end
    end

    describe "when prepare raises an error" do
      let(:query_string) { "{ complexity(intValue: 3) { value } }"}
      let(:query_context) { { raise_prepare_error: true } }

      it "handles it nicely" do
        result = query.result
        assert_equal ["Boom"], result["errors"].map { |e| e["message"] }
        complexity = reduce_result.first
        assert_equal 0.1, complexity
      end
    end
  end

  describe "custom complexities by complexity_for(...)" do
    class CustomComplexityByMethodSchema < GraphQL::Schema
      module ComplexityInterface
        include GraphQL::Schema::Interface
        field :value, Int
      end

      class SingleComplexity < GraphQL::Schema::Object
        field :value, Int, complexity: 0.1
        field :complexity, SingleComplexity do
          argument :int_value, Int, required: false

          def complexity_for(query:, child_complexity:, lookahead:)
            lookahead.arguments[:int_value] + child_complexity
          end
        end
        implements ComplexityInterface
      end

      class ComplexityFourField < GraphQL::Schema::Field
        def complexity_for(query:, lookahead:, child_complexity:)
          4
        end
      end

      class DoubleComplexity < GraphQL::Schema::Object
        field_class ComplexityFourField
        field :value, Int
        implements ComplexityInterface
      end

      class Thing < GraphQL::Schema::Object
        field :name, String
      end

      class CustomThingConnection < GraphQL::Types::Relay::BaseConnection
        edge_type Thing.edge_type
        field :something_special, String, complexity: 3
      end

      class Query < GraphQL::Schema::Object
        field :complexity, SingleComplexity do
          argument :int_value, Int, required: false
          def complexity_for(query:, child_complexity:, lookahead:)
            lookahead.arguments[:int_value] + child_complexity
          end
        end

        field :inner_complexity, ComplexityInterface do
          argument :value, Int, required: false
        end

        field :things, Thing.connection_type, max_page_size: 100 do
          argument :count, Int, validates: { numericality: { less_than: 50 } }
        end

        def things(count:)
          count.times.map {|t| {name: t.to_s}}
        end

        class ThingsCustom < GraphQL::Schema::Resolver
          type CustomThingConnection, null: false
          complexity 100

          def resolve
            5.times { |t| { name: "Thing #{t}" } }
          end
        end

        field :things_custom, resolver: ThingsCustom
      end

      query(Query)
      orphan_types(DoubleComplexity)
      complexity_cost_calculation_mode(:future)
    end

    let(:query) { GraphQL::Query.new(complexity_schema, query_string) }
    let(:complexity_schema) { CustomComplexityByMethodSchema }
    let(:query_string) {%|
      {
        a: complexity(intValue: 3) { value }
        b: complexity(intValue: 6) {
          value
          complexity(intValue: 1) {
            value
          }
        }
      }
    |}

    it "inherits complexity_cost_calculation_mode" do
      schema = Class.new(CustomComplexityByMethodSchema)
      assert_equal CustomComplexityByMethodSchema.complexity_cost_calculation_mode, schema.complexity_cost_calculation_mode
    end

    it "sums the complexity" do
      complexity = reduce_result.first
      # 10 from `complexity`, `0.3` from `value`
      assert_equal 10.3, complexity
    end

    describe "same field on multiple types" do
      let(:query_string) {%|
      {
        innerComplexity(value: 2) {
          ... on SingleComplexity { value }
          ... on DoubleComplexity { value }
        }
      }
      |}

      it "picks them max for those fields" do
        complexity = reduce_result.first
        # 1 for innerComplexity + 4 for DoubleComplexity.value
        assert_equal 5, complexity
      end
    end

    describe "when the query fails validation" do
      let(:query_string) {%|
      {
        things(count: 200, first: 5) {
          nodes { name }
        }
      }
      |}
      it "handles the error" do
        res = GraphQL::Query.new(complexity_schema, query_string).result
        assert_equal ["count must be less than 50"], res["errors"].map { |e| e["message"] }
        assert_equal [], reduce_result, "It doesn't finish calculation"
      end
    end

    describe "when connection fields have custom complexity" do
      let(:query_string) { "{ thingsCustom(first: 2) { somethingSpecial nodes { name } } }"}

      it "uses the custom configured value" do
        complexity = reduce_result.first
        assert_equal 106, complexity
      end
    end
  end

  describe "field_complexity hook" do
    class CustomComplexityAnalyzer < GraphQL::Analysis::QueryComplexity
      def initialize(query)
        super
        @field_complexities_by_query = {}
      end

      def result
        super
        @field_complexities_by_query[@query]
      end

      private

      def field_complexity(scoped_type_complexity, max_complexity:, child_complexity:)
        @field_complexities_by_query[scoped_type_complexity.query] ||= {}
        @field_complexities_by_query[scoped_type_complexity.query][scoped_type_complexity.response_path] = {
          max_complexity: max_complexity,
          child_complexity: child_complexity,
        }
      end
    end

    let(:reduce_result) { GraphQL::Analysis.analyze_query(query, [CustomComplexityAnalyzer]) }

    let(:query_string) {%|
    {
      cheese {
        id
      }

      cheese {
        id
        flavor
      }
    }
    |}
    it "gets called for each field with complexity data" do
      field_complexities = reduce_result.first

      assert_equal({
        ['cheese', 'id'] => { max_complexity: 1, child_complexity: 0 },
        ['cheese', 'flavor'] => { max_complexity: 1, child_complexity: 0 },
        ['cheese'] => { max_complexity: 3, child_complexity: 2 },
      }, field_complexities)
    end
  end

  describe "maximum of possible scopes regardless of selection order" do
    class MaxOfPossibleScopes < GraphQL::Schema
      class Cheese < GraphQL::Schema::Object
        field :kind, String
      end

      module Producer
        include GraphQL::Schema::Interface
        field :cheese, Cheese, complexity: 5
        field :name, String, complexity: 5
      end

      class Farm < GraphQL::Schema::Object
        implements Producer
        field :cheese, Cheese, complexity: 10
        field :name, String, complexity: 10
      end

      class Entity < GraphQL::Schema::Union
        possible_types Farm
      end

      class Query < GraphQL::Schema::Object
        field :entity, Entity, fallback_value: nil
      end

      def self.resolve_type
        Farm
      end

      def self.cost(query_string_or_query)
        query = if query_string_or_query.is_a?(String)
          GraphQL::Query.new(self, query_string_or_query)
        else
          query_string_or_query
        end

        GraphQL::Analysis::AST.analyze_query(
          query,
          [GraphQL::Analysis::AST::QueryComplexity],
        ).first
      end

      query(Query)
    end

    describe "in :future mode" do
      let(:schema) { Class.new(MaxOfPossibleScopes) { complexity_cost_calculation_mode(:future) }}
      it "uses maximum of merged composite fields, regardless of selection order" do
        a = schema.cost(%|
          {
            entity {
              ...on Producer { cheese { kind } }
              ...on Farm { cheese { kind } }
            }
          }
        |)

        b = schema.cost(%|
          {
            entity {
              ...on Farm { cheese { kind } }
              ...on Producer { cheese { kind } }
            }
          }
        |)

        assert_equal 0, a - b
      end

      it "uses maximum of merged leaf fields, regardless of selection order" do
        a = schema.cost(%|
          {
            entity {
              ...on Producer { name }
              ...on Farm { name }
            }
          }
        |)

        b = schema.cost(%|
          {
            entity {
              ...on Farm { name }
              ...on Producer { name }
            }
          }
        |)

        assert_equal 0, a - b
      end
    end

    describe "in :legacy mode" do
      let(:schema) { Class.new(MaxOfPossibleScopes) { complexity_cost_calculation_mode(:legacy) }}
      it "uses the last of merged composite fields" do
        a = schema.cost(%|
          {
            entity {
              ...on Producer { cheese { kind } }
              ...on Farm { cheese { kind } }
            }
          }
        |)

        b = schema.cost(%|
          {
            entity {
              ...on Farm { cheese { kind } }
              ...on Producer { cheese { kind } }
            }
          }
        |)

        assert_equal 5, a - b
      end

      it "uses the last-occurring leaf field" do
        a = schema.cost(%|
          {
            entity {
              ...on Producer { name }
              ...on Farm { name }
            }
          }
        |)

        b = schema.cost(%|
          {
            entity {
              ...on Farm { name }
              ...on Producer { name }
            }
          }
        |)

        assert_equal 5, a - b
      end
    end

    describe "In dynamic mode with :compare" do
      let(:schema) {
        Class.new(MaxOfPossibleScopes) do
          def self.complexity_cost_calculation_mode_for(context)
            :compare
          end

          def self.legacy_complexity_cost_calculation_mismatch(query, future_cpx, legacy_cpx)
            query.context.response_extensions["complexity_warning"] = {
              "current" => legacy_cpx,
              "future" => future_cpx
            }
            1003
          end
        end
      }
      it "calls the handler and uses the returned value" do
        query = GraphQL::Query.new(schema, %|
          {
            entity {
              ...on Producer { cheese { kind } }
              ...on Farm { cheese { kind } }
            }
          }
        |)
        a = schema.cost(query)
        assert_equal 12, a
        refute query.result.to_h.key?("extensions")

        queryb = GraphQL::Query.new(schema, %|
          {
            entity {
              ...on Farm { cheese { kind } }
              ...on Producer { cheese { kind } }
            }
          }
        |)
        b = schema.cost(queryb)
        assert_equal 1003, b
        assert_equal({"complexity_warning" => {"current" => 7, "future" => 12}}, queryb.result.to_h["extensions"])
      end

      it "calls the custom handler when leaf fields don't match" do
        a = schema.cost(%|
          {
            entity {
              ...on Producer { name }
              ...on Farm { name }
            }
          }
        |)
        assert_equal 11, a

        b = schema.cost(%|
          {
            entity {
              ...on Farm { name }
              ...on Producer { name }
            }
          }
        |)
        assert_equal 1003, b
      end
    end

    describe "without a mode setting" do
      it "warns, and invalid mismatched scope types will still compute without error" do
        cost = nil

        stdout, _stderr = capture_io do
          cost = MaxOfPossibleScopes.cost(%|
            {
              entity {
                ...on Farm { cheese { kind } }
                ...on Producer { cheese: name }
              }
            }
          |)
        end

        assert_equal 12, cost

        assert_includes stdout, "GraphQL-Ruby's complexity cost system is getting some \"breaking fixes\" in a future version. See the migration notes at https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#complexity_cost_calculation_mode_for-class_method

To opt into the future behavior, configure your schema (MaxOfPossibleScopes) with:

  complexity_cost_calculation_mode(:future) # or `:legacy`, `:compare`"
      end

      it "uses legacy mode" do
        cost = nil
        assert_nil MaxOfPossibleScopes.complexity_cost_calculation_mode
        stdout, _stderr = capture_io do
          cost = MaxOfPossibleScopes.cost(%|
            {
              entity {
                ...on Farm { name }
                ...on Producer { name }
              }
            }
          |)
        end
        puts stdout

        assert_equal 6, cost

        assert_includes stdout, "GraphQL-Ruby's complexity cost system is getting some \"breaking fixes\" in a future version. See the migration notes at https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#complexity_cost_calculation_mode_for-class_method

To opt into the future behavior, configure your schema (MaxOfPossibleScopes) with:

  complexity_cost_calculation_mode(:future) # or `:legacy`, `:compare`"
      end
    end
  end
end