FIRQueryTests.mm 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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 checkOnlineAndOfflineQuery:[collection queryWhereField:@"zip" isNotEqualTo:@98101]
  466. matchesResult:@[ @"a", @"b", @"d", @"e", @"f", @"g", @"h" ]];
  467. [self checkOnlineAndOfflineQuery:[collection queryWhereField:@"zip" isNotEqualTo:@(NAN)]
  468. matchesResult:@[ @"b", @"c", @"d", @"e", @"f", @"g", @"h" ]];
  469. [self checkOnlineAndOfflineQuery:[collection queryWhereField:@"zip"
  470. isNotEqualTo:@[ [NSNull null] ]]
  471. matchesResult:@[ @"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h" ]];
  472. }
  473. - (void)testQueriesCanUseArrayContainsFilters {
  474. NSDictionary *testDocs = @{
  475. @"a" : @{@"array" : @[ @42 ]},
  476. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  477. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  478. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  479. @"e" : @{@"array" : @[ [NSNull null] ]},
  480. @"f" : @{@"array" : @[ @(NAN) ]},
  481. };
  482. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  483. // Search for 42
  484. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  485. arrayContains:@42]];
  486. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  487. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"] ]));
  488. // With null.
  489. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  490. arrayContains:[NSNull null]]];
  491. XCTAssertTrue(snapshot.isEmpty);
  492. // With NAN.
  493. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  494. arrayContains:@(NAN)]];
  495. XCTAssertTrue(snapshot.isEmpty);
  496. }
  497. - (void)testQueriesCanUseInFilters {
  498. NSDictionary *testDocs = @{
  499. @"a" : @{@"zip" : @98101},
  500. @"b" : @{@"zip" : @91102},
  501. @"c" : @{@"zip" : @98103},
  502. @"d" : @{@"zip" : @[ @98101 ]},
  503. @"e" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  504. @"f" : @{@"zip" : @{@"code" : @500}},
  505. @"g" : @{@"zip" : @[ @98101, @98102 ]},
  506. @"h" : @{@"zip" : [NSNull null]},
  507. @"i" : @{@"zip" : @(NAN)}
  508. };
  509. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  510. // Search for zips matching 98101, 98103, and [98101, 98102].
  511. FIRQuerySnapshot *snapshot = [self
  512. readDocumentSetForRef:[collection queryWhereField:@"zip"
  513. in:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  514. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  515. (@[ testDocs[@"a"], testDocs[@"c"], testDocs[@"g"] ]));
  516. // With objects
  517. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  518. in:@[ @{@"code" : @500} ]]];
  519. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"f"] ]));
  520. // With null.
  521. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ [NSNull null] ]]];
  522. XCTAssertTrue(snapshot.isEmpty);
  523. // With null and a value.
  524. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  525. in:@[ [NSNull null], @98101 ]]];
  526. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  527. // With NAN.
  528. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ @(NAN) ]]];
  529. XCTAssertTrue(snapshot.isEmpty);
  530. // With NAN and a value.
  531. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  532. in:@[ @(NAN), @98101 ]]];
  533. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  534. }
  535. - (void)testQueriesCanUseInFiltersWithDocIds {
  536. NSDictionary *testDocs = @{
  537. @"aa" : @{@"key" : @"aa"},
  538. @"ab" : @{@"key" : @"ab"},
  539. @"ba" : @{@"key" : @"ba"},
  540. @"bb" : @{@"key" : @"bb"},
  541. };
  542. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  543. FIRQuerySnapshot *snapshot =
  544. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  545. in:@[ @"aa", @"ab" ]]];
  546. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"aa"], testDocs[@"ab"] ]));
  547. }
  548. - (void)testQueriesCanUseNotInFilters {
  549. // These documents are ordered by value in "zip" since the NOT_IN filter is an inequality, which
  550. // results in documents being sorted by value.
  551. NSDictionary *testDocs = @{
  552. @"a" : @{@"zip" : @(NAN)},
  553. @"b" : @{@"zip" : @91102},
  554. @"c" : @{@"zip" : @98101},
  555. @"d" : @{@"zip" : @98103},
  556. @"e" : @{@"zip" : @[ @98101 ]},
  557. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  558. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  559. @"h" : @{@"zip" : @{@"code" : @500}},
  560. @"i" : @{@"zip" : [NSNull null]},
  561. @"j" : @{@"code" : @500},
  562. };
  563. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  564. // Search for zips not matching 98101, 98103, and [98101, 98102].
  565. FIRQuerySnapshot *snapshot = [self
  566. readDocumentSetForRef:[collection queryWhereField:@"zip"
  567. notIn:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  568. XCTAssertEqualObjects(
  569. FIRQuerySnapshotGetData(snapshot),
  570. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"e"], testDocs[@"g"], testDocs[@"h"] ]));
  571. // With objects.
  572. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  573. notIn:@[ @{@"code" : @500} ]]];
  574. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  575. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  576. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"]
  577. ]));
  578. // With null.
  579. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  580. notIn:@[ [NSNull null] ]]];
  581. XCTAssertTrue(snapshot.isEmpty);
  582. // With NAN.
  583. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" notIn:@[ @(NAN) ]]];
  584. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  585. testDocs[@"b"], testDocs[@"c"], testDocs[@"d"], testDocs[@"e"],
  586. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  587. ]));
  588. // With NAN and a number.
  589. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  590. notIn:@[ @(NAN), @98101 ]]];
  591. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  592. testDocs[@"b"], testDocs[@"d"], testDocs[@"e"], testDocs[@"f"],
  593. testDocs[@"g"], testDocs[@"h"]
  594. ]));
  595. }
  596. - (void)testQueriesCanUseNotInFiltersWithDocIds {
  597. NSDictionary *testDocs = @{
  598. @"aa" : @{@"key" : @"aa"},
  599. @"ab" : @{@"key" : @"ab"},
  600. @"ba" : @{@"key" : @"ba"},
  601. @"bb" : @{@"key" : @"bb"},
  602. };
  603. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  604. FIRQuerySnapshot *snapshot =
  605. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  606. notIn:@[ @"aa", @"ab" ]]];
  607. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"ba"], testDocs[@"bb"] ]));
  608. }
  609. - (void)testSDKUsesNotInFiltersSameAsServer {
  610. NSDictionary *testDocs = @{
  611. @"a" : @{@"zip" : @(NAN)},
  612. @"b" : @{@"zip" : @91102},
  613. @"c" : @{@"zip" : @98101},
  614. @"d" : @{@"zip" : @"98101"},
  615. @"e" : @{@"zip" : @[ @98101 ]},
  616. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  617. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  618. @"h" : @{@"zip" : @{@"code" : @500}},
  619. @"i" : @{@"zip" : [NSNull null]},
  620. @"j" : @{@"code" : @500},
  621. };
  622. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  623. // populate cache with all documents first to ensure getDocsFromCache() scans all docs
  624. [self readDocumentSetForRef:collection];
  625. [self checkOnlineAndOfflineQuery:[collection
  626. queryWhereField:@"zip"
  627. notIn:@[ @98101, @98103, @[ @98101, @98102 ] ]]
  628. matchesResult:@[ @"a", @"b", @"d", @"e", @"g", @"h" ]];
  629. [self checkOnlineAndOfflineQuery:[collection queryWhereField:@"zip" notIn:@[ [NSNull null] ]]
  630. matchesResult:@[]];
  631. }
  632. - (void)testQueriesCanUseArrayContainsAnyFilters {
  633. NSDictionary *testDocs = @{
  634. @"a" : @{@"array" : @[ @42 ]},
  635. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  636. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  637. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  638. @"e" : @{@"array" : @[ @43 ]},
  639. @"f" : @{@"array" : @[ @{@"a" : @42} ]},
  640. @"g" : @{@"array" : @42},
  641. @"h" : @{@"array" : @[ [NSNull null] ]},
  642. @"i" : @{@"array" : @[ @(NAN) ]},
  643. };
  644. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  645. // Search for zips matching [42, 43].
  646. FIRQuerySnapshot *snapshot = [self
  647. readDocumentSetForRef:[collection queryWhereField:@"array" arrayContainsAny:@[ @42, @43 ]]];
  648. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  649. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"], testDocs[@"e"] ]));
  650. // With objects.
  651. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  652. arrayContainsAny:@[ @{@"a" : @42} ]]];
  653. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  654. testDocs[@"f"],
  655. ]));
  656. // With null.
  657. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  658. arrayContainsAny:@[ [NSNull null] ]]];
  659. XCTAssertTrue(snapshot.isEmpty);
  660. // With null and a value.
  661. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  662. arrayContainsAny:@[ [NSNull null], @43 ]]];
  663. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  664. // With NAN.
  665. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  666. arrayContainsAny:@[ @(NAN) ]]];
  667. XCTAssertTrue(snapshot.isEmpty);
  668. // With NAN and a value.
  669. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  670. arrayContainsAny:@[ @(NAN), @43 ]]];
  671. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  672. }
  673. - (void)testCollectionGroupQueries {
  674. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  675. // for predictable ordering.
  676. NSString *collectionGroup = [NSString
  677. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  678. NSArray *docPaths = @[
  679. @"abc/123/${collectionGroup}/cg-doc1", @"abc/123/${collectionGroup}/cg-doc2",
  680. @"${collectionGroup}/cg-doc3", @"${collectionGroup}/cg-doc4",
  681. @"def/456/${collectionGroup}/cg-doc5", @"${collectionGroup}/virtual-doc/nested-coll/not-cg-doc",
  682. @"x${collectionGroup}/not-cg-doc", @"${collectionGroup}x/not-cg-doc",
  683. @"abc/123/${collectionGroup}x/not-cg-doc", @"abc/123/x${collectionGroup}/not-cg-doc",
  684. @"abc/${collectionGroup}"
  685. ];
  686. FIRWriteBatch *batch = [self.db batch];
  687. for (NSString *docPath in docPaths) {
  688. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  689. withString:collectionGroup];
  690. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  691. }
  692. [self commitWriteBatch:batch];
  693. FIRQuerySnapshot *querySnapshot =
  694. [self readDocumentSetForRef:[self.db collectionGroupWithID:collectionGroup]];
  695. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  696. XCTAssertEqualObjects(ids, (@[ @"cg-doc1", @"cg-doc2", @"cg-doc3", @"cg-doc4", @"cg-doc5" ]));
  697. }
  698. - (void)testCollectionGroupQueriesWithStartAtEndAtWithArbitraryDocumentIDs {
  699. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  700. // for predictable ordering.
  701. NSString *collectionGroup = [NSString
  702. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  703. NSArray *docPaths = @[
  704. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  705. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  706. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  707. ];
  708. FIRWriteBatch *batch = [self.db batch];
  709. for (NSString *docPath in docPaths) {
  710. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  711. withString:collectionGroup];
  712. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  713. }
  714. [self commitWriteBatch:batch];
  715. FIRQuerySnapshot *querySnapshot = [self
  716. readDocumentSetForRef:[[[[self.db collectionGroupWithID:collectionGroup]
  717. queryOrderedByFieldPath:[FIRFieldPath documentID]]
  718. queryStartingAfterValues:@[ @"a/b" ]]
  719. queryEndingBeforeValues:@[
  720. [NSString stringWithFormat:@"a/b/%@/cg-doc3", collectionGroup]
  721. ]]];
  722. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  723. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  724. }
  725. - (void)testSnapshotListenerSortsQueryByDocumentIdInTheSameOrderAsServer {
  726. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  727. @"A" : @{@"a" : @1},
  728. @"a" : @{@"a" : @1},
  729. @"Aa" : @{@"a" : @1},
  730. @"7" : @{@"a" : @1},
  731. @"12" : @{@"a" : @1},
  732. @"__id7__" : @{@"a" : @1},
  733. @"__id12__" : @{@"a" : @1},
  734. @"__id-2__" : @{@"a" : @1},
  735. @"__id1_" : @{@"a" : @1},
  736. @"_id1__" : @{@"a" : @1},
  737. @"__id" : @{@"a" : @1},
  738. @"__id9223372036854775807__" : @{@"a" : @1},
  739. @"__id-9223372036854775808__" : @{@"a" : @1},
  740. }];
  741. FIRQuery *query = [collRef queryOrderedByFieldPath:[FIRFieldPath documentID]];
  742. NSArray<NSString *> *expectedDocs = @[
  743. @"__id-9223372036854775808__", @"__id-2__", @"__id7__", @"__id12__",
  744. @"__id9223372036854775807__", @"12", @"7", @"A", @"Aa", @"__id", @"__id1_", @"_id1__", @"a"
  745. ];
  746. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  747. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  748. id<FIRListenerRegistration> registration =
  749. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  750. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  751. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  752. [registration remove];
  753. }
  754. - (void)testSnapshotListenerSortsFilteredQueryByDocumentIdInTheSameOrderAsServer {
  755. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  756. @"A" : @{@"a" : @1},
  757. @"a" : @{@"a" : @1},
  758. @"Aa" : @{@"a" : @1},
  759. @"7" : @{@"a" : @1},
  760. @"12" : @{@"a" : @1},
  761. @"__id7__" : @{@"a" : @1},
  762. @"__id12__" : @{@"a" : @1},
  763. @"__id-2__" : @{@"a" : @1},
  764. @"__id1_" : @{@"a" : @1},
  765. @"_id1__" : @{@"a" : @1},
  766. @"__id" : @{@"a" : @1},
  767. @"__id9223372036854775807__" : @{@"a" : @1},
  768. @"__id-9223372036854775808__" : @{@"a" : @1},
  769. }];
  770. FIRQuery *query = [[[collRef queryWhereFieldPath:[FIRFieldPath documentID]
  771. isGreaterThan:@"__id7__"]
  772. queryWhereFieldPath:[FIRFieldPath documentID]
  773. isLessThanOrEqualTo:@"A"] queryOrderedByFieldPath:[FIRFieldPath documentID]];
  774. NSArray<NSString *> *expectedDocs =
  775. @[ @"__id12__", @"__id9223372036854775807__", @"12", @"7", @"A" ];
  776. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  777. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  778. id<FIRListenerRegistration> registration =
  779. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  780. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  781. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  782. [registration remove];
  783. }
  784. - (void)testSdkOrdersQueryByDocumentIdTheSameWayOnlineAndOffline {
  785. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  786. @"A" : @{@"a" : @1},
  787. @"a" : @{@"a" : @1},
  788. @"Aa" : @{@"a" : @1},
  789. @"7" : @{@"a" : @1},
  790. @"12" : @{@"a" : @1},
  791. @"__id7__" : @{@"a" : @1},
  792. @"__id12__" : @{@"a" : @1},
  793. @"__id-2__" : @{@"a" : @1},
  794. @"__id1_" : @{@"a" : @1},
  795. @"_id1__" : @{@"a" : @1},
  796. @"__id" : @{@"a" : @1},
  797. @"__id9223372036854775807__" : @{@"a" : @1},
  798. @"__id-9223372036854775808__" : @{@"a" : @1},
  799. }];
  800. [self checkOnlineAndOfflineQuery:[collRef queryOrderedByFieldPath:[FIRFieldPath documentID]]
  801. matchesResult:@[
  802. @"__id-9223372036854775808__", @"__id-2__", @"__id7__", @"__id12__",
  803. @"__id9223372036854775807__", @"12", @"7", @"A", @"Aa", @"__id", @"__id1_",
  804. @"_id1__", @"a"
  805. ]];
  806. }
  807. - (void)testSnapshotListenerSortsUnicodeStringsInTheSameOrderAsServer {
  808. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  809. @"a" : @{@"value" : @"Łukasiewicz"},
  810. @"b" : @{@"value" : @"Sierpiński"},
  811. @"c" : @{@"value" : @"岩澤"},
  812. @"d" : @{@"value" : @"🄟"},
  813. @"e" : @{@"value" : @"P"},
  814. @"f" : @{@"value" : @"︒"},
  815. @"g" : @{@"value" : @"🐵"}
  816. }];
  817. FIRQuery *query = [collRef queryOrderedByField:@"value"];
  818. NSArray<NSString *> *expectedDocs = @[ @"b", @"a", @"c", @"f", @"e", @"d", @"g" ];
  819. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  820. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  821. id<FIRListenerRegistration> registration =
  822. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  823. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  824. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  825. [registration remove];
  826. [self checkOnlineAndOfflineQuery:query matchesResult:expectedDocs];
  827. }
  828. - (void)testSnapshotListenerSortsUnicodeStringsInArrayInTheSameOrderAsServer {
  829. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  830. @"a" : @{@"value" : @[ @"Łukasiewicz" ]},
  831. @"b" : @{@"value" : @[ @"Sierpiński" ]},
  832. @"c" : @{@"value" : @[ @"岩澤" ]},
  833. @"d" : @{@"value" : @[ @"🄟" ]},
  834. @"e" : @{@"value" : @[ @"P" ]},
  835. @"f" : @{@"value" : @[ @"︒" ]},
  836. @"g" : @{@"value" : @[ @"🐵" ]}
  837. }];
  838. FIRQuery *query = [collRef queryOrderedByField:@"value"];
  839. NSArray<NSString *> *expectedDocs = @[ @"b", @"a", @"c", @"f", @"e", @"d", @"g" ];
  840. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  841. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  842. id<FIRListenerRegistration> registration =
  843. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  844. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  845. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  846. [registration remove];
  847. [self checkOnlineAndOfflineQuery:query matchesResult:expectedDocs];
  848. }
  849. - (void)testSnapshotListenerSortsUnicodeStringsInMapInTheSameOrderAsServer {
  850. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  851. @"a" : @{@"value" : @{@"foo" : @"Łukasiewicz"}},
  852. @"b" : @{@"value" : @{@"foo" : @"Sierpiński"}},
  853. @"c" : @{@"value" : @{@"foo" : @"岩澤"}},
  854. @"d" : @{@"value" : @{@"foo" : @"🄟"}},
  855. @"e" : @{@"value" : @{@"foo" : @"P"}},
  856. @"f" : @{@"value" : @{@"foo" : @"︒"}},
  857. @"g" : @{@"value" : @{@"foo" : @"🐵"}}
  858. }];
  859. FIRQuery *query = [collRef queryOrderedByField:@"value"];
  860. NSArray<NSString *> *expectedDocs = @[ @"b", @"a", @"c", @"f", @"e", @"d", @"g" ];
  861. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  862. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  863. id<FIRListenerRegistration> registration =
  864. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  865. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  866. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  867. [registration remove];
  868. [self checkOnlineAndOfflineQuery:query matchesResult:expectedDocs];
  869. }
  870. - (void)testSnapshotListenerSortsUnicodeStringsInMapKeyInTheSameOrderAsServer {
  871. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  872. @"a" : @{@"value" : @{@"Łukasiewicz" : @"foo"}},
  873. @"b" : @{@"value" : @{@"Sierpiński" : @"foo"}},
  874. @"c" : @{@"value" : @{@"岩澤" : @"foo"}},
  875. @"d" : @{@"value" : @{@"🄟" : @"foo"}},
  876. @"e" : @{@"value" : @{@"P" : @"foo"}},
  877. @"f" : @{@"value" : @{@"︒" : @"foo"}},
  878. @"g" : @{@"value" : @{@"🐵" : @"foo"}}
  879. }];
  880. FIRQuery *query = [collRef queryOrderedByField:@"value"];
  881. NSArray<NSString *> *expectedDocs = @[ @"b", @"a", @"c", @"f", @"e", @"d", @"g" ];
  882. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  883. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  884. id<FIRListenerRegistration> registration =
  885. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  886. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  887. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  888. [registration remove];
  889. [self checkOnlineAndOfflineQuery:query matchesResult:expectedDocs];
  890. }
  891. - (void)testSnapshotListenerSortsUnicodeStringsInDocumentKeyInTheSameOrderAsServer {
  892. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  893. @"Łukasiewicz" : @{@"value" : @"foo"},
  894. @"Sierpiński" : @{@"value" : @"foo"},
  895. @"岩澤" : @{@"value" : @"foo"},
  896. @"🄟" : @{@"value" : @"foo"},
  897. @"P" : @{@"value" : @"foo"},
  898. @"︒" : @{@"value" : @"foo"},
  899. @"🐵" : @{@"value" : @"foo"}
  900. }];
  901. FIRQuery *query = [collRef queryOrderedByFieldPath:[FIRFieldPath documentID]];
  902. NSArray<NSString *> *expectedDocs =
  903. @[ @"Sierpiński", @"Łukasiewicz", @"岩澤", @"︒", @"P", @"🄟", @"🐵" ];
  904. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  905. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  906. id<FIRListenerRegistration> registration =
  907. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  908. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  909. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  910. [registration remove];
  911. [self checkOnlineAndOfflineQuery:query matchesResult:expectedDocs];
  912. }
  913. - (void)testCollectionGroupQueriesWithWhereFiltersOnArbitraryDocumentIDs {
  914. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  915. // for predictable ordering.
  916. NSString *collectionGroup = [NSString
  917. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  918. NSArray *docPaths = @[
  919. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  920. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  921. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  922. ];
  923. FIRWriteBatch *batch = [self.db batch];
  924. for (NSString *docPath in docPaths) {
  925. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  926. withString:collectionGroup];
  927. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  928. }
  929. [self commitWriteBatch:batch];
  930. FIRQuerySnapshot *querySnapshot = [self
  931. readDocumentSetForRef:[[[self.db collectionGroupWithID:collectionGroup]
  932. queryWhereFieldPath:[FIRFieldPath documentID]
  933. isGreaterThanOrEqualTo:@"a/b"]
  934. queryWhereFieldPath:[FIRFieldPath documentID]
  935. isLessThan:[NSString stringWithFormat:@"a/b/%@/cg-doc3",
  936. collectionGroup]]];
  937. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  938. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  939. }
  940. - (void)testOrQueries {
  941. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  942. @"doc1" : @{@"a" : @1, @"b" : @0},
  943. @"doc2" : @{@"a" : @2, @"b" : @1},
  944. @"doc3" : @{@"a" : @3, @"b" : @2},
  945. @"doc4" : @{@"a" : @1, @"b" : @3},
  946. @"doc5" : @{@"a" : @1, @"b" : @1}
  947. }];
  948. // Two equalities: a==1 || b==1.
  949. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  950. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  951. ]];
  952. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  953. matchesResult:@[ @"doc1", @"doc2", @"doc4", @"doc5" ]];
  954. // (a==1 && b==0) || (a==3 && b==2)
  955. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  956. [FIRFilter andFilterWithFilters:@[
  957. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@0]
  958. ]],
  959. [FIRFilter andFilterWithFilters:@[
  960. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  961. ]]
  962. ]];
  963. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  964. matchesResult:@[ @"doc1", @"doc3" ]];
  965. // a==1 && (b==0 || b==3).
  966. FIRFilter *filter3 = [FIRFilter andFilterWithFilters:@[
  967. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter orFilterWithFilters:@[
  968. [FIRFilter filterWhereField:@"b" isEqualTo:@0], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  969. ]]
  970. ]];
  971. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  972. matchesResult:@[ @"doc1", @"doc4" ]];
  973. // (a==2 || b==2) && (a==3 || b==3)
  974. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  975. [FIRFilter orFilterWithFilters:@[
  976. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  977. ]],
  978. [FIRFilter orFilterWithFilters:@[
  979. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  980. ]]
  981. ]];
  982. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  983. // Test with limits without orderBy (the __name__ ordering is the tie breaker).
  984. FIRFilter *filter5 = [FIRFilter orFilterWithFilters:@[
  985. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  986. ]];
  987. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:filter5] queryLimitedTo:1]
  988. matchesResult:@[ @"doc2" ]];
  989. }
  990. - (void)testOrQueriesWithIn {
  991. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  992. @"doc1" : @{@"a" : @1, @"b" : @0},
  993. @"doc2" : @{@"b" : @1},
  994. @"doc3" : @{@"a" : @3, @"b" : @2},
  995. @"doc4" : @{@"a" : @1, @"b" : @3},
  996. @"doc5" : @{@"a" : @1},
  997. @"doc6" : @{@"a" : @2}
  998. }];
  999. // a==2 || b in [2,3]
  1000. FIRFilter *filter = [FIRFilter orFilterWithFilters:@[
  1001. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" in:@[ @2, @3 ]]
  1002. ]];
  1003. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  1004. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  1005. }
  1006. - (void)testOrQueriesWithArrayMembership {
  1007. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1008. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  1009. @"doc2" : @{@"b" : @[ @1 ]},
  1010. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  1011. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  1012. @"doc5" : @{@"a" : @1},
  1013. @"doc6" : @{@"a" : @2}
  1014. }];
  1015. // a==2 || b array-contains 7
  1016. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  1017. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  1018. arrayContains:@7]
  1019. ]];
  1020. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  1021. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  1022. // a==2 || b array-contains-any [0, 3]
  1023. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  1024. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  1025. arrayContainsAny:@[ @0, @3 ]]
  1026. ]];
  1027. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  1028. matchesResult:@[ @"doc1", @"doc4", @"doc6" ]];
  1029. }
  1030. - (void)testMultipleInOps {
  1031. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1032. @"doc1" : @{@"a" : @1, @"b" : @0},
  1033. @"doc2" : @{@"b" : @1},
  1034. @"doc3" : @{@"a" : @3, @"b" : @2},
  1035. @"doc4" : @{@"a" : @1, @"b" : @3},
  1036. @"doc5" : @{@"a" : @1},
  1037. @"doc6" : @{@"a" : @2}
  1038. }];
  1039. // Two IN operations on different fields with disjunction.
  1040. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  1041. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  1042. in:@[ @0, @2 ]]
  1043. ]];
  1044. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  1045. matchesResult:@[ @"doc1", @"doc3", @"doc6" ]];
  1046. // Two IN operations on the same field with disjunction.
  1047. // a IN [0,3] || a IN [0,2] should union them (similar to: a IN [0,2,3]).
  1048. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  1049. [FIRFilter filterWhereField:@"a" in:@[ @0, @3 ]], [FIRFilter filterWhereField:@"a"
  1050. in:@[ @0, @2 ]]
  1051. ]];
  1052. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  1053. matchesResult:@[ @"doc3", @"doc6" ]];
  1054. }
  1055. - (void)testUsingInWithArrayContainsAny {
  1056. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1057. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  1058. @"doc2" : @{@"b" : @[ @1 ]},
  1059. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  1060. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  1061. @"doc5" : @{@"a" : @1},
  1062. @"doc6" : @{@"a" : @2, @"c" : @20}
  1063. }];
  1064. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  1065. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  1066. arrayContainsAny:@[ @0, @7 ]]
  1067. ]];
  1068. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  1069. matchesResult:@[ @"doc1", @"doc3", @"doc4", @"doc6" ]];
  1070. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  1071. [FIRFilter andFilterWithFilters:@[
  1072. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"c"
  1073. isEqualTo:@10]
  1074. ]],
  1075. [FIRFilter filterWhereField:@"b" arrayContainsAny:@[ @0, @7 ]]
  1076. ]];
  1077. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  1078. matchesResult:@[ @"doc1", @"doc3", @"doc4" ]];
  1079. }
  1080. - (void)testUseInWithArrayContains {
  1081. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1082. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  1083. @"doc2" : @{@"b" : @[ @1 ]},
  1084. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  1085. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  1086. @"doc5" : @{@"a" : @1},
  1087. @"doc6" : @{@"a" : @2}
  1088. }];
  1089. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  1090. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  1091. arrayContainsAny:@[ @3 ]]
  1092. ]];
  1093. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  1094. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  1095. FIRFilter *filter2 = [FIRFilter andFilterWithFilters:@[
  1096. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  1097. arrayContains:@7]
  1098. ]];
  1099. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2] matchesResult:@[ @"doc3" ]];
  1100. FIRFilter *filter3 = [FIRFilter orFilterWithFilters:@[
  1101. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter andFilterWithFilters:@[
  1102. [FIRFilter filterWhereField:@"b" arrayContains:@3], [FIRFilter filterWhereField:@"a"
  1103. isEqualTo:@1]
  1104. ]]
  1105. ]];
  1106. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  1107. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  1108. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  1109. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter orFilterWithFilters:@[
  1110. [FIRFilter filterWhereField:@"b" arrayContains:@7], [FIRFilter filterWhereField:@"a"
  1111. isEqualTo:@1]
  1112. ]]
  1113. ]];
  1114. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  1115. }
  1116. - (void)testOrderByEquality {
  1117. // TODO(orquery): Enable this test against production when possible.
  1118. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1119. "Skip this test if running against production because order-by-equality is not "
  1120. "supported yet.");
  1121. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1122. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  1123. @"doc2" : @{@"b" : @[ @1 ]},
  1124. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  1125. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  1126. @"doc5" : @{@"a" : @1},
  1127. @"doc6" : @{@"a" : @2, @"c" : @20}
  1128. }];
  1129. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:[FIRFilter filterWhereField:@"a"
  1130. isEqualTo:@1]]
  1131. queryOrderedByField:@"a"]
  1132. matchesResult:@[ @"doc1", @"doc4", @"doc5" ]];
  1133. [self checkOnlineAndOfflineQuery:[[collRef
  1134. queryWhereFilter:[FIRFilter filterWhereField:@"a"
  1135. in:@[ @2, @3 ]]]
  1136. queryOrderedByField:@"a"]
  1137. matchesResult:@[ @"doc6", @"doc3" ]];
  1138. }
  1139. - (void)testResumingAQueryShouldUseBloomFilterToAvoidFullRequery {
  1140. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1141. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1142. // sends.
  1143. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1144. "Skip this test when running against the Firestore emulator because the emulator does "
  1145. "not include a bloom filter when it sends existence filter messages, making it "
  1146. "impossible for this test to verify the correctness of the bloom filter.");
  1147. // Set this test to stop when the first failure occurs because some test assertion failures make
  1148. // the rest of the test not applicable or will even crash.
  1149. [self setContinueAfterFailure:NO];
  1150. // Prepare the names and contents of the 100 documents to create.
  1151. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1152. [[NSMutableDictionary alloc] init];
  1153. for (int i = 0; i < 100; i++) {
  1154. [testDocs setValue:@{@"key" : @42} forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1155. }
  1156. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1157. // be run multiple times only if a bloom filter false positive occurs.
  1158. int attemptNumber = 0;
  1159. while (true) {
  1160. attemptNumber++;
  1161. // Create 100 documents in a new collection.
  1162. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1163. // Run a query to populate the local cache with the 100 documents and a resume token.
  1164. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1165. source:FIRFirestoreSourceDefault];
  1166. XCTAssertEqual(querySnapshot1.count, 100, @"querySnapshot1.count has an unexpected value");
  1167. NSArray<FIRDocumentReference *> *createdDocuments =
  1168. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1169. // Delete 50 of the 100 documents. Use a different Firestore instance to avoid affecting the
  1170. // local cache.
  1171. NSSet<NSString *> *deletedDocumentIds;
  1172. {
  1173. FIRFirestore *db2 = [self firestore];
  1174. FIRWriteBatch *batch = [db2 batch];
  1175. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1176. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 2) {
  1177. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1178. [batch deleteDocument:documentToDelete];
  1179. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1180. }
  1181. [self commitWriteBatch:batch];
  1182. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1183. }
  1184. XCTAssertEqual(deletedDocumentIds.count, 50u, @"deletedDocumentIds has the wrong size");
  1185. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1186. // existence filter rather than "delete" events when the query is resumed.
  1187. [NSThread sleepForTimeInterval:10.0f];
  1188. // Resume the query and save the resulting snapshot for verification.
  1189. // Use some internal testing hooks to "capture" the existence filter mismatches to verify that
  1190. // Watch sent a bloom filter, and it was used to avert a full requery.
  1191. __block FIRQuerySnapshot *querySnapshot2;
  1192. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1193. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1194. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1195. }];
  1196. // Verify that the snapshot from the resumed query contains the expected documents; that is,
  1197. // that it contains the 50 documents that were _not_ deleted.
  1198. {
  1199. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1200. for (FIRDocumentReference *documentRef in createdDocuments) {
  1201. if (![deletedDocumentIds containsObject:documentRef.documentID]) {
  1202. [expectedDocumentIds addObject:documentRef.documentID];
  1203. }
  1204. }
  1205. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1206. [NSSet setWithArray:expectedDocumentIds],
  1207. @"querySnapshot2 has the wrong documents");
  1208. }
  1209. // Verify that Watch sent an existence filter with the correct counts when the query was
  1210. // resumed.
  1211. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1212. @"Watch should have sent exactly 1 existence filter");
  1213. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1214. existenceFilterMismatches[0];
  1215. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 100);
  1216. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 50);
  1217. // Verify that Watch sent a valid bloom filter.
  1218. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1219. XCTAssertNotNil(bloomFilter,
  1220. "Watch should have included a bloom filter in the existence filter");
  1221. XCTAssertGreaterThan(bloomFilter.hashCount, 0);
  1222. XCTAssertGreaterThan(bloomFilter.bitmapLength, 0);
  1223. XCTAssertGreaterThan(bloomFilter.padding, 0);
  1224. XCTAssertLessThan(bloomFilter.padding, 8);
  1225. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1226. // positive occurred then retry the entire test. Although statistically rare, false positives
  1227. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1228. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1229. // fail the test because that is so improbable that something must have gone wrong.
  1230. if (attemptNumber == 1 && !bloomFilter.applied) {
  1231. continue;
  1232. }
  1233. XCTAssertTrue(bloomFilter.applied,
  1234. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1235. @(attemptNumber));
  1236. // Break out of the test loop now that the test passes.
  1237. break;
  1238. }
  1239. }
  1240. - (void)
  1241. testBloomFilterShouldAvertAFullRequeryWhenDocumentsWereAddedDeletedRemovedUpdatedAndUnchangedSinceTheResumeToken {
  1242. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1243. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1244. // sends.
  1245. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1246. "Skip this test when running against the Firestore emulator because the emulator does "
  1247. "not include a bloom filter when it sends existence filter messages, making it "
  1248. "impossible for this test to verify the correctness of the bloom filter.");
  1249. // Set this test to stop when the first failure occurs because some test assertion failures make
  1250. // the rest of the test not applicable or will even crash.
  1251. [self setContinueAfterFailure:NO];
  1252. // Prepare the names and contents of the 20 documents to create.
  1253. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1254. [[NSMutableDictionary alloc] init];
  1255. for (int i = 0; i < 20; i++) {
  1256. [testDocs setValue:@{@"key" : @42, @"removed" : @NO}
  1257. forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1258. }
  1259. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1260. // be run multiple times only if a bloom filter false positive occurs.
  1261. int attemptNumber = 0;
  1262. while (true) {
  1263. attemptNumber++;
  1264. // Create 20 documents in a new collection.
  1265. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1266. FIRQuery *query = [collRef queryWhereField:@"removed" isEqualTo:@NO];
  1267. // Run a query to populate the local cache with the 20 documents and a resume token.
  1268. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:query
  1269. source:FIRFirestoreSourceDefault];
  1270. XCTAssertEqual(querySnapshot1.count, 20u, @"querySnapshot1.count has an unexpected value");
  1271. NSArray<FIRDocumentReference *> *createdDocuments =
  1272. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1273. // Out of the 20 existing documents, leave 5 docs untouched, delete 5 docs, remove 5 docs,
  1274. // update 5 docs, and add 15 new docs.
  1275. NSSet<NSString *> *deletedDocumentIds;
  1276. NSSet<NSString *> *removedDocumentIds;
  1277. NSSet<NSString *> *updatedDocumentIds;
  1278. NSMutableArray<NSString *> *addedDocumentIds = [[NSMutableArray alloc] init];
  1279. {
  1280. FIRFirestore *db2 = [self firestore];
  1281. FIRWriteBatch *batch = [db2 batch];
  1282. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1283. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 4) {
  1284. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1285. [batch deleteDocument:documentToDelete];
  1286. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1287. }
  1288. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1289. XCTAssertEqual(deletedDocumentIds.count, 5u, @"deletedDocumentIds has the wrong size");
  1290. // Update 5 documents to no longer match the query.
  1291. NSMutableArray<NSString *> *removedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1292. for (decltype(createdDocuments.count) i = 1; i < createdDocuments.count; i += 4) {
  1293. FIRDocumentReference *documentToRemove = [db2 documentWithPath:createdDocuments[i].path];
  1294. [batch updateData:@{@"removed" : @YES} forDocument:documentToRemove];
  1295. [removedDocumentIdsAccumulator addObject:documentToRemove.documentID];
  1296. }
  1297. removedDocumentIds = [NSSet setWithArray:removedDocumentIdsAccumulator];
  1298. XCTAssertEqual(removedDocumentIds.count, 5u, @"removedDocumentIds has the wrong size");
  1299. // Update 5 documents, but ensure they still match the query.
  1300. NSMutableArray<NSString *> *updatedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1301. for (decltype(createdDocuments.count) i = 2; i < createdDocuments.count; i += 4) {
  1302. FIRDocumentReference *documentToUpdate = [db2 documentWithPath:createdDocuments[i].path];
  1303. [batch updateData:@{@"key" : @43} forDocument:documentToUpdate];
  1304. [updatedDocumentIdsAccumulator addObject:documentToUpdate.documentID];
  1305. }
  1306. updatedDocumentIds = [NSSet setWithArray:updatedDocumentIdsAccumulator];
  1307. XCTAssertEqual(updatedDocumentIds.count, 5u, @"updatedDocumentIds has the wrong size");
  1308. for (int i = 0; i < 15; i += 1) {
  1309. FIRDocumentReference *documentToAdd = [db2
  1310. documentWithPath:[NSString stringWithFormat:@"%@/newDoc%@", collRef.path, @(1000 + i)]];
  1311. [batch setData:@{@"key" : @42, @"removed" : @NO} forDocument:documentToAdd];
  1312. [addedDocumentIds addObject:documentToAdd.documentID];
  1313. }
  1314. // Ensure the documentIds above are mutually exclusive.
  1315. NSMutableSet<NSString *> *mergedSet = [NSMutableSet setWithArray:addedDocumentIds];
  1316. [mergedSet unionSet:deletedDocumentIds];
  1317. [mergedSet unionSet:removedDocumentIds];
  1318. [mergedSet unionSet:updatedDocumentIds];
  1319. XCTAssertEqual(mergedSet.count, 30u, @"There are documents experienced multiple operations.");
  1320. [self commitWriteBatch:batch];
  1321. }
  1322. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1323. // existence filter rather than "delete" events when the query is resumed.
  1324. [NSThread sleepForTimeInterval:10.0f];
  1325. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1326. // hooks to "capture" the existence filter mismatches to verify that Watch sent a bloom
  1327. // filter, and it was used to avert a full requery.
  1328. __block FIRQuerySnapshot *querySnapshot2;
  1329. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1330. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1331. querySnapshot2 = [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  1332. }];
  1333. XCTAssertEqual(querySnapshot2.count, 25u, @"querySnapshot1.count has an unexpected value");
  1334. // Verify that the snapshot from the resumed query contains the expected documents; that is, 10
  1335. // existing documents that still match the query, and 15 documents that are newly added.
  1336. {
  1337. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1338. for (FIRDocumentReference *documentRef in createdDocuments) {
  1339. if (![deletedDocumentIds containsObject:documentRef.documentID] &&
  1340. ![removedDocumentIds containsObject:documentRef.documentID]) {
  1341. [expectedDocumentIds addObject:documentRef.documentID];
  1342. }
  1343. }
  1344. [expectedDocumentIds addObjectsFromArray:addedDocumentIds];
  1345. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1346. [NSSet setWithArray:expectedDocumentIds],
  1347. @"querySnapshot2 has the wrong documents");
  1348. }
  1349. // Verify that Watch sent an existence filter with the correct counts when the query was
  1350. // resumed.
  1351. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1352. @"Watch should have sent exactly 1 existence filter");
  1353. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1354. existenceFilterMismatches[0];
  1355. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 35);
  1356. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 25);
  1357. // Verify that Watch sent a valid bloom filter.
  1358. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1359. XCTAssertNotNil(bloomFilter,
  1360. "Watch should have included a bloom filter in the existence filter");
  1361. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1362. // positive occurred then retry the entire test. Although statistically rare, false positives
  1363. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1364. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1365. // fail the test because that is so improbable that something must have gone wrong.
  1366. if (attemptNumber == 1 && !bloomFilter.applied) {
  1367. continue;
  1368. }
  1369. XCTAssertTrue(bloomFilter.applied,
  1370. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1371. @(attemptNumber));
  1372. // Break out of the test loop now that the test passes.
  1373. break;
  1374. }
  1375. }
  1376. - (void)testBloomFilterShouldCorrectlyEncodeComplexUnicodeCharacters {
  1377. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1378. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1379. // sends.
  1380. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1381. "Skip this test when running against the Firestore emulator because the emulator does "
  1382. "not include a bloom filter when it sends existence filter messages, making it "
  1383. "impossible for this test to verify the correctness of the bloom filter.");
  1384. // Set this test to stop when the first failure occurs because some test assertion failures make
  1385. // the rest of the test not applicable or will even crash.
  1386. [self setContinueAfterFailure:NO];
  1387. // Define a comparator that compares `NSString` objects in a way that orders canonically-
  1388. // equivalent, but distinct, strings in a consistent manner by using `NSForcedOrderingSearch`.
  1389. // Otherwise, the bare `[NSString compare:]` method considers canonically-equivalent, but
  1390. // distinct, strings as "equal" and orders them indeterminately.
  1391. NSComparator sortComparator = ^(NSString *string1, NSString *string2) {
  1392. return [string1 compare:string2 options:NSForcedOrderingSearch];
  1393. };
  1394. // Firestore does not do any Unicode normalization on the document IDs. Therefore, two document
  1395. // IDs that are canonically-equivalent (i.e. they visually appear identical) but are represented
  1396. // by a different sequence of Unicode code points are treated as distinct document IDs.
  1397. NSArray<NSString *> *testDocIds;
  1398. {
  1399. NSMutableArray<NSString *> *testDocIdsAccumulator = [[NSMutableArray alloc] init];
  1400. [testDocIdsAccumulator addObject:@"DocumentToDelete"];
  1401. // The next two strings both end with "e" with an accent: the first uses the dedicated Unicode
  1402. // code point for this character, while the second uses the standard lowercase "e" followed by
  1403. // the accent combining character.
  1404. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u00E9"];
  1405. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u0065\u0301"];
  1406. // The next two strings both end with an "e" with two different accents applied via the
  1407. // following two combining characters. The combining characters are specified in a different
  1408. // order and Firestore treats these document IDs as unique, despite the order of the combining
  1409. // characters being irrelevant.
  1410. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0301\u0327"];
  1411. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0327\u0301"];
  1412. // The next string contains a character outside the BMP (the "basic multilingual plane"); that
  1413. // is, its code point is greater than 0xFFFF. Since NSString stores text in sequences of 16-bit
  1414. // code units, using the UTF-16 encoding (according to
  1415. // https://www.objc.io/issues/9-strings/unicode) it is stored as a surrogate pair, two 16-bit
  1416. // code units U+D83D and U+DE00, to represent this character. Make sure that its presence is
  1417. // correctly tested in the bloom filter, which uses UTF-8 encoding.
  1418. [testDocIdsAccumulator addObject:@"Smiley_\U0001F600"];
  1419. testDocIds = [NSArray arrayWithArray:testDocIdsAccumulator];
  1420. }
  1421. // Verify assumptions about the equivalence of strings in `testDocIds`.
  1422. XCTAssertEqualObjects(testDocIds[1].decomposedStringWithCanonicalMapping,
  1423. testDocIds[2].decomposedStringWithCanonicalMapping);
  1424. XCTAssertEqualObjects(testDocIds[3].decomposedStringWithCanonicalMapping,
  1425. testDocIds[4].decomposedStringWithCanonicalMapping);
  1426. XCTAssertEqual([testDocIds[5] characterAtIndex:7], 0xD83D);
  1427. XCTAssertEqual([testDocIds[5] characterAtIndex:8], 0xDE00);
  1428. // Create the mapping from document ID to document data for the document IDs specified in
  1429. // `testDocIds`.
  1430. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1431. [[NSMutableDictionary alloc] init];
  1432. for (NSString *testDocId in testDocIds) {
  1433. [testDocs setValue:@{@"foo" : @42} forKey:testDocId];
  1434. }
  1435. // Create the documents whose names contain complex Unicode characters in a new collection.
  1436. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1437. // Run a query to populate the local cache with documents that have names with complex Unicode
  1438. // characters.
  1439. {
  1440. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1441. source:FIRFirestoreSourceDefault];
  1442. XCTAssertEqualObjects(
  1443. [FIRQuerySnapshotGetIDs(querySnapshot1) sortedArrayUsingComparator:sortComparator],
  1444. [testDocIds sortedArrayUsingComparator:sortComparator],
  1445. @"querySnapshot1 has the wrong documents");
  1446. }
  1447. // Delete one of the documents so that the next call to collection.get() will experience an
  1448. // existence filter mismatch. Use a different Firestore instance to avoid affecting the local
  1449. // cache.
  1450. FIRDocumentReference *documentToDelete = [collRef documentWithPath:@"DocumentToDelete"];
  1451. {
  1452. FIRFirestore *db2 = [self firestore];
  1453. [self deleteDocumentRef:[db2 documentWithPath:documentToDelete.path]];
  1454. }
  1455. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1456. // existence filter rather than "delete" events when the query is resumed.
  1457. [NSThread sleepForTimeInterval:10.0f];
  1458. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1459. // hooks to "capture" the existence filter mismatches.
  1460. __block FIRQuerySnapshot *querySnapshot2;
  1461. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1462. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1463. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1464. }];
  1465. // Verify that the snapshot from the resumed query contains the expected documents; that is, that
  1466. // it contains the documents whose names contain complex Unicode characters and _not_ the document
  1467. // that was deleted.
  1468. {
  1469. NSMutableArray<NSString *> *querySnapshot2ExpectedDocumentIds =
  1470. [NSMutableArray arrayWithArray:testDocIds];
  1471. [querySnapshot2ExpectedDocumentIds removeObject:documentToDelete.documentID];
  1472. XCTAssertEqualObjects(
  1473. [FIRQuerySnapshotGetIDs(querySnapshot2) sortedArrayUsingComparator:sortComparator],
  1474. [querySnapshot2ExpectedDocumentIds sortedArrayUsingComparator:sortComparator],
  1475. @"querySnapshot2 has the wrong documents");
  1476. }
  1477. // Verify that Watch sent an existence filter with the correct counts.
  1478. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1479. @"Watch should have sent exactly 1 existence filter");
  1480. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1481. existenceFilterMismatches[0];
  1482. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, (int)testDocIds.count);
  1483. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, (int)testDocIds.count - 1);
  1484. // Verify that Watch sent a valid bloom filter.
  1485. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1486. XCTAssertNotNil(bloomFilter, "Watch should have included a bloom filter in the existence filter");
  1487. // The bloom filter application should statistically be successful almost every time; the _only_
  1488. // time when it would _not_ be successful is if there is a false positive when testing for
  1489. // 'DocumentToDelete' in the bloom filter. So verify that the bloom filter application is
  1490. // successful, unless there was a false positive.
  1491. BOOL isFalsePositive = [bloomFilter mightContain:documentToDelete];
  1492. XCTAssertEqual(bloomFilter.applied, !isFalsePositive);
  1493. // Verify that the bloom filter contains the document paths with complex Unicode characters.
  1494. for (FIRDocumentSnapshot *documentSnapshot in querySnapshot2.documents) {
  1495. XCTAssertTrue([bloomFilter mightContain:documentSnapshot.reference],
  1496. @"The bloom filter should contain %@", documentSnapshot.documentID);
  1497. }
  1498. }
  1499. @end