EncoderTests.swift 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  1. // This file is derived from swift/test/stdlib/TestJSONEncoder.swift
  2. // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
  3. // Licensed under Apache License v2.0 with Runtime Library Exception
  4. //
  5. // See https://swift.org/LICENSE.txt for license information
  6. // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
  7. //
  8. //===----------------------------------------------------------------------===//
  9. import FirebaseSharedSwift
  10. import Swift
  11. import Foundation
  12. // MARK: - Test Suite
  13. import XCTest
  14. class TestStructureEncoder: XCTestCase {
  15. // MARK: - Encoding Top-Level Empty Types
  16. func testEncodingTopLevelEmptyStruct() {
  17. let empty = EmptyStruct()
  18. _testRoundTrip(of: empty, expected: _emptyDictionary)
  19. }
  20. func testEncodingTopLevelEmptyClass() {
  21. let empty = EmptyClass()
  22. _testRoundTrip(of: empty, expected: _emptyDictionary)
  23. }
  24. // MARK: - Encoding Top-Level Single-Value Types
  25. func testEncodingTopLevelSingleValueEnum() {
  26. _testRoundTrip(of: Switch.off)
  27. _testRoundTrip(of: Switch.on)
  28. }
  29. func testEncodingTopLevelSingleValueStruct() {
  30. _testRoundTrip(of: Timestamp(3_141_592_653))
  31. }
  32. func testEncodingTopLevelSingleValueClass() {
  33. _testRoundTrip(of: Counter())
  34. }
  35. // MARK: - Encoding Top-Level Structured Types
  36. func testEncodingTopLevelStructuredStruct() {
  37. // Address is a struct type with multiple fields.
  38. let address = Address.testValue
  39. _testRoundTrip(of: address)
  40. }
  41. func testEncodingTopLevelStructuredClass() {
  42. // Person is a class with multiple fields.
  43. let expected = ["name": "Johnny Appleseed", "email": "appleseed@apple.com"]
  44. let person = Person.testValue
  45. _testRoundTrip(of: person, expected: expected)
  46. }
  47. func testEncodingTopLevelStructuredSingleStruct() {
  48. // Numbers is a struct which encodes as an array through a single value container.
  49. let numbers = Numbers.testValue
  50. _testRoundTrip(of: numbers)
  51. }
  52. func testEncodingTopLevelStructuredSingleClass() {
  53. // Mapping is a class which encodes as a dictionary through a single value container.
  54. let mapping = Mapping.testValue
  55. _testRoundTrip(of: mapping)
  56. }
  57. func testEncodingTopLevelDeepStructuredType() {
  58. // Company is a type with fields which are Codable themselves.
  59. let company = Company.testValue
  60. _testRoundTrip(of: company)
  61. }
  62. func testEncodingClassWhichSharesEncoderWithSuper() {
  63. // Employee is a type which shares its encoder & decoder with its superclass, Person.
  64. let employee = Employee.testValue
  65. _testRoundTrip(of: employee)
  66. }
  67. func testEncodingTopLevelNullableType() {
  68. // EnhancedBool is a type which encodes either as a Bool or as nil.
  69. _testRoundTrip(of: EnhancedBool.true, expected: true)
  70. _testRoundTrip(of: EnhancedBool.false, expected: false)
  71. _testRoundTrip(of: EnhancedBool.fileNotFound, expected: NSNull())
  72. }
  73. func testEncodingMultipleNestedContainersWithTheSameTopLevelKey() {
  74. struct Model: Codable, Equatable {
  75. let first: String
  76. let second: String
  77. init(from coder: Decoder) throws {
  78. let container = try coder.container(keyedBy: TopLevelCodingKeys.self)
  79. let firstNestedContainer = try container.nestedContainer(
  80. keyedBy: FirstNestedCodingKeys.self,
  81. forKey: .top
  82. )
  83. first = try firstNestedContainer.decode(String.self, forKey: .first)
  84. let secondNestedContainer = try container.nestedContainer(
  85. keyedBy: SecondNestedCodingKeys.self,
  86. forKey: .top
  87. )
  88. second = try secondNestedContainer.decode(String.self, forKey: .second)
  89. }
  90. func encode(to encoder: Encoder) throws {
  91. var container = encoder.container(keyedBy: TopLevelCodingKeys.self)
  92. var firstNestedContainer = container.nestedContainer(
  93. keyedBy: FirstNestedCodingKeys.self,
  94. forKey: .top
  95. )
  96. try firstNestedContainer.encode(first, forKey: .first)
  97. var secondNestedContainer = container.nestedContainer(
  98. keyedBy: SecondNestedCodingKeys.self,
  99. forKey: .top
  100. )
  101. try secondNestedContainer.encode(second, forKey: .second)
  102. }
  103. init(first: String, second: String) {
  104. self.first = first
  105. self.second = second
  106. }
  107. static var testValue: Model {
  108. return Model(first: "Johnny Appleseed",
  109. second: "appleseed@apple.com")
  110. }
  111. enum TopLevelCodingKeys: String, CodingKey {
  112. case top
  113. }
  114. enum FirstNestedCodingKeys: String, CodingKey {
  115. case first
  116. }
  117. enum SecondNestedCodingKeys: String, CodingKey {
  118. case second
  119. }
  120. }
  121. let model = Model.testValue
  122. if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
  123. let expected = ["top": ["first": "Johnny Appleseed", "second": "appleseed@apple.com"]]
  124. _testRoundTrip(of: model, expected: expected)
  125. } else {
  126. _testRoundTrip(of: model)
  127. }
  128. }
  129. // NOTE: This test causes a precondition error, so I am uncertain about how it ought to be tested.
  130. // func testEncodingConflictedTypeNestedContainersWithTheSameTopLevelKey() {
  131. // struct Model : Encodable, Equatable {
  132. // let first: String
  133. //
  134. // func encode(to encoder: Encoder) throws {
  135. // var container = encoder.container(keyedBy: TopLevelCodingKeys.self)
  136. //
  137. // var firstNestedContainer = container.nestedContainer(keyedBy: FirstNestedCodingKeys.self, forKey: .top)
  138. // try firstNestedContainer.encode(self.first, forKey: .first)
  139. //
  140. // // The following line would fail as it attempts to re-encode into already encoded container is invalid. This will always fail
  141. // var secondNestedContainer = container.nestedUnkeyedContainer(forKey: .top)
  142. // try secondNestedContainer.encode("second")
  143. // }
  144. //
  145. // init(first: String) {
  146. // self.first = first
  147. // }
  148. //
  149. // static var testValue: Model {
  150. // return Model(first: "Johnny Appleseed")
  151. // }
  152. //
  153. // enum TopLevelCodingKeys : String, CodingKey {
  154. // case top
  155. // }
  156. // enum FirstNestedCodingKeys : String, CodingKey {
  157. // case first
  158. // }
  159. // }
  160. //
  161. // let model = Model.testValue
  162. // // This following test would fail as it attempts to re-encode into already encoded container is invalid. This will always fail
  163. // if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
  164. // _testEncodeFailure(of: model)
  165. // } else {
  166. // _testEncodeFailure(of: model)
  167. // }
  168. // }
  169. // MARK: - Date Strategy Tests
  170. // Disabled for now till we resolve rdar://52618414
  171. func x_testEncodingDate() {
  172. func formattedLength(of value: Double) -> Int {
  173. let empty = UnsafeMutablePointer<Int8>.allocate(capacity: 0)
  174. defer { empty.deallocate() }
  175. let length = snprintf(ptr: empty, 0, "%0.*g", DBL_DECIMAL_DIG, value)
  176. return Int(length)
  177. }
  178. // Duplicated to handle a special case
  179. func localTestRoundTrip<T: Codable & Equatable>(of value: T) {
  180. var payload: Any! = nil
  181. do {
  182. let encoder = StructureEncoder()
  183. payload = try encoder.encode(value)
  184. } catch {
  185. XCTFail("Failed to encode \(T.self): \(error)")
  186. }
  187. do {
  188. let decoder = StructureDecoder()
  189. let decoded = try decoder.decode(T.self, from: payload!)
  190. /// `snprintf`'s `%g`, which `JSONSerialization` uses internally for double values, does not respect
  191. /// our precision requests in every case. This bug effects Darwin, FreeBSD, and Linux currently
  192. /// causing this test (which uses the current time) to fail occasionally.
  193. if formattedLength(of: (decoded as! Date).timeIntervalSinceReferenceDate) >
  194. DBL_DECIMAL_DIG +
  195. 2 {
  196. let adjustedTimeIntervalSinceReferenceDate: (Date) -> Double = { date in
  197. let adjustment = pow(10, Double(DBL_DECIMAL_DIG))
  198. return Double(floor(adjustment * date.timeIntervalSinceReferenceDate)
  199. .rounded() / adjustment)
  200. }
  201. let decodedAprox = adjustedTimeIntervalSinceReferenceDate(decoded as! Date)
  202. let valueAprox = adjustedTimeIntervalSinceReferenceDate(value as! Date)
  203. XCTAssertEqual(
  204. decodedAprox,
  205. valueAprox,
  206. "\(T.self) did not round-trip to an equal value after DBL_DECIMAL_DIG adjustment \(decodedAprox) != \(valueAprox)."
  207. )
  208. return
  209. }
  210. XCTAssertEqual(
  211. decoded,
  212. value,
  213. "\(T.self) did not round-trip to an equal value. \((decoded as! Date).timeIntervalSinceReferenceDate) != \((value as! Date).timeIntervalSinceReferenceDate)"
  214. )
  215. } catch {
  216. XCTFail("Failed to decode \(T.self): \(error)")
  217. }
  218. }
  219. // Test the above `snprintf` edge case evaluation with a known triggering case
  220. let knownBadDate = Date(timeIntervalSinceReferenceDate: 0.0021413276231263384)
  221. localTestRoundTrip(of: knownBadDate)
  222. localTestRoundTrip(of: Date())
  223. // Optional dates should encode the same way.
  224. localTestRoundTrip(of: Optional(Date()))
  225. }
  226. func testEncodingDateSecondsSince1970() {
  227. // Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
  228. let seconds = 1000.0
  229. let expected = 1000
  230. _testRoundTrip(of: Date(timeIntervalSince1970: seconds),
  231. expected: expected,
  232. dateEncodingStrategy: .secondsSince1970,
  233. dateDecodingStrategy: .secondsSince1970)
  234. // Optional dates should encode the same way.
  235. _testRoundTrip(of: Optional(Date(timeIntervalSince1970: seconds)),
  236. expected: expected,
  237. dateEncodingStrategy: .secondsSince1970,
  238. dateDecodingStrategy: .secondsSince1970)
  239. }
  240. func testEncodingDateMillisecondsSince1970() {
  241. // Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
  242. let seconds = 1000.0
  243. let expected = 1_000_000
  244. _testRoundTrip(of: Date(timeIntervalSince1970: seconds),
  245. expected: expected,
  246. dateEncodingStrategy: .millisecondsSince1970,
  247. dateDecodingStrategy: .millisecondsSince1970)
  248. // Optional dates should encode the same way.
  249. _testRoundTrip(of: Optional(Date(timeIntervalSince1970: seconds)),
  250. expected: expected,
  251. dateEncodingStrategy: .millisecondsSince1970,
  252. dateDecodingStrategy: .millisecondsSince1970)
  253. }
  254. func testEncodingDateISO8601() {
  255. if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
  256. let formatter = ISO8601DateFormatter()
  257. formatter.formatOptions = .withInternetDateTime
  258. let timestamp = Date(timeIntervalSince1970: 1000)
  259. let expected = "\(formatter.string(from: timestamp))"
  260. _testRoundTrip(of: timestamp,
  261. expected: expected,
  262. dateEncodingStrategy: .iso8601,
  263. dateDecodingStrategy: .iso8601)
  264. // Optional dates should encode the same way.
  265. _testRoundTrip(of: Optional(timestamp),
  266. expected: expected,
  267. dateEncodingStrategy: .iso8601,
  268. dateDecodingStrategy: .iso8601)
  269. }
  270. }
  271. func testEncodingDateFormatted() {
  272. let formatter = DateFormatter()
  273. formatter.dateStyle = .full
  274. formatter.timeStyle = .full
  275. let timestamp = Date(timeIntervalSince1970: 1000)
  276. let expected = "\(formatter.string(from: timestamp))"
  277. _testRoundTrip(of: timestamp,
  278. expected: expected,
  279. dateEncodingStrategy: .formatted(formatter),
  280. dateDecodingStrategy: .formatted(formatter))
  281. // Optional dates should encode the same way.
  282. _testRoundTrip(of: Optional(timestamp),
  283. expected: expected,
  284. dateEncodingStrategy: .formatted(formatter),
  285. dateDecodingStrategy: .formatted(formatter))
  286. }
  287. func testEncodingDateCustom() {
  288. let timestamp = Date()
  289. // We'll encode a number instead of a date.
  290. let encode = { (_ data: Date, _ encoder: Encoder) throws -> Void in
  291. var container = encoder.singleValueContainer()
  292. try container.encode(42)
  293. }
  294. let decode = { (_: Decoder) throws -> Date in timestamp }
  295. let expected = 42
  296. _testRoundTrip(of: timestamp,
  297. expected: expected,
  298. dateEncodingStrategy: .custom(encode),
  299. dateDecodingStrategy: .custom(decode))
  300. // Optional dates should encode the same way.
  301. _testRoundTrip(of: Optional(timestamp),
  302. expected: expected,
  303. dateEncodingStrategy: .custom(encode),
  304. dateDecodingStrategy: .custom(decode))
  305. }
  306. func testEncodingDateCustomEmpty() {
  307. let timestamp = Date()
  308. // Encoding nothing should encode an empty keyed container ({}).
  309. let encode = { (_: Date, _: Encoder) throws -> Void in }
  310. let decode = { (_: Decoder) throws -> Date in timestamp }
  311. let expected: [String: String] = [:]
  312. _testRoundTrip(of: timestamp,
  313. expected: expected,
  314. dateEncodingStrategy: .custom(encode),
  315. dateDecodingStrategy: .custom(decode))
  316. // Optional dates should encode the same way.
  317. _testRoundTrip(of: Optional(timestamp),
  318. expected: expected,
  319. dateEncodingStrategy: .custom(encode),
  320. dateDecodingStrategy: .custom(decode))
  321. }
  322. // MARK: - Data Strategy Tests
  323. func testEncodingData() {
  324. let data = Data([0xDE, 0xAD, 0xBE, 0xEF])
  325. let expected = [222, 173, 190, 239]
  326. _testRoundTrip(of: data,
  327. expected: expected,
  328. dataEncodingStrategy: .deferredToData,
  329. dataDecodingStrategy: .deferredToData)
  330. // Optional data should encode the same way.
  331. _testRoundTrip(of: Optional(data),
  332. expected: expected,
  333. dataEncodingStrategy: .deferredToData,
  334. dataDecodingStrategy: .deferredToData)
  335. }
  336. func testEncodingDataBase64() {
  337. let data = Data([0xDE, 0xAD, 0xBE, 0xEF])
  338. let expected = "3q2+7w=="
  339. _testRoundTrip(of: data, expected: expected)
  340. // Optional data should encode the same way.
  341. _testRoundTrip(of: Optional(data), expected: expected)
  342. }
  343. func testEncodingDataCustom() {
  344. // We'll encode a number instead of data.
  345. let encode = { (_ data: Data, _ encoder: Encoder) throws -> Void in
  346. var container = encoder.singleValueContainer()
  347. try container.encode(42)
  348. }
  349. let decode = { (_: Decoder) throws -> Data in Data() }
  350. let expected = 42
  351. _testRoundTrip(of: Data(),
  352. expected: expected,
  353. dataEncodingStrategy: .custom(encode),
  354. dataDecodingStrategy: .custom(decode))
  355. // Optional data should encode the same way.
  356. _testRoundTrip(of: Optional(Data()),
  357. expected: expected,
  358. dataEncodingStrategy: .custom(encode),
  359. dataDecodingStrategy: .custom(decode))
  360. }
  361. func testEncodingDataCustomEmpty() {
  362. // Encoding nothing should encode an empty keyed container ({}).
  363. let encode = { (_: Data, _: Encoder) throws -> Void in }
  364. let decode = { (_: Decoder) throws -> Data in Data() }
  365. _testRoundTrip(of: Data(),
  366. expected: [:] as [String: String],
  367. dataEncodingStrategy: .custom(encode),
  368. dataDecodingStrategy: .custom(decode))
  369. // Optional Data should encode the same way.
  370. _testRoundTrip(of: Optional(Data()),
  371. expected: [:] as [String: String],
  372. dataEncodingStrategy: .custom(encode),
  373. dataDecodingStrategy: .custom(decode))
  374. }
  375. // MARK: - Non-Conforming Floating Point Strategy Tests
  376. func testEncodingNonConformingFloats() {
  377. _testEncodeFailure(of: Float.infinity)
  378. _testEncodeFailure(of: Float.infinity)
  379. _testEncodeFailure(of: -Float.infinity)
  380. _testEncodeFailure(of: Float.nan)
  381. _testEncodeFailure(of: Double.infinity)
  382. _testEncodeFailure(of: -Double.infinity)
  383. _testEncodeFailure(of: Double.nan)
  384. // Optional Floats/Doubles should encode the same way.
  385. _testEncodeFailure(of: Float.infinity)
  386. _testEncodeFailure(of: -Float.infinity)
  387. _testEncodeFailure(of: Float.nan)
  388. _testEncodeFailure(of: Double.infinity)
  389. _testEncodeFailure(of: -Double.infinity)
  390. _testEncodeFailure(of: Double.nan)
  391. }
  392. func testEncodingNonConformingFloatStrings() {
  393. let encodingStrategy: StructureEncoder.NonConformingFloatEncodingStrategy = .convertToString(
  394. positiveInfinity: "INF",
  395. negativeInfinity: "-INF",
  396. nan: "NaN"
  397. )
  398. let decodingStrategy: StructureDecoder.NonConformingFloatDecodingStrategy = .convertFromString(
  399. positiveInfinity: "INF",
  400. negativeInfinity: "-INF",
  401. nan: "NaN"
  402. )
  403. _testRoundTrip(of: Float.infinity,
  404. expected: "INF",
  405. nonConformingFloatEncodingStrategy: encodingStrategy,
  406. nonConformingFloatDecodingStrategy: decodingStrategy)
  407. _testRoundTrip(of: -Float.infinity,
  408. expected: "-INF",
  409. nonConformingFloatEncodingStrategy: encodingStrategy,
  410. nonConformingFloatDecodingStrategy: decodingStrategy)
  411. // Since Float.nan != Float.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
  412. _testRoundTrip(of: FloatNaNPlaceholder(),
  413. expected: "NaN",
  414. nonConformingFloatEncodingStrategy: encodingStrategy,
  415. nonConformingFloatDecodingStrategy: decodingStrategy)
  416. _testRoundTrip(of: Double.infinity,
  417. expected: "INF",
  418. nonConformingFloatEncodingStrategy: encodingStrategy,
  419. nonConformingFloatDecodingStrategy: decodingStrategy)
  420. _testRoundTrip(of: -Double.infinity,
  421. expected: "-INF",
  422. nonConformingFloatEncodingStrategy: encodingStrategy,
  423. nonConformingFloatDecodingStrategy: decodingStrategy)
  424. // Since Double.nan != Double.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
  425. _testRoundTrip(of: DoubleNaNPlaceholder(),
  426. expected: "NaN",
  427. nonConformingFloatEncodingStrategy: encodingStrategy,
  428. nonConformingFloatDecodingStrategy: decodingStrategy)
  429. // Optional Floats and Doubles should encode the same way.
  430. _testRoundTrip(of: Optional(Float.infinity),
  431. expected: "INF",
  432. nonConformingFloatEncodingStrategy: encodingStrategy,
  433. nonConformingFloatDecodingStrategy: decodingStrategy)
  434. _testRoundTrip(of: Optional(-Float.infinity),
  435. expected: "-INF",
  436. nonConformingFloatEncodingStrategy: encodingStrategy,
  437. nonConformingFloatDecodingStrategy: decodingStrategy)
  438. _testRoundTrip(of: Optional(Double.infinity),
  439. expected: "INF",
  440. nonConformingFloatEncodingStrategy: encodingStrategy,
  441. nonConformingFloatDecodingStrategy: decodingStrategy)
  442. _testRoundTrip(of: Optional(-Double.infinity),
  443. expected: "-INF",
  444. nonConformingFloatEncodingStrategy: encodingStrategy,
  445. nonConformingFloatDecodingStrategy: decodingStrategy)
  446. }
  447. // MARK: - Key Strategy Tests
  448. private struct EncodeMe: Encodable {
  449. var keyName: String
  450. func encode(to coder: Encoder) throws {
  451. var c = coder.container(keyedBy: _TestKey.self)
  452. try c.encode("test", forKey: _TestKey(stringValue: keyName)!)
  453. }
  454. }
  455. func testEncodingKeyStrategySnake() {
  456. let toSnakeCaseTests = [
  457. ("simpleOneTwo", "simple_one_two"),
  458. ("myURL", "my_url"),
  459. ("singleCharacterAtEndX", "single_character_at_end_x"),
  460. ("thisIsAnXMLProperty", "this_is_an_xml_property"),
  461. ("single", "single"), // no underscore
  462. ("", ""), // don't die on empty string
  463. ("a", "a"), // single character
  464. ("aA", "a_a"), // two characters
  465. ("version4Thing", "version4_thing"), // numerics
  466. ("partCAPS", "part_caps"), // only insert underscore before first all caps
  467. ("partCAPSLowerAGAIN", "part_caps_lower_again"), // switch back and forth caps.
  468. ("manyWordsInThisThing", "many_words_in_this_thing"), // simple lowercase + underscore + more
  469. ("asdfĆqer", "asdf_ćqer"),
  470. ("already_snake_case", "already_snake_case"),
  471. ("dataPoint22", "data_point22"),
  472. ("dataPoint22Word", "data_point22_word"),
  473. ("_oneTwoThree", "_one_two_three"),
  474. ("oneTwoThree_", "one_two_three_"),
  475. ("__oneTwoThree", "__one_two_three"),
  476. ("oneTwoThree__", "one_two_three__"),
  477. ("_oneTwoThree_", "_one_two_three_"),
  478. ("__oneTwoThree", "__one_two_three"),
  479. ("__oneTwoThree__", "__one_two_three__"),
  480. ("_test", "_test"),
  481. ("_test_", "_test_"),
  482. ("__test", "__test"),
  483. ("test__", "test__"),
  484. ("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
  485. ("🐧🐟", "🐧🐟"), // fishy emoji example?
  486. ]
  487. for test in toSnakeCaseTests {
  488. let expected = ["\(test.1)": "test"]
  489. let encoded = EncodeMe(keyName: test.0)
  490. let encoder = StructureEncoder()
  491. encoder.keyEncodingStrategy = .convertToSnakeCase
  492. let result = try! encoder.encode(encoded)
  493. XCTAssertEqual(expected, result as? [String: String])
  494. }
  495. }
  496. func testEncodingKeyStrategyCustom() {
  497. let expected = ["QQQhello": "test"]
  498. let encoded = EncodeMe(keyName: "hello")
  499. let encoder = StructureEncoder()
  500. let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in
  501. let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)!
  502. return key
  503. }
  504. encoder.keyEncodingStrategy = .custom(customKeyConversion)
  505. let result = try! encoder.encode(encoded)
  506. XCTAssertEqual(expected, result as? [String: String])
  507. }
  508. func testEncodingDictionaryStringKeyConversionUntouched() {
  509. let toEncode = ["leaveMeAlone": "test"]
  510. let encoder = StructureEncoder()
  511. encoder.keyEncodingStrategy = .convertToSnakeCase
  512. let result = try! encoder.encode(toEncode)
  513. XCTAssertEqual(toEncode, result as? [String: String])
  514. }
  515. private struct EncodeFailure: Encodable {
  516. var someValue: Double
  517. }
  518. private struct EncodeFailureNested: Encodable {
  519. var nestedValue: EncodeFailure
  520. }
  521. func testEncodingDictionaryFailureKeyPath() {
  522. let toEncode: [String: EncodeFailure] = ["key": EncodeFailure(someValue: Double.nan)]
  523. let encoder = StructureEncoder()
  524. encoder.keyEncodingStrategy = .convertToSnakeCase
  525. do {
  526. _ = try encoder.encode(toEncode)
  527. } catch let EncodingError.invalidValue(_, context) {
  528. XCTAssertEqual(2, context.codingPath.count)
  529. XCTAssertEqual("key", context.codingPath[0].stringValue)
  530. XCTAssertEqual("someValue", context.codingPath[1].stringValue)
  531. } catch {
  532. XCTFail("Unexpected error: \(String(describing: error))")
  533. }
  534. }
  535. func testEncodingDictionaryFailureKeyPathNested() {
  536. let toEncode: [String: [String: EncodeFailureNested]] =
  537. ["key": ["sub_key": EncodeFailureNested(nestedValue: EncodeFailure(someValue: Double.nan))]]
  538. let encoder = StructureEncoder()
  539. encoder.keyEncodingStrategy = .convertToSnakeCase
  540. do {
  541. _ = try encoder.encode(toEncode)
  542. } catch let EncodingError.invalidValue(_, context) {
  543. XCTAssertEqual(4, context.codingPath.count)
  544. XCTAssertEqual("key", context.codingPath[0].stringValue)
  545. XCTAssertEqual("sub_key", context.codingPath[1].stringValue)
  546. XCTAssertEqual("nestedValue", context.codingPath[2].stringValue)
  547. XCTAssertEqual("someValue", context.codingPath[3].stringValue)
  548. } catch {
  549. XCTFail("Unexpected error: \(String(describing: error))")
  550. }
  551. }
  552. private struct EncodeNested: Encodable {
  553. let nestedValue: EncodeMe
  554. }
  555. private struct EncodeNestedNested: Encodable {
  556. let outerValue: EncodeNested
  557. }
  558. func testEncodingKeyStrategyPath() {
  559. // Make sure a more complex path shows up the way we want
  560. // Make sure the path reflects keys in the Swift, not the resulting ones in the structure
  561. let expected = ["QQQouterValue": ["QQQnestedValue": ["QQQhelloWorld": "test"]]]
  562. let encoded =
  563. EncodeNestedNested(outerValue: EncodeNested(nestedValue: EncodeMe(keyName: "helloWorld")))
  564. let encoder = StructureEncoder()
  565. var callCount = 0
  566. let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in
  567. // This should be called three times:
  568. // 1. to convert 'outerValue' to something
  569. // 2. to convert 'nestedValue' to something
  570. // 3. to convert 'helloWorld' to something
  571. callCount = callCount + 1
  572. if path.count == 0 {
  573. XCTFail("The path should always have at least one entry")
  574. } else if path.count == 1 {
  575. XCTAssertEqual(["outerValue"], path.map { $0.stringValue })
  576. } else if path.count == 2 {
  577. XCTAssertEqual(["outerValue", "nestedValue"], path.map { $0.stringValue })
  578. } else if path.count == 3 {
  579. XCTAssertEqual(["outerValue", "nestedValue", "helloWorld"], path.map { $0.stringValue })
  580. } else {
  581. XCTFail("The path mysteriously had more entries")
  582. }
  583. let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)!
  584. return key
  585. }
  586. encoder.keyEncodingStrategy = .custom(customKeyConversion)
  587. let result = try! encoder.encode(encoded)
  588. XCTAssertEqual(expected, result as? [String: [String: [String: String]]])
  589. XCTAssertEqual(3, callCount)
  590. }
  591. private struct DecodeMe: Decodable {
  592. let found: Bool
  593. init(from coder: Decoder) throws {
  594. let c = try coder.container(keyedBy: _TestKey.self)
  595. // Get the key that we expect to be passed in (camel case)
  596. let camelCaseKey = try c.decode(String.self, forKey: _TestKey(stringValue: "camelCaseKey")!)
  597. // Use the camel case key to decode from the structure. The decoder should convert it to snake case to find it.
  598. found = try c.decode(Bool.self, forKey: _TestKey(stringValue: camelCaseKey)!)
  599. }
  600. }
  601. func testDecodingKeyStrategyCamel() {
  602. let fromSnakeCaseTests = [
  603. ("", ""), // don't die on empty string
  604. ("a", "a"), // single character
  605. ("ALLCAPS", "ALLCAPS"), // If no underscores, we leave the word as-is
  606. ("ALL_CAPS", "allCaps"), // Conversion from screaming snake case
  607. ("single", "single"), // do not capitalize anything with no underscore
  608. ("snake_case", "snakeCase"), // capitalize a character
  609. ("one_two_three", "oneTwoThree"), // more than one word
  610. ("one_2_three", "one2Three"), // numerics
  611. ("one2_three", "one2Three"), // numerics, part 2
  612. ("snake_Ćase", "snakeĆase"), // do not further modify a capitalized diacritic
  613. ("snake_ćase", "snakeĆase"), // capitalize a diacritic
  614. ("alreadyCamelCase", "alreadyCamelCase"), // do not modify already camel case
  615. ("__this_and_that", "__thisAndThat"),
  616. ("_this_and_that", "_thisAndThat"),
  617. ("this__and__that", "thisAndThat"),
  618. ("this_and_that__", "thisAndThat__"),
  619. ("this_aNd_that", "thisAndThat"),
  620. ("_one_two_three", "_oneTwoThree"),
  621. ("one_two_three_", "oneTwoThree_"),
  622. ("__one_two_three", "__oneTwoThree"),
  623. ("one_two_three__", "oneTwoThree__"),
  624. ("_one_two_three_", "_oneTwoThree_"),
  625. ("__one_two_three", "__oneTwoThree"),
  626. ("__one_two_three__", "__oneTwoThree__"),
  627. ("_test", "_test"),
  628. ("_test_", "_test_"),
  629. ("__test", "__test"),
  630. ("test__", "test__"),
  631. ("_", "_"),
  632. ("__", "__"),
  633. ("___", "___"),
  634. ("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
  635. ("🐧_🐟", "🐧🐟"), // fishy emoji example?
  636. ]
  637. for test in fromSnakeCaseTests {
  638. // This structure 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.
  639. let input = ["camelCaseKey": "\(test.1)", "\(test.0)": true] as [String: Any]
  640. let decoder = StructureDecoder()
  641. decoder.keyDecodingStrategy = .convertFromSnakeCase
  642. let result = try! decoder.decode(DecodeMe.self, from: input)
  643. XCTAssertTrue(result.found)
  644. }
  645. }
  646. private struct DecodeMe2: Decodable { var hello: String }
  647. func testDecodingKeyStrategyCustom() {
  648. let input = ["----hello": "test"]
  649. let decoder = StructureDecoder()
  650. let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in
  651. // This converter removes the first 4 characters from the start of all string keys, if it has more than 4 characters
  652. let string = path.last!.stringValue
  653. guard string.count > 4 else { return path.last! }
  654. let newString = String(string.dropFirst(4))
  655. return _TestKey(stringValue: newString)!
  656. }
  657. decoder.keyDecodingStrategy = .custom(customKeyConversion)
  658. let result = try! decoder.decode(DecodeMe2.self, from: input)
  659. XCTAssertEqual("test", result.hello)
  660. }
  661. func testDecodingDictionaryStringKeyConversionUntouched() {
  662. let input = ["leave_me_alone": "test"]
  663. let decoder = StructureDecoder()
  664. decoder.keyDecodingStrategy = .convertFromSnakeCase
  665. let result = try! decoder.decode([String: String].self, from: input)
  666. XCTAssertEqual(["leave_me_alone": "test"], result)
  667. }
  668. func testDecodingDictionaryFailureKeyPath() {
  669. let input = ["leave_me_alone": "test"]
  670. let decoder = StructureDecoder()
  671. decoder.keyDecodingStrategy = .convertFromSnakeCase
  672. do {
  673. _ = try decoder.decode([String: Int].self, from: input)
  674. } catch let DecodingError.typeMismatch(_, context) {
  675. XCTAssertEqual(1, context.codingPath.count)
  676. XCTAssertEqual("leave_me_alone", context.codingPath[0].stringValue)
  677. } catch {
  678. XCTFail("Unexpected error: \(String(describing: error))")
  679. }
  680. }
  681. private struct DecodeFailure: Decodable {
  682. var intValue: Int
  683. }
  684. private struct DecodeFailureNested: Decodable {
  685. var nestedValue: DecodeFailure
  686. }
  687. func testDecodingDictionaryFailureKeyPathNested() {
  688. let input = ["top_level": ["sub_level": ["nested_value": ["int_value": "not_an_int"]]]]
  689. let decoder = StructureDecoder()
  690. decoder.keyDecodingStrategy = .convertFromSnakeCase
  691. do {
  692. _ = try decoder.decode([String: [String: DecodeFailureNested]].self, from: input)
  693. } catch let DecodingError.typeMismatch(_, context) {
  694. XCTAssertEqual(4, context.codingPath.count)
  695. XCTAssertEqual("top_level", context.codingPath[0].stringValue)
  696. XCTAssertEqual("sub_level", context.codingPath[1].stringValue)
  697. XCTAssertEqual("nestedValue", context.codingPath[2].stringValue)
  698. XCTAssertEqual("intValue", context.codingPath[3].stringValue)
  699. } catch {
  700. XCTFail("Unexpected error: \(String(describing: error))")
  701. }
  702. }
  703. private struct DecodeMe3: Codable {
  704. var thisIsCamelCase: String
  705. }
  706. func testEncodingKeyStrategySnakeGenerated() {
  707. // Test that this works with a struct that has automatically generated keys
  708. let input = ["this_is_camel_case": "test"]
  709. let decoder = StructureDecoder()
  710. decoder.keyDecodingStrategy = .convertFromSnakeCase
  711. let result = try! decoder.decode(DecodeMe3.self, from: input)
  712. XCTAssertEqual("test", result.thisIsCamelCase)
  713. }
  714. func testDecodingKeyStrategyCamelGenerated() {
  715. let encoded = DecodeMe3(thisIsCamelCase: "test")
  716. let encoder = StructureEncoder()
  717. encoder.keyEncodingStrategy = .convertToSnakeCase
  718. let result = try! encoder.encode(encoded)
  719. XCTAssertEqual(["this_is_camel_case": "test"], result as? [String: String])
  720. }
  721. func testKeyStrategySnakeGeneratedAndCustom() {
  722. // Test that this works with a struct that has automatically generated keys
  723. struct DecodeMe4: Codable {
  724. var thisIsCamelCase: String
  725. var thisIsCamelCaseToo: String
  726. private enum CodingKeys: String, CodingKey {
  727. case thisIsCamelCase = "fooBar"
  728. case thisIsCamelCaseToo
  729. }
  730. }
  731. // Decoding
  732. let input = ["foo_bar": "test", "this_is_camel_case_too": "test2"]
  733. let decoder = StructureDecoder()
  734. decoder.keyDecodingStrategy = .convertFromSnakeCase
  735. let decodingResult = try! decoder.decode(DecodeMe4.self, from: input)
  736. XCTAssertEqual("test", decodingResult.thisIsCamelCase)
  737. XCTAssertEqual("test2", decodingResult.thisIsCamelCaseToo)
  738. // Encoding
  739. let encoded = DecodeMe4(thisIsCamelCase: "test", thisIsCamelCaseToo: "test2")
  740. let encoder = StructureEncoder()
  741. encoder.keyEncodingStrategy = .convertToSnakeCase
  742. let encodingResult = try! encoder.encode(encoded)
  743. XCTAssertEqual(
  744. ["foo_bar": "test", "this_is_camel_case_too": "test2"],
  745. encodingResult as? [String: String]
  746. )
  747. }
  748. func testKeyStrategyDuplicateKeys() {
  749. // This test is mostly to make sure we don't assert on duplicate keys
  750. struct DecodeMe5: Codable {
  751. var oneTwo: String
  752. var numberOfKeys: Int
  753. enum CodingKeys: String, CodingKey {
  754. case oneTwo
  755. case oneTwoThree
  756. }
  757. init() {
  758. oneTwo = "test"
  759. numberOfKeys = 0
  760. }
  761. init(from decoder: Decoder) throws {
  762. let container = try decoder.container(keyedBy: CodingKeys.self)
  763. oneTwo = try container.decode(String.self, forKey: .oneTwo)
  764. numberOfKeys = container.allKeys.count
  765. }
  766. func encode(to encoder: Encoder) throws {
  767. var container = encoder.container(keyedBy: CodingKeys.self)
  768. try container.encode(oneTwo, forKey: .oneTwo)
  769. try container.encode("test2", forKey: .oneTwoThree)
  770. }
  771. }
  772. let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in
  773. // All keys are the same!
  774. _TestKey(stringValue: "oneTwo")!
  775. }
  776. // Decoding
  777. // This input has a dictionary with two keys, but only one will end up in the container
  778. let input = ["unused key 1": "test1", "unused key 2": "test2"]
  779. let decoder = StructureDecoder()
  780. decoder.keyDecodingStrategy = .custom(customKeyConversion)
  781. let decodingResult = try! decoder.decode(DecodeMe5.self, from: input)
  782. // There will be only one result for oneTwo (the second one in the structure)
  783. XCTAssertEqual(1, decodingResult.numberOfKeys)
  784. // Encoding
  785. let encoded = DecodeMe5()
  786. let encoder = StructureEncoder()
  787. encoder.keyEncodingStrategy = .custom(customKeyConversion)
  788. let decodingResult2 = try! encoder.encode(encoded)
  789. // There will be only one value in the result (the second one encoded)
  790. XCTAssertEqual(["oneTwo": "test2"], decodingResult2 as? [String: String])
  791. }
  792. // MARK: - Encoder Features
  793. func testNestedContainerCodingPaths() {
  794. let encoder = StructureEncoder()
  795. do {
  796. _ = try encoder.encode(NestedContainersTestType())
  797. } catch let error as NSError {
  798. XCTFail("Caught error during encoding nested container types: \(error)")
  799. }
  800. }
  801. func testSuperEncoderCodingPaths() {
  802. let encoder = StructureEncoder()
  803. do {
  804. _ = try encoder.encode(NestedContainersTestType(testSuperEncoder: true))
  805. } catch let error as NSError {
  806. XCTFail("Caught error during encoding nested container types: \(error)")
  807. }
  808. }
  809. func testInterceptDecimal() {
  810. let expected =
  811. NSDecimalNumber(
  812. string: "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
  813. )
  814. // Want to make sure we write out a number, not the keyed encoding here.
  815. // 1e127 is too big to fit natively in a Double, too, so want to make sure it's encoded as a Decimal.
  816. let decimal = Decimal(sign: .plus, exponent: 127, significand: Decimal(1))
  817. _testRoundTrip(of: decimal, expected: expected)
  818. // Optional Decimals should encode the same way.
  819. _testRoundTrip(of: Optional(decimal), expected: expected)
  820. }
  821. func testInterceptURL() {
  822. // Want to make sure StructureEncoder writes out single-value URLs, not the keyed encoding.
  823. let expected = "http://swift.org"
  824. let url = URL(string: "http://swift.org")!
  825. _testRoundTrip(of: url, expected: expected)
  826. // Optional URLs should encode the same way.
  827. _testRoundTrip(of: Optional(url), expected: expected)
  828. }
  829. // MARK: - Type coercion
  830. func testTypeCoercion() {
  831. _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int].self)
  832. _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int8].self)
  833. _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int16].self)
  834. _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int32].self)
  835. _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int64].self)
  836. _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt].self)
  837. _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt8].self)
  838. _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt16].self)
  839. _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt32].self)
  840. _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt64].self)
  841. _testRoundTripTypeCoercionFailure(of: [false, true], as: [Float].self)
  842. _testRoundTripTypeCoercionFailure(of: [false, true], as: [Double].self)
  843. _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int], as: [Bool].self)
  844. _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int8], as: [Bool].self)
  845. _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int16], as: [Bool].self)
  846. _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int32], as: [Bool].self)
  847. _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int64], as: [Bool].self)
  848. _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt], as: [Bool].self)
  849. _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt8], as: [Bool].self)
  850. _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt16], as: [Bool].self)
  851. _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt32], as: [Bool].self)
  852. _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt64], as: [Bool].self)
  853. _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Float], as: [Bool].self)
  854. _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Double], as: [Bool].self)
  855. }
  856. func testDecodingConcreteTypeParameter() {
  857. let encoder = StructureEncoder()
  858. guard let value = try? encoder.encode(Employee.testValue) else {
  859. XCTFail("Unable to encode Employee.")
  860. return
  861. }
  862. let decoder = StructureDecoder()
  863. guard let decoded = try? decoder.decode(Employee.self as Person.Type, from: value) else {
  864. XCTFail("Failed to decode Employee as Person.")
  865. return
  866. }
  867. XCTAssert(
  868. type(of: decoded) == Employee.self,
  869. "Expected decoded value to be of type Employee; got \(type(of: decoded)) instead."
  870. )
  871. }
  872. // MARK: - Encoder State
  873. // SR-6078
  874. func testEncoderStateThrowOnEncode() {
  875. struct ReferencingEncoderWrapper<T: Encodable>: Encodable {
  876. let value: T
  877. init(_ value: T) { self.value = value }
  878. func encode(to encoder: Encoder) throws {
  879. // This approximates a subclass calling into its superclass, where the superclass encodes a value that might throw.
  880. // The key here is that getting the superEncoder creates a referencing encoder.
  881. var container = encoder.unkeyedContainer()
  882. let superEncoder = container.superEncoder()
  883. // Pushing a nested container on leaves the referencing encoder with multiple containers.
  884. var nestedContainer = superEncoder.unkeyedContainer()
  885. try nestedContainer.encode(value)
  886. }
  887. }
  888. // The structure that would be encoded here looks like
  889. //
  890. // [[[Float.infinity]]]
  891. //
  892. // The wrapper asks for an unkeyed container ([^]), gets a super encoder, and creates a nested container into that ([[^]]).
  893. // We then encode an array into that ([[[^]]]), which happens to be a value that causes us to throw an error.
  894. //
  895. // The issue at hand reproduces when you have a referencing encoder (superEncoder() creates one) that has a container on the stack (unkeyedContainer() adds one) that encodes a value going through box_() (Array does that) that encodes something which throws (Float.infinity does that).
  896. // When reproducing, this will cause a test failure via fatalError().
  897. _ = try? StructureEncoder().encode(ReferencingEncoderWrapper([Float.infinity]))
  898. }
  899. func testEncoderStateThrowOnEncodeCustomDate() {
  900. // This test is identical to testEncoderStateThrowOnEncode, except throwing via a custom Date closure.
  901. struct ReferencingEncoderWrapper<T: Encodable>: Encodable {
  902. let value: T
  903. init(_ value: T) { self.value = value }
  904. func encode(to encoder: Encoder) throws {
  905. var container = encoder.unkeyedContainer()
  906. let superEncoder = container.superEncoder()
  907. var nestedContainer = superEncoder.unkeyedContainer()
  908. try nestedContainer.encode(value)
  909. }
  910. }
  911. // The closure needs to push a container before throwing an error to trigger.
  912. let encoder = StructureEncoder()
  913. encoder.dateEncodingStrategy = .custom { _, encoder in
  914. _ = encoder.unkeyedContainer()
  915. enum CustomError: Error { case foo }
  916. throw CustomError.foo
  917. }
  918. _ = try? encoder.encode(ReferencingEncoderWrapper(Date()))
  919. }
  920. func testEncoderStateThrowOnEncodeCustomData() {
  921. // This test is identical to testEncoderStateThrowOnEncode, except throwing via a custom Data closure.
  922. struct ReferencingEncoderWrapper<T: Encodable>: Encodable {
  923. let value: T
  924. init(_ value: T) { self.value = value }
  925. func encode(to encoder: Encoder) throws {
  926. var container = encoder.unkeyedContainer()
  927. let superEncoder = container.superEncoder()
  928. var nestedContainer = superEncoder.unkeyedContainer()
  929. try nestedContainer.encode(value)
  930. }
  931. }
  932. // The closure needs to push a container before throwing an error to trigger.
  933. let encoder = StructureEncoder()
  934. encoder.dataEncodingStrategy = .custom { _, encoder in
  935. _ = encoder.unkeyedContainer()
  936. enum CustomError: Error { case foo }
  937. throw CustomError.foo
  938. }
  939. _ = try? encoder.encode(ReferencingEncoderWrapper(Data()))
  940. }
  941. // MARK: - Decoder State
  942. // SR-6048
  943. func testDecoderStateThrowOnDecode() {
  944. // The container stack here starts as [[1,2,3]]. Attempting to decode as [String] matches the outer layer (Array), and begins decoding the array.
  945. // Once Array decoding begins, 1 is pushed onto the container stack ([[1,2,3], 1]), and 1 is attempted to be decoded as String. This throws a .typeMismatch, but the container is not popped off the stack.
  946. // When attempting to decode [Int], the container stack is still ([[1,2,3], 1]), and 1 fails to decode as [Int].
  947. let input = [1, 2, 3]
  948. _ = try! StructureDecoder().decode(EitherDecodable<[String], [Int]>.self, from: input)
  949. }
  950. func testDecoderStateThrowOnDecodeCustomDate() {
  951. // This test is identical to testDecoderStateThrowOnDecode, except we're going to fail because our closure throws an error, not because we hit a type mismatch.
  952. let decoder = StructureDecoder()
  953. decoder.dateDecodingStrategy = .custom { decoder in
  954. enum CustomError: Error { case foo }
  955. throw CustomError.foo
  956. }
  957. let input = 1
  958. _ = try! decoder.decode(EitherDecodable<Date, Int>.self, from: input)
  959. }
  960. func testDecoderStateThrowOnDecodeCustomData() {
  961. // This test is identical to testDecoderStateThrowOnDecode, except we're going to fail because our closure throws an error, not because we hit a type mismatch.
  962. let decoder = StructureDecoder()
  963. decoder.dataDecodingStrategy = .custom { decoder in
  964. enum CustomError: Error { case foo }
  965. throw CustomError.foo
  966. }
  967. let input = 1
  968. _ = try! decoder.decode(EitherDecodable<Data, Int>.self, from: input)
  969. }
  970. // MARK: - Helper Functions
  971. private var _emptyDictionary: [String: String] {
  972. return [:]
  973. }
  974. private func _testEncodeFailure<T: Encodable>(of value: T) {
  975. do {
  976. _ = try StructureEncoder().encode(value)
  977. XCTFail("Encode of top-level \(T.self) was expected to fail.")
  978. } catch {}
  979. }
  980. private func _testRoundTrip<T, U>(of value: T,
  981. expected: U,
  982. dateEncodingStrategy: StructureEncoder
  983. .DateEncodingStrategy = .deferredToDate,
  984. dateDecodingStrategy: StructureDecoder
  985. .DateDecodingStrategy = .deferredToDate,
  986. dataEncodingStrategy: StructureEncoder
  987. .DataEncodingStrategy = .base64,
  988. dataDecodingStrategy: StructureDecoder
  989. .DataDecodingStrategy = .base64,
  990. keyEncodingStrategy: StructureEncoder
  991. .KeyEncodingStrategy = .useDefaultKeys,
  992. keyDecodingStrategy: StructureDecoder
  993. .KeyDecodingStrategy = .useDefaultKeys,
  994. nonConformingFloatEncodingStrategy: StructureEncoder
  995. .NonConformingFloatEncodingStrategy = .throw,
  996. nonConformingFloatDecodingStrategy: StructureDecoder
  997. .NonConformingFloatDecodingStrategy = .throw)
  998. where T: Codable,
  999. T: Equatable, U: Equatable {
  1000. var payload: Any! = nil
  1001. do {
  1002. let encoder = StructureEncoder()
  1003. encoder.dateEncodingStrategy = dateEncodingStrategy
  1004. encoder.dataEncodingStrategy = dataEncodingStrategy
  1005. encoder.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy
  1006. encoder.keyEncodingStrategy = keyEncodingStrategy
  1007. payload = try encoder.encode(value)
  1008. } catch {
  1009. XCTFail("Failed to encode \(T.self): \(error)")
  1010. }
  1011. XCTAssertEqual(
  1012. expected,
  1013. payload as? U,
  1014. "Produced structure not identical to expected structure."
  1015. )
  1016. do {
  1017. let decoder = StructureDecoder()
  1018. decoder.dateDecodingStrategy = dateDecodingStrategy
  1019. decoder.dataDecodingStrategy = dataDecodingStrategy
  1020. decoder.nonConformingFloatDecodingStrategy = nonConformingFloatDecodingStrategy
  1021. decoder.keyDecodingStrategy = keyDecodingStrategy
  1022. let decoded = try decoder.decode(T.self, from: payload!)
  1023. XCTAssertEqual(decoded, value, "\(T.self) did not round-trip to an equal value.")
  1024. } catch {
  1025. XCTFail("Failed to decode \(T.self): \(error)")
  1026. }
  1027. }
  1028. private func _testRoundTrip<T>(of value: T,
  1029. dateEncodingStrategy: StructureEncoder
  1030. .DateEncodingStrategy = .deferredToDate,
  1031. dateDecodingStrategy: StructureDecoder
  1032. .DateDecodingStrategy = .deferredToDate,
  1033. dataEncodingStrategy: StructureEncoder
  1034. .DataEncodingStrategy = .base64,
  1035. dataDecodingStrategy: StructureDecoder
  1036. .DataDecodingStrategy = .base64,
  1037. keyEncodingStrategy: StructureEncoder
  1038. .KeyEncodingStrategy = .useDefaultKeys,
  1039. keyDecodingStrategy: StructureDecoder
  1040. .KeyDecodingStrategy = .useDefaultKeys,
  1041. nonConformingFloatEncodingStrategy: StructureEncoder
  1042. .NonConformingFloatEncodingStrategy = .throw,
  1043. nonConformingFloatDecodingStrategy: StructureDecoder
  1044. .NonConformingFloatDecodingStrategy = .throw) where T: Codable,
  1045. T: Equatable {
  1046. var payload: Any! = nil
  1047. do {
  1048. let encoder = StructureEncoder()
  1049. encoder.dateEncodingStrategy = dateEncodingStrategy
  1050. encoder.dataEncodingStrategy = dataEncodingStrategy
  1051. encoder.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy
  1052. encoder.keyEncodingStrategy = keyEncodingStrategy
  1053. payload = try encoder.encode(value)
  1054. } catch {
  1055. XCTFail("Failed to encode \(T.self): \(error)")
  1056. }
  1057. do {
  1058. let decoder = StructureDecoder()
  1059. decoder.dateDecodingStrategy = dateDecodingStrategy
  1060. decoder.dataDecodingStrategy = dataDecodingStrategy
  1061. decoder.nonConformingFloatDecodingStrategy = nonConformingFloatDecodingStrategy
  1062. decoder.keyDecodingStrategy = keyDecodingStrategy
  1063. let decoded = try decoder.decode(T.self, from: payload!)
  1064. XCTAssertEqual(decoded, value, "\(T.self) did not round-trip to an equal value.")
  1065. } catch {
  1066. XCTFail("Failed to decode \(T.self): \(error)")
  1067. }
  1068. }
  1069. private func _testRoundTripTypeCoercionFailure<T, U>(of value: T, as type: U.Type)
  1070. where T: Codable, U: Codable {
  1071. do {
  1072. let data = try StructureEncoder().encode(value)
  1073. _ = try StructureDecoder().decode(U.self, from: data)
  1074. XCTFail("Coercion from \(T.self) to \(U.self) was expected to fail.")
  1075. } catch {}
  1076. }
  1077. }
  1078. // MARK: - Helper Global Functions
  1079. func expectEqualPaths(_ lhs: [CodingKey], _ rhs: [CodingKey], _ prefix: String) {
  1080. if lhs.count != rhs.count {
  1081. XCTFail("\(prefix) [CodingKey].count mismatch: \(lhs.count) != \(rhs.count)")
  1082. return
  1083. }
  1084. for (key1, key2) in zip(lhs, rhs) {
  1085. switch (key1.intValue, key2.intValue) {
  1086. case (.none, .none): break
  1087. case let (.some(i1), .none):
  1088. XCTFail("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != nil")
  1089. return
  1090. case let (.none, .some(i2)):
  1091. XCTFail("\(prefix) CodingKey.intValue mismatch: nil != \(type(of: key2))(\(i2))")
  1092. return
  1093. case let (.some(i1), .some(i2)):
  1094. guard i1 == i2 else {
  1095. XCTFail(
  1096. "\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != \(type(of: key2))(\(i2))"
  1097. )
  1098. return
  1099. }
  1100. }
  1101. XCTAssertEqual(
  1102. key1.stringValue,
  1103. key2.stringValue,
  1104. "\(prefix) CodingKey.stringValue mismatch: \(type(of: key1))('\(key1.stringValue)') != \(type(of: key2))('\(key2.stringValue)')"
  1105. )
  1106. }
  1107. }
  1108. // MARK: - Test Types
  1109. /* FIXME: Import from %S/Inputs/Coding/SharedTypes.swift somehow. */
  1110. // MARK: - Empty Types
  1111. private struct EmptyStruct: Codable, Equatable {
  1112. static func == (_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool {
  1113. return true
  1114. }
  1115. }
  1116. private class EmptyClass: Codable, Equatable {
  1117. static func == (_ lhs: EmptyClass, _ rhs: EmptyClass) -> Bool {
  1118. return true
  1119. }
  1120. }
  1121. // MARK: - Single-Value Types
  1122. /// A simple on-off switch type that encodes as a single Bool value.
  1123. private enum Switch: Codable {
  1124. case off
  1125. case on
  1126. init(from decoder: Decoder) throws {
  1127. let container = try decoder.singleValueContainer()
  1128. switch try container.decode(Bool.self) {
  1129. case false: self = .off
  1130. case true: self = .on
  1131. }
  1132. }
  1133. func encode(to encoder: Encoder) throws {
  1134. var container = encoder.singleValueContainer()
  1135. switch self {
  1136. case .off: try container.encode(false)
  1137. case .on: try container.encode(true)
  1138. }
  1139. }
  1140. }
  1141. /// A simple timestamp type that encodes as a single Double value.
  1142. private struct Timestamp: Codable, Equatable {
  1143. let value: Double
  1144. init(_ value: Double) {
  1145. self.value = value
  1146. }
  1147. init(from decoder: Decoder) throws {
  1148. let container = try decoder.singleValueContainer()
  1149. value = try container.decode(Double.self)
  1150. }
  1151. func encode(to encoder: Encoder) throws {
  1152. var container = encoder.singleValueContainer()
  1153. try container.encode(value)
  1154. }
  1155. static func == (_ lhs: Timestamp, _ rhs: Timestamp) -> Bool {
  1156. return lhs.value == rhs.value
  1157. }
  1158. }
  1159. /// A simple referential counter type that encodes as a single Int value.
  1160. private final class Counter: Codable, Equatable {
  1161. var count: Int = 0
  1162. init() {}
  1163. init(from decoder: Decoder) throws {
  1164. let container = try decoder.singleValueContainer()
  1165. count = try container.decode(Int.self)
  1166. }
  1167. func encode(to encoder: Encoder) throws {
  1168. var container = encoder.singleValueContainer()
  1169. try container.encode(count)
  1170. }
  1171. static func == (_ lhs: Counter, _ rhs: Counter) -> Bool {
  1172. return lhs === rhs || lhs.count == rhs.count
  1173. }
  1174. }
  1175. // MARK: - Structured Types
  1176. /// A simple address type that encodes as a dictionary of values.
  1177. private struct Address: Codable, Equatable {
  1178. let street: String
  1179. let city: String
  1180. let state: String
  1181. let zipCode: Int
  1182. let country: String
  1183. init(street: String, city: String, state: String, zipCode: Int, country: String) {
  1184. self.street = street
  1185. self.city = city
  1186. self.state = state
  1187. self.zipCode = zipCode
  1188. self.country = country
  1189. }
  1190. static func == (_ lhs: Address, _ rhs: Address) -> Bool {
  1191. return lhs.street == rhs.street &&
  1192. lhs.city == rhs.city &&
  1193. lhs.state == rhs.state &&
  1194. lhs.zipCode == rhs.zipCode &&
  1195. lhs.country == rhs.country
  1196. }
  1197. static var testValue: Address {
  1198. return Address(street: "1 Infinite Loop",
  1199. city: "Cupertino",
  1200. state: "CA",
  1201. zipCode: 95014,
  1202. country: "United States")
  1203. }
  1204. }
  1205. /// A simple person class that encodes as a dictionary of values.
  1206. private class Person: Codable, Equatable {
  1207. let name: String
  1208. let email: String
  1209. let website: URL?
  1210. init(name: String, email: String, website: URL? = nil) {
  1211. self.name = name
  1212. self.email = email
  1213. self.website = website
  1214. }
  1215. func isEqual(_ other: Person) -> Bool {
  1216. return name == other.name &&
  1217. email == other.email &&
  1218. website == other.website
  1219. }
  1220. static func == (_ lhs: Person, _ rhs: Person) -> Bool {
  1221. return lhs.isEqual(rhs)
  1222. }
  1223. class var testValue: Person {
  1224. return Person(name: "Johnny Appleseed", email: "appleseed@apple.com")
  1225. }
  1226. }
  1227. /// A class which shares its encoder and decoder with its superclass.
  1228. private class Employee: Person {
  1229. let id: Int
  1230. init(name: String, email: String, website: URL? = nil, id: Int) {
  1231. self.id = id
  1232. super.init(name: name, email: email, website: website)
  1233. }
  1234. enum CodingKeys: String, CodingKey {
  1235. case id
  1236. }
  1237. required init(from decoder: Decoder) throws {
  1238. let container = try decoder.container(keyedBy: CodingKeys.self)
  1239. id = try container.decode(Int.self, forKey: .id)
  1240. try super.init(from: decoder)
  1241. }
  1242. override func encode(to encoder: Encoder) throws {
  1243. var container = encoder.container(keyedBy: CodingKeys.self)
  1244. try container.encode(id, forKey: .id)
  1245. try super.encode(to: encoder)
  1246. }
  1247. override func isEqual(_ other: Person) -> Bool {
  1248. if let employee = other as? Employee {
  1249. guard id == employee.id else { return false }
  1250. }
  1251. return super.isEqual(other)
  1252. }
  1253. override class var testValue: Employee {
  1254. return Employee(name: "Johnny Appleseed", email: "appleseed@apple.com", id: 42)
  1255. }
  1256. }
  1257. /// A simple company struct which encodes as a dictionary of nested values.
  1258. private struct Company: Codable, Equatable {
  1259. let address: Address
  1260. var employees: [Employee]
  1261. init(address: Address, employees: [Employee]) {
  1262. self.address = address
  1263. self.employees = employees
  1264. }
  1265. static func == (_ lhs: Company, _ rhs: Company) -> Bool {
  1266. return lhs.address == rhs.address && lhs.employees == rhs.employees
  1267. }
  1268. static var testValue: Company {
  1269. return Company(address: Address.testValue, employees: [Employee.testValue])
  1270. }
  1271. }
  1272. /// An enum type which decodes from Bool?.
  1273. private enum EnhancedBool: Codable {
  1274. case `true`
  1275. case `false`
  1276. case fileNotFound
  1277. init(from decoder: Decoder) throws {
  1278. let container = try decoder.singleValueContainer()
  1279. if container.decodeNil() {
  1280. self = .fileNotFound
  1281. } else {
  1282. let value = try container.decode(Bool.self)
  1283. self = value ? .true : .false
  1284. }
  1285. }
  1286. func encode(to encoder: Encoder) throws {
  1287. var container = encoder.singleValueContainer()
  1288. switch self {
  1289. case .true: try container.encode(true)
  1290. case .false: try container.encode(false)
  1291. case .fileNotFound: try container.encodeNil()
  1292. }
  1293. }
  1294. }
  1295. /// A type which encodes as an array directly through a single value container.
  1296. struct Numbers: Codable, Equatable {
  1297. let values = [4, 8, 15, 16, 23, 42]
  1298. init() {}
  1299. init(from decoder: Decoder) throws {
  1300. let container = try decoder.singleValueContainer()
  1301. let decodedValues = try container.decode([Int].self)
  1302. guard decodedValues == values else {
  1303. throw DecodingError
  1304. .dataCorrupted(DecodingError
  1305. .Context(codingPath: decoder.codingPath, debugDescription: "The Numbers are wrong!"))
  1306. }
  1307. }
  1308. func encode(to encoder: Encoder) throws {
  1309. var container = encoder.singleValueContainer()
  1310. try container.encode(values)
  1311. }
  1312. static func == (_ lhs: Numbers, _ rhs: Numbers) -> Bool {
  1313. return lhs.values == rhs.values
  1314. }
  1315. static var testValue: Numbers {
  1316. return Numbers()
  1317. }
  1318. }
  1319. /// A type which encodes as a dictionary directly through a single value container.
  1320. private final class Mapping: Codable, Equatable {
  1321. let values: [String: URL]
  1322. init(values: [String: URL]) {
  1323. self.values = values
  1324. }
  1325. init(from decoder: Decoder) throws {
  1326. let container = try decoder.singleValueContainer()
  1327. values = try container.decode([String: URL].self)
  1328. }
  1329. func encode(to encoder: Encoder) throws {
  1330. var container = encoder.singleValueContainer()
  1331. try container.encode(values)
  1332. }
  1333. static func == (_ lhs: Mapping, _ rhs: Mapping) -> Bool {
  1334. return lhs === rhs || lhs.values == rhs.values
  1335. }
  1336. static var testValue: Mapping {
  1337. return Mapping(values: ["Apple": URL(string: "http://apple.com")!,
  1338. "localhost": URL(string: "http://127.0.0.1")!])
  1339. }
  1340. }
  1341. struct NestedContainersTestType: Encodable {
  1342. let testSuperEncoder: Bool
  1343. init(testSuperEncoder: Bool = false) {
  1344. self.testSuperEncoder = testSuperEncoder
  1345. }
  1346. enum TopLevelCodingKeys: Int, CodingKey {
  1347. case a
  1348. case b
  1349. case c
  1350. }
  1351. enum IntermediateCodingKeys: Int, CodingKey {
  1352. case one
  1353. case two
  1354. }
  1355. func encode(to encoder: Encoder) throws {
  1356. if testSuperEncoder {
  1357. var topLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self)
  1358. expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.")
  1359. expectEqualPaths(
  1360. topLevelContainer.codingPath,
  1361. [],
  1362. "New first-level keyed container has non-empty codingPath."
  1363. )
  1364. let superEncoder = topLevelContainer.superEncoder(forKey: .a)
  1365. expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.")
  1366. expectEqualPaths(
  1367. topLevelContainer.codingPath,
  1368. [],
  1369. "First-level keyed container's codingPath changed."
  1370. )
  1371. expectEqualPaths(
  1372. superEncoder.codingPath,
  1373. [TopLevelCodingKeys.a],
  1374. "New superEncoder had unexpected codingPath."
  1375. )
  1376. _testNestedContainers(in: superEncoder, baseCodingPath: [TopLevelCodingKeys.a])
  1377. } else {
  1378. _testNestedContainers(in: encoder, baseCodingPath: [])
  1379. }
  1380. }
  1381. func _testNestedContainers(in encoder: Encoder, baseCodingPath: [CodingKey]) {
  1382. expectEqualPaths(encoder.codingPath, baseCodingPath, "New encoder has non-empty codingPath.")
  1383. // codingPath should not change upon fetching a non-nested container.
  1384. var firstLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self)
  1385. expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
  1386. expectEqualPaths(
  1387. firstLevelContainer.codingPath,
  1388. baseCodingPath,
  1389. "New first-level keyed container has non-empty codingPath."
  1390. )
  1391. // Nested Keyed Container
  1392. do {
  1393. // Nested container for key should have a new key pushed on.
  1394. var secondLevelContainer = firstLevelContainer.nestedContainer(
  1395. keyedBy: IntermediateCodingKeys.self,
  1396. forKey: .a
  1397. )
  1398. expectEqualPaths(
  1399. encoder.codingPath,
  1400. baseCodingPath,
  1401. "Top-level Encoder's codingPath changed."
  1402. )
  1403. expectEqualPaths(
  1404. firstLevelContainer.codingPath,
  1405. baseCodingPath,
  1406. "First-level keyed container's codingPath changed."
  1407. )
  1408. expectEqualPaths(
  1409. secondLevelContainer.codingPath,
  1410. baseCodingPath + [TopLevelCodingKeys.a],
  1411. "New second-level keyed container had unexpected codingPath."
  1412. )
  1413. // Inserting a keyed container should not change existing coding paths.
  1414. let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(
  1415. keyedBy: IntermediateCodingKeys.self,
  1416. forKey: .one
  1417. )
  1418. expectEqualPaths(
  1419. encoder.codingPath,
  1420. baseCodingPath,
  1421. "Top-level Encoder's codingPath changed."
  1422. )
  1423. expectEqualPaths(
  1424. firstLevelContainer.codingPath,
  1425. baseCodingPath,
  1426. "First-level keyed container's codingPath changed."
  1427. )
  1428. expectEqualPaths(
  1429. secondLevelContainer.codingPath,
  1430. baseCodingPath + [TopLevelCodingKeys.a],
  1431. "Second-level keyed container's codingPath changed."
  1432. )
  1433. expectEqualPaths(
  1434. thirdLevelContainerKeyed.codingPath,
  1435. baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.one],
  1436. "New third-level keyed container had unexpected codingPath."
  1437. )
  1438. // Inserting an unkeyed container should not change existing coding paths.
  1439. let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer(forKey: .two)
  1440. expectEqualPaths(
  1441. encoder.codingPath,
  1442. baseCodingPath + [],
  1443. "Top-level Encoder's codingPath changed."
  1444. )
  1445. expectEqualPaths(
  1446. firstLevelContainer.codingPath,
  1447. baseCodingPath + [],
  1448. "First-level keyed container's codingPath changed."
  1449. )
  1450. expectEqualPaths(
  1451. secondLevelContainer.codingPath,
  1452. baseCodingPath + [TopLevelCodingKeys.a],
  1453. "Second-level keyed container's codingPath changed."
  1454. )
  1455. expectEqualPaths(
  1456. thirdLevelContainerUnkeyed.codingPath,
  1457. baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.two],
  1458. "New third-level unkeyed container had unexpected codingPath."
  1459. )
  1460. }
  1461. // Nested Unkeyed Container
  1462. do {
  1463. // Nested container for key should have a new key pushed on.
  1464. var secondLevelContainer = firstLevelContainer.nestedUnkeyedContainer(forKey: .b)
  1465. expectEqualPaths(
  1466. encoder.codingPath,
  1467. baseCodingPath,
  1468. "Top-level Encoder's codingPath changed."
  1469. )
  1470. expectEqualPaths(
  1471. firstLevelContainer.codingPath,
  1472. baseCodingPath,
  1473. "First-level keyed container's codingPath changed."
  1474. )
  1475. expectEqualPaths(
  1476. secondLevelContainer.codingPath,
  1477. baseCodingPath + [TopLevelCodingKeys.b],
  1478. "New second-level keyed container had unexpected codingPath."
  1479. )
  1480. // Appending a keyed container should not change existing coding paths.
  1481. let thirdLevelContainerKeyed = secondLevelContainer
  1482. .nestedContainer(keyedBy: IntermediateCodingKeys.self)
  1483. expectEqualPaths(
  1484. encoder.codingPath,
  1485. baseCodingPath,
  1486. "Top-level Encoder's codingPath changed."
  1487. )
  1488. expectEqualPaths(
  1489. firstLevelContainer.codingPath,
  1490. baseCodingPath,
  1491. "First-level keyed container's codingPath changed."
  1492. )
  1493. expectEqualPaths(
  1494. secondLevelContainer.codingPath,
  1495. baseCodingPath + [TopLevelCodingKeys.b],
  1496. "Second-level unkeyed container's codingPath changed."
  1497. )
  1498. expectEqualPaths(
  1499. thirdLevelContainerKeyed.codingPath,
  1500. baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 0)],
  1501. "New third-level keyed container had unexpected codingPath."
  1502. )
  1503. // Appending an unkeyed container should not change existing coding paths.
  1504. let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer()
  1505. expectEqualPaths(
  1506. encoder.codingPath,
  1507. baseCodingPath,
  1508. "Top-level Encoder's codingPath changed."
  1509. )
  1510. expectEqualPaths(
  1511. firstLevelContainer.codingPath,
  1512. baseCodingPath,
  1513. "First-level keyed container's codingPath changed."
  1514. )
  1515. expectEqualPaths(
  1516. secondLevelContainer.codingPath,
  1517. baseCodingPath + [TopLevelCodingKeys.b],
  1518. "Second-level unkeyed container's codingPath changed."
  1519. )
  1520. expectEqualPaths(
  1521. thirdLevelContainerUnkeyed.codingPath,
  1522. baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 1)],
  1523. "New third-level unkeyed container had unexpected codingPath."
  1524. )
  1525. }
  1526. }
  1527. }
  1528. // MARK: - Helper Types
  1529. /// A key type which can take on any string or integer value.
  1530. /// This needs to mirror _JSONKey.
  1531. private struct _TestKey: CodingKey {
  1532. var stringValue: String
  1533. var intValue: Int?
  1534. init?(stringValue: String) {
  1535. self.stringValue = stringValue
  1536. intValue = nil
  1537. }
  1538. init?(intValue: Int) {
  1539. stringValue = "\(intValue)"
  1540. self.intValue = intValue
  1541. }
  1542. init(index: Int) {
  1543. stringValue = "Index \(index)"
  1544. intValue = index
  1545. }
  1546. }
  1547. private struct FloatNaNPlaceholder: Codable, Equatable {
  1548. init() {}
  1549. func encode(to encoder: Encoder) throws {
  1550. var container = encoder.singleValueContainer()
  1551. try container.encode(Float.nan)
  1552. }
  1553. init(from decoder: Decoder) throws {
  1554. let container = try decoder.singleValueContainer()
  1555. let float = try container.decode(Float.self)
  1556. if !float.isNaN {
  1557. throw DecodingError
  1558. .dataCorrupted(DecodingError
  1559. .Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN."))
  1560. }
  1561. }
  1562. static func == (_ lhs: FloatNaNPlaceholder, _ rhs: FloatNaNPlaceholder) -> Bool {
  1563. return true
  1564. }
  1565. }
  1566. private struct DoubleNaNPlaceholder: Codable, Equatable {
  1567. init() {}
  1568. func encode(to encoder: Encoder) throws {
  1569. var container = encoder.singleValueContainer()
  1570. try container.encode(Double.nan)
  1571. }
  1572. init(from decoder: Decoder) throws {
  1573. let container = try decoder.singleValueContainer()
  1574. let double = try container.decode(Double.self)
  1575. if !double.isNaN {
  1576. throw DecodingError
  1577. .dataCorrupted(DecodingError
  1578. .Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN."))
  1579. }
  1580. }
  1581. static func == (_ lhs: DoubleNaNPlaceholder, _ rhs: DoubleNaNPlaceholder) -> Bool {
  1582. return true
  1583. }
  1584. }
  1585. private enum EitherDecodable<T: Decodable, U: Decodable>: Decodable {
  1586. case t(T)
  1587. case u(U)
  1588. init(from decoder: Decoder) throws {
  1589. let container = try decoder.singleValueContainer()
  1590. do {
  1591. self = .t(try container.decode(T.self))
  1592. } catch {
  1593. self = .u(try container.decode(U.self))
  1594. }
  1595. }
  1596. }