FIRValidationTests.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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;
  17. #import <XCTest/XCTest.h>
  18. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  19. #import "Firestore/Example/Tests/Util/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)testWritesWithDirectlyNestedArraysFail {
  138. [self expectWrite:@{
  139. @"nested-array" : @[ @1, @[ @2 ] ]
  140. }
  141. toFailWithReason:@"Nested arrays are not supported"];
  142. }
  143. - (void)testWritesWithIndirectlyNestedArraysSucceed {
  144. NSDictionary<NSString *, id> *data = @{ @"nested-array" : @[ @1, @{@"foo" : @[ @2 ]} ] };
  145. FIRDocumentReference *ref = [self documentRef];
  146. FIRDocumentReference *ref2 = [self documentRef];
  147. XCTestExpectation *expectation = [self expectationWithDescription:@"setData"];
  148. [ref setData:data
  149. completion:^(NSError *_Nullable error) {
  150. XCTAssertNil(error);
  151. [expectation fulfill];
  152. }];
  153. [self awaitExpectations];
  154. expectation = [self expectationWithDescription:@"batch.setData"];
  155. [[[ref.firestore batch] setData:data forDocument:ref]
  156. commitWithCompletion:^(NSError *_Nullable error) {
  157. XCTAssertNil(error);
  158. [expectation fulfill];
  159. }];
  160. [self awaitExpectations];
  161. expectation = [self expectationWithDescription:@"updateData"];
  162. [ref updateData:data
  163. completion:^(NSError *_Nullable error) {
  164. XCTAssertNil(error);
  165. [expectation fulfill];
  166. }];
  167. [self awaitExpectations];
  168. expectation = [self expectationWithDescription:@"batch.updateData"];
  169. [[[ref.firestore batch] updateData:data forDocument:ref]
  170. commitWithCompletion:^(NSError *_Nullable error) {
  171. XCTAssertNil(error);
  172. [expectation fulfill];
  173. }];
  174. [self awaitExpectations];
  175. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  176. [ref.firestore runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  177. // Note ref2 does not exist at this point so set that and update ref.
  178. [transaction updateData:data forDocument:ref];
  179. [transaction setData:data forDocument:ref2];
  180. return nil;
  181. }
  182. completion:^(id result, NSError *error) {
  183. // ends up being a no-op transaction.
  184. XCTAssertNil(error);
  185. [transactionDone fulfill];
  186. }];
  187. [self awaitExpectations];
  188. }
  189. - (void)testWritesWithInvalidTypesFail {
  190. [self expectWrite:@{
  191. @"foo" : @{@"bar" : self}
  192. }
  193. toFailWithReason:@"Unsupported type: FIRValidationTests (found in field foo.bar)"];
  194. }
  195. - (void)testWritesWithLargeNumbersFail {
  196. NSNumber *num = @((unsigned long long)LONG_MAX + 1);
  197. NSString *reason =
  198. [NSString stringWithFormat:@"NSNumber (%@) is too large (found in field num)", num];
  199. [self expectWrite:@{@"num" : num} toFailWithReason:reason];
  200. }
  201. - (void)testWritesWithReferencesToADifferentDatabaseFail {
  202. FIRDocumentReference *ref =
  203. [[self firestoreWithProjectID:@"different-db"] documentWithPath:@"baz/quu"];
  204. id data = @{@"foo" : ref};
  205. [self expectWrite:data
  206. toFailWithReason:
  207. [NSString
  208. stringWithFormat:@"Document Reference is for database different-db/(default) but "
  209. "should be for database %@/(default) (found in field foo)",
  210. [FSTIntegrationTestCase projectID]]];
  211. }
  212. - (void)testWritesWithReservedFieldsFail {
  213. [self expectWrite:@{
  214. @"__baz__" : @1
  215. }
  216. toFailWithReason:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  217. [self expectWrite:@{
  218. @"foo" : @{@"__baz__" : @1}
  219. }
  220. toFailWithReason:
  221. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  222. [self expectWrite:@{
  223. @"__baz__" : @{@"foo" : @1}
  224. }
  225. toFailWithReason:@"Document fields cannot begin and end with __ (found in field __baz__)"];
  226. [self expectUpdate:@{
  227. @"foo.__baz__" : @1
  228. }
  229. toFailWithReason:
  230. @"Document fields cannot begin and end with __ (found in field foo.__baz__)"];
  231. [self expectUpdate:@{
  232. @"__baz__.foo" : @1
  233. }
  234. toFailWithReason:
  235. @"Document fields cannot begin and end with __ (found in field __baz__.foo)"];
  236. [self expectUpdate:@{
  237. @1 : @1
  238. }
  239. toFailWithReason:@"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths."];
  240. }
  241. - (void)testSetsWithFieldValueDeleteFail {
  242. [self expectSet:@{@"foo" : [FIRFieldValue fieldValueForDelete]}
  243. toFailWithReason:
  244. @"FieldValue.delete() can only be used with updateData() and setData() with "
  245. @"SetOptions.merge()."];
  246. }
  247. - (void)testUpdatesWithNestedFieldValueDeleteFail {
  248. [self expectUpdate:@{
  249. @"foo" : @{@"bar" : [FIRFieldValue fieldValueForDelete]}
  250. }
  251. toFailWithReason:
  252. @"FieldValue.delete() can only appear at the top level of your update data "
  253. "(found in field foo.bar)"];
  254. }
  255. - (void)testBatchWritesWithIncorrectReferencesFail {
  256. FIRFirestore *db1 = [self firestore];
  257. FIRFirestore *db2 = [self firestore];
  258. XCTAssertNotEqual(db1, db2);
  259. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  260. id data = @{ @"foo" : @1 };
  261. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  262. FIRWriteBatch *batch = [db1 batch];
  263. FSTAssertThrows([batch setData:data forDocument:badRef], reason);
  264. FSTAssertThrows([batch setData:data forDocument:badRef options:[FIRSetOptions merge]], reason);
  265. FSTAssertThrows([batch updateData:data forDocument:badRef], reason);
  266. FSTAssertThrows([batch deleteDocument:badRef], reason);
  267. }
  268. - (void)testTransactionWritesWithIncorrectReferencesFail {
  269. FIRFirestore *db1 = [self firestore];
  270. FIRFirestore *db2 = [self firestore];
  271. XCTAssertNotEqual(db1, db2);
  272. NSString *reason = @"Provided document reference is from a different Firestore instance.";
  273. id data = @{ @"foo" : @1 };
  274. FIRDocumentReference *badRef = [db2 documentWithPath:@"foo/bar"];
  275. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  276. [db1 runTransactionWithBlock:^id(FIRTransaction *txn, NSError **pError) {
  277. FSTAssertThrows([txn getDocument:badRef error:nil], reason);
  278. FSTAssertThrows([txn setData:data forDocument:badRef], reason);
  279. FSTAssertThrows([txn setData:data forDocument:badRef options:[FIRSetOptions merge]], reason);
  280. FSTAssertThrows([txn updateData:data forDocument:badRef], reason);
  281. FSTAssertThrows([txn deleteDocument:badRef], reason);
  282. return nil;
  283. }
  284. completion:^(id result, NSError *error) {
  285. // ends up being a no-op transaction.
  286. XCTAssertNil(error);
  287. [transactionDone fulfill];
  288. }];
  289. [self awaitExpectations];
  290. }
  291. #pragma mark - Field Path validation
  292. // TODO(b/37244157): More validation for invalid field paths.
  293. - (void)testFieldPathsWithEmptySegmentsFail {
  294. NSArray *badFieldPaths = @[ @"", @"foo..baz", @".foo", @"foo." ];
  295. for (NSString *fieldPath in badFieldPaths) {
  296. NSString *reason =
  297. [NSString stringWithFormat:
  298. @"Invalid field path (%@). Paths must not be empty, begin with "
  299. @"'.', end with '.', or contain '..'",
  300. fieldPath];
  301. [self expectFieldPath:fieldPath toFailWithReason:reason];
  302. }
  303. }
  304. - (void)testFieldPathsWithInvalidSegmentsFail {
  305. NSArray *badFieldPaths = @[ @"foo~bar", @"foo*bar", @"foo/bar", @"foo[1", @"foo]1", @"foo[1]" ];
  306. for (NSString *fieldPath in badFieldPaths) {
  307. NSString *reason =
  308. [NSString stringWithFormat:
  309. @"Invalid field path (%@). Paths must not contain '~', '*', '/', '[', or ']'",
  310. fieldPath];
  311. [self expectFieldPath:fieldPath toFailWithReason:reason];
  312. }
  313. }
  314. #pragma mark - Query Validation
  315. - (void)testQueryWithNonPositiveLimitFails {
  316. FSTAssertThrows([[self collectionRef] queryLimitedTo:0],
  317. @"Invalid Query. Query limit (0) is invalid. Limit must be positive.");
  318. FSTAssertThrows([[self collectionRef] queryLimitedTo:-1],
  319. @"Invalid Query. Query limit (-1) is invalid. Limit must be positive.");
  320. }
  321. - (void)testQueryInequalityOnNullOrNaNFails {
  322. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:nil],
  323. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  324. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:[NSNull null]],
  325. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  326. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:@(NAN)],
  327. @"Invalid Query. You can only perform equality comparisons on NaN.");
  328. }
  329. - (void)testQueryCannotBeCreatedFromDocumentsMissingSortValues {
  330. FIRCollectionReference *testCollection = [self collectionRefWithDocuments:@{
  331. @"f" : @{@"v" : @"f", @"nosort" : @1.0}
  332. }];
  333. FIRQuery *query = [testCollection queryOrderedByField:@"sort"];
  334. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:[testCollection documentWithPath:@"f"]];
  335. XCTAssertTrue(snapshot.exists);
  336. NSString *reason =
  337. @"Invalid query. You are trying to start or end a query using a document for "
  338. "which the field 'sort' (used as the order by) does not exist.";
  339. FSTAssertThrows([query queryStartingAtDocument:snapshot], reason);
  340. FSTAssertThrows([query queryStartingAfterDocument:snapshot], reason);
  341. FSTAssertThrows([query queryEndingBeforeDocument:snapshot], reason);
  342. FSTAssertThrows([query queryEndingAtDocument:snapshot], reason);
  343. }
  344. - (void)testQueryBoundMustNotHaveMoreComponentsThanSortOrders {
  345. FIRCollectionReference *testCollection = [self collectionRef];
  346. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  347. NSString *reason =
  348. @"Invalid query. You are trying to start or end a query using more values "
  349. "than were specified in the order by.";
  350. // More elements than order by
  351. FSTAssertThrows(([query queryStartingAtValues:@[ @1, @2 ]]), reason);
  352. FSTAssertThrows(([[query queryOrderedByField:@"bar"] queryStartingAtValues:@[ @1, @2, @3 ]]),
  353. reason);
  354. }
  355. - (void)testQueryOrderedByKeyBoundMustBeAStringWithoutSlashes {
  356. FIRCollectionReference *testCollection = [self collectionRef];
  357. FIRQuery *query = [testCollection queryOrderedByFieldPath:[FIRFieldPath documentID]];
  358. FSTAssertThrows([query queryStartingAtValues:@[ @1 ]],
  359. @"Invalid query. Expected a string for the document ID.");
  360. FSTAssertThrows([query queryStartingAtValues:@[ @"foo/bar" ]],
  361. @"Invalid query. Document ID 'foo/bar' contains a slash.");
  362. }
  363. - (void)testQueryMustNotSpecifyStartingOrEndingPointAfterOrder {
  364. FIRCollectionReference *testCollection = [self collectionRef];
  365. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  366. NSString *reason =
  367. @"Invalid query. You must not specify a starting point before specifying the order by.";
  368. FSTAssertThrows([[query queryStartingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  369. FSTAssertThrows([[query queryStartingAfterValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  370. reason = @"Invalid query. You must not specify an ending point before specifying the order by.";
  371. FSTAssertThrows([[query queryEndingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  372. FSTAssertThrows([[query queryEndingBeforeValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  373. }
  374. - (void)testQueriesFilteredByDocumentIDMustUseStringsOrDocumentReferences {
  375. FIRCollectionReference *collection = [self collectionRef];
  376. NSString *reason =
  377. @"Invalid query. When querying by document ID you must provide a valid "
  378. "document ID, but it was an empty string.";
  379. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@""], reason);
  380. reason =
  381. @"Invalid query. When querying by document ID you must provide a valid document ID, "
  382. "but 'foo/bar/baz' contains a '/' character.";
  383. FSTAssertThrows(
  384. [collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@"foo/bar/baz"], reason);
  385. reason =
  386. @"Invalid query. When querying by document ID you must provide a valid string or "
  387. "DocumentReference, but it was of type: __NSCFNumber";
  388. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@1], reason);
  389. }
  390. - (void)testQueryInequalityFieldMustMatchFirstOrderByField {
  391. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  392. FIRQuery *base = [coll queryWhereField:@"x" isGreaterThanOrEqualTo:@32];
  393. FSTAssertThrows([base queryWhereField:@"y" isLessThan:@"cat"],
  394. @"Invalid Query. All where filters with an inequality (lessThan, "
  395. "lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  396. "field. But you have inequality filters on 'x' and 'y'");
  397. NSString *reason =
  398. @"Invalid query. You have a where filter with "
  399. "an inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) "
  400. "on field 'x' and so you must also use 'x' as your first queryOrderedBy field, "
  401. "but your first queryOrderedBy is currently on field 'y' instead.";
  402. FSTAssertThrows([base queryOrderedByField:@"y"], reason);
  403. FSTAssertThrows([[coll queryOrderedByField:@"y"] queryWhereField:@"x" isGreaterThan:@32], reason);
  404. FSTAssertThrows([[base queryOrderedByField:@"y"] queryOrderedByField:@"x"], reason);
  405. FSTAssertThrows([[[coll queryOrderedByField:@"y"] queryOrderedByField:@"x"] queryWhereField:@"x"
  406. isGreaterThan:@32],
  407. reason);
  408. XCTAssertNoThrow([base queryWhereField:@"x" isLessThanOrEqualTo:@"cat"],
  409. @"Same inequality fields work");
  410. XCTAssertNoThrow([base queryWhereField:@"y" isEqualTo:@"cat"],
  411. @"Inequality and equality on different fields works");
  412. XCTAssertNoThrow([base queryOrderedByField:@"x"], @"inequality same as order by works");
  413. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"x" isGreaterThan:@32],
  414. @"inequality same as order by works");
  415. XCTAssertNoThrow([[base queryOrderedByField:@"x"] queryOrderedByField:@"y"],
  416. @"inequality same as first order by works.");
  417. XCTAssertNoThrow([[[coll queryOrderedByField:@"x"] queryOrderedByField:@"y"] queryWhereField:@"x"
  418. isGreaterThan:@32],
  419. @"inequality same as first order by works.");
  420. }
  421. #pragma mark - GeoPoint Validation
  422. - (void)testInvalidGeoPointParameters {
  423. [self verifyExceptionForInvalidLatitude:NAN];
  424. [self verifyExceptionForInvalidLatitude:-INFINITY];
  425. [self verifyExceptionForInvalidLatitude:INFINITY];
  426. [self verifyExceptionForInvalidLatitude:-90.1];
  427. [self verifyExceptionForInvalidLatitude:90.1];
  428. [self verifyExceptionForInvalidLongitude:NAN];
  429. [self verifyExceptionForInvalidLongitude:-INFINITY];
  430. [self verifyExceptionForInvalidLongitude:INFINITY];
  431. [self verifyExceptionForInvalidLongitude:-180.1];
  432. [self verifyExceptionForInvalidLongitude:180.1];
  433. }
  434. #pragma mark - Helpers
  435. /** Performs a write using each write API and makes sure it fails with the expected reason. */
  436. - (void)expectWrite:(id)data toFailWithReason:(NSString *)reason {
  437. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:YES];
  438. }
  439. /** Performs a write using each set API and makes sure it fails with the expected reason. */
  440. - (void)expectSet:(id)data toFailWithReason:(NSString *)reason {
  441. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:NO];
  442. }
  443. /** Performs a write using each update API and makes sure it fails with the expected reason. */
  444. - (void)expectUpdate:(id)data toFailWithReason:(NSString *)reason {
  445. [self expectWrite:data toFailWithReason:reason includeSets:NO includeUpdates:YES];
  446. }
  447. /**
  448. * Performs a write using each set and/or update API and makes sure it fails with the expected
  449. * reason.
  450. */
  451. - (void)expectWrite:(id)data
  452. toFailWithReason:(NSString *)reason
  453. includeSets:(BOOL)includeSets
  454. includeUpdates:(BOOL)includeUpdates {
  455. FIRDocumentReference *ref = [self documentRef];
  456. if (includeSets) {
  457. FSTAssertThrows([ref setData:data], reason, @"for %@", data);
  458. FSTAssertThrows([[ref.firestore batch] setData:data forDocument:ref], reason, @"for %@", data);
  459. }
  460. if (includeUpdates) {
  461. FSTAssertThrows([ref updateData:data], reason, @"for %@", data);
  462. FSTAssertThrows([[ref.firestore batch] updateData:data forDocument:ref], reason, @"for %@",
  463. data);
  464. }
  465. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  466. [ref.firestore runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  467. if (includeSets) {
  468. FSTAssertThrows([transaction setData:data forDocument:ref], reason, @"for %@", data);
  469. }
  470. if (includeUpdates) {
  471. FSTAssertThrows([transaction updateData:data forDocument:ref], reason, @"for %@", data);
  472. }
  473. return nil;
  474. }
  475. completion:^(id result, NSError *error) {
  476. // ends up being a no-op transaction.
  477. XCTAssertNil(error);
  478. [transactionDone fulfill];
  479. }];
  480. [self awaitExpectations];
  481. }
  482. - (void)testFieldNamesMustNotBeEmpty {
  483. NSString *reason = @"Invalid field path. Provided names must not be empty.";
  484. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[]], reason);
  485. reason = @"Invalid field name at index 0. Field names must not be empty.";
  486. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[ @"" ]], reason);
  487. reason = @"Invalid field name at index 1. Field names must not be empty.";
  488. FSTAssertThrows(([[FIRFieldPath alloc] initWithFields:@[ @"foo", @"" ]]), reason);
  489. }
  490. /**
  491. * Tests a field path with all of our APIs that accept field paths and ensures they fail with the
  492. * specified reason.
  493. */
  494. - (void)expectFieldPath:(NSString *)fieldPath toFailWithReason:(NSString *)reason {
  495. // Get an arbitrary snapshot we can use for testing.
  496. FIRDocumentReference *docRef = [self documentRef];
  497. [self writeDocumentRef:docRef data:@{ @"test" : @1 }];
  498. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:docRef];
  499. // Update paths.
  500. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  501. dict[fieldPath] = @1;
  502. [self expectUpdate:dict toFailWithReason:reason];
  503. // Snapshot fields.
  504. FSTAssertThrows(snapshot[fieldPath], reason);
  505. // Query filter / order fields.
  506. FIRCollectionReference *collection = [self collectionRef];
  507. FSTAssertThrows([collection queryWhereField:fieldPath isEqualTo:@1], reason);
  508. // isLessThan, etc. omitted for brevity since the code path is trivially shared.
  509. FSTAssertThrows([collection queryOrderedByField:fieldPath], reason);
  510. }
  511. - (void)verifyExceptionForInvalidLatitude:(double)latitude {
  512. NSString *reason = [NSString
  513. stringWithFormat:@"GeoPoint requires a latitude value in the range of [-90, 90], but was %f",
  514. latitude];
  515. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:latitude longitude:0], reason);
  516. }
  517. - (void)verifyExceptionForInvalidLongitude:(double)longitude {
  518. NSString *reason =
  519. [NSString stringWithFormat:
  520. @"GeoPoint requires a longitude value in the range of [-180, 180], but was %f",
  521. longitude];
  522. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:0 longitude:longitude], reason);
  523. }
  524. @end