FIRValidationTests.mm 48 KB

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