FIRStorageIntegrationTests.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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;
  16. #import <FirebaseAuth/FirebaseAuth.h>
  17. #import "FirebaseCore/Extension/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. // Don't fulfill twice if a second observe failure happens before the cancel completes.
  444. BOOL __block fulfilled = NO;
  445. [task observeStatus:FIRStorageTaskStatusFailure
  446. handler:^(FIRStorageTaskSnapshot *snapshot) {
  447. XCTAssertTrue([[snapshot description] containsString:@"State: Failed"]);
  448. if (!fulfilled) {
  449. fulfilled = YES;
  450. [expectation fulfill];
  451. }
  452. }];
  453. [task observeStatus:FIRStorageTaskStatusProgress
  454. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  455. [task cancel];
  456. }];
  457. [self waitForExpectations];
  458. }
  459. - (void)assertMetadata:(FIRStorageMetadata *)actualMetadata
  460. contentType:(NSString *)expectedContentType
  461. customMetadata:(NSDictionary *)expectedCustomMetadata {
  462. XCTAssertEqualObjects(actualMetadata.cacheControl, @"cache-control");
  463. XCTAssertEqualObjects(actualMetadata.contentDisposition, @"content-disposition");
  464. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"gzip");
  465. XCTAssertEqualObjects(actualMetadata.contentLanguage, @"de");
  466. XCTAssertEqualObjects(actualMetadata.contentType, expectedContentType);
  467. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  468. for (NSString *key in expectedCustomMetadata) {
  469. XCTAssertEqualObjects([actualMetadata.customMetadata objectForKey:key],
  470. [expectedCustomMetadata objectForKey:key]);
  471. }
  472. }
  473. - (void)assertMetadataNil:(FIRStorageMetadata *)actualMetadata {
  474. XCTAssertNil(actualMetadata.cacheControl);
  475. XCTAssertNil(actualMetadata.contentDisposition);
  476. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"identity");
  477. XCTAssertNil(actualMetadata.contentLanguage);
  478. XCTAssertNil(actualMetadata.contentType);
  479. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  480. XCTAssertNil(actualMetadata.customMetadata);
  481. }
  482. - (void)testUpdateMetadata {
  483. XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdateMetadata"];
  484. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  485. // Update all available metadata
  486. FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
  487. metadata.cacheControl = @"cache-control";
  488. metadata.contentDisposition = @"content-disposition";
  489. metadata.contentEncoding = @"gzip";
  490. metadata.contentLanguage = @"de";
  491. metadata.contentType = @"content-type-a";
  492. metadata.customMetadata = @{@"a" : @"b"};
  493. [ref updateMetadata:metadata
  494. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  495. XCTAssertNil(error);
  496. [self assertMetadata:updatedMetadata
  497. contentType:@"content-type-a"
  498. customMetadata:@{@"a" : @"b"}];
  499. // Update a subset of the metadata using the existing object.
  500. FIRStorageMetadata *metadata = updatedMetadata;
  501. metadata.contentType = @"content-type-b";
  502. metadata.customMetadata = @{@"a" : @"b", @"c" : @"d"};
  503. [ref updateMetadata:metadata
  504. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  505. XCTAssertNil(error);
  506. [self assertMetadata:updatedMetadata
  507. contentType:@"content-type-b"
  508. customMetadata:@{@"a" : @"b", @"c" : @"d"}];
  509. // Clear all metadata.
  510. FIRStorageMetadata *metadata = updatedMetadata;
  511. metadata.cacheControl = nil;
  512. metadata.contentDisposition = nil;
  513. metadata.contentEncoding = nil;
  514. metadata.contentLanguage = nil;
  515. metadata.contentType = nil;
  516. metadata.customMetadata = [NSDictionary dictionary];
  517. [ref updateMetadata:metadata
  518. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  519. XCTAssertNil(error);
  520. [self assertMetadataNil:updatedMetadata];
  521. [expectation fulfill];
  522. }];
  523. }];
  524. }];
  525. [self waitForExpectations];
  526. }
  527. - (void)testResumeGetFile {
  528. XCTestExpectation *expectation = [self expectationWithDescription:@"testResumeGetFile"];
  529. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  530. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  531. NSURL *fileURL =
  532. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  533. __block long resumeAtBytes = 256 * 1024;
  534. __block long downloadedBytes = 0;
  535. __block double computationResult = 0;
  536. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  537. [task observeStatus:FIRStorageTaskStatusSuccess
  538. handler:^(FIRStorageTaskSnapshot *snapshot) {
  539. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  540. [expectation fulfill];
  541. }];
  542. [task observeStatus:FIRStorageTaskStatusProgress
  543. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  544. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  545. [[snapshot description] containsString:@"State: Resume"]);
  546. NSProgress *progress = snapshot.progress;
  547. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  548. downloadedBytes = (long)progress.completedUnitCount;
  549. if (progress.completedUnitCount > resumeAtBytes) {
  550. // Making sure the main run loop is busy.
  551. for (int i = 0; i < 500; ++i) {
  552. dispatch_async(dispatch_get_main_queue(), ^{
  553. computationResult = sqrt(INT_MAX - i);
  554. });
  555. }
  556. NSLog(@"Pausing");
  557. [task pause];
  558. resumeAtBytes = INT_MAX;
  559. }
  560. }];
  561. [task observeStatus:FIRStorageTaskStatusPause
  562. handler:^(FIRStorageTaskSnapshot *snapshot) {
  563. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  564. NSLog(@"Resuming");
  565. [task resume];
  566. }];
  567. [self waitForExpectations];
  568. XCTAssertEqual(INT_MAX, resumeAtBytes);
  569. XCTAssertEqualWithAccuracy(sqrt(INT_MAX - 499), computationResult, 0.1);
  570. }
  571. - (void)testResumeGetFileInBackgroundQueue {
  572. XCTestExpectation *expectation =
  573. [self expectationWithDescription:@"testResumeGetFileInBackgroundQueue"];
  574. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  575. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  576. NSURL *fileURL =
  577. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  578. __block long resumeAtBytes = 256 * 1024;
  579. __block long downloadedBytes = 0;
  580. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  581. [task observeStatus:FIRStorageTaskStatusSuccess
  582. handler:^(FIRStorageTaskSnapshot *snapshot) {
  583. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  584. [expectation fulfill];
  585. }];
  586. [task observeStatus:FIRStorageTaskStatusProgress
  587. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  588. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  589. [[snapshot description] containsString:@"State: Resume"]);
  590. NSProgress *progress = snapshot.progress;
  591. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  592. downloadedBytes = (long)progress.completedUnitCount;
  593. if (progress.completedUnitCount > resumeAtBytes) {
  594. NSLog(@"Pausing");
  595. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  596. [task pause];
  597. });
  598. resumeAtBytes = INT_MAX;
  599. }
  600. }];
  601. [task observeStatus:FIRStorageTaskStatusPause
  602. handler:^(FIRStorageTaskSnapshot *snapshot) {
  603. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  604. NSLog(@"Resuming");
  605. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  606. [task resume];
  607. });
  608. }];
  609. [self waitForExpectations];
  610. XCTAssertEqual(INT_MAX, resumeAtBytes);
  611. }
  612. - (void)testPagedListFiles {
  613. XCTestExpectation *expectation = [self expectationWithDescription:@"testPagedListFiles"];
  614. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  615. [ref listWithMaxResults:2
  616. completion:^(FIRStorageListResult *_Nullable listResult, NSError *_Nullable error) {
  617. XCTAssertNotNil(listResult);
  618. XCTAssertNil(error);
  619. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  620. XCTAssertEqualObjects(listResult.prefixes, @[]);
  621. XCTAssertNotNil(listResult.pageToken);
  622. [ref listWithMaxResults:2
  623. pageToken:listResult.pageToken
  624. completion:^(FIRStorageListResult *_Nullable listResult,
  625. NSError *_Nullable error) {
  626. XCTAssertNotNil(listResult);
  627. XCTAssertNil(error);
  628. XCTAssertEqualObjects(listResult.items, @[]);
  629. XCTAssertEqualObjects(listResult.prefixes,
  630. @[ [ref child:@"prefix"] ]);
  631. XCTAssertNil(listResult.pageToken);
  632. [expectation fulfill];
  633. }];
  634. }];
  635. [self waitForExpectations];
  636. }
  637. - (void)testListAllFiles {
  638. XCTestExpectation *expectation = [self expectationWithDescription:@"testListAllFiles"];
  639. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  640. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  641. NSError *_Nullable error) {
  642. XCTAssertNotNil(listResult);
  643. XCTAssertNil(error);
  644. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  645. XCTAssertEqualObjects(listResult.prefixes, @[ [ref child:@"prefix"] ]);
  646. XCTAssertNil(listResult.pageToken);
  647. [expectation fulfill];
  648. }];
  649. [self waitForExpectations];
  650. }
  651. - (void)testListFilesAtRoot {
  652. XCTestExpectation *expectation = [self expectationWithDescription:@"testListFilesAtRoot"];
  653. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  654. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  655. NSError *_Nullable error) {
  656. XCTAssertNotNil(listResult);
  657. XCTAssertNil(error);
  658. XCTAssertNil(listResult.pageToken);
  659. [expectation fulfill];
  660. }];
  661. [self waitForExpectations];
  662. }
  663. - (void)waitForExpectations {
  664. [self waitForExpectationsWithTimeout:kFIRStorageIntegrationTestTimeout
  665. handler:^(NSError *_Nullable error) {
  666. if (error) {
  667. NSLog(@"%@", error);
  668. }
  669. }];
  670. }
  671. @end