FIRStorageIntegrationTests.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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 "FirebaseStorageInternal/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)testDifferentInstance {
  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)testCopyMetadata {
  147. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetMetadata"];
  148. FIRStorageReference *ref = [self.storage.reference child:@"ios/public/1mb"];
  149. [ref metadataWithCompletion:^(FIRStorageMetadata *metadata, NSError *error) {
  150. XCTAssertNotNil(metadata, "Metadata should not be nil");
  151. XCTAssertNil(error, "Error should be nil");
  152. FIRStorageMetadata *metadata2 = metadata.copy;
  153. XCTAssertNotEqual(metadata, metadata2);
  154. XCTAssertEqualObjects(metadata, metadata2);
  155. [expectation fulfill];
  156. }];
  157. [self waitForExpectations];
  158. }
  159. - (void)testDelete {
  160. XCTestExpectation *expectation = [self expectationWithDescription:@"testDelete"];
  161. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/fileToDelete"];
  162. NSData *data = [@"Delete me!!!!!!!" dataUsingEncoding:NSUTF8StringEncoding];
  163. [ref putData:data
  164. metadata:nil
  165. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  166. XCTAssertNotNil(metadata, "Metadata should not be nil");
  167. XCTAssertNil(error, "Error should be nil");
  168. [ref deleteWithCompletion:^(NSError *error) {
  169. XCTAssertNil(error, "Error should be nil");
  170. [expectation fulfill];
  171. }];
  172. }];
  173. [self waitForExpectations];
  174. }
  175. - (void)testDeleteWithNilCompletion {
  176. XCTestExpectation *expectation = [self expectationWithDescription:@"testDeleteWithNilCompletion"];
  177. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/fileToDelete"];
  178. NSData *data = [@"Delete me!!!!!!!" dataUsingEncoding:NSUTF8StringEncoding];
  179. [ref putData:data
  180. metadata:nil
  181. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  182. XCTAssertNotNil(metadata, "Metadata should not be nil");
  183. XCTAssertNil(error, "Error should be nil");
  184. [ref deleteWithCompletion:nil];
  185. [expectation fulfill];
  186. }];
  187. [self waitForExpectations];
  188. }
  189. - (void)testPutDataSpecialCharacter {
  190. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutDataSpecialCharacter"];
  191. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/-._~!$'()*,=:@&+;"];
  192. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  193. [ref putData:data
  194. metadata:nil
  195. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  196. XCTAssertNotNil(metadata, "Metadata should not be nil");
  197. XCTAssertNil(error, "Error should be nil");
  198. [expectation fulfill];
  199. }];
  200. [self waitForExpectations];
  201. }
  202. - (void)testPutDataInBackgroundQueue {
  203. XCTestExpectation *expectation =
  204. [self expectationWithDescription:@"testPutDataInBackgroundQueue"];
  205. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/testBytesUpload"];
  206. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  207. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  208. [ref putData:data
  209. metadata:nil
  210. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  211. XCTAssertNotNil(metadata, "Metadata should not be nil");
  212. XCTAssertNil(error, "Error should be nil");
  213. [expectation fulfill];
  214. }];
  215. });
  216. [self waitForExpectations];
  217. }
  218. - (void)testPutDataWithEmptyData {
  219. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutDataWithEmptyData"];
  220. FIRStorageReference *ref =
  221. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutEmptyData"];
  222. NSData *data = [[NSData alloc] init];
  223. [ref putData:data
  224. metadata:nil
  225. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  226. XCTAssertNotNil(metadata, "Metadata should not be nil");
  227. XCTAssertNil(error, "Error should be nil");
  228. [expectation fulfill];
  229. }];
  230. [self waitForExpectations];
  231. }
  232. - (void)testPutData {
  233. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutData"];
  234. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/private/secretfile.txt"];
  235. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  236. [ref putData:data
  237. metadata:nil
  238. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  239. XCTAssertNil(metadata, "Metadata should be nil");
  240. XCTAssertNotNil(error, "Error should not be nil");
  241. XCTAssertEqual(error.code, FIRStorageErrorCodeUnauthorized);
  242. [expectation fulfill];
  243. }];
  244. [self waitForExpectations];
  245. }
  246. - (void)testPutFile {
  247. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutFile"];
  248. FIRStorageReference *ref =
  249. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutFile"];
  250. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  251. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  252. NSURL *fileURL =
  253. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  254. [data writeToURL:fileURL atomically:YES];
  255. FIRStorageUploadTask *task = [ref putFile:fileURL
  256. metadata:nil
  257. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  258. XCTAssertNotNil(metadata, "Metadata should not be nil");
  259. XCTAssertNil(error, "Error should be nil");
  260. }];
  261. __block long uploadedBytes = -1;
  262. [task observeStatus:FIRStorageTaskStatusSuccess
  263. handler:^(FIRStorageTaskSnapshot *snapshot) {
  264. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  265. [expectation fulfill];
  266. }];
  267. [task observeStatus:FIRStorageTaskStatusProgress
  268. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  269. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  270. [[snapshot description] containsString:@"State: Resume"]);
  271. NSProgress *progress = snapshot.progress;
  272. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, uploadedBytes);
  273. uploadedBytes = (long)progress.completedUnitCount;
  274. }];
  275. [self waitForExpectations];
  276. }
  277. - (void)testPutFileWithSpecialCharacters {
  278. XCTestExpectation *expectation =
  279. [self expectationWithDescription:@"testPutFileWithSpecialCharacters"];
  280. NSString *fileName = @"hello&+@_ .txt";
  281. FIRStorageReference *ref =
  282. [self.storage referenceWithPath:[@"ios/public/" stringByAppendingString:fileName]];
  283. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  284. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  285. NSURL *fileURL = [tmpDirURL URLByAppendingPathComponent:fileName];
  286. [data writeToURL:fileURL atomically:YES];
  287. [ref putFile:fileURL
  288. metadata:nil
  289. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  290. XCTAssertNotNil(metadata, "Metadata should not be nil");
  291. XCTAssertNil(error, "Error should be nil");
  292. XCTAssertEqualObjects(fileName, metadata.name);
  293. FIRStorageReference *download =
  294. [self.storage referenceWithPath:[@"ios/public/" stringByAppendingString:fileName]];
  295. [download metadataWithCompletion:^(FIRStorageMetadata *metadata, NSError *error) {
  296. XCTAssertNotNil(metadata, "Metadata should not be nil");
  297. XCTAssertNil(error, "Error should be nil");
  298. XCTAssertEqualObjects(fileName, metadata.name);
  299. [expectation fulfill];
  300. }];
  301. }];
  302. [self waitForExpectations];
  303. }
  304. - (void)testPutDataNoMetadata {
  305. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutDataNoMetadata"];
  306. FIRStorageReference *ref =
  307. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutDataNoMetadata"];
  308. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  309. [ref putData:data
  310. metadata:nil
  311. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  312. XCTAssertNotNil(metadata, "Metadata should not be nil");
  313. XCTAssertNil(error, "Error should be nil");
  314. [expectation fulfill];
  315. }];
  316. [self waitForExpectations];
  317. }
  318. - (void)testPutFileNoMetadata {
  319. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutFileNoMetadata"];
  320. FIRStorageReference *ref =
  321. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutFileNoMetadata"];
  322. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  323. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  324. NSURL *fileURL =
  325. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  326. [data writeToURL:fileURL atomically:YES];
  327. [ref putFile:fileURL
  328. metadata:nil
  329. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  330. XCTAssertNotNil(metadata, "Metadata should not be nil");
  331. XCTAssertNil(error, "Error should be nil");
  332. [expectation fulfill];
  333. }];
  334. [self waitForExpectations];
  335. }
  336. - (void)testGetData {
  337. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetData"];
  338. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  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. [self waitForExpectations];
  346. }
  347. - (void)testGetDataInBackgroundQueue {
  348. XCTestExpectation *expectation =
  349. [self expectationWithDescription:@"testGetDataInBackgroundQueue"];
  350. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  351. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  352. [ref dataWithMaxSize:1 * 1024 * 1024
  353. completion:^(NSData *data, NSError *error) {
  354. XCTAssertNotNil(data, "Data should not be nil");
  355. XCTAssertNil(error, "Error should be nil");
  356. [expectation fulfill];
  357. }];
  358. });
  359. [self waitForExpectations];
  360. }
  361. - (void)testGetDataWithCustomCallbackQueue {
  362. XCTestExpectation *expectation =
  363. [self expectationWithDescription:@"testUnauthenticatedGetDataInCustomCallbackQueue"];
  364. NSString *callbackQueueLabelString = @"customCallbackQueue";
  365. const char *callbackQueueLabel = [callbackQueueLabelString UTF8String];
  366. const void *callbackQueueKey = callbackQueueLabel;
  367. dispatch_queue_t callbackQueue = dispatch_queue_create(callbackQueueLabel, NULL);
  368. dispatch_queue_set_specific(callbackQueue, callbackQueueKey, (void *)callbackQueueKey, NULL);
  369. _storage.callbackQueue = callbackQueue;
  370. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  371. [ref dataWithMaxSize:1 * 1024 * 1024
  372. completion:^(NSData *data, NSError *error) {
  373. XCTAssertNotNil(data, "Data should not be nil");
  374. XCTAssertNil(error, "Error should be nil");
  375. char *currentQueueLabel = dispatch_get_specific(callbackQueueKey);
  376. NSString *currentQueueLabelString = [NSString stringWithUTF8String:currentQueueLabel];
  377. XCTAssertEqualObjects(currentQueueLabelString, callbackQueueLabelString);
  378. [expectation fulfill];
  379. // Reset the callbackQueue to default (main queue).
  380. self.storage.callbackQueue = dispatch_get_main_queue();
  381. dispatch_queue_set_specific(callbackQueue, callbackQueueKey, NULL, NULL);
  382. }];
  383. [self waitForExpectations];
  384. }
  385. - (void)testGetDataTooSmall {
  386. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetDataTooSmall"];
  387. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  388. /// Only allow 1kB size, which is smaller than our file
  389. [ref dataWithMaxSize:1 * 1024
  390. completion:^(NSData *data, NSError *error) {
  391. XCTAssertNil(data);
  392. XCTAssertEqual(error.code, FIRStorageErrorCodeDownloadSizeExceeded);
  393. [expectation fulfill];
  394. }];
  395. [self waitForExpectations];
  396. }
  397. - (void)testGetDownloadURL {
  398. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetDownloadURL"];
  399. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  400. // Download URL format is
  401. // "https://firebasestorage.googleapis.com:443/v0/b/{bucket}/o/{path}?alt=media&token={token}"
  402. NSString *downloadURLPattern =
  403. @"^https:\\/\\/firebasestorage.googleapis.com:443\\/v0\\/b\\/[^\\/]*\\/o\\/"
  404. @"ios%2Fpublic%2F1mb\\?alt=media&token=[a-z0-9-]*$";
  405. [ref downloadURLWithCompletion:^(NSURL *downloadURL, NSError *error) {
  406. XCTAssertNil(error);
  407. NSRegularExpression *testRegex =
  408. [NSRegularExpression regularExpressionWithPattern:downloadURLPattern options:0 error:nil];
  409. NSString *urlString = [downloadURL absoluteString];
  410. XCTAssertEqual([testRegex numberOfMatchesInString:urlString
  411. options:0
  412. range:NSMakeRange(0, [urlString length])],
  413. 1);
  414. [expectation fulfill];
  415. }];
  416. [self waitForExpectations];
  417. }
  418. - (void)testGetFile {
  419. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetFile"];
  420. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/helloworld"];
  421. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  422. NSURL *fileURL =
  423. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  424. NSData *fileData = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  425. [ref putData:fileData
  426. metadata:nil
  427. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  428. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  429. [task observeStatus:FIRStorageTaskStatusSuccess
  430. handler:^(FIRStorageTaskSnapshot *snapshot) {
  431. [ref dataWithMaxSize:fileData.length
  432. completion:^(NSData *_Nullable data, NSError *_Nullable error) {
  433. XCTAssertEqualObjects(data, fileData);
  434. [expectation fulfill];
  435. }];
  436. }];
  437. [task observeStatus:FIRStorageTaskStatusProgress
  438. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  439. NSProgress *progress = snapshot.progress;
  440. NSLog(@"%lld of %lld", progress.completedUnitCount, progress.totalUnitCount);
  441. }];
  442. [task observeStatus:FIRStorageTaskStatusFailure
  443. handler:^(FIRStorageTaskSnapshot *snapshot) {
  444. XCTAssertNil(snapshot.error);
  445. }];
  446. }];
  447. [self waitForExpectations];
  448. }
  449. - (void)testCancelDownload {
  450. XCTestExpectation *expectation = [self expectationWithDescription:@"testCancelDownload"];
  451. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  452. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  453. NSURL *fileURL =
  454. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"dat"];
  455. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  456. // Don't fulfill twice if a second observe failure happens before the cancel completes.
  457. BOOL __block fulfilled = NO;
  458. [task observeStatus:FIRStorageTaskStatusFailure
  459. handler:^(FIRStorageTaskSnapshot *snapshot) {
  460. XCTAssertTrue([[snapshot description] containsString:@"State: Failed"]);
  461. if (!fulfilled) {
  462. fulfilled = YES;
  463. [expectation fulfill];
  464. }
  465. }];
  466. [task observeStatus:FIRStorageTaskStatusProgress
  467. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  468. [task cancel];
  469. }];
  470. [self waitForExpectations];
  471. }
  472. - (void)assertMetadata:(FIRStorageMetadata *)actualMetadata
  473. contentType:(NSString *)expectedContentType
  474. customMetadata:(NSDictionary *)expectedCustomMetadata {
  475. XCTAssertEqualObjects(actualMetadata.cacheControl, @"cache-control");
  476. XCTAssertEqualObjects(actualMetadata.contentDisposition, @"content-disposition");
  477. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"gzip");
  478. XCTAssertEqualObjects(actualMetadata.contentLanguage, @"de");
  479. XCTAssertEqualObjects(actualMetadata.contentType, expectedContentType);
  480. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  481. for (NSString *key in expectedCustomMetadata) {
  482. XCTAssertEqualObjects([actualMetadata.customMetadata objectForKey:key],
  483. [expectedCustomMetadata objectForKey:key]);
  484. }
  485. }
  486. - (void)assertMetadataNil:(FIRStorageMetadata *)actualMetadata {
  487. XCTAssertNil(actualMetadata.cacheControl);
  488. XCTAssertNil(actualMetadata.contentDisposition);
  489. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"identity");
  490. XCTAssertNil(actualMetadata.contentLanguage);
  491. XCTAssertNil(actualMetadata.contentType);
  492. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  493. XCTAssertNil(actualMetadata.customMetadata);
  494. }
  495. - (void)testUpdateMetadata {
  496. XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdateMetadata"];
  497. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  498. // Update all available metadata
  499. FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
  500. metadata.cacheControl = @"cache-control";
  501. metadata.contentDisposition = @"content-disposition";
  502. metadata.contentEncoding = @"gzip";
  503. metadata.contentLanguage = @"de";
  504. metadata.contentType = @"content-type-a";
  505. metadata.customMetadata = @{@"a" : @"b", @"y" : @"z"};
  506. [ref updateMetadata:metadata
  507. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  508. XCTAssertNil(error);
  509. [self assertMetadata:updatedMetadata
  510. contentType:@"content-type-a"
  511. customMetadata:@{@"a" : @"b", @"y" : @"z"}];
  512. // Update a subset of the metadata using the existing object.
  513. FIRStorageMetadata *metadata = updatedMetadata;
  514. metadata.contentType = @"content-type-b";
  515. metadata.customMetadata = @{@"c" : @"d", @"y" : @""};
  516. [ref updateMetadata:metadata
  517. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  518. XCTAssertNil(error);
  519. [self assertMetadata:updatedMetadata
  520. contentType:@"content-type-b"
  521. // "a" is now deleted and the empty string for "y" remains.
  522. customMetadata:@{@"c" : @"d", @"y" : @""}];
  523. // Clear all metadata with nils.
  524. FIRStorageMetadata *metadata = updatedMetadata;
  525. metadata.cacheControl = nil;
  526. metadata.contentDisposition = nil;
  527. metadata.contentEncoding = nil;
  528. metadata.contentLanguage = nil;
  529. metadata.contentType = nil;
  530. metadata.customMetadata = nil;
  531. [ref updateMetadata:metadata
  532. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  533. XCTAssertNil(error);
  534. [self assertMetadataNil:updatedMetadata];
  535. XCTAssertNil(updatedMetadata.customMetadata);
  536. [expectation fulfill];
  537. }];
  538. }];
  539. }];
  540. [self waitForExpectations];
  541. }
  542. - (void)testResumeGetFile {
  543. XCTestExpectation *expectation = [self expectationWithDescription:@"testResumeGetFile"];
  544. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  545. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  546. NSURL *fileURL =
  547. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  548. __block long resumeAtBytes = 256 * 1024;
  549. __block long downloadedBytes = 0;
  550. __block double computationResult = 0;
  551. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  552. [task observeStatus:FIRStorageTaskStatusSuccess
  553. handler:^(FIRStorageTaskSnapshot *snapshot) {
  554. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  555. [expectation fulfill];
  556. }];
  557. [task observeStatus:FIRStorageTaskStatusProgress
  558. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  559. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  560. [[snapshot description] containsString:@"State: Resume"]);
  561. NSProgress *progress = snapshot.progress;
  562. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  563. downloadedBytes = (long)progress.completedUnitCount;
  564. if (progress.completedUnitCount > resumeAtBytes) {
  565. // Making sure the main run loop is busy.
  566. for (int i = 0; i < 500; ++i) {
  567. dispatch_async(dispatch_get_main_queue(), ^{
  568. computationResult = sqrt(INT_MAX - i);
  569. });
  570. }
  571. NSLog(@"Pausing");
  572. [task pause];
  573. resumeAtBytes = INT_MAX;
  574. }
  575. }];
  576. [task observeStatus:FIRStorageTaskStatusPause
  577. handler:^(FIRStorageTaskSnapshot *snapshot) {
  578. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  579. NSLog(@"Resuming");
  580. [task resume];
  581. }];
  582. [self waitForExpectations];
  583. XCTAssertEqual(INT_MAX, resumeAtBytes);
  584. XCTAssertEqualWithAccuracy(sqrt(INT_MAX - 499), computationResult, 0.1);
  585. }
  586. - (void)testResumeGetFileInBackgroundQueue {
  587. XCTestExpectation *expectation =
  588. [self expectationWithDescription:@"testResumeGetFileInBackgroundQueue"];
  589. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  590. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  591. NSURL *fileURL =
  592. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  593. __block long resumeAtBytes = 256 * 1024;
  594. __block long downloadedBytes = 0;
  595. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  596. [task observeStatus:FIRStorageTaskStatusSuccess
  597. handler:^(FIRStorageTaskSnapshot *snapshot) {
  598. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  599. [expectation fulfill];
  600. }];
  601. [task observeStatus:FIRStorageTaskStatusProgress
  602. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  603. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  604. [[snapshot description] containsString:@"State: Resume"]);
  605. NSProgress *progress = snapshot.progress;
  606. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  607. downloadedBytes = (long)progress.completedUnitCount;
  608. if (progress.completedUnitCount > resumeAtBytes) {
  609. NSLog(@"Pausing");
  610. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  611. [task pause];
  612. });
  613. resumeAtBytes = INT_MAX;
  614. }
  615. }];
  616. [task observeStatus:FIRStorageTaskStatusPause
  617. handler:^(FIRStorageTaskSnapshot *snapshot) {
  618. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  619. NSLog(@"Resuming");
  620. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  621. [task resume];
  622. });
  623. }];
  624. [self waitForExpectations];
  625. XCTAssertEqual(INT_MAX, resumeAtBytes);
  626. }
  627. - (void)testPagedListFiles {
  628. XCTestExpectation *expectation = [self expectationWithDescription:@"testPagedListFiles"];
  629. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  630. [ref listWithMaxResults:2
  631. completion:^(FIRStorageListResult *_Nullable listResult, NSError *_Nullable error) {
  632. XCTAssertNotNil(listResult);
  633. XCTAssertNil(error);
  634. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  635. XCTAssertEqualObjects(listResult.prefixes, @[]);
  636. XCTAssertNotNil(listResult.pageToken);
  637. [ref listWithMaxResults:2
  638. pageToken:listResult.pageToken
  639. completion:^(FIRStorageListResult *_Nullable listResult,
  640. NSError *_Nullable error) {
  641. XCTAssertNotNil(listResult);
  642. XCTAssertNil(error);
  643. XCTAssertEqualObjects(listResult.items, @[]);
  644. XCTAssertEqualObjects(listResult.prefixes,
  645. @[ [ref child:@"prefix"] ]);
  646. XCTAssertNil(listResult.pageToken);
  647. [expectation fulfill];
  648. }];
  649. }];
  650. [self waitForExpectations];
  651. }
  652. - (void)testListAllFiles {
  653. XCTestExpectation *expectation = [self expectationWithDescription:@"testListAllFiles"];
  654. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  655. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  656. NSError *_Nullable error) {
  657. XCTAssertNotNil(listResult);
  658. XCTAssertNil(error);
  659. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  660. XCTAssertEqualObjects(listResult.prefixes, @[ [ref child:@"prefix"] ]);
  661. XCTAssertNil(listResult.pageToken);
  662. [expectation fulfill];
  663. }];
  664. [self waitForExpectations];
  665. }
  666. - (void)testListFilesAtRoot {
  667. XCTestExpectation *expectation = [self expectationWithDescription:@"testListFilesAtRoot"];
  668. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  669. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  670. NSError *_Nullable error) {
  671. XCTAssertNotNil(listResult);
  672. XCTAssertNil(error);
  673. XCTAssertNil(listResult.pageToken);
  674. [expectation fulfill];
  675. }];
  676. [self waitForExpectations];
  677. }
  678. - (void)testCopyListResult {
  679. XCTestExpectation *expectation = [self expectationWithDescription:@"testCopyListResult"];
  680. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  681. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  682. NSError *_Nullable error) {
  683. XCTAssertNotNil(listResult);
  684. XCTAssertNil(error);
  685. XCTAssertNil(listResult.pageToken);
  686. FIRStorageListResult *listResult2 = listResult.copy;
  687. XCTAssertEqual(listResult.pageToken, listResult2.pageToken);
  688. XCTAssertNotEqual(listResult, listResult2);
  689. [expectation fulfill];
  690. }];
  691. [self waitForExpectations];
  692. }
  693. - (void)waitForExpectations {
  694. [self waitForExpectationsWithTimeout:kFIRStorageIntegrationTestTimeout
  695. handler:^(NSError *_Nullable error) {
  696. if (error) {
  697. NSLog(@"%@", error);
  698. }
  699. }];
  700. }
  701. @end