FIRQueryTests.mm 82 KB

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