FirestoreEncoderTests.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import FirebaseFirestore
  18. import FirebaseFirestoreSwift
  19. import XCTest
  20. class FirestoreEncoderTests: XCTestCase {
  21. func testInt() {
  22. struct Model: Codable, Equatable {
  23. let x: Int
  24. }
  25. let model = Model(x: 42)
  26. let dict = ["x": 42]
  27. assertThat(model).roundTrips(to: dict)
  28. }
  29. func testEmpty() {
  30. struct Model: Codable, Equatable {}
  31. assertThat(Model()).roundTrips(to: [String: Any]())
  32. }
  33. func testString() throws {
  34. struct Model: Codable, Equatable {
  35. let s: String
  36. }
  37. assertThat(Model(s: "abc")).roundTrips(to: ["s": "abc"])
  38. }
  39. func testOptional() {
  40. struct Model: Codable, Equatable {
  41. let x: Int
  42. let opt: Int?
  43. }
  44. assertThat(Model(x: 42, opt: nil)).roundTrips(to: ["x": 42])
  45. assertThat(Model(x: 42, opt: 7)).roundTrips(to: ["x": 42, "opt": 7])
  46. assertThat(["x": 42, "opt": 5]).decodes(to: Model(x: 42, opt: 5))
  47. assertThat(["x": 42, "opt": true]).failsDecoding(to: Model.self)
  48. assertThat(["x": 42, "opt": "abc"]).failsDecoding(to: Model.self)
  49. assertThat(["x": 45.55, "opt": 5]).failsDecoding(to: Model.self)
  50. assertThat(["opt": 5]).failsDecoding(to: Model.self)
  51. // TODO: - handle encoding keys with nil values
  52. // See https://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder
  53. // and https://bugs.swift.org/browse/SR-9232
  54. // XCTAssertTrue(encodedDict.keys.contains("x"))
  55. }
  56. func testEnum() {
  57. enum MyEnum: Codable, Equatable {
  58. case num(number: Int)
  59. case text(String)
  60. case timestamp(Timestamp)
  61. private enum CodingKeys: String, CodingKey {
  62. case num
  63. case text
  64. case timestamp
  65. }
  66. private enum DecodingError: Error {
  67. case decoding(String)
  68. }
  69. init(from decoder: Decoder) throws {
  70. let values = try decoder.container(keyedBy: CodingKeys.self)
  71. if let value = try? values.decode(Int.self, forKey: .num) {
  72. self = .num(number: value)
  73. return
  74. }
  75. if let value = try? values.decode(String.self, forKey: .text) {
  76. self = .text(value)
  77. return
  78. }
  79. if let value = try? values.decode(Timestamp.self, forKey: .timestamp) {
  80. self = .timestamp(value)
  81. return
  82. }
  83. throw DecodingError.decoding("Decoding error: \(dump(values))")
  84. }
  85. func encode(to encoder: Encoder) throws {
  86. var container = encoder.container(keyedBy: CodingKeys.self)
  87. switch self {
  88. case let .num(number):
  89. try container.encode(number, forKey: .num)
  90. case let .text(value):
  91. try container.encode(value, forKey: .text)
  92. case let .timestamp(stamp):
  93. try container.encode(stamp, forKey: .timestamp)
  94. }
  95. }
  96. }
  97. struct Model: Codable, Equatable {
  98. let x: Int
  99. let e: MyEnum
  100. }
  101. assertThat(Model(x: 42, e: MyEnum.num(number: 4)))
  102. .roundTrips(to: ["x": 42, "e": ["num": 4]])
  103. assertThat(Model(x: 43, e: MyEnum.text("abc")))
  104. .roundTrips(to: ["x": 43, "e": ["text": "abc"]])
  105. let timestamp = Timestamp(date: Date())
  106. assertThat(Model(x: 43, e: MyEnum.timestamp(timestamp)))
  107. .roundTrips(to: ["x": 43, "e": ["timestamp": timestamp]])
  108. }
  109. func testGeoPoint() {
  110. struct Model: Codable, Equatable {
  111. let p: GeoPoint
  112. }
  113. let geopoint = GeoPoint(latitude: 1, longitude: -2)
  114. assertThat(Model(p: geopoint)).roundTrips(to: ["p": geopoint])
  115. }
  116. func testDate() {
  117. struct Model: Codable, Equatable {
  118. let date: Date
  119. }
  120. let date = Date(timeIntervalSinceReferenceDate: 0)
  121. assertThat(Model(date: date)).roundTrips(to: ["date": date])
  122. }
  123. func testTimestampCanDecodeAsDate() {
  124. struct EncodingModel: Codable, Equatable {
  125. let date: Timestamp
  126. }
  127. struct DecodingModel: Codable, Equatable {
  128. let date: Date
  129. }
  130. let date = Date(timeIntervalSinceReferenceDate: 0)
  131. let timestamp = Timestamp(date: date)
  132. assertThat(EncodingModel(date: timestamp))
  133. .encodes(to: ["date": timestamp])
  134. .decodes(to: DecodingModel(date: date))
  135. }
  136. func testDocumentReference() {
  137. struct Model: Codable, Equatable {
  138. let doc: DocumentReference
  139. }
  140. let d = FSTTestDocRef("abc/xyz")
  141. assertThat(Model(doc: d)).roundTrips(to: ["doc": d])
  142. }
  143. func testEncodingDocumentReferenceThrowsWithJSONEncoder() {
  144. assertThat(FSTTestDocRef("abc/xyz")).failsEncodingWithJSONEncoder()
  145. }
  146. func testEncodingDocumentReferenceNotEmbeddedThrows() {
  147. assertThat(FSTTestDocRef("abc/xyz")).failsEncodingAtTopLevel()
  148. }
  149. func testTimestamp() {
  150. struct Model: Codable, Equatable {
  151. let timestamp: Timestamp
  152. }
  153. let t = Timestamp(date: Date())
  154. assertThat(Model(timestamp: t)).roundTrips(to: ["timestamp": t])
  155. }
  156. func testBadValue() {
  157. struct Model: Codable, Equatable {
  158. let x: Int
  159. }
  160. assertThat(["x": "abc"]).failsDecoding(to: Model.self) // Wrong type
  161. }
  162. func testValueTooBig() {
  163. struct Model: Codable, Equatable {
  164. let x: CChar
  165. }
  166. assertThat(Model(x: 42)).roundTrips(to: ["x": 42])
  167. assertThat(["x": 12345]).failsDecoding(to: Model.self) // Overflow
  168. }
  169. // Inspired by https://github.com/firebase/firebase-android-sdk/blob/master/firebase-firestore/src/test/java/com/google/firebase/firestore/util/MapperTest.java
  170. func testBeans() {
  171. struct Model: Codable, Equatable {
  172. let s: String
  173. let d: Double
  174. let f: Float
  175. let l: CLongLong
  176. let i: Int
  177. let b: Bool
  178. let sh: CShort
  179. let byte: CChar
  180. let uchar: CUnsignedChar
  181. let ai: [Int]
  182. let si: [String]
  183. let caseSensitive: String
  184. let casESensitive: String
  185. let casESensitivE: String
  186. }
  187. let model = Model(
  188. s: "abc",
  189. d: 123,
  190. f: -4,
  191. l: 1_234_567_890_123,
  192. i: -4444,
  193. b: false,
  194. sh: 123,
  195. byte: 45,
  196. uchar: 44,
  197. ai: [1, 2, 3, 4],
  198. si: ["abc", "def"],
  199. caseSensitive: "aaa",
  200. casESensitive: "bbb",
  201. casESensitivE: "ccc"
  202. )
  203. let dict = [
  204. "s": "abc",
  205. "d": 123,
  206. "f": -4,
  207. "l": Int64(1_234_567_890_123),
  208. "i": -4444,
  209. "b": false,
  210. "sh": 123,
  211. "byte": 45,
  212. "uchar": 44,
  213. "ai": [1, 2, 3, 4],
  214. "si": ["abc", "def"],
  215. "caseSensitive": "aaa",
  216. "casESensitive": "bbb",
  217. "casESensitivE": "ccc",
  218. ] as [String: Any]
  219. assertThat(model).roundTrips(to: dict)
  220. }
  221. func testCodingKeysCanCustomizeEncodingAndDecoding() throws {
  222. struct Model: Codable, Equatable {
  223. var s: String
  224. var ms: String = "filler"
  225. var d: Double
  226. var md: Double = 42.42
  227. // Use CodingKeys to only encode part of the struct.
  228. enum CodingKeys: String, CodingKey {
  229. case s
  230. case d
  231. }
  232. }
  233. assertThat(Model(s: "abc", ms: "dummy", d: 123.3, md: 0))
  234. .encodes(to: ["s": "abc", "d": 123.3])
  235. .decodes(to: Model(s: "abc", ms: "filler", d: 123.3, md: 42.42))
  236. }
  237. func testNestedObjects() {
  238. struct SecondLevelNestedModel: Codable, Equatable {
  239. var age: Int8
  240. var weight: Double
  241. }
  242. struct NestedModel: Codable, Equatable {
  243. var group: String
  244. var groupList: [SecondLevelNestedModel]
  245. var groupMap: [String: SecondLevelNestedModel]
  246. var point: GeoPoint
  247. }
  248. struct Model: Codable, Equatable {
  249. var id: Int64
  250. var group: NestedModel
  251. }
  252. let model = Model(
  253. id: 123,
  254. group: NestedModel(
  255. group: "g1",
  256. groupList: [
  257. SecondLevelNestedModel(age: 20, weight: 80.1),
  258. SecondLevelNestedModel(age: 25, weight: 85.1),
  259. ],
  260. groupMap: [
  261. "name1": SecondLevelNestedModel(age: 30, weight: 64.2),
  262. "name2": SecondLevelNestedModel(age: 35, weight: 79.2),
  263. ],
  264. point: GeoPoint(latitude: 12.0, longitude: 9.1)
  265. )
  266. )
  267. let dict = [
  268. "group": [
  269. "group": "g1",
  270. "point": GeoPoint(latitude: 12.0, longitude: 9.1),
  271. "groupList": [
  272. [
  273. "age": 20,
  274. "weight": 80.1,
  275. ],
  276. [
  277. "age": 25,
  278. "weight": 85.1,
  279. ],
  280. ],
  281. "groupMap": [
  282. "name1": [
  283. "age": 30,
  284. "weight": 64.2,
  285. ],
  286. "name2": [
  287. "age": 35,
  288. "weight": 79.2,
  289. ],
  290. ],
  291. ],
  292. "id": 123,
  293. ] as [String: Any]
  294. assertThat(model).roundTrips(to: dict)
  295. }
  296. func testCollapsingNestedObjects() {
  297. // The model is flat but the document has a nested Map.
  298. struct Model: Codable, Equatable {
  299. var id: Int64
  300. var name: String
  301. init(id: Int64, name: String) {
  302. self.id = id
  303. self.name = name
  304. }
  305. private enum CodingKeys: String, CodingKey {
  306. case id
  307. case nested
  308. }
  309. private enum NestedCodingKeys: String, CodingKey {
  310. case name
  311. }
  312. init(from decoder: Decoder) throws {
  313. let container = try decoder.container(keyedBy: CodingKeys.self)
  314. try id = container.decode(Int64.self, forKey: .id)
  315. let nestedContainer = try container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .nested)
  316. try name = nestedContainer.decode(String.self, forKey: .name)
  317. }
  318. func encode(to encoder: Encoder) throws {
  319. var container = encoder.container(keyedBy: CodingKeys.self)
  320. try container.encode(id, forKey: .id)
  321. var nestedContainer = container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .nested)
  322. try nestedContainer.encode(name, forKey: .name)
  323. }
  324. }
  325. assertThat(Model(id: 12345, name: "ModelName"))
  326. .roundTrips(to: [
  327. "id": 12345,
  328. "nested": ["name": "ModelName"],
  329. ])
  330. }
  331. class SuperModel: Codable, Equatable {
  332. var superPower: Double? = 100.0
  333. var superName: String? = "superName"
  334. init(power: Double, name: String) {
  335. superPower = power
  336. superName = name
  337. }
  338. static func == (lhs: SuperModel, rhs: SuperModel) -> Bool {
  339. return (lhs.superName == rhs.superName) && (lhs.superPower == rhs.superPower)
  340. }
  341. private enum CodingKeys: String, CodingKey {
  342. case superPower
  343. case superName
  344. }
  345. required init(from decoder: Decoder) throws {
  346. let container = try decoder.container(keyedBy: CodingKeys.self)
  347. superPower = try container.decode(Double.self, forKey: .superPower)
  348. superName = try container.decode(String.self, forKey: .superName)
  349. }
  350. func encode(to encoder: Encoder) throws {
  351. var container = encoder.container(keyedBy: CodingKeys.self)
  352. try container.encode(superPower, forKey: .superPower)
  353. try container.encode(superName, forKey: .superName)
  354. }
  355. }
  356. class SubModel: SuperModel {
  357. var timestamp: Timestamp? = Timestamp(seconds: 848_483_737, nanoseconds: 23423)
  358. init(power: Double, name: String, seconds: Int64, nano: Int32) {
  359. super.init(power: power, name: name)
  360. timestamp = Timestamp(seconds: seconds, nanoseconds: nano)
  361. }
  362. static func == (lhs: SubModel, rhs: SubModel) -> Bool {
  363. return ((lhs as SuperModel) == (rhs as SuperModel)) && (lhs.timestamp == rhs.timestamp)
  364. }
  365. private enum CodingKeys: String, CodingKey {
  366. case timestamp
  367. }
  368. required init(from decoder: Decoder) throws {
  369. let container = try decoder.container(keyedBy: CodingKeys.self)
  370. timestamp = try container.decode(Timestamp.self, forKey: .timestamp)
  371. try super.init(from: container.superDecoder())
  372. }
  373. override func encode(to encoder: Encoder) throws {
  374. var container = encoder.container(keyedBy: CodingKeys.self)
  375. try container.encode(timestamp, forKey: .timestamp)
  376. try super.encode(to: container.superEncoder())
  377. }
  378. }
  379. func testClassHierarchy() {
  380. assertThat(SubModel(power: 100, name: "name", seconds: 123_456_789, nano: 654_321))
  381. .roundTrips(to: [
  382. "super": ["superPower": 100, "superName": "name"],
  383. "timestamp": Timestamp(seconds: 123_456_789, nanoseconds: 654_321),
  384. ])
  385. }
  386. func testEncodingEncodableArrayNotSupported() {
  387. struct Model: Codable, Equatable {
  388. var name: String
  389. }
  390. assertThat([Model(name: "1")]).failsToEncode()
  391. }
  392. func testFieldValuePassthrough() throws {
  393. struct Model: Encodable, Equatable {
  394. var fieldValue: FieldValue
  395. }
  396. assertThat(Model(fieldValue: FieldValue.delete()))
  397. .encodes(to: ["fieldValue": FieldValue.delete()])
  398. }
  399. func testEncodingFieldValueNotEmbeddedThrows() {
  400. let ts = FieldValue.serverTimestamp()
  401. assertThat(ts).failsEncodingAtTopLevel()
  402. }
  403. #if swift(>=5.1)
  404. func testServerTimestamp() throws {
  405. struct Model: Codable, Equatable {
  406. @ServerTimestamp var timestamp: Timestamp? = nil
  407. }
  408. // Encoding a pending server timestamp
  409. assertThat(Model())
  410. .encodes(to: ["timestamp": FieldValue.serverTimestamp()])
  411. // Encoding a resolved server timestamp yields a timestamp; decoding
  412. // yields it back.
  413. let timestamp = Timestamp(seconds: 123_456_789, nanoseconds: 4321)
  414. assertThat(Model(timestamp: timestamp))
  415. .roundTrips(to: ["timestamp": timestamp])
  416. // Decoding a NSNull() leads to nil.
  417. assertThat(["timestamp": NSNull()])
  418. .decodes(to: Model(timestamp: nil))
  419. }
  420. func testServerTimestampUserType() throws {
  421. struct Model: Codable, Equatable {
  422. @ServerTimestamp var timestamp: String? = nil
  423. }
  424. // Encoding a pending server timestamp
  425. assertThat(Model())
  426. .encodes(to: ["timestamp": FieldValue.serverTimestamp()])
  427. // Encoding a resolved server timestamp yields a timestamp; decoding
  428. // yields it back.
  429. let timestamp = Timestamp(seconds: 1_570_484_031, nanoseconds: 122_999_906)
  430. assertThat(Model(timestamp: "2019-10-07T21:33:51.123Z"))
  431. .roundTrips(to: ["timestamp": timestamp])
  432. assertThat(Model(timestamp: "Invalid date"))
  433. .failsToEncode()
  434. }
  435. #endif // swift(>=5.1)
  436. @available(swift, deprecated: 5.1)
  437. func testSwift4ServerTimestamp() throws {
  438. struct Model: Codable, Equatable {
  439. var timestamp: Swift4ServerTimestamp
  440. }
  441. // Encoding a pending server timestamp
  442. assertThat(Model(timestamp: .pending))
  443. .encodes(to: ["timestamp": FieldValue.serverTimestamp()])
  444. // Encoding a resolved server timestamp yields a timestamp; decoding yields
  445. // it back.
  446. let timestamp = Timestamp(seconds: 123_456_789, nanoseconds: 4321)
  447. assertThat(Model(timestamp: .resolved(timestamp)))
  448. .roundTrips(to: ["timestamp": timestamp])
  449. // Decoding a NSNull() leads to nil.
  450. assertThat(["timestamp": NSNull()])
  451. .decodes(to: Model(timestamp: .pending))
  452. }
  453. #if swift(>=5.1)
  454. func testExplicitNull() throws {
  455. struct Model: Codable, Equatable {
  456. @ExplicitNull var name: String?
  457. }
  458. assertThat(Model(name: nil))
  459. .roundTrips(to: ["name": NSNull()])
  460. assertThat(Model(name: "good name"))
  461. .roundTrips(to: ["name": "good name"])
  462. }
  463. #endif // swift(>=5.1)
  464. @available(swift, deprecated: 5.1)
  465. func testSwift4ExplicitNull() throws {
  466. struct Model: Codable, Equatable {
  467. var name: Swift4ExplicitNull<String>
  468. }
  469. assertThat(Model(name: .none))
  470. .roundTrips(to: ["name": NSNull()])
  471. assertThat(Model(name: .some("good name")))
  472. .roundTrips(to: ["name": "good name"])
  473. }
  474. #if swift(>=5.1)
  475. func testAutomaticallyPopulatesDocumentIDOnDocumentReference() throws {
  476. struct Model: Codable, Equatable {
  477. var name: String
  478. @DocumentID var docId: DocumentReference?
  479. }
  480. assertThat(["name": "abc"], in: "abc/123")
  481. .decodes(to: Model(name: "abc", docId: FSTTestDocRef("abc/123")))
  482. }
  483. func testAutomaticallyPopulatesDocumentIDOnString() throws {
  484. struct Model: Codable, Equatable {
  485. var name: String
  486. @DocumentID var docId: String?
  487. }
  488. assertThat(["name": "abc"], in: "abc/123")
  489. .decodes(to: Model(name: "abc", docId: "123"))
  490. }
  491. func testDocumentIDIgnoredInEncoding() throws {
  492. struct Model: Codable, Equatable {
  493. var name: String
  494. @DocumentID var docId: DocumentReference?
  495. }
  496. assertThat(Model(name: "abc", docId: FSTTestDocRef("abc/123")))
  497. .encodes(to: ["name": "abc"])
  498. }
  499. func testDocumentIDWithJsonEncoderThrows() {
  500. assertThat(DocumentID(wrappedValue: FSTTestDocRef("abc/xyz")))
  501. .failsEncodingWithJSONEncoder()
  502. }
  503. func testDecodingDocumentIDWithConfictingFieldsThrows() throws {
  504. struct Model: Codable, Equatable {
  505. var name: String
  506. @DocumentID var docId: DocumentReference?
  507. }
  508. do {
  509. _ = try Firestore.Decoder().decode(
  510. Model.self,
  511. from: ["name": "abc", "docId": "Causing conflict"],
  512. in: FSTTestDocRef("abc/123")
  513. )
  514. XCTFail("Failed to throw")
  515. } catch let FirestoreDecodingError.fieldNameConfict(msg) {
  516. XCTAssertEqual(msg, "Field name [\"docId\"] was found from document \"abc/123\", "
  517. + "cannot assign the document reference to this field.")
  518. return
  519. } catch {
  520. XCTFail("Unrecognized error: \(error)")
  521. }
  522. }
  523. #endif // swift(>=5.1)
  524. }
  525. private func assertThat(_ dictionary: [String: Any], in document: String? = nil, file: StaticString = #file, line: UInt = #line) -> DictionarySubject {
  526. return DictionarySubject(dictionary, in: document, file: file, line: line)
  527. }
  528. private func assertThat<X: Equatable & Codable>(_ model: X, file: StaticString = #file, line: UInt = #line) -> CodableSubject<X> {
  529. return CodableSubject(model, file: file, line: line)
  530. }
  531. private func assertThat<X: Equatable & Encodable>(_ model: X, file: StaticString = #file, line: UInt = #line) -> EncodableSubject<X> {
  532. return EncodableSubject(model, file: file, line: line)
  533. }
  534. private class EncodableSubject<X: Equatable & Encodable> {
  535. var subject: X
  536. var file: StaticString
  537. var line: UInt
  538. init(_ subject: X, file: StaticString, line: UInt) {
  539. self.subject = subject
  540. self.file = file
  541. self.line = line
  542. }
  543. @discardableResult
  544. func encodes(to expected: [String: Any]) -> DictionarySubject {
  545. let encoded = assertEncodes(to: expected)
  546. return DictionarySubject(encoded, file: file, line: line)
  547. }
  548. func failsToEncode() {
  549. do {
  550. _ = try Firestore.Encoder().encode(subject)
  551. } catch {
  552. return
  553. }
  554. XCTFail("Failed to throw")
  555. }
  556. func failsEncodingWithJSONEncoder() {
  557. do {
  558. _ = try JSONEncoder().encode(subject)
  559. XCTFail("Failed to throw", file: file, line: line)
  560. } catch FirestoreEncodingError.encodingIsNotSupported {
  561. return
  562. } catch {
  563. XCTFail("Unrecognized error: \(error)", file: file, line: line)
  564. }
  565. }
  566. func failsEncodingAtTopLevel() {
  567. do {
  568. _ = try Firestore.Encoder().encode(subject)
  569. XCTFail("Failed to throw", file: file, line: line)
  570. } catch EncodingError.invalidValue(_, _) {
  571. return
  572. } catch {
  573. XCTFail("Unrecognized error: \(error)", file: file, line: line)
  574. }
  575. }
  576. private func assertEncodes(to expected: [String: Any]) -> [String: Any] {
  577. do {
  578. let enc = try Firestore.Encoder().encode(subject)
  579. XCTAssertEqual(enc as NSDictionary, expected as NSDictionary, file: file, line: line)
  580. return enc
  581. } catch {
  582. XCTFail("Failed to encode \(X.self): error: \(error)")
  583. return ["": -1]
  584. }
  585. }
  586. }
  587. private class CodableSubject<X: Equatable & Codable>: EncodableSubject<X> {
  588. func roundTrips(to expected: [String: Any]) {
  589. let reverseSubject = encodes(to: expected)
  590. reverseSubject.decodes(to: subject)
  591. }
  592. }
  593. private class DictionarySubject {
  594. var subject: [String: Any]
  595. var document: DocumentReference?
  596. var file: StaticString
  597. var line: UInt
  598. init(_ subject: [String: Any], in documentName: String? = nil, file: StaticString, line: UInt) {
  599. self.subject = subject
  600. if let documentName = documentName {
  601. document = FSTTestDocRef(documentName)
  602. }
  603. self.file = file
  604. self.line = line
  605. }
  606. func decodes<X: Equatable & Codable>(to expected: X) -> Void {
  607. do {
  608. let decoded = try Firestore.Decoder().decode(X.self, from: subject, in: document)
  609. XCTAssertEqual(decoded, expected)
  610. } catch {
  611. XCTFail("Failed to decode \(X.self): \(error)", file: file, line: line)
  612. }
  613. }
  614. func failsDecoding<X: Equatable & Codable>(to _: X.Type) -> Void {
  615. XCTAssertThrowsError(try Firestore.Decoder().decode(X.self, from: subject), file: file, line: line)
  616. }
  617. }
  618. #if swift(>=5.1)
  619. enum DateError: Error {
  620. case invalidDate(String)
  621. }
  622. // Extends Strings to allow them to be wrapped with @ServerTimestamp. Resolved
  623. // server timestamps will be stored in an ISO 8601 date format.
  624. //
  625. // This example exists outside the main implementation to show that users can
  626. // extend @ServerTimestamp with arbitrary types.
  627. extension String: ServerTimestampWrappable {
  628. static let formatter: DateFormatter = {
  629. let formatter = DateFormatter()
  630. formatter.calendar = Calendar(identifier: .iso8601)
  631. formatter.locale = Locale(identifier: "en_US_POSIX")
  632. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  633. formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
  634. return formatter
  635. }()
  636. public static func wrap(_ timestamp: Timestamp) throws -> Self {
  637. return formatter.string(from: timestamp.dateValue())
  638. }
  639. public static func unwrap(_ value: Self) throws -> Timestamp {
  640. let date = formatter.date(from: value)
  641. if let date = date {
  642. return Timestamp(date: date)
  643. } else {
  644. throw DateError.invalidDate(value)
  645. }
  646. }
  647. }
  648. #endif // swift(>=5.1)