FIRValidationTests.mm 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. #include <limits>
  19. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  20. #import "Firestore/Source/API/FIRQuery+Internal.h"
  21. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  22. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  23. // We have tests for passing nil when nil is not supposed to be allowed. So suppress the warnings.
  24. #pragma clang diagnostic ignored "-Wnonnull"
  25. @interface FIRValidationTests : FSTIntegrationTestCase
  26. @end
  27. @implementation FIRValidationTests
  28. #pragma mark - FIRFirestoreSettings Validation
  29. - (void)testNilHostFails {
  30. FIRFirestoreSettings *settings = self.db.settings;
  31. FSTAssertThrows(settings.host = nil,
  32. @"Host setting may not be nil. You should generally just use the default value "
  33. "(which is firestore.googleapis.com)");
  34. }
  35. - (void)testNilDispatchQueueFails {
  36. FIRFirestoreSettings *settings = self.db.settings;
  37. FSTAssertThrows(settings.dispatchQueue = nil,
  38. @"Dispatch queue setting may not be nil. Create a new dispatch queue with "
  39. "dispatch_queue_create(\"com.example.MyQueue\", NULL) or just use the default "
  40. "(which is the main queue, returned from dispatch_get_main_queue())");
  41. }
  42. - (void)testChangingSettingsAfterUseFails {
  43. FIRFirestoreSettings *settings = self.db.settings;
  44. [[self.db documentWithPath:@"foo/bar"] setData:@{@"a" : @42}];
  45. settings.host = @"example.com";
  46. FSTAssertThrows(self.db.settings = settings,
  47. @"Firestore instance has already been started and its settings can no longer be "
  48. @"changed. You can only set settings before calling any other methods on "
  49. @"a Firestore instance.");
  50. }
  51. #pragma mark - FIRFirestore Validation
  52. - (void)testNilFIRAppFails {
  53. FSTAssertThrows(
  54. [FIRFirestore firestoreForApp:nil],
  55. @"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd like to use the "
  56. "default FirebaseApp instance.");
  57. }
  58. // TODO(b/62410906): Test for firestoreForApp:database: with nil DatabaseID.
  59. - (void)testNilTransactionBlocksFail {
  60. FSTAssertThrows([self.db runTransactionWithBlock:nil
  61. completion:^(id result, NSError *error) {
  62. XCTFail(@"Completion shouldn't run.");
  63. }],
  64. @"Transaction block cannot be nil.");
  65. FSTAssertThrows([self.db
  66. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  67. XCTFail(@"Transaction block shouldn't run.");
  68. return nil;
  69. }
  70. completion:nil],
  71. @"Transaction completion block cannot be nil.");
  72. }
  73. #pragma mark - Collection and Document Path Validation
  74. - (void)testNilCollectionPathsFail {
  75. FIRDocumentReference *baseDocRef = [self.db documentWithPath:@"foo/bar"];
  76. NSString *nilError = @"Collection path cannot be nil.";
  77. FSTAssertThrows([self.db collectionWithPath:nil], nilError);
  78. FSTAssertThrows([baseDocRef collectionWithPath:nil], nilError);
  79. }
  80. - (void)testWrongLengthCollectionPathsFail {
  81. FIRDocumentReference *baseDocRef = [self.db documentWithPath:@"foo/bar"];
  82. NSArray *badAbsolutePaths = @[ @"foo/bar", @"foo/bar/baz/quu" ];
  83. NSArray *badRelativePaths = @[ @"", @"baz/quu" ];
  84. NSArray *badPathLengths = @[ @2, @4 ];
  85. NSString *errorFormat = @"Invalid collection reference. Collection references must have an odd "
  86. @"number of segments, but %@ has %@";
  87. for (NSUInteger i = 0; i < badAbsolutePaths.count; i++) {
  88. NSString *error =
  89. [NSString stringWithFormat:errorFormat, badAbsolutePaths[i], badPathLengths[i]];
  90. FSTAssertThrows([self.db collectionWithPath:badAbsolutePaths[i]], error);
  91. FSTAssertThrows([baseDocRef collectionWithPath:badRelativePaths[i]], error);
  92. }
  93. }
  94. - (void)testNilDocumentPathsFail {
  95. FIRCollectionReference *baseCollectionRef = [self.db collectionWithPath:@"foo"];
  96. NSString *nilError = @"Document path cannot be nil.";
  97. FSTAssertThrows([self.db documentWithPath:nil], nilError);
  98. FSTAssertThrows([baseCollectionRef documentWithPath:nil], nilError);
  99. }
  100. - (void)testWrongLengthDocumentPathsFail {
  101. FIRCollectionReference *baseCollectionRef = [self.db collectionWithPath:@"foo"];
  102. NSArray *badAbsolutePaths = @[ @"foo", @"foo/bar/baz" ];
  103. NSArray *badRelativePaths = @[ @"", @"bar/baz" ];
  104. NSArray *badPathLengths = @[ @1, @3 ];
  105. NSString *errorFormat = @"Invalid document reference. Document references must have an even "
  106. @"number of segments, but %@ has %@";
  107. for (NSUInteger i = 0; i < badAbsolutePaths.count; i++) {
  108. NSString *error =
  109. [NSString stringWithFormat:errorFormat, badAbsolutePaths[i], badPathLengths[i]];
  110. FSTAssertThrows([self.db documentWithPath:badAbsolutePaths[i]], error);
  111. FSTAssertThrows([baseCollectionRef documentWithPath:badRelativePaths[i]], error);
  112. }
  113. }
  114. - (void)testPathsWithEmptySegmentsFail {
  115. // We're only testing using collectionWithPath since the validation happens in BasePath which is
  116. // shared by all methods that accept paths.
  117. // leading / trailing slashes are okay.
  118. [self.db collectionWithPath:@"/foo/"];
  119. [self.db collectionWithPath:@"/foo"];
  120. [self.db collectionWithPath:@"foo/"];
  121. FSTAssertThrows([self.db collectionWithPath:@"foo//bar/baz"],
  122. @"Invalid path (foo//bar/baz). Paths must not contain // in them.");
  123. FSTAssertThrows([self.db collectionWithPath:@"//foo"],
  124. @"Invalid path (//foo). Paths must not contain // in them.");
  125. FSTAssertThrows([self.db collectionWithPath:@"foo//"],
  126. @"Invalid path (foo//). Paths must not contain // in them.");
  127. }
  128. #pragma mark - Write Validation
  129. - (void)testWritesWithNonDictionaryValuesFail {
  130. NSArray *badData = @[
  131. @42, @"test", @[ @1 ], [NSDate date], [NSNull null], [FIRFieldValue fieldValueForDelete],
  132. [FIRFieldValue fieldValueForServerTimestamp]
  133. ];
  134. for (id data in badData) {
  135. [self expectWrite:data toFailWithReason:@"Data to be written must be an NSDictionary."];
  136. }
  137. }
  138. - (void)testWritesWithDirectlyNestedArraysFail {
  139. [self expectWrite:@{@"nested-array" : @[ @1, @[ @2 ] ]}
  140. toFailWithReason:@"Nested arrays are not supported"];
  141. }
  142. - (void)testWritesWithIndirectlyNestedArraysSucceed {
  143. NSDictionary<NSString *, id> *data = @{@"nested-array" : @[ @1, @{@"foo" : @[ @2 ]} ]};
  144. FIRDocumentReference *ref = [self documentRef];
  145. FIRDocumentReference *ref2 = [self documentRef];
  146. XCTestExpectation *expectation = [self expectationWithDescription:@"setData"];
  147. [ref setData:data
  148. completion:^(NSError *_Nullable error) {
  149. XCTAssertNil(error);
  150. [expectation fulfill];
  151. }];
  152. [self awaitExpectations];
  153. expectation = [self expectationWithDescription:@"batch.setData"];
  154. [[[ref.firestore batch] setData:data
  155. forDocument:ref] commitWithCompletion:^(NSError *_Nullable error) {
  156. XCTAssertNil(error);
  157. [expectation fulfill];
  158. }];
  159. [self awaitExpectations];
  160. expectation = [self expectationWithDescription:@"updateData"];
  161. [ref updateData:data
  162. completion:^(NSError *_Nullable error) {
  163. XCTAssertNil(error);
  164. [expectation fulfill];
  165. }];
  166. [self awaitExpectations];
  167. expectation = [self expectationWithDescription:@"batch.updateData"];
  168. [[[ref.firestore batch] updateData:data
  169. forDocument:ref] commitWithCompletion:^(NSError *_Nullable error) {
  170. XCTAssertNil(error);
  171. [expectation fulfill];
  172. }];
  173. [self awaitExpectations];
  174. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  175. [ref.firestore
  176. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  177. // Note ref2 does not exist at this point so set that and update ref.
  178. [transaction updateData:data forDocument:ref];
  179. [transaction setData:data forDocument:ref2];
  180. return nil;
  181. }
  182. completion:^(id result, NSError *error) {
  183. // ends up being a no-op transaction.
  184. XCTAssertNil(error);
  185. [transactionDone fulfill];
  186. }];
  187. [self awaitExpectations];
  188. }
  189. - (void)testWritesWithInvalidTypesFail {
  190. [self expectWrite:@{@"foo" : @{@"bar" : self}}
  191. toFailWithReason:@"Unsupported type: FIRValidationTests (found in field foo.bar)"];
  192. }
  193. - (void)testWritesWithLargeNumbersFail {
  194. NSNumber *num = @(static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) + 1);
  195. NSString *reason =
  196. [NSString stringWithFormat:@"NSNumber (%@) is too large (found in field num)", num];
  197. [self expectWrite:@{@"num" : num} toFailWithReason:reason];
  198. }
  199. - (void)testWritesWithReferencesToADifferentDatabaseFail {
  200. FIRDocumentReference *ref =
  201. [[self firestoreWithProjectID:@"different-db"] documentWithPath:@"baz/quu"];
  202. id data = @{@"foo" : ref};
  203. [self expectWrite:data
  204. toFailWithReason:
  205. [NSString
  206. stringWithFormat:@"Document Reference is for database different-db/(default) but "
  207. "should be for database %@/(default) (found in field foo)",
  208. [FSTIntegrationTestCase projectID]]];
  209. }
  210. - (void)testWritesWithReservedFieldsFail {
  211. [self expectWrite:@{@"__baz__" : @1}
  212. toFailWithReason:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  213. [self expectWrite:@{@"foo" : @{@"__baz__" : @1}}
  214. toFailWithReason:
  215. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  216. [self expectWrite:@{@"__baz__" : @{@"foo" : @1}}
  217. toFailWithReason:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  218. [self expectUpdate:@{@"foo.__baz__" : @1}
  219. toFailWithReason:
  220. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  221. [self expectUpdate:@{@"__baz__.foo" : @1}
  222. toFailWithReason:
  223. @"Document fields cannot begin and end with __ (found in field __baz__.foo)"];
  224. [self expectUpdate:@{@1 : @1}
  225. toFailWithReason:@"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths."];
  226. }
  227. - (void)testSetsWithFieldValueDeleteFail {
  228. [self expectSet:@{@"foo" : [FIRFieldValue fieldValueForDelete]}
  229. toFailWithReason:@"FieldValue.delete() can only be used with updateData() and setData() with "
  230. @"merge:true (found in field foo)"];
  231. }
  232. - (void)testUpdatesWithNestedFieldValueDeleteFail {
  233. [self expectUpdate:@{@"foo" : @{@"bar" : [FIRFieldValue fieldValueForDelete]}}
  234. toFailWithReason:@"FieldValue.delete() can only appear at the top level of your update data "
  235. "(found in field foo.bar)"];
  236. }
  237. - (void)testBatchWritesWithIncorrectReferencesFail {
  238. FIRFirestore *db1 = [self firestore];
  239. FIRFirestore *db2 = [self firestore];
  240. XCTAssertNotEqual(db1, db2);
  241. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  242. id data = @{@"foo" : @1};
  243. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  244. FIRWriteBatch *batch = [db1 batch];
  245. FSTAssertThrows([batch setData:data forDocument:badRef], reason);
  246. FSTAssertThrows([batch setData:data forDocument:badRef merge:YES], reason);
  247. FSTAssertThrows([batch updateData:data forDocument:badRef], reason);
  248. FSTAssertThrows([batch deleteDocument:badRef], reason);
  249. }
  250. - (void)testTransactionWritesWithIncorrectReferencesFail {
  251. FIRFirestore *db1 = [self firestore];
  252. FIRFirestore *db2 = [self firestore];
  253. XCTAssertNotEqual(db1, db2);
  254. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  255. id data = @{@"foo" : @1};
  256. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  257. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  258. [db1
  259. runTransactionWithBlock:^id(FIRTransaction *txn, NSError **pError) {
  260. FSTAssertThrows([txn getDocument:badRef error:nil], reason);
  261. FSTAssertThrows([txn setData:data forDocument:badRef], reason);
  262. FSTAssertThrows([txn setData:data forDocument:badRef merge:YES], reason);
  263. FSTAssertThrows([txn updateData:data forDocument:badRef], reason);
  264. FSTAssertThrows([txn deleteDocument:badRef], reason);
  265. return nil;
  266. }
  267. completion:^(id result, NSError *error) {
  268. // ends up being a no-op transaction.
  269. XCTAssertNil(error);
  270. [transactionDone fulfill];
  271. }];
  272. [self awaitExpectations];
  273. }
  274. #pragma mark - Field Path validation
  275. // TODO(b/37244157): More validation for invalid field paths.
  276. - (void)testFieldPathsWithEmptySegmentsFail {
  277. NSArray *badFieldPaths = @[ @"", @"foo..baz", @".foo", @"foo." ];
  278. for (NSString *fieldPath in badFieldPaths) {
  279. NSString *reason =
  280. [NSString stringWithFormat:@"Invalid field path (%@). Paths must not be empty, begin with "
  281. @"'.', end with '.', or contain '..'",
  282. fieldPath];
  283. [self expectFieldPath:fieldPath toFailWithReason:reason];
  284. }
  285. }
  286. - (void)testFieldPathsWithInvalidSegmentsFail {
  287. NSArray *badFieldPaths = @[ @"foo~bar", @"foo*bar", @"foo/bar", @"foo[1", @"foo]1", @"foo[1]" ];
  288. for (NSString *fieldPath in badFieldPaths) {
  289. NSString *reason =
  290. [NSString stringWithFormat:
  291. @"Invalid field path (%@). Paths must not contain '~', '*', '/', '[', or ']'",
  292. fieldPath];
  293. [self expectFieldPath:fieldPath toFailWithReason:reason];
  294. }
  295. }
  296. #pragma mark - ArrayUnion / ArrayRemove Validation
  297. - (void)testArrayTransformsInQueriesFail {
  298. FSTAssertThrows(
  299. [[self collectionRef]
  300. queryWhereField:@"test"
  301. isEqualTo:@{@"test" : [FIRFieldValue fieldValueForArrayUnion:@[ @1 ]]}],
  302. @"FieldValue.arrayUnion() can only be used with updateData() and setData() (found in field "
  303. "test)");
  304. FSTAssertThrows(
  305. [[self collectionRef]
  306. queryWhereField:@"test"
  307. isEqualTo:@{@"test" : [FIRFieldValue fieldValueForArrayRemove:@[ @1 ]]}],
  308. @"FieldValue.arrayRemove() can only be used with updateData() and setData() (found in field "
  309. @"test)");
  310. }
  311. - (void)testInvalidArrayTransformElementFails {
  312. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayUnion:@[ @1, self ]]}
  313. toFailWithReason:@"Unsupported type: FIRValidationTests"];
  314. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayRemove:@[ @1, self ]]}
  315. toFailWithReason:@"Unsupported type: FIRValidationTests"];
  316. }
  317. - (void)testArraysInArrayTransformsFail {
  318. // This would result in a directly nested array which is not supported.
  319. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayUnion:@[ @1, @[ @"nested" ] ]]}
  320. toFailWithReason:@"Nested arrays are not supported"];
  321. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayRemove:@[ @1, @[ @"nested" ] ]]}
  322. toFailWithReason:@"Nested arrays are not supported"];
  323. }
  324. #pragma mark - Query Validation
  325. - (void)testQueryWithNonPositiveLimitFails {
  326. FSTAssertThrows([[self collectionRef] queryLimitedTo:0],
  327. @"Invalid Query. Query limit (0) is invalid. Limit must be positive.");
  328. FSTAssertThrows([[self collectionRef] queryLimitedTo:-1],
  329. @"Invalid Query. Query limit (-1) is invalid. Limit must be positive.");
  330. }
  331. - (void)testNonEqualityQueriesOnNullOrNaNFail {
  332. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:nil],
  333. @"Invalid Query. Null supports only equality comparisons.");
  334. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:[NSNull null]],
  335. @"Invalid Query. Null supports only equality comparisons.");
  336. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:nil],
  337. @"Invalid Query. Null supports only equality comparisons.");
  338. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:[NSNull null]],
  339. @"Invalid Query. Null supports only equality comparisons.");
  340. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContainsAny:[NSNull null]],
  341. @"Invalid Query. A non-empty array is required for 'arrayContainsAny' filters.");
  342. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContainsAny:[NSNull null]],
  343. @"Invalid Query. A non-empty array is required for 'arrayContainsAny' filters.");
  344. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:@(NAN)],
  345. @"Invalid Query. NaN supports only equality comparisons.");
  346. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:@(NAN)],
  347. @"Invalid Query. NaN supports only equality comparisons.");
  348. }
  349. - (void)testQueryCannotBeCreatedFromDocumentsMissingSortValues {
  350. FIRCollectionReference *testCollection =
  351. [self collectionRefWithDocuments:@{@"f" : @{@"v" : @"f", @"nosort" : @1.0}}];
  352. FIRQuery *query = [testCollection queryOrderedByField:@"sort"];
  353. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:[testCollection documentWithPath:@"f"]];
  354. XCTAssertTrue(snapshot.exists);
  355. NSString *reason = @"Invalid query. You are trying to start or end a query using a document for "
  356. "which the field 'sort' (used as the order by) does not exist.";
  357. FSTAssertThrows([query queryStartingAtDocument:snapshot], reason);
  358. FSTAssertThrows([query queryStartingAfterDocument:snapshot], reason);
  359. FSTAssertThrows([query queryEndingBeforeDocument:snapshot], reason);
  360. FSTAssertThrows([query queryEndingAtDocument:snapshot], reason);
  361. }
  362. - (void)testQueriesCannotBeSortedByAnUncommittedServerTimestamp {
  363. __weak FIRCollectionReference *collection = [self collectionRef];
  364. FIRFirestore *db = [self firestore];
  365. [db disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable network"]];
  366. [self awaitExpectations];
  367. XCTestExpectation *offlineCallbackDone =
  368. [self expectationWithDescription:@"offline callback done"];
  369. XCTestExpectation *onlineCallbackDone = [self expectationWithDescription:@"online callback done"];
  370. [collection addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) {
  371. XCTAssertNil(error);
  372. // Skip the initial empty snapshot.
  373. if (snapshot.empty) return;
  374. XCTAssertEqual(snapshot.count, 1);
  375. FIRQueryDocumentSnapshot *docSnap = snapshot.documents[0];
  376. if (snapshot.metadata.pendingWrites) {
  377. // Offline snapshot. Since the server timestamp is uncommitted, we
  378. // shouldn't be able to query by it.
  379. NSString *reason =
  380. @"Invalid query. You are trying to start or end a query using a document for which the "
  381. @"field 'timestamp' is an uncommitted server timestamp. (Since the value of this field "
  382. @"is unknown, you cannot start/end a query with it.)";
  383. FSTAssertThrows([[[collection queryOrderedByField:@"timestamp"] queryEndingAtDocument:docSnap]
  384. addSnapshotListener:^(FIRQuerySnapshot *, NSError *){
  385. }],
  386. reason);
  387. [offlineCallbackDone fulfill];
  388. } else {
  389. // Online snapshot. Since the server timestamp is committed, we should be able to query by it.
  390. [[[collection queryOrderedByField:@"timestamp"] queryEndingAtDocument:docSnap]
  391. addSnapshotListener:^(FIRQuerySnapshot *, NSError *){
  392. }];
  393. [onlineCallbackDone fulfill];
  394. }
  395. }];
  396. FIRDocumentReference *document = [collection documentWithAutoID];
  397. [document setData:@{@"timestamp" : [FIRFieldValue fieldValueForServerTimestamp]}];
  398. [self awaitExpectations];
  399. [db enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable network"]];
  400. [self awaitExpectations];
  401. }
  402. - (void)testQueryBoundMustNotHaveMoreComponentsThanSortOrders {
  403. FIRCollectionReference *testCollection = [self collectionRef];
  404. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  405. NSString *reason = @"Invalid query. You are trying to start or end a query using more values "
  406. "than were specified in the order by.";
  407. // More elements than order by
  408. FSTAssertThrows(([query queryStartingAtValues:@[ @1, @2 ]]), reason);
  409. FSTAssertThrows(([[query queryOrderedByField:@"bar"] queryStartingAtValues:@[ @1, @2, @3 ]]),
  410. reason);
  411. }
  412. - (void)testQueryOrderedByKeyBoundMustBeAStringWithoutSlashes {
  413. FIRQuery *query = [[self.db collectionWithPath:@"collection"]
  414. queryOrderedByFieldPath:[FIRFieldPath documentID]];
  415. FIRQuery *cgQuery = [[self.db collectionGroupWithID:@"collection"]
  416. queryOrderedByFieldPath:[FIRFieldPath documentID]];
  417. FSTAssertThrows([query queryStartingAtValues:@[ @1 ]],
  418. @"Invalid query. Expected a string for the document ID.");
  419. FSTAssertThrows([query queryStartingAtValues:@[ @"foo/bar" ]],
  420. @"Invalid query. When querying a collection and ordering by document "
  421. "ID, you must pass a plain document ID, but 'foo/bar' contains a slash.");
  422. FSTAssertThrows([cgQuery queryStartingAtValues:@[ @"foo" ]],
  423. @"Invalid query. When querying a collection group and ordering by "
  424. "document ID, you must pass a value that results in a valid document path, "
  425. "but 'foo' is not because it contains an odd number of segments.");
  426. }
  427. - (void)testQueryMustNotSpecifyStartingOrEndingPointAfterOrder {
  428. FIRCollectionReference *testCollection = [self collectionRef];
  429. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  430. NSString *reason =
  431. @"Invalid query. You must not specify a starting point before specifying the order by.";
  432. FSTAssertThrows([[query queryStartingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  433. FSTAssertThrows([[query queryStartingAfterValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  434. reason = @"Invalid query. You must not specify an ending point before specifying the order by.";
  435. FSTAssertThrows([[query queryEndingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  436. FSTAssertThrows([[query queryEndingBeforeValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  437. }
  438. - (void)testQueriesFilteredByDocumentIdMustUseStringsOrDocumentReferences {
  439. FIRCollectionReference *collection = [self collectionRef];
  440. NSString *reason = @"Invalid query. When querying by document ID you must provide a valid "
  441. "document ID, but it was an empty string.";
  442. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@""], reason);
  443. reason = @"Invalid query. When querying a collection by document ID you must provide a "
  444. "plain document ID, but 'foo/bar/baz' contains a '/' character.";
  445. FSTAssertThrows(
  446. [collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@"foo/bar/baz"], reason);
  447. reason = @"Invalid query. When querying by document ID you must provide a valid string or "
  448. "DocumentReference, but it was of type: __NSCFNumber";
  449. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@1], reason);
  450. reason = @"Invalid query. When querying a collection group by document ID, the value "
  451. "provided must result in a valid document path, but 'foo/bar/baz' is not because it "
  452. "has an odd number of segments.";
  453. FSTAssertThrows(
  454. [[self.db collectionGroupWithID:@"collection"] queryWhereFieldPath:[FIRFieldPath documentID]
  455. isEqualTo:@"foo/bar/baz"],
  456. reason);
  457. reason =
  458. @"Invalid query. You can't perform arrayContains queries on document ID since document IDs "
  459. "are not arrays.";
  460. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] arrayContains:@1],
  461. reason);
  462. reason = @"Invalid query. You can't perform arrayContainsAny queries on document ID since "
  463. @"document IDs "
  464. "are not arrays.";
  465. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] arrayContainsAny:@1],
  466. reason);
  467. }
  468. - (void)testQueriesUsingInAndDocumentIdMustHaveProperDocumentReferencesInArray {
  469. FIRCollectionReference *collection = [self collectionRef];
  470. NSString *reason = @"Invalid query. When querying by document ID you must provide a valid "
  471. "document ID, but it was an empty string.";
  472. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:@[ @"" ]], reason);
  473. reason = @"Invalid query. When querying a collection by document ID you must provide a "
  474. "plain document ID, but 'foo/bar/baz' contains a '/' character.";
  475. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:@[ @"foo/bar/baz" ]],
  476. reason);
  477. reason = @"Invalid query. When querying by document ID you must provide a valid string or "
  478. "DocumentReference, but it was of type: __NSArrayI";
  479. NSArray *value = @[ @1, @2 ];
  480. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:value], reason);
  481. reason = @"Invalid query. When querying a collection group by document ID, the value "
  482. "provided must result in a valid document path, but 'foo' is not because it "
  483. "has an odd number of segments.";
  484. FSTAssertThrows(
  485. [[self.db collectionGroupWithID:@"collection"] queryWhereFieldPath:[FIRFieldPath documentID]
  486. in:@[ @"foo" ]],
  487. reason);
  488. }
  489. - (void)testQueryInequalityFieldMustMatchFirstOrderByField {
  490. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  491. FIRQuery *base = [coll queryWhereField:@"x" isGreaterThanOrEqualTo:@32];
  492. FSTAssertThrows([base queryWhereField:@"y" isLessThan:@"cat"],
  493. @"Invalid Query. All where filters with an inequality (lessThan, "
  494. "lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  495. "field. But you have inequality filters on 'x' and 'y'");
  496. NSString *reason =
  497. @"Invalid query. You have a where filter with "
  498. "an inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) "
  499. "on field 'x' and so you must also use 'x' as your first queryOrderedBy field, "
  500. "but your first queryOrderedBy is currently on field 'y' instead.";
  501. FSTAssertThrows([base queryOrderedByField:@"y"], reason);
  502. FSTAssertThrows([[coll queryOrderedByField:@"y"] queryWhereField:@"x" isGreaterThan:@32], reason);
  503. FSTAssertThrows([[base queryOrderedByField:@"y"] queryOrderedByField:@"x"], reason);
  504. FSTAssertThrows([[[coll queryOrderedByField:@"y"] queryOrderedByField:@"x"] queryWhereField:@"x"
  505. isGreaterThan:@32],
  506. reason);
  507. XCTAssertNoThrow([base queryWhereField:@"x" isLessThanOrEqualTo:@"cat"],
  508. @"Same inequality fields work");
  509. XCTAssertNoThrow([base queryWhereField:@"y" isEqualTo:@"cat"],
  510. @"Inequality and equality on different fields works");
  511. XCTAssertNoThrow([base queryWhereField:@"y" arrayContains:@"cat"],
  512. @"Inequality and array_contains on different fields works");
  513. XCTAssertNoThrow([base queryWhereField:@"y" arrayContainsAny:@[ @"cat" ]],
  514. @"array-contains-any on different fields works");
  515. XCTAssertNoThrow([base queryWhereField:@"y" in:@[ @"cat" ]], @"IN on different fields works");
  516. XCTAssertNoThrow([base queryOrderedByField:@"x"], @"inequality same as order by works");
  517. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"x" isGreaterThan:@32],
  518. @"inequality same as order by works");
  519. XCTAssertNoThrow([[base queryOrderedByField:@"x"] queryOrderedByField:@"y"],
  520. @"inequality same as first order by works.");
  521. XCTAssertNoThrow([[[coll queryOrderedByField:@"x"] queryOrderedByField:@"y"] queryWhereField:@"x"
  522. isGreaterThan:@32],
  523. @"inequality same as first order by works.");
  524. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" isEqualTo:@"cat"],
  525. @"equality different than orderBy works.");
  526. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" arrayContains:@"cat"],
  527. @"array_contains different than orderBy works.");
  528. }
  529. - (void)testQueriesWithMultipleArrayFiltersFail {
  530. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  531. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  532. arrayContains:@2],
  533. @"Invalid Query. You cannot use more than one 'arrayContains' filter.");
  534. FSTAssertThrows(
  535. [[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  536. arrayContainsAny:@[ @2 ]],
  537. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'arrayContains' filters.");
  538. FSTAssertThrows(
  539. [[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  540. arrayContains:@2],
  541. @"Invalid Query. You cannot use 'arrayContains' filters with 'arrayContainsAny' filters.");
  542. }
  543. - (void)testQueriesWithMultipleDisjunctiveFiltersFail {
  544. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  545. FSTAssertThrows([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo" in:@[ @2 ]],
  546. @"Invalid Query. You cannot use more than one 'in' filter.");
  547. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  548. arrayContainsAny:@[ @2 ]],
  549. @"Invalid Query. You cannot use more than one 'arrayContainsAny' filter.");
  550. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  551. in:@[ @2 ]],
  552. @"Invalid Query. You cannot use 'in' filters with 'arrayContainsAny' filters.");
  553. FSTAssertThrows([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo"
  554. arrayContainsAny:@[ @2 ]],
  555. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  556. // This is redundant with the above tests, but makes sure our validation doesn't get confused.
  557. FSTAssertThrows([[[coll queryWhereField:@"foo"
  558. in:@[ @1 ]] queryWhereField:@"foo"
  559. arrayContains:@2] queryWhereField:@"foo"
  560. arrayContainsAny:@[ @2 ]],
  561. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  562. FSTAssertThrows([[[coll queryWhereField:@"foo"
  563. arrayContains:@1] queryWhereField:@"foo"
  564. in:@[ @2 ]] queryWhereField:@"foo"
  565. arrayContainsAny:@[ @2 ]],
  566. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  567. }
  568. - (void)testQueriesCanUseInWithArrayContain {
  569. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  570. XCTAssertNoThrow([[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  571. in:@[ @2 ]],
  572. @"arrayContains with IN works.");
  573. XCTAssertNoThrow([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo"
  574. arrayContains:@2],
  575. @"IN with arrayContains works.");
  576. FSTAssertThrows([[[coll queryWhereField:@"foo"
  577. in:@[ @1 ]] queryWhereField:@"foo"
  578. arrayContains:@2] queryWhereField:@"foo"
  579. arrayContains:@3],
  580. @"Invalid Query. You cannot use more than one 'arrayContains' filter.");
  581. FSTAssertThrows([[[coll queryWhereField:@"foo"
  582. arrayContains:@1] queryWhereField:@"foo"
  583. in:@[ @2 ]] queryWhereField:@"foo"
  584. in:@[ @3 ]],
  585. @"Invalid Query. You cannot use more than one 'in' filter.");
  586. }
  587. - (void)testQueriesInAndArrayContainsAnyArrayRules {
  588. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  589. FSTAssertThrows([coll queryWhereField:@"foo" in:@[]],
  590. @"Invalid Query. A non-empty array is required for 'in' filters.");
  591. FSTAssertThrows([coll queryWhereField:@"foo" arrayContainsAny:@[]],
  592. @"Invalid Query. A non-empty array is required for 'arrayContainsAny' filters.");
  593. // The 10 element max includes duplicates.
  594. NSArray *values = @[ @1, @2, @3, @4, @5, @6, @7, @8, @9, @9, @9 ];
  595. FSTAssertThrows(
  596. [coll queryWhereField:@"foo" in:values],
  597. @"Invalid Query. 'in' filters support a maximum of 10 elements in the value array.");
  598. FSTAssertThrows([coll queryWhereField:@"foo" arrayContainsAny:values],
  599. @"Invalid Query. 'arrayContainsAny' filters support a maximum of 10 elements"
  600. " in the value array.");
  601. NSArray *withNullValues = @[ @1, [NSNull null] ];
  602. FSTAssertThrows([coll queryWhereField:@"foo" in:withNullValues],
  603. @"Invalid Query. 'in' filters cannot contain 'null' in the value array.");
  604. FSTAssertThrows(
  605. [coll queryWhereField:@"foo" arrayContainsAny:withNullValues],
  606. @"Invalid Query. 'arrayContainsAny' filters cannot contain 'null' in the value array.");
  607. NSArray *withNaNValues = @[ @2, @(NAN) ];
  608. FSTAssertThrows([coll queryWhereField:@"foo" in:withNaNValues],
  609. @"Invalid Query. 'in' filters cannot contain 'NaN' in the value array.");
  610. FSTAssertThrows(
  611. [coll queryWhereField:@"foo" arrayContainsAny:withNaNValues],
  612. @"Invalid Query. 'arrayContainsAny' filters cannot contain 'NaN' in the value array.");
  613. }
  614. #pragma mark - GeoPoint Validation
  615. - (void)testInvalidGeoPointParameters {
  616. [self verifyExceptionForInvalidLatitude:NAN];
  617. [self verifyExceptionForInvalidLatitude:-INFINITY];
  618. [self verifyExceptionForInvalidLatitude:INFINITY];
  619. [self verifyExceptionForInvalidLatitude:-90.1];
  620. [self verifyExceptionForInvalidLatitude:90.1];
  621. [self verifyExceptionForInvalidLongitude:NAN];
  622. [self verifyExceptionForInvalidLongitude:-INFINITY];
  623. [self verifyExceptionForInvalidLongitude:INFINITY];
  624. [self verifyExceptionForInvalidLongitude:-180.1];
  625. [self verifyExceptionForInvalidLongitude:180.1];
  626. }
  627. #pragma mark - Helpers
  628. /** Performs a write using each write API and makes sure it fails with the expected reason. */
  629. - (void)expectWrite:(id)data toFailWithReason:(NSString *)reason {
  630. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:YES];
  631. }
  632. /** Performs a write using each set API and makes sure it fails with the expected reason. */
  633. - (void)expectSet:(id)data toFailWithReason:(NSString *)reason {
  634. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:NO];
  635. }
  636. /** Performs a write using each update API and makes sure it fails with the expected reason. */
  637. - (void)expectUpdate:(id)data toFailWithReason:(NSString *)reason {
  638. [self expectWrite:data toFailWithReason:reason includeSets:NO includeUpdates:YES];
  639. }
  640. /**
  641. * Performs a write using each set and/or update API and makes sure it fails with the expected
  642. * reason.
  643. */
  644. - (void)expectWrite:(id)data
  645. toFailWithReason:(NSString *)reason
  646. includeSets:(BOOL)includeSets
  647. includeUpdates:(BOOL)includeUpdates {
  648. FIRDocumentReference *ref = [self documentRef];
  649. if (includeSets) {
  650. FSTAssertThrows([ref setData:data], reason, @"for %@", data);
  651. FSTAssertThrows([[ref.firestore batch] setData:data forDocument:ref], reason, @"for %@", data);
  652. }
  653. if (includeUpdates) {
  654. FSTAssertThrows([ref updateData:data], reason, @"for %@", data);
  655. FSTAssertThrows([[ref.firestore batch] updateData:data forDocument:ref], reason, @"for %@",
  656. data);
  657. }
  658. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  659. [ref.firestore
  660. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  661. if (includeSets) {
  662. FSTAssertThrows([transaction setData:data forDocument:ref], reason, @"for %@", data);
  663. }
  664. if (includeUpdates) {
  665. FSTAssertThrows([transaction updateData:data forDocument:ref], reason, @"for %@", data);
  666. }
  667. return nil;
  668. }
  669. completion:^(id result, NSError *error) {
  670. // ends up being a no-op transaction.
  671. XCTAssertNil(error);
  672. [transactionDone fulfill];
  673. }];
  674. [self awaitExpectations];
  675. }
  676. - (void)testFieldNamesMustNotBeEmpty {
  677. NSString *reason = @"Invalid field path. Provided names must not be empty.";
  678. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[]], reason);
  679. reason = @"Invalid field name at index 0. Field names must not be empty.";
  680. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[ @"" ]], reason);
  681. reason = @"Invalid field name at index 1. Field names must not be empty.";
  682. FSTAssertThrows(([[FIRFieldPath alloc] initWithFields:@[ @"foo", @"" ]]), reason);
  683. }
  684. /**
  685. * Tests a field path with all of our APIs that accept field paths and ensures they fail with the
  686. * specified reason.
  687. */
  688. - (void)expectFieldPath:(NSString *)fieldPath toFailWithReason:(NSString *)reason {
  689. // Get an arbitrary snapshot we can use for testing.
  690. FIRDocumentReference *docRef = [self documentRef];
  691. [self writeDocumentRef:docRef data:@{@"test" : @1}];
  692. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:docRef];
  693. // Update paths.
  694. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  695. dict[fieldPath] = @1;
  696. [self expectUpdate:dict toFailWithReason:reason];
  697. // Snapshot fields.
  698. FSTAssertThrows(snapshot[fieldPath], reason);
  699. // Query filter / order fields.
  700. FIRCollectionReference *collection = [self collectionRef];
  701. FSTAssertThrows([collection queryWhereField:fieldPath isEqualTo:@1], reason);
  702. // isLessThan, etc. omitted for brevity since the code path is trivially shared.
  703. FSTAssertThrows([collection queryOrderedByField:fieldPath], reason);
  704. }
  705. - (void)verifyExceptionForInvalidLatitude:(double)latitude {
  706. NSString *reason = [NSString
  707. stringWithFormat:@"GeoPoint requires a latitude value in the range of [-90, 90], but was %g",
  708. latitude];
  709. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:latitude longitude:0], reason);
  710. }
  711. - (void)verifyExceptionForInvalidLongitude:(double)longitude {
  712. NSString *reason =
  713. [NSString stringWithFormat:
  714. @"GeoPoint requires a longitude value in the range of [-180, 180], but was %g",
  715. longitude];
  716. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:0 longitude:longitude], reason);
  717. }
  718. @end