FIRStorageIntegrationTests.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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. XCTAssertEqualObjects(actualMetadata.name, @"1mb");
  481. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  482. for (NSString *key in expectedCustomMetadata) {
  483. XCTAssertEqualObjects([actualMetadata.customMetadata objectForKey:key],
  484. [expectedCustomMetadata objectForKey:key]);
  485. }
  486. }
  487. - (void)assertMetadataNil:(FIRStorageMetadata *)actualMetadata {
  488. XCTAssertNil(actualMetadata.cacheControl);
  489. XCTAssertNil(actualMetadata.contentDisposition);
  490. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"identity");
  491. XCTAssertNil(actualMetadata.contentLanguage);
  492. XCTAssertNil(actualMetadata.contentType);
  493. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  494. XCTAssertNil(actualMetadata.customMetadata);
  495. }
  496. - (void)testUpdateMetadata {
  497. XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdateMetadata"];
  498. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  499. // Update all available metadata
  500. FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
  501. metadata.cacheControl = @"cache-control";
  502. metadata.contentDisposition = @"content-disposition";
  503. metadata.contentEncoding = @"gzip";
  504. metadata.contentLanguage = @"de";
  505. metadata.contentType = @"content-type-a";
  506. metadata.customMetadata = @{@"a" : @"b", @"y" : @"z"};
  507. [ref updateMetadata:metadata
  508. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  509. XCTAssertNil(error);
  510. [self assertMetadata:updatedMetadata
  511. contentType:@"content-type-a"
  512. customMetadata:@{@"a" : @"b", @"y" : @"z"}];
  513. // Update a subset of the metadata using the existing object.
  514. FIRStorageMetadata *metadata = updatedMetadata;
  515. metadata.contentType = @"content-type-b";
  516. metadata.customMetadata = @{@"c" : @"d", @"y" : @""};
  517. [ref updateMetadata:metadata
  518. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  519. XCTAssertNil(error);
  520. [self assertMetadata:updatedMetadata
  521. contentType:@"content-type-b"
  522. // "a" is now deleted and the empty string for "y" remains.
  523. customMetadata:@{@"c" : @"d", @"y" : @""}];
  524. // Clear all metadata with nils.
  525. FIRStorageMetadata *metadata = updatedMetadata;
  526. metadata.cacheControl = nil;
  527. metadata.contentDisposition = nil;
  528. metadata.contentEncoding = nil;
  529. metadata.contentLanguage = nil;
  530. metadata.contentType = nil;
  531. metadata.customMetadata = nil;
  532. [ref updateMetadata:metadata
  533. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  534. XCTAssertNil(error);
  535. [self assertMetadataNil:updatedMetadata];
  536. XCTAssertNil(updatedMetadata.customMetadata);
  537. [expectation fulfill];
  538. }];
  539. }];
  540. }];
  541. [self waitForExpectations];
  542. }
  543. - (void)testMetadataDictInitAndClear {
  544. FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] initWithDictionary:@{
  545. @"cacheControl" : @"cache-control",
  546. @"contentDisposition" : @"content-disposition",
  547. @"contentEncoding" : @"gzip",
  548. @"contentLanguage" : @"de",
  549. @"contentType" : @"content-type-a",
  550. @"md5Hash" : @"123456789012345678901234", // length 24
  551. @"name" : @"1mb",
  552. @"metadata" : @{@"a" : @"b", @"y" : @"z"}
  553. }];
  554. [self assertMetadata:metadata
  555. contentType:@"content-type-a"
  556. customMetadata:@{@"a" : @"b", @"y" : @"z"}];
  557. metadata.cacheControl = nil;
  558. metadata.contentDisposition = nil;
  559. metadata.contentEncoding = @"identity";
  560. metadata.contentLanguage = nil;
  561. metadata.contentType = nil;
  562. metadata.customMetadata = nil;
  563. [self assertMetadataNil:metadata];
  564. metadata.contentEncoding = nil;
  565. XCTestExpectation *expectation =
  566. [self expectationWithDescription:@"testMetadataDictInitAndClear"];
  567. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  568. [ref updateMetadata:metadata
  569. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  570. XCTAssertNil(error);
  571. [self assertMetadataNil:updatedMetadata];
  572. XCTAssertNil(updatedMetadata.customMetadata);
  573. [expectation fulfill];
  574. }];
  575. [self waitForExpectations];
  576. }
  577. - (void)testResumeGetFile {
  578. XCTestExpectation *expectation = [self expectationWithDescription:@"testResumeGetFile"];
  579. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  580. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  581. NSURL *fileURL =
  582. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  583. __block long resumeAtBytes = 256 * 1024;
  584. __block long downloadedBytes = 0;
  585. __block double computationResult = 0;
  586. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  587. [task observeStatus:FIRStorageTaskStatusSuccess
  588. handler:^(FIRStorageTaskSnapshot *snapshot) {
  589. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  590. [expectation fulfill];
  591. }];
  592. [task observeStatus:FIRStorageTaskStatusProgress
  593. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  594. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  595. [[snapshot description] containsString:@"State: Resume"]);
  596. NSProgress *progress = snapshot.progress;
  597. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  598. downloadedBytes = (long)progress.completedUnitCount;
  599. if (progress.completedUnitCount > resumeAtBytes) {
  600. // Making sure the main run loop is busy.
  601. for (int i = 0; i < 500; ++i) {
  602. dispatch_async(dispatch_get_main_queue(), ^{
  603. computationResult = sqrt(INT_MAX - i);
  604. });
  605. }
  606. NSLog(@"Pausing");
  607. [task pause];
  608. resumeAtBytes = INT_MAX;
  609. }
  610. }];
  611. [task observeStatus:FIRStorageTaskStatusPause
  612. handler:^(FIRStorageTaskSnapshot *snapshot) {
  613. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  614. NSLog(@"Resuming");
  615. [task resume];
  616. }];
  617. [self waitForExpectations];
  618. XCTAssertEqual(INT_MAX, resumeAtBytes);
  619. XCTAssertEqualWithAccuracy(sqrt(INT_MAX - 499), computationResult, 0.1);
  620. }
  621. - (void)testResumeGetFileInBackgroundQueue {
  622. XCTestExpectation *expectation =
  623. [self expectationWithDescription:@"testResumeGetFileInBackgroundQueue"];
  624. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  625. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  626. NSURL *fileURL =
  627. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  628. __block long resumeAtBytes = 256 * 1024;
  629. __block long downloadedBytes = 0;
  630. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  631. [task observeStatus:FIRStorageTaskStatusSuccess
  632. handler:^(FIRStorageTaskSnapshot *snapshot) {
  633. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  634. [expectation fulfill];
  635. }];
  636. [task observeStatus:FIRStorageTaskStatusProgress
  637. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  638. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  639. [[snapshot description] containsString:@"State: Resume"]);
  640. NSProgress *progress = snapshot.progress;
  641. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  642. downloadedBytes = (long)progress.completedUnitCount;
  643. if (progress.completedUnitCount > resumeAtBytes) {
  644. NSLog(@"Pausing");
  645. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  646. [task pause];
  647. });
  648. resumeAtBytes = INT_MAX;
  649. }
  650. }];
  651. [task observeStatus:FIRStorageTaskStatusPause
  652. handler:^(FIRStorageTaskSnapshot *snapshot) {
  653. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  654. NSLog(@"Resuming");
  655. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  656. [task resume];
  657. });
  658. }];
  659. [self waitForExpectations];
  660. XCTAssertEqual(INT_MAX, resumeAtBytes);
  661. }
  662. - (void)testPagedListFiles {
  663. XCTestExpectation *expectation = [self expectationWithDescription:@"testPagedListFiles"];
  664. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  665. [ref listWithMaxResults:2
  666. completion:^(FIRStorageListResult *_Nullable listResult, NSError *_Nullable error) {
  667. XCTAssertNotNil(listResult);
  668. XCTAssertNil(error);
  669. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  670. XCTAssertEqualObjects(listResult.prefixes, @[]);
  671. XCTAssertNotNil(listResult.pageToken);
  672. [ref listWithMaxResults:2
  673. pageToken:listResult.pageToken
  674. completion:^(FIRStorageListResult *_Nullable listResult,
  675. NSError *_Nullable error) {
  676. XCTAssertNotNil(listResult);
  677. XCTAssertNil(error);
  678. XCTAssertEqualObjects(listResult.items, @[]);
  679. XCTAssertEqualObjects(listResult.prefixes,
  680. @[ [ref child:@"prefix"] ]);
  681. XCTAssertNil(listResult.pageToken);
  682. [expectation fulfill];
  683. }];
  684. }];
  685. [self waitForExpectations];
  686. }
  687. - (void)testListAllFiles {
  688. XCTestExpectation *expectation = [self expectationWithDescription:@"testListAllFiles"];
  689. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  690. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  691. NSError *_Nullable error) {
  692. XCTAssertNotNil(listResult);
  693. XCTAssertNil(error);
  694. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  695. XCTAssertEqualObjects(listResult.prefixes, @[ [ref child:@"prefix"] ]);
  696. XCTAssertNil(listResult.pageToken);
  697. [expectation fulfill];
  698. }];
  699. [self waitForExpectations];
  700. }
  701. - (void)testListFilesAtRoot {
  702. XCTestExpectation *expectation = [self expectationWithDescription:@"testListFilesAtRoot"];
  703. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  704. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  705. NSError *_Nullable error) {
  706. XCTAssertNotNil(listResult);
  707. XCTAssertNil(error);
  708. XCTAssertNil(listResult.pageToken);
  709. [expectation fulfill];
  710. }];
  711. [self waitForExpectations];
  712. }
  713. - (void)testCopyListResult {
  714. XCTestExpectation *expectation = [self expectationWithDescription:@"testCopyListResult"];
  715. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  716. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  717. NSError *_Nullable error) {
  718. XCTAssertNotNil(listResult);
  719. XCTAssertNil(error);
  720. XCTAssertNil(listResult.pageToken);
  721. FIRStorageListResult *listResult2 = listResult.copy;
  722. XCTAssertEqual(listResult.pageToken, listResult2.pageToken);
  723. XCTAssertNotEqual(listResult, listResult2);
  724. [expectation fulfill];
  725. }];
  726. [self waitForExpectations];
  727. }
  728. - (void)waitForExpectations {
  729. [self waitForExpectationsWithTimeout:kFIRStorageIntegrationTestTimeout
  730. handler:^(NSError *_Nullable error) {
  731. if (error) {
  732. NSLog(@"%@", error);
  733. }
  734. }];
  735. }
  736. @end