FIRValidationTests.mm 40 KB

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