forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestJSONSerialization.swift
1557 lines (1338 loc) · 66.6 KB
/
TestJSONSerialization.swift
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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
class TestJSONSerialization : XCTestCase {
let supportedEncodings: [String.Encoding] = [
.utf8,
.utf16, .utf16BigEndian,
.utf32LittleEndian, .utf32BigEndian
]
static var allTests: [(String, (TestJSONSerialization) -> () throws -> Void)] {
return JSONObjectWithDataTests
+ deserializationTests
+ isValidJSONObjectTests
+ serializationTests
}
}
//MARK: - JSONObjectWithData
extension TestJSONSerialization {
class var JSONObjectWithDataTests: [(String, (TestJSONSerialization) -> () throws -> Void)] {
return [
("test_JSONObjectWithData_emptyObject", test_JSONObjectWithData_emptyObject),
("test_JSONObjectWithData_encodingDetection", test_JSONObjectWithData_encodingDetection),
]
}
func test_JSONObjectWithData_emptyObject() {
var bytes: [UInt8] = [0x7B, 0x7D]
let subject = bytes.withUnsafeMutableBufferPointer {
return Data(buffer: $0)
}
let object = try! JSONSerialization.jsonObject(with: subject, options: []) as? [String:Any]
XCTAssertEqual(object?.count, 0)
}
//MARK: - Encoding Detection
func test_JSONObjectWithData_encodingDetection() {
let subjects: [(String, [UInt8])] = [
// BOM Detection
("{} UTF-8 w/BOM", [0xEF, 0xBB, 0xBF, 0x7B, 0x7D]),
("{} UTF-16BE w/BOM", [0xFE, 0xFF, 0x0, 0x7B, 0x0, 0x7D]),
("{} UTF-16LE w/BOM", [0xFF, 0xFE, 0x7B, 0x0, 0x7D, 0x0]),
("{} UTF-32BE w/BOM", [0x00, 0x00, 0xFE, 0xFF, 0x0, 0x0, 0x0, 0x7B, 0x0, 0x0, 0x0, 0x7D]),
("{} UTF-32LE w/BOM", [0xFF, 0xFE, 0x00, 0x00, 0x7B, 0x0, 0x0, 0x0, 0x7D, 0x0, 0x0, 0x0]),
// RFC4627 Detection
("{} UTF-8", [0x7B, 0x7D]),
("{} UTF-16BE", [0x0, 0x7B, 0x0, 0x7D]),
("{} UTF-16LE", [0x7B, 0x0, 0x7D, 0x0]),
("{} UTF-32BE", [0x0, 0x0, 0x0, 0x7B, 0x0, 0x0, 0x0, 0x7D]),
("{} UTF-32LE", [0x7B, 0x0, 0x0, 0x0, 0x7D, 0x0, 0x0, 0x0]),
// // Single Characters
// ("'3' UTF-8", [0x33]),
// ("'3' UTF-16BE", [0x0, 0x33]),
// ("'3' UTF-16LE", [0x33, 0x0]),
]
for (description, encoded) in subjects {
let result = try? JSONSerialization.jsonObject(with: Data(bytes:encoded, count: encoded.count), options: [])
XCTAssertNotNil(result, description)
}
}
}
//MARK: - JSONDeserialization
extension TestJSONSerialization {
enum ObjectType {
case data
case stream
}
static var objectType = ObjectType.data
class var deserializationTests: [(String, (TestJSONSerialization) -> () throws -> Void)] {
return [
//Deserialization with Data
("test_deserialize_emptyObject_withData", test_deserialize_emptyObject_withData),
("test_deserialize_multiStringObject_withData", test_deserialize_multiStringObject_withData),
("test_deserialize_emptyArray_withData", test_deserialize_emptyArray_withData),
("test_deserialize_multiStringArray_withData", test_deserialize_multiStringArray_withData),
("test_deserialize_unicodeString_withData", test_deserialize_unicodeString_withData),
("test_deserialize_stringWithSpacesAtStart_withData", test_deserialize_stringWithSpacesAtStart_withData),
("test_deserialize_values_withData", test_deserialize_values_withData),
("test_deserialize_values_as_reference_types_withData", test_deserialize_values_as_reference_types_withData),
("test_deserialize_numbers_withData", test_deserialize_numbers_withData),
("test_deserialize_numbers_as_reference_types_withData", test_deserialize_numbers_as_reference_types_withData),
("test_deserialize_simpleEscapeSequences_withData", test_deserialize_simpleEscapeSequences_withData),
("test_deserialize_unicodeEscapeSequence_withData", test_deserialize_unicodeEscapeSequence_withData),
("test_deserialize_unicodeSurrogatePairEscapeSequence_withData", test_deserialize_unicodeSurrogatePairEscapeSequence_withData),
// Disabled due to uninitialized memory SR-606
// ("test_deserialize_allowFragments_withData", test_deserialize_allowFragments_withData),
("test_deserialize_unterminatedObjectString_withData", test_deserialize_unterminatedObjectString_withData),
("test_deserialize_missingObjectKey_withData", test_deserialize_missingObjectKey_withData),
("test_deserialize_unexpectedEndOfFile_withData", test_deserialize_unexpectedEndOfFile_withData),
("test_deserialize_invalidValueInObject_withData", test_deserialize_invalidValueInObject_withData),
("test_deserialize_invalidValueIncorrectSeparatorInObject_withData", test_deserialize_invalidValueIncorrectSeparatorInObject_withData),
("test_deserialize_invalidValueInArray_withData", test_deserialize_invalidValueInArray_withData),
("test_deserialize_badlyFormedArray_withData", test_deserialize_badlyFormedArray_withData),
("test_deserialize_invalidEscapeSequence_withData", test_deserialize_invalidEscapeSequence_withData),
("test_deserialize_unicodeMissingLeadingSurrogate_withData", test_deserialize_unicodeMissingLeadingSurrogate_withData),
("test_deserialize_unicodeMissingTrailingSurrogate_withData", test_deserialize_unicodeMissingTrailingSurrogate_withData),
//Deserialization with Stream
("test_deserialize_emptyObject_withStream", test_deserialize_emptyObject_withStream),
("test_deserialize_multiStringObject_withStream", test_deserialize_multiStringObject_withStream),
("test_deserialize_emptyArray_withStream", test_deserialize_emptyArray_withStream),
("test_deserialize_multiStringArray_withStream", test_deserialize_multiStringArray_withStream),
("test_deserialize_unicodeString_withStream", test_deserialize_unicodeString_withStream),
("test_deserialize_stringWithSpacesAtStart_withStream", test_deserialize_stringWithSpacesAtStart_withStream),
("test_deserialize_values_withStream", test_deserialize_values_withStream),
("test_deserialize_values_as_reference_types_withStream", test_deserialize_values_as_reference_types_withStream),
("test_deserialize_numbers_withStream", test_deserialize_numbers_withStream),
("test_deserialize_numbers_as_reference_types_withStream", test_deserialize_numbers_as_reference_types_withStream),
("test_deserialize_simpleEscapeSequences_withStream", test_deserialize_simpleEscapeSequences_withStream),
("test_deserialize_unicodeEscapeSequence_withStream", test_deserialize_unicodeEscapeSequence_withStream),
("test_deserialize_unicodeSurrogatePairEscapeSequence_withStream", test_deserialize_unicodeSurrogatePairEscapeSequence_withStream),
// Disabled due to uninitialized memory SR-606
// ("test_deserialize_allowFragments_withStream", test_deserialize_allowFragments_withStream),
("test_deserialize_unterminatedObjectString_withStream", test_deserialize_unterminatedObjectString_withStream),
("test_deserialize_missingObjectKey_withStream", test_deserialize_missingObjectKey_withStream),
("test_deserialize_unexpectedEndOfFile_withStream", test_deserialize_unexpectedEndOfFile_withStream),
("test_deserialize_invalidValueInObject_withStream", test_deserialize_invalidValueInObject_withStream),
("test_deserialize_invalidValueIncorrectSeparatorInObject_withStream", test_deserialize_invalidValueIncorrectSeparatorInObject_withStream),
("test_deserialize_invalidValueInArray_withStream", test_deserialize_invalidValueInArray_withStream),
("test_deserialize_badlyFormedArray_withStream", test_deserialize_badlyFormedArray_withStream),
("test_deserialize_invalidEscapeSequence_withStream", test_deserialize_invalidEscapeSequence_withStream),
("test_deserialize_unicodeMissingLeadingSurrogate_withStream", test_deserialize_unicodeMissingLeadingSurrogate_withStream),
("test_deserialize_unicodeMissingTrailingSurrogate_withStream", test_deserialize_unicodeMissingTrailingSurrogate_withStream),
("test_JSONObjectWithStream_withFile", test_JSONObjectWithStream_withFile),
("test_JSONObjectWithStream_withURL", test_JSONObjectWithStream_withURL),
]
}
func test_deserialize_emptyObject_withData() {
deserialize_emptyObject(objectType: .data)
}
func test_deserialize_multiStringObject_withData() {
deserialize_multiStringObject(objectType: .data)
}
func test_deserialize_emptyArray_withData() {
deserialize_emptyArray(objectType: .data)
}
func test_deserialize_multiStringArray_withData() {
deserialize_multiStringArray(objectType: .data)
}
func test_deserialize_unicodeString_withData() {
deserialize_unicodeString(objectType: .data)
}
func test_deserialize_stringWithSpacesAtStart_withData() {
deserialize_stringWithSpacesAtStart(objectType: .data)
}
func test_deserialize_values_withData() {
deserialize_values(objectType: .data)
}
func test_deserialize_values_as_reference_types_withData() {
deserialize_values_as_reference_types(objectType: .data)
}
func test_deserialize_numbers_withData() {
deserialize_numbers(objectType: .data)
}
func test_deserialize_numbers_as_reference_types_withData() {
deserialize_numbers_as_reference_types(objectType: .data)
}
func test_deserialize_simpleEscapeSequences_withData() {
deserialize_simpleEscapeSequences(objectType: .data)
}
func test_deserialize_unicodeEscapeSequence_withData() {
deserialize_unicodeEscapeSequence(objectType: .data)
}
func test_deserialize_unicodeSurrogatePairEscapeSequence_withData() {
deserialize_unicodeSurrogatePairEscapeSequence(objectType: .data)
}
// Disabled due to uninitialized memory SR-606
// func test_deserialize_allowFragments_withData() {
// deserialize_allowFragments(objectType: .data)
// }
func test_deserialize_unterminatedObjectString_withData() {
deserialize_unterminatedObjectString(objectType: .data)
}
func test_deserialize_missingObjectKey_withData() {
deserialize_missingObjectKey(objectType: .data)
}
func test_deserialize_unexpectedEndOfFile_withData() {
deserialize_unexpectedEndOfFile(objectType: .data)
}
func test_deserialize_invalidValueInObject_withData() {
deserialize_invalidValueInObject(objectType: .data)
}
func test_deserialize_invalidValueIncorrectSeparatorInObject_withData() {
deserialize_invalidValueIncorrectSeparatorInObject(objectType: .data)
}
func test_deserialize_invalidValueInArray_withData() {
deserialize_invalidValueInArray(objectType: .data)
}
func test_deserialize_badlyFormedArray_withData() {
deserialize_badlyFormedArray(objectType: .data)
}
func test_deserialize_invalidEscapeSequence_withData() {
deserialize_invalidEscapeSequence(objectType: .data)
}
func test_deserialize_unicodeMissingLeadingSurrogate_withData() {
deserialize_unicodeMissingLeadingSurrogate(objectType: .data)
}
func test_deserialize_unicodeMissingTrailingSurrogate_withData() {
deserialize_unicodeMissingTrailingSurrogate(objectType: .data)
}
func test_deserialize_emptyObject_withStream() {
deserialize_emptyObject(objectType: .stream)
}
func test_deserialize_multiStringObject_withStream() {
deserialize_multiStringObject(objectType: .stream)
}
func test_deserialize_emptyArray_withStream() {
deserialize_emptyArray(objectType: .stream)
}
func test_deserialize_multiStringArray_withStream() {
deserialize_multiStringArray(objectType: .stream)
}
func test_deserialize_unicodeString_withStream() {
deserialize_unicodeString(objectType: .stream)
}
func test_deserialize_stringWithSpacesAtStart_withStream() {
deserialize_stringWithSpacesAtStart(objectType: .stream)
}
func test_deserialize_values_withStream() {
deserialize_values(objectType: .stream)
}
func test_deserialize_values_as_reference_types_withStream() {
deserialize_values_as_reference_types(objectType: .stream)
}
func test_deserialize_numbers_withStream() {
deserialize_numbers(objectType: .stream)
}
func test_deserialize_numbers_as_reference_types_withStream() {
deserialize_numbers_as_reference_types(objectType: .stream)
}
func test_deserialize_simpleEscapeSequences_withStream() {
deserialize_simpleEscapeSequences(objectType: .stream)
}
func test_deserialize_unicodeEscapeSequence_withStream() {
deserialize_unicodeEscapeSequence(objectType: .stream)
}
func test_deserialize_unicodeSurrogatePairEscapeSequence_withStream() {
deserialize_unicodeSurrogatePairEscapeSequence(objectType: .stream)
}
// Disabled due to uninitialized memory SR-606
// func test_deserialize_allowFragments_withStream() {
// deserialize_allowFragments(objectType: .stream)
// }
func test_deserialize_unterminatedObjectString_withStream() {
deserialize_unterminatedObjectString(objectType: .stream)
}
func test_deserialize_missingObjectKey_withStream() {
deserialize_missingObjectKey(objectType: .stream)
}
func test_deserialize_unexpectedEndOfFile_withStream() {
deserialize_unexpectedEndOfFile(objectType: .stream)
}
func test_deserialize_invalidValueInObject_withStream() {
deserialize_invalidValueInObject(objectType: .stream)
}
func test_deserialize_invalidValueIncorrectSeparatorInObject_withStream() {
deserialize_invalidValueIncorrectSeparatorInObject(objectType: .stream)
}
func test_deserialize_invalidValueInArray_withStream() {
deserialize_invalidValueInArray(objectType: .stream)
}
func test_deserialize_badlyFormedArray_withStream() {
deserialize_badlyFormedArray(objectType: .stream)
}
func test_deserialize_invalidEscapeSequence_withStream() {
deserialize_invalidEscapeSequence(objectType: .stream)
}
func test_deserialize_unicodeMissingLeadingSurrogate_withStream() {
deserialize_unicodeMissingLeadingSurrogate(objectType: .stream)
}
func test_deserialize_unicodeMissingTrailingSurrogate_withStream() {
deserialize_unicodeMissingTrailingSurrogate(objectType: .stream)
}
//MARK: - Object Deserialization
func deserialize_emptyObject(objectType: ObjectType) {
let subject = "{}"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [String: Any]
XCTAssertEqual(result?.count, 0)
} catch {
XCTFail("Error thrown: \(error)")
}
}
func deserialize_multiStringObject(objectType: ObjectType) {
let subject = "{ \"hello\": \"world\", \"swift\": \"rocks\" }"
do {
for encoding in [String.Encoding.utf8, String.Encoding.utf16BigEndian] {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [String: Any]
XCTAssertEqual(result?["hello"] as? String, "world")
XCTAssertEqual(result?["swift"] as? String, "rocks")
}
} catch {
XCTFail("Error thrown: \(error)")
}
}
func deserialize_stringWithSpacesAtStart(objectType: ObjectType) {
let subject = "{\"title\" : \" hello world!!\" }"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [String: Any]
XCTAssertEqual(result?["title"] as? String, " hello world!!")
} catch{
XCTFail("Error thrown: \(error)")
}
}
//MARK: - Array Deserialization
func deserialize_emptyArray(objectType: ObjectType) {
let subject = "[]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
XCTAssertEqual(result?.count, 0)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func deserialize_multiStringArray(objectType: ObjectType) {
let subject = "[\"hello\", \"swift⚡️\"]"
do {
for encoding in [String.Encoding.utf8, String.Encoding.utf16BigEndian] {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
XCTAssertEqual(result?[0] as? String, "hello")
XCTAssertEqual(result?[1] as? String, "swift⚡️")
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func deserialize_unicodeString(objectType: ObjectType) {
/// Ģ has the same LSB as quotation mark " (U+0022) so test guarding against this case
let subject = "[\"unicode\", \"Ģ\", \"😢\"]"
do {
for encoding in [String.Encoding.utf16LittleEndian, String.Encoding.utf16BigEndian, String.Encoding.utf32LittleEndian, String.Encoding.utf32BigEndian] {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
XCTAssertEqual(result?[0] as? String, "unicode")
XCTAssertEqual(result?[1] as? String, "Ģ")
XCTAssertEqual(result?[2] as? String, "😢")
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Value parsing
func deserialize_values(objectType: ObjectType) {
let subject = "[true, false, \"hello\", null, {}, []]"
do {
for encoding in supportedEncodings {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
XCTAssertEqual(result?[0] as? Bool, true)
XCTAssertEqual(result?[1] as? Bool, false)
XCTAssertEqual(result?[2] as? String, "hello")
XCTAssertNotNil(result?[3] as? NSNull)
XCTAssertNotNil(result?[4] as? [String:Any])
XCTAssertNotNil(result?[5] as? [Any])
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func deserialize_values_as_reference_types(objectType: ObjectType) {
let subject = "[true, false, \"hello\", null, {}, []]"
do {
for encoding in supportedEncodings {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
XCTAssertEqual(result?[0] as? NSNumber, true)
XCTAssertEqual(result?[1] as? NSNumber, false)
XCTAssertEqual(result?[2] as? String, "hello")
XCTAssertNotNil(result?[3] as? NSNull)
XCTAssertNotNil(result?[4] as? [String:Any])
XCTAssertNotNil(result?[5] as? [Any])
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Number parsing
func deserialize_numbers(objectType: ObjectType) {
let subject = "[1, -1, 1.3, -1.3, 1e3, 1E-3, 10, -12.34e56, 12.34e-56, 12.34e+6, 0.002, 0.0043e+4]"
do {
for encoding in supportedEncodings {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
XCTAssertEqual(result?[0] as? Int, 1)
XCTAssertEqual(result?[1] as? Int, -1)
XCTAssertEqual(result?[2] as? Double, 1.3)
XCTAssertEqual(result?[3] as? Double, -1.3)
XCTAssertEqual(result?[4] as? Int, 1000)
XCTAssertEqual(result?[5] as? Double, 0.001)
XCTAssertEqual(result?[6] as? Int, 10)
XCTAssertEqual(result?[6] as? Double, 10.0)
XCTAssertEqual(result?[7] as? Double, -12.34e56)
XCTAssertEqual(result?[8] as? Double, 12.34e-56)
XCTAssertEqual(result?[9] as? Double, 12.34e6)
XCTAssertEqual(result?[10] as? Double, 2e-3)
XCTAssertEqual(result?[11] as? Double, 43)
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func deserialize_numbers_as_reference_types(objectType: ObjectType) {
let subject = "[1, -1, 1.3, -1.3, 1e3, 1E-3, 10, -12.34e56, 12.34e-56, 12.34e+6, 0.002, 0.0043e+4]"
do {
for encoding in supportedEncodings {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
XCTAssertEqual(result?[0] as? NSNumber, 1)
XCTAssertEqual(result?[1] as? NSNumber, -1)
XCTAssertEqual(result?[2] as? NSNumber, 1.3)
XCTAssertEqual(result?[3] as? NSNumber, -1.3)
XCTAssertEqual(result?[4] as? NSNumber, 1000)
XCTAssertEqual(result?[5] as? NSNumber, 0.001)
XCTAssertEqual(result?[6] as? NSNumber, 10)
XCTAssertEqual(result?[6] as? NSNumber, 10.0)
XCTAssertEqual(result?[7] as? NSNumber, -12.34e56)
XCTAssertEqual(result?[8] as? NSNumber, 12.34e-56)
XCTAssertEqual(result?[9] as? NSNumber, 12.34e6)
XCTAssertEqual(result?[10] as? NSNumber, 2e-3)
XCTAssertEqual(result?[11] as? NSNumber, 43)
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Escape Sequences
func deserialize_simpleEscapeSequences(objectType: ObjectType) {
let subject = "[\"\\\"\", \"\\\\\", \"\\/\", \"\\b\", \"\\f\", \"\\n\", \"\\r\", \"\\t\"]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let res = try getjsonObjectResult(data, objectType) as? [Any]
let result = res?.compactMap { $0 as? String }
XCTAssertEqual(result?[0], "\"")
XCTAssertEqual(result?[1], "\\")
XCTAssertEqual(result?[2], "/")
XCTAssertEqual(result?[3], "\u{08}")
XCTAssertEqual(result?[4], "\u{0C}")
XCTAssertEqual(result?[5], "\u{0A}")
XCTAssertEqual(result?[6], "\u{0D}")
XCTAssertEqual(result?[7], "\u{09}")
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func deserialize_unicodeEscapeSequence(objectType: ObjectType) {
let subject = "[\"\\u2728\"]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
// result?[0] as? String returns an Optional<String> and RHS is promoted
// to Optional<String>
XCTAssertEqual(result?[0] as? String, "✨")
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func deserialize_unicodeSurrogatePairEscapeSequence(objectType: ObjectType) {
let subject = "[\"\\uD834\\udd1E\"]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? [Any]
// result?[0] as? String returns an Optional<String> and RHS is promoted
// to Optional<String>
XCTAssertEqual(result?[0] as? String, "\u{1D11E}")
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func deserialize_allowFragments(objectType: ObjectType) {
let subject = "3"
do {
for encoding in supportedEncodings {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try getjsonObjectResult(data, objectType) as? Int
XCTAssertEqual(result, 3)
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Parsing Errors
func deserialize_unterminatedObjectString(objectType: ObjectType) {
let subject = "{\"}"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: UnterminatedString")
} catch {
// Passing case; the object as unterminated
}
}
func deserialize_missingObjectKey(objectType: ObjectType) {
let subject = "{3}"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: Missing key for value")
} catch {
// Passing case; the key was missing for a value
}
}
func deserialize_unexpectedEndOfFile(objectType: ObjectType) {
let subject = "{"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: Unexpected end of file")
} catch {
// Success
}
}
func deserialize_invalidValueInObject(objectType: ObjectType) {
let subject = "{\"error\":}"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: Invalid value")
} catch {
// Passing case; the value is invalid
}
}
func deserialize_invalidValueIncorrectSeparatorInObject(objectType: ObjectType) {
let subject = "{\"missing\";}"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: Invalid value")
} catch {
// passing case the value is invalid
}
}
func deserialize_invalidValueInArray(objectType: ObjectType) {
let subject = "[,"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: Invalid value")
} catch {
// Passing case; the element in the array is missing
}
}
func deserialize_badlyFormedArray(objectType: ObjectType) {
let subject = "[2b4]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: Badly formed array")
} catch {
// Passing case; the array is malformed
}
}
func deserialize_invalidEscapeSequence(objectType: ObjectType) {
let subject = "[\"\\e\"]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType)
XCTFail("Expected error: Invalid escape sequence")
} catch {
// Passing case; the escape sequence is invalid
}
}
func deserialize_unicodeMissingLeadingSurrogate(objectType: ObjectType) {
let subject = "[\"\\uDFF3\"]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType) as? [String]
XCTFail("Expected error: Missing Leading Surrogate")
} catch {
// Passing case; the unicode character is malformed
}
}
func deserialize_unicodeMissingTrailingSurrogate(objectType: ObjectType) {
let subject = "[\"\\uD834\"]"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
let _ = try getjsonObjectResult(data, objectType) as? [String]
XCTFail("Expected error: Missing Trailing Surrogate")
} catch {
// Passing case; the unicode character is malformed
}
}
func test_JSONObjectWithStream_withFile() {
let subject = "{}"
do {
guard let data = subject.data(using: .utf8) else {
XCTFail("Unable to convert string to data")
return
}
if let filePath = createTestFile("TestJSON.txt",_contents: data) {
let fileStream: InputStream = InputStream(fileAtPath: filePath)!
fileStream.open()
let resultRead = try JSONSerialization.jsonObject(with: fileStream, options: [])
let result = resultRead as? [String: Any]
XCTAssertEqual(result?.count, 0)
fileStream.close()
removeTestFile(filePath)
}
} catch {
XCTFail("Error thrown: \(error)")
}
}
func test_JSONObjectWithStream_withURL() {
let subject = "[true, false, \"hello\", null, {}, []]"
do {
for encoding in supportedEncodings {
guard let data = subject.data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
if let filePath = createTestFile("TestJSON.txt",_contents: data) {
let url = URL(fileURLWithPath: filePath)
let inputStream: InputStream = InputStream(url: url)!
inputStream.open()
let result = try JSONSerialization.jsonObject(with: inputStream, options: []) as? [Any]
inputStream.close()
removeTestFile(filePath)
XCTAssertEqual(result?[0] as? Bool, true)
XCTAssertEqual(result?[1] as? Bool, false)
XCTAssertEqual(result?[2] as? String, "hello")
XCTAssertNotNil(result?[3] as? NSNull)
XCTAssertNotNil(result?[4] as? [String:Any])
XCTAssertNotNil(result?[5] as? [Any])
}
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
private func getjsonObjectResult(_ data: Data,
_ objectType: ObjectType,
options opt: JSONSerialization.ReadingOptions = []) throws -> Any {
var result: Any
switch objectType {
case .data:
//Test with Data
result = try JSONSerialization.jsonObject(with: data, options: opt)
case .stream:
//Test with stream
let stream: InputStream = InputStream(data: data)
stream.open()
result = try JSONSerialization.jsonObject(with: stream, options: opt)
stream.close()
}
return result
}
}
// MARK: - isValidJSONObjectTests
extension TestJSONSerialization {
class var isValidJSONObjectTests: [(String, (TestJSONSerialization) -> () throws -> Void)] {
return [
("test_isValidJSONObjectTrue", test_isValidJSONObjectTrue),
("test_isValidJSONObjectFalse", test_isValidJSONObjectFalse),
("test_validNumericJSONObjects", test_validNumericJSONObjects)
]
}
func test_isValidJSONObjectTrue() {
let trueJSON: [Any] = [
// []
Array<Any>(),
// [1, ["string", [[]]]]
Array<Any>(arrayLiteral:
NSNumber(value: Int(1)),
Array<Any>(arrayLiteral:
"string",
Array<Any>(arrayLiteral:
Array<Any>()
)
)
),
// [NSNull(), ["1" : ["string", 1], "2" : NSNull()]]
Array<Any>(arrayLiteral:
NSNull(),
Dictionary<String, Any>(dictionaryLiteral:
(
"1",
Array<Any>(arrayLiteral:
"string",
NSNumber(value: Int(1))
)
),
(
"2",
NSNull()
)
)
),
// ["0" : 0]
Dictionary<String, Any>(dictionaryLiteral:
(
"0",
NSNumber(value: Int(0))
)
),
]
for testCase in trueJSON {
XCTAssertTrue(JSONSerialization.isValidJSONObject(testCase))
}
// [Any?.none]
let optionalAny: Any? = nil
let anyArray: [Any] = [optionalAny as Any]
XCTAssertTrue(JSONSerialization.isValidJSONObject(anyArray))
}
func test_isValidJSONObjectFalse() {
var falseJSON = [Any]()
falseJSON.append(NSNumber(value: Int(0)))
falseJSON.append(NSNull())
falseJSON.append("string")
falseJSON.append(Array<Any>(arrayLiteral:
NSNumber(value: Int(1)),
NSNumber(value: Int(2)),
NSNumber(value: Int(3)),
Dictionary<NSNumber, Any>(dictionaryLiteral:
(
NSNumber(value: Int(4)),
NSNumber(value: Int(5))
)
)
))
let one = NSNumber(value: Int(1))
let two = NSNumber(value: Int(2))
let divo = NSNumber(value: Double(1) / Double(0))
falseJSON.append([one, two, divo])
falseJSON.append([NSNull() : NSNumber(value: Int(1))])
falseJSON.append(Array<Any>(arrayLiteral:
Array<Any>(arrayLiteral:
Array<Any>(arrayLiteral:
Dictionary<NSNumber, Any>(dictionaryLiteral:
(
NSNumber(value: Int(1)),
NSNumber(value: Int(2))
)
)
)
)
))
for testCase in falseJSON {
XCTAssertFalse(JSONSerialization.isValidJSONObject(testCase))
}
}
func test_validNumericJSONObjects() {
// All of the numeric types supported by JSONSerialization
XCTAssertTrue(JSONSerialization.isValidJSONObject([nil, NSNull()]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([true, false]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([Int.min, Int8.min, Int16.min, Int32.min, Int64.min]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([UInt.min, UInt8.min, UInt16.min, UInt32.min, UInt64.min]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([Float.leastNonzeroMagnitude, Double.leastNonzeroMagnitude]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([NSNumber(value: true), NSNumber(value: Float.greatestFiniteMagnitude), NSNumber(value: Double.greatestFiniteMagnitude)]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([NSNumber(value: Int.max), NSNumber(value: Int8.max), NSNumber(value: Int16.max), NSNumber(value: Int32.max), NSNumber(value: Int64.max)]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([NSNumber(value: UInt.max), NSNumber(value: UInt8.max), NSNumber(value: UInt16.max), NSNumber(value: UInt32.max), NSNumber(value: UInt64.max)]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([NSDecimalNumber(booleanLiteral: true), NSDecimalNumber(decimal: Decimal.greatestFiniteMagnitude), NSDecimalNumber(floatLiteral: Double.greatestFiniteMagnitude), NSDecimalNumber(integerLiteral: Int.min)]))
XCTAssertTrue(JSONSerialization.isValidJSONObject([Decimal(123), Decimal(Double.leastNonzeroMagnitude)]))
XCTAssertFalse(JSONSerialization.isValidJSONObject(Float.nan))
XCTAssertFalse(JSONSerialization.isValidJSONObject(Float.infinity))
XCTAssertFalse(JSONSerialization.isValidJSONObject(-Float.infinity))
XCTAssertFalse(JSONSerialization.isValidJSONObject(NSNumber(value: Float.nan)))
XCTAssertFalse(JSONSerialization.isValidJSONObject(NSNumber(value: Float.infinity)))
XCTAssertFalse(JSONSerialization.isValidJSONObject(NSNumber(value: -Float.infinity)))
XCTAssertFalse(JSONSerialization.isValidJSONObject(Double.nan))
XCTAssertFalse(JSONSerialization.isValidJSONObject(Double.infinity))
XCTAssertFalse(JSONSerialization.isValidJSONObject(-Double.infinity))
XCTAssertFalse(JSONSerialization.isValidJSONObject(NSNumber(value: Double.nan)))
XCTAssertFalse(JSONSerialization.isValidJSONObject(NSNumber(value: Double.infinity)))
XCTAssertFalse(JSONSerialization.isValidJSONObject(NSNumber(value: -Double.infinity)))
XCTAssertFalse(JSONSerialization.isValidJSONObject(NSDecimalNumber(decimal: Decimal(floatLiteral: Double.nan))))
}
}
// MARK: - serializationTests
extension TestJSONSerialization {
class var serializationTests: [(String, (TestJSONSerialization) -> () throws -> Void)] {
return [
("test_serialize_emptyObject", test_serialize_emptyObject),
("test_serialize_null", test_serialize_null),
("test_serialize_complexObject", test_serialize_complexObject),
("test_nested_array", test_nested_array),
("test_nested_dictionary", test_nested_dictionary),
("test_serialize_number", test_serialize_number),
("test_serialize_IntMax", test_serialize_IntMax),
("test_serialize_IntMin", test_serialize_IntMin),
("test_serialize_UIntMax", test_serialize_UIntMax),
("test_serialize_UIntMin", test_serialize_UIntMin),
("test_serialize_8BitSizes", test_serialize_8BitSizes),
("test_serialize_16BitSizes", test_serialize_16BitSizes),