FIRValidationTests.mm 40 KB

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