FIRValidationTests.mm 47 KB

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