EncoderTests.swift 66 KB

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