FIRValidationTests.mm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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([self.db
  64. 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
  178. 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
  279. runTransactionWithBlock:^id(FIRTransaction *txn, NSError **pError) {
  280. FSTAssertThrows([txn getDocument:badRef error:nil], reason);
  281. FSTAssertThrows([txn setData:data forDocument:badRef], reason);
  282. FSTAssertThrows([txn setData:data forDocument:badRef merge:YES], reason);
  283. FSTAssertThrows([txn updateData:data forDocument:badRef], reason);
  284. FSTAssertThrows([txn deleteDocument:badRef], reason);
  285. return nil;
  286. }
  287. completion:^(id result, NSError *error) {
  288. // ends up being a no-op transaction.
  289. XCTAssertNil(error);
  290. [transactionDone fulfill];
  291. }];
  292. [self awaitExpectations];
  293. }
  294. #pragma mark - Field Path validation
  295. // TODO(b/37244157): More validation for invalid field paths.
  296. - (void)testFieldPathsWithEmptySegmentsFail {
  297. NSArray *badFieldPaths = @[ @"", @"foo..baz", @".foo", @"foo." ];
  298. for (NSString *fieldPath in badFieldPaths) {
  299. NSString *reason =
  300. [NSString stringWithFormat:
  301. @"Invalid field path (%@). Paths must not be empty, begin with "
  302. @"'.', end with '.', or contain '..'",
  303. fieldPath];
  304. [self expectFieldPath:fieldPath toFailWithReason:reason];
  305. }
  306. }
  307. - (void)testFieldPathsWithInvalidSegmentsFail {
  308. NSArray *badFieldPaths = @[ @"foo~bar", @"foo*bar", @"foo/bar", @"foo[1", @"foo]1", @"foo[1]" ];
  309. for (NSString *fieldPath in badFieldPaths) {
  310. NSString *reason =
  311. [NSString stringWithFormat:
  312. @"Invalid field path (%@). Paths must not contain '~', '*', '/', '[', or ']'",
  313. fieldPath];
  314. [self expectFieldPath:fieldPath toFailWithReason:reason];
  315. }
  316. }
  317. #pragma mark - ArrayUnion / ArrayRemove Validation
  318. - (void)testArrayTransformsInQueriesFail {
  319. FSTAssertThrows(
  320. [[self collectionRef] queryWhereField:@"test"
  321. isEqualTo:@{
  322. @"test" : [FIRFieldValue fieldValueForArrayUnion:@[ @1 ]]
  323. }],
  324. @"FieldValue.arrayUnion() can only be used with updateData() and setData() (found in field "
  325. "test)");
  326. FSTAssertThrows(
  327. [[self collectionRef] queryWhereField:@"test"
  328. isEqualTo:@{
  329. @"test" : [FIRFieldValue fieldValueForArrayRemove:@[ @1 ]]
  330. }],
  331. @"FieldValue.arrayRemove() can only be used with updateData() and setData() (found in field "
  332. @"test)");
  333. }
  334. - (void)testInvalidArrayTransformElementFails {
  335. [self expectWrite:@{
  336. @"foo" : [FIRFieldValue fieldValueForArrayUnion:@[ @1, self ]]
  337. }
  338. toFailWithReason:@"Unsupported type: FIRValidationTests"];
  339. [self expectWrite:@{
  340. @"foo" : [FIRFieldValue fieldValueForArrayRemove:@[ @1, self ]]
  341. }
  342. toFailWithReason:@"Unsupported type: FIRValidationTests"];
  343. }
  344. - (void)testArraysInArrayTransformsFail {
  345. // This would result in a directly nested array which is not supported.
  346. [self expectWrite:@{
  347. @"foo" : [FIRFieldValue fieldValueForArrayUnion:@[ @1, @[ @"nested" ] ]]
  348. }
  349. toFailWithReason:@"Nested arrays are not supported"];
  350. [self expectWrite:@{
  351. @"foo" : [FIRFieldValue fieldValueForArrayRemove:@[ @1, @[ @"nested" ] ]]
  352. }
  353. toFailWithReason:@"Nested arrays are not supported"];
  354. }
  355. #pragma mark - Query Validation
  356. - (void)testQueryWithNonPositiveLimitFails {
  357. FSTAssertThrows([[self collectionRef] queryLimitedTo:0],
  358. @"Invalid Query. Query limit (0) is invalid. Limit must be positive.");
  359. FSTAssertThrows([[self collectionRef] queryLimitedTo:-1],
  360. @"Invalid Query. Query limit (-1) is invalid. Limit must be positive.");
  361. }
  362. - (void)testNonEqualityQueriesOnNullOrNaNFail {
  363. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:nil],
  364. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  365. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:[NSNull null]],
  366. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  367. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:nil],
  368. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  369. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:[NSNull null]],
  370. @"Invalid Query. You can only perform equality comparisons on nil / NSNull.");
  371. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" isGreaterThan:@(NAN)],
  372. @"Invalid Query. You can only perform equality comparisons on NaN.");
  373. FSTAssertThrows([[self collectionRef] queryWhereField:@"a" arrayContains:@(NAN)],
  374. @"Invalid Query. You can only perform equality comparisons on NaN.");
  375. }
  376. - (void)testQueryCannotBeCreatedFromDocumentsMissingSortValues {
  377. FIRCollectionReference *testCollection = [self collectionRefWithDocuments:@{
  378. @"f" : @{@"v" : @"f", @"nosort" : @1.0}
  379. }];
  380. FIRQuery *query = [testCollection queryOrderedByField:@"sort"];
  381. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:[testCollection documentWithPath:@"f"]];
  382. XCTAssertTrue(snapshot.exists);
  383. NSString *reason =
  384. @"Invalid query. You are trying to start or end a query using a document for "
  385. "which the field 'sort' (used as the order by) does not exist.";
  386. FSTAssertThrows([query queryStartingAtDocument:snapshot], reason);
  387. FSTAssertThrows([query queryStartingAfterDocument:snapshot], reason);
  388. FSTAssertThrows([query queryEndingBeforeDocument:snapshot], reason);
  389. FSTAssertThrows([query queryEndingAtDocument:snapshot], reason);
  390. }
  391. - (void)testQueryBoundMustNotHaveMoreComponentsThanSortOrders {
  392. FIRCollectionReference *testCollection = [self collectionRef];
  393. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  394. NSString *reason =
  395. @"Invalid query. You are trying to start or end a query using more values "
  396. "than were specified in the order by.";
  397. // More elements than order by
  398. FSTAssertThrows(([query queryStartingAtValues:@[ @1, @2 ]]), reason);
  399. FSTAssertThrows(([[query queryOrderedByField:@"bar"] queryStartingAtValues:@[ @1, @2, @3 ]]),
  400. reason);
  401. }
  402. - (void)testQueryOrderedByKeyBoundMustBeAStringWithoutSlashes {
  403. FIRCollectionReference *testCollection = [self collectionRef];
  404. FIRQuery *query = [testCollection queryOrderedByFieldPath:[FIRFieldPath documentID]];
  405. FSTAssertThrows([query queryStartingAtValues:@[ @1 ]],
  406. @"Invalid query. Expected a string for the document ID.");
  407. FSTAssertThrows([query queryStartingAtValues:@[ @"foo/bar" ]],
  408. @"Invalid query. Document ID 'foo/bar' contains a slash.");
  409. }
  410. - (void)testQueryMustNotSpecifyStartingOrEndingPointAfterOrder {
  411. FIRCollectionReference *testCollection = [self collectionRef];
  412. FIRQuery *query = [testCollection queryOrderedByField:@"foo"];
  413. NSString *reason =
  414. @"Invalid query. You must not specify a starting point before specifying the order by.";
  415. FSTAssertThrows([[query queryStartingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  416. FSTAssertThrows([[query queryStartingAfterValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  417. reason = @"Invalid query. You must not specify an ending point before specifying the order by.";
  418. FSTAssertThrows([[query queryEndingAtValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  419. FSTAssertThrows([[query queryEndingBeforeValues:@[ @1 ]] queryOrderedByField:@"bar"], reason);
  420. }
  421. - (void)testQueriesFilteredByDocumentIDMustUseStringsOrDocumentReferences {
  422. FIRCollectionReference *collection = [self collectionRef];
  423. NSString *reason =
  424. @"Invalid query. When querying by document ID you must provide a valid "
  425. "document ID, but it was an empty string.";
  426. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@""], reason);
  427. reason =
  428. @"Invalid query. When querying by document ID you must provide a valid document ID, "
  429. "but 'foo/bar/baz' contains a '/' character.";
  430. FSTAssertThrows(
  431. [collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@"foo/bar/baz"], reason);
  432. reason =
  433. @"Invalid query. When querying by document ID you must provide a valid string or "
  434. "DocumentReference, but it was of type: __NSCFNumber";
  435. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] isEqualTo:@1], reason);
  436. reason =
  437. @"Invalid query. You can't perform arrayContains queries on document ID since document IDs "
  438. "are not arrays.";
  439. FSTAssertThrows([collection queryWhereFieldPath:[FIRFieldPath documentID] arrayContains:@1],
  440. reason);
  441. }
  442. - (void)testQueryInequalityFieldMustMatchFirstOrderByField {
  443. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  444. FIRQuery *base = [coll queryWhereField:@"x" isGreaterThanOrEqualTo:@32];
  445. FSTAssertThrows([base queryWhereField:@"y" isLessThan:@"cat"],
  446. @"Invalid Query. All where filters with an inequality (lessThan, "
  447. "lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  448. "field. But you have inequality filters on 'x' and 'y'");
  449. NSString *reason =
  450. @"Invalid query. You have a where filter with "
  451. "an inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) "
  452. "on field 'x' and so you must also use 'x' as your first queryOrderedBy field, "
  453. "but your first queryOrderedBy is currently on field 'y' instead.";
  454. FSTAssertThrows([base queryOrderedByField:@"y"], reason);
  455. FSTAssertThrows([[coll queryOrderedByField:@"y"] queryWhereField:@"x" isGreaterThan:@32], reason);
  456. FSTAssertThrows([[base queryOrderedByField:@"y"] queryOrderedByField:@"x"], reason);
  457. FSTAssertThrows([[[coll queryOrderedByField:@"y"] queryOrderedByField:@"x"] queryWhereField:@"x"
  458. isGreaterThan:@32],
  459. reason);
  460. XCTAssertNoThrow([base queryWhereField:@"x" isLessThanOrEqualTo:@"cat"],
  461. @"Same inequality fields work");
  462. XCTAssertNoThrow([base queryWhereField:@"y" isEqualTo:@"cat"],
  463. @"Inequality and equality on different fields works");
  464. XCTAssertNoThrow([base queryWhereField:@"y" arrayContains:@"cat"],
  465. @"Inequality and array_contains on different fields works");
  466. XCTAssertNoThrow([base queryOrderedByField:@"x"], @"inequality same as order by works");
  467. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"x" isGreaterThan:@32],
  468. @"inequality same as order by works");
  469. XCTAssertNoThrow([[base queryOrderedByField:@"x"] queryOrderedByField:@"y"],
  470. @"inequality same as first order by works.");
  471. XCTAssertNoThrow([[[coll queryOrderedByField:@"x"] queryOrderedByField:@"y"] queryWhereField:@"x"
  472. isGreaterThan:@32],
  473. @"inequality same as first order by works.");
  474. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" isEqualTo:@"cat"],
  475. @"equality different than orderBy works.");
  476. XCTAssertNoThrow([[coll queryOrderedByField:@"x"] queryWhereField:@"y" arrayContains:@"cat"],
  477. @"array_contains different than orderBy works.");
  478. }
  479. - (void)testQueryMustNotHaveMultipleArrayContainsFilters {
  480. FIRCollectionReference *coll = [self.db collectionWithPath:@"collection"];
  481. FSTAssertThrows(
  482. [[coll queryWhereField:@"foo" arrayContains:@1] queryWhereField:@"foo" arrayContains:@2],
  483. @"Invalid Query. Queries only support a single arrayContains filter.");
  484. }
  485. #pragma mark - GeoPoint Validation
  486. - (void)testInvalidGeoPointParameters {
  487. [self verifyExceptionForInvalidLatitude:NAN];
  488. [self verifyExceptionForInvalidLatitude:-INFINITY];
  489. [self verifyExceptionForInvalidLatitude:INFINITY];
  490. [self verifyExceptionForInvalidLatitude:-90.1];
  491. [self verifyExceptionForInvalidLatitude:90.1];
  492. [self verifyExceptionForInvalidLongitude:NAN];
  493. [self verifyExceptionForInvalidLongitude:-INFINITY];
  494. [self verifyExceptionForInvalidLongitude:INFINITY];
  495. [self verifyExceptionForInvalidLongitude:-180.1];
  496. [self verifyExceptionForInvalidLongitude:180.1];
  497. }
  498. #pragma mark - Helpers
  499. /** Performs a write using each write API and makes sure it fails with the expected reason. */
  500. - (void)expectWrite:(id)data toFailWithReason:(NSString *)reason {
  501. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:YES];
  502. }
  503. /** Performs a write using each set API and makes sure it fails with the expected reason. */
  504. - (void)expectSet:(id)data toFailWithReason:(NSString *)reason {
  505. [self expectWrite:data toFailWithReason:reason includeSets:YES includeUpdates:NO];
  506. }
  507. /** Performs a write using each update API and makes sure it fails with the expected reason. */
  508. - (void)expectUpdate:(id)data toFailWithReason:(NSString *)reason {
  509. [self expectWrite:data toFailWithReason:reason includeSets:NO includeUpdates:YES];
  510. }
  511. /**
  512. * Performs a write using each set and/or update API and makes sure it fails with the expected
  513. * reason.
  514. */
  515. - (void)expectWrite:(id)data
  516. toFailWithReason:(NSString *)reason
  517. includeSets:(BOOL)includeSets
  518. includeUpdates:(BOOL)includeUpdates {
  519. FIRDocumentReference *ref = [self documentRef];
  520. if (includeSets) {
  521. FSTAssertThrows([ref setData:data], reason, @"for %@", data);
  522. FSTAssertThrows([[ref.firestore batch] setData:data forDocument:ref], reason, @"for %@", data);
  523. }
  524. if (includeUpdates) {
  525. FSTAssertThrows([ref updateData:data], reason, @"for %@", data);
  526. FSTAssertThrows([[ref.firestore batch] updateData:data forDocument:ref], reason, @"for %@",
  527. data);
  528. }
  529. XCTestExpectation *transactionDone = [self expectationWithDescription:@"transaction done"];
  530. [ref.firestore
  531. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  532. if (includeSets) {
  533. FSTAssertThrows([transaction setData:data forDocument:ref], reason, @"for %@", data);
  534. }
  535. if (includeUpdates) {
  536. FSTAssertThrows([transaction updateData:data forDocument:ref], reason, @"for %@", data);
  537. }
  538. return nil;
  539. }
  540. completion:^(id result, NSError *error) {
  541. // ends up being a no-op transaction.
  542. XCTAssertNil(error);
  543. [transactionDone fulfill];
  544. }];
  545. [self awaitExpectations];
  546. }
  547. - (void)testFieldNamesMustNotBeEmpty {
  548. NSString *reason = @"Invalid field path. Provided names must not be empty.";
  549. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[]], reason);
  550. reason = @"Invalid field name at index 0. Field names must not be empty.";
  551. FSTAssertThrows([[FIRFieldPath alloc] initWithFields:@[ @"" ]], reason);
  552. reason = @"Invalid field name at index 1. Field names must not be empty.";
  553. FSTAssertThrows(([[FIRFieldPath alloc] initWithFields:@[ @"foo", @"" ]]), reason);
  554. }
  555. /**
  556. * Tests a field path with all of our APIs that accept field paths and ensures they fail with the
  557. * specified reason.
  558. */
  559. - (void)expectFieldPath:(NSString *)fieldPath toFailWithReason:(NSString *)reason {
  560. // Get an arbitrary snapshot we can use for testing.
  561. FIRDocumentReference *docRef = [self documentRef];
  562. [self writeDocumentRef:docRef data:@{@"test" : @1}];
  563. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:docRef];
  564. // Update paths.
  565. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  566. dict[fieldPath] = @1;
  567. [self expectUpdate:dict toFailWithReason:reason];
  568. // Snapshot fields.
  569. FSTAssertThrows(snapshot[fieldPath], reason);
  570. // Query filter / order fields.
  571. FIRCollectionReference *collection = [self collectionRef];
  572. FSTAssertThrows([collection queryWhereField:fieldPath isEqualTo:@1], reason);
  573. // isLessThan, etc. omitted for brevity since the code path is trivially shared.
  574. FSTAssertThrows([collection queryOrderedByField:fieldPath], reason);
  575. }
  576. - (void)verifyExceptionForInvalidLatitude:(double)latitude {
  577. NSString *reason = [NSString
  578. stringWithFormat:@"GeoPoint requires a latitude value in the range of [-90, 90], but was %f",
  579. latitude];
  580. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:latitude longitude:0], reason);
  581. }
  582. - (void)verifyExceptionForInvalidLongitude:(double)longitude {
  583. NSString *reason =
  584. [NSString stringWithFormat:
  585. @"GeoPoint requires a longitude value in the range of [-180, 180], but was %f",
  586. longitude];
  587. FSTAssertThrows([[FIRGeoPoint alloc] initWithLatitude:0 longitude:longitude], reason);
  588. }
  589. @end