FIRValidationTests.mm 32 KB

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