DataEncoderTests.swift 68 KB

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