FIRQueryTests.mm 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  1. /*
  2. * Copyright 2017 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 <FirebaseFirestore/FirebaseFirestore.h>
  17. #import <XCTest/XCTest.h>
  18. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  19. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  20. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  21. #import "Firestore/Example/Tests/Util/FSTTestingHooks.h"
  22. // TODO(MIEQ) update these imports with public imports when aggregate types are public
  23. #import "Firestore/Source/API/FIRAggregateQuerySnapshot+Internal.h"
  24. #import "Firestore/Source/API/FIRQuery+Internal.h"
  25. @interface FIRQueryTests : FSTIntegrationTestCase
  26. @end
  27. @implementation FIRQueryTests
  28. /**
  29. * Checks that running the query while online (against the backend/emulator) results in the same
  30. * documents as running the query while offline. It also checks that both online and offline
  31. * query result is equal to the expected documents.
  32. *
  33. * @param query The query to check.
  34. * @param expectedDocs Array of document keys that are expected to match the query.
  35. */
  36. - (void)checkOnlineAndOfflineQuery:(FIRQuery *)query matchesResult:(NSArray *)expectedDocs {
  37. FIRQuerySnapshot *docsFromServer = [self readDocumentSetForRef:query
  38. source:FIRFirestoreSourceServer];
  39. FIRQuerySnapshot *docsFromCache = [self readDocumentSetForRef:query
  40. source:FIRFirestoreSourceCache];
  41. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(docsFromServer),
  42. FIRQuerySnapshotGetIDs(docsFromCache));
  43. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(docsFromCache), expectedDocs);
  44. }
  45. - (void)testLimitQueries {
  46. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  47. @"a" : @{@"k" : @"a"},
  48. @"b" : @{@"k" : @"b"},
  49. @"c" : @{@"k" : @"c"}
  50. }];
  51. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collRef queryLimitedTo:2]];
  52. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ @{@"k" : @"a"}, @{@"k" : @"b"} ]));
  53. }
  54. - (void)testLimitQueriesWithDescendingSortOrder {
  55. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  56. @"a" : @{@"k" : @"a", @"sort" : @0},
  57. @"b" : @{@"k" : @"b", @"sort" : @1},
  58. @"c" : @{@"k" : @"c", @"sort" : @1},
  59. @"d" : @{@"k" : @"d", @"sort" : @2},
  60. }];
  61. FIRQuerySnapshot *snapshot =
  62. [self readDocumentSetForRef:[[collRef queryOrderedByField:@"sort"
  63. descending:YES] queryLimitedTo:2]];
  64. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  65. (@[ @{@"k" : @"d", @"sort" : @2}, @{@"k" : @"c", @"sort" : @1} ]));
  66. }
  67. - (void)testLimitToLastMustAlsoHaveExplicitOrderBy {
  68. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{}];
  69. FIRQuery *query = [collRef queryLimitedToLast:2];
  70. FSTAssertThrows([query getDocumentsWithCompletion:^(FIRQuerySnapshot *, NSError *){
  71. }],
  72. @"limit(toLast:) queries require specifying at least one OrderBy() clause.");
  73. }
  74. // Two queries that mapped to the same target ID are referred to as
  75. // "mirror queries". An example for a mirror query is a limitToLast()
  76. // query and a limit() query that share the same backend Target ID.
  77. // Since limitToLast() queries are sent to the backend with a modified
  78. // orderBy() clause, they can map to the same target representation as
  79. // limit() query, even if both queries appear separate to the user.
  80. - (void)testListenUnlistenRelistenSequenceOfMirrorQueries {
  81. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  82. @"a" : @{@"k" : @"a", @"sort" : @0},
  83. @"b" : @{@"k" : @"b", @"sort" : @1},
  84. @"c" : @{@"k" : @"c", @"sort" : @1},
  85. @"d" : @{@"k" : @"d", @"sort" : @2},
  86. }];
  87. // Setup a `limit` query.
  88. FIRQuery *limit = [[collRef queryOrderedByField:@"sort" descending:NO] queryLimitedTo:2];
  89. FSTEventAccumulator *limitAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  90. id<FIRListenerRegistration> limitRegistration =
  91. [limit addSnapshotListener:limitAccumulator.valueEventHandler];
  92. // Setup a mirroring `limitToLast` query.
  93. FIRQuery *limitToLast = [[collRef queryOrderedByField:@"sort"
  94. descending:YES] queryLimitedToLast:2];
  95. FSTEventAccumulator *limitToLastAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  96. id<FIRListenerRegistration> limitToLastRegistration =
  97. [limitToLast addSnapshotListener:limitToLastAccumulator.valueEventHandler];
  98. // Verify both queries get expected result.
  99. FIRQuerySnapshot *snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  100. NSArray *expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1} ];
  101. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  102. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  103. expected = @[ @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"a", @"sort" : @0} ];
  104. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  105. // Unlisten then re-listen limit query.
  106. [limitRegistration remove];
  107. [limit addSnapshotListener:[limitAccumulator valueEventHandler]];
  108. // Verify limit query still works.
  109. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  110. expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1} ];
  111. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  112. // Add a document that would change the result set.
  113. [self addDocumentRef:collRef data:@{@"k" : @"e", @"sort" : @-1}];
  114. // Verify both queries get expected result.
  115. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  116. expected = @[ @{@"k" : @"e", @"sort" : @-1}, @{@"k" : @"a", @"sort" : @0} ];
  117. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  118. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  119. expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"e", @"sort" : @-1} ];
  120. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  121. // Unlisten to limitToLast, update a doc, then relisten to limitToLast
  122. [limitToLastRegistration remove];
  123. [self updateDocumentRef:[collRef documentWithPath:@"a"] data:@{@"k" : @"a", @"sort" : @-2}];
  124. [limitToLast addSnapshotListener:[limitToLastAccumulator valueEventHandler]];
  125. // Verify both queries get expected result.
  126. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  127. expected = @[ @{@"k" : @"a", @"sort" : @-2}, @{@"k" : @"e", @"sort" : @-1} ];
  128. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  129. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  130. expected = @[ @{@"k" : @"e", @"sort" : @-1}, @{@"k" : @"a", @"sort" : @-2} ];
  131. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  132. }
  133. - (void)testLimitToLastQueriesWithCursors {
  134. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  135. @"a" : @{@"k" : @"a", @"sort" : @0},
  136. @"b" : @{@"k" : @"b", @"sort" : @1},
  137. @"c" : @{@"k" : @"c", @"sort" : @1},
  138. @"d" : @{@"k" : @"d", @"sort" : @2},
  139. }];
  140. FIRQuerySnapshot *snapshot =
  141. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  142. queryEndingBeforeValues:@[ @2 ]]];
  143. XCTAssertEqualObjects(
  144. FIRQuerySnapshotGetData(snapshot), (@[
  145. @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}
  146. ]));
  147. snapshot = [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"]
  148. queryLimitedToLast:3] queryEndingAtValues:@[ @1 ]]];
  149. XCTAssertEqualObjects(
  150. FIRQuerySnapshotGetData(snapshot), (@[
  151. @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}
  152. ]));
  153. snapshot = [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"]
  154. queryLimitedToLast:3] queryStartingAtValues:@[ @2 ]]];
  155. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ @{@"k" : @"d", @"sort" : @2} ]));
  156. snapshot =
  157. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  158. queryStartingAfterValues:@[ @0 ]]];
  159. XCTAssertEqualObjects(
  160. FIRQuerySnapshotGetData(snapshot), (@[
  161. @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}, @{@"k" : @"d", @"sort" : @2}
  162. ]));
  163. snapshot =
  164. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  165. queryStartingAfterValues:@[ @-1 ]]];
  166. XCTAssertEqualObjects(
  167. FIRQuerySnapshotGetData(snapshot), (@[
  168. @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}, @{@"k" : @"d", @"sort" : @2}
  169. ]));
  170. }
  171. - (void)testKeyOrderIsDescendingForDescendingInequality {
  172. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  173. @"a" : @{@"foo" : @42},
  174. @"b" : @{@"foo" : @42.0},
  175. @"c" : @{@"foo" : @42},
  176. @"d" : @{@"foo" : @21},
  177. @"e" : @{@"foo" : @21.0},
  178. @"f" : @{@"foo" : @66},
  179. @"g" : @{@"foo" : @66.0},
  180. }];
  181. FIRQuerySnapshot *snapshot =
  182. [self readDocumentSetForRef:[[collRef queryWhereField:@"foo"
  183. isGreaterThan:@21] queryOrderedByField:@"foo"
  184. descending:YES]];
  185. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"g", @"f", @"c", @"b", @"a" ]));
  186. }
  187. - (void)testUnaryFilterQueries {
  188. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  189. @"a" : @{@"null" : [NSNull null], @"nan" : @(NAN)},
  190. @"b" : @{@"null" : [NSNull null], @"nan" : @0},
  191. @"c" : @{@"null" : @NO, @"nan" : @(NAN)}
  192. }];
  193. FIRQuerySnapshot *results =
  194. [self readDocumentSetForRef:[[collRef queryWhereField:@"null"
  195. isEqualTo:[NSNull null]] queryWhereField:@"nan"
  196. isEqualTo:@(NAN)]];
  197. XCTAssertEqualObjects(FIRQuerySnapshotGetData(results),
  198. (@[ @{@"null" : [NSNull null], @"nan" : @(NAN)} ]));
  199. }
  200. - (void)testQueryWithFieldPaths {
  201. FIRCollectionReference *collRef = [self
  202. collectionRefWithDocuments:@{@"a" : @{@"a" : @1}, @"b" : @{@"a" : @2}, @"c" : @{@"a" : @3}}];
  203. FIRQuery *query = [collRef queryWhereFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  204. isLessThan:@3];
  205. query = [query queryOrderedByFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  206. descending:YES];
  207. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  208. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"b", @"a" ]));
  209. }
  210. - (void)testQueryWithPredicate {
  211. FIRCollectionReference *collRef = [self
  212. collectionRefWithDocuments:@{@"a" : @{@"a" : @1}, @"b" : @{@"a" : @2}, @"c" : @{@"a" : @3}}];
  213. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"a < 3"];
  214. FIRQuery *query = [collRef queryFilteredUsingPredicate:predicate];
  215. query = [query queryOrderedByFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  216. descending:YES];
  217. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  218. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"b", @"a" ]));
  219. }
  220. - (void)testFilterOnInfinity {
  221. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  222. @"a" : @{@"inf" : @(INFINITY)},
  223. @"b" : @{@"inf" : @(-INFINITY)}
  224. }];
  225. FIRQuerySnapshot *results = [self readDocumentSetForRef:[collRef queryWhereField:@"inf"
  226. isEqualTo:@(INFINITY)]];
  227. XCTAssertEqualObjects(FIRQuerySnapshotGetData(results), (@[ @{@"inf" : @(INFINITY)} ]));
  228. }
  229. - (void)testCanExplicitlySortByDocumentID {
  230. NSDictionary *testDocs = @{
  231. @"a" : @{@"key" : @"a"},
  232. @"b" : @{@"key" : @"b"},
  233. @"c" : @{@"key" : @"c"},
  234. };
  235. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  236. // Ideally this would be descending to validate it's different than
  237. // the default, but that requires an extra index
  238. FIRQuerySnapshot *docs =
  239. [self readDocumentSetForRef:[collection queryOrderedByFieldPath:[FIRFieldPath documentID]]];
  240. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs),
  241. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"c"] ]));
  242. }
  243. - (void)testCanQueryByDocumentID {
  244. NSDictionary *testDocs = @{
  245. @"aa" : @{@"key" : @"aa"},
  246. @"ab" : @{@"key" : @"ab"},
  247. @"ba" : @{@"key" : @"ba"},
  248. @"bb" : @{@"key" : @"bb"},
  249. };
  250. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  251. FIRQuerySnapshot *docs =
  252. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  253. isEqualTo:@"ab"]];
  254. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  255. }
  256. - (void)testCanQueryByDocumentIDs {
  257. NSDictionary *testDocs = @{
  258. @"aa" : @{@"key" : @"aa"},
  259. @"ab" : @{@"key" : @"ab"},
  260. @"ba" : @{@"key" : @"ba"},
  261. @"bb" : @{@"key" : @"bb"},
  262. };
  263. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  264. FIRQuerySnapshot *docs =
  265. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  266. isEqualTo:@"ab"]];
  267. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  268. docs = [self readDocumentSetForRef:[[collection queryWhereFieldPath:[FIRFieldPath documentID]
  269. isGreaterThan:@"aa"]
  270. queryWhereFieldPath:[FIRFieldPath documentID]
  271. isLessThanOrEqualTo:@"ba"]];
  272. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"], testDocs[@"ba"] ]));
  273. }
  274. - (void)testCanQueryByDocumentIDsUsingRefs {
  275. NSDictionary *testDocs = @{
  276. @"aa" : @{@"key" : @"aa"},
  277. @"ab" : @{@"key" : @"ab"},
  278. @"ba" : @{@"key" : @"ba"},
  279. @"bb" : @{@"key" : @"bb"},
  280. };
  281. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  282. FIRQuerySnapshot *docs = [self
  283. readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  284. isEqualTo:[collection documentWithPath:@"ab"]]];
  285. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  286. docs = [self
  287. readDocumentSetForRef:[[collection queryWhereFieldPath:[FIRFieldPath documentID]
  288. isGreaterThan:[collection documentWithPath:@"aa"]]
  289. queryWhereFieldPath:[FIRFieldPath documentID]
  290. isLessThanOrEqualTo:[collection documentWithPath:@"ba"]]];
  291. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"], testDocs[@"ba"] ]));
  292. }
  293. - (void)testWatchSurvivesNetworkDisconnect {
  294. XCTestExpectation *testExpectiation =
  295. [self expectationWithDescription:@"testWatchSurvivesNetworkDisconnect"];
  296. FIRCollectionReference *collectionRef = [self collectionRef];
  297. FIRDocumentReference *docRef = [collectionRef documentWithAutoID];
  298. FIRFirestore *firestore = collectionRef.firestore;
  299. [collectionRef
  300. addSnapshotListenerWithIncludeMetadataChanges:YES
  301. listener:^(FIRQuerySnapshot *snapshot, NSError *error) {
  302. XCTAssertNil(error);
  303. if (!snapshot.empty && !snapshot.metadata.fromCache) {
  304. [testExpectiation fulfill];
  305. }
  306. }];
  307. [firestore disableNetworkWithCompletion:^(NSError *error) {
  308. XCTAssertNil(error);
  309. [docRef setData:@{@"foo" : @"bar"}];
  310. [firestore enableNetworkWithCompletion:^(NSError *error) {
  311. XCTAssertNil(error);
  312. }];
  313. }];
  314. [self awaitExpectations];
  315. }
  316. - (void)testQueriesFireFromCacheWhenOffline {
  317. NSDictionary *testDocs = @{
  318. @"a" : @{@"foo" : @1},
  319. };
  320. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  321. id<FIRListenerRegistration> registration = [collection
  322. addSnapshotListenerWithIncludeMetadataChanges:YES
  323. listener:self.eventAccumulator.valueEventHandler];
  324. FIRQuerySnapshot *querySnap = [self.eventAccumulator awaitEventWithName:@"initial event"];
  325. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnap), @[ @{@"foo" : @1} ]);
  326. XCTAssertEqual(querySnap.metadata.isFromCache, NO);
  327. [self disableNetwork];
  328. querySnap = [self.eventAccumulator awaitEventWithName:@"offline event with isFromCache=YES"];
  329. XCTAssertEqual(querySnap.metadata.isFromCache, YES);
  330. [self enableNetwork];
  331. querySnap = [self.eventAccumulator awaitEventWithName:@"back online event with isFromCache=NO"];
  332. XCTAssertEqual(querySnap.metadata.isFromCache, NO);
  333. [registration remove];
  334. }
  335. - (void)testQueriesCanRaiseInitialSnapshotFromCachedEmptyResults {
  336. FIRCollectionReference *collection = [self collectionRefWithDocuments:@{}];
  337. // Populate the cache with empty query result.
  338. FIRQuerySnapshot *querySnapshotA = [self readDocumentSetForRef:collection];
  339. XCTAssertFalse(querySnapshotA.metadata.fromCache);
  340. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotA), @[]);
  341. // Add a snapshot listener whose first event should be raised from cache.
  342. id<FIRListenerRegistration> registration = [collection
  343. addSnapshotListenerWithIncludeMetadataChanges:YES
  344. listener:self.eventAccumulator.valueEventHandler];
  345. FIRQuerySnapshot *querySnapshotB = [self.eventAccumulator awaitEventWithName:@"initial event"];
  346. XCTAssertTrue(querySnapshotB.metadata.fromCache);
  347. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotB), @[]);
  348. [registration remove];
  349. }
  350. - (void)testQueriesCanRaiseInitialSnapshotFromEmptyDueToDeleteCachedResults {
  351. NSDictionary *testDocs = @{
  352. @"a" : @{@"foo" : @1},
  353. };
  354. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  355. // Populate the cache with a single document.
  356. FIRQuerySnapshot *querySnapshotA = [self readDocumentSetForRef:collection];
  357. XCTAssertFalse(querySnapshotA.metadata.fromCache);
  358. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotA), @[ @{@"foo" : @1} ]);
  359. // Delete the document, making the cached query result empty.
  360. FIRDocumentReference *docRef = [collection documentWithPath:@"a"];
  361. [self deleteDocumentRef:docRef];
  362. // Add a snapshot listener whose first event should be raised from cache.
  363. id<FIRListenerRegistration> registration = [collection
  364. addSnapshotListenerWithIncludeMetadataChanges:YES
  365. listener:self.eventAccumulator.valueEventHandler];
  366. FIRQuerySnapshot *querySnapshotB = [self.eventAccumulator awaitEventWithName:@"initial event"];
  367. XCTAssertTrue(querySnapshotB.metadata.fromCache);
  368. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotB), @[]);
  369. [registration remove];
  370. }
  371. - (void)testDocumentChangesUseNSNotFound {
  372. NSDictionary *testDocs = @{
  373. @"a" : @{@"foo" : @1},
  374. };
  375. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  376. id<FIRListenerRegistration> registration =
  377. [collection addSnapshotListener:self.eventAccumulator.valueEventHandler];
  378. FIRQuerySnapshot *querySnap = [self.eventAccumulator awaitEventWithName:@"initial event"];
  379. XCTAssertEqual(querySnap.documentChanges.count, 1ul);
  380. FIRDocumentChange *change = querySnap.documentChanges[0];
  381. XCTAssertEqual(change.oldIndex, NSNotFound);
  382. XCTAssertEqual(change.newIndex, 0ul);
  383. FIRDocumentReference *doc = change.document.reference;
  384. [self deleteDocumentRef:doc];
  385. querySnap = [self.eventAccumulator awaitEventWithName:@"delete"];
  386. XCTAssertEqual(querySnap.documentChanges.count, 1ul);
  387. change = querySnap.documentChanges[0];
  388. XCTAssertEqual(change.oldIndex, 0ul);
  389. XCTAssertEqual(change.newIndex, NSNotFound);
  390. [registration remove];
  391. }
  392. - (void)testCanHaveMultipleMutationsWhileOffline {
  393. FIRCollectionReference *col = [self collectionRef];
  394. // set a few docs to known values
  395. NSDictionary *initialDocs = @{@"doc1" : @{@"key1" : @"value1"}, @"doc2" : @{@"key2" : @"value2"}};
  396. [self writeAllDocuments:initialDocs toCollection:col];
  397. // go offline for the rest of this test
  398. [self disableNetwork];
  399. // apply *multiple* mutations while offline
  400. [[col documentWithPath:@"doc1"] setData:@{@"key1b" : @"value1b"}];
  401. [[col documentWithPath:@"doc2"] setData:@{@"key2b" : @"value2b"}];
  402. FIRQuerySnapshot *result = [self readDocumentSetForRef:col];
  403. XCTAssertEqualObjects(FIRQuerySnapshotGetData(result), (@[
  404. @{@"key1b" : @"value1b"},
  405. @{@"key2b" : @"value2b"},
  406. ]));
  407. }
  408. - (void)testQueriesCanUseNotEqualFilters {
  409. // These documents are ordered by value in "zip" since notEquals filter is an inequality, which
  410. // results in documents being sorted by value.
  411. NSDictionary *testDocs = @{
  412. @"a" : @{@"zip" : @(NAN)},
  413. @"b" : @{@"zip" : @91102},
  414. @"c" : @{@"zip" : @98101},
  415. @"d" : @{@"zip" : @98103},
  416. @"e" : @{@"zip" : @[ @98101 ]},
  417. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  418. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  419. @"h" : @{@"zip" : @{@"code" : @500}},
  420. @"i" : @{@"zip" : [NSNull null]},
  421. @"j" : @{@"code" : @500},
  422. };
  423. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  424. // Search for zips not matching 98101.
  425. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  426. isNotEqualTo:@98101]];
  427. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  428. testDocs[@"a"], testDocs[@"b"], testDocs[@"d"], testDocs[@"e"],
  429. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  430. ]));
  431. // With objects.
  432. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  433. isNotEqualTo:@{@"code" : @500}]];
  434. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  435. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  436. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"]
  437. ]));
  438. // With null.
  439. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  440. isNotEqualTo:@[ [NSNull null] ]]];
  441. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  442. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  443. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  444. ]));
  445. // With NAN.
  446. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" isNotEqualTo:@(NAN)]];
  447. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  448. testDocs[@"b"], testDocs[@"c"], testDocs[@"d"], testDocs[@"e"],
  449. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  450. ]));
  451. }
  452. - (void)testQueriesCanUseNotEqualFiltersWithDocIds {
  453. NSDictionary *testDocs = @{
  454. @"aa" : @{@"key" : @"aa"},
  455. @"ab" : @{@"key" : @"ab"},
  456. @"ba" : @{@"key" : @"ba"},
  457. @"bb" : @{@"key" : @"bb"},
  458. };
  459. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  460. FIRQuerySnapshot *snapshot =
  461. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  462. isNotEqualTo:@"aa"]];
  463. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  464. (@[ testDocs[@"ab"], testDocs[@"ba"], testDocs[@"bb"] ]));
  465. }
  466. - (void)testQueriesCanUseArrayContainsFilters {
  467. NSDictionary *testDocs = @{
  468. @"a" : @{@"array" : @[ @42 ]},
  469. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  470. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  471. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  472. @"e" : @{@"array" : @[ [NSNull null] ]},
  473. @"f" : @{@"array" : @[ @(NAN) ]},
  474. };
  475. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  476. // Search for 42
  477. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  478. arrayContains:@42]];
  479. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  480. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"] ]));
  481. // With null.
  482. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  483. arrayContains:[NSNull null]]];
  484. XCTAssertTrue(snapshot.isEmpty);
  485. // With NAN.
  486. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  487. arrayContains:@(NAN)]];
  488. XCTAssertTrue(snapshot.isEmpty);
  489. }
  490. - (void)testQueriesCanUseInFilters {
  491. NSDictionary *testDocs = @{
  492. @"a" : @{@"zip" : @98101},
  493. @"b" : @{@"zip" : @91102},
  494. @"c" : @{@"zip" : @98103},
  495. @"d" : @{@"zip" : @[ @98101 ]},
  496. @"e" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  497. @"f" : @{@"zip" : @{@"code" : @500}},
  498. @"g" : @{@"zip" : @[ @98101, @98102 ]},
  499. @"h" : @{@"zip" : [NSNull null]},
  500. @"i" : @{@"zip" : @(NAN)}
  501. };
  502. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  503. // Search for zips matching 98101, 98103, and [98101, 98102].
  504. FIRQuerySnapshot *snapshot = [self
  505. readDocumentSetForRef:[collection queryWhereField:@"zip"
  506. in:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  507. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  508. (@[ testDocs[@"a"], testDocs[@"c"], testDocs[@"g"] ]));
  509. // With objects
  510. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  511. in:@[ @{@"code" : @500} ]]];
  512. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"f"] ]));
  513. // With null.
  514. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ [NSNull null] ]]];
  515. XCTAssertTrue(snapshot.isEmpty);
  516. // With null and a value.
  517. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  518. in:@[ [NSNull null], @98101 ]]];
  519. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  520. // With NAN.
  521. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ @(NAN) ]]];
  522. XCTAssertTrue(snapshot.isEmpty);
  523. // With NAN and a value.
  524. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  525. in:@[ @(NAN), @98101 ]]];
  526. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  527. }
  528. - (void)testQueriesCanUseInFiltersWithDocIds {
  529. NSDictionary *testDocs = @{
  530. @"aa" : @{@"key" : @"aa"},
  531. @"ab" : @{@"key" : @"ab"},
  532. @"ba" : @{@"key" : @"ba"},
  533. @"bb" : @{@"key" : @"bb"},
  534. };
  535. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  536. FIRQuerySnapshot *snapshot =
  537. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  538. in:@[ @"aa", @"ab" ]]];
  539. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"aa"], testDocs[@"ab"] ]));
  540. }
  541. - (void)testQueriesCanUseNotInFilters {
  542. // These documents are ordered by value in "zip" since the NOT_IN filter is an inequality, which
  543. // results in documents being sorted by value.
  544. NSDictionary *testDocs = @{
  545. @"a" : @{@"zip" : @(NAN)},
  546. @"b" : @{@"zip" : @91102},
  547. @"c" : @{@"zip" : @98101},
  548. @"d" : @{@"zip" : @98103},
  549. @"e" : @{@"zip" : @[ @98101 ]},
  550. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  551. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  552. @"h" : @{@"zip" : @{@"code" : @500}},
  553. @"i" : @{@"zip" : [NSNull null]},
  554. @"j" : @{@"code" : @500},
  555. };
  556. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  557. // Search for zips not matching 98101, 98103, and [98101, 98102].
  558. FIRQuerySnapshot *snapshot = [self
  559. readDocumentSetForRef:[collection queryWhereField:@"zip"
  560. notIn:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  561. XCTAssertEqualObjects(
  562. FIRQuerySnapshotGetData(snapshot),
  563. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"e"], testDocs[@"g"], testDocs[@"h"] ]));
  564. // With objects.
  565. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  566. notIn:@[ @{@"code" : @500} ]]];
  567. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  568. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  569. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"]
  570. ]));
  571. // With null.
  572. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  573. notIn:@[ [NSNull null] ]]];
  574. XCTAssertTrue(snapshot.isEmpty);
  575. // With NAN.
  576. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" notIn:@[ @(NAN) ]]];
  577. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  578. testDocs[@"b"], testDocs[@"c"], testDocs[@"d"], testDocs[@"e"],
  579. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  580. ]));
  581. // With NAN and a number.
  582. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  583. notIn:@[ @(NAN), @98101 ]]];
  584. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  585. testDocs[@"b"], testDocs[@"d"], testDocs[@"e"], testDocs[@"f"],
  586. testDocs[@"g"], testDocs[@"h"]
  587. ]));
  588. }
  589. - (void)testQueriesCanUseNotInFiltersWithDocIds {
  590. NSDictionary *testDocs = @{
  591. @"aa" : @{@"key" : @"aa"},
  592. @"ab" : @{@"key" : @"ab"},
  593. @"ba" : @{@"key" : @"ba"},
  594. @"bb" : @{@"key" : @"bb"},
  595. };
  596. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  597. FIRQuerySnapshot *snapshot =
  598. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  599. notIn:@[ @"aa", @"ab" ]]];
  600. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"ba"], testDocs[@"bb"] ]));
  601. }
  602. - (void)testQueriesCanUseArrayContainsAnyFilters {
  603. NSDictionary *testDocs = @{
  604. @"a" : @{@"array" : @[ @42 ]},
  605. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  606. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  607. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  608. @"e" : @{@"array" : @[ @43 ]},
  609. @"f" : @{@"array" : @[ @{@"a" : @42} ]},
  610. @"g" : @{@"array" : @42},
  611. @"h" : @{@"array" : @[ [NSNull null] ]},
  612. @"i" : @{@"array" : @[ @(NAN) ]},
  613. };
  614. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  615. // Search for zips matching [42, 43].
  616. FIRQuerySnapshot *snapshot = [self
  617. readDocumentSetForRef:[collection queryWhereField:@"array" arrayContainsAny:@[ @42, @43 ]]];
  618. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  619. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"], testDocs[@"e"] ]));
  620. // With objects.
  621. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  622. arrayContainsAny:@[ @{@"a" : @42} ]]];
  623. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  624. testDocs[@"f"],
  625. ]));
  626. // With null.
  627. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  628. arrayContainsAny:@[ [NSNull null] ]]];
  629. XCTAssertTrue(snapshot.isEmpty);
  630. // With null and a value.
  631. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  632. arrayContainsAny:@[ [NSNull null], @43 ]]];
  633. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  634. // With NAN.
  635. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  636. arrayContainsAny:@[ @(NAN) ]]];
  637. XCTAssertTrue(snapshot.isEmpty);
  638. // With NAN and a value.
  639. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  640. arrayContainsAny:@[ @(NAN), @43 ]]];
  641. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  642. }
  643. - (void)testCollectionGroupQueries {
  644. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  645. // for predictable ordering.
  646. NSString *collectionGroup = [NSString
  647. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  648. NSArray *docPaths = @[
  649. @"abc/123/${collectionGroup}/cg-doc1", @"abc/123/${collectionGroup}/cg-doc2",
  650. @"${collectionGroup}/cg-doc3", @"${collectionGroup}/cg-doc4",
  651. @"def/456/${collectionGroup}/cg-doc5", @"${collectionGroup}/virtual-doc/nested-coll/not-cg-doc",
  652. @"x${collectionGroup}/not-cg-doc", @"${collectionGroup}x/not-cg-doc",
  653. @"abc/123/${collectionGroup}x/not-cg-doc", @"abc/123/x${collectionGroup}/not-cg-doc",
  654. @"abc/${collectionGroup}"
  655. ];
  656. FIRWriteBatch *batch = [self.db batch];
  657. for (NSString *docPath in docPaths) {
  658. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  659. withString:collectionGroup];
  660. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  661. }
  662. [self commitWriteBatch:batch];
  663. FIRQuerySnapshot *querySnapshot =
  664. [self readDocumentSetForRef:[self.db collectionGroupWithID:collectionGroup]];
  665. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  666. XCTAssertEqualObjects(ids, (@[ @"cg-doc1", @"cg-doc2", @"cg-doc3", @"cg-doc4", @"cg-doc5" ]));
  667. }
  668. - (void)testCollectionGroupQueriesWithStartAtEndAtWithArbitraryDocumentIDs {
  669. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  670. // for predictable ordering.
  671. NSString *collectionGroup = [NSString
  672. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  673. NSArray *docPaths = @[
  674. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  675. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  676. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  677. ];
  678. FIRWriteBatch *batch = [self.db batch];
  679. for (NSString *docPath in docPaths) {
  680. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  681. withString:collectionGroup];
  682. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  683. }
  684. [self commitWriteBatch:batch];
  685. FIRQuerySnapshot *querySnapshot = [self
  686. readDocumentSetForRef:[[[[self.db collectionGroupWithID:collectionGroup]
  687. queryOrderedByFieldPath:[FIRFieldPath documentID]]
  688. queryStartingAfterValues:@[ @"a/b" ]]
  689. queryEndingBeforeValues:@[
  690. [NSString stringWithFormat:@"a/b/%@/cg-doc3", collectionGroup]
  691. ]]];
  692. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  693. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  694. }
  695. - (void)testCollectionGroupQueriesWithWhereFiltersOnArbitraryDocumentIDs {
  696. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  697. // for predictable ordering.
  698. NSString *collectionGroup = [NSString
  699. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  700. NSArray *docPaths = @[
  701. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  702. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  703. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  704. ];
  705. FIRWriteBatch *batch = [self.db batch];
  706. for (NSString *docPath in docPaths) {
  707. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  708. withString:collectionGroup];
  709. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  710. }
  711. [self commitWriteBatch:batch];
  712. FIRQuerySnapshot *querySnapshot = [self
  713. readDocumentSetForRef:[[[self.db collectionGroupWithID:collectionGroup]
  714. queryWhereFieldPath:[FIRFieldPath documentID]
  715. isGreaterThanOrEqualTo:@"a/b"]
  716. queryWhereFieldPath:[FIRFieldPath documentID]
  717. isLessThan:[NSString stringWithFormat:@"a/b/%@/cg-doc3",
  718. collectionGroup]]];
  719. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  720. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  721. }
  722. - (void)testOrQueries {
  723. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  724. @"doc1" : @{@"a" : @1, @"b" : @0},
  725. @"doc2" : @{@"a" : @2, @"b" : @1},
  726. @"doc3" : @{@"a" : @3, @"b" : @2},
  727. @"doc4" : @{@"a" : @1, @"b" : @3},
  728. @"doc5" : @{@"a" : @1, @"b" : @1}
  729. }];
  730. // Two equalities: a==1 || b==1.
  731. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  732. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  733. ]];
  734. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  735. matchesResult:@[ @"doc1", @"doc2", @"doc4", @"doc5" ]];
  736. // (a==1 && b==0) || (a==3 && b==2)
  737. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  738. [FIRFilter andFilterWithFilters:@[
  739. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@0]
  740. ]],
  741. [FIRFilter andFilterWithFilters:@[
  742. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  743. ]]
  744. ]];
  745. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  746. matchesResult:@[ @"doc1", @"doc3" ]];
  747. // a==1 && (b==0 || b==3).
  748. FIRFilter *filter3 = [FIRFilter andFilterWithFilters:@[
  749. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter orFilterWithFilters:@[
  750. [FIRFilter filterWhereField:@"b" isEqualTo:@0], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  751. ]]
  752. ]];
  753. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  754. matchesResult:@[ @"doc1", @"doc4" ]];
  755. // (a==2 || b==2) && (a==3 || b==3)
  756. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  757. [FIRFilter orFilterWithFilters:@[
  758. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  759. ]],
  760. [FIRFilter orFilterWithFilters:@[
  761. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  762. ]]
  763. ]];
  764. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  765. // Test with limits without orderBy (the __name__ ordering is the tie breaker).
  766. FIRFilter *filter5 = [FIRFilter orFilterWithFilters:@[
  767. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  768. ]];
  769. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:filter5] queryLimitedTo:1]
  770. matchesResult:@[ @"doc2" ]];
  771. }
  772. - (void)testOrQueriesWithCompositeIndexes {
  773. // TODO(orquery): Enable this test against production when possible.
  774. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  775. "Skip this test because prod testing with composite indexes is not supported yet.");
  776. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  777. @"doc1" : @{@"a" : @1, @"b" : @0},
  778. @"doc2" : @{@"a" : @2, @"b" : @1},
  779. @"doc3" : @{@"a" : @3, @"b" : @2},
  780. @"doc4" : @{@"a" : @1, @"b" : @3},
  781. @"doc5" : @{@"a" : @1, @"b" : @1}
  782. }];
  783. // with one inequality: a>2 || b==1.
  784. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  785. [FIRFilter filterWhereField:@"a" isGreaterThan:@2], [FIRFilter filterWhereField:@"b"
  786. isEqualTo:@1]
  787. ]];
  788. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  789. matchesResult:@[ @"doc5", @"doc2", @"doc3" ]];
  790. // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2
  791. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  792. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b"
  793. isGreaterThan:@0]
  794. ]];
  795. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:filter2] queryLimitedTo:2]
  796. matchesResult:@[ @"doc1", @"doc2" ]];
  797. // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2
  798. // Note: The public query API does not allow implicit ordering when limitToLast is used.
  799. FIRFilter *filter3 = [FIRFilter orFilterWithFilters:@[
  800. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b"
  801. isGreaterThan:@0]
  802. ]];
  803. [self checkOnlineAndOfflineQuery:[[[collRef queryWhereFilter:filter3] queryLimitedToLast:2]
  804. queryOrderedByField:@"b"]
  805. matchesResult:@[ @"doc3", @"doc4" ]];
  806. // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1
  807. FIRFilter *filter4 = [FIRFilter orFilterWithFilters:@[
  808. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  809. ]];
  810. [self checkOnlineAndOfflineQuery:[[[collRef queryWhereFilter:filter4] queryLimitedTo:1]
  811. queryOrderedByField:@"a"]
  812. matchesResult:@[ @"doc5" ]];
  813. // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT_TO_LAST 1
  814. FIRFilter *filter5 = [FIRFilter orFilterWithFilters:@[
  815. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  816. ]];
  817. [self checkOnlineAndOfflineQuery:[[[collRef queryWhereFilter:filter5] queryLimitedToLast:1]
  818. queryOrderedByField:@"a"]
  819. matchesResult:@[ @"doc2" ]];
  820. }
  821. - (void)testOrQueriesWithIn {
  822. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  823. @"doc1" : @{@"a" : @1, @"b" : @0},
  824. @"doc2" : @{@"b" : @1},
  825. @"doc3" : @{@"a" : @3, @"b" : @2},
  826. @"doc4" : @{@"a" : @1, @"b" : @3},
  827. @"doc5" : @{@"a" : @1},
  828. @"doc6" : @{@"a" : @2}
  829. }];
  830. // a==2 || b in [2,3]
  831. FIRFilter *filter = [FIRFilter orFilterWithFilters:@[
  832. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" in:@[ @2, @3 ]]
  833. ]];
  834. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  835. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  836. }
  837. - (void)testOrQueriesWithArrayMembership {
  838. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  839. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  840. @"doc2" : @{@"b" : @[ @1 ]},
  841. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  842. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  843. @"doc5" : @{@"a" : @1},
  844. @"doc6" : @{@"a" : @2}
  845. }];
  846. // a==2 || b array-contains 7
  847. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  848. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  849. arrayContains:@7]
  850. ]];
  851. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  852. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  853. // a==2 || b array-contains-any [0, 3]
  854. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  855. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  856. arrayContainsAny:@[ @0, @3 ]]
  857. ]];
  858. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  859. matchesResult:@[ @"doc1", @"doc4", @"doc6" ]];
  860. }
  861. - (void)testMultipleInOps {
  862. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  863. @"doc1" : @{@"a" : @1, @"b" : @0},
  864. @"doc2" : @{@"b" : @1},
  865. @"doc3" : @{@"a" : @3, @"b" : @2},
  866. @"doc4" : @{@"a" : @1, @"b" : @3},
  867. @"doc5" : @{@"a" : @1},
  868. @"doc6" : @{@"a" : @2}
  869. }];
  870. // Two IN operations on different fields with disjunction.
  871. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  872. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  873. in:@[ @0, @2 ]]
  874. ]];
  875. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  876. matchesResult:@[ @"doc1", @"doc3", @"doc6" ]];
  877. // Two IN operations on the same field with disjunction.
  878. // a IN [0,3] || a IN [0,2] should union them (similar to: a IN [0,2,3]).
  879. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  880. [FIRFilter filterWhereField:@"a" in:@[ @0, @3 ]], [FIRFilter filterWhereField:@"a"
  881. in:@[ @0, @2 ]]
  882. ]];
  883. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  884. matchesResult:@[ @"doc3", @"doc6" ]];
  885. }
  886. - (void)testUsingInWithArrayContainsAny {
  887. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  888. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  889. @"doc2" : @{@"b" : @[ @1 ]},
  890. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  891. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  892. @"doc5" : @{@"a" : @1},
  893. @"doc6" : @{@"a" : @2, @"c" : @20}
  894. }];
  895. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  896. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  897. arrayContainsAny:@[ @0, @7 ]]
  898. ]];
  899. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  900. matchesResult:@[ @"doc1", @"doc3", @"doc4", @"doc6" ]];
  901. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  902. [FIRFilter andFilterWithFilters:@[
  903. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"c"
  904. isEqualTo:@10]
  905. ]],
  906. [FIRFilter filterWhereField:@"b" arrayContainsAny:@[ @0, @7 ]]
  907. ]];
  908. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  909. matchesResult:@[ @"doc1", @"doc3", @"doc4" ]];
  910. }
  911. - (void)testUseInWithArrayContains {
  912. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  913. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  914. @"doc2" : @{@"b" : @[ @1 ]},
  915. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  916. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  917. @"doc5" : @{@"a" : @1},
  918. @"doc6" : @{@"a" : @2}
  919. }];
  920. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  921. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  922. arrayContainsAny:@[ @3 ]]
  923. ]];
  924. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  925. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  926. FIRFilter *filter2 = [FIRFilter andFilterWithFilters:@[
  927. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  928. arrayContains:@7]
  929. ]];
  930. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2] matchesResult:@[ @"doc3" ]];
  931. FIRFilter *filter3 = [FIRFilter orFilterWithFilters:@[
  932. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter andFilterWithFilters:@[
  933. [FIRFilter filterWhereField:@"b" arrayContains:@3], [FIRFilter filterWhereField:@"a"
  934. isEqualTo:@1]
  935. ]]
  936. ]];
  937. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  938. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  939. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  940. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter orFilterWithFilters:@[
  941. [FIRFilter filterWhereField:@"b" arrayContains:@7], [FIRFilter filterWhereField:@"a"
  942. isEqualTo:@1]
  943. ]]
  944. ]];
  945. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  946. }
  947. - (void)testOrderByEquality {
  948. // TODO(orquery): Enable this test against production when possible.
  949. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  950. "Skip this test if running against production because order-by-equality is not "
  951. "supported yet.");
  952. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  953. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  954. @"doc2" : @{@"b" : @[ @1 ]},
  955. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  956. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  957. @"doc5" : @{@"a" : @1},
  958. @"doc6" : @{@"a" : @2, @"c" : @20}
  959. }];
  960. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:[FIRFilter filterWhereField:@"a"
  961. isEqualTo:@1]]
  962. queryOrderedByField:@"a"]
  963. matchesResult:@[ @"doc1", @"doc4", @"doc5" ]];
  964. [self checkOnlineAndOfflineQuery:[[collRef
  965. queryWhereFilter:[FIRFilter filterWhereField:@"a"
  966. in:@[ @2, @3 ]]]
  967. queryOrderedByField:@"a"]
  968. matchesResult:@[ @"doc6", @"doc3" ]];
  969. }
  970. // Multiple Inequality
  971. - (void)testMultipleInequalityOnDifferentFields {
  972. // TODO(MIEQ): Enable this test against production when possible.
  973. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  974. "Skip this test if running against production because multiple inequality is "
  975. "not supported yet.");
  976. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  977. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @0},
  978. @"doc2" : @{@"key" : @"b", @"sort" : @3, @"v" : @1},
  979. @"doc3" : @{@"key" : @"c", @"sort" : @1, @"v" : @3},
  980. @"doc4" : @{@"key" : @"d", @"sort" : @2, @"v" : @2}
  981. }];
  982. // Multiple inequality fields
  983. FIRQuerySnapshot *snapshot = [self
  984. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  985. queryWhereField:@"sort"
  986. isLessThanOrEqualTo:@2] queryWhereField:@"v" isGreaterThan:@2]];
  987. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc3" ]));
  988. // Duplicate inequality fields
  989. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  990. queryWhereField:@"sort"
  991. isLessThanOrEqualTo:@2] queryWhereField:@"sort"
  992. isGreaterThan:@1]];
  993. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4" ]));
  994. // With multiple IN
  995. snapshot = [self
  996. readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  997. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  998. isLessThanOrEqualTo:@2]
  999. queryWhereField:@"v"
  1000. in:@[ @2, @3, @4 ]] queryWhereField:@"sort"
  1001. in:@[ @2, @3 ]]];
  1002. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4" ]));
  1003. // With NOT-IN
  1004. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key"
  1005. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1006. isLessThanOrEqualTo:@2]
  1007. queryWhereField:@"v"
  1008. notIn:@[ @2, @4, @5 ]]];
  1009. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc1", @"doc3" ]));
  1010. // With orderby
  1011. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key"
  1012. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1013. isLessThanOrEqualTo:@2]
  1014. queryOrderedByField:@"v"
  1015. descending:YES]];
  1016. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc3", @"doc4", @"doc1" ]));
  1017. // With limit
  1018. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1019. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1020. isLessThanOrEqualTo:@2]
  1021. queryOrderedByField:@"v"
  1022. descending:YES] queryLimitedTo:2]];
  1023. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc3", @"doc4" ]));
  1024. // With limitedToLast
  1025. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1026. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1027. isLessThanOrEqualTo:@2]
  1028. queryOrderedByField:@"v"
  1029. descending:YES] queryLimitedToLast:2]];
  1030. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4", @"doc1" ]));
  1031. }
  1032. - (void)testMultipleInequalityOnSpecialValues {
  1033. // TODO(MIEQ): Enable this test against production when possible.
  1034. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1035. "Skip this test if running against production because multiple inequality is "
  1036. "not supported yet.");
  1037. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1038. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @0},
  1039. @"doc2" : @{@"key" : @"b", @"sort" : @(NAN), @"v" : @1},
  1040. @"doc3" : @{@"key" : @"c", @"sort" : [NSNull null], @"v" : @3},
  1041. @"doc4" : @{@"key" : @"d", @"v" : @0},
  1042. @"doc5" : @{@"key" : @"e", @"sort" : @1},
  1043. @"doc6" : @{@"key" : @"f", @"sort" : @1, @"v" : @1}
  1044. }];
  1045. FIRQuerySnapshot *snapshot =
  1046. [self readDocumentSetForRef:[[collRef queryWhereField:@"key"
  1047. isNotEqualTo:@"a"] queryWhereField:@"sort"
  1048. isLessThanOrEqualTo:@2]];
  1049. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc5", @"doc6" ]));
  1050. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1051. queryWhereField:@"sort"
  1052. isLessThanOrEqualTo:@2] queryWhereField:@"v"
  1053. isLessThanOrEqualTo:@1]];
  1054. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc6" ]));
  1055. }
  1056. - (void)testMultipleInequalityWithArrayMembership {
  1057. // TODO(MIEQ): Enable this test against production when possible.
  1058. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1059. "Skip this test if running against production because multiple inequality is "
  1060. "not supported yet.");
  1061. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1062. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @[ @0 ]},
  1063. @"doc2" : @{@"key" : @"b", @"sort" : @1, @"v" : @[ @0, @1, @3 ]},
  1064. @"doc3" : @{@"key" : @"c", @"sort" : @1, @"v" : @[]},
  1065. @"doc4" : @{@"key" : @"d", @"sort" : @2, @"v" : @[ @1 ]},
  1066. @"doc5" : @{@"key" : @"e", @"sort" : @3, @"v" : @[ @2, @4 ]},
  1067. @"doc6" : @{@"key" : @"f", @"sort" : @4, @"v" : @[ @(NAN) ]},
  1068. @"doc7" : @{@"key" : @"g", @"sort" : @4, @"v" : @[ [NSNull null] ]}
  1069. }];
  1070. FIRQuerySnapshot *snapshot = [self
  1071. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1072. queryWhereField:@"sort"
  1073. isGreaterThanOrEqualTo:@1] queryWhereField:@"v" arrayContains:@0]];
  1074. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2" ]));
  1075. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key"
  1076. isNotEqualTo:@"a"] queryWhereField:@"sort"
  1077. isGreaterThanOrEqualTo:@1]
  1078. queryWhereField:@"v"
  1079. arrayContainsAny:@[ @0, @1 ]]];
  1080. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc4" ]));
  1081. }
  1082. - (NSDictionary<NSString *, id> *)nestedData:(int)number {
  1083. return @{
  1084. @"name" : [NSString stringWithFormat:@"room %d", number],
  1085. @"metadata" : @{@"createdAt" : @(number)},
  1086. @"field" : [NSString stringWithFormat:@"field %d", number],
  1087. @"field.dot" : @(number),
  1088. @"field\\slash" : @(number)
  1089. };
  1090. }
  1091. - (void)testMultipleInequalityWithNestedField {
  1092. // TODO(MIEQ): Enable this test against production when possible.
  1093. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1094. "Skip this test if running against production because multiple inequality is "
  1095. "not supported yet.");
  1096. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1097. @"doc1" : [self nestedData:400],
  1098. @"doc2" : [self nestedData:200],
  1099. @"doc3" : [self nestedData:100],
  1100. @"doc4" : [self nestedData:300]
  1101. }];
  1102. FIRQuerySnapshot *snapshot = [self
  1103. readDocumentSetForRef:[[[[collRef queryWhereField:@"metadata.createdAt"
  1104. isLessThanOrEqualTo:@500] queryWhereField:@"metadata.createdAt"
  1105. isGreaterThan:@100]
  1106. queryWhereField:@"name"
  1107. isNotEqualTo:@"room 200"] queryOrderedByField:@"name"
  1108. descending:NO]];
  1109. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4", @"doc1" ]));
  1110. snapshot =
  1111. [self readDocumentSetForRef:[[[[collRef queryWhereField:@"field"
  1112. isGreaterThanOrEqualTo:@"field 100"]
  1113. queryWhereFieldPath:[[FIRFieldPath alloc]
  1114. initWithFields:@[ @"field.dot" ]]
  1115. isNotEqualTo:@300] queryWhereField:@"field\\slash"
  1116. isLessThan:@400]
  1117. queryOrderedByField:@"name"
  1118. descending:YES]];
  1119. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc3" ]));
  1120. }
  1121. - (void)testMultipleInequalityWithCompositeFilters {
  1122. // TODO(MIEQ): Enable this test against production when possible.
  1123. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1124. "Skip this test if running against production because multiple inequality is "
  1125. "not supported yet.");
  1126. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1127. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @5},
  1128. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @4},
  1129. @"doc3" : @{@"key" : @"c", @"sort" : @3, @"v" : @3},
  1130. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @2},
  1131. @"doc5" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1132. @"doc6" : @{@"key" : @"b", @"sort" : @0, @"v" : @0}
  1133. }];
  1134. FIRQuerySnapshot *snapshot = [self
  1135. readDocumentSetForRef:[collRef queryWhereFilter:[FIRFilter orFilterWithFilters:@[
  1136. [FIRFilter andFilterWithFilters:@[
  1137. [FIRFilter filterWhereField:@"key" isEqualTo:@"b"],
  1138. [FIRFilter filterWhereField:@"sort" isLessThanOrEqualTo:@2]
  1139. ]],
  1140. [FIRFilter andFilterWithFilters:@[
  1141. [FIRFilter filterWhereField:@"key" isNotEqualTo:@"b"],
  1142. [FIRFilter filterWhereField:@"v" isGreaterThan:@4]
  1143. ]]
  1144. ]]]];
  1145. // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc
  1146. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1147. (@[ @"doc1", @"doc6", @"doc5", @"doc4" ]));
  1148. snapshot = [self
  1149. readDocumentSetForRef:[[[collRef queryWhereFilter:[FIRFilter orFilterWithFilters:@[
  1150. [FIRFilter andFilterWithFilters:@[
  1151. [FIRFilter filterWhereField:@"key" isEqualTo:@"b"],
  1152. [FIRFilter filterWhereField:@"sort"
  1153. isLessThanOrEqualTo:@2]
  1154. ]],
  1155. [FIRFilter andFilterWithFilters:@[
  1156. [FIRFilter filterWhereField:@"key" isNotEqualTo:@"b"],
  1157. [FIRFilter filterWhereField:@"v" isGreaterThan:@4]
  1158. ]]
  1159. ]]] queryOrderedByField:@"sort"
  1160. descending:YES] queryOrderedByField:@"key"]];
  1161. // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc
  1162. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1163. (@[ @"doc5", @"doc4", @"doc1", @"doc6" ]));
  1164. snapshot = [self
  1165. readDocumentSetForRef:[collRef
  1166. queryWhereFilter:[FIRFilter andFilterWithFilters:@[
  1167. [FIRFilter orFilterWithFilters:@[
  1168. [FIRFilter andFilterWithFilters:@[
  1169. [FIRFilter filterWhereField:@"key" isEqualTo:@"b"],
  1170. [FIRFilter filterWhereField:@"sort" isLessThanOrEqualTo:@4]
  1171. ]],
  1172. [FIRFilter andFilterWithFilters:@[
  1173. [FIRFilter filterWhereField:@"key" isNotEqualTo:@"b"],
  1174. [FIRFilter filterWhereField:@"v" isGreaterThanOrEqualTo:@4]
  1175. ]]
  1176. ]],
  1177. [FIRFilter orFilterWithFilters:@[
  1178. [FIRFilter andFilterWithFilters:@[
  1179. [FIRFilter filterWhereField:@"key" isGreaterThan:@"b"],
  1180. [FIRFilter filterWhereField:@"sort" isGreaterThanOrEqualTo:@1]
  1181. ]],
  1182. [FIRFilter andFilterWithFilters:@[
  1183. [FIRFilter filterWhereField:@"key" isLessThan:@"b"],
  1184. [FIRFilter filterWhereField:@"v" isGreaterThan:@0]
  1185. ]]
  1186. ]]
  1187. ]]]];
  1188. // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc
  1189. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc1", @"doc2" ]));
  1190. }
  1191. - (void)testMultipleInequalityFieldsWillBeImplicitlyOrderedLexicographically {
  1192. // TODO(MIEQ): Enable this test against production when possible.
  1193. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1194. "Skip this test if running against production because multiple inequality is "
  1195. "not supported yet.");
  1196. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1197. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @5},
  1198. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @4},
  1199. @"doc3" : @{@"key" : @"b", @"sort" : @3, @"v" : @3},
  1200. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @2},
  1201. @"doc5" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1202. @"doc6" : @{@"key" : @"b", @"sort" : @0, @"v" : @0}
  1203. }];
  1204. FIRQuerySnapshot *snapshot = [self
  1205. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1206. queryWhereField:@"sort"
  1207. isGreaterThan:@1] queryWhereField:@"v" in:@[ @1, @2, @3, @4 ]]];
  1208. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1209. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1210. (@[ @"doc2", @"doc4", @"doc5", @"doc3" ]));
  1211. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"sort"
  1212. isGreaterThan:@1] queryWhereField:@"key"
  1213. isNotEqualTo:@"a"]
  1214. queryWhereField:@"v"
  1215. in:@[ @1, @2, @3, @4 ]]];
  1216. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1217. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1218. (@[ @"doc2", @"doc4", @"doc5", @"doc3" ]));
  1219. }
  1220. - (void)testMultipleInequalityWithMultipleExplicitOrderBy {
  1221. // TODO(MIEQ): Enable this test against production when possible.
  1222. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1223. "Skip this test if running against production because multiple inequality is "
  1224. "not supported yet.");
  1225. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1226. @"doc1" : @{@"key" : @"a", @"sort" : @5, @"v" : @0},
  1227. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @0},
  1228. @"doc3" : @{@"key" : @"b", @"sort" : @3, @"v" : @1},
  1229. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1230. @"doc5" : @{@"key" : @"bb", @"sort" : @1, @"v" : @1},
  1231. @"doc6" : @{@"key" : @"c", @"sort" : @0, @"v" : @2}
  1232. }];
  1233. FIRQuerySnapshot *snapshot = [self
  1234. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1235. queryWhereField:@"sort"
  1236. isGreaterThanOrEqualTo:@1] queryOrderedByField:@"v" descending:NO]];
  1237. // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc
  1238. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1239. (@[ @"doc2", @"doc4", @"doc3", @"doc5" ]));
  1240. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1241. isGreaterThan:@"a"] queryWhereField:@"sort"
  1242. isGreaterThanOrEqualTo:@1]
  1243. queryOrderedByField:@"v"
  1244. descending:NO] queryOrderedByField:@"sort"
  1245. descending:NO]];
  1246. // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc
  1247. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1248. (@[ @"doc2", @"doc5", @"doc4", @"doc3" ]));
  1249. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1250. queryWhereField:@"sort"
  1251. isGreaterThanOrEqualTo:@1] queryOrderedByField:@"v"
  1252. descending:YES]];
  1253. // Implicit order by matches the direction of last explicit order by.
  1254. // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc
  1255. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1256. (@[ @"doc5", @"doc3", @"doc4", @"doc2" ]));
  1257. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1258. isGreaterThan:@"a"] queryWhereField:@"sort"
  1259. isGreaterThanOrEqualTo:@1]
  1260. queryOrderedByField:@"v"
  1261. descending:YES] queryOrderedByField:@"sort"
  1262. descending:NO]];
  1263. // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc
  1264. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1265. (@[ @"doc5", @"doc4", @"doc3", @"doc2" ]));
  1266. }
  1267. - (void)testMultipleInequalityInAggregateQuery {
  1268. // TODO(MIEQ): Enable this test against production when possible.
  1269. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1270. "Skip this test if running against production because multiple inequality is "
  1271. "not supported yet.");
  1272. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1273. @"doc1" : @{@"key" : @"a", @"sort" : @5, @"v" : @0},
  1274. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @0},
  1275. @"doc3" : @{@"key" : @"b", @"sort" : @3, @"v" : @1},
  1276. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1277. @"doc5" : @{@"key" : @"bb", @"sort" : @1, @"v" : @1},
  1278. }];
  1279. FIRAggregateQuerySnapshot *snapshot =
  1280. [self readSnapshotForAggregate:[[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1281. queryWhereField:@"sort"
  1282. isGreaterThanOrEqualTo:@1] queryOrderedByField:@"v"
  1283. descending:NO]
  1284. aggregate:@[
  1285. [FIRAggregateField aggregateFieldForCount],
  1286. [FIRAggregateField aggregateFieldForSumOfField:@"sort"],
  1287. [FIRAggregateField aggregateFieldForAverageOfField:@"v"]
  1288. ]]];
  1289. XCTAssertEqual([snapshot count], [NSNumber numberWithLong:4L]);
  1290. snapshot = [self
  1291. readSnapshotForAggregate:[[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1292. queryWhereField:@"sort"
  1293. isGreaterThanOrEqualTo:@1] queryWhereField:@"v" isNotEqualTo:@0]
  1294. aggregate:@[
  1295. [FIRAggregateField aggregateFieldForCount],
  1296. [FIRAggregateField aggregateFieldForSumOfField:@"sort"],
  1297. [FIRAggregateField aggregateFieldForAverageOfField:@"v"],
  1298. ]]];
  1299. XCTAssertEqual([snapshot valueForAggregation:[FIRAggregateField aggregateFieldForCount]],
  1300. [NSNumber numberWithLong:3L]);
  1301. XCTAssertEqual(
  1302. [[snapshot valueForAggregation:[FIRAggregateField aggregateFieldForSumOfField:@"sort"]]
  1303. longValue],
  1304. 6L);
  1305. XCTAssertEqual(
  1306. [snapshot valueForAggregation:[FIRAggregateField aggregateFieldForAverageOfField:@"v"]],
  1307. [NSNumber numberWithDouble:1.0]);
  1308. }
  1309. - (void)testMultipleInequalityFieldsWithDocumentKey {
  1310. // TODO(MIEQ): Enable this test against production when possible.
  1311. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1312. "Skip this test if running against production because multiple inequality is "
  1313. "not supported yet.");
  1314. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1315. @"doc1" : @{@"key" : @"a", @"sort" : @5},
  1316. @"doc2" : @{@"key" : @"aa", @"sort" : @4},
  1317. @"doc3" : @{@"key" : @"b", @"sort" : @3},
  1318. @"doc4" : @{@"key" : @"b", @"sort" : @2},
  1319. @"doc5" : @{@"key" : @"bb", @"sort" : @1}
  1320. }];
  1321. FIRQuerySnapshot *snapshot = [self
  1322. readDocumentSetForRef:[[[collRef queryWhereField:@"sort"
  1323. isGreaterThan:@1] queryWhereField:@"key" isNotEqualTo:@"a"]
  1324. queryWhereFieldPath:[FIRFieldPath documentID]
  1325. isLessThan:@"doc5"]];
  1326. // Document Key in inequality field will implicitly ordered to the last.
  1327. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1328. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc4", @"doc3" ]));
  1329. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereFieldPath:[FIRFieldPath documentID]
  1330. isLessThan:@"doc5"]
  1331. queryWhereField:@"sort"
  1332. isGreaterThan:@1] queryWhereField:@"key"
  1333. isNotEqualTo:@"a"]];
  1334. // Changing filters order will not effect implicit order.
  1335. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1336. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc4", @"doc3" ]));
  1337. snapshot = [self
  1338. readDocumentSetForRef:[[[[collRef queryWhereFieldPath:[FIRFieldPath documentID]
  1339. isLessThan:@"doc5"] queryWhereField:@"sort"
  1340. isGreaterThan:@1]
  1341. queryWhereField:@"key"
  1342. isNotEqualTo:@"a"] queryOrderedByField:@"sort" descending:YES]];
  1343. // Ordered by: 'sort' desc,'key' desc, __name__ desc
  1344. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc3", @"doc4" ]));
  1345. }
  1346. - (void)testMultipleInequalityReadFromCacheWhenOffline {
  1347. // TODO(MIEQ): Enable this test against production when possible.
  1348. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1349. "Skip this test if running against production because multiple inequality is "
  1350. "not supported yet.");
  1351. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1352. @"doc1" : @{@"key" : @"a", @"sort" : @1},
  1353. @"doc2" : @{@"key" : @"aa", @"sort" : @4},
  1354. @"doc3" : @{@"key" : @"b", @"sort" : @3},
  1355. @"doc4" : @{@"key" : @"b", @"sort" : @2},
  1356. }];
  1357. FIRQuery *query = [[collRef queryWhereField:@"key" isNotEqualTo:@"a"] queryWhereField:@"sort"
  1358. isLessThanOrEqualTo:@3];
  1359. // populate the cache.
  1360. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  1361. XCTAssertEqual(snapshot.count, 2L);
  1362. XCTAssertEqual(snapshot.metadata.isFromCache, NO);
  1363. [self disableNetwork];
  1364. snapshot = [self readDocumentSetForRef:query];
  1365. XCTAssertEqual(snapshot.count, 2L);
  1366. XCTAssertEqual(snapshot.metadata.isFromCache, YES);
  1367. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1368. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4", @"doc3" ]));
  1369. }
  1370. - (void)testMultipleInequalityFromCacheAndFromServer {
  1371. // TODO(MIEQ): Enable this test against production when possible.
  1372. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1373. "Skip this test if running against production because multiple inequality is "
  1374. "not supported yet.");
  1375. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1376. @"doc1" : @{@"a" : @1, @"b" : @0},
  1377. @"doc2" : @{@"a" : @2, @"b" : @1},
  1378. @"doc3" : @{@"a" : @3, @"b" : @2},
  1379. @"doc4" : @{@"a" : @1, @"b" : @3},
  1380. @"doc5" : @{@"a" : @1, @"b" : @1},
  1381. }];
  1382. // implicit AND: a != 1 && b < 2
  1383. FIRQuery *query = [[collRef queryWhereField:@"a" isNotEqualTo:@1] queryWhereField:@"b"
  1384. isLessThan:@2];
  1385. [self checkOnlineAndOfflineQuery:query matchesResult:@[ @"doc2" ]];
  1386. // explicit AND: a != 1 && b < 2
  1387. FIRFilter *filter = [FIRFilter andFilterWithFilters:@[
  1388. [FIRFilter filterWhereField:@"a" isNotEqualTo:@1], [FIRFilter filterWhereField:@"b"
  1389. isLessThan:@2]
  1390. ]];
  1391. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter] matchesResult:@[ @"doc2" ]];
  1392. // explicit AND: a < 3 && b not-in [2, 3]
  1393. // Implicitly ordered by: a asc, b asc, __name__ asc
  1394. filter = [FIRFilter andFilterWithFilters:@[
  1395. [FIRFilter filterWhereField:@"a" isLessThan:@3], [FIRFilter filterWhereField:@"b"
  1396. notIn:@[ @2, @3 ]]
  1397. ]];
  1398. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  1399. matchesResult:@[ @"doc1", @"doc5", @"doc2" ]];
  1400. // a <3 && b != 0, ordered by: b desc, a desc, __name__ desc
  1401. query = [[[[collRef queryWhereField:@"a" isLessThan:@3] queryWhereField:@"b" isNotEqualTo:@0]
  1402. queryOrderedByField:@"b"
  1403. descending:YES] queryLimitedTo:2];
  1404. [self checkOnlineAndOfflineQuery:query matchesResult:@[ @"doc4", @"doc2" ]];
  1405. // explicit OR: a>2 || b<1.
  1406. filter = [FIRFilter orFilterWithFilters:@[
  1407. [FIRFilter filterWhereField:@"a" isGreaterThan:@2], [FIRFilter filterWhereField:@"b"
  1408. isLessThan:@1]
  1409. ]];
  1410. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  1411. matchesResult:@[ @"doc1", @"doc3" ]];
  1412. }
  1413. - (void)testResumingAQueryShouldUseBloomFilterToAvoidFullRequery {
  1414. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1415. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1416. // sends.
  1417. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1418. "Skip this test when running against the Firestore emulator because the emulator does "
  1419. "not include a bloom filter when it sends existence filter messages, making it "
  1420. "impossible for this test to verify the correctness of the bloom filter.");
  1421. // Set this test to stop when the first failure occurs because some test assertion failures make
  1422. // the rest of the test not applicable or will even crash.
  1423. [self setContinueAfterFailure:NO];
  1424. // Prepare the names and contents of the 100 documents to create.
  1425. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1426. [[NSMutableDictionary alloc] init];
  1427. for (int i = 0; i < 100; i++) {
  1428. [testDocs setValue:@{@"key" : @42} forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1429. }
  1430. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1431. // be run multiple times only if a bloom filter false positive occurs.
  1432. int attemptNumber = 0;
  1433. while (true) {
  1434. attemptNumber++;
  1435. // Create 100 documents in a new collection.
  1436. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1437. // Run a query to populate the local cache with the 100 documents and a resume token.
  1438. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1439. source:FIRFirestoreSourceDefault];
  1440. XCTAssertEqual(querySnapshot1.count, 100, @"querySnapshot1.count has an unexpected value");
  1441. NSArray<FIRDocumentReference *> *createdDocuments =
  1442. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1443. // Delete 50 of the 100 documents. Use a different Firestore instance to avoid affecting the
  1444. // local cache.
  1445. NSSet<NSString *> *deletedDocumentIds;
  1446. {
  1447. FIRFirestore *db2 = [self firestore];
  1448. FIRWriteBatch *batch = [db2 batch];
  1449. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1450. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 2) {
  1451. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1452. [batch deleteDocument:documentToDelete];
  1453. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1454. }
  1455. [self commitWriteBatch:batch];
  1456. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1457. }
  1458. XCTAssertEqual(deletedDocumentIds.count, 50u, @"deletedDocumentIds has the wrong size");
  1459. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1460. // existence filter rather than "delete" events when the query is resumed.
  1461. [NSThread sleepForTimeInterval:10.0f];
  1462. // Resume the query and save the resulting snapshot for verification.
  1463. // Use some internal testing hooks to "capture" the existence filter mismatches to verify that
  1464. // Watch sent a bloom filter, and it was used to avert a full requery.
  1465. __block FIRQuerySnapshot *querySnapshot2;
  1466. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1467. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1468. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1469. }];
  1470. // Verify that the snapshot from the resumed query contains the expected documents; that is,
  1471. // that it contains the 50 documents that were _not_ deleted.
  1472. {
  1473. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1474. for (FIRDocumentReference *documentRef in createdDocuments) {
  1475. if (![deletedDocumentIds containsObject:documentRef.documentID]) {
  1476. [expectedDocumentIds addObject:documentRef.documentID];
  1477. }
  1478. }
  1479. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1480. [NSSet setWithArray:expectedDocumentIds],
  1481. @"querySnapshot2 has the wrong documents");
  1482. }
  1483. // Verify that Watch sent an existence filter with the correct counts when the query was
  1484. // resumed.
  1485. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1486. @"Watch should have sent exactly 1 existence filter");
  1487. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1488. existenceFilterMismatches[0];
  1489. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 100);
  1490. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 50);
  1491. // Verify that Watch sent a valid bloom filter.
  1492. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1493. XCTAssertNotNil(bloomFilter,
  1494. "Watch should have included a bloom filter in the existence filter");
  1495. XCTAssertGreaterThan(bloomFilter.hashCount, 0);
  1496. XCTAssertGreaterThan(bloomFilter.bitmapLength, 0);
  1497. XCTAssertGreaterThan(bloomFilter.padding, 0);
  1498. XCTAssertLessThan(bloomFilter.padding, 8);
  1499. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1500. // positive occurred then retry the entire test. Although statistically rare, false positives
  1501. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1502. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1503. // fail the test because that is so improbable that something must have gone wrong.
  1504. if (attemptNumber == 1 && !bloomFilter.applied) {
  1505. continue;
  1506. }
  1507. XCTAssertTrue(bloomFilter.applied,
  1508. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1509. @(attemptNumber));
  1510. // Break out of the test loop now that the test passes.
  1511. break;
  1512. }
  1513. }
  1514. - (void)
  1515. testBloomFilterShouldAvertAFullRequeryWhenDocumentsWereAddedDeletedRemovedUpdatedAndUnchangedSinceTheResumeToken {
  1516. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1517. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1518. // sends.
  1519. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1520. "Skip this test when running against the Firestore emulator because the emulator does "
  1521. "not include a bloom filter when it sends existence filter messages, making it "
  1522. "impossible for this test to verify the correctness of the bloom filter.");
  1523. // Set this test to stop when the first failure occurs because some test assertion failures make
  1524. // the rest of the test not applicable or will even crash.
  1525. [self setContinueAfterFailure:NO];
  1526. // Prepare the names and contents of the 20 documents to create.
  1527. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1528. [[NSMutableDictionary alloc] init];
  1529. for (int i = 0; i < 20; i++) {
  1530. [testDocs setValue:@{@"key" : @42, @"removed" : @NO}
  1531. forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1532. }
  1533. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1534. // be run multiple times only if a bloom filter false positive occurs.
  1535. int attemptNumber = 0;
  1536. while (true) {
  1537. attemptNumber++;
  1538. // Create 20 documents in a new collection.
  1539. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1540. FIRQuery *query = [collRef queryWhereField:@"removed" isEqualTo:@NO];
  1541. // Run a query to populate the local cache with the 20 documents and a resume token.
  1542. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:query
  1543. source:FIRFirestoreSourceDefault];
  1544. XCTAssertEqual(querySnapshot1.count, 20u, @"querySnapshot1.count has an unexpected value");
  1545. NSArray<FIRDocumentReference *> *createdDocuments =
  1546. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1547. // Out of the 20 existing documents, leave 5 docs untouched, delete 5 docs, remove 5 docs,
  1548. // update 5 docs, and add 15 new docs.
  1549. NSSet<NSString *> *deletedDocumentIds;
  1550. NSSet<NSString *> *removedDocumentIds;
  1551. NSSet<NSString *> *updatedDocumentIds;
  1552. NSMutableArray<NSString *> *addedDocumentIds = [[NSMutableArray alloc] init];
  1553. {
  1554. FIRFirestore *db2 = [self firestore];
  1555. FIRWriteBatch *batch = [db2 batch];
  1556. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1557. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 4) {
  1558. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1559. [batch deleteDocument:documentToDelete];
  1560. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1561. }
  1562. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1563. XCTAssertEqual(deletedDocumentIds.count, 5u, @"deletedDocumentIds has the wrong size");
  1564. // Update 5 documents to no longer match the query.
  1565. NSMutableArray<NSString *> *removedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1566. for (decltype(createdDocuments.count) i = 1; i < createdDocuments.count; i += 4) {
  1567. FIRDocumentReference *documentToRemove = [db2 documentWithPath:createdDocuments[i].path];
  1568. [batch updateData:@{@"removed" : @YES} forDocument:documentToRemove];
  1569. [removedDocumentIdsAccumulator addObject:documentToRemove.documentID];
  1570. }
  1571. removedDocumentIds = [NSSet setWithArray:removedDocumentIdsAccumulator];
  1572. XCTAssertEqual(removedDocumentIds.count, 5u, @"removedDocumentIds has the wrong size");
  1573. // Update 5 documents, but ensure they still match the query.
  1574. NSMutableArray<NSString *> *updatedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1575. for (decltype(createdDocuments.count) i = 2; i < createdDocuments.count; i += 4) {
  1576. FIRDocumentReference *documentToUpdate = [db2 documentWithPath:createdDocuments[i].path];
  1577. [batch updateData:@{@"key" : @43} forDocument:documentToUpdate];
  1578. [updatedDocumentIdsAccumulator addObject:documentToUpdate.documentID];
  1579. }
  1580. updatedDocumentIds = [NSSet setWithArray:updatedDocumentIdsAccumulator];
  1581. XCTAssertEqual(updatedDocumentIds.count, 5u, @"updatedDocumentIds has the wrong size");
  1582. for (int i = 0; i < 15; i += 1) {
  1583. FIRDocumentReference *documentToAdd = [db2
  1584. documentWithPath:[NSString stringWithFormat:@"%@/newDoc%@", collRef.path, @(1000 + i)]];
  1585. [batch setData:@{@"key" : @42, @"removed" : @NO} forDocument:documentToAdd];
  1586. [addedDocumentIds addObject:documentToAdd.documentID];
  1587. }
  1588. // Ensure the documentIds above are mutually exclusive.
  1589. NSMutableSet<NSString *> *mergedSet = [NSMutableSet setWithArray:addedDocumentIds];
  1590. [mergedSet unionSet:deletedDocumentIds];
  1591. [mergedSet unionSet:removedDocumentIds];
  1592. [mergedSet unionSet:updatedDocumentIds];
  1593. XCTAssertEqual(mergedSet.count, 30u, @"There are documents experienced multiple operations.");
  1594. [self commitWriteBatch:batch];
  1595. }
  1596. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1597. // existence filter rather than "delete" events when the query is resumed.
  1598. [NSThread sleepForTimeInterval:10.0f];
  1599. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1600. // hooks to "capture" the existence filter mismatches to verify that Watch sent a bloom
  1601. // filter, and it was used to avert a full requery.
  1602. __block FIRQuerySnapshot *querySnapshot2;
  1603. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1604. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1605. querySnapshot2 = [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  1606. }];
  1607. XCTAssertEqual(querySnapshot2.count, 25u, @"querySnapshot1.count has an unexpected value");
  1608. // Verify that the snapshot from the resumed query contains the expected documents; that is, 10
  1609. // existing documents that still match the query, and 15 documents that are newly added.
  1610. {
  1611. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1612. for (FIRDocumentReference *documentRef in createdDocuments) {
  1613. if (![deletedDocumentIds containsObject:documentRef.documentID] &&
  1614. ![removedDocumentIds containsObject:documentRef.documentID]) {
  1615. [expectedDocumentIds addObject:documentRef.documentID];
  1616. }
  1617. }
  1618. [expectedDocumentIds addObjectsFromArray:addedDocumentIds];
  1619. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1620. [NSSet setWithArray:expectedDocumentIds],
  1621. @"querySnapshot2 has the wrong documents");
  1622. }
  1623. // Verify that Watch sent an existence filter with the correct counts when the query was
  1624. // resumed.
  1625. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1626. @"Watch should have sent exactly 1 existence filter");
  1627. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1628. existenceFilterMismatches[0];
  1629. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 35);
  1630. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 25);
  1631. // Verify that Watch sent a valid bloom filter.
  1632. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1633. XCTAssertNotNil(bloomFilter,
  1634. "Watch should have included a bloom filter in the existence filter");
  1635. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1636. // positive occurred then retry the entire test. Although statistically rare, false positives
  1637. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1638. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1639. // fail the test because that is so improbable that something must have gone wrong.
  1640. if (attemptNumber == 1 && !bloomFilter.applied) {
  1641. continue;
  1642. }
  1643. XCTAssertTrue(bloomFilter.applied,
  1644. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1645. @(attemptNumber));
  1646. // Break out of the test loop now that the test passes.
  1647. break;
  1648. }
  1649. }
  1650. - (void)testBloomFilterShouldCorrectlyEncodeComplexUnicodeCharacters {
  1651. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1652. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1653. // sends.
  1654. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1655. "Skip this test when running against the Firestore emulator because the emulator does "
  1656. "not include a bloom filter when it sends existence filter messages, making it "
  1657. "impossible for this test to verify the correctness of the bloom filter.");
  1658. // Set this test to stop when the first failure occurs because some test assertion failures make
  1659. // the rest of the test not applicable or will even crash.
  1660. [self setContinueAfterFailure:NO];
  1661. // Define a comparator that compares `NSString` objects in a way that orders canonically-
  1662. // equivalent, but distinct, strings in a consistent manner by using `NSForcedOrderingSearch`.
  1663. // Otherwise, the bare `[NSString compare:]` method considers canonically-equivalent, but
  1664. // distinct, strings as "equal" and orders them indeterminately.
  1665. NSComparator sortComparator = ^(NSString *string1, NSString *string2) {
  1666. return [string1 compare:string2 options:NSForcedOrderingSearch];
  1667. };
  1668. // Firestore does not do any Unicode normalization on the document IDs. Therefore, two document
  1669. // IDs that are canonically-equivalent (i.e. they visually appear identical) but are represented
  1670. // by a different sequence of Unicode code points are treated as distinct document IDs.
  1671. NSArray<NSString *> *testDocIds;
  1672. {
  1673. NSMutableArray<NSString *> *testDocIdsAccumulator = [[NSMutableArray alloc] init];
  1674. [testDocIdsAccumulator addObject:@"DocumentToDelete"];
  1675. // The next two strings both end with "e" with an accent: the first uses the dedicated Unicode
  1676. // code point for this character, while the second uses the standard lowercase "e" followed by
  1677. // the accent combining character.
  1678. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u00E9"];
  1679. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u0065\u0301"];
  1680. // The next two strings both end with an "e" with two different accents applied via the
  1681. // following two combining characters. The combining characters are specified in a different
  1682. // order and Firestore treats these document IDs as unique, despite the order of the combining
  1683. // characters being irrelevant.
  1684. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0301\u0327"];
  1685. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0327\u0301"];
  1686. // The next string contains a character outside the BMP (the "basic multilingual plane"); that
  1687. // is, its code point is greater than 0xFFFF. Since NSString stores text in sequences of 16-bit
  1688. // code units, using the UTF-16 encoding (according to
  1689. // https://www.objc.io/issues/9-strings/unicode) it is stored as a surrogate pair, two 16-bit
  1690. // code units U+D83D and U+DE00, to represent this character. Make sure that its presence is
  1691. // correctly tested in the bloom filter, which uses UTF-8 encoding.
  1692. [testDocIdsAccumulator addObject:@"Smiley_\U0001F600"];
  1693. testDocIds = [NSArray arrayWithArray:testDocIdsAccumulator];
  1694. }
  1695. // Verify assumptions about the equivalence of strings in `testDocIds`.
  1696. XCTAssertEqualObjects(testDocIds[1].decomposedStringWithCanonicalMapping,
  1697. testDocIds[2].decomposedStringWithCanonicalMapping);
  1698. XCTAssertEqualObjects(testDocIds[3].decomposedStringWithCanonicalMapping,
  1699. testDocIds[4].decomposedStringWithCanonicalMapping);
  1700. XCTAssertEqual([testDocIds[5] characterAtIndex:7], 0xD83D);
  1701. XCTAssertEqual([testDocIds[5] characterAtIndex:8], 0xDE00);
  1702. // Create the mapping from document ID to document data for the document IDs specified in
  1703. // `testDocIds`.
  1704. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1705. [[NSMutableDictionary alloc] init];
  1706. for (NSString *testDocId in testDocIds) {
  1707. [testDocs setValue:@{@"foo" : @42} forKey:testDocId];
  1708. }
  1709. // Create the documents whose names contain complex Unicode characters in a new collection.
  1710. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1711. // Run a query to populate the local cache with documents that have names with complex Unicode
  1712. // characters.
  1713. {
  1714. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1715. source:FIRFirestoreSourceDefault];
  1716. XCTAssertEqualObjects(
  1717. [FIRQuerySnapshotGetIDs(querySnapshot1) sortedArrayUsingComparator:sortComparator],
  1718. [testDocIds sortedArrayUsingComparator:sortComparator],
  1719. @"querySnapshot1 has the wrong documents");
  1720. }
  1721. // Delete one of the documents so that the next call to collection.get() will experience an
  1722. // existence filter mismatch. Use a different Firestore instance to avoid affecting the local
  1723. // cache.
  1724. FIRDocumentReference *documentToDelete = [collRef documentWithPath:@"DocumentToDelete"];
  1725. {
  1726. FIRFirestore *db2 = [self firestore];
  1727. [self deleteDocumentRef:[db2 documentWithPath:documentToDelete.path]];
  1728. }
  1729. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1730. // existence filter rather than "delete" events when the query is resumed.
  1731. [NSThread sleepForTimeInterval:10.0f];
  1732. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1733. // hooks to "capture" the existence filter mismatches.
  1734. __block FIRQuerySnapshot *querySnapshot2;
  1735. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1736. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1737. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1738. }];
  1739. // Verify that the snapshot from the resumed query contains the expected documents; that is, that
  1740. // it contains the documents whose names contain complex Unicode characters and _not_ the document
  1741. // that was deleted.
  1742. {
  1743. NSMutableArray<NSString *> *querySnapshot2ExpectedDocumentIds =
  1744. [NSMutableArray arrayWithArray:testDocIds];
  1745. [querySnapshot2ExpectedDocumentIds removeObject:documentToDelete.documentID];
  1746. XCTAssertEqualObjects(
  1747. [FIRQuerySnapshotGetIDs(querySnapshot2) sortedArrayUsingComparator:sortComparator],
  1748. [querySnapshot2ExpectedDocumentIds sortedArrayUsingComparator:sortComparator],
  1749. @"querySnapshot2 has the wrong documents");
  1750. }
  1751. // Verify that Watch sent an existence filter with the correct counts.
  1752. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1753. @"Watch should have sent exactly 1 existence filter");
  1754. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1755. existenceFilterMismatches[0];
  1756. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, (int)testDocIds.count);
  1757. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, (int)testDocIds.count - 1);
  1758. // Verify that Watch sent a valid bloom filter.
  1759. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1760. XCTAssertNotNil(bloomFilter, "Watch should have included a bloom filter in the existence filter");
  1761. // The bloom filter application should statistically be successful almost every time; the _only_
  1762. // time when it would _not_ be successful is if there is a false positive when testing for
  1763. // 'DocumentToDelete' in the bloom filter. So verify that the bloom filter application is
  1764. // successful, unless there was a false positive.
  1765. BOOL isFalsePositive = [bloomFilter mightContain:documentToDelete];
  1766. XCTAssertEqual(bloomFilter.applied, !isFalsePositive);
  1767. // Verify that the bloom filter contains the document paths with complex Unicode characters.
  1768. for (FIRDocumentSnapshot *documentSnapshot in querySnapshot2.documents) {
  1769. XCTAssertTrue([bloomFilter mightContain:documentSnapshot.reference],
  1770. @"The bloom filter should contain %@", documentSnapshot.documentID);
  1771. }
  1772. }
  1773. @end