FIRValidationTests.mm 40 KB

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