/
input_object_spec.rb
1147 lines (952 loc) · 36.1 KB
/
input_object_spec.rb
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
997
998
999
1000
# frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema::InputObject do
let(:input_object) { Jazz::EnsembleInput }
describe ".path" do
it "is the name" do
assert_equal "EnsembleInput", input_object.path
end
it "is used in argument paths" do
assert_equal "EnsembleInput.name", input_object.arguments["name"].path
end
end
describe "type info" do
it "has it" do
assert_equal "EnsembleInput", input_object.graphql_name
assert_equal nil, input_object.description
assert_equal 1, input_object.arguments.size
end
it "returns newly-added argument definitions" do
arg = nil
Class.new(GraphQL::Schema::InputObject) do
arg = argument(:int, Integer)
end
assert_instance_of GraphQL::Schema::Argument, arg
end
it "is the #owner of its arguments" do
argument = input_object.arguments["name"]
assert_equal input_object, argument.owner
end
it "inherits arguments" do
base_class = Class.new(GraphQL::Schema::InputObject) do
argument :arg1, String
argument :arg2, String
end
subclass = Class.new(base_class) do
argument :arg2, Integer
argument :arg3, Integer
end
ensemble_class = Class.new(subclass) do
argument :ensemble_id, GraphQL::Types::ID, required: false, loads: Jazz::Ensemble
end
assert_equal 3, subclass.arguments.size
assert_equal ["arg1", "arg2", "arg3"], subclass.arguments.keys
assert_equal ["String!", "Int!", "Int!"], subclass.arguments.values.map { |a| a.type.to_type_signature }
assert_equal ["String!", "Int!", "Int!", "ID"], ensemble_class.arguments.values.map { |a| a.type.to_type_signature }
assert_equal :ensemble, ensemble_class.arguments["ensembleId"].keyword
end
end
describe "camelizing with numbers" do
module InputObjectWithNumbers
class InputObject < GraphQL::Schema::InputObject
argument :number_arg1, Integer, required: false
argument :number_arg_2, Integer, required: false
argument :number_arg3, Integer, required: false, camelize: false
argument :number_arg_4, Integer, required: false, camelize: false
argument :numberArg5, Integer, required: false
argument :numberArg6, Integer, required: false, camelize: false
end
end
it "accepts leading underscores or _no_ underscores" do
input_obj = InputObjectWithNumbers::InputObject
assert_equal ["numberArg1", "numberArg2", "number_arg3", "number_arg_4", "numberArg5", "numberArg6"], input_obj.arguments.keys
assert_equal ["numberArg1", "numberArg2", "number_arg3", "number_arg_4", "numberArg5", "numberArg6"], input_obj.arguments.values.map(&:graphql_name)
assert_equal :number_arg1, input_obj.arguments["numberArg1"].keyword
assert_equal :number_arg_2, input_obj.arguments["numberArg2"].keyword
assert_equal :number_arg3, input_obj.arguments["number_arg3"].keyword
assert_equal :number_arg_4, input_obj.arguments["number_arg_4"].keyword
assert_equal :numberArg5, input_obj.arguments["numberArg5"].keyword
assert_equal :numberArg6, input_obj.arguments["numberArg6"].keyword
end
end
describe "prepare with camelized inputs" do
class PrepareCamelizedSchema < GraphQL::Schema
class CamelizedInput < GraphQL::Schema::InputObject
argument :inputString, String,
camelize: false,
as: :input_string,
prepare: ->(val, ctx) { val.upcase }
end
class Query < GraphQL::Schema::Object
field :input_test, String, null: false do
argument :camelized_input, CamelizedInput
end
def input_test(camelized_input:)
camelized_input[:input_string]
end
end
query(Query)
end
it "calls the prepare proc" do
res = PrepareCamelizedSchema.execute("{ inputTest(camelizedInput: { inputString: \"abc\" }) }")
assert_equal "ABC", res["data"]["inputTest"]
end
end
describe "prepare: / loads: / as:" do
module InputObjectPrepareTest
class InputObj < GraphQL::Schema::InputObject
argument :a, Integer
argument :b, Integer, as: :b2
argument :c, Integer, prepare: :prep
argument :d, Integer, prepare: :prep, as: :d2
argument :e, Integer, prepare: ->(val, ctx) { val * ctx[:multiply_by] * 2 }, as: :e2
argument :instrument_id, ID, loads: Jazz::InstrumentType
argument :danger, Integer, required: false, prepare: ->(val, ctx) { raise GraphQL::ExecutionError.new('boom!') }
def prep(val)
val * context[:multiply_by]
end
end
class Thing < GraphQL::Schema::Object
field :name, String
end
class PreparedInputObj < GraphQL::Schema::InputObject
argument :thing_id, ID, loads: Thing, prepare: ->(val, ctx) { "thing-#{val}" }
end
class ResolverPrepares < GraphQL::Schema::Resolver
argument :input_object, PreparedInputObj
argument :thing_id, ID, loads: Thing, prepare: ->(val, ctx) { "thing-#{val}" }
type [String], null: false
def resolve(thing:, input_object:)
[thing.name, input_object[:thing].name]
end
end
class Query < GraphQL::Schema::Object
field :inputs, [String], null: false do
argument :input, InputObj
end
def inputs(input:)
[input.to_kwargs.inspect, input.instrument.name]
end
field :multiple_prepares, [String] do
argument :input_object, PreparedInputObj
argument :thing_id, ID, loads: Thing, prepare: ->(val, ctx) { "thing-#{val}" }
end
def multiple_prepares(thing:, input_object:)
[thing.name, input_object[:thing].name]
end
field :resolver_prepares, resolver: ResolverPrepares
field :t, Thing
end
class Mutation < GraphQL::Schema::Object
class InstrumentInput < GraphQL::Schema::InputObject
argument :instrument_id, ID, loads: Jazz::InstrumentType
end
class TouchInstrument < GraphQL::Schema::Mutation
argument :input_obj, InstrumentInput
field :instrument_name_method, String, null: false
field :instrument_name_key, String, null: false
def resolve(input_obj:)
# Make sure both kinds of access work the same:
{
instrument_name_method: input_obj.instrument.name,
instrument_name_key: input_obj[:instrument].name,
}
end
end
class InstrumentByNameInput < GraphQL::Schema::InputObject
argument :instrument_name, ID, loads: Jazz::InstrumentType, as: :instrument
def self.load_instrument(instrument_name, context)
-> {
instruments = Jazz::Models.data["Instrument"]
instruments.find { |i| i.name == instrument_name }
}
end
end
class TouchInstrumentByName < TouchInstrument
argument :input_obj, InstrumentByNameInput
end
field :touch_instrument, mutation: TouchInstrument
field :touch_instrument_by_name, mutation: TouchInstrumentByName
class ListInstruments < GraphQL::Schema::Mutation
argument :list, [InstrumentInput]
field :resolved_list, String, null: false
def resolve(list:)
{
resolved_list: list.map(&:to_kwargs).inspect
}
end
end
field :list_instruments, mutation: ListInstruments
end
class Schema < GraphQL::Schema
query(Query)
mutation(Mutation)
lazy_resolve(Proc, :call)
def self.object_from_id(id, ctx)
-> {
if id.start_with?("thing-")
OpenStruct.new(name: id)
else
Jazz::GloballyIdentifiableType.find(id)
end
}
end
def self.resolve_type(type, obj, ctx)
type
end
orphan_types [Jazz::InstrumentType]
max_complexity 100
end
end
it "always prepares before loading" do
res = InputObjectPrepareTest::Schema.execute("{ resolverPrepares(thingId: \"abc\", inputObject: { thingId: \"def\" }) }")
assert_equal ["thing-abc", "thing-def"], res["data"]["resolverPrepares"]
res = InputObjectPrepareTest::Schema.execute("{ multiplePrepares(thingId: \"abc\", inputObject: { thingId: \"def\" }) }")
assert_equal ["thing-abc", "thing-def"], res["data"]["multiplePrepares"]
end
it "calls methods on the input object" do
query_str = <<-GRAPHQL
{ inputs(input: { a: 1, b: 2, c: 3, d: 4, e: 5, instrumentId: "Instrument/Drum Kit" }) }
GRAPHQL
res = InputObjectPrepareTest::Schema.execute(query_str, context: { multiply_by: 3 })
expected_obj = [{ a: 1, b2: 2, c: 9, d2: 12, e2: 30, instrument: Jazz::Models::Instrument.new("Drum Kit", "PERCUSSION") }.inspect, "Drum Kit"]
assert_equal expected_obj, res["data"]["inputs"]
end
it "calls load_ methods for arguments when they're present" do
query_str = <<-GRAPHQL
mutation {
touchInstrumentByName(inputObj: { instrumentName: "Flute" }) {
instrumentNameMethod
instrumentNameKey
}
}
GRAPHQL
res = InputObjectPrepareTest::Schema.execute(query_str)
assert_equal "Flute", res["data"]["touchInstrumentByName"]["instrumentNameMethod"]
assert_equal "Flute", res["data"]["touchInstrumentByName"]["instrumentNameKey"]
end
it "handles exceptions preparing variable input objects" do
query_str = <<-GRAPHQL
query($input: InputObj!){ inputs(input: $input) }
GRAPHQL
input = { "a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5, "instrumentId" => "Instrument/Drum Kit", "danger" => 1 }
res = InputObjectPrepareTest::Schema.execute(query_str, context: { multiply_by: 3 },
variables: { input: input})
assert_nil(res["data"])
assert_equal("boom!", res["errors"][0]["message"])
assert_equal([{ "line" => 1, "column" => 33 }], res["errors"][0]["locations"])
end
it "handles not-found with max complexity analyzer running" do
query_str = <<-GRAPHQL
{ inputs(input: {a: 1, b: 2, c: 3, d: 4, e: 6, instrumentId: "Instrument/Nonsense"}) }
GRAPHQL
res = InputObjectPrepareTest::Schema.execute(
query_str,
context: { multiply_by: 3 }
)
assert_equal ["No object found for `instrumentId: \"Instrument/Nonsense\"`"], res["errors"].map { |e| e["message"] }
end
it "loads input object arguments" do
query_str = <<-GRAPHQL
mutation {
touchInstrument(inputObj: { instrumentId: "Instrument/Drum Kit" }) {
instrumentNameMethod
instrumentNameKey
}
}
GRAPHQL
res = InputObjectPrepareTest::Schema.execute(query_str)
assert_equal "Drum Kit", res["data"]["touchInstrument"]["instrumentNameMethod"]
assert_equal "Drum Kit", res["data"]["touchInstrument"]["instrumentNameKey"]
end
it "loads nested input object arguments" do
query_str = <<-GRAPHQL
mutation {
listInstruments(list: [{ instrumentId: "Instrument/Drum Kit" }]) {
resolvedList
}
}
GRAPHQL
res = InputObjectPrepareTest::Schema.execute(query_str)
expected_obj = [{ instrument: Jazz::Models::Instrument.new("Drum Kit", "PERCUSSION") }].inspect
assert_equal expected_obj, res["data"]["listInstruments"]["resolvedList"]
end
end
describe "prepare (entire input object)" do
module InputObjectPrepareObjectTest
class RangeInput < GraphQL::Schema::InputObject
argument :min, Integer
argument :max, Integer, required: false
def self.authorized?(obj, arg, ctx)
if arg.end <= 100
super
else
ctx.add_error(GraphQL::ExecutionError.new("Range too big"))
false
end
end
def prepare
min..max
end
end
class SmallIntegerArgument < GraphQL::Schema::Argument
def authorized?(obj, val, ctx)
if val > 100
raise GraphQL::ExecutionError, "#{path} too big"
else
super
end
end
end
class HashInput < GraphQL::Schema::InputObject
argument_class SmallIntegerArgument
argument :k1, Integer
argument :k2, Integer
end
class HashInputResolver < GraphQL::Schema::Resolver
argument :input, HashInput, prepare: ->(val, ctx) { val.to_h }
type String, null: true
def resolve(input:)
"#{input.class}, #{input.inspect}"
end
end
class Query < GraphQL::Schema::Object
field :inputs, String do
argument :input, RangeInput
end
def inputs(input:)
input.inspect
end
field :hash_input, resolver: HashInputResolver
end
class Schema < GraphQL::Schema
query(Query)
end
end
it "calls prepare on the input object (literal)" do
query_str = <<-GRAPHQL
{ inputs(input: { min: 5, max: 10 }) }
GRAPHQL
res = InputObjectPrepareObjectTest::Schema.execute(query_str)
assert_equal "5..10", res["data"]["inputs"]
end
it "calls prepare on the input object (variable)" do
query_str = <<-GRAPHQL
query ($input: RangeInput!){ inputs(input: $input) }
GRAPHQL
res = InputObjectPrepareObjectTest::Schema.execute(query_str, variables: { input: { min: 5, max: 10 } })
assert_equal "5..10", res["data"]["inputs"]
end
it "authorizes the prepared value" do
query_str = <<-GRAPHQL
query ($input: RangeInput!){ inputs(input: $input) }
GRAPHQL
res = InputObjectPrepareObjectTest::Schema.execute(query_str, variables: { input: { min: 5, max: 101 } })
assert_nil res["data"]["inputs"]
assert_equal ["Range too big"], res["errors"].map { |e| e["message"] }
end
it "authorizes Hashes returned from prepare:" do
query_str = "{ hashInput(input: { k1: 5, k2: 12 }) }"
res = InputObjectPrepareObjectTest::Schema.execute(query_str)
assert_equal "Hash, {:k1=>5, :k2=>12}", res["data"]["hashInput"]
query_str = "{ hashInput(input: { k1: 500, k2: 12 }) }"
res = InputObjectPrepareObjectTest::Schema.execute(query_str)
assert_equal ["HashInput.k1 too big"], res["errors"].map { |e| e["message"] }
assert_nil res["data"]["hashInput"]
end
end
describe "loading application object(s)" do
module InputObjectLoadsTest
class BaseArgument < GraphQL::Schema::Argument
def authorized?(obj, val, ctx)
if contains_spinal_tap?(val)
false
else
true
end
end
def contains_spinal_tap?(val)
if val.is_a?(Array)
val.any? { |v| contains_spinal_tap?(v) }
else
val.is_a?(Jazz::Models::Ensemble) && val.name == "Spinal Tap"
end
end
end
class SingleLoadInputObj < GraphQL::Schema::InputObject
argument_class BaseArgument
argument :instrument_id, ID, loads: Jazz::InstrumentType
end
class MultiLoadInputObj < GraphQL::Schema::InputObject
argument_class BaseArgument
argument :instrument_ids, [ID], loads: Jazz::InstrumentType
end
class Query < GraphQL::Schema::Object
field :single_load_input, Jazz::InstrumentType do
argument :input, SingleLoadInputObj
end
field :multi_load_input, [Jazz::InstrumentType] do
argument :input, MultiLoadInputObj
end
def single_load_input(input:)
input.instrument
end
def multi_load_input(input:)
input.instruments
end
end
class Schema < GraphQL::Schema
query(Query)
def self.object_from_id(id, ctx)
Jazz::GloballyIdentifiableType.find(id)
end
def self.resolve_type(type, obj, ctx)
type
end
end
end
let(:single_query_str) {
<<-GRAPHQL
query($id: ID!) {
singleLoadInput(input: {instrumentId: $id}) {
id
}
}
GRAPHQL
}
let(:multi_query_str) {
<<-GRAPHQL
query($ids: [ID!]!) {
multiLoadInput(input: {instrumentIds: $ids}) {
id
}
}
GRAPHQL
}
it "loads arguments as objects of the given type and strips `_id` suffix off argument name" do
res = InputObjectLoadsTest::Schema.execute(single_query_str, variables: { id: "Ensemble/Robert Glasper Experiment" })
assert_equal "Ensemble/Robert Glasper Experiment", res["data"]["singleLoadInput"]["id"]
end
it "loads arguments as objects of the given type and strips `_ids` suffix off argument name and appends `s`" do
res = InputObjectLoadsTest::Schema.execute(multi_query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]})
assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["multiLoadInput"].map { |e| e["id"] }
end
it "authorizes based on loaded objects" do
res = InputObjectLoadsTest::Schema.execute(single_query_str, variables: { id: "Ensemble/Spinal Tap" })
assert_nil res["data"]["singleLoadInput"]
res2 = InputObjectLoadsTest::Schema.execute(multi_query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Spinal Tap"]})
assert_nil res2["data"]["multiLoadInput"]
end
end
describe "in queries" do
it "is passed to the field method" do
query_str = <<-GRAPHQL
{
inspectInput(input: {
stringValue: "ABC",
legacyInput: { intValue: 4 },
nestedInput: { stringValue: "xyz"},
ensembleId: "Ensemble/Robert Glasper Experiment"
})
}
GRAPHQL
res = Jazz::Schema.execute(query_str, context: { message: "hi" })
expected_info = [
"Jazz::InspectableInput",
"hi, ABC, 4, (hi, xyz, -, (-))",
"ABC",
"ABC",
"true",
"ABC",
Jazz::Models::Ensemble.new("Robert Glasper Experiment").to_s,
"true",
]
assert_equal expected_info, res["data"]["inspectInput"]
end
it "works with given nil values for nested inputs" do
query_str = <<-GRAPHQL
query($input: InspectableInput!){
inspectInput(input: $input)
}
GRAPHQL
input = {
"nestedInput" => nil,
"stringValue" => "xyz"
}
res = Jazz::Schema.execute(query_str, variables: { input: input }, context: { message: "hi" })
assert res["data"]["inspectInput"]
end
it "uses empty object when no variable value is given" do
query_str = <<-GRAPHQL
query($input: InspectableInput){
inspectInput(input: {
nestedInput: $input,
stringValue: "xyz"
})
}
GRAPHQL
res = Jazz::Schema.execute(query_str, variables: { input: nil }, context: { message: "hi" })
expected_info = [
"Jazz::InspectableInput",
"hi, xyz, -, (-)",
"xyz",
"xyz",
"true",
"xyz",
"No ensemble",
"false"
]
assert_equal expected_info, res["data"]["inspectInput"]
end
it "handles camelized booleans" do
res = Jazz::Schema.execute("query($input: CamelizedBooleanInput!){ inputObjectCamelization(input: $input) }", variables: { input: { camelizedBoolean: false } })
assert_equal "{:camelized_boolean=>false}", res["data"]["inputObjectCamelization"]
end
end
describe "when used with default_value" do
it "comes as an instance" do
res = Jazz::Schema.execute("{ defaultValueTest }")
assert_equal "Jazz::InspectableInput -> {:string_value=>\"S\"}", res["data"]["defaultValueTest"]
end
it "works with empty objects" do
res = Jazz::Schema.execute("{ defaultValueTest2 }")
assert_equal "Jazz::FullyOptionalInput -> {}", res["data"]["defaultValueTest2"]
end
it "introspects in GraphQL language with enums" do
class InputDefaultSchema < GraphQL::Schema
class Letter < GraphQL::Schema::Enum
value "A", value: 1
value "B", value: 2
end
class InputObj < GraphQL::Schema::InputObject
argument :arg_a, Letter, required: false
argument :arg_b, Letter, required: false
end
class Query < GraphQL::Schema::Object
field :i, Int do
argument :arg, InputObj, required: false, default_value: { arg_a: 1, arg_b: 2 }
end
end
query(Query)
end
res = InputDefaultSchema.execute "
{
__type(name: \"Query\") {
fields {
name
args {
name
defaultValue
}
}
}
}
"
assert_equal "{argA: A, argB: B}", res["data"]["__type"]["fields"].first["args"].first["defaultValue"]
end
end
describe "#dig" do
module InputObjectDigTest
class TestInput1 < GraphQL::Schema::InputObject
graphql_name "TestInput1"
argument :d, Int
argument :e, Int
end
class TestInput2 < GraphQL::Schema::InputObject
graphql_name "TestInput2"
argument :a, Int
argument :b, Int
argument :c, TestInput1, as: :inputObject
end
end
arg_values = {
a: 1,
b: 2,
inputObject: InputObjectDigTest::TestInput1.new(nil, ruby_kwargs: { d: 3, e: 4 }, context: nil, defaults_used: Set.new)
}
input_object = InputObjectDigTest::TestInput2.new(
nil,
ruby_kwargs: arg_values,
context: nil,
defaults_used: Set.new
)
it "returns the value at that key" do
assert_equal 1, input_object.dig(:a)
assert input_object.dig(:inputObject).is_a?(GraphQL::Schema::InputObject)
end
it "works with nested keys" do
assert_equal 3, input_object.dig(:inputObject, :d)
end
it "returns nil for missing keys" do
assert_nil input_object.dig("z")
assert_nil input_object.dig(7)
end
end
describe "introspection" do
it "returns input fields" do
res = Jazz::Schema.execute('
{
__type(name: "InspectableInput") {
name
inputFields { name }
}
__schema {
types {
name
inputFields { name }
}
}
}')
# Test __type
assert_equal ["ensembleId", "stringValue", "nestedInput", "legacyInput"], res["data"]["__type"]["inputFields"].map { |f| f["name"] }
# Test __schema { types }
# It's upcased to test custom introspection
input_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "INSPECTABLEINPUT" }
assert_equal ["ensembleId", "stringValue", "nestedInput", "legacyInput"], input_type["inputFields"].map { |f| f["name"] }
end
end
describe "nested objects inside lists" do
class NestedInputObjectSchema < GraphQL::Schema
class ItemInput < GraphQL::Schema::InputObject
argument :str, String
end
class NestedStuff < GraphQL::Schema::RelayClassicMutation
argument :items, [ItemInput]
field :str, String, null: false
def resolve(items:)
{
str: items.map { |i| i.class.name }.join(", ")
}
end
end
class Mutation < GraphQL::Schema::Object
field :nested_stuff, mutation: NestedStuff
end
mutation(Mutation)
end
it "properly wraps them in instances" do
res = NestedInputObjectSchema.execute "
mutation($input: NestedStuffInput!) {
nestedStuff(input: $input) {
str
}
}
", variables: { input: { "items" => [{ "str" => "1"}, { "str" => "2"}]}}
assert_equal "NestedInputObjectSchema::ItemInput, NestedInputObjectSchema::ItemInput", res["data"]["nestedStuff"]["str"]
end
end
describe 'default values' do
describe 'when the type is an enum with underlying ruby values' do
it 'provides the default value' do
class TestEnum < GraphQL::Schema::Enum
value 'A', 'Represents an authorized agent in our system.', value: 'a'
value 'B', 'Agent is disabled, web app access is denied.', value: 'b'
end
class TestInput < GraphQL::Schema::InputObject
argument :foo, TestEnum, 'TestEnum', required: false, default_value: 'a'
end
test_input_type = TestInput
default_test_input_value = test_input_type.coerce_isolated_input({})
assert_equal default_test_input_value[:foo], 'a'
end
end
describe "when it's an empty object" do
it "is passed in" do
input_obj = Class.new(GraphQL::Schema::InputObject) do
graphql_name "InputObj"
argument :s, String, required: false
end
query = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
field :f, String do
argument :arg, input_obj, required: false, default_value: {}
end
def f(arg:)
arg.to_h.inspect
end
end
schema = Class.new(GraphQL::Schema) do
query(query)
end
res = schema.execute("{ f } ")
assert_equal "{}", res["data"]["f"]
end
end
end
describe "tests from legacy input_object_type" do
let(:input_object) { Dummy::DairyProductInput }
def validate_isolated_input(t, input)
t.validate_input(input, GraphQL::Query::NullContext)
end
describe "input validation" do
it "Accepts anything that yields key-value pairs to #all?" do
values_obj = MinimumInputObject.new({"source" => "COW", "fatContent" => 0.4})
assert input_object.valid_isolated_input?(values_obj)
end
describe "validate_input with non-enumerable input" do
it "returns a valid result for MinimumInputObject" do
result = validate_isolated_input(input_object, MinimumInputObject.new({"source" => "COW", "fatContent" => 0.4}))
assert(result.valid?)
end
it "returns an invalid result for MinimumInvalidInputObject" do
invalid_input = MinimumInputObject.new({"source" => "KOALA", "fatContent" => 0.4})
result = validate_isolated_input(input_object, invalid_input)
assert(!result.valid?)
end
end
describe "validate_input with null" do
let(:schema) { GraphQL::Schema.from_definition(%|
type Query {
a: Int
}
input ExampleInputObject {
a: String
b: Int!
}
|) }
let(:input_type) { schema.types['ExampleInputObject'] }
it "returns an invalid result when value is null for non-null argument" do
invalid_input = MinimumInputObject.new({"a" => "Test", "b" => nil})
result = validate_isolated_input(input_type, invalid_input)
assert(!result.valid?)
end
it "returns valid result when value is null for nullable argument" do
invalid_input = MinimumInputObject.new({"a" => nil, "b" => 1})
result = validate_isolated_input(input_type, invalid_input)
assert(result.valid?)
end
end
describe "validate_input with enumerable input" do
describe "with good input" do
it "returns a valid result" do
input = {
"source" => "COW",
"fatContent" => 0.4
}
result = validate_isolated_input(input_object, input)
assert(result.valid?)
end
end
if testing_rails? && ActionPack::VERSION::MAJOR > 3
it "returns a valid result" do
input = ActionController::Parameters.new(
"source" => "COW",
"fatContent" => 0.4,
)
result = validate_isolated_input(input_object, input)
assert_nil result.problems
assert(result.valid?)
end
end
describe "with bad enum and float" do
let(:result) { validate_isolated_input(input_object, {"source" => "KOALA", "fatContent" => "bad_num"}) }
it "returns an invalid result" do
assert(!result.valid?)
end
it "has problems with correct paths" do
paths = result.problems.map { |p| p["path"] }
assert(paths.include?(["source"]))
assert(paths.include?(["fatContent"]))
end
it "has correct problem explanation" do
expected = validate_isolated_input(Dummy::DairyAnimal, "KOALA").problems[0]["explanation"]
source_problem = result.problems.detect { |p| p["path"] == ["source"] }
actual = source_problem["explanation"]
assert_equal(expected, actual)
end
end
describe 'with a string as input' do
let(:result) { validate_isolated_input(input_object, "just a string") }
it "returns an invalid result" do
assert(!result.valid?)
end
it "has problem with correct path" do
paths = result.problems.map { |p| p["path"] }
assert(paths.include?([]))
end
it "has correct problem explanation" do
assert_includes result.problems[0]["explanation"], "to be a key-value object"
end
end
describe 'with an array as input' do
let(:result) { validate_isolated_input(input_object, ["string array"]) }
it "returns an invalid result" do
assert(!result.valid?)
end
it "has problem with correct path" do
paths = result.problems.map { |p| p["path"] }
assert(paths.include?([]))
end
it "has correct problem explanation" do
assert_includes result.problems[0]["explanation"], "to be a key-value object"
end
end
describe 'with a int as input' do
let(:result) { validate_isolated_input(input_object, 10) }
it "returns an invalid result" do
assert(!result.valid?)
end
it "has problem with correct path" do
paths = result.problems.map { |p| p["path"] }
assert(paths.include?([]))
end
it "has correct problem explanation" do
assert_includes result.problems[0]["explanation"], "to be a key-value object"
end
end
describe "with extra argument" do
let(:result) { validate_isolated_input(input_object, {"source" => "COW", "fatContent" => 0.4, "isDelicious" => false}) }
it "returns an invalid result" do
assert(!result.valid?)
end
it "has problem with correct path" do
paths = result.problems.map { |p| p["path"] }
assert_equal([["isDelicious"]], paths)
end
it "has correct problem explanation" do
assert(result.problems[0]["explanation"].include?("Field is not defined"))
end
end
describe "list with one invalid element" do
let(:list_type) { Dummy::DairyProductInput.to_list_type }
let(:result) do
validate_isolated_input(list_type, [
{ "source" => "COW", "fatContent" => 0.4 },
{ "source" => "KOALA", "fatContent" => 0.4 }
])
end
it "returns an invalid result" do
assert(!result.valid?)
end
it "has one problem" do
assert_equal(result.problems.length, 1)
end
it "has problem with correct path" do
path = result.problems[0]["path"]
assert_equal(path, [1, "source"])
end
it "has problem with correct explanation" do
expected = validate_isolated_input(Dummy::DairyAnimal, "KOALA").problems[0]["explanation"]
actual = result.problems[0]["explanation"]
assert_equal(expected, actual)
end
end