CodableIntegrationTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright 2019 Google LLC
  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. class CodableIntegrationTests: FSTIntegrationTestCase {
  20. private enum WriteFlavor {
  21. case docRef
  22. case writeBatch
  23. case transaction
  24. }
  25. private let allFlavors: [WriteFlavor] = [.docRef, .writeBatch, .transaction]
  26. private func setData<T: Encodable>(from value: T,
  27. forDocument doc: DocumentReference,
  28. withFlavor flavor: WriteFlavor = .docRef,
  29. merge: Bool? = nil,
  30. mergeFields: [Any]? = nil) throws {
  31. let completion = completionForExpectation(withName: "setData")
  32. switch flavor {
  33. case .docRef:
  34. if let merge = merge {
  35. try doc.setData(from: value, merge: merge, completion: completion)
  36. } else if let mergeFields = mergeFields {
  37. try doc.setData(from: value, mergeFields: mergeFields, completion: completion)
  38. } else {
  39. try doc.setData(from: value, completion: completion)
  40. }
  41. case .writeBatch:
  42. if let merge = merge {
  43. try doc.firestore.batch().setData(from: value, forDocument: doc, merge: merge)
  44. .commit(completion: completion)
  45. } else if let mergeFields = mergeFields {
  46. try doc.firestore.batch().setData(from: value, forDocument: doc, mergeFields: mergeFields)
  47. .commit(completion: completion)
  48. } else {
  49. try doc.firestore.batch().setData(from: value, forDocument: doc)
  50. .commit(completion: completion)
  51. }
  52. case .transaction:
  53. doc.firestore.runTransaction({ transaction, errorPointer -> Any? in
  54. do {
  55. if let merge = merge {
  56. try transaction.setData(from: value, forDocument: doc, merge: merge)
  57. } else if let mergeFields = mergeFields {
  58. try transaction.setData(from: value, forDocument: doc, mergeFields: mergeFields)
  59. } else {
  60. try transaction.setData(from: value, forDocument: doc)
  61. }
  62. } catch {
  63. XCTFail("setData with transaction failed.")
  64. }
  65. return nil
  66. }) { object, error in
  67. completion(error)
  68. }
  69. }
  70. awaitExpectations()
  71. }
  72. func testCodableRoundTrip() throws {
  73. struct Model: Codable, Equatable {
  74. var name: String
  75. var age: Int32
  76. var ts: Timestamp
  77. var geoPoint: GeoPoint
  78. var docRef: DocumentReference
  79. }
  80. let docToWrite = documentRef()
  81. let model = Model(name: "test",
  82. age: 42,
  83. ts: Timestamp(seconds: 987_654_321, nanoseconds: 0),
  84. geoPoint: GeoPoint(latitude: 45, longitude: 54),
  85. docRef: docToWrite)
  86. for flavor in allFlavors {
  87. try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
  88. let readAfterWrite = try readDocument(forRef: docToWrite).data(as: Model.self)
  89. XCTAssertEqual(readAfterWrite, model, "Failed with flavor \(flavor)")
  90. }
  91. }
  92. func testServerTimestamp() throws {
  93. struct Model: Codable, Equatable {
  94. var name: String
  95. @ServerTimestamp var ts: Timestamp? = nil
  96. }
  97. let model = Model(name: "name")
  98. let docToWrite = documentRef()
  99. for flavor in allFlavors {
  100. try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
  101. let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
  102. XCTAssertNotNil(decoded.ts, "Failed with flavor \(flavor)")
  103. if let ts = decoded.ts {
  104. XCTAssertGreaterThan(ts.seconds, 1_500_000_000, "Failed with flavor \(flavor)")
  105. } else {
  106. XCTFail("Expect server timestamp is set, but getting .pending")
  107. }
  108. }
  109. }
  110. func testServerTimestampBehavior() throws {
  111. struct Model: Codable, Equatable {
  112. var name: String
  113. @ServerTimestamp var ts: Timestamp? = nil
  114. }
  115. disableNetwork()
  116. let docToWrite = documentRef()
  117. let now = Int64(Date().timeIntervalSince1970)
  118. let pastTimestamp = Timestamp(seconds: 807_940_800, nanoseconds: 0)
  119. // Write a document with a current value to enable testing with .previous.
  120. let originalModel = Model(name: "name", ts: pastTimestamp)
  121. let completion1 = completionForExpectation(withName: "setData")
  122. try docToWrite.setData(from: originalModel, completion: completion1)
  123. // Overwrite with a nil server timestamp so that ServerTimestampBehavior is testable.
  124. let newModel = Model(name: "name")
  125. let completion2 = completionForExpectation(withName: "setData")
  126. try docToWrite.setData(from: newModel, completion: completion2)
  127. let snapshot = readDocument(forRef: docToWrite)
  128. var decoded = try snapshot.data(as: Model.self, with: .none)
  129. XCTAssertNil(decoded.ts)
  130. decoded = try snapshot.data(as: Model.self, with: .estimate)
  131. XCTAssertNotNil(decoded.ts)
  132. XCTAssertNotNil(decoded.ts?.seconds)
  133. XCTAssertGreaterThanOrEqual(decoded.ts!.seconds, now)
  134. decoded = try snapshot.data(as: Model.self, with: .previous)
  135. XCTAssertNotNil(decoded.ts)
  136. XCTAssertNotNil(decoded.ts?.seconds)
  137. XCTAssertEqual(decoded.ts!.seconds, pastTimestamp.seconds)
  138. enableNetwork()
  139. awaitExpectations()
  140. }
  141. func testFieldValue() throws {
  142. struct Model: Encodable {
  143. var name: String
  144. var array: FieldValue
  145. var intValue: FieldValue
  146. }
  147. let model = Model(
  148. name: "name",
  149. array: FieldValue.arrayUnion([1, 2, 3]),
  150. intValue: FieldValue.increment(3 as Int64)
  151. )
  152. let docToWrite = documentRef()
  153. for flavor in allFlavors {
  154. try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
  155. let data = readDocument(forRef: docToWrite)
  156. XCTAssertEqual(data["array"] as! [Int], [1, 2, 3], "Failed with flavor \(flavor)")
  157. XCTAssertEqual(data["intValue"] as! Int, 3, "Failed with flavor \(flavor)")
  158. }
  159. }
  160. func testExplicitNull() throws {
  161. struct Model: Encodable {
  162. var name: String
  163. @ExplicitNull var explicitNull: String?
  164. var optional: String?
  165. }
  166. let model = Model(
  167. name: "name",
  168. explicitNull: nil,
  169. optional: nil
  170. )
  171. let docToWrite = documentRef()
  172. for flavor in allFlavors {
  173. try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
  174. let data = readDocument(forRef: docToWrite).data()
  175. XCTAssertTrue(data!.keys.contains("explicitNull"), "Failed with flavor \(flavor)")
  176. XCTAssertEqual(data!["explicitNull"] as! NSNull, NSNull(), "Failed with flavor \(flavor)")
  177. XCTAssertFalse(data!.keys.contains("optional"), "Failed with flavor \(flavor)")
  178. }
  179. }
  180. func testSelfDocumentID() throws {
  181. struct Model: Codable, Equatable {
  182. var name: String
  183. @DocumentID var docId: DocumentReference?
  184. }
  185. let docToWrite = documentRef()
  186. let model = Model(
  187. name: "name",
  188. docId: nil
  189. )
  190. try setData(from: model, forDocument: docToWrite, withFlavor: .docRef)
  191. let data = readDocument(forRef: docToWrite).data()
  192. // "docId" is ignored during encoding
  193. XCTAssertEqual(data! as! [String: String], ["name": "name"])
  194. // Decoded result has "docId" auto-populated.
  195. let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
  196. XCTAssertEqual(decoded, Model(name: "name", docId: docToWrite))
  197. }
  198. func testSelfDocumentIDWithCustomCodable() throws {
  199. struct Model: Codable, Equatable {
  200. var name: String
  201. @DocumentID var docId: DocumentReference?
  202. enum CodingKeys: String, CodingKey {
  203. case name
  204. case docId
  205. }
  206. public init(name: String, docId: DocumentReference?) {
  207. self.name = name
  208. self.docId = docId
  209. }
  210. public init(from decoder: Decoder) throws {
  211. let container = try decoder.container(keyedBy: CodingKeys.self)
  212. name = try container.decode(String.self, forKey: .name)
  213. docId = try container.decode(DocumentID<DocumentReference>.self, forKey: .docId)
  214. .wrappedValue
  215. }
  216. public func encode(to encoder: Encoder) throws {
  217. var container = encoder.container(keyedBy: CodingKeys.self)
  218. try container.encode(name, forKey: .name)
  219. // DocumentId should not be encoded when writing to Firestore; it's auto-populated when
  220. // reading.
  221. }
  222. }
  223. let docToWrite = documentRef()
  224. let model = Model(
  225. name: "name",
  226. docId: nil
  227. )
  228. try setData(from: model, forDocument: docToWrite, withFlavor: .docRef)
  229. let data = readDocument(forRef: docToWrite).data()
  230. // "docId" is ignored during encoding
  231. XCTAssertEqual(data! as! [String: String], ["name": "name"])
  232. // Decoded result has "docId" auto-populated.
  233. let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
  234. XCTAssertEqual(decoded, Model(name: "name", docId: docToWrite))
  235. }
  236. func testSetThenMerge() throws {
  237. struct Model: Codable, Equatable {
  238. var name: String? = nil
  239. var age: Int32? = nil
  240. var hobby: String? = nil
  241. }
  242. let docToWrite = documentRef()
  243. let model = Model(name: "test",
  244. age: 42, hobby: nil)
  245. // 'name' will be skipped in merge because it's Optional.
  246. let update = Model(name: nil, age: 43, hobby: "No")
  247. for flavor in allFlavors {
  248. try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
  249. try setData(from: update, forDocument: docToWrite, withFlavor: flavor, merge: true)
  250. var readAfterUpdate = try readDocument(forRef: docToWrite).data(as: Model.self)
  251. XCTAssertEqual(readAfterUpdate, Model(name: "test",
  252. age: 43, hobby: "No"), "Failed with flavor \(flavor)")
  253. let newUpdate = Model(name: "xxxx", age: 10, hobby: "Play")
  254. // Note 'name' is not updated.
  255. try setData(from: newUpdate, forDocument: docToWrite, withFlavor: flavor,
  256. mergeFields: ["age", FieldPath(["hobby"])])
  257. readAfterUpdate = try readDocument(forRef: docToWrite).data(as: Model.self)
  258. XCTAssertEqual(readAfterUpdate, Model(name: "test",
  259. age: 10,
  260. hobby: "Play"), "Failed with flavor \(flavor)")
  261. }
  262. }
  263. func testAddDocument() throws {
  264. struct Model: Codable, Equatable {
  265. var name: String
  266. }
  267. let collection = collectionRef()
  268. let model = Model(name: "test")
  269. let added = expectation(description: "Add document")
  270. let docRef = try collection.addDocument(from: model) { error in
  271. XCTAssertNil(error)
  272. added.fulfill()
  273. }
  274. awaitExpectations()
  275. let result = try readDocument(forRef: docRef).data(as: Model.self)
  276. XCTAssertEqual(model, result)
  277. }
  278. }