FIRValidationTests.mm 29 KB

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