FIRStorageIntegrationTests.m 31 KB

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