FIRStorageIntegrationTests.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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"};
  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"}];
  512. // Update a subset of the metadata using the existing object.
  513. FIRStorageMetadata *metadata = updatedMetadata;
  514. metadata.contentType = @"content-type-b";
  515. metadata.customMetadata = @{@"a" : @"b", @"c" : @"d"};
  516. [ref updateMetadata:metadata
  517. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  518. XCTAssertNil(error);
  519. [self assertMetadata:updatedMetadata
  520. contentType:@"content-type-b"
  521. customMetadata:@{@"a" : @"b", @"c" : @"d"}];
  522. // Clear all metadata.
  523. FIRStorageMetadata *metadata = updatedMetadata;
  524. metadata.cacheControl = nil;
  525. metadata.contentDisposition = nil;
  526. metadata.contentEncoding = nil;
  527. metadata.contentLanguage = nil;
  528. metadata.contentType = nil;
  529. metadata.customMetadata = [NSDictionary dictionary];
  530. [ref updateMetadata:metadata
  531. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  532. XCTAssertNil(error);
  533. [self assertMetadataNil:updatedMetadata];
  534. [expectation fulfill];
  535. }];
  536. }];
  537. }];
  538. [self waitForExpectations];
  539. }
  540. - (void)testResumeGetFile {
  541. XCTestExpectation *expectation = [self expectationWithDescription:@"testResumeGetFile"];
  542. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  543. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  544. NSURL *fileURL =
  545. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  546. __block long resumeAtBytes = 256 * 1024;
  547. __block long downloadedBytes = 0;
  548. __block double computationResult = 0;
  549. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  550. [task observeStatus:FIRStorageTaskStatusSuccess
  551. handler:^(FIRStorageTaskSnapshot *snapshot) {
  552. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  553. [expectation fulfill];
  554. }];
  555. [task observeStatus:FIRStorageTaskStatusProgress
  556. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  557. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  558. [[snapshot description] containsString:@"State: Resume"]);
  559. NSProgress *progress = snapshot.progress;
  560. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  561. downloadedBytes = (long)progress.completedUnitCount;
  562. if (progress.completedUnitCount > resumeAtBytes) {
  563. // Making sure the main run loop is busy.
  564. for (int i = 0; i < 500; ++i) {
  565. dispatch_async(dispatch_get_main_queue(), ^{
  566. computationResult = sqrt(INT_MAX - i);
  567. });
  568. }
  569. NSLog(@"Pausing");
  570. [task pause];
  571. resumeAtBytes = INT_MAX;
  572. }
  573. }];
  574. [task observeStatus:FIRStorageTaskStatusPause
  575. handler:^(FIRStorageTaskSnapshot *snapshot) {
  576. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  577. NSLog(@"Resuming");
  578. [task resume];
  579. }];
  580. [self waitForExpectations];
  581. XCTAssertEqual(INT_MAX, resumeAtBytes);
  582. XCTAssertEqualWithAccuracy(sqrt(INT_MAX - 499), computationResult, 0.1);
  583. }
  584. - (void)testResumeGetFileInBackgroundQueue {
  585. XCTestExpectation *expectation =
  586. [self expectationWithDescription:@"testResumeGetFileInBackgroundQueue"];
  587. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  588. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  589. NSURL *fileURL =
  590. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  591. __block long resumeAtBytes = 256 * 1024;
  592. __block long downloadedBytes = 0;
  593. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  594. [task observeStatus:FIRStorageTaskStatusSuccess
  595. handler:^(FIRStorageTaskSnapshot *snapshot) {
  596. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  597. [expectation fulfill];
  598. }];
  599. [task observeStatus:FIRStorageTaskStatusProgress
  600. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  601. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  602. [[snapshot description] containsString:@"State: Resume"]);
  603. NSProgress *progress = snapshot.progress;
  604. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  605. downloadedBytes = (long)progress.completedUnitCount;
  606. if (progress.completedUnitCount > resumeAtBytes) {
  607. NSLog(@"Pausing");
  608. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  609. [task pause];
  610. });
  611. resumeAtBytes = INT_MAX;
  612. }
  613. }];
  614. [task observeStatus:FIRStorageTaskStatusPause
  615. handler:^(FIRStorageTaskSnapshot *snapshot) {
  616. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  617. NSLog(@"Resuming");
  618. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  619. [task resume];
  620. });
  621. }];
  622. [self waitForExpectations];
  623. XCTAssertEqual(INT_MAX, resumeAtBytes);
  624. }
  625. - (void)testPagedListFiles {
  626. XCTestExpectation *expectation = [self expectationWithDescription:@"testPagedListFiles"];
  627. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  628. [ref listWithMaxResults:2
  629. completion:^(FIRStorageListResult *_Nullable listResult, NSError *_Nullable error) {
  630. XCTAssertNotNil(listResult);
  631. XCTAssertNil(error);
  632. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  633. XCTAssertEqualObjects(listResult.prefixes, @[]);
  634. XCTAssertNotNil(listResult.pageToken);
  635. [ref listWithMaxResults:2
  636. pageToken:listResult.pageToken
  637. completion:^(FIRStorageListResult *_Nullable listResult,
  638. NSError *_Nullable error) {
  639. XCTAssertNotNil(listResult);
  640. XCTAssertNil(error);
  641. XCTAssertEqualObjects(listResult.items, @[]);
  642. XCTAssertEqualObjects(listResult.prefixes,
  643. @[ [ref child:@"prefix"] ]);
  644. XCTAssertNil(listResult.pageToken);
  645. [expectation fulfill];
  646. }];
  647. }];
  648. [self waitForExpectations];
  649. }
  650. - (void)testListAllFiles {
  651. XCTestExpectation *expectation = [self expectationWithDescription:@"testListAllFiles"];
  652. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  653. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  654. NSError *_Nullable error) {
  655. XCTAssertNotNil(listResult);
  656. XCTAssertNil(error);
  657. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  658. XCTAssertEqualObjects(listResult.prefixes, @[ [ref child:@"prefix"] ]);
  659. XCTAssertNil(listResult.pageToken);
  660. [expectation fulfill];
  661. }];
  662. [self waitForExpectations];
  663. }
  664. - (void)testListFilesAtRoot {
  665. XCTestExpectation *expectation = [self expectationWithDescription:@"testListFilesAtRoot"];
  666. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  667. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  668. NSError *_Nullable error) {
  669. XCTAssertNotNil(listResult);
  670. XCTAssertNil(error);
  671. XCTAssertNil(listResult.pageToken);
  672. [expectation fulfill];
  673. }];
  674. [self waitForExpectations];
  675. }
  676. - (void)testCopyListResult {
  677. XCTestExpectation *expectation = [self expectationWithDescription:@"testCopyListResult"];
  678. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  679. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  680. NSError *_Nullable error) {
  681. XCTAssertNotNil(listResult);
  682. XCTAssertNil(error);
  683. XCTAssertNil(listResult.pageToken);
  684. FIRStorageListResult *listResult2 = listResult.copy;
  685. XCTAssertEqual(listResult.pageToken, listResult2.pageToken);
  686. XCTAssertNotEqual(listResult, listResult2);
  687. [expectation fulfill];
  688. }];
  689. [self waitForExpectations];
  690. }
  691. - (void)waitForExpectations {
  692. [self waitForExpectationsWithTimeout:kFIRStorageIntegrationTestTimeout
  693. handler:^(NSError *_Nullable error) {
  694. if (error) {
  695. NSLog(@"%@", error);
  696. }
  697. }];
  698. }
  699. @end