FIRValidationTests.mm 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  224. [self expectWrite:@{@"foo" : @{@"__baz__" : @1}}
  225. toFailWithReason:
  226. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  227. [self expectWrite:@{@"__baz__" : @{@"foo" : @1}}
  228. toFailWithReason:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  229. [self expectUpdate:@{@"foo.__baz__" : @1}
  230. toFailWithReason:
  231. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  232. [self expectUpdate:@{@"__baz__.foo" : @1}
  233. toFailWithReason:
  234. @"Document fields cannot begin and end with __ (found in field __baz__.foo)"];
  235. [self expectUpdate:@{@1 : @1}
  236. toFailWithReason:@"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths."];
  237. }
  238. - (void)testSetsWithFieldValueDeleteFail {
  239. [self expectSet:@{@"foo" : [FIRFieldValue fieldValueForDelete]}
  240. toFailWithReason:@"FieldValue.delete() can only be used with updateData() and setData() with "
  241. @"merge:true (found in field foo)"];
  242. }
  243. - (void)testUpdatesWithNestedFieldValueDeleteFail {
  244. [self expectUpdate:@{@"foo" : @{@"bar" : [FIRFieldValue fieldValueForDelete]}}
  245. toFailWithReason:@"FieldValue.delete() can only appear at the top level of your update data "
  246. "(found in field foo.bar)"];
  247. }
  248. - (void)testBatchWritesWithIncorrectReferencesFail {
  249. FIRFirestore *db1 = [self firestore];
  250. FIRFirestore *db2 = [self firestore];
  251. XCTAssertNotEqual(db1, db2);
  252. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  253. id data = @{@"foo" : @1};
  254. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  255. FIRWriteBatch *batch = [db1 batch];
  256. FSTAssertThrows([batch setData:data forDocument:badRef], reason);
  257. FSTAssertThrows([batch setData:data forDocument:badRef merge:YES], reason);
  258. FSTAssertThrows([batch updateData:data forDocument:badRef], reason);
  259. FSTAssertThrows([batch deleteDocument:badRef], reason);
  260. }
  261. - (void)testTransactionWritesWithIncorrectReferencesFail {
  262. FIRFirestore *db1 = [self firestore];
  263. FIRFirestore *db2 = [self firestore];
  264. XCTAssertNotEqual(db1, db2);
  265. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  266. id data = @{@"foo" : @1};
  267. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  268. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  269. [db1
  270. runTransactionWithBlock:^id(FIRTransaction *txn, NSError **pError) {
  271. FSTAssertThrows([txn getDocument:badRef error:nil], reason);
  272. FSTAssertThrows([txn setData:data forDocument:badRef], reason);
  273. FSTAssertThrows([txn setData:data forDocument:badRef merge:YES], reason);
  274. FSTAssertThrows([txn updateData:data forDocument:badRef], reason);
  275. FSTAssertThrows([txn deleteDocument:badRef], reason);
  276. return nil;
  277. }
  278. completion:^(id result, NSError *error) {
  279. // ends up being a no-op transaction.
  280. XCTAssertNil(error);
  281. [transactionDone fulfill];
  282. }];
  283. [self awaitExpectations];
  284. }
  285. #pragma mark - Field Path validation
  286. // TODO(b/37244157): More validation for invalid field paths.
  287. - (void)testFieldPathsWithEmptySegmentsFail {
  288. NSArray *badFieldPaths = @[ @"", @"foo..baz", @".foo", @"foo." ];
  289. for (NSString *fieldPath in badFieldPaths) {
  290. NSString *reason =
  291. [NSString stringWithFormat:@"Invalid field path (%@). Paths must not be empty, begin with "
  292. @"'.', end with '.', or contain '..'",
  293. fieldPath];
  294. [self expectFieldPath:fieldPath toFailWithReason:reason];
  295. }
  296. }
  297. - (void)testFieldPathsWithInvalidSegmentsFail {
  298. NSArray *badFieldPaths = @[ @"foo~bar", @"foo*bar", @"foo/bar", @"foo[1", @"foo]1", @"foo[1]" ];
  299. for (NSString *fieldPath in badFieldPaths) {
  300. NSString *reason =
  301. [NSString stringWithFormat:
  302. @"Invalid field path (%@). Paths must not contain '~', '*', '/', '[', or ']'",
  303. fieldPath];
  304. [self expectFieldPath:fieldPath toFailWithReason:reason];
  305. }
  306. }
  307. #pragma mark - ArrayUnion / ArrayRemove Validation
  308. - (void)testArrayTransformsInQueriesFail {
  309. FSTAssertThrows(
  310. [[self collectionRef]
  311. queryWhereField:@"test"
  312. isEqualTo:@{@"test" : [FIRFieldValue fieldValueForArrayUnion:@[ @1 ]]}],
  313. @"FieldValue.arrayUnion() can only be used with updateData() and setData() (found in field "
  314. "test)");
  315. FSTAssertThrows(
  316. [[self collectionRef]
  317. queryWhereField:@"test"
  318. isEqualTo:@{@"test" : [FIRFieldValue fieldValueForArrayRemove:@[ @1 ]]}],
  319. @"FieldValue.arrayRemove() can only be used with updateData() and setData() (found in field "
  320. @"test)");
  321. }
  322. - (void)testInvalidArrayTransformElementFails {
  323. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayUnion:@[ @1, self ]]}
  324. toFailWithReason:@"Unsupported type: FIRValidationTests"];
  325. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayRemove:@[ @1, self ]]}
  326. toFailWithReason:@"Unsupported type: FIRValidationTests"];
  327. }
  328. - (void)testArraysInArrayTransformsFail {
  329. // This would result in a directly nested array which is not supported.
  330. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayUnion:@[ @1, @[ @"nested" ] ]]}
  331. toFailWithReason:@"Nested arrays are not supported"];
  332. [self expectWrite:@{@"foo" : [FIRFieldValue fieldValueForArrayRemove:@[ @1, @[ @"nested" ] ]]}
  333. toFailWithReason:@"Nested arrays are not supported"];
  334. }
  335. #pragma mark - Query Validation
  336. - (void)testQueryWithNonPositiveLimitFails {
  337. FSTAssertThrows([[self collectionRef] queryLimitedTo:0],
  338. @"Invalid Query. Query limit (0) is invalid. Limit must be positive.");
  339. FSTAssertThrows([[self collectionRef] queryLimitedTo:-1],
  340. @"Invalid Query. Query limit (-1) is invalid. Limit must be positive.");
  341. }
  342. - (void)testNonEqualityQueriesOnNullOrNaNFail {
  343. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:nil],
  344. @"Invalid Query. Null supports only equality comparisons.");
  345. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:[NSNull null]],
  346. @"Invalid Query. Null supports only equality comparisons.");
  347. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:nil],
  348. @"Invalid Query. Null supports only equality comparisons.");
  349. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:[NSNull null]],
  350. @"Invalid Query. Null supports only equality comparisons.");
  351. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:@(NAN)],
  352. @"Invalid Query. NaN supports only equality comparisons.");
  353. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:@(NAN)],
  354. @"Invalid Query. NaN supports only equality comparisons.");
  355. }
  356. - (void)testQueryCannotBeCreatedFromDocumentsMissingSortValues {
  357. FIRCollectionReference *testCollection =
  358. [self collectionRefWithDocuments:@{@"f" : @{@"v" : @"f", @"nosort" : @1.0}}];
  359. FIRQuery *query = [testCollection queryOrderedByField:@"sort"];
  360. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:[testCollection documentWithPath:@"f"]];
  361. XCTAssertTrue(snapshot.exists);
  362. NSString *reason = @"Invalid query. You are trying to start or end a query using a document for "
  363. "which the field 'sort' (used as the order by) does not exist.";
  364. FSTAssertThrows([query queryStartingAtDocument:snapshot], reason);
  365. FSTAssertThrows([query queryStartingAfterDocument:snapshot], reason);
  366. FSTAssertThrows([query queryEndingBeforeDocument:snapshot], reason);
  367. FSTAssertThrows([query queryEndingAtDocument:snapshot], reason);
  368. }
  369. - (void)testQueriesCannotBeSortedByAnUncommittedServerTimestamp {
  370. __weak FIRCollectionReference *collection = [self collectionRef];
  371. FIRFirestore *db = [self firestore];
  372. [db disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable network"]];
  373. [self awaitExpectations];
  374. XCTestExpectation *offlineCallbackDone =
  375. [self expectationWithDescription:@"offline callback done"];
  376. XCTestExpectation *onlineCallbackDone = [self expectationWithDescription:@"online callback done"];
  377. [collection addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) {
  378. XCTAssertNil(error);
  379. // Skip the initial empty snapshot.
  380. if (snapshot.empty) return;
  381. XCTAssertEqual(snapshot.count, 1);
  382. FIRQueryDocumentSnapshot *docSnap = snapshot.documents[0];
  383. if (snapshot.metadata.pendingWrites) {
  384. // Offline snapshot. Since the server timestamp is uncommitted, we
  385. // shouldn't be able to query by it.
  386. NSString *reason =
  387. @"Invalid query. You are trying to start or end a query using a document for which the "
  388. @"field 'timestamp' is an uncommitted server timestamp. (Since the value of this field "
  389. @"is unknown, you cannot start/end a query with it.)";
  390. FSTAssertThrows([[[collection queryOrderedByField:@"timestamp"] queryEndingAtDocument:docSnap]
  391. addSnapshotListener:^(FIRQuerySnapshot *, NSError *){
  392. }],
  393. reason);
  394. [offlineCallbackDone fulfill];
  395. } else {
  396. // Online snapshot. Since the server timestamp is committed, we should be able to query by it.
  397. [[[collection queryOrderedByField:@"timestamp"] queryEndingAtDocument:docSnap]
  398. addSnapshotListener:^(FIRQuerySnapshot *, NSError *){
  399. }];
  400. [onlineCallbackDone fulfill];
  401. }
  402. }];
  403. FIRDocumentReference *document = [collection documentWithAutoID];
  404. [document setData:@{@"timestamp" : [FIRFieldValue fieldValueForServerTimestamp]}];
  405. [self awaitExpectations];
  406. [db enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable network"]];
  407. [self awaitExpectations];
  408. }
  409. - (void)testQueryBoundMustNotHaveMoreComponentsThanSortOrders {
  410. FIRCollectionReference *testCollection = [self collectionRef];
  411. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  412. NSString *reason = @"Invalid query. You are trying to start or end a query using more values "
  413. "than were specified in the order by.";
  414. // More elements than order by
  415. FSTAssertThrows(([query queryStartingAtValues:@[ @1, @2 ]]), reason);
  416. FSTAssertThrows(([[query queryOrderedByField:@"bar"] queryStartingAtValues:@[ @1, @2, @3 ]]),
  417. reason);
  418. }
  419. - (void)testQueryOrderedByKeyBoundMustBeAStringWithoutSlashes {
  420. FIRQuery *query = [[self.db collectionWithPath:@"collection"]
  421. queryOrderedByFieldPath:[FIRFieldPath documentID]];
  422. FIRQuery *cgQuery = [[self.db collectionGroupWithID:@"collection"]
  423. queryOrderedByFieldPath:[FIRFieldPath documentID]];
  424. FSTAssertThrows([query queryStartingAtValues:@[ @1 ]],
  425. @"Invalid query. Expected a string for the document ID.");
  426. FSTAssertThrows([query queryStartingAtValues:@[ @"foo/bar" ]],
  427. @"Invalid query. When querying a collection and ordering by document "
  428. "ID, you must pass a plain document ID, but 'foo/bar' contains a slash.");
  429. FSTAssertThrows([cgQuery queryStartingAtValues:@[ @"foo" ]],
  430. @"Invalid query. When querying a collection group and ordering by "
  431. "document ID, you must pass a value that results in a valid document path, "
  432. "but 'foo' is not because it contains an odd number of segments.");
  433. }
  434. - (void)testQueryMustNotSpecifyStartingOrEndingPointAfterOrder {
  435. FIRCollectionReference *testCollection = [self collectionRef];
  436. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  437. NSString *reason =
  438. @"Invalid query. You must not specify a starting point before specifying the order by.";
  439. FSTAssertThrows([[query queryStartingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  440. FSTAssertThrows([[query queryStartingAfterValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  441. reason = @"Invalid query. You must not specify an ending point before specifying the order by.";
  442. FSTAssertThrows([[query queryEndingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  443. FSTAssertThrows([[query queryEndingBeforeValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  444. }
  445. - (void)testQueriesFilteredByDocumentIdMustUseStringsOrDocumentReferences {
  446. FIRCollectionReference *collection = [self collectionRef];
  447. NSString *reason = @"Invalid query. When querying by document ID you must provide a valid "
  448. "document ID, but it was an empty string.";
  449. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@""], reason);
  450. reason = @"Invalid query. When querying a collection by document ID you must provide a "
  451. "plain document ID, but 'foo/bar/baz' contains a '/' character.";
  452. FSTAssertThrows(
  453. [collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@"foo/bar/baz"], reason);
  454. reason = @"Invalid query. When querying by document ID you must provide a valid string or "
  455. "DocumentReference, but it was of type: __NSCFNumber";
  456. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@1], reason);
  457. reason = @"Invalid query. When querying a collection group by document ID, the value "
  458. "provided must result in a valid document path, but 'foo/bar/baz' is not because it "
  459. "has an odd number of segments.";
  460. FSTAssertThrows(
  461. [[self.db collectionGroupWithID:@"collection"] queryWhereFieldPath:[FIRFieldPath documentID]
  462. isEqualTo:@"foo/bar/baz"],
  463. reason);
  464. reason =
  465. @"Invalid query. You can't perform arrayContains queries on document ID since document IDs "
  466. "are not arrays.";
  467. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] arrayContains:@1],
  468. reason);
  469. }
  470. - (void)testQueriesUsingInAndDocumentIdMustHaveProperDocumentReferencesInArray {
  471. FIRCollectionReference *collection = [self collectionRef];
  472. NSString *reason = @"Invalid query. When querying by document ID you must provide a valid "
  473. "document ID, but it was an empty string.";
  474. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:@[ @"" ]], reason);
  475. reason = @"Invalid query. When querying a collection by document ID you must provide a "
  476. "plain document ID, but 'foo/bar/baz' contains a '/' character.";
  477. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:@[ @"foo/bar/baz" ]],
  478. reason);
  479. reason = @"Invalid query. When querying by document ID you must provide a valid string or "
  480. "DocumentReference, but it was of type: __NSArrayI";
  481. NSArray *value = @[ @1, @2 ];
  482. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:value], reason);
  483. reason = @"Invalid query. When querying a collection group by document ID, the value "
  484. "provided must result in a valid document path, but 'foo' is not because it "
  485. "has an odd number of segments.";
  486. FSTAssertThrows(
  487. [[self.db collectionGroupWithID:@"collection"] queryWhereFieldPath:[FIRFieldPath documentID]
  488. in:@[ @"foo" ]],
  489. reason);
  490. }
  491. - (void)testQueryInequalityFieldMustMatchFirstOrderByField {
  492. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  493. FIRQuery *base = [coll queryWhereField:@"x" isGreaterThanOrEqualTo:@32];
  494. FSTAssertThrows([base queryWhereField:@"y" isLessThan:@"cat"],
  495. @"Invalid Query. All where filters with an inequality (lessThan, "
  496. "lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  497. "field. But you have inequality filters on 'x' and 'y'");
  498. NSString *reason =
  499. @"Invalid query. You have a where filter with "
  500. "an inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) "
  501. "on field 'x' and so you must also use 'x' as your first queryOrderedBy field, "
  502. "but your first queryOrderedBy is currently on field 'y' instead.";
  503. FSTAssertThrows([base queryOrderedByField:@"y"], reason);
  504. FSTAssertThrows([[coll queryOrderedByField:@"y"] queryWhereField:@"x" isGreaterThan:@32], reason);
  505. FSTAssertThrows([[base queryOrderedByField:@"y"] queryOrderedByField:@"x"], reason);
  506. FSTAssertThrows([[[coll queryOrderedByField:@"y"] queryOrderedByField:@"x"] queryWhereField:@"x"
  507. isGreaterThan:@32],
  508. reason);
  509. XCTAssertNoThrow([base queryWhereField:@"x" isLessThanOrEqualTo:@"cat"],
  510. @"Same inequality fields work");
  511. XCTAssertNoThrow([base queryWhereField:@"y" isEqualTo:@"cat"],
  512. @"Inequality and equality on different fields works");
  513. XCTAssertNoThrow([base queryWhereField:@"y" arrayContains:@"cat"],
  514. @"Inequality and array_contains on different fields works");
  515. XCTAssertNoThrow([base queryWhereField:@"y" arrayContainsAny:@[ @"cat" ]],
  516. @"array-contains-any on different fields works");
  517. XCTAssertNoThrow([base queryWhereField:@"y" in:@[ @"cat" ]], @"IN on different fields works");
  518. XCTAssertNoThrow([base queryOrderedByField:@"x"], @"inequality same as order by works");
  519. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"x" isGreaterThan:@32],
  520. @"inequality same as order by works");
  521. XCTAssertNoThrow([[base queryOrderedByField:@"x"] queryOrderedByField:@"y"],
  522. @"inequality same as first order by works.");
  523. XCTAssertNoThrow([[[coll queryOrderedByField:@"x"] queryOrderedByField:@"y"] queryWhereField:@"x"
  524. isGreaterThan:@32],
  525. @"inequality same as first order by works.");
  526. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" isEqualTo:@"cat"],
  527. @"equality different than orderBy works.");
  528. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" arrayContains:@"cat"],
  529. @"array_contains different than orderBy works.");
  530. }
  531. - (void)testQueriesWithMultipleArrayFiltersFail {
  532. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  533. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  534. arrayContains:@2],
  535. @"Invalid Query. You cannot use more than one 'arrayContains' filter.");
  536. FSTAssertThrows(
  537. [[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  538. arrayContainsAny:@[ @2 ]],
  539. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'arrayContains' filters.");
  540. FSTAssertThrows(
  541. [[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  542. arrayContains:@2],
  543. @"Invalid Query. You cannot use 'arrayContains' filters with 'arrayContainsAny' filters.");
  544. }
  545. - (void)testQueriesWithMultipleDisjunctiveFiltersFail {
  546. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  547. FSTAssertThrows([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo" in:@[ @2 ]],
  548. @"Invalid Query. You cannot use more than one 'in' filter.");
  549. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  550. arrayContainsAny:@[ @2 ]],
  551. @"Invalid Query. You cannot use more than one 'arrayContainsAny' filter.");
  552. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  553. in:@[ @2 ]],
  554. @"Invalid Query. You cannot use 'in' filters with 'arrayContainsAny' filters.");
  555. FSTAssertThrows([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo"
  556. arrayContainsAny:@[ @2 ]],
  557. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  558. // This is redundant with the above tests, but makes sure our validation doesn't get confused.
  559. FSTAssertThrows([[[coll queryWhereField:@"foo"
  560. in:@[ @1 ]] queryWhereField:@"foo"
  561. arrayContains:@2] queryWhereField:@"foo"
  562. arrayContainsAny:@[ @2 ]],
  563. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  564. FSTAssertThrows([[[coll queryWhereField:@"foo"
  565. arrayContains:@1] queryWhereField:@"foo"
  566. in:@[ @2 ]] queryWhereField:@"foo"
  567. arrayContainsAny:@[ @2 ]],
  568. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  569. }
  570. - (void)testQueriesCanUseInWithArrayContain {
  571. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  572. XCTAssertNoThrow([[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  573. in:@[ @2 ]],
  574. @"arrayContains with IN works.");
  575. XCTAssertNoThrow([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo"
  576. arrayContains:@2],
  577. @"IN with arrayContains works.");
  578. FSTAssertThrows([[[coll queryWhereField:@"foo"
  579. in:@[ @1 ]] queryWhereField:@"foo"
  580. arrayContains:@2] queryWhereField:@"foo"
  581. arrayContains:@3],
  582. @"Invalid Query. You cannot use more than one 'arrayContains' filter.");
  583. FSTAssertThrows([[[coll queryWhereField:@"foo"
  584. arrayContains:@1] queryWhereField:@"foo"
  585. in:@[ @2 ]] queryWhereField:@"foo"
  586. in:@[ @3 ]],
  587. @"Invalid Query. You cannot use more than one 'in' filter.");
  588. }
  589. - (void)testQueriesInAndArrayContainsAnyArrayRules {
  590. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  591. FSTAssertThrows([coll queryWhereField:@"foo" in:@[]],
  592. @"Invalid Query. A non-empty array is required for 'in' filters.");
  593. FSTAssertThrows([coll queryWhereField:@"foo" arrayContainsAny:@[]],
  594. @"Invalid Query. A non-empty array is required for 'arrayContainsAny' filters.");
  595. // The 10 element max includes duplicates.
  596. NSArray *values = @[ @1, @2, @3, @4, @5, @6, @7, @8, @9, @9, @9 ];
  597. FSTAssertThrows(
  598. [coll queryWhereField:@"foo" in:values],
  599. @"Invalid Query. 'in' filters support a maximum of 10 elements in the value array.");
  600. FSTAssertThrows([coll queryWhereField:@"foo" arrayContainsAny:values],
  601. @"Invalid Query. 'arrayContainsAny' filters support a maximum of 10 elements"
  602. " in the value array.");
  603. NSArray *withNullValues = @[ @1, [NSNull null] ];
  604. FSTAssertThrows([coll queryWhereField:@"foo" in:withNullValues],
  605. @"Invalid Query. 'in' filters cannot contain 'null' in the value array.");
  606. FSTAssertThrows(
  607. [coll queryWhereField:@"foo" arrayContainsAny:withNullValues],
  608. @"Invalid Query. 'arrayContainsAny' filters cannot contain 'null' in the value array.");
  609. NSArray *withNaNValues = @[ @2, @(NAN) ];
  610. FSTAssertThrows([coll queryWhereField:@"foo" in:withNaNValues],
  611. @"Invalid Query. 'in' filters cannot contain 'NaN' in the value array.");
  612. FSTAssertThrows(
  613. [coll queryWhereField:@"foo" arrayContainsAny:withNaNValues],
  614. @"Invalid Query. 'arrayContainsAny' filters cannot contain 'NaN' in the value array.");
  615. }
  616. #pragma mark - GeoPoint Validation
  617. - (void)testInvalidGeoPointParameters {
  618. [self verifyExceptionForInvalidLatitude:NAN];
  619. [self verifyExceptionForInvalidLatitude:-INFINITY];
  620. [self verifyExceptionForInvalidLatitude:INFINITY];
  621. [self verifyExceptionForInvalidLatitude:-90.1];
  622. [self verifyExceptionForInvalidLatitude:90.1];
  623. [self verifyExceptionForInvalidLongitude:NAN];
  624. [self verifyExceptionForInvalidLongitude:-INFINITY];
  625. [self verifyExceptionForInvalidLongitude:INFINITY];
  626. [self verifyExceptionForInvalidLongitude:-180.1];
  627. [self verifyExceptionForInvalidLongitude:180.1];
  628. }
  629. #pragma mark - Helpers
  630. /** Performs a write using each write API and makes sure it fails with the expected reason. */
  631. - (void)expectWrite:(id)data toFailWithReason:(NSString *)reason {
  632. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:YES];
  633. }
  634. /** Performs a write using each set API and makes sure it fails with the expected reason. */
  635. - (void)expectSet:(id)data toFailWithReason:(NSString *)reason {
  636. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:NO];
  637. }
  638. /** Performs a write using each update API and makes sure it fails with the expected reason. */
  639. - (void)expectUpdate:(id)data toFailWithReason:(NSString *)reason {
  640. [self expectWrite:data toFailWithReason:reason includeSets:NO includeUpdates:YES];
  641. }
  642. /**
  643. * Performs a write using each set and/or update API and makes sure it fails with the expected
  644. * reason.
  645. */
  646. - (void)expectWrite:(id)data
  647. toFailWithReason:(NSString *)reason
  648. includeSets:(BOOL)includeSets
  649. includeUpdates:(BOOL)includeUpdates {
  650. FIRDocumentReference *ref = [self documentRef];
  651. if (includeSets) {
  652. FSTAssertThrows([ref setData:data], reason, @"for %@", data);
  653. FSTAssertThrows([[ref.firestore batch] setData:data forDocument:ref], reason, @"for %@", data);
  654. }
  655. if (includeUpdates) {
  656. FSTAssertThrows([ref updateData:data], reason, @"for %@", data);
  657. FSTAssertThrows([[ref.firestore batch] updateData:data forDocument:ref], reason, @"for %@",
  658. data);
  659. }
  660. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  661. [ref.firestore
  662. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  663. if (includeSets) {
  664. FSTAssertThrows([transaction setData:data forDocument:ref], reason, @"for %@", data);
  665. }
  666. if (includeUpdates) {
  667. FSTAssertThrows([transaction updateData:data forDocument:ref], reason, @"for %@", data);
  668. }
  669. return nil;
  670. }
  671. completion:^(id result, NSError *error) {
  672. // ends up being a no-op transaction.
  673. XCTAssertNil(error);
  674. [transactionDone fulfill];
  675. }];
  676. [self awaitExpectations];
  677. }
  678. - (void)testFieldNamesMustNotBeEmpty {
  679. NSString *reason = @"Invalid field path. Provided names must not be empty.";
  680. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[]], reason);
  681. reason = @"Invalid field name at index 0. Field names must not be empty.";
  682. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[ @"" ]], reason);
  683. reason = @"Invalid field name at index 1. Field names must not be empty.";
  684. FSTAssertThrows(([[FIRFieldPath alloc] initWithFields:@[ @"foo", @"" ]]), reason);
  685. }
  686. /**
  687. * Tests a field path with all of our APIs that accept field paths and ensures they fail with the
  688. * specified reason.
  689. */
  690. - (void)expectFieldPath:(NSString *)fieldPath toFailWithReason:(NSString *)reason {
  691. // Get an arbitrary snapshot we can use for testing.
  692. FIRDocumentReference *docRef = [self documentRef];
  693. [self writeDocumentRef:docRef data:@{@"test" : @1}];
  694. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:docRef];
  695. // Update paths.
  696. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  697. dict[fieldPath] = @1;
  698. [self expectUpdate:dict toFailWithReason:reason];
  699. // Snapshot fields.
  700. FSTAssertThrows(snapshot[fieldPath], reason);
  701. // Query filter / order fields.
  702. FIRCollectionReference *collection = [self collectionRef];
  703. FSTAssertThrows([collection queryWhereField:fieldPath isEqualTo:@1], reason);
  704. // isLessThan, etc. omitted for brevity since the code path is trivially shared.
  705. FSTAssertThrows([collection queryOrderedByField:fieldPath], reason);
  706. }
  707. - (void)verifyExceptionForInvalidLatitude:(double)latitude {
  708. NSString *reason = [NSString
  709. stringWithFormat:@"GeoPoint requires a latitude value in the range of [-90, 90], but was %g",
  710. latitude];
  711. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:latitude longitude:0], reason);
  712. }
  713. - (void)verifyExceptionForInvalidLongitude:(double)longitude {
  714. NSString *reason =
  715. [NSString stringWithFormat:
  716. @"GeoPoint requires a longitude value in the range of [-180, 180], but was %g",
  717. longitude];
  718. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:0 longitude:longitude], reason);
  719. }
  720. @end