FIRStorageIntegrationTests.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import <XCTest/XCTest.h>
  15. #import "FirebaseStorage/Sources/Public/FirebaseStorage/FirebaseStorage.h"
  16. #import <FirebaseAuth/FirebaseAuth.h>
  17. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  18. #import "FirebaseStorage/Tests/Integration/Credentials.h"
  19. NSTimeInterval kFIRStorageIntegrationTestTimeout = 60;
  20. /**
  21. * Firebase Storage Integration tests
  22. *
  23. * To run these tests, you need to define the following access rights:
  24. *
  25. rules_version = '2';
  26. service firebase.storage {
  27. match /b/{bucket}/o {
  28. match /{directChild=*} {
  29. allow read: if request.auth != null;
  30. }
  31. match /ios {
  32. match /public/{allPaths=**} {
  33. allow write: if request.auth != null;
  34. allow read: if true;
  35. }
  36. match /private/{allPaths=**} {
  37. allow read, write: if false;
  38. }
  39. }
  40. }
  41. }
  42. *
  43. * You also need to enable email/password sign in and add a test user in your
  44. * Firebase Authentication settings. Your account credentials need to match
  45. * the credentials defined in `kTestUser` and `kTestPassword`.
  46. *
  47. * You can define these access rights in the Firebase Console of your project.
  48. */
  49. NSString *const kTestUser = KUSER_NAME;
  50. NSString *const kTestPassword = KPASSWORD;
  51. @interface FIRStorageIntegrationTests : XCTestCase
  52. @property(strong, nonatomic) FIRApp *app;
  53. @property(strong, nonatomic) FIRAuth *auth;
  54. @property(strong, nonatomic) FIRStorage *storage;
  55. @end
  56. @implementation FIRStorageIntegrationTests
  57. + (void)setUp {
  58. [FIRApp configure];
  59. }
  60. - (void)setUp {
  61. [super setUp];
  62. self.app = [FIRApp defaultApp];
  63. self.auth = [FIRAuth authWithApp:self.app];
  64. self.storage = [FIRStorage storageForApp:self.app];
  65. static dispatch_once_t once;
  66. dispatch_once(&once, ^{
  67. XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
  68. [self.auth signInWithEmail:kTestUser
  69. password:kTestPassword
  70. completion:^(FIRAuthDataResult *result, NSError *error) {
  71. XCTAssertNil(error);
  72. [signInExpectation fulfill];
  73. }];
  74. [self waitForExpectations];
  75. XCTestExpectation *setUpExpectation = [self expectationWithDescription:@"setUp"];
  76. NSArray<NSString *> *largeFiles = @[ @"ios/public/1mb" ];
  77. NSArray<NSString *> *emptyFiles = @[
  78. @"ios/public/empty", @"ios/public/list/a", @"ios/public/list/b", @"ios/public/list/prefix/c"
  79. ];
  80. setUpExpectation.expectedFulfillmentCount = largeFiles.count + emptyFiles.count;
  81. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"1mb" ofType:@"dat"];
  82. if (filePath == nil) {
  83. // Use bundleForClass to allow 1mb.dat to be in the test target's bundle.
  84. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  85. filePath = [bundle pathForResource:@"1mb" ofType:@"dat"];
  86. }
  87. NSData *data = [NSData dataWithContentsOfFile:filePath];
  88. XCTAssertNotNil(data, "Could not load bundled file");
  89. for (NSString *largeFile in largeFiles) {
  90. FIRStorageReference *file = [[FIRStorage storage].reference child:largeFile];
  91. [file putData:data
  92. metadata:nil
  93. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  94. XCTAssertNil(error);
  95. [setUpExpectation fulfill];
  96. }];
  97. }
  98. for (NSString *emptyFile in emptyFiles) {
  99. FIRStorageReference *file = [[FIRStorage storage].reference child:emptyFile];
  100. [file putData:[NSData data]
  101. metadata:nil
  102. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  103. XCTAssertNil(error);
  104. [setUpExpectation fulfill];
  105. }];
  106. }
  107. [self waitForExpectations];
  108. });
  109. }
  110. - (void)tearDown {
  111. self.app = nil;
  112. self.storage = nil;
  113. [super tearDown];
  114. }
  115. - (void)testSameInstanceNoBucket {
  116. FIRStorage *storage1 = [FIRStorage storageForApp:self.app];
  117. FIRStorage *storage2 = [FIRStorage storageForApp:self.app];
  118. XCTAssertEqual(storage1, storage2);
  119. }
  120. - (void)testSameInstanceCustomBucket {
  121. FIRStorage *storage1 = [FIRStorage storageForApp:self.app URL:@"gs://foo-bar.appspot.com"];
  122. FIRStorage *storage2 = [FIRStorage storageForApp:self.app URL:@"gs://foo-bar.appspot.com"];
  123. XCTAssertEqual(storage1, storage2);
  124. }
  125. - (void)testDiffferentInstance {
  126. FIRStorage *storage1 = [FIRStorage storageForApp:self.app];
  127. FIRStorage *storage2 = [FIRStorage storageForApp:self.app URL:@"gs://foo-bar.appspot.com"];
  128. XCTAssertNotEqual(storage1, storage2);
  129. }
  130. - (void)testName {
  131. NSString *aGSURI = [NSString
  132. stringWithFormat:@"gs://%@.appspot.com/path/to", [[FIRApp defaultApp] options].projectID];
  133. FIRStorageReference *ref = [self.storage referenceForURL:aGSURI];
  134. XCTAssertEqualObjects(ref.description, aGSURI);
  135. }
  136. - (void)testGetMetadata {
  137. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetMetadata"];
  138. FIRStorageReference *ref = [self.storage.reference child:@"ios/public/1mb"];
  139. [ref metadataWithCompletion:^(FIRStorageMetadata *metadata, NSError *error) {
  140. XCTAssertNotNil(metadata, "Metadata should not be nil");
  141. XCTAssertNil(error, "Error should be nil");
  142. [expectation fulfill];
  143. }];
  144. [self waitForExpectations];
  145. }
  146. - (void)testDelete {
  147. XCTestExpectation *expectation = [self expectationWithDescription:@"testDelete"];
  148. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/fileToDelete"];
  149. NSData *data = [@"Delete me!!!!!!!" dataUsingEncoding:NSUTF8StringEncoding];
  150. [ref putData:data
  151. metadata:nil
  152. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  153. XCTAssertNotNil(metadata, "Metadata should not be nil");
  154. XCTAssertNil(error, "Error should be nil");
  155. [ref deleteWithCompletion:^(NSError *error) {
  156. XCTAssertNil(error, "Error should be nil");
  157. [expectation fulfill];
  158. }];
  159. }];
  160. [self waitForExpectations];
  161. }
  162. - (void)testDeleteWithNilCompletion {
  163. XCTestExpectation *expectation = [self expectationWithDescription:@"testDeleteWithNilCompletion"];
  164. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/fileToDelete"];
  165. NSData *data = [@"Delete me!!!!!!!" dataUsingEncoding:NSUTF8StringEncoding];
  166. [ref putData:data
  167. metadata:nil
  168. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  169. XCTAssertNotNil(metadata, "Metadata should not be nil");
  170. XCTAssertNil(error, "Error should be nil");
  171. [ref deleteWithCompletion:nil];
  172. [expectation fulfill];
  173. }];
  174. [self waitForExpectations];
  175. }
  176. - (void)testPutDataSpecialCharacter {
  177. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutDataSpecialCharacter"];
  178. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/-._~!$'()*,=:@&+;"];
  179. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  180. [ref putData:data
  181. metadata:nil
  182. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  183. XCTAssertNotNil(metadata, "Metadata should not be nil");
  184. XCTAssertNil(error, "Error should be nil");
  185. [expectation fulfill];
  186. }];
  187. [self waitForExpectations];
  188. }
  189. - (void)testPutDataInBackgroundQueue {
  190. XCTestExpectation *expectation =
  191. [self expectationWithDescription:@"testPutDataInBackgroundQueue"];
  192. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/testBytesUpload"];
  193. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  194. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  195. [ref putData:data
  196. metadata:nil
  197. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  198. XCTAssertNotNil(metadata, "Metadata should not be nil");
  199. XCTAssertNil(error, "Error should be nil");
  200. [expectation fulfill];
  201. }];
  202. });
  203. [self waitForExpectations];
  204. }
  205. - (void)testPutDataWithEmptyData {
  206. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutDataWithEmptyData"];
  207. FIRStorageReference *ref =
  208. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutEmptyData"];
  209. NSData *data = [[NSData alloc] init];
  210. [ref putData:data
  211. metadata:nil
  212. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  213. XCTAssertNotNil(metadata, "Metadata should not be nil");
  214. XCTAssertNil(error, "Error should be nil");
  215. [expectation fulfill];
  216. }];
  217. [self waitForExpectations];
  218. }
  219. - (void)testPutData {
  220. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutData"];
  221. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/private/secretfile.txt"];
  222. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  223. [ref putData:data
  224. metadata:nil
  225. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  226. XCTAssertNil(metadata, "Metadata should be nil");
  227. XCTAssertNotNil(error, "Error should not be nil");
  228. XCTAssertEqual(error.code, FIRStorageErrorCodeUnauthorized);
  229. [expectation fulfill];
  230. }];
  231. [self waitForExpectations];
  232. }
  233. - (void)testPutFile {
  234. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutFile"];
  235. FIRStorageReference *ref =
  236. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutFile"];
  237. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  238. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  239. NSURL *fileURL =
  240. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  241. [data writeToURL:fileURL atomically:YES];
  242. FIRStorageUploadTask *task = [ref putFile:fileURL
  243. metadata:nil
  244. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  245. XCTAssertNotNil(metadata, "Metadata should not be nil");
  246. XCTAssertNil(error, "Error should be nil");
  247. }];
  248. __block long uploadedBytes = -1;
  249. [task observeStatus:FIRStorageTaskStatusSuccess
  250. handler:^(FIRStorageTaskSnapshot *snapshot) {
  251. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  252. [expectation fulfill];
  253. }];
  254. [task observeStatus:FIRStorageTaskStatusProgress
  255. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  256. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  257. [[snapshot description] containsString:@"State: Resume"]);
  258. NSProgress *progress = snapshot.progress;
  259. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, uploadedBytes);
  260. uploadedBytes = (long)progress.completedUnitCount;
  261. }];
  262. [self waitForExpectations];
  263. }
  264. - (void)testPutFileWithSpecialCharacters {
  265. XCTestExpectation *expectation =
  266. [self expectationWithDescription:@"testPutFileWithSpecialCharacters"];
  267. NSString *fileName = @"hello&+@_ .txt";
  268. FIRStorageReference *ref =
  269. [self.storage referenceWithPath:[@"ios/public/" stringByAppendingString:fileName]];
  270. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  271. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  272. NSURL *fileURL = [tmpDirURL URLByAppendingPathComponent:fileName];
  273. [data writeToURL:fileURL atomically:YES];
  274. [ref putFile:fileURL
  275. metadata:nil
  276. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  277. XCTAssertNotNil(metadata, "Metadata should not be nil");
  278. XCTAssertNil(error, "Error should be nil");
  279. XCTAssertEqualObjects(fileName, metadata.name);
  280. FIRStorageReference *download =
  281. [self.storage referenceWithPath:[@"ios/public/" stringByAppendingString:fileName]];
  282. [download metadataWithCompletion:^(FIRStorageMetadata *metadata, NSError *error) {
  283. XCTAssertNotNil(metadata, "Metadata should not be nil");
  284. XCTAssertNil(error, "Error should be nil");
  285. XCTAssertEqualObjects(fileName, metadata.name);
  286. [expectation fulfill];
  287. }];
  288. }];
  289. [self waitForExpectations];
  290. }
  291. - (void)testPutDataNoMetadata {
  292. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutDataNoMetadata"];
  293. FIRStorageReference *ref =
  294. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutDataNoMetadata"];
  295. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  296. [ref putData:data
  297. metadata:nil
  298. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  299. XCTAssertNotNil(metadata, "Metadata should not be nil");
  300. XCTAssertNil(error, "Error should be nil");
  301. [expectation fulfill];
  302. }];
  303. [self waitForExpectations];
  304. }
  305. - (void)testPutFileNoMetadata {
  306. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutFileNoMetadata"];
  307. FIRStorageReference *ref =
  308. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutFileNoMetadata"];
  309. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  310. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  311. NSURL *fileURL =
  312. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  313. [data writeToURL:fileURL atomically:YES];
  314. [ref putFile:fileURL
  315. metadata:nil
  316. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  317. XCTAssertNotNil(metadata, "Metadata should not be nil");
  318. XCTAssertNil(error, "Error should be nil");
  319. [expectation fulfill];
  320. }];
  321. [self waitForExpectations];
  322. }
  323. - (void)testGetData {
  324. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetData"];
  325. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  326. [ref dataWithMaxSize:1 * 1024 * 1024
  327. completion:^(NSData *data, NSError *error) {
  328. XCTAssertNotNil(data, "Data should not be nil");
  329. XCTAssertNil(error, "Error should be nil");
  330. [expectation fulfill];
  331. }];
  332. [self waitForExpectations];
  333. }
  334. - (void)testGetDataInBackgroundQueue {
  335. XCTestExpectation *expectation =
  336. [self expectationWithDescription:@"testGetDataInBackgroundQueue"];
  337. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  338. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  339. [ref dataWithMaxSize:1 * 1024 * 1024
  340. completion:^(NSData *data, NSError *error) {
  341. XCTAssertNotNil(data, "Data should not be nil");
  342. XCTAssertNil(error, "Error should be nil");
  343. [expectation fulfill];
  344. }];
  345. });
  346. [self waitForExpectations];
  347. }
  348. - (void)testGetDataWithCustomCallbackQueue {
  349. XCTestExpectation *expectation =
  350. [self expectationWithDescription:@"testUnauthenticatedGetDataInCustomCallbackQueue"];
  351. NSString *callbackQueueLabelString = @"customCallbackQueue";
  352. const char *callbackQueueLabel = [callbackQueueLabelString UTF8String];
  353. const void *callbackQueueKey = callbackQueueLabel;
  354. dispatch_queue_t callbackQueue = dispatch_queue_create(callbackQueueLabel, NULL);
  355. dispatch_queue_set_specific(callbackQueue, callbackQueueKey, (void *)callbackQueueKey, NULL);
  356. _storage.callbackQueue = callbackQueue;
  357. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  358. [ref dataWithMaxSize:1 * 1024 * 1024
  359. completion:^(NSData *data, NSError *error) {
  360. XCTAssertNotNil(data, "Data should not be nil");
  361. XCTAssertNil(error, "Error should be nil");
  362. char *currentQueueLabel = dispatch_get_specific(callbackQueueKey);
  363. NSString *currentQueueLabelString = [NSString stringWithUTF8String:currentQueueLabel];
  364. XCTAssertEqualObjects(currentQueueLabelString, callbackQueueLabelString);
  365. [expectation fulfill];
  366. // Reset the callbackQueue to default (main queue).
  367. self.storage.callbackQueue = dispatch_get_main_queue();
  368. dispatch_queue_set_specific(callbackQueue, callbackQueueKey, NULL, NULL);
  369. }];
  370. [self waitForExpectations];
  371. }
  372. - (void)testGetDataTooSmall {
  373. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetDataTooSmall"];
  374. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  375. /// Only allow 1kB size, which is smaller than our file
  376. [ref dataWithMaxSize:1 * 1024
  377. completion:^(NSData *data, NSError *error) {
  378. XCTAssertNil(data);
  379. XCTAssertEqual(error.code, FIRStorageErrorCodeDownloadSizeExceeded);
  380. [expectation fulfill];
  381. }];
  382. [self waitForExpectations];
  383. }
  384. - (void)testGetDownloadURL {
  385. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetDownloadURL"];
  386. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  387. // Download URL format is
  388. // "https://firebasestorage.googleapis.com:443/v0/b/{bucket}/o/{path}?alt=media&token={token}"
  389. NSString *downloadURLPattern =
  390. @"^https:\\/\\/firebasestorage.googleapis.com:443\\/v0\\/b\\/[^\\/]*\\/o\\/"
  391. @"ios%2Fpublic%2F1mb\\?alt=media&token=[a-z0-9-]*$";
  392. [ref downloadURLWithCompletion:^(NSURL *downloadURL, NSError *error) {
  393. XCTAssertNil(error);
  394. NSRegularExpression *testRegex =
  395. [NSRegularExpression regularExpressionWithPattern:downloadURLPattern options:0 error:nil];
  396. NSString *urlString = [downloadURL absoluteString];
  397. XCTAssertEqual([testRegex numberOfMatchesInString:urlString
  398. options:0
  399. range:NSMakeRange(0, [urlString length])],
  400. 1);
  401. [expectation fulfill];
  402. }];
  403. [self waitForExpectations];
  404. }
  405. - (void)testGetFile {
  406. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetFile"];
  407. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/helloworld"];
  408. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  409. NSURL *fileURL =
  410. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  411. NSData *fileData = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  412. [ref putData:fileData
  413. metadata:nil
  414. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  415. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  416. [task observeStatus:FIRStorageTaskStatusSuccess
  417. handler:^(FIRStorageTaskSnapshot *snapshot) {
  418. [ref dataWithMaxSize:fileData.length
  419. completion:^(NSData *_Nullable data, NSError *_Nullable error) {
  420. XCTAssertEqualObjects(data, fileData);
  421. [expectation fulfill];
  422. }];
  423. }];
  424. [task observeStatus:FIRStorageTaskStatusProgress
  425. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  426. NSProgress *progress = snapshot.progress;
  427. NSLog(@"%lld of %lld", progress.completedUnitCount, progress.totalUnitCount);
  428. }];
  429. [task observeStatus:FIRStorageTaskStatusFailure
  430. handler:^(FIRStorageTaskSnapshot *snapshot) {
  431. XCTAssertNil(snapshot.error);
  432. }];
  433. }];
  434. [self waitForExpectations];
  435. }
  436. - (void)testCancelDownload {
  437. XCTestExpectation *expectation = [self expectationWithDescription:@"testCancelDownload"];
  438. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  439. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  440. NSURL *fileURL =
  441. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"dat"];
  442. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  443. [task observeStatus:FIRStorageTaskStatusFailure
  444. handler:^(FIRStorageTaskSnapshot *snapshot) {
  445. XCTAssertTrue([[snapshot description] containsString:@"State: Failed"]);
  446. [expectation fulfill];
  447. }];
  448. [task observeStatus:FIRStorageTaskStatusProgress
  449. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  450. [task cancel];
  451. }];
  452. [self waitForExpectations];
  453. }
  454. - (void)assertMetadata:(FIRStorageMetadata *)actualMetadata
  455. contentType:(NSString *)expectedContentType
  456. customMetadata:(NSDictionary *)expectedCustomMetadata {
  457. XCTAssertEqualObjects(actualMetadata.cacheControl, @"cache-control");
  458. XCTAssertEqualObjects(actualMetadata.contentDisposition, @"content-disposition");
  459. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"gzip");
  460. XCTAssertEqualObjects(actualMetadata.contentLanguage, @"de");
  461. XCTAssertEqualObjects(actualMetadata.contentType, expectedContentType);
  462. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  463. for (NSString *key in expectedCustomMetadata) {
  464. XCTAssertEqualObjects([actualMetadata.customMetadata objectForKey:key],
  465. [expectedCustomMetadata objectForKey:key]);
  466. }
  467. }
  468. - (void)assertMetadataNil:(FIRStorageMetadata *)actualMetadata {
  469. XCTAssertNil(actualMetadata.cacheControl);
  470. XCTAssertNil(actualMetadata.contentDisposition);
  471. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"identity");
  472. XCTAssertNil(actualMetadata.contentLanguage);
  473. XCTAssertNil(actualMetadata.contentType);
  474. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  475. XCTAssertNil(actualMetadata.customMetadata);
  476. }
  477. - (void)testUpdateMetadata {
  478. XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdateMetadata"];
  479. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  480. // Update all available metadata
  481. FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
  482. metadata.cacheControl = @"cache-control";
  483. metadata.contentDisposition = @"content-disposition";
  484. metadata.contentEncoding = @"gzip";
  485. metadata.contentLanguage = @"de";
  486. metadata.contentType = @"content-type-a";
  487. metadata.customMetadata = @{@"a" : @"b"};
  488. [ref updateMetadata:metadata
  489. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  490. XCTAssertNil(error);
  491. [self assertMetadata:updatedMetadata
  492. contentType:@"content-type-a"
  493. customMetadata:@{@"a" : @"b"}];
  494. // Update a subset of the metadata using the existing object.
  495. FIRStorageMetadata *metadata = updatedMetadata;
  496. metadata.contentType = @"content-type-b";
  497. metadata.customMetadata = @{@"a" : @"b", @"c" : @"d"};
  498. [ref updateMetadata:metadata
  499. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  500. XCTAssertNil(error);
  501. [self assertMetadata:updatedMetadata
  502. contentType:@"content-type-b"
  503. customMetadata:@{@"a" : @"b", @"c" : @"d"}];
  504. // Clear all metadata.
  505. FIRStorageMetadata *metadata = updatedMetadata;
  506. metadata.cacheControl = nil;
  507. metadata.contentDisposition = nil;
  508. metadata.contentEncoding = nil;
  509. metadata.contentLanguage = nil;
  510. metadata.contentType = nil;
  511. metadata.customMetadata = [NSDictionary dictionary];
  512. [ref updateMetadata:metadata
  513. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  514. XCTAssertNil(error);
  515. [self assertMetadataNil:updatedMetadata];
  516. [expectation fulfill];
  517. }];
  518. }];
  519. }];
  520. [self waitForExpectations];
  521. }
  522. - (void)testResumeGetFile {
  523. XCTestExpectation *expectation = [self expectationWithDescription:@"testResumeGetFile"];
  524. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  525. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  526. NSURL *fileURL =
  527. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  528. __block long resumeAtBytes = 256 * 1024;
  529. __block long downloadedBytes = 0;
  530. __block double computationResult = 0;
  531. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  532. [task observeStatus:FIRStorageTaskStatusSuccess
  533. handler:^(FIRStorageTaskSnapshot *snapshot) {
  534. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  535. [expectation fulfill];
  536. }];
  537. [task observeStatus:FIRStorageTaskStatusProgress
  538. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  539. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  540. [[snapshot description] containsString:@"State: Resume"]);
  541. NSProgress *progress = snapshot.progress;
  542. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  543. downloadedBytes = (long)progress.completedUnitCount;
  544. if (progress.completedUnitCount > resumeAtBytes) {
  545. // Making sure the main run loop is busy.
  546. for (int i = 0; i < 500; ++i) {
  547. dispatch_async(dispatch_get_main_queue(), ^{
  548. computationResult = sqrt(INT_MAX - i);
  549. });
  550. }
  551. NSLog(@"Pausing");
  552. [task pause];
  553. resumeAtBytes = INT_MAX;
  554. }
  555. }];
  556. [task observeStatus:FIRStorageTaskStatusPause
  557. handler:^(FIRStorageTaskSnapshot *snapshot) {
  558. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  559. NSLog(@"Resuming");
  560. [task resume];
  561. }];
  562. [self waitForExpectations];
  563. XCTAssertEqual(INT_MAX, resumeAtBytes);
  564. XCTAssertEqualWithAccuracy(sqrt(INT_MAX - 499), computationResult, 0.1);
  565. }
  566. - (void)testResumeGetFileInBackgroundQueue {
  567. XCTestExpectation *expectation =
  568. [self expectationWithDescription:@"testResumeGetFileInBackgroundQueue"];
  569. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  570. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  571. NSURL *fileURL =
  572. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  573. __block long resumeAtBytes = 256 * 1024;
  574. __block long downloadedBytes = 0;
  575. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  576. [task observeStatus:FIRStorageTaskStatusSuccess
  577. handler:^(FIRStorageTaskSnapshot *snapshot) {
  578. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  579. [expectation fulfill];
  580. }];
  581. [task observeStatus:FIRStorageTaskStatusProgress
  582. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  583. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  584. [[snapshot description] containsString:@"State: Resume"]);
  585. NSProgress *progress = snapshot.progress;
  586. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  587. downloadedBytes = (long)progress.completedUnitCount;
  588. if (progress.completedUnitCount > resumeAtBytes) {
  589. NSLog(@"Pausing");
  590. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  591. [task pause];
  592. });
  593. resumeAtBytes = INT_MAX;
  594. }
  595. }];
  596. [task observeStatus:FIRStorageTaskStatusPause
  597. handler:^(FIRStorageTaskSnapshot *snapshot) {
  598. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  599. NSLog(@"Resuming");
  600. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  601. [task resume];
  602. });
  603. }];
  604. [self waitForExpectations];
  605. XCTAssertEqual(INT_MAX, resumeAtBytes);
  606. }
  607. - (void)testPagedListFiles {
  608. XCTestExpectation *expectation = [self expectationWithDescription:@"testPagedListFiles"];
  609. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  610. [ref listWithMaxResults:2
  611. completion:^(FIRStorageListResult *_Nullable listResult, NSError *_Nullable error) {
  612. XCTAssertNotNil(listResult);
  613. XCTAssertNil(error);
  614. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  615. XCTAssertEqualObjects(listResult.prefixes, @[]);
  616. XCTAssertNotNil(listResult.pageToken);
  617. [ref listWithMaxResults:2
  618. pageToken:listResult.pageToken
  619. completion:^(FIRStorageListResult *_Nullable listResult,
  620. NSError *_Nullable error) {
  621. XCTAssertNotNil(listResult);
  622. XCTAssertNil(error);
  623. XCTAssertEqualObjects(listResult.items, @[]);
  624. XCTAssertEqualObjects(listResult.prefixes,
  625. @[ [ref child:@"prefix"] ]);
  626. XCTAssertNil(listResult.pageToken);
  627. [expectation fulfill];
  628. }];
  629. }];
  630. [self waitForExpectations];
  631. }
  632. - (void)testListAllFiles {
  633. XCTestExpectation *expectation = [self expectationWithDescription:@"testListAllFiles"];
  634. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  635. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  636. NSError *_Nullable error) {
  637. XCTAssertNotNil(listResult);
  638. XCTAssertNil(error);
  639. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  640. XCTAssertEqualObjects(listResult.prefixes, @[ [ref child:@"prefix"] ]);
  641. XCTAssertNil(listResult.pageToken);
  642. [expectation fulfill];
  643. }];
  644. [self waitForExpectations];
  645. }
  646. - (void)testListFilesAtRoot {
  647. XCTestExpectation *expectation = [self expectationWithDescription:@"testListFilesAtRoot"];
  648. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  649. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  650. NSError *_Nullable error) {
  651. XCTAssertNotNil(listResult);
  652. XCTAssertNil(error);
  653. XCTAssertNil(listResult.pageToken);
  654. [expectation fulfill];
  655. }];
  656. [self waitForExpectations];
  657. }
  658. - (void)waitForExpectations {
  659. [self waitForExpectationsWithTimeout:kFIRStorageIntegrationTestTimeout
  660. handler:^(NSError *_Nullable error) {
  661. if (error) {
  662. NSLog(@"%@", error);
  663. }
  664. }];
  665. }
  666. @end