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