AggregationIntegrationTests.swift 12 KB

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