FIRValidationTests.mm 43 KB

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