FIRValidationTests.mm 32 KB

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