AggregationIntegrationTests.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  20. class AggregationIntegrationTests: FSTIntegrationTestCase {
  21. func testCount() async throws {
  22. let collection = collectionRef()
  23. try await collection.addDocument(data: [:])
  24. let snapshot = try await collection.count.getAggregation(source: .server)
  25. XCTAssertEqual(snapshot.count, 1)
  26. }
  27. func testCanRunAggregateQuery() async throws {
  28. let collection = collectionRef()
  29. try await collection.addDocument(data: ["author": "authorA",
  30. "title": "titleA",
  31. "pages": 100,
  32. "height": 24.5,
  33. "weight": 24.1,
  34. "foo": 1,
  35. "bar": 2,
  36. "baz": 3])
  37. try await collection.addDocument(data: ["author": "authorB",
  38. "title": "titleB",
  39. "pages": 50,
  40. "height": 25.5,
  41. "weight": 75.5,
  42. "foo": 1,
  43. "bar": 2,
  44. "baz": 3])
  45. let snapshot = try await collection.aggregate([
  46. AggregateField.count(),
  47. AggregateField.sum("pages"),
  48. AggregateField.average("pages"),
  49. ]).getAggregation(source: .server)
  50. // Count
  51. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 2)
  52. // Sum
  53. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? NSNumber, 150)
  54. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? Double, 150)
  55. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? Int64, 150)
  56. // Average
  57. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? NSNumber, 75.0)
  58. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? Double, 75.0)
  59. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? Int64, 75)
  60. }
  61. func testCannotPerformMoreThanMaxAggregations() async throws {
  62. let collection = collectionRef()
  63. try await collection.addDocument(data: ["author": "authorA",
  64. "title": "titleA",
  65. "pages": 100,
  66. "height": 24.5,
  67. "weight": 24.1,
  68. "foo": 1,
  69. "bar": 2,
  70. "baz": 3])
  71. // Max is 5, we're attempting 6. I also like to live dangerously.
  72. do {
  73. let snapshot = try await collection.aggregate([
  74. AggregateField.count(),
  75. AggregateField.sum("pages"),
  76. AggregateField.sum("weight"),
  77. AggregateField.average("pages"),
  78. AggregateField.average("weight"),
  79. AggregateField.average("foo"),
  80. ]).getAggregation(source: .server)
  81. XCTFail("Error expected.")
  82. } catch let error as NSError {
  83. XCTAssertNotNil(error)
  84. XCTAssertTrue(error.localizedDescription.contains("maximum number of aggregations"))
  85. }
  86. }
  87. func testPerformsAggregationsWhenNaNExistsForSomeFieldValues() async throws {
  88. try XCTSkipIf(!FSTIntegrationTestCase.isRunningAgainstEmulator(),
  89. "Skip this test if running against production because it requires a composite index.")
  90. let collection = collectionRef()
  91. try await collection.addDocument(data: ["author": "authorA",
  92. "title": "titleA",
  93. "pages": 100,
  94. "year": 1980,
  95. "rating": 4])
  96. try await collection.addDocument(data: ["author": "authorB",
  97. "title": "titleB",
  98. "pages": 50,
  99. "year": 2020,
  100. "rating": Double.nan])
  101. let snapshot = try await collection.aggregate([
  102. AggregateField.sum("pages"),
  103. AggregateField.sum("rating"),
  104. AggregateField.average("pages"),
  105. AggregateField.average("rating"),
  106. ]).getAggregation(source: .server)
  107. // Sum
  108. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? NSNumber, 150)
  109. XCTAssertTrue((snapshot.get(AggregateField.sum("rating")) as? Double)?.isNaN ?? false)
  110. // Average
  111. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? NSNumber, 75.0)
  112. XCTAssertTrue((snapshot.get(AggregateField.average("rating")) as? Double)?.isNaN ?? false)
  113. }
  114. func testThrowsAnErrorWhenGettingTheResultOfAnUnrequestedAggregation() async throws {
  115. let collection = collectionRef()
  116. try await collection.addDocument(data: [:])
  117. let snapshot = try await collection.aggregate([AggregateField.average("foo")])
  118. .getAggregation(source: .server)
  119. XCTAssertTrue(FSTNSExceptionUtil.testForException({
  120. snapshot.count
  121. }, reasonContains: "'count()' was not requested in the aggregation query"))
  122. XCTAssertTrue(FSTNSExceptionUtil.testForException({
  123. snapshot.get(AggregateField.sum("foo"))
  124. }, reasonContains: "'sum(foo)' was not requested in the aggregation query"))
  125. XCTAssertTrue(FSTNSExceptionUtil.testForException({
  126. snapshot.get(AggregateField.average("bar"))
  127. }, reasonContains: "'avg(bar)' was not requested in the aggregation query"))
  128. }
  129. func testPerformsAggregationsOnNestedMapValues() async throws {
  130. let collection = collectionRef()
  131. try await collection.addDocument(data: ["metadata": [
  132. "pages": 100,
  133. "rating": [
  134. "critic": 2,
  135. "user": 5,
  136. ],
  137. ]])
  138. try await collection.addDocument(data: ["metadata": [
  139. "pages": 50,
  140. "rating": [
  141. "critic": 4,
  142. "user": 4,
  143. ],
  144. ]])
  145. let snapshot = try await collection.aggregate([
  146. AggregateField.count(),
  147. AggregateField.sum("metadata.pages"),
  148. AggregateField.average("metadata.pages"),
  149. ]).getAggregation(source: .server)
  150. // Count
  151. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 2)
  152. // Sum
  153. XCTAssertEqual(
  154. snapshot.get(AggregateField.sum(FieldPath(["metadata", "pages"]))) as? NSNumber,
  155. 150
  156. )
  157. XCTAssertEqual(snapshot.get(AggregateField.sum("metadata.pages")) as? NSNumber, 150)
  158. // Average
  159. XCTAssertEqual(
  160. snapshot.get(AggregateField.average(FieldPath(["metadata", "pages"]))) as? Double,
  161. 75.0
  162. )
  163. }
  164. func testSumOverflow() async throws {
  165. try XCTSkipIf(!FSTIntegrationTestCase.isRunningAgainstEmulator(),
  166. "Skip this test if running against production because it requires a composite index.")
  167. let collection = collectionRef()
  168. try await collection.addDocument(data: [
  169. "longOverflow": Int64.max,
  170. "accumulationOverflow": Int64.max,
  171. "positiveInfinity": Double.greatestFiniteMagnitude,
  172. "negativeInfinity": -Double.greatestFiniteMagnitude,
  173. ])
  174. try await collection.addDocument(data: [
  175. "longOverflow": Int64.max,
  176. "accumulationOverflow": 1,
  177. "positiveInfinity": Double.greatestFiniteMagnitude,
  178. "negativeInfinity": -Double.greatestFiniteMagnitude,
  179. ])
  180. try await collection.addDocument(data: [
  181. "longOverflow": Int64.max,
  182. "accumulationOverflow": -101,
  183. "positiveInfinity": Double.greatestFiniteMagnitude,
  184. "negativeInfinity": -Double.greatestFiniteMagnitude,
  185. ])
  186. let snapshot = try await collection.aggregate([
  187. AggregateField.sum("longOverflow"),
  188. AggregateField.sum("accumulationOverflow"),
  189. AggregateField.sum("positiveInfinity"),
  190. AggregateField.sum("negativeInfinity"),
  191. ]).getAggregation(source: .server)
  192. // Sum
  193. XCTAssertEqual(
  194. snapshot.get(AggregateField.sum("longOverflow")) as? Double,
  195. Double(Int64.max) + Double(Int64.max) + Double(Int64.max)
  196. )
  197. XCTAssertEqual(
  198. snapshot.get(AggregateField.sum("accumulationOverflow")) as? Int64,
  199. Int64.max - 100
  200. )
  201. XCTAssertEqual(
  202. snapshot.get(AggregateField.sum("positiveInfinity")) as? Double,
  203. Double.infinity
  204. )
  205. XCTAssertEqual(
  206. snapshot.get(AggregateField.sum("negativeInfinity")) as? Double,
  207. -Double.infinity
  208. )
  209. }
  210. func testAverageOverflow() async throws {
  211. try XCTSkipIf(!FSTIntegrationTestCase.isRunningAgainstEmulator(),
  212. "Skip this test if running against production because it requires a composite index.")
  213. let collection = collectionRef()
  214. try await collection.addDocument(data: [
  215. "longOverflow": Int64.max,
  216. "doubleOverflow": Double.greatestFiniteMagnitude,
  217. "negativeInfinity": -Double.greatestFiniteMagnitude,
  218. ])
  219. try await collection.addDocument(data: [
  220. "longOverflow": Int64.max,
  221. "doubleOverflow": Double.greatestFiniteMagnitude,
  222. "negativeInfinity": -Double.greatestFiniteMagnitude,
  223. ])
  224. try await collection.addDocument(data: [
  225. "longOverflow": Int64.max,
  226. "doubleOverflow": Double.greatestFiniteMagnitude,
  227. "negativeInfinity": -Double.greatestFiniteMagnitude,
  228. ])
  229. let snapshot = try await collection.aggregate([
  230. AggregateField.average("longOverflow"),
  231. AggregateField.average("doubleOverflow"),
  232. AggregateField.average("negativeInfinity"),
  233. ]).getAggregation(source: .server)
  234. // Average
  235. XCTAssertEqual(
  236. snapshot.get(AggregateField.average("longOverflow")) as? Double,
  237. Double(Int64.max)
  238. )
  239. XCTAssertEqual(
  240. snapshot.get(AggregateField.average("doubleOverflow")) as? Double,
  241. Double.infinity
  242. )
  243. XCTAssertEqual(
  244. snapshot.get(AggregateField.average("negativeInfinity")) as? Double,
  245. -Double.infinity
  246. )
  247. }
  248. func testAverageUnderflow() async throws {
  249. let collection = collectionRef()
  250. try await collection.addDocument(data: ["underflowSmall": Double.leastNonzeroMagnitude])
  251. try await collection.addDocument(data: ["underflowSmall": 0])
  252. let snapshot = try await collection.aggregate([AggregateField.average("underflowSmall")])
  253. .getAggregation(source: .server)
  254. // Average
  255. XCTAssertEqual(snapshot.get(AggregateField.average("underflowSmall")) as? Double, 0.0)
  256. }
  257. func testPerformsAggregateOverResultSetOfZeroDocuments() async throws {
  258. let collection = collectionRef()
  259. try await collection.addDocument(data: ["pages": 100])
  260. try await collection.addDocument(data: ["pages": 50])
  261. let snapshot = try await collection.whereField("pages", isGreaterThan: 200)
  262. .aggregate([AggregateField.count(), AggregateField.sum("pages"),
  263. AggregateField.average("pages")]).getAggregation(source: .server)
  264. // Count
  265. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 0)
  266. // Sum
  267. XCTAssertEqual(snapshot.get(AggregateField.sum("pages")) as? NSNumber, 0)
  268. // Average
  269. XCTAssertEqual(snapshot.get(AggregateField.average("pages")) as? NSNull, NSNull())
  270. }
  271. func testPerformsAggregateOverResultSetOfZeroFields() async throws {
  272. let collection = collectionRef()
  273. try await collection.addDocument(data: ["pages": 100])
  274. try await collection.addDocument(data: ["pages": 50])
  275. let snapshot = try await collection
  276. .aggregate([AggregateField.count(), AggregateField.sum("notInMyDocs"),
  277. AggregateField.average("notInMyDocs")]).getAggregation(source: .server)
  278. // Count - 0 because aggregation is performed on documents matching the query AND documents
  279. // that have all aggregated fields
  280. XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 0)
  281. // Sum
  282. XCTAssertEqual(snapshot.get(AggregateField.sum("notInMyDocs")) as? NSNumber, 0)
  283. // Average
  284. XCTAssertEqual(snapshot.get(AggregateField.average("notInMyDocs")) as? NSNull, NSNull())
  285. }
  286. }