FIRValidationTests.mm 28 KB

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