AggregationIntegrationTests.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. * Copyright 2023 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 FirebaseFirestore
  17. import FirebaseFirestoreSwift
  18. import Foundation
  19. // TODO(sum/avg) remove `sumAvgIsPublic` from the directive below to enable these tests when sum/avg is public
  20. #if sumAvgIsPublic && swift(>=5.5.2)
  21. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  22. class AggregationIntegrationTests: FSTIntegrationTestCase {
  23. func testCount() async throws {
  24. let collection = collectionRef()
  25. try await collection.addDocument(data: [:])
  26. let snapshot = try await collection.count.getAggregation(source: .server)
  27. XCTAssertEqual(snapshot.count, 1)
  28. }
  29. func testCanRunAggregateQuery() async throws {
  30. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  31. try XCTSkipIf(
  32. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  33. "only tested against emulator"
  34. )
  35. let collection = collectionRef()
  36. try await collection.addDocument(data: ["author": "authorA",
  37. "title": "titleA",
  38. "pages": 100,
  39. "height": 24.5,
  40. "weight": 24.1,
  41. "foo": 1,
  42. "bar": 2,
  43. "baz": 3])
  44. try await collection.addDocument(data: ["author": "authorB",
  45. "title": "titleB",
  46. "pages": 50,
  47. "height": 25.5,
  48. "weight": 75.5,
  49. "foo": 1,
  50. "bar": 2,
  51. "baz": 3])
  52. let snapshot = try await collection.aggregate([
  53. AggregateField.count(),
  54. AggregateField.sum("pages"),
  55. AggregateField.sum("weight"),
  56. AggregateField.average("pages"),
  57. AggregateField.average("weight"),
  58. ]).getAggregation(source: .server)
  59. // Count
  60. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 2)
  61. // Sum
  62. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? NSNumber, 150)
  63. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? Double, 150)
  64. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? Int64, 150)
  65. XCTAssertEqual(snapshot.get(AggregateField.sum("weight")) as? NSNumber, 99.6)
  66. XCTAssertEqual(snapshot.get(AggregateField.sum("weight")) as? Double, 99.6)
  67. // Average
  68. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? NSNumber, 75.0)
  69. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? Double, 75.0)
  70. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? Int64, 75)
  71. XCTAssertEqual(snapshot.get(AggregateField.average("weight")) as? NSNumber, 49.8)
  72. XCTAssertEqual(snapshot.get(AggregateField.average("weight")) as? Double, 49.8)
  73. }
  74. func testCannotPerformMoreThanMaxAggregations() async throws {
  75. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  76. try XCTSkipIf(
  77. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  78. "only tested against emulator"
  79. )
  80. let collection = collectionRef()
  81. try await collection.addDocument(data: ["author": "authorA",
  82. "title": "titleA",
  83. "pages": 100,
  84. "height": 24.5,
  85. "weight": 24.1,
  86. "foo": 1,
  87. "bar": 2,
  88. "baz": 3])
  89. // Max is 5, we're attempting 6. I also like to live dangerously.
  90. do {
  91. let snapshot = try await collection.aggregate([
  92. AggregateField.count(),
  93. AggregateField.sum("pages"),
  94. AggregateField.sum("weight"),
  95. AggregateField.average("pages"),
  96. AggregateField.average("weight"),
  97. AggregateField.average("foo"),
  98. ]).getAggregation(source: .server)
  99. XCTFail("Error expected.")
  100. } catch let error as NSError {
  101. XCTAssertNotNil(error)
  102. XCTAssertTrue(error.localizedDescription.contains("maximum number of aggregations"))
  103. }
  104. }
  105. func testPerformsAggregationsWhenNaNExistsForSomeFieldValues() async throws {
  106. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  107. try XCTSkipIf(
  108. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  109. "only tested against emulator"
  110. )
  111. let collection = collectionRef()
  112. try await collection.addDocument(data: ["author": "authorA",
  113. "title": "titleA",
  114. "pages": 100,
  115. "year": 1980,
  116. "rating": 4])
  117. try await collection.addDocument(data: ["author": "authorB",
  118. "title": "titleB",
  119. "pages": 50,
  120. "year": 2020,
  121. "rating": Double.nan])
  122. let snapshot = try await collection.aggregate([
  123. AggregateField.sum("pages"),
  124. AggregateField.sum("rating"),
  125. AggregateField.average("pages"),
  126. AggregateField.average("rating"),
  127. ]).getAggregation(source: .server)
  128. // Sum
  129. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? NSNumber, 150)
  130. XCTAssertTrue((snapshot.get(AggregateField.sum("rating")) as? Double)?.isNaN ?? false)
  131. // Average
  132. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? NSNumber, 75.0)
  133. XCTAssertTrue((snapshot.get(AggregateField.average("rating")) as? Double)?.isNaN ?? false)
  134. }
  135. func testThrowsAnErrorWhenGettingTheResultOfAnUnrequestedAggregation() async throws {
  136. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  137. try XCTSkipIf(
  138. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  139. "only tested against emulator"
  140. )
  141. let collection = collectionRef()
  142. try await collection.addDocument(data: [:])
  143. let snapshot = try await collection.aggregate([AggregateField.average("foo")])
  144. .getAggregation(source: .server)
  145. XCTAssertTrue(FSTNSExceptionUtil.testForException({
  146. snapshot.count
  147. }, reasonContains: "'count()' was not requested in the aggregation query"))
  148. XCTAssertTrue(FSTNSExceptionUtil.testForException({
  149. snapshot.get(AggregateField.sum("foo"))
  150. }, reasonContains: "'sum(foo)' was not requested in the aggregation query"))
  151. XCTAssertTrue(FSTNSExceptionUtil.testForException({
  152. snapshot.get(AggregateField.average("bar"))
  153. }, reasonContains: "'avg(bar)' was not requested in the aggregation query"))
  154. }
  155. func testPerformsAggregationsOnNestedMapValues() async throws {
  156. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  157. try XCTSkipIf(
  158. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  159. "only tested against emulator"
  160. )
  161. let collection = collectionRef()
  162. try await collection.addDocument(data: ["metadata": [
  163. "pages": 100,
  164. "rating": [
  165. "critic": 2,
  166. "user": 5,
  167. ],
  168. ]])
  169. try await collection.addDocument(data: ["metadata": [
  170. "pages": 50,
  171. "rating": [
  172. "critic": 4,
  173. "user": 4,
  174. ],
  175. ]])
  176. let snapshot = try await collection.aggregate([
  177. AggregateField.count(),
  178. AggregateField.sum("metadata.pages"),
  179. AggregateField.sum(FieldPath(["metadata", "rating", "user"])),
  180. AggregateField.average("metadata.pages"),
  181. AggregateField.average(FieldPath(["metadata", "rating", "critic"])),
  182. ]).getAggregation(source: .server)
  183. // Count
  184. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 2)
  185. // Sum
  186. XCTAssertEqual(
  187. snapshot.get(AggregateField.sum(FieldPath(["metadata", "pages"]))) as? NSNumber,
  188. 150
  189. )
  190. XCTAssertEqual(snapshot.get(AggregateField.sum("metadata.pages")) as? NSNumber, 150)
  191. XCTAssertEqual(snapshot.get(AggregateField.sum("metadata.rating.user")) as? NSNumber, 9)
  192. // Average
  193. XCTAssertEqual(
  194. snapshot.get(AggregateField.average(FieldPath(["metadata", "pages"]))) as? Double,
  195. 75.0
  196. )
  197. XCTAssertEqual(
  198. snapshot.get(AggregateField.average("metadata.rating.critic")) as? Double,
  199. 3.0
  200. )
  201. }
  202. func testSumOverflow() async throws {
  203. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  204. try XCTSkipIf(
  205. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  206. "only tested against emulator"
  207. )
  208. let collection = collectionRef()
  209. try await collection.addDocument(data: [
  210. "longOverflow": Int64.max,
  211. "accumulationOverflow": Int64.max,
  212. "positiveInfinity": Double.greatestFiniteMagnitude,
  213. "negativeInfinity": -Double.greatestFiniteMagnitude,
  214. ])
  215. try await collection.addDocument(data: [
  216. "longOverflow": Int64.max,
  217. "accumulationOverflow": 1,
  218. "positiveInfinity": Double.greatestFiniteMagnitude,
  219. "negativeInfinity": -Double.greatestFiniteMagnitude,
  220. ])
  221. try await collection.addDocument(data: [
  222. "longOverflow": Int64.max,
  223. "accumulationOverflow": -101,
  224. "positiveInfinity": Double.greatestFiniteMagnitude,
  225. "negativeInfinity": -Double.greatestFiniteMagnitude,
  226. ])
  227. let snapshot = try await collection.aggregate([
  228. AggregateField.sum("longOverflow"),
  229. AggregateField.sum("accumulationOverflow"),
  230. AggregateField.sum("positiveInfinity"),
  231. AggregateField.sum("negativeInfinity"),
  232. ]).getAggregation(source: .server)
  233. // Sum
  234. XCTAssertEqual(
  235. snapshot.get(AggregateField.sum("longOverflow")) as? Double,
  236. Double(Int64.max) + Double(Int64.max) + Double(Int64.max)
  237. )
  238. XCTAssertEqual(
  239. snapshot.get(AggregateField.sum("accumulationOverflow")) as? Int64,
  240. Int64.max - 100
  241. )
  242. XCTAssertEqual(
  243. snapshot.get(AggregateField.sum("positiveInfinity")) as? Double,
  244. Double.infinity
  245. )
  246. XCTAssertEqual(
  247. snapshot.get(AggregateField.sum("negativeInfinity")) as? Double,
  248. -Double.infinity
  249. )
  250. }
  251. func testAverageOverflow() async throws {
  252. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  253. try XCTSkipIf(
  254. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  255. "only tested against emulator"
  256. )
  257. let collection = collectionRef()
  258. try await collection.addDocument(data: [
  259. "longOverflow": Int64.max,
  260. "doubleOverflow": Double.greatestFiniteMagnitude,
  261. "negativeInfinity": -Double.greatestFiniteMagnitude,
  262. ])
  263. try await collection.addDocument(data: [
  264. "longOverflow": Int64.max,
  265. "doubleOverflow": Double.greatestFiniteMagnitude,
  266. "negativeInfinity": -Double.greatestFiniteMagnitude,
  267. ])
  268. try await collection.addDocument(data: [
  269. "longOverflow": Int64.max,
  270. "doubleOverflow": Double.greatestFiniteMagnitude,
  271. "negativeInfinity": -Double.greatestFiniteMagnitude,
  272. ])
  273. let snapshot = try await collection.aggregate([
  274. AggregateField.average("longOverflow"),
  275. AggregateField.average("doubleOverflow"),
  276. AggregateField.average("negativeInfinity"),
  277. ]).getAggregation(source: .server)
  278. // Average
  279. XCTAssertEqual(
  280. snapshot.get(AggregateField.average("longOverflow")) as? Double,
  281. Double(Int64.max)
  282. )
  283. XCTAssertEqual(
  284. snapshot.get(AggregateField.average("doubleOverflow")) as? Double,
  285. Double.infinity
  286. )
  287. XCTAssertEqual(
  288. snapshot.get(AggregateField.average("negativeInfinity")) as? Double,
  289. -Double.infinity
  290. )
  291. }
  292. func testAverageUnderflow() async throws {
  293. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  294. try XCTSkipIf(
  295. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  296. "only tested against emulator"
  297. )
  298. let collection = collectionRef()
  299. try await collection.addDocument(data: ["underflowSmall": Double.leastNonzeroMagnitude])
  300. try await collection.addDocument(data: ["underflowSmall": 0])
  301. let snapshot = try await collection.aggregate([AggregateField.average("underflowSmall")])
  302. .getAggregation(source: .server)
  303. // Average
  304. XCTAssertEqual(snapshot.get(AggregateField.average("underflowSmall")) as? Double, 0.0)
  305. }
  306. func testPerformsAggregateOverResultSetOfZeroDocuments() async throws {
  307. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  308. try XCTSkipIf(
  309. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  310. "only tested against emulator"
  311. )
  312. let collection = collectionRef()
  313. try await collection.addDocument(data: ["pages": 100])
  314. try await collection.addDocument(data: ["pages": 50])
  315. let snapshot = try await collection.whereField("pages", isGreaterThan: 200)
  316. .aggregate([AggregateField.count(), AggregateField.sum("pages"),
  317. AggregateField.average("pages")]).getAggregation(source: .server)
  318. // Count
  319. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 0)
  320. // Sum
  321. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? NSNumber, 0)
  322. // Average
  323. // TODO: (sum/avg) this design is bad, will require and API update
  324. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? NSNull, NSNull())
  325. }
  326. func testPerformsAggregateOverResultSetOfZeroFields() async throws {
  327. // TODO(sum/avg) remove the check below when sum and avg are supported in production
  328. try XCTSkipIf(
  329. !FSTIntegrationTestCase.isRunningAgainstEmulator(),
  330. "only tested against emulator"
  331. )
  332. let collection = collectionRef()
  333. try await collection.addDocument(data: ["pages": 100])
  334. try await collection.addDocument(data: ["pages": 50])
  335. let snapshot = try await collection
  336. .aggregate([AggregateField.count(), AggregateField.sum("notInMyDocs"),
  337. AggregateField.average("notInMyDocs")]).getAggregation(source: .server)
  338. // Count - 0 because aggregation is performed on documents matching the query AND documents that have all aggregated fields
  339. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 0)
  340. // Sum
  341. XCTAssertEqual(snapshot.get(AggregateField.sum("notInMyDocs")) as? NSNumber, 0)
  342. // Average
  343. // TODO: (sum/avg) this design is bad, will require and API update
  344. XCTAssertEqual(snapshot.get(AggregateField.average("notInMyDocs")) as? NSNull, NSNull())
  345. }
  346. }
  347. #endif