forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestJSONEncoder.swift
1691 lines (1420 loc) · 66.4 KB
/
TestJSONEncoder.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 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
import Foundation
import XCTest
// MARK: - Test Suite
class TestJSONEncoder : XCTestCase {
// MARK: - Encoding Top-Level Empty Types
func testEncodingTopLevelEmptyStruct() {
let empty = EmptyStruct()
_testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary)
}
func testEncodingTopLevelEmptyClass() {
let empty = EmptyClass()
_testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary)
}
// MARK: - Encoding Top-Level Single-Value Types
func testEncodingTopLevelSingleValueEnum() {
_testRoundTrip(of: Switch.off)
_testRoundTrip(of: Switch.on)
}
func testEncodingTopLevelSingleValueStruct() {
_testRoundTrip(of: Timestamp(3141592653))
}
func testEncodingTopLevelSingleValueClass() {
_testRoundTrip(of: Counter())
}
// MARK: - Encoding Top-Level Structured Types
func testEncodingTopLevelStructuredStruct() {
// Address is a struct type with multiple fields.
let address = Address.testValue
_testRoundTrip(of: address)
}
func testEncodingTopLevelStructuredClass() {
// Person is a class with multiple fields.
let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"[email protected]\"}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON)
}
func testEncodingTopLevelStructuredSingleStruct() {
// Numbers is a struct which encodes as an array through a single value container.
let numbers = Numbers.testValue
_testRoundTrip(of: numbers)
}
func testEncodingTopLevelStructuredSingleClass() {
// Mapping is a class which encodes as a dictionary through a single value container.
let mapping = Mapping.testValue
_testRoundTrip(of: mapping)
}
func testEncodingTopLevelDeepStructuredType() {
// Company is a type with fields which are Codable themselves.
let company = Company.testValue
_testRoundTrip(of: company)
}
func testEncodingClassWhichSharesEncoderWithSuper() {
// Employee is a type which shares its encoder & decoder with its superclass, Person.
let employee = Employee.testValue
_testRoundTrip(of: employee)
}
func testEncodingTopLevelNullableType() {
// EnhancedBool is a type which encodes either as a Bool or as nil.
_testRoundTrip(of: EnhancedBool.true, expectedJSON: "true".data(using: .utf8)!)
_testRoundTrip(of: EnhancedBool.false, expectedJSON: "false".data(using: .utf8)!)
_testRoundTrip(of: EnhancedBool.fileNotFound, expectedJSON: "null".data(using: .utf8)!)
}
func testEncodingMultipleNestedContainersWithTheSameTopLevelKey() {
struct Model : Codable, Equatable {
let first: String
let second: String
init(from coder: Decoder) throws {
let container = try coder.container(keyedBy: TopLevelCodingKeys.self)
let firstNestedContainer = try container.nestedContainer(keyedBy: FirstNestedCodingKeys.self, forKey: .top)
self.first = try firstNestedContainer.decode(String.self, forKey: .first)
let secondNestedContainer = try container.nestedContainer(keyedBy: SecondNestedCodingKeys.self, forKey: .top)
self.second = try secondNestedContainer.decode(String.self, forKey: .second)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: TopLevelCodingKeys.self)
var firstNestedContainer = container.nestedContainer(keyedBy: FirstNestedCodingKeys.self, forKey: .top)
try firstNestedContainer.encode(self.first, forKey: .first)
var secondNestedContainer = container.nestedContainer(keyedBy: SecondNestedCodingKeys.self, forKey: .top)
try secondNestedContainer.encode(self.second, forKey: .second)
}
init(first: String, second: String) {
self.first = first
self.second = second
}
static var testValue: Model {
return Model(first: "Johnny Appleseed",
second: "[email protected]")
}
enum TopLevelCodingKeys : String, CodingKey {
case top
}
enum FirstNestedCodingKeys : String, CodingKey {
case first
}
enum SecondNestedCodingKeys : String, CodingKey {
case second
}
}
let model = Model.testValue
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
let expectedJSON = "{\"top\":{\"first\":\"Johnny Appleseed\",\"second\":\"[email protected]\"}}".data(using: .utf8)!
_testRoundTrip(of: model, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
} else {
_testRoundTrip(of: model)
}
}
#if false // FIXME: XCTest doesn't support crash tests yet rdar://20195010&22387653
func testEncodingConflictedTypeNestedContainersWithTheSameTopLevelKey() {
struct Model : Encodable, Equatable {
let first: String
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: TopLevelCodingKeys.self)
var firstNestedContainer = container.nestedContainer(keyedBy: FirstNestedCodingKeys.self, forKey: .top)
try firstNestedContainer.encode(self.first, forKey: .first)
// The following line would fail as it attempts to re-encode into already encoded container is invalid. This will always fail
var secondNestedContainer = container.nestedUnkeyedContainer(forKey: .top)
try secondNestedContainer.encode("second")
}
init(first: String) {
self.first = first
}
static var testValue: Model {
return Model(first: "Johnny Appleseed")
}
enum TopLevelCodingKeys : String, CodingKey {
case top
}
enum FirstNestedCodingKeys : String, CodingKey {
case first
}
}
let model = Model.testValue
// This following test would fail as it attempts to re-encode into already encoded container is invalid. This will always fail
expectCrashLater()
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
_testEncodeFailure(of: model)
} else {
_testEncodeFailure(of: model)
}
}
#endif
// MARK: - Output Formatting Tests
func testEncodingOutputFormattingDefault() {
let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"[email protected]\"}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON)
}
func testEncodingOutputFormattingPrettyPrinted() {
let expectedJSON = "{\n \"name\" : \"Johnny Appleseed\",\n \"email\" : \"[email protected]\"\n}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted])
}
func testEncodingOutputFormattingSortedKeys() {
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
let expectedJSON = "{\"email\":\"[email protected]\",\"name\":\"Johnny Appleseed\"}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
}
}
func testEncodingOutputFormattingPrettyPrintedSortedKeys() {
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
let expectedJSON = "{\n \"email\" : \"[email protected]\",\n \"name\" : \"Johnny Appleseed\"\n}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys])
}
}
// MARK: - Date Strategy Tests
// Disabled for now till we resolve rdar://52618414
func x_testEncodingDate() {
func formattedLength(of value: Double) -> Int {
let empty = UnsafeMutablePointer<Int8>.allocate(capacity: 0)
defer { empty.deallocate() }
let length = snprintf(ptr: empty, 0, "%0.*g", DBL_DECIMAL_DIG, value)
return Int(length)
}
// Duplicated to handle a special case
func localTestRoundTrip<T: Codable & Equatable>(of value: T) {
var payload: Data! = nil
do {
let encoder = JSONEncoder()
payload = try encoder.encode(value)
} catch {
XCTFail("Failed to encode \(T.self) to JSON: \(error)")
}
do {
let decoder = JSONDecoder()
let decoded = try decoder.decode(T.self, from: payload)
/// `snprintf`'s `%g`, which `JSONSerialization` uses internally for double values, does not respect
/// our precision requests in every case. This bug effects Darwin, FreeBSD, and Linux currently
/// causing this test (which uses the current time) to fail occasionally.
if formattedLength(of: (decoded as! Date).timeIntervalSinceReferenceDate) > DBL_DECIMAL_DIG + 2 {
let adjustedTimeIntervalSinceReferenceDate: (Date) -> Double = { date in
let adjustment = pow(10, Double(DBL_DECIMAL_DIG))
return Double(floor(adjustment * date.timeIntervalSinceReferenceDate).rounded() / adjustment)
}
let decodedAprox = adjustedTimeIntervalSinceReferenceDate(decoded as! Date)
let valueAprox = adjustedTimeIntervalSinceReferenceDate(value as! Date)
XCTAssertEqual(decodedAprox, valueAprox, "\(T.self) did not round-trip to an equal value after DBL_DECIMAL_DIG adjustment \(decodedAprox) != \(valueAprox).")
return
}
XCTAssertEqual(decoded, value, "\(T.self) did not round-trip to an equal value. \((decoded as! Date).timeIntervalSinceReferenceDate) != \((value as! Date).timeIntervalSinceReferenceDate)")
} catch {
XCTFail("Failed to decode \(T.self) from JSON: \(error)")
}
}
// Test the above `snprintf` edge case evaluation with a known triggering case
let knownBadDate = Date(timeIntervalSinceReferenceDate: 0.0021413276231263384)
localTestRoundTrip(of: knownBadDate)
localTestRoundTrip(of: Date())
// Optional dates should encode the same way.
localTestRoundTrip(of: Optional(Date()))
}
func testEncodingDateSecondsSince1970() {
// Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
let seconds = 1000.0
let expectedJSON = "1000".data(using: .utf8)!
_testRoundTrip(of: Date(timeIntervalSince1970: seconds),
expectedJSON: expectedJSON,
dateEncodingStrategy: .secondsSince1970,
dateDecodingStrategy: .secondsSince1970)
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(Date(timeIntervalSince1970: seconds)),
expectedJSON: expectedJSON,
dateEncodingStrategy: .secondsSince1970,
dateDecodingStrategy: .secondsSince1970)
}
func testEncodingDateMillisecondsSince1970() {
// Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
let seconds = 1000.0
let expectedJSON = "1000000".data(using: .utf8)!
_testRoundTrip(of: Date(timeIntervalSince1970: seconds),
expectedJSON: expectedJSON,
dateEncodingStrategy: .millisecondsSince1970,
dateDecodingStrategy: .millisecondsSince1970)
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(Date(timeIntervalSince1970: seconds)),
expectedJSON: expectedJSON,
dateEncodingStrategy: .millisecondsSince1970,
dateDecodingStrategy: .millisecondsSince1970)
}
func testEncodingDateISO8601() {
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
let timestamp = Date(timeIntervalSince1970: 1000)
let expectedJSON = "\"\(formatter.string(from: timestamp))\"".data(using: .utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .iso8601,
dateDecodingStrategy: .iso8601)
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .iso8601,
dateDecodingStrategy: .iso8601)
}
}
func testEncodingDateFormatted() {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .full
let timestamp = Date(timeIntervalSince1970: 1000)
let expectedJSON = "\"\(formatter.string(from: timestamp))\"".data(using: .utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .formatted(formatter),
dateDecodingStrategy: .formatted(formatter))
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .formatted(formatter),
dateDecodingStrategy: .formatted(formatter))
}
func testEncodingDateCustom() {
let timestamp = Date()
// We'll encode a number instead of a date.
let encode = { (_ data: Date, _ encoder: Encoder) throws -> Void in
var container = encoder.singleValueContainer()
try container.encode(42)
}
let decode = { (_: Decoder) throws -> Date in return timestamp }
let expectedJSON = "42".data(using: .utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
}
func testEncodingDateCustomEmpty() {
let timestamp = Date()
// Encoding nothing should encode an empty keyed container ({}).
let encode = { (_: Date, _: Encoder) throws -> Void in }
let decode = { (_: Decoder) throws -> Date in return timestamp }
let expectedJSON = "{}".data(using: .utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
}
// MARK: - Data Strategy Tests
func testEncodingData() {
let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF])
let expectedJSON = "[222,173,190,239]".data(using: .utf8)!
_testRoundTrip(of: data,
expectedJSON: expectedJSON,
dataEncodingStrategy: .deferredToData,
dataDecodingStrategy: .deferredToData)
// Optional data should encode the same way.
_testRoundTrip(of: Optional(data),
expectedJSON: expectedJSON,
dataEncodingStrategy: .deferredToData,
dataDecodingStrategy: .deferredToData)
}
func testEncodingDataBase64() {
let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF])
let expectedJSON = "\"3q2+7w==\"".data(using: .utf8)!
_testRoundTrip(of: data, expectedJSON: expectedJSON)
// Optional data should encode the same way.
_testRoundTrip(of: Optional(data), expectedJSON: expectedJSON)
}
func testEncodingDataCustom() {
// We'll encode a number instead of data.
let encode = { (_ data: Data, _ encoder: Encoder) throws -> Void in
var container = encoder.singleValueContainer()
try container.encode(42)
}
let decode = { (_: Decoder) throws -> Data in return Data() }
let expectedJSON = "42".data(using: .utf8)!
_testRoundTrip(of: Data(),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
// Optional data should encode the same way.
_testRoundTrip(of: Optional(Data()),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
}
func testEncodingDataCustomEmpty() {
// Encoding nothing should encode an empty keyed container ({}).
let encode = { (_: Data, _: Encoder) throws -> Void in }
let decode = { (_: Decoder) throws -> Data in return Data() }
let expectedJSON = "{}".data(using: .utf8)!
_testRoundTrip(of: Data(),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
// Optional Data should encode the same way.
_testRoundTrip(of: Optional(Data()),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
}
// MARK: - Non-Conforming Floating Point Strategy Tests
func testEncodingNonConformingFloats() {
_testEncodeFailure(of: Float.infinity)
_testEncodeFailure(of: Float.infinity)
_testEncodeFailure(of: -Float.infinity)
_testEncodeFailure(of: Float.nan)
_testEncodeFailure(of: Double.infinity)
_testEncodeFailure(of: -Double.infinity)
_testEncodeFailure(of: Double.nan)
// Optional Floats/Doubles should encode the same way.
_testEncodeFailure(of: Float.infinity)
_testEncodeFailure(of: -Float.infinity)
_testEncodeFailure(of: Float.nan)
_testEncodeFailure(of: Double.infinity)
_testEncodeFailure(of: -Double.infinity)
_testEncodeFailure(of: Double.nan)
}
func testEncodingNonConformingFloatStrings() {
let encodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN")
let decodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN")
_testRoundTrip(of: Float.infinity,
expectedJSON: "\"INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: -Float.infinity,
expectedJSON: "\"-INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Since Float.nan != Float.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
_testRoundTrip(of: FloatNaNPlaceholder(),
expectedJSON: "\"NaN\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Double.infinity,
expectedJSON: "\"INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: -Double.infinity,
expectedJSON: "\"-INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Since Double.nan != Double.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
_testRoundTrip(of: DoubleNaNPlaceholder(),
expectedJSON: "\"NaN\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Optional Floats and Doubles should encode the same way.
_testRoundTrip(of: Optional(Float.infinity),
expectedJSON: "\"INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Optional(-Float.infinity),
expectedJSON: "\"-INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Optional(Double.infinity),
expectedJSON: "\"INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Optional(-Double.infinity),
expectedJSON: "\"-INF\"".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
}
// MARK: - Key Strategy Tests
private struct EncodeMe : Encodable {
var keyName: String
func encode(to coder: Encoder) throws {
var c = coder.container(keyedBy: _TestKey.self)
try c.encode("test", forKey: _TestKey(stringValue: keyName)!)
}
}
func testEncodingKeyStrategySnake() {
let toSnakeCaseTests = [
("simpleOneTwo", "simple_one_two"),
("myURL", "my_url"),
("singleCharacterAtEndX", "single_character_at_end_x"),
("thisIsAnXMLProperty", "this_is_an_xml_property"),
("single", "single"), // no underscore
("", ""), // don't die on empty string
("a", "a"), // single character
("aA", "a_a"), // two characters
("version4Thing", "version4_thing"), // numerics
("partCAPS", "part_caps"), // only insert underscore before first all caps
("partCAPSLowerAGAIN", "part_caps_lower_again"), // switch back and forth caps.
("manyWordsInThisThing", "many_words_in_this_thing"), // simple lowercase + underscore + more
("asdfĆqer", "asdf_ćqer"),
("already_snake_case", "already_snake_case"),
("dataPoint22", "data_point22"),
("dataPoint22Word", "data_point22_word"),
("_oneTwoThree", "_one_two_three"),
("oneTwoThree_", "one_two_three_"),
("__oneTwoThree", "__one_two_three"),
("oneTwoThree__", "one_two_three__"),
("_oneTwoThree_", "_one_two_three_"),
("__oneTwoThree", "__one_two_three"),
("__oneTwoThree__", "__one_two_three__"),
("_test", "_test"),
("_test_", "_test_"),
("__test", "__test"),
("test__", "test__"),
("m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ", "m͉̟̹y̦̳_g͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖_u͇̝̠r͙̻̥͓̣l̥̖͎͓̪̫ͅ_r̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ"), // because Itai wanted to test this
("🐧🐟", "🐧🐟") // fishy emoji example?
]
for test in toSnakeCaseTests {
let expected = "{\"\(test.1)\":\"test\"}"
let encoded = EncodeMe(keyName: test.0)
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: .utf8)
XCTAssertEqual(expected, resultString)
}
}
func testEncodingKeyStrategyCustom() {
let expected = "{\"QQQhello\":\"test\"}"
let encoded = EncodeMe(keyName: "hello")
let encoder = JSONEncoder()
let customKeyConversion = { (_ path : [CodingKey]) -> CodingKey in
let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)!
return key
}
encoder.keyEncodingStrategy = .custom(customKeyConversion)
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: .utf8)
XCTAssertEqual(expected, resultString)
}
func testEncodingDictionaryStringKeyConversionUntouched() {
let expected = "{\"leaveMeAlone\":\"test\"}"
let toEncode: [String: String] = ["leaveMeAlone": "test"]
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let resultData = try! encoder.encode(toEncode)
let resultString = String(bytes: resultData, encoding: .utf8)
XCTAssertEqual(expected, resultString)
}
private struct EncodeFailure : Encodable {
var someValue: Double
}
private struct EncodeFailureNested : Encodable {
var nestedValue: EncodeFailure
}
func testEncodingDictionaryFailureKeyPath() {
let toEncode: [String: EncodeFailure] = ["key": EncodeFailure(someValue: Double.nan)]
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
do {
_ = try encoder.encode(toEncode)
} catch EncodingError.invalidValue(_, let context) {
XCTAssertEqual(2, context.codingPath.count)
XCTAssertEqual("key", context.codingPath[0].stringValue)
XCTAssertEqual("someValue", context.codingPath[1].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
func testEncodingDictionaryFailureKeyPathNested() {
let toEncode: [String: [String: EncodeFailureNested]] = ["key": ["sub_key": EncodeFailureNested(nestedValue: EncodeFailure(someValue: Double.nan))]]
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
do {
_ = try encoder.encode(toEncode)
} catch EncodingError.invalidValue(_, let context) {
XCTAssertEqual(4, context.codingPath.count)
XCTAssertEqual("key", context.codingPath[0].stringValue)
XCTAssertEqual("sub_key", context.codingPath[1].stringValue)
XCTAssertEqual("nestedValue", context.codingPath[2].stringValue)
XCTAssertEqual("someValue", context.codingPath[3].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
private struct EncodeNested : Encodable {
let nestedValue: EncodeMe
}
private struct EncodeNestedNested : Encodable {
let outerValue: EncodeNested
}
func testEncodingKeyStrategyPath() {
// Make sure a more complex path shows up the way we want
// Make sure the path reflects keys in the Swift, not the resulting ones in the JSON
let expected = "{\"QQQouterValue\":{\"QQQnestedValue\":{\"QQQhelloWorld\":\"test\"}}}"
let encoded = EncodeNestedNested(outerValue: EncodeNested(nestedValue: EncodeMe(keyName: "helloWorld")))
let encoder = JSONEncoder()
var callCount = 0
let customKeyConversion = { (_ path : [CodingKey]) -> CodingKey in
// This should be called three times:
// 1. to convert 'outerValue' to something
// 2. to convert 'nestedValue' to something
// 3. to convert 'helloWorld' to something
callCount = callCount + 1
if path.count == 0 {
XCTFail("The path should always have at least one entry")
} else if path.count == 1 {
XCTAssertEqual(["outerValue"], path.map { $0.stringValue })
} else if path.count == 2 {
XCTAssertEqual(["outerValue", "nestedValue"], path.map { $0.stringValue })
} else if path.count == 3 {
XCTAssertEqual(["outerValue", "nestedValue", "helloWorld"], path.map { $0.stringValue })
} else {
XCTFail("The path mysteriously had more entries")
}
let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)!
return key
}
encoder.keyEncodingStrategy = .custom(customKeyConversion)
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: .utf8)
XCTAssertEqual(expected, resultString)
XCTAssertEqual(3, callCount)
}
private struct DecodeMe : Decodable {
let found: Bool
init(from coder: Decoder) throws {
let c = try coder.container(keyedBy: _TestKey.self)
// Get the key that we expect to be passed in (camel case)
let camelCaseKey = try c.decode(String.self, forKey: _TestKey(stringValue: "camelCaseKey")!)
// Use the camel case key to decode from the JSON. The decoder should convert it to snake case to find it.
found = try c.decode(Bool.self, forKey: _TestKey(stringValue: camelCaseKey)!)
}
}
func testDecodingKeyStrategyCamel() {
let fromSnakeCaseTests = [
("", ""), // don't die on empty string
("a", "a"), // single character
("ALLCAPS", "ALLCAPS"), // If no underscores, we leave the word as-is
("ALL_CAPS", "allCaps"), // Conversion from screaming snake case
("single", "single"), // do not capitalize anything with no underscore
("snake_case", "snakeCase"), // capitalize a character
("one_two_three", "oneTwoThree"), // more than one word
("one_2_three", "one2Three"), // numerics
("one2_three", "one2Three"), // numerics, part 2
("snake_Ćase", "snakeĆase"), // do not further modify a capitalized diacritic
("snake_ćase", "snakeĆase"), // capitalize a diacritic
("alreadyCamelCase", "alreadyCamelCase"), // do not modify already camel case
("__this_and_that", "__thisAndThat"),
("_this_and_that", "_thisAndThat"),
("this__and__that", "thisAndThat"),
("this_and_that__", "thisAndThat__"),
("this_aNd_that", "thisAndThat"),
("_one_two_three", "_oneTwoThree"),
("one_two_three_", "oneTwoThree_"),
("__one_two_three", "__oneTwoThree"),
("one_two_three__", "oneTwoThree__"),
("_one_two_three_", "_oneTwoThree_"),
("__one_two_three", "__oneTwoThree"),
("__one_two_three__", "__oneTwoThree__"),
("_test", "_test"),
("_test_", "_test_"),
("__test", "__test"),
("test__", "test__"),
("_", "_"),
("__", "__"),
("___", "___"),
("m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ", "m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ"), // because Itai wanted to test this
("🐧_🐟", "🐧🐟") // fishy emoji example?
]
for test in fromSnakeCaseTests {
// This JSON contains the camel case key that the test object should decode with, then it uses the snake case key (test.0) as the actual key for the boolean value.
let input = "{\"camelCaseKey\":\"\(test.1)\",\"\(test.0)\":true}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode(DecodeMe.self, from: input)
XCTAssertTrue(result.found)
}
}
private struct DecodeMe2 : Decodable { var hello: String }
func testDecodingKeyStrategyCustom() {
let input = "{\"----hello\":\"test\"}".data(using: .utf8)!
let decoder = JSONDecoder()
let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in
// This converter removes the first 4 characters from the start of all string keys, if it has more than 4 characters
let string = path.last!.stringValue
guard string.count > 4 else { return path.last! }
let newString = String(string.dropFirst(4))
return _TestKey(stringValue: newString)!
}
decoder.keyDecodingStrategy = .custom(customKeyConversion)
let result = try! decoder.decode(DecodeMe2.self, from: input)
XCTAssertEqual("test", result.hello)
}
func testDecodingDictionaryStringKeyConversionUntouched() {
let input = "{\"leave_me_alone\":\"test\"}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode([String: String].self, from: input)
XCTAssertEqual(["leave_me_alone": "test"], result)
}
func testDecodingDictionaryFailureKeyPath() {
let input = "{\"leave_me_alone\":\"test\"}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
_ = try decoder.decode([String: Int].self, from: input)
} catch DecodingError.typeMismatch(_, let context) {
XCTAssertEqual(1, context.codingPath.count)
XCTAssertEqual("leave_me_alone", context.codingPath[0].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
private struct DecodeFailure : Decodable {
var intValue: Int
}
private struct DecodeFailureNested : Decodable {
var nestedValue: DecodeFailure
}
func testDecodingDictionaryFailureKeyPathNested() {
let input = "{\"top_level\": {\"sub_level\": {\"nested_value\": {\"int_value\": \"not_an_int\"}}}}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
_ = try decoder.decode([String: [String : DecodeFailureNested]].self, from: input)
} catch DecodingError.typeMismatch(_, let context) {
XCTAssertEqual(4, context.codingPath.count)
XCTAssertEqual("top_level", context.codingPath[0].stringValue)
XCTAssertEqual("sub_level", context.codingPath[1].stringValue)
XCTAssertEqual("nestedValue", context.codingPath[2].stringValue)
XCTAssertEqual("intValue", context.codingPath[3].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
private struct DecodeMe3 : Codable {
var thisIsCamelCase : String
}
func testEncodingKeyStrategySnakeGenerated() {
// Test that this works with a struct that has automatically generated keys
let input = "{\"this_is_camel_case\":\"test\"}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode(DecodeMe3.self, from: input)
XCTAssertEqual("test", result.thisIsCamelCase)
}
func testDecodingKeyStrategyCamelGenerated() {
let encoded = DecodeMe3(thisIsCamelCase: "test")
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: .utf8)
XCTAssertEqual("{\"this_is_camel_case\":\"test\"}", resultString)
}
func testKeyStrategySnakeGeneratedAndCustom() {
// Test that this works with a struct that has automatically generated keys
struct DecodeMe4 : Codable {
var thisIsCamelCase : String
var thisIsCamelCaseToo : String
private enum CodingKeys : String, CodingKey {
case thisIsCamelCase = "fooBar"
case thisIsCamelCaseToo
}
}
// Decoding
let input = "{\"foo_bar\":\"test\",\"this_is_camel_case_too\":\"test2\"}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decodingResult = try! decoder.decode(DecodeMe4.self, from: input)
XCTAssertEqual("test", decodingResult.thisIsCamelCase)
XCTAssertEqual("test2", decodingResult.thisIsCamelCaseToo)
// Encoding
let encoded = DecodeMe4(thisIsCamelCase: "test", thisIsCamelCaseToo: "test2")
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let encodingResultData = try! encoder.encode(encoded)
let encodingResultString = String(bytes: encodingResultData, encoding: .utf8)
XCTAssertEqual("{\"foo_bar\":\"test\",\"this_is_camel_case_too\":\"test2\"}", encodingResultString)
}
func testKeyStrategyDuplicateKeys() {
// This test is mostly to make sure we don't assert on duplicate keys
struct DecodeMe5 : Codable {
var oneTwo : String
var numberOfKeys : Int
enum CodingKeys : String, CodingKey {
case oneTwo
case oneTwoThree
}
init() {
oneTwo = "test"
numberOfKeys = 0
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
oneTwo = try container.decode(String.self, forKey: .oneTwo)
numberOfKeys = container.allKeys.count
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(oneTwo, forKey: .oneTwo)
try container.encode("test2", forKey: .oneTwoThree)
}
}
let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in
// All keys are the same!
return _TestKey(stringValue: "oneTwo")!
}
// Decoding
// This input has a dictionary with two keys, but only one will end up in the container
let input = "{\"unused key 1\":\"test1\",\"unused key 2\":\"test2\"}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom(customKeyConversion)
let decodingResult = try! decoder.decode(DecodeMe5.self, from: input)
// There will be only one result for oneTwo (the second one in the json)
XCTAssertEqual(1, decodingResult.numberOfKeys)
// Encoding
let encoded = DecodeMe5()
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .custom(customKeyConversion)
let decodingResultData = try! encoder.encode(encoded)
let decodingResultString = String(bytes: decodingResultData, encoding: .utf8)
// There will be only one value in the result (the second one encoded)
XCTAssertEqual("{\"oneTwo\":\"test2\"}", decodingResultString)
}
// MARK: - Encoder Features
func testNestedContainerCodingPaths() {
let encoder = JSONEncoder()
do {
let _ = try encoder.encode(NestedContainersTestType())
} catch let error as NSError {
XCTFail("Caught error during encoding nested container types: \(error)")
}
}
func testSuperEncoderCodingPaths() {
let encoder = JSONEncoder()
do {
let _ = try encoder.encode(NestedContainersTestType(testSuperEncoder: true))
} catch let error as NSError {
XCTFail("Caught error during encoding nested container types: \(error)")
}
}
func testInterceptDecimal() {
let expectedJSON = "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".data(using: .utf8)!
// Want to make sure we write out a JSON number, not the keyed encoding here.
// 1e127 is too big to fit natively in a Double, too, so want to make sure it's encoded as a Decimal.
let decimal = Decimal(sign: .plus, exponent: 127, significand: Decimal(1))
_testRoundTrip(of: decimal, expectedJSON: expectedJSON)
// Optional Decimals should encode the same way.
_testRoundTrip(of: Optional(decimal), expectedJSON: expectedJSON)
}
func testInterceptURL() {
// Want to make sure JSONEncoder writes out single-value URLs, not the keyed encoding.
let expectedJSON = "\"http:\\/\\/swift.org\"".data(using: .utf8)!
let url = URL(string: "http://swift.org")!
_testRoundTrip(of: url, expectedJSON: expectedJSON)
// Optional URLs should encode the same way.
_testRoundTrip(of: Optional(url), expectedJSON: expectedJSON)
}
func testInterceptURLWithoutEscapingOption() {
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
// Want to make sure JSONEncoder writes out single-value URLs, not the keyed encoding.
let expectedJSON = "\"http://swift.org\"".data(using: .utf8)!
let url = URL(string: "http://swift.org")!
_testRoundTrip(of: url, expectedJSON: expectedJSON, outputFormatting: [.withoutEscapingSlashes])
// Optional URLs should encode the same way.
_testRoundTrip(of: Optional(url), expectedJSON: expectedJSON, outputFormatting: [.withoutEscapingSlashes])
}
}
// MARK: - Type coercion
func testTypeCoercion() {
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int8].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int16].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int32].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int64].self)