FIRValidationTests.mm 43 KB

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