FIRValidationTests.mm 42 KB

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