FIRValidationTests.mm 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. }
  348. - (void)testNonEqualityQueriesOnNullOrNaNFail {
  349. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:nil],
  350. @"Invalid Query. Null supports only equality comparisons.");
  351. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:[NSNull null]],
  352. @"Invalid Query. Null supports only equality comparisons.");
  353. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:nil],
  354. @"Invalid Query. Null supports only equality comparisons.");
  355. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:[NSNull null]],
  356. @"Invalid Query. Null supports only equality comparisons.");
  357. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:@(NAN)],
  358. @"Invalid Query. NaN supports only equality comparisons.");
  359. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:@(NAN)],
  360. @"Invalid Query. NaN supports only equality comparisons.");
  361. }
  362. - (void)testQueryCannotBeCreatedFromDocumentsMissingSortValues {
  363. FIRCollectionReference *testCollection =
  364. [self collectionRefWithDocuments:@{@"f" : @{@"v" : @"f", @"nosort" : @1.0}}];
  365. FIRQuery *query = [testCollection queryOrderedByField:@"sort"];
  366. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:[testCollection documentWithPath:@"f"]];
  367. XCTAssertTrue(snapshot.exists);
  368. NSString *reason = @"Invalid query. You are trying to start or end a query using a document for "
  369. "which the field 'sort' (used as the order by) does not exist.";
  370. FSTAssertThrows([query queryStartingAtDocument:snapshot], reason);
  371. FSTAssertThrows([query queryStartingAfterDocument:snapshot], reason);
  372. FSTAssertThrows([query queryEndingBeforeDocument:snapshot], reason);
  373. FSTAssertThrows([query queryEndingAtDocument:snapshot], reason);
  374. }
  375. - (void)testQueriesCannotBeSortedByAnUncommittedServerTimestamp {
  376. __weak FIRCollectionReference *collection = [self collectionRef];
  377. FIRFirestore *db = [self firestore];
  378. [db disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable network"]];
  379. [self awaitExpectations];
  380. XCTestExpectation *offlineCallbackDone =
  381. [self expectationWithDescription:@"offline callback done"];
  382. XCTestExpectation *onlineCallbackDone = [self expectationWithDescription:@"online callback done"];
  383. [collection addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) {
  384. XCTAssertNil(error);
  385. // Skip the initial empty snapshot.
  386. if (snapshot.empty) return;
  387. XCTAssertEqual(snapshot.count, 1);
  388. FIRQueryDocumentSnapshot *docSnap = snapshot.documents[0];
  389. if (snapshot.metadata.pendingWrites) {
  390. // Offline snapshot. Since the server timestamp is uncommitted, we
  391. // shouldn't be able to query by it.
  392. NSString *reason =
  393. @"Invalid query. You are trying to start or end a query using a document for which the "
  394. @"field 'timestamp' is an uncommitted server timestamp. (Since the value of this field "
  395. @"is unknown, you cannot start/end a query with it.)";
  396. FSTAssertThrows([[[collection queryOrderedByField:@"timestamp"] queryEndingAtDocument:docSnap]
  397. addSnapshotListener:^(FIRQuerySnapshot *, NSError *){
  398. }],
  399. reason);
  400. [offlineCallbackDone fulfill];
  401. } else {
  402. // Online snapshot. Since the server timestamp is committed, we should be able to query by it.
  403. [[[collection queryOrderedByField:@"timestamp"] queryEndingAtDocument:docSnap]
  404. addSnapshotListener:^(FIRQuerySnapshot *, NSError *){
  405. }];
  406. [onlineCallbackDone fulfill];
  407. }
  408. }];
  409. FIRDocumentReference *document = [collection documentWithAutoID];
  410. [document setData:@{@"timestamp" : [FIRFieldValue fieldValueForServerTimestamp]}];
  411. [self awaitExpectations];
  412. [db enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable network"]];
  413. [self awaitExpectations];
  414. }
  415. - (void)testQueryBoundMustNotHaveMoreComponentsThanSortOrders {
  416. FIRCollectionReference *testCollection = [self collectionRef];
  417. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  418. NSString *reason = @"Invalid query. You are trying to start or end a query using more values "
  419. "than were specified in the order by.";
  420. // More elements than order by
  421. FSTAssertThrows(([query queryStartingAtValues:@[ @1, @2 ]]), reason);
  422. FSTAssertThrows(([[query queryOrderedByField:@"bar"] queryStartingAtValues:@[ @1, @2, @3 ]]),
  423. reason);
  424. }
  425. - (void)testQueryOrderedByKeyBoundMustBeAStringWithoutSlashes {
  426. FIRQuery *query = [[self.db collectionWithPath:@"collection"]
  427. queryOrderedByFieldPath:[FIRFieldPath documentID]];
  428. FIRQuery *cgQuery = [[self.db collectionGroupWithID:@"collection"]
  429. queryOrderedByFieldPath:[FIRFieldPath documentID]];
  430. FSTAssertThrows([query queryStartingAtValues:@[ @1 ]],
  431. @"Invalid query. Expected a string for the document ID.");
  432. FSTAssertThrows([query queryStartingAtValues:@[ @"foo/bar" ]],
  433. @"Invalid query. When querying a collection and ordering by document "
  434. "ID, you must pass a plain document ID, but 'foo/bar' contains a slash.");
  435. FSTAssertThrows([cgQuery queryStartingAtValues:@[ @"foo" ]],
  436. @"Invalid query. When querying a collection group and ordering by "
  437. "document ID, you must pass a value that results in a valid document path, "
  438. "but 'foo' is not because it contains an odd number of segments.");
  439. }
  440. - (void)testQueryMustNotSpecifyStartingOrEndingPointAfterOrder {
  441. FIRCollectionReference *testCollection = [self collectionRef];
  442. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  443. NSString *reason =
  444. @"Invalid query. You must not specify a starting point before specifying the order by.";
  445. FSTAssertThrows([[query queryStartingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  446. FSTAssertThrows([[query queryStartingAfterValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  447. reason = @"Invalid query. You must not specify an ending point before specifying the order by.";
  448. FSTAssertThrows([[query queryEndingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  449. FSTAssertThrows([[query queryEndingBeforeValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  450. }
  451. - (void)testQueriesFilteredByDocumentIdMustUseStringsOrDocumentReferences {
  452. FIRCollectionReference *collection = [self collectionRef];
  453. NSString *reason = @"Invalid query. When querying by document ID you must provide a valid "
  454. "document ID, but it was an empty string.";
  455. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@""], reason);
  456. reason = @"Invalid query. When querying a collection by document ID you must provide a "
  457. "plain document ID, but 'foo/bar/baz' contains a '/' character.";
  458. FSTAssertThrows(
  459. [collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@"foo/bar/baz"], reason);
  460. reason = @"Invalid query. When querying by document ID you must provide a valid string or "
  461. "DocumentReference, but it was of type: __NSCFNumber";
  462. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@1], reason);
  463. reason = @"Invalid query. When querying a collection group by document ID, the value "
  464. "provided must result in a valid document path, but 'foo/bar/baz' is not because it "
  465. "has an odd number of segments.";
  466. FSTAssertThrows(
  467. [[self.db collectionGroupWithID:@"collection"] queryWhereFieldPath:[FIRFieldPath documentID]
  468. isEqualTo:@"foo/bar/baz"],
  469. reason);
  470. reason =
  471. @"Invalid query. You can't perform arrayContains queries on document ID since document IDs "
  472. "are not arrays.";
  473. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] arrayContains:@1],
  474. reason);
  475. }
  476. - (void)testQueriesUsingInAndDocumentIdMustHaveProperDocumentReferencesInArray {
  477. FIRCollectionReference *collection = [self collectionRef];
  478. NSString *reason = @"Invalid query. When querying by document ID you must provide a valid "
  479. "document ID, but it was an empty string.";
  480. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:@[ @"" ]], reason);
  481. reason = @"Invalid query. When querying a collection by document ID you must provide a "
  482. "plain document ID, but 'foo/bar/baz' contains a '/' character.";
  483. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:@[ @"foo/bar/baz" ]],
  484. reason);
  485. reason = @"Invalid query. When querying by document ID you must provide a valid string or "
  486. "DocumentReference, but it was of type: __NSArrayI";
  487. NSArray *value = @[ @1, @2 ];
  488. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] in:value], reason);
  489. reason = @"Invalid query. When querying a collection group by document ID, the value "
  490. "provided must result in a valid document path, but 'foo' is not because it "
  491. "has an odd number of segments.";
  492. FSTAssertThrows(
  493. [[self.db collectionGroupWithID:@"collection"] queryWhereFieldPath:[FIRFieldPath documentID]
  494. in:@[ @"foo" ]],
  495. reason);
  496. }
  497. - (void)testQueryInequalityFieldMustMatchFirstOrderByField {
  498. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  499. FIRQuery *base = [coll queryWhereField:@"x" isGreaterThanOrEqualTo:@32];
  500. FSTAssertThrows([base queryWhereField:@"y" isLessThan:@"cat"],
  501. @"Invalid Query. All where filters with an inequality (lessThan, "
  502. "lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  503. "field. But you have inequality filters on 'x' and 'y'");
  504. NSString *reason =
  505. @"Invalid query. You have a where filter with "
  506. "an inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) "
  507. "on field 'x' and so you must also use 'x' as your first queryOrderedBy field, "
  508. "but your first queryOrderedBy is currently on field 'y' instead.";
  509. FSTAssertThrows([base queryOrderedByField:@"y"], reason);
  510. FSTAssertThrows([[coll queryOrderedByField:@"y"] queryWhereField:@"x" isGreaterThan:@32], reason);
  511. FSTAssertThrows([[base queryOrderedByField:@"y"] queryOrderedByField:@"x"], reason);
  512. FSTAssertThrows([[[coll queryOrderedByField:@"y"] queryOrderedByField:@"x"] queryWhereField:@"x"
  513. isGreaterThan:@32],
  514. reason);
  515. XCTAssertNoThrow([base queryWhereField:@"x" isLessThanOrEqualTo:@"cat"],
  516. @"Same inequality fields work");
  517. XCTAssertNoThrow([base queryWhereField:@"y" isEqualTo:@"cat"],
  518. @"Inequality and equality on different fields works");
  519. XCTAssertNoThrow([base queryWhereField:@"y" arrayContains:@"cat"],
  520. @"Inequality and array_contains on different fields works");
  521. XCTAssertNoThrow([base queryWhereField:@"y" arrayContainsAny:@[ @"cat" ]],
  522. @"array-contains-any on different fields works");
  523. XCTAssertNoThrow([base queryWhereField:@"y" in:@[ @"cat" ]], @"IN on different fields works");
  524. XCTAssertNoThrow([base queryOrderedByField:@"x"], @"inequality same as order by works");
  525. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"x" isGreaterThan:@32],
  526. @"inequality same as order by works");
  527. XCTAssertNoThrow([[base queryOrderedByField:@"x"] queryOrderedByField:@"y"],
  528. @"inequality same as first order by works.");
  529. XCTAssertNoThrow([[[coll queryOrderedByField:@"x"] queryOrderedByField:@"y"] queryWhereField:@"x"
  530. isGreaterThan:@32],
  531. @"inequality same as first order by works.");
  532. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" isEqualTo:@"cat"],
  533. @"equality different than orderBy works.");
  534. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" arrayContains:@"cat"],
  535. @"array_contains different than orderBy works.");
  536. }
  537. - (void)testQueriesWithMultipleArrayFiltersFail {
  538. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  539. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  540. arrayContains:@2],
  541. @"Invalid Query. You cannot use more than one 'arrayContains' filter.");
  542. FSTAssertThrows(
  543. [[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  544. arrayContainsAny:@[ @2 ]],
  545. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'arrayContains' filters.");
  546. FSTAssertThrows(
  547. [[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  548. arrayContains:@2],
  549. @"Invalid Query. You cannot use 'arrayContains' filters with 'arrayContainsAny' filters.");
  550. }
  551. - (void)testQueriesWithMultipleDisjunctiveFiltersFail {
  552. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  553. FSTAssertThrows([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo" in:@[ @2 ]],
  554. @"Invalid Query. You cannot use more than one 'in' filter.");
  555. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  556. arrayContainsAny:@[ @2 ]],
  557. @"Invalid Query. You cannot use more than one 'arrayContainsAny' filter.");
  558. FSTAssertThrows([[coll queryWhereField:@"foo" arrayContainsAny:@[ @1 ]] queryWhereField:@"foo"
  559. in:@[ @2 ]],
  560. @"Invalid Query. You cannot use 'in' filters with 'arrayContainsAny' filters.");
  561. FSTAssertThrows([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo"
  562. arrayContainsAny:@[ @2 ]],
  563. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  564. // This is redundant with the above tests, but makes sure our validation doesn't get confused.
  565. FSTAssertThrows([[[coll queryWhereField:@"foo"
  566. in:@[ @1 ]] queryWhereField:@"foo"
  567. arrayContains:@2] queryWhereField:@"foo"
  568. arrayContainsAny:@[ @2 ]],
  569. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  570. FSTAssertThrows([[[coll queryWhereField:@"foo"
  571. arrayContains:@1] queryWhereField:@"foo"
  572. in:@[ @2 ]] queryWhereField:@"foo"
  573. arrayContainsAny:@[ @2 ]],
  574. @"Invalid Query. You cannot use 'arrayContainsAny' filters with 'in' filters.");
  575. }
  576. - (void)testQueriesCanUseInWithArrayContain {
  577. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  578. XCTAssertNoThrow([[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo"
  579. in:@[ @2 ]],
  580. @"arrayContains with IN works.");
  581. XCTAssertNoThrow([[coll queryWhereField:@"foo" in:@[ @1 ]] queryWhereField:@"foo"
  582. arrayContains:@2],
  583. @"IN with arrayContains works.");
  584. FSTAssertThrows([[[coll queryWhereField:@"foo"
  585. in:@[ @1 ]] queryWhereField:@"foo"
  586. arrayContains:@2] queryWhereField:@"foo"
  587. arrayContains:@3],
  588. @"Invalid Query. You cannot use more than one 'arrayContains' filter.");
  589. FSTAssertThrows([[[coll queryWhereField:@"foo"
  590. arrayContains:@1] queryWhereField:@"foo"
  591. in:@[ @2 ]] queryWhereField:@"foo"
  592. in:@[ @3 ]],
  593. @"Invalid Query. You cannot use more than one 'in' filter.");
  594. }
  595. - (void)testQueriesInAndArrayContainsAnyArrayRules {
  596. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  597. FSTAssertThrows([coll queryWhereField:@"foo" in:@[]],
  598. @"Invalid Query. A non-empty array is required for 'in' filters.");
  599. FSTAssertThrows([coll queryWhereField:@"foo" arrayContainsAny:@[]],
  600. @"Invalid Query. A non-empty array is required for 'arrayContainsAny' filters.");
  601. // The 10 element max includes duplicates.
  602. NSArray *values = @[ @1, @2, @3, @4, @5, @6, @7, @8, @9, @9, @9 ];
  603. FSTAssertThrows(
  604. [coll queryWhereField:@"foo" in:values],
  605. @"Invalid Query. 'in' filters support a maximum of 10 elements in the value array.");
  606. FSTAssertThrows([coll queryWhereField:@"foo" arrayContainsAny:values],
  607. @"Invalid Query. 'arrayContainsAny' filters support a maximum of 10 elements"
  608. " in the value array.");
  609. NSArray *withNullValues = @[ @1, [NSNull null] ];
  610. FSTAssertThrows([coll queryWhereField:@"foo" in:withNullValues],
  611. @"Invalid Query. 'in' filters cannot contain 'null' in the value array.");
  612. FSTAssertThrows(
  613. [coll queryWhereField:@"foo" arrayContainsAny:withNullValues],
  614. @"Invalid Query. 'arrayContainsAny' filters cannot contain 'null' in the value array.");
  615. NSArray *withNaNValues = @[ @2, @(NAN) ];
  616. FSTAssertThrows([coll queryWhereField:@"foo" in:withNaNValues],
  617. @"Invalid Query. 'in' filters cannot contain 'NaN' in the value array.");
  618. FSTAssertThrows(
  619. [coll queryWhereField:@"foo" arrayContainsAny:withNaNValues],
  620. @"Invalid Query. 'arrayContainsAny' filters cannot contain 'NaN' in the value array.");
  621. }
  622. #pragma mark - GeoPoint Validation
  623. - (void)testInvalidGeoPointParameters {
  624. [self verifyExceptionForInvalidLatitude:NAN];
  625. [self verifyExceptionForInvalidLatitude:-INFINITY];
  626. [self verifyExceptionForInvalidLatitude:INFINITY];
  627. [self verifyExceptionForInvalidLatitude:-90.1];
  628. [self verifyExceptionForInvalidLatitude:90.1];
  629. [self verifyExceptionForInvalidLongitude:NAN];
  630. [self verifyExceptionForInvalidLongitude:-INFINITY];
  631. [self verifyExceptionForInvalidLongitude:INFINITY];
  632. [self verifyExceptionForInvalidLongitude:-180.1];
  633. [self verifyExceptionForInvalidLongitude:180.1];
  634. }
  635. #pragma mark - Helpers
  636. /** Performs a write using each write API and makes sure it fails with the expected reason. */
  637. - (void)expectWrite:(id)data toFailWithReason:(NSString *)reason {
  638. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:YES];
  639. }
  640. /** Performs a write using each set API and makes sure it fails with the expected reason. */
  641. - (void)expectSet:(id)data toFailWithReason:(NSString *)reason {
  642. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:NO];
  643. }
  644. /** Performs a write using each update API and makes sure it fails with the expected reason. */
  645. - (void)expectUpdate:(id)data toFailWithReason:(NSString *)reason {
  646. [self expectWrite:data toFailWithReason:reason includeSets:NO includeUpdates:YES];
  647. }
  648. /**
  649. * Performs a write using each set and/or update API and makes sure it fails with the expected
  650. * reason.
  651. */
  652. - (void)expectWrite:(id)data
  653. toFailWithReason:(NSString *)reason
  654. includeSets:(BOOL)includeSets
  655. includeUpdates:(BOOL)includeUpdates {
  656. FIRDocumentReference *ref = [self documentRef];
  657. if (includeSets) {
  658. FSTAssertThrows([ref setData:data], reason, @"for %@", data);
  659. FSTAssertThrows([[ref.firestore batch] setData:data forDocument:ref], reason, @"for %@", data);
  660. }
  661. if (includeUpdates) {
  662. FSTAssertThrows([ref updateData:data], reason, @"for %@", data);
  663. FSTAssertThrows([[ref.firestore batch] updateData:data forDocument:ref], reason, @"for %@",
  664. data);
  665. }
  666. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  667. [ref.firestore
  668. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  669. if (includeSets) {
  670. FSTAssertThrows([transaction setData:data forDocument:ref], reason, @"for %@", data);
  671. }
  672. if (includeUpdates) {
  673. FSTAssertThrows([transaction updateData:data forDocument:ref], reason, @"for %@", data);
  674. }
  675. return nil;
  676. }
  677. completion:^(id result, NSError *error) {
  678. // ends up being a no-op transaction.
  679. XCTAssertNil(error);
  680. [transactionDone fulfill];
  681. }];
  682. [self awaitExpectations];
  683. }
  684. - (void)testFieldNamesMustNotBeEmpty {
  685. NSString *reason = @"Invalid field path. Provided names must not be empty.";
  686. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[]], reason);
  687. reason = @"Invalid field name at index 0. Field names must not be empty.";
  688. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[ @"" ]], reason);
  689. reason = @"Invalid field name at index 1. Field names must not be empty.";
  690. FSTAssertThrows(([[FIRFieldPath alloc] initWithFields:@[ @"foo", @"" ]]), reason);
  691. }
  692. /**
  693. * Tests a field path with all of our APIs that accept field paths and ensures they fail with the
  694. * specified reason.
  695. */
  696. - (void)expectFieldPath:(NSString *)fieldPath toFailWithReason:(NSString *)reason {
  697. // Get an arbitrary snapshot we can use for testing.
  698. FIRDocumentReference *docRef = [self documentRef];
  699. [self writeDocumentRef:docRef data:@{@"test" : @1}];
  700. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:docRef];
  701. // Update paths.
  702. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  703. dict[fieldPath] = @1;
  704. [self expectUpdate:dict toFailWithReason:reason];
  705. // Snapshot fields.
  706. FSTAssertThrows(snapshot[fieldPath], reason);
  707. // Query filter / order fields.
  708. FIRCollectionReference *collection = [self collectionRef];
  709. FSTAssertThrows([collection queryWhereField:fieldPath isEqualTo:@1], reason);
  710. // isLessThan, etc. omitted for brevity since the code path is trivially shared.
  711. FSTAssertThrows([collection queryOrderedByField:fieldPath], reason);
  712. }
  713. - (void)verifyExceptionForInvalidLatitude:(double)latitude {
  714. NSString *reason = [NSString
  715. stringWithFormat:@"GeoPoint requires a latitude value in the range of [-90, 90], but was %g",
  716. latitude];
  717. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:latitude longitude:0], reason);
  718. }
  719. - (void)verifyExceptionForInvalidLongitude:(double)longitude {
  720. NSString *reason =
  721. [NSString stringWithFormat:
  722. @"GeoPoint requires a longitude value in the range of [-180, 180], but was %g",
  723. longitude];
  724. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:0 longitude:longitude], reason);
  725. }
  726. @end