FIRValidationTests.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 Firestore;
  17. #import <XCTest/XCTest.h>
  18. #import "FSTHelpers.h"
  19. #import "FSTIntegrationTestCase.h"
  20. // We have tests for passing nil when nil is not supposed to be allowed. So suppress the warnings.
  21. #pragma clang diagnostic ignored "-Wnonnull"
  22. @interface FIRValidationTests : FSTIntegrationTestCase
  23. @end
  24. @implementation FIRValidationTests
  25. #pragma mark - FIRFirestoreSettings Validation
  26. - (void)testNilHostFails {
  27. FIRFirestoreSettings *settings = self.db.settings;
  28. FSTAssertThrows(settings.host = nil,
  29. @"host setting may not be nil. You should generally just use the default value "
  30. "(which is firestore.googleapis.com)");
  31. }
  32. - (void)testNilDispatchQueueFails {
  33. FIRFirestoreSettings *settings = self.db.settings;
  34. FSTAssertThrows(settings.dispatchQueue = nil,
  35. @"dispatch queue setting may not be nil. Create a new dispatch queue with "
  36. "dispatch_queue_create(\"com.example.MyQueue\", NULL) or just use the default "
  37. "(which is the main queue, returned from dispatch_get_main_queue())");
  38. }
  39. - (void)testChangingSettingsAfterUseFails {
  40. FIRFirestoreSettings *settings = self.db.settings;
  41. [[self.db documentWithPath:@"foo/bar"] setData:@{ @"a" : @42 }];
  42. settings.host = @"example.com";
  43. FSTAssertThrows(self.db.settings = settings,
  44. @"Firestore instance has already been started and its settings can no longer be "
  45. @"changed. You can only set settings before calling any other methods on "
  46. @"a Firestore instance.");
  47. }
  48. #pragma mark - FIRFirestore Validation
  49. - (void)testNilFIRAppFails {
  50. FSTAssertThrows(
  51. [FIRFirestore firestoreForApp:nil],
  52. @"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd like to use the "
  53. "default FirebaseApp instance.");
  54. }
  55. // TODO(b/62410906): Test for firestoreForApp:database: with nil DatabaseID.
  56. - (void)testNilTransactionBlocksFail {
  57. FSTAssertThrows([self.db runTransactionWithBlock:nil
  58. completion:^(id result, NSError *error) {
  59. XCTFail(@"Completion shouldn't run.");
  60. }],
  61. @"Transaction block cannot be nil.");
  62. FSTAssertThrows(
  63. [self.db runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  64. XCTFail(@"Transaction block shouldn't run.");
  65. return nil;
  66. }
  67. completion:nil],
  68. @"Transaction completion block cannot be nil.");
  69. }
  70. #pragma mark - Collection and Document Path Validation
  71. - (void)testNilCollectionPathsFail {
  72. FIRDocumentReference *baseDocRef = [self.db documentWithPath:@"foo/bar"];
  73. NSString *nilError = @"Collection path cannot be nil.";
  74. FSTAssertThrows([self.db collectionWithPath:nil], nilError);
  75. FSTAssertThrows([baseDocRef collectionWithPath:nil], nilError);
  76. }
  77. - (void)testWrongLengthCollectionPathsFail {
  78. FIRDocumentReference *baseDocRef = [self.db documentWithPath:@"foo/bar"];
  79. NSArray *badAbsolutePaths = @[ @"foo/bar", @"foo/bar/baz/quu" ];
  80. NSArray *badRelativePaths = @[ @"", @"baz/quu" ];
  81. NSArray *badPathLengths = @[ @2, @4 ];
  82. NSString *errorFormat =
  83. @"Invalid collection reference. Collection references must have an odd "
  84. @"number of segments, but %@ has %@";
  85. for (NSUInteger i = 0; i < badAbsolutePaths.count; i++) {
  86. NSString *error =
  87. [NSString stringWithFormat:errorFormat, badAbsolutePaths[i], badPathLengths[i]];
  88. FSTAssertThrows([self.db collectionWithPath:badAbsolutePaths[i]], error);
  89. FSTAssertThrows([baseDocRef collectionWithPath:badRelativePaths[i]], error);
  90. }
  91. }
  92. - (void)testNilDocumentPathsFail {
  93. FIRCollectionReference *baseCollectionRef = [self.db collectionWithPath:@"foo"];
  94. NSString *nilError = @"Document path cannot be nil.";
  95. FSTAssertThrows([self.db documentWithPath:nil], nilError);
  96. FSTAssertThrows([baseCollectionRef documentWithPath:nil], nilError);
  97. }
  98. - (void)testWrongLengthDocumentPathsFail {
  99. FIRCollectionReference *baseCollectionRef = [self.db collectionWithPath:@"foo"];
  100. NSArray *badAbsolutePaths = @[ @"foo", @"foo/bar/baz" ];
  101. NSArray *badRelativePaths = @[ @"", @"bar/baz" ];
  102. NSArray *badPathLengths = @[ @1, @3 ];
  103. NSString *errorFormat =
  104. @"Invalid document reference. Document references must have an even "
  105. @"number of segments, but %@ has %@";
  106. for (NSUInteger i = 0; i < badAbsolutePaths.count; i++) {
  107. NSString *error =
  108. [NSString stringWithFormat:errorFormat, badAbsolutePaths[i], badPathLengths[i]];
  109. FSTAssertThrows([self.db documentWithPath:badAbsolutePaths[i]], error);
  110. FSTAssertThrows([baseCollectionRef documentWithPath:badRelativePaths[i]], error);
  111. }
  112. }
  113. - (void)testPathsWithEmptySegmentsFail {
  114. // We're only testing using collectionWithPath since the validation happens in FSTPath which is
  115. // shared by all methods that accept paths.
  116. // leading / trailing slashes are okay.
  117. [self.db collectionWithPath:@"/foo/"];
  118. [self.db collectionWithPath:@"/foo"];
  119. [self.db collectionWithPath:@"foo/"];
  120. FSTAssertThrows([self.db collectionWithPath:@"foo//bar/baz"],
  121. @"Invalid path (foo//bar/baz). Paths must not contain // in them.");
  122. FSTAssertThrows([self.db collectionWithPath:@"//foo"],
  123. @"Invalid path (//foo). Paths must not contain // in them.");
  124. FSTAssertThrows([self.db collectionWithPath:@"foo//"],
  125. @"Invalid path (foo//). Paths must not contain // in them.");
  126. }
  127. #pragma mark - Write Validation
  128. - (void)testWritesWithNonDictionaryValuesFail {
  129. NSArray *badData = @[
  130. @42, @"test", @[ @1 ], [NSDate date], [NSNull null], [FIRFieldValue fieldValueForDelete],
  131. [FIRFieldValue fieldValueForServerTimestamp]
  132. ];
  133. for (id data in badData) {
  134. [self expectWrite:data toFailWithReason:@"Data to be written must be an NSDictionary."];
  135. }
  136. }
  137. - (void)testWritesWithNestedArraysFail {
  138. [self expectWrite:@{
  139. @"nested-array" : @[ @1, @[ @2 ] ]
  140. }
  141. toFailWithReason:@"Nested arrays are not supported"];
  142. }
  143. - (void)testWritesWithInvalidTypesFail {
  144. [self expectWrite:@{
  145. @"foo" : @{@"bar" : self}
  146. }
  147. toFailWithReason:@"Unsupported type: FIRValidationTests (found in field foo.bar)"];
  148. }
  149. - (void)testWritesWithLargeNumbersFail {
  150. NSNumber *num = @((unsigned long long)LONG_MAX + 1);
  151. NSString *reason =
  152. [NSString stringWithFormat:@"NSNumber (%@) is too large (found in field num)", num];
  153. [self expectWrite:@{@"num" : num} toFailWithReason:reason];
  154. }
  155. - (void)testWritesWithReferencesToADifferentDatabaseFail {
  156. FIRDocumentReference *ref =
  157. [[self firestoreWithProjectID:@"different-db"] documentWithPath:@"baz/quu"];
  158. id data = @{@"foo" : ref};
  159. [self expectWrite:data
  160. toFailWithReason:
  161. [NSString
  162. stringWithFormat:@"Document Reference is for database different-db/(default) but "
  163. "should be for database %@/(default) (found in field foo)",
  164. [FSTIntegrationTestCase projectID]]];
  165. }
  166. - (void)testWritesWithReservedFieldsFail {
  167. [self expectWrite:@{
  168. @"__baz__" : @1
  169. }
  170. toFailWithReason:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  171. [self expectWrite:@{
  172. @"foo" : @{@"__baz__" : @1}
  173. }
  174. toFailWithReason:
  175. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  176. [self expectWrite:@{
  177. @"__baz__" : @{@"foo" : @1}
  178. }
  179. toFailWithReason:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  180. [self expectUpdate:@{
  181. @"foo.__baz__" : @1
  182. }
  183. toFailWithReason:
  184. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  185. [self expectUpdate:@{
  186. @"__baz__.foo" : @1
  187. }
  188. toFailWithReason:
  189. @"Document fields cannot begin and end with __ (found in field __baz__.foo)"];
  190. [self expectUpdate:@{
  191. @1 : @1
  192. }
  193. toFailWithReason:@"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths."];
  194. }
  195. - (void)testSetsWithFieldValueDeleteFail {
  196. [self expectSet:@{@"foo" : [FIRFieldValue fieldValueForDelete]}
  197. toFailWithReason:@"FieldValue.delete() can only be used with updateData()."];
  198. }
  199. - (void)testUpdatesWithNestedFieldValueDeleteFail {
  200. [self expectUpdate:@{
  201. @"foo" : @{@"bar" : [FIRFieldValue fieldValueForDelete]}
  202. }
  203. toFailWithReason:
  204. @"FieldValue.delete() can only appear at the top level of your update data "
  205. "(found in field foo.bar)"];
  206. }
  207. - (void)testBatchWritesWithIncorrectReferencesFail {
  208. FIRFirestore *db1 = [self firestore];
  209. FIRFirestore *db2 = [self firestore];
  210. XCTAssertNotEqual(db1, db2);
  211. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  212. id data = @{ @"foo" : @1 };
  213. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  214. FIRWriteBatch *batch = [db1 batch];
  215. FSTAssertThrows([batch setData:data forDocument:badRef], reason);
  216. FSTAssertThrows([batch setData:data forDocument:badRef options:[FIRSetOptions merge]], reason);
  217. FSTAssertThrows([batch updateData:data forDocument:badRef], reason);
  218. FSTAssertThrows([batch deleteDocument:badRef], reason);
  219. }
  220. - (void)testTransactionWritesWithIncorrectReferencesFail {
  221. FIRFirestore *db1 = [self firestore];
  222. FIRFirestore *db2 = [self firestore];
  223. XCTAssertNotEqual(db1, db2);
  224. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  225. id data = @{ @"foo" : @1 };
  226. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  227. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  228. [db1 runTransactionWithBlock:^id(FIRTransaction *txn, NSError **pError) {
  229. FSTAssertThrows([txn getDocument:badRef error:nil], reason);
  230. FSTAssertThrows([txn setData:data forDocument:badRef], reason);
  231. FSTAssertThrows([txn setData:data forDocument:badRef options:[FIRSetOptions merge]], reason);
  232. FSTAssertThrows([txn updateData:data forDocument:badRef], reason);
  233. FSTAssertThrows([txn deleteDocument:badRef], reason);
  234. return nil;
  235. }
  236. completion:^(id result, NSError *error) {
  237. // ends up being a no-op transaction.
  238. XCTAssertNil(error);
  239. [transactionDone fulfill];
  240. }];
  241. [self awaitExpectations];
  242. }
  243. #pragma mark - Field Path validation
  244. // TODO(b/37244157): More validation for invalid field paths.
  245. - (void)testFieldPathsWithEmptySegmentsFail {
  246. NSArray *badFieldPaths = @[ @"", @"foo..baz", @".foo", @"foo." ];
  247. for (NSString *fieldPath in badFieldPaths) {
  248. NSString *reason =
  249. [NSString stringWithFormat:
  250. @"Invalid field path (%@). Paths must not be empty, begin with "
  251. @"'.', end with '.', or contain '..'",
  252. fieldPath];
  253. [self expectFieldPath:fieldPath toFailWithReason:reason];
  254. }
  255. }
  256. - (void)testFieldPathsWithInvalidSegmentsFail {
  257. NSArray *badFieldPaths = @[ @"foo~bar", @"foo*bar", @"foo/bar", @"foo[1", @"foo]1", @"foo[1]" ];
  258. for (NSString *fieldPath in badFieldPaths) {
  259. NSString *reason =
  260. [NSString stringWithFormat:
  261. @"Invalid field path (%@). Paths must not contain '~', '*', '/', '[', or ']'",
  262. fieldPath];
  263. [self expectFieldPath:fieldPath toFailWithReason:reason];
  264. }
  265. }
  266. #pragma mark - Query Validation
  267. - (void)testQueryWithNonPositiveLimitFails {
  268. FSTAssertThrows([[self collectionRef] queryLimitedTo:0],
  269. @"Invalid Query. Query limit (0) is invalid. Limit must be positive.");
  270. FSTAssertThrows([[self collectionRef] queryLimitedTo:-1],
  271. @"Invalid Query. Query limit (-1) is invalid. Limit must be positive.");
  272. }
  273. - (void)testQueryInequalityOnNullOrNaNFails {
  274. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:nil],
  275. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  276. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:[NSNull null]],
  277. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  278. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:@(NAN)],
  279. @"Invalid Query. You can only perform equality comparisons on NaN.");
  280. }
  281. - (void)testQueryCannotBeCreatedFromDocumentsMissingSortValues {
  282. FIRCollectionReference *testCollection = [self collectionRefWithDocuments:@{
  283. @"f" : @{@"v" : @"f", @"nosort" : @1.0}
  284. }];
  285. FIRQuery *query = [testCollection queryOrderedByField:@"sort"];
  286. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:[testCollection documentWithPath:@"f"]];
  287. XCTAssertTrue(snapshot.exists);
  288. NSString *reason =
  289. @"Invalid query. You are trying to start or end a query using a document for "
  290. "which the field 'sort' (used as the order by) does not exist.";
  291. FSTAssertThrows([query queryStartingAtDocument:snapshot], reason);
  292. FSTAssertThrows([query queryStartingAfterDocument:snapshot], reason);
  293. FSTAssertThrows([query queryEndingBeforeDocument:snapshot], reason);
  294. FSTAssertThrows([query queryEndingAtDocument:snapshot], reason);
  295. }
  296. - (void)testQueryBoundMustNotHaveMoreComponentsThanSortOrders {
  297. FIRCollectionReference *testCollection = [self collectionRef];
  298. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  299. NSString *reason =
  300. @"Invalid query. You are trying to start or end a query using more values "
  301. "than were specified in the order by.";
  302. // More elements than order by
  303. FSTAssertThrows(([query queryStartingAtValues:@[ @1, @2 ]]), reason);
  304. FSTAssertThrows(([[query queryOrderedByField:@"bar"] queryStartingAtValues:@[ @1, @2, @3 ]]),
  305. reason);
  306. }
  307. - (void)testQueryOrderedByKeyBoundMustBeAStringWithoutSlashes {
  308. FIRCollectionReference *testCollection = [self collectionRef];
  309. FIRQuery *query = [testCollection queryOrderedByFieldPath:[FIRFieldPath documentID]];
  310. FSTAssertThrows([query queryStartingAtValues:@[ @1 ]],
  311. @"Invalid query. Expected a string for the document ID.");
  312. FSTAssertThrows([query queryStartingAtValues:@[ @"foo/bar" ]],
  313. @"Invalid query. Document ID 'foo/bar' contains a slash.");
  314. }
  315. - (void)testQueryMustNotSpecifyStartingOrEndingPointAfterOrder {
  316. FIRCollectionReference *testCollection = [self collectionRef];
  317. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  318. NSString *reason =
  319. @"Invalid query. You must not specify a starting point before specifying the order by.";
  320. FSTAssertThrows([[query queryStartingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  321. FSTAssertThrows([[query queryStartingAfterValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  322. reason = @"Invalid query. You must not specify an ending point before specifying the order by.";
  323. FSTAssertThrows([[query queryEndingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  324. FSTAssertThrows([[query queryEndingBeforeValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  325. }
  326. - (void)testQueriesFilteredByDocumentIDMustUseStringsOrDocumentReferences {
  327. FIRCollectionReference *collection = [self collectionRef];
  328. NSString *reason =
  329. @"Invalid query. When querying by document ID you must provide a valid "
  330. "document ID, but it was an empty string.";
  331. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@""], reason);
  332. reason =
  333. @"Invalid query. When querying by document ID you must provide a valid document ID, "
  334. "but 'foo/bar/baz' contains a '/' character.";
  335. FSTAssertThrows(
  336. [collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@"foo/bar/baz"], reason);
  337. reason =
  338. @"Invalid query. When querying by document ID you must provide a valid string or "
  339. "DocumentReference, but it was of type: __NSCFNumber";
  340. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@1], reason);
  341. }
  342. - (void)testQueryInequalityFieldMustMatchFirstOrderByField {
  343. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  344. FIRQuery *base = [coll queryWhereField:@"x" isGreaterThanOrEqualTo:@32];
  345. FSTAssertThrows([base queryWhereField:@"y" isLessThan:@"cat"],
  346. @"Invalid Query. All where filters with an inequality (lessThan, "
  347. "lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  348. "field. But you have inequality filters on 'x' and 'y'");
  349. NSString *reason =
  350. @"Invalid query. You have a where filter with "
  351. "an inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) "
  352. "on field 'x' and so you must also use 'x' as your first queryOrderedBy field, "
  353. "but your first queryOrderedBy is currently on field 'y' instead.";
  354. FSTAssertThrows([base queryOrderedByField:@"y"], reason);
  355. FSTAssertThrows([[coll queryOrderedByField:@"y"] queryWhereField:@"x" isGreaterThan:@32], reason);
  356. FSTAssertThrows([[base queryOrderedByField:@"y"] queryOrderedByField:@"x"], reason);
  357. FSTAssertThrows([[[coll queryOrderedByField:@"y"] queryOrderedByField:@"x"] queryWhereField:@"x"
  358. isGreaterThan:@32],
  359. reason);
  360. XCTAssertNoThrow([base queryWhereField:@"x" isLessThanOrEqualTo:@"cat"],
  361. @"Same inequality fields work");
  362. XCTAssertNoThrow([base queryWhereField:@"y" isEqualTo:@"cat"],
  363. @"Inequality and equality on different fields works");
  364. XCTAssertNoThrow([base queryOrderedByField:@"x"], @"inequality same as order by works");
  365. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"x" isGreaterThan:@32],
  366. @"inequality same as order by works");
  367. XCTAssertNoThrow([[base queryOrderedByField:@"x"] queryOrderedByField:@"y"],
  368. @"inequality same as first order by works.");
  369. XCTAssertNoThrow([[[coll queryOrderedByField:@"x"] queryOrderedByField:@"y"] queryWhereField:@"x"
  370. isGreaterThan:@32],
  371. @"inequality same as first order by works.");
  372. }
  373. #pragma mark - GeoPoint Validation
  374. - (void)testInvalidGeoPointParameters {
  375. [self verifyExceptionForInvalidLatitude:NAN];
  376. [self verifyExceptionForInvalidLatitude:-INFINITY];
  377. [self verifyExceptionForInvalidLatitude:INFINITY];
  378. [self verifyExceptionForInvalidLatitude:-90.1];
  379. [self verifyExceptionForInvalidLatitude:90.1];
  380. [self verifyExceptionForInvalidLongitude:NAN];
  381. [self verifyExceptionForInvalidLongitude:-INFINITY];
  382. [self verifyExceptionForInvalidLongitude:INFINITY];
  383. [self verifyExceptionForInvalidLongitude:-180.1];
  384. [self verifyExceptionForInvalidLongitude:180.1];
  385. }
  386. #pragma mark - Helpers
  387. /** Performs a write using each write API and makes sure it fails with the expected reason. */
  388. - (void)expectWrite:(id)data toFailWithReason:(NSString *)reason {
  389. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:YES];
  390. }
  391. /** Performs a write using each set API and makes sure it fails with the expected reason. */
  392. - (void)expectSet:(id)data toFailWithReason:(NSString *)reason {
  393. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:NO];
  394. }
  395. /** Performs a write using each update API and makes sure it fails with the expected reason. */
  396. - (void)expectUpdate:(id)data toFailWithReason:(NSString *)reason {
  397. [self expectWrite:data toFailWithReason:reason includeSets:NO includeUpdates:YES];
  398. }
  399. /**
  400. * Performs a write using each set and/or update API and makes sure it fails with the expected
  401. * reason.
  402. */
  403. - (void)expectWrite:(id)data
  404. toFailWithReason:(NSString *)reason
  405. includeSets:(BOOL)includeSets
  406. includeUpdates:(BOOL)includeUpdates {
  407. FIRDocumentReference *ref = [self documentRef];
  408. if (includeSets) {
  409. FSTAssertThrows([ref setData:data], reason, @"for %@", data);
  410. FSTAssertThrows([[ref.firestore batch] setData:data forDocument:ref], reason, @"for %@", data);
  411. }
  412. if (includeUpdates) {
  413. FSTAssertThrows([ref updateData:data], reason, @"for %@", data);
  414. FSTAssertThrows([[ref.firestore batch] updateData:data forDocument:ref], reason, @"for %@",
  415. data);
  416. }
  417. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  418. [ref.firestore runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  419. if (includeSets) {
  420. FSTAssertThrows([transaction setData:data forDocument:ref], reason, @"for %@", data);
  421. }
  422. if (includeUpdates) {
  423. FSTAssertThrows([transaction updateData:data forDocument:ref], reason, @"for %@", data);
  424. }
  425. return nil;
  426. }
  427. completion:^(id result, NSError *error) {
  428. // ends up being a no-op transaction.
  429. XCTAssertNil(error);
  430. [transactionDone fulfill];
  431. }];
  432. [self awaitExpectations];
  433. }
  434. - (void)testFieldNamesMustNotBeEmpty {
  435. NSString *reason = @"Invalid field path. Provided names must not be empty.";
  436. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[]], reason);
  437. reason = @"Invalid field name at index 0. Field names must not be empty.";
  438. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[ @"" ]], reason);
  439. reason = @"Invalid field name at index 1. Field names must not be empty.";
  440. FSTAssertThrows(([[FIRFieldPath alloc] initWithFields:@[ @"foo", @"" ]]), reason);
  441. }
  442. /**
  443. * Tests a field path with all of our APIs that accept field paths and ensures they fail with the
  444. * specified reason.
  445. */
  446. - (void)expectFieldPath:(NSString *)fieldPath toFailWithReason:(NSString *)reason {
  447. // Get an arbitrary snapshot we can use for testing.
  448. FIRDocumentReference *docRef = [self documentRef];
  449. [self writeDocumentRef:docRef data:@{ @"test" : @1 }];
  450. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:docRef];
  451. // Update paths.
  452. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  453. dict[fieldPath] = @1;
  454. [self expectUpdate:dict toFailWithReason:reason];
  455. // Snapshot fields.
  456. FSTAssertThrows(snapshot[fieldPath], reason);
  457. // Query filter / order fields.
  458. FIRCollectionReference *collection = [self collectionRef];
  459. FSTAssertThrows([collection queryWhereField:fieldPath isEqualTo:@1], reason);
  460. // isLessThan, etc. omitted for brevity since the code path is trivially shared.
  461. FSTAssertThrows([collection queryOrderedByField:fieldPath], reason);
  462. }
  463. - (void)verifyExceptionForInvalidLatitude:(double)latitude {
  464. NSString *reason = [NSString
  465. stringWithFormat:@"GeoPoint requires a latitude value in the range of [-90, 90], but was %f",
  466. latitude];
  467. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:latitude longitude:0], reason);
  468. }
  469. - (void)verifyExceptionForInvalidLongitude:(double)longitude {
  470. NSString *reason =
  471. [NSString stringWithFormat:
  472. @"GeoPoint requires a longitude value in the range of [-180, 180], but was %f",
  473. longitude];
  474. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:0 longitude:longitude], reason);
  475. }
  476. @end