File: coerce_spec.rb

package info (click to toggle)
ruby-grape 1.6.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,156 kB
  • sloc: ruby: 25,265; makefile: 7
file content (1263 lines) | stat: -rw-r--r-- 39,657 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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
# frozen_string_literal: true

require 'spec_helper'

describe Grape::Validations::Validators::CoerceValidator do
  subject do
    Class.new(Grape::API)
  end

  def app
    subject
  end

  describe 'coerce' do
    class SecureURIOnly
      def self.parse(value)
        URI.parse(value)
      end

      def self.parsed?(value)
        value.is_a? URI::HTTPS
      end
    end

    context 'i18n' do
      after do
        I18n.available_locales = %i[en]
        I18n.locale = :en
        I18n.default_locale = :en
      end

      it 'i18n error on malformed input' do
        I18n.available_locales = %i[en zh-CN]
        I18n.load_path << File.expand_path('zh-CN.yml', __dir__)
        I18n.reload!
        I18n.locale = :'zh-CN'
        subject.params do
          requires :age, type: Integer
        end
        subject.get '/single' do
          'int works'
        end

        get '/single', age: '43a'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('年龄格式不正确')
      end

      it 'gives an english fallback error when default locale message is blank' do
        I18n.available_locales = %i[en pt-BR]
        I18n.locale = :'pt-BR'
        subject.params do
          requires :age, type: Integer
        end
        subject.get '/single' do
          'int works'
        end

        get '/single', age: '43a'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('age is invalid')
      end
    end

    context 'with a custom validation message' do
      it 'errors on malformed input' do
        subject.params do
          requires :int, type: { value: Integer, message: 'type cast is invalid' }
        end
        subject.get '/single' do
          'int works'
        end

        get '/single', int: '43a'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('int type cast is invalid')

        get '/single', int: '43'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('int works')
      end

      context 'on custom coercion rules' do
        before do
          subject.params do
            requires :a, types: { value: [Grape::API::Boolean, String], message: 'type cast is invalid' }, coerce_with: (lambda do |val|
              case val
              when 'yup'
                true
              when 'false'
                0
              else
                val
              end
            end)
          end
          subject.get '/' do
            params[:a].class.to_s
          end
        end

        it 'respects :coerce_with' do
          get '/', a: 'yup'

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('TrueClass')
        end

        it 'still validates type' do
          get '/', a: 'false'
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('a type cast is invalid')
        end

        it 'performs no additional coercion' do
          get '/', a: 'true'
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('String')
        end
      end
    end

    it 'error on malformed input' do
      subject.params do
        requires :int, type: Integer
      end
      subject.get '/single' do
        'int works'
      end

      get '/single', int: '43a'
      expect(last_response.status).to eq(400)
      expect(last_response.body).to eq('int is invalid')

      get '/single', int: '43'
      expect(last_response.status).to eq(200)
      expect(last_response.body).to eq('int works')
    end

    it 'error on malformed input (Array)' do
      subject.params do
        requires :ids, type: Array[Integer]
      end
      subject.get '/array' do
        'array int works'
      end

      get 'array', ids: %w[1 2 az]
      expect(last_response.status).to eq(400)
      expect(last_response.body).to eq('ids is invalid')

      get 'array', ids: %w[1 2 890]
      expect(last_response.status).to eq(200)
      expect(last_response.body).to eq('array int works')
    end

    context 'coerces' do
      context 'json' do
        let(:headers) { { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } }

        it 'BigDecimal' do
          subject.params do
            requires :bigdecimal, type: BigDecimal
          end
          subject.post '/bigdecimal' do
            "#{params[:bigdecimal].class} #{params[:bigdecimal].to_f}"
          end

          post '/bigdecimal', { bigdecimal: 45.1 }.to_json, headers
          expect(last_response.status).to eq(201)
          expect(last_response.body).to eq('BigDecimal 45.1')
        end

        it 'Grape::API::Boolean' do
          subject.params do
            requires :boolean, type: Grape::API::Boolean
          end
          subject.post '/boolean' do
            params[:boolean]
          end

          post '/boolean', { boolean: 'true' }.to_json, headers
          expect(last_response.status).to eq(201)
          expect(last_response.body).to eq('true')
        end
      end

      it 'BigDecimal' do
        subject.params do
          requires :bigdecimal, coerce: BigDecimal
        end
        subject.get '/bigdecimal' do
          params[:bigdecimal].class
        end

        get '/bigdecimal', bigdecimal: '45'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('BigDecimal')
      end

      it 'Integer' do
        subject.params do
          requires :int, coerce: Integer
        end
        subject.get '/int' do
          params[:int].class
        end

        get '/int', int: '45'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq(integer_class_name)
      end

      it 'String' do
        subject.params do
          requires :string, coerce: String
        end
        subject.get '/string' do
          params[:string].class
        end

        get '/string', string: 45
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('String')

        get '/string', string: nil
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('NilClass')
      end

      context 'a custom type' do
        it 'coerces the given value' do
          subject.params do
            requires :uri, coerce: SecureURIOnly
          end
          subject.get '/secure_uri' do
            params[:uri].class
          end

          get 'secure_uri', uri: 'https://www.example.com'

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('URI::HTTPS')

          get 'secure_uri', uri: 'http://www.example.com'

          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('uri is invalid')
        end

        context 'returning the InvalidValue instance when invalid' do
          let(:custom_type) do
            Class.new do
              def self.parse(_val)
                Grape::Types::InvalidValue.new('must be unique')
              end
            end
          end

          it 'uses a custom message added to the invalid value' do
            type = custom_type

            subject.params do
              requires :name, type: type
            end
            subject.get '/whatever' do
              params[:name].class
            end

            get 'whatever', name: 'Bob'

            expect(last_response.status).to eq(400)
            expect(last_response.body).to eq('name must be unique')
          end
        end
      end

      context 'Array' do
        it 'Array of Integers' do
          subject.params do
            requires :arry, coerce: Array[Integer]
          end
          subject.get '/array' do
            params[:arry][0].class
          end

          get '/array', arry: %w[1 2 3]
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq(integer_class_name)
        end

        it 'Array of Bools' do
          subject.params do
            requires :arry, coerce: Array[Grape::API::Boolean]
          end
          subject.get '/array' do
            params[:arry][0].class
          end

          get 'array', arry: [1, 0]
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('TrueClass')
        end

        it 'Array of type implementing parse' do
          subject.params do
            requires :uri, type: Array[URI]
          end
          subject.get '/uri_array' do
            params[:uri][0].class
          end
          get 'uri_array', uri: ['http://www.google.com']
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('URI::HTTP')
        end

        it 'Set of type implementing parse' do
          subject.params do
            requires :uri, type: Set[URI]
          end
          subject.get '/uri_array' do
            "#{params[:uri].class},#{params[:uri].first.class},#{params[:uri].size}"
          end
          get 'uri_array', uri: Array.new(2) { 'http://www.example.com' }
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('Set,URI::HTTP,1')
        end

        it 'Array of a custom type' do
          subject.params do
            requires :uri, type: Array[SecureURIOnly]
          end
          subject.get '/secure_uris' do
            params[:uri].first.class
          end
          get 'secure_uris', uri: ['https://www.example.com']
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('URI::HTTPS')
          get 'secure_uris', uri: ['https://www.example.com', 'http://www.example.com']
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('uri is invalid')
        end
      end

      context 'Set' do
        it 'Set of Integers' do
          subject.params do
            requires :set, coerce: Set[Integer]
          end
          subject.get '/set' do
            params[:set].first.class
          end

          get '/set', set: Set.new([1, 2, 3, 4]).to_a
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq(integer_class_name)
        end

        it 'Set of Bools' do
          subject.params do
            requires :set, coerce: Set[Grape::API::Boolean]
          end
          subject.get '/set' do
            params[:set].first.class
          end

          get '/set', set: Set.new([1, 0]).to_a
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('TrueClass')
        end
      end

      it 'Grape::API::Boolean' do
        subject.params do
          requires :boolean, type: Grape::API::Boolean
        end
        subject.get '/boolean' do
          params[:boolean].class
        end

        get '/boolean', boolean: 1
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('TrueClass')
      end

      context 'File' do
        let(:file) { Rack::Test::UploadedFile.new(__FILE__) }
        let(:filename) { File.basename(__FILE__).to_s }

        it 'Rack::Multipart::UploadedFile' do
          subject.params do
            requires :file, type: Rack::Multipart::UploadedFile
          end
          subject.post '/upload' do
            params[:file][:filename]
          end

          post '/upload', file: file
          expect(last_response.status).to eq(201)
          expect(last_response.body).to eq(filename)

          post '/upload', file: 'not a file'
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('file is invalid')
        end

        it 'File' do
          subject.params do
            requires :file, coerce: File
          end
          subject.post '/upload' do
            params[:file][:filename]
          end

          post '/upload', file: file
          expect(last_response.status).to eq(201)
          expect(last_response.body).to eq(filename)

          post '/upload', file: 'not a file'
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('file is invalid')

          post '/upload', file: { filename: 'fake file', tempfile: '/etc/passwd' }
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('file is invalid')
        end

        it 'collection' do
          subject.params do
            requires :files, type: Array[File]
          end
          subject.post '/upload' do
            params[:files].first[:filename]
          end

          post '/upload', files: [file]
          expect(last_response.status).to eq(201)
          expect(last_response.body).to eq(filename)
        end
      end

      it 'Nests integers' do
        subject.params do
          requires :integers, type: Hash do
            requires :int, coerce: Integer
          end
        end
        subject.get '/int' do
          params[:integers][:int].class
        end

        get '/int', integers: { int: '45' }
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq(integer_class_name)
      end

      context 'nil values' do
        context 'primitive types' do
          Grape::Validations::Types::PRIMITIVES.each do |type|
            it 'respects the nil value' do
              subject.params do
                requires :param, type: type
              end
              subject.get '/nil_value' do
                params[:param].class
              end

              get '/nil_value', param: nil
              expect(last_response.status).to eq(200)
              expect(last_response.body).to eq('NilClass')
            end
          end
        end

        context 'structures types' do
          Grape::Validations::Types::STRUCTURES.each do |type|
            it 'respects the nil value' do
              subject.params do
                requires :param, type: type
              end
              subject.get '/nil_value' do
                params[:param].class
              end

              get '/nil_value', param: nil
              expect(last_response.status).to eq(200)
              expect(last_response.body).to eq('NilClass')
            end
          end
        end

        context 'special types' do
          Grape::Validations::Types::SPECIAL.each_key do |type|
            it 'respects the nil value' do
              subject.params do
                requires :param, type: type
              end
              subject.get '/nil_value' do
                params[:param].class
              end

              get '/nil_value', param: nil
              expect(last_response.status).to eq(200)
              expect(last_response.body).to eq('NilClass')
            end
          end

          context 'variant-member-type collections' do
            [
              Array[Integer, String],
              [Integer, String, Array[Integer, String]]
            ].each do |type|
              it 'respects the nil value' do
                subject.params do
                  requires :param, type: type
                end
                subject.get '/nil_value' do
                  params[:param].class
                end

                get '/nil_value', param: nil
                expect(last_response.status).to eq(200)
                expect(last_response.body).to eq('NilClass')
              end
            end
          end
        end
      end

      context 'empty string' do
        context 'primitive types' do
          (Grape::Validations::Types::PRIMITIVES - [String]).each do |type|
            it "is coerced to nil for type #{type}" do
              subject.params do
                requires :param, type: type
              end
              subject.get '/empty_string' do
                params[:param].class
              end

              get '/empty_string', param: ''
              expect(last_response.status).to eq(200)
              expect(last_response.body).to eq('NilClass')
            end
          end

          it 'is not coerced to nil for type String' do
            subject.params do
              requires :param, type: String
            end
            subject.get '/empty_string' do
              params[:param].class
            end

            get '/empty_string', param: ''
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('String')
          end
        end

        context 'structures types' do
          (Grape::Validations::Types::STRUCTURES - [Hash]).each do |type|
            it "is coerced to nil for type #{type}" do
              subject.params do
                requires :param, type: type
              end
              subject.get '/empty_string' do
                params[:param].class
              end

              get '/empty_string', param: ''
              expect(last_response.status).to eq(200)
              expect(last_response.body).to eq('NilClass')
            end
          end
        end

        context 'special types' do
          (Grape::Validations::Types::SPECIAL.keys - [File, Rack::Multipart::UploadedFile]).each do |type|
            it "is coerced to nil for type #{type}" do
              subject.params do
                requires :param, type: type
              end
              subject.get '/empty_string' do
                params[:param].class
              end

              get '/empty_string', param: ''
              expect(last_response.status).to eq(200)
              expect(last_response.body).to eq('NilClass')
            end
          end

          context 'variant-member-type collections' do
            [
              Array[Integer, String],
              [Integer, String, Array[Integer, String]]
            ].each do |type|
              it "is coerced to nil for type #{type}" do
                subject.params do
                  requires :param, type: type
                end
                subject.get '/empty_string' do
                  params[:param].class
                end

                get '/empty_string', param: ''
                expect(last_response.status).to eq(200)
                expect(last_response.body).to eq('NilClass')
              end
            end
          end
        end
      end
    end

    context 'using coerce_with' do
      it 'parses parameters with Array type' do
        subject.params do
          requires :values, type: Array, coerce_with: ->(val) { val.split(/\s+/).map(&:to_i) }
        end
        subject.get '/ints' do
          params[:values]
        end

        get '/ints', values: '1 2 3 4'
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq([1, 2, 3, 4])

        get '/ints', values: 'a b c d'
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq([0, 0, 0, 0])
      end

      it 'parses parameters with Array[String] type' do
        subject.params do
          requires :values, type: Array[String], coerce_with: ->(val) { val.split(/\s+/) }
        end
        subject.get '/strings' do
          params[:values]
        end

        get '/strings', values: '1 2 3 4'
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq(%w[1 2 3 4])

        get '/strings', values: 'a b c d'
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq(%w[a b c d])
      end

      it 'parses parameters with Array[Array[String]] type and coerce_with' do
        subject.params do
          requires :values, type: Array[Array[String]], coerce_with: ->(val) { val.is_a?(String) ? [val.split(',').map(&:strip)] : val }
        end
        subject.post '/coerce_nested_strings' do
          params[:values]
        end

        post '/coerce_nested_strings', ::Grape::Json.dump(values: 'a,b,c,d'), 'CONTENT_TYPE' => 'application/json'
        expect(last_response.status).to eq(201)
        expect(JSON.parse(last_response.body)).to eq([%w[a b c d]])

        post '/coerce_nested_strings', ::Grape::Json.dump(values: [%w[a c], %w[b]]), 'CONTENT_TYPE' => 'application/json'
        expect(last_response.status).to eq(201)
        expect(JSON.parse(last_response.body)).to eq([%w[a c], %w[b]])

        post '/coerce_nested_strings', ::Grape::Json.dump(values: [[]]), 'CONTENT_TYPE' => 'application/json'
        expect(last_response.status).to eq(201)
        expect(JSON.parse(last_response.body)).to eq([[]])

        post '/coerce_nested_strings', ::Grape::Json.dump(values: [['a', { bar: 0 }], ['b']]), 'CONTENT_TYPE' => 'application/json'
        expect(last_response.status).to eq(400)
      end

      it 'parses parameters with Array[Integer] type' do
        subject.params do
          requires :values, type: Array[Integer], coerce_with: ->(val) { val.split(/\s+/).map(&:to_i) }
        end
        subject.get '/ints' do
          params[:values]
        end

        get '/ints', values: '1 2 3 4'
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq([1, 2, 3, 4])

        get '/ints', values: 'a b c d'
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq([0, 0, 0, 0])
      end

      it 'parses parameters even if type is valid' do
        subject.params do
          requires :values, type: Array, coerce_with: ->(array) { array.map { |val| val.to_i + 1 } }
        end
        subject.get '/ints' do
          params[:values]
        end

        get '/ints', values: [1, 2, 3, 4]
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq([2, 3, 4, 5])

        get '/ints', values: %w[a b c d]
        expect(last_response.status).to eq(200)
        expect(JSON.parse(last_response.body)).to eq([1, 1, 1, 1])
      end

      context 'Array type and coerce_with should' do
        before do
          subject.params do
            optional :arr, type: Array, coerce_with: (lambda do |val|
              if val.nil?
                []
              else
                val
              end
            end)
          end
          subject.get '/' do
            params[:arr].class.to_s
          end
        end

        it 'coerce nil value to array' do
          get '/', arr: nil

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('Array')
        end

        it 'not coerce missing field' do
          get '/'

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('NilClass')
        end

        it 'coerce array as array' do
          get '/', arr: []

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('Array')
        end
      end

      it 'uses parse where available' do
        subject.params do
          requires :ints, type: Array, coerce_with: JSON do
            requires :i, type: Integer
            requires :j
          end
        end
        subject.get '/ints' do
          ints = params[:ints].first
          'coercion works' if ints[:i] == 1 && ints[:j] == '2'
        end

        get '/ints', ints: [{ i: 1, j: '2' }]
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('ints is invalid')

        get '/ints', ints: '{"i":1,"j":"2"}'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('ints is invalid')

        get '/ints', ints: '[{"i":"1","j":"2"}]'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('coercion works')
      end

      it 'accepts any callable' do
        subject.params do
          requires :ints, type: Hash, coerce_with: JSON.method(:parse) do
            requires :int, type: Integer, coerce_with: ->(val) { val == 'three' ? 3 : val }
          end
        end
        subject.get '/ints' do
          params[:ints][:int]
        end

        get '/ints', ints: '{"int":"3"}'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('ints[int] is invalid')

        get '/ints', ints: '{"int":"three"}'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('3')

        get '/ints', ints: '{"int":3}'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('3')
      end

      context 'Integer type and coerce_with should' do
        before do
          subject.params do
            optional :int, type: Integer, coerce_with: (lambda do |val|
              if val.nil?
                0
              else
                val.to_i
              end
            end)
          end
          subject.get '/' do
            params[:int].class.to_s
          end
        end

        it 'coerce nil value to integer' do
          get '/', int: nil

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('Integer')
        end

        it 'not coerce missing field' do
          get '/'

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('NilClass')
        end

        it 'coerce integer as integer' do
          get '/', int: 1

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('Integer')
        end
      end

      context 'Integer type and coerce_with potentially returning nil' do
        before do
          subject.params do
            requires :int, type: Integer, coerce_with: (lambda do |val|
              case val
              when '0'
                nil
              when /^-?\d+$/
                val.to_i
              else
                val
              end
            end)
          end
          subject.get '/' do
            params[:int].class.to_s
          end
        end

        it 'accepts value that coerces to nil' do
          get '/', int: '0'

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('NilClass')
        end

        it 'coerces to Integer' do
          get '/', int: '1'

          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('Integer')
        end

        it 'returns invalid value if coercion returns a wrong type' do
          get '/', int: 'lol'

          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('int is invalid')
        end
      end

      it 'must be supplied with :type or :coerce' do
        expect do
          subject.params do
            requires :ints, coerce_with: JSON
          end
        end.to raise_error(ArgumentError)
      end
    end

    context 'first-class JSON' do
      it 'parses objects, hashes, and arrays' do
        subject.params do
          requires :splines, type: JSON do
            requires :x, type: Integer, values: [1, 2, 3]
            optional :ints, type: Array[Integer]
            optional :obj, type: Hash do
              optional :y
            end
          end
        end
        subject.get '/' do
          if params[:splines].is_a? Hash
            params[:splines][:obj][:y]
          elsif params[:splines].any? { |s| s.key? :obj }
            'arrays work'
          end
        end

        get '/', splines: '{"x":1,"ints":[1,2,3],"obj":{"y":"woof"}}'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('woof')

        get '/', splines: { x: 1, ints: [1, 2, 3], obj: { y: 'woof' } }
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('woof')

        get '/', splines: '[{"x":2,"ints":[]},{"x":3,"ints":[4],"obj":{"y":"quack"}}]'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('arrays work')

        get '/', splines: [{ x: 2, ints: [5] }, { x: 3, ints: [4], obj: { y: 'quack' } }]
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('arrays work')

        get '/', splines: '{"x":4,"ints":[2]}'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')

        get '/', splines: { x: 4, ints: [2] }
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')

        get '/', splines: '[{"x":1,"ints":[]},{"x":4,"ints":[]}]'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')

        get '/', splines: [{ x: 1, ints: [5] }, { x: 4, ints: [6] }]
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')
      end

      it 'works when declared optional' do
        subject.params do
          optional :splines, type: JSON do
            requires :x, type: Integer, values: [1, 2, 3]
            optional :ints, type: Array[Integer]
            optional :obj, type: Hash do
              optional :y
            end
          end
        end
        subject.get '/' do
          if params[:splines].is_a? Hash
            params[:splines][:obj][:y]
          elsif params[:splines].any? { |s| s.key? :obj }
            'arrays work'
          end
        end

        get '/', splines: '{"x":1,"ints":[1,2,3],"obj":{"y":"woof"}}'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('woof')

        get '/', splines: '[{"x":2,"ints":[]},{"x":3,"ints":[4],"obj":{"y":"quack"}}]'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('arrays work')

        get '/', splines: '{"x":4,"ints":[2]}'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')

        get '/', splines: '[{"x":1,"ints":[]},{"x":4,"ints":[]}]'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')
      end

      it 'accepts Array[JSON] shorthand' do
        subject.params do
          requires :splines, type: Array[JSON] do
            requires :x, type: Integer, values: [1, 2, 3]
            requires :y
          end
        end
        subject.get '/' do
          params[:splines].first[:y].class.to_s
          spline = params[:splines].first
          "#{spline[:x].class}.#{spline[:y].class}"
        end

        get '/', splines: '{"x":"1","y":"woof"}'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq("#{integer_class_name}.String")

        get '/', splines: '[{"x":1,"y":2},{"x":1,"y":"quack"}]'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq("#{integer_class_name}.#{integer_class_name}")

        get '/', splines: '{"x":"4","y":"woof"}'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')

        get '/', splines: '[{"x":"4","y":"woof"}]'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('splines[x] does not have a valid value')
      end

      it "doesn't make sense using coerce_with" do
        expect do
          subject.params do
            requires :bad, type: JSON, coerce_with: JSON do
              requires :x
            end
          end
        end.to raise_error(ArgumentError)

        expect do
          subject.params do
            requires :bad, type: Array[JSON], coerce_with: JSON do
              requires :x
            end
          end
        end.to raise_error(ArgumentError)
      end
    end

    context 'multiple types' do
      it 'coerces to first possible type' do
        subject.params do
          requires :a, types: [Grape::API::Boolean, Integer, String]
        end
        subject.get '/' do
          params[:a].class.to_s
        end

        get '/', a: 'true'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('TrueClass')

        get '/', a: '5'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq(integer_class_name)

        get '/', a: 'anything else'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('String')
      end

      it 'fails when no coercion is possible' do
        subject.params do
          requires :a, types: [Grape::API::Boolean, Integer]
        end
        subject.get '/' do
          params[:a].class.to_s
        end

        get '/', a: true
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('TrueClass')

        get '/', a: 'not good'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('a is invalid')
      end

      context 'for primitive collections' do
        before do
          subject.params do
            optional :a, types: [String, Array[String]]
            optional :b, types: [Array[Integer], Array[String]]
            optional :c, type: Array[Integer, String]
            optional :d, types: [Integer, String, Set[Integer, String]]
          end
          subject.get '/' do
            (
              params[:a] ||
              params[:b] ||
              params[:c] ||
              params[:d]
            ).inspect
          end
        end

        it 'allows singular form declaration' do
          get '/', a: 'one way'
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('"one way"')

          get '/', a: %w[the other]
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('["the", "other"]')

          get '/', a: { a: 1, b: 2 }
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('a is invalid')

          get '/', a: [1, 2, 3]
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('["1", "2", "3"]')
        end

        it 'allows multiple collection types' do
          get '/', b: [1, 2, 3]
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('[1, 2, 3]')

          get '/', b: %w[1 2 3]
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('[1, 2, 3]')

          get '/', b: [1, true, 'three']
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('["1", "true", "three"]')
        end

        it 'allows collections with multiple types' do
          get '/', c: [1, '2', true, 'three']
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('[1, 2, "true", "three"]')

          get '/', d: '1'
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('1')

          get '/', d: 'one'
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('"one"')

          get '/', d: %w[1 two]
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('#<Set: {1, "two"}>')
        end
      end

      context 'when params is Hashie::Mash' do
        context 'for primitive collections' do
          before do
            subject.params do
              build_with Grape::Extensions::Hashie::Mash::ParamBuilder
              optional :a, types: [String, Array[String]]
              optional :b, types: [Array[Integer], Array[String]]
              optional :c, type: Array[Integer, String]
              optional :d, types: [Integer, String, Set[Integer, String]]
            end
            subject.get '/' do
              (
                params.a ||
                params.b ||
                params.c ||
                params.d
              ).inspect
            end
          end

          it 'allows singular form declaration' do
            get '/', a: 'one way'
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('"one way"')

            get '/', a: %w[the other]
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('#<Hashie::Array ["the", "other"]>')

            get '/', a: { a: 1, b: 2 }
            expect(last_response.status).to eq(400)
            expect(last_response.body).to eq('a is invalid')

            get '/', a: [1, 2, 3]
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('#<Hashie::Array ["1", "2", "3"]>')
          end

          it 'allows multiple collection types' do
            get '/', b: [1, 2, 3]
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('#<Hashie::Array [1, 2, 3]>')

            get '/', b: %w[1 2 3]
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('#<Hashie::Array [1, 2, 3]>')

            get '/', b: [1, true, 'three']
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('#<Hashie::Array ["1", "true", "three"]>')
          end

          it 'allows collections with multiple types' do
            get '/', c: [1, '2', true, 'three']
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('#<Hashie::Array [1, 2, "true", "three"]>')

            get '/', d: '1'
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('1')

            get '/', d: 'one'
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('"one"')

            get '/', d: %w[1 two]
            expect(last_response.status).to eq(200)
            expect(last_response.body).to eq('#<Set: {1, "two"}>')
          end
        end
      end

      context 'custom coercion rules' do
        before do
          subject.params do
            requires :a, types: [Grape::API::Boolean, String], coerce_with: (lambda do |val|
              case val
              when 'yup'
                true
              when 'false'
                0
              else
                val
              end
            end)
          end
          subject.get '/' do
            params[:a].class.to_s
          end
        end

        it 'respects :coerce_with' do
          get '/', a: 'yup'
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('TrueClass')
        end

        it 'still validates type' do
          get '/', a: 'false'
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eq('a is invalid')
        end

        it 'performs no additional coercion' do
          get '/', a: 'true'
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eq('String')
        end
      end

      it 'may not be supplied together with a single type' do
        expect do
          subject.params do
            requires :a, type: Integer, types: [Integer, String]
          end
        end.to raise_exception ArgumentError
      end
    end

    context 'converter' do
      it 'does not build a coercer multiple times' do
        subject.params do
          requires :something, type: Array[String]
        end
        subject.get do
        end

        expect(Grape::Validations::Types::ArrayCoercer).to(
          receive(:new).at_most(:once).and_call_original
        )

        10.times { get '/' }
      end
    end
  end
end