FIRValidationTests.mm 29 KB

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