FIRStorageIntegrationTests.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import <XCTest/XCTest.h>
  15. @import FirebaseStorage;
  16. #import <FirebaseAuth/FirebaseAuth.h>
  17. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  18. #import "FirebaseStorage/Tests/ObjCIntegration/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)testPutFileWithMetadata {
  278. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutFileWithMetaData"];
  279. FIRStorageReference *ref =
  280. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutFile"];
  281. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  282. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  283. NSURL *fileURL =
  284. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  285. [data writeToURL:fileURL atomically:YES];
  286. FIRStorageMetadata *putMetadata = [[FIRStorageMetadata alloc] init];
  287. putMetadata.contentType = @"text/plain";
  288. FIRStorageUploadTask *task = [ref putFile:fileURL
  289. metadata:putMetadata
  290. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  291. XCTAssertNotNil(metadata, "Metadata should not be nil");
  292. XCTAssertNil(error, "Error should be nil");
  293. }];
  294. __block long uploadedBytes = -1;
  295. [task observeStatus:FIRStorageTaskStatusSuccess
  296. handler:^(FIRStorageTaskSnapshot *snapshot) {
  297. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  298. [expectation fulfill];
  299. }];
  300. [task observeStatus:FIRStorageTaskStatusProgress
  301. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  302. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  303. [[snapshot description] containsString:@"State: Resume"]);
  304. NSProgress *progress = snapshot.progress;
  305. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, uploadedBytes);
  306. uploadedBytes = (long)progress.completedUnitCount;
  307. }];
  308. [self waitForExpectations];
  309. }
  310. - (void)testPutFileWithSpecialCharacters {
  311. XCTestExpectation *expectation =
  312. [self expectationWithDescription:@"testPutFileWithSpecialCharacters"];
  313. NSString *fileName = @"hello&+@_ .txt";
  314. FIRStorageReference *ref =
  315. [self.storage referenceWithPath:[@"ios/public/" stringByAppendingString:fileName]];
  316. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  317. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  318. NSURL *fileURL = [tmpDirURL URLByAppendingPathComponent:fileName];
  319. [data writeToURL:fileURL atomically:YES];
  320. [ref putFile:fileURL
  321. metadata:nil
  322. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  323. XCTAssertNotNil(metadata, "Metadata should not be nil");
  324. XCTAssertNil(error, "Error should be nil");
  325. XCTAssertEqualObjects(fileName, metadata.name);
  326. FIRStorageReference *download =
  327. [self.storage referenceWithPath:[@"ios/public/" stringByAppendingString:fileName]];
  328. [download metadataWithCompletion:^(FIRStorageMetadata *metadata, NSError *error) {
  329. XCTAssertNotNil(metadata, "Metadata should not be nil");
  330. XCTAssertNil(error, "Error should be nil");
  331. XCTAssertEqualObjects(fileName, metadata.name);
  332. [expectation fulfill];
  333. }];
  334. }];
  335. [self waitForExpectations];
  336. }
  337. - (void)testPutDataNoMetadata {
  338. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutDataNoMetadata"];
  339. FIRStorageReference *ref =
  340. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutDataNoMetadata"];
  341. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  342. [ref putData:data
  343. metadata:nil
  344. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  345. XCTAssertNotNil(metadata, "Metadata should not be nil");
  346. XCTAssertNil(error, "Error should be nil");
  347. [expectation fulfill];
  348. }];
  349. [self waitForExpectations];
  350. }
  351. - (void)testPutFileNoMetadata {
  352. XCTestExpectation *expectation = [self expectationWithDescription:@"testPutFileNoMetadata"];
  353. FIRStorageReference *ref =
  354. [self.storage referenceWithPath:@"ios/public/testUnauthenticatedSimplePutFileNoMetadata"];
  355. NSData *data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  356. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  357. NSURL *fileURL =
  358. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  359. [data writeToURL:fileURL atomically:YES];
  360. [ref putFile:fileURL
  361. metadata:nil
  362. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  363. XCTAssertNotNil(metadata, "Metadata should not be nil");
  364. XCTAssertNil(error, "Error should be nil");
  365. [expectation fulfill];
  366. }];
  367. [self waitForExpectations];
  368. }
  369. - (void)testGetData {
  370. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetData"];
  371. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  372. [ref dataWithMaxSize:1 * 1024 * 1024
  373. completion:^(NSData *data, NSError *error) {
  374. XCTAssertNotNil(data, "Data should not be nil");
  375. XCTAssertNil(error, "Error should be nil");
  376. [expectation fulfill];
  377. }];
  378. [self waitForExpectations];
  379. }
  380. - (void)testGetDataInBackgroundQueue {
  381. XCTestExpectation *expectation =
  382. [self expectationWithDescription:@"testGetDataInBackgroundQueue"];
  383. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  384. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  385. [ref dataWithMaxSize:1 * 1024 * 1024
  386. completion:^(NSData *data, NSError *error) {
  387. XCTAssertNotNil(data, "Data should not be nil");
  388. XCTAssertNil(error, "Error should be nil");
  389. [expectation fulfill];
  390. }];
  391. });
  392. [self waitForExpectations];
  393. }
  394. - (void)testGetDataWithCustomCallbackQueue {
  395. XCTestExpectation *expectation =
  396. [self expectationWithDescription:@"testUnauthenticatedGetDataInCustomCallbackQueue"];
  397. NSString *callbackQueueLabelString = @"customCallbackQueue";
  398. const char *callbackQueueLabel = [callbackQueueLabelString UTF8String];
  399. const void *callbackQueueKey = callbackQueueLabel;
  400. dispatch_queue_t callbackQueue = dispatch_queue_create(callbackQueueLabel, NULL);
  401. dispatch_queue_set_specific(callbackQueue, callbackQueueKey, (void *)callbackQueueKey, NULL);
  402. _storage.callbackQueue = callbackQueue;
  403. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  404. [ref dataWithMaxSize:1 * 1024 * 1024
  405. completion:^(NSData *data, NSError *error) {
  406. XCTAssertNotNil(data, "Data should not be nil");
  407. XCTAssertNil(error, "Error should be nil");
  408. char *currentQueueLabel = dispatch_get_specific(callbackQueueKey);
  409. NSString *currentQueueLabelString = [NSString stringWithUTF8String:currentQueueLabel];
  410. XCTAssertEqualObjects(currentQueueLabelString, callbackQueueLabelString);
  411. [expectation fulfill];
  412. // Reset the callbackQueue to default (main queue).
  413. self.storage.callbackQueue = dispatch_get_main_queue();
  414. dispatch_queue_set_specific(callbackQueue, callbackQueueKey, NULL, NULL);
  415. }];
  416. [self waitForExpectations];
  417. }
  418. - (void)testGetDataTooSmall {
  419. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetDataTooSmall"];
  420. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  421. /// Only allow 1kB size, which is smaller than our file
  422. [ref dataWithMaxSize:1 * 1024
  423. completion:^(NSData *data, NSError *error) {
  424. XCTAssertNil(data);
  425. XCTAssertEqual(error.code, FIRStorageErrorCodeDownloadSizeExceeded);
  426. [expectation fulfill];
  427. }];
  428. [self waitForExpectations];
  429. }
  430. - (void)testGetDownloadURL {
  431. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetDownloadURL"];
  432. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  433. // Download URL format is
  434. // "https://firebasestorage.googleapis.com:443/v0/b/{bucket}/o/{path}?alt=media&token={token}"
  435. NSString *downloadURLPattern =
  436. @"^https:\\/\\/firebasestorage.googleapis.com:443\\/v0\\/b\\/[^\\/]*\\/o\\/"
  437. @"ios%2Fpublic%2F1mb\\?alt=media&token=[a-z0-9-]*$";
  438. [ref downloadURLWithCompletion:^(NSURL *downloadURL, NSError *error) {
  439. XCTAssertNil(error);
  440. NSRegularExpression *testRegex =
  441. [NSRegularExpression regularExpressionWithPattern:downloadURLPattern options:0 error:nil];
  442. NSString *urlString = [downloadURL absoluteString];
  443. XCTAssertEqual([testRegex numberOfMatchesInString:urlString
  444. options:0
  445. range:NSMakeRange(0, [urlString length])],
  446. 1);
  447. [expectation fulfill];
  448. }];
  449. [self waitForExpectations];
  450. }
  451. - (void)testGetFile {
  452. XCTestExpectation *expectation = [self expectationWithDescription:@"testGetFile"];
  453. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/helloworld"];
  454. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  455. NSURL *fileURL =
  456. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  457. NSData *fileData = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
  458. [ref putData:fileData
  459. metadata:nil
  460. completion:^(FIRStorageMetadata *metadata, NSError *error) {
  461. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  462. [task observeStatus:FIRStorageTaskStatusSuccess
  463. handler:^(FIRStorageTaskSnapshot *snapshot) {
  464. [ref dataWithMaxSize:fileData.length
  465. completion:^(NSData *_Nullable data, NSError *_Nullable error) {
  466. XCTAssertEqualObjects(data, fileData);
  467. [expectation fulfill];
  468. }];
  469. }];
  470. [task observeStatus:FIRStorageTaskStatusProgress
  471. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  472. NSProgress *progress = snapshot.progress;
  473. NSLog(@"%lld of %lld", progress.completedUnitCount, progress.totalUnitCount);
  474. }];
  475. [task observeStatus:FIRStorageTaskStatusFailure
  476. handler:^(FIRStorageTaskSnapshot *snapshot) {
  477. XCTAssertNil(snapshot.error);
  478. }];
  479. }];
  480. [self waitForExpectations];
  481. }
  482. - (void)testCancelDownload {
  483. XCTestExpectation *expectation = [self expectationWithDescription:@"testCancelDownload"];
  484. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  485. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  486. NSURL *fileURL =
  487. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"dat"];
  488. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  489. // Don't fulfill twice if a second observe failure happens before the cancel completes.
  490. BOOL __block fulfilled = NO;
  491. [task observeStatus:FIRStorageTaskStatusFailure
  492. handler:^(FIRStorageTaskSnapshot *snapshot) {
  493. XCTAssertTrue([[snapshot description] containsString:@"State: Failed"]);
  494. if (!fulfilled) {
  495. fulfilled = YES;
  496. XCTAssertEqual(snapshot.error.code, FIRStorageErrorCodeCancelled);
  497. [expectation fulfill];
  498. }
  499. }];
  500. [task observeStatus:FIRStorageTaskStatusProgress
  501. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  502. [task cancel];
  503. }];
  504. [self waitForExpectations];
  505. }
  506. - (void)assertMetadata:(FIRStorageMetadata *)actualMetadata
  507. contentType:(NSString *)expectedContentType
  508. customMetadata:(NSDictionary *)expectedCustomMetadata {
  509. XCTAssertEqualObjects(actualMetadata.cacheControl, @"cache-control");
  510. XCTAssertEqualObjects(actualMetadata.contentDisposition, @"content-disposition");
  511. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"gzip");
  512. XCTAssertEqualObjects(actualMetadata.contentLanguage, @"de");
  513. XCTAssertEqualObjects(actualMetadata.contentType, expectedContentType);
  514. XCTAssertEqualObjects(actualMetadata.name, @"1mb");
  515. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  516. for (NSString *key in expectedCustomMetadata) {
  517. XCTAssertEqualObjects([actualMetadata.customMetadata objectForKey:key],
  518. [expectedCustomMetadata objectForKey:key]);
  519. }
  520. }
  521. - (void)assertMetadataNil:(FIRStorageMetadata *)actualMetadata {
  522. XCTAssertNil(actualMetadata.cacheControl);
  523. XCTAssertNil(actualMetadata.contentDisposition);
  524. XCTAssertEqualObjects(actualMetadata.contentEncoding, @"identity");
  525. XCTAssertNil(actualMetadata.contentLanguage);
  526. XCTAssertNil(actualMetadata.contentType);
  527. XCTAssertTrue([actualMetadata.md5Hash length] == 24);
  528. XCTAssertNil(actualMetadata.customMetadata);
  529. }
  530. - (void)testUpdateMetadata {
  531. XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdateMetadata"];
  532. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  533. // Update all available metadata
  534. FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
  535. metadata.cacheControl = @"cache-control";
  536. metadata.contentDisposition = @"content-disposition";
  537. metadata.contentEncoding = @"gzip";
  538. metadata.contentLanguage = @"de";
  539. metadata.contentType = @"content-type-a";
  540. metadata.customMetadata = @{@"a" : @"b", @"y" : @"z"};
  541. [ref updateMetadata:metadata
  542. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  543. XCTAssertNil(error);
  544. [self assertMetadata:updatedMetadata
  545. contentType:@"content-type-a"
  546. customMetadata:@{@"a" : @"b", @"y" : @"z"}];
  547. // Update a subset of the metadata using the existing object.
  548. FIRStorageMetadata *metadata = updatedMetadata;
  549. metadata.contentType = @"content-type-b";
  550. metadata.customMetadata = @{@"c" : @"d", @"y" : @""};
  551. [ref updateMetadata:metadata
  552. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  553. XCTAssertNil(error);
  554. [self assertMetadata:updatedMetadata
  555. contentType:@"content-type-b"
  556. // "a" is now deleted and the empty string for "y" remains.
  557. customMetadata:@{@"c" : @"d", @"y" : @""}];
  558. // Clear all metadata with nils.
  559. FIRStorageMetadata *metadata = updatedMetadata;
  560. metadata.cacheControl = nil;
  561. metadata.contentDisposition = nil;
  562. metadata.contentEncoding = nil;
  563. metadata.contentLanguage = nil;
  564. metadata.contentType = nil;
  565. metadata.customMetadata = nil;
  566. [ref updateMetadata:metadata
  567. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  568. XCTAssertNil(error);
  569. [self assertMetadataNil:updatedMetadata];
  570. XCTAssertNil(updatedMetadata.customMetadata);
  571. [expectation fulfill];
  572. }];
  573. }];
  574. }];
  575. [self waitForExpectations];
  576. }
  577. - (void)testMetadataDictInitAndClear {
  578. FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] initWithDictionary:@{
  579. @"cacheControl" : @"cache-control",
  580. @"contentDisposition" : @"content-disposition",
  581. @"contentEncoding" : @"gzip",
  582. @"contentLanguage" : @"de",
  583. @"contentType" : @"content-type-a",
  584. @"md5Hash" : @"123456789012345678901234", // length 24
  585. @"name" : @"1mb",
  586. @"metadata" : @{@"a" : @"b", @"y" : @"z"}
  587. }];
  588. [self assertMetadata:metadata
  589. contentType:@"content-type-a"
  590. customMetadata:@{@"a" : @"b", @"y" : @"z"}];
  591. metadata.cacheControl = nil;
  592. metadata.contentDisposition = nil;
  593. metadata.contentEncoding = @"identity";
  594. metadata.contentLanguage = nil;
  595. metadata.contentType = nil;
  596. metadata.customMetadata = nil;
  597. [self assertMetadataNil:metadata];
  598. metadata.contentEncoding = nil;
  599. XCTestExpectation *expectation =
  600. [self expectationWithDescription:@"testMetadataDictInitAndClear"];
  601. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  602. [ref updateMetadata:metadata
  603. completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
  604. XCTAssertNil(error);
  605. [self assertMetadataNil:updatedMetadata];
  606. XCTAssertNil(updatedMetadata.customMetadata);
  607. [expectation fulfill];
  608. }];
  609. [self waitForExpectations];
  610. }
  611. - (void)testResumeGetFile {
  612. XCTestExpectation *expectation = [self expectationWithDescription:@"testResumeGetFile"];
  613. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  614. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  615. NSURL *fileURL =
  616. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  617. __block long resumeAtBytes = 256 * 1024;
  618. __block long downloadedBytes = 0;
  619. __block double computationResult = 0;
  620. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  621. [task observeStatus:FIRStorageTaskStatusSuccess
  622. handler:^(FIRStorageTaskSnapshot *snapshot) {
  623. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  624. [expectation fulfill];
  625. }];
  626. [task observeStatus:FIRStorageTaskStatusProgress
  627. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  628. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  629. [[snapshot description] containsString:@"State: Resume"]);
  630. NSProgress *progress = snapshot.progress;
  631. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  632. downloadedBytes = (long)progress.completedUnitCount;
  633. if (progress.completedUnitCount > resumeAtBytes) {
  634. // Making sure the main run loop is busy.
  635. for (int i = 0; i < 500; ++i) {
  636. dispatch_async(dispatch_get_main_queue(), ^{
  637. computationResult = sqrt(INT_MAX - i);
  638. });
  639. }
  640. NSLog(@"Pausing");
  641. [task pause];
  642. resumeAtBytes = INT_MAX;
  643. }
  644. }];
  645. [task observeStatus:FIRStorageTaskStatusPause
  646. handler:^(FIRStorageTaskSnapshot *snapshot) {
  647. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  648. NSLog(@"Resuming");
  649. [task resume];
  650. }];
  651. [self waitForExpectations];
  652. XCTAssertEqual(INT_MAX, resumeAtBytes);
  653. XCTAssertEqualWithAccuracy(sqrt(INT_MAX - 499), computationResult, 0.1);
  654. }
  655. - (void)testResumeGetFileInBackgroundQueue {
  656. XCTestExpectation *expectation =
  657. [self expectationWithDescription:@"testResumeGetFileInBackgroundQueue"];
  658. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/1mb"];
  659. NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  660. NSURL *fileURL =
  661. [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
  662. __block long resumeAtBytes = 256 * 1024;
  663. __block long downloadedBytes = 0;
  664. FIRStorageDownloadTask *task = [ref writeToFile:fileURL];
  665. [task observeStatus:FIRStorageTaskStatusSuccess
  666. handler:^(FIRStorageTaskSnapshot *snapshot) {
  667. XCTAssertEqualObjects([snapshot description], @"<State: Success>");
  668. [expectation fulfill];
  669. }];
  670. [task observeStatus:FIRStorageTaskStatusProgress
  671. handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) {
  672. XCTAssertTrue([[snapshot description] containsString:@"State: Progress"] ||
  673. [[snapshot description] containsString:@"State: Resume"]);
  674. NSProgress *progress = snapshot.progress;
  675. XCTAssertGreaterThanOrEqual(progress.completedUnitCount, downloadedBytes);
  676. downloadedBytes = (long)progress.completedUnitCount;
  677. if (progress.completedUnitCount > resumeAtBytes) {
  678. NSLog(@"Pausing");
  679. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  680. [task pause];
  681. });
  682. resumeAtBytes = INT_MAX;
  683. }
  684. }];
  685. [task observeStatus:FIRStorageTaskStatusPause
  686. handler:^(FIRStorageTaskSnapshot *snapshot) {
  687. XCTAssertEqualObjects([snapshot description], @"<State: Paused>");
  688. NSLog(@"Resuming");
  689. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  690. [task resume];
  691. });
  692. }];
  693. [self waitForExpectations];
  694. XCTAssertEqual(INT_MAX, resumeAtBytes);
  695. }
  696. - (void)testPagedListFiles {
  697. XCTestExpectation *expectation = [self expectationWithDescription:@"testPagedListFiles"];
  698. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  699. [ref listWithMaxResults:2
  700. completion:^(FIRStorageListResult *_Nullable listResult, NSError *_Nullable error) {
  701. XCTAssertNotNil(listResult);
  702. XCTAssertNil(error);
  703. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  704. XCTAssertEqualObjects(listResult.prefixes, @[]);
  705. XCTAssertNotNil(listResult.pageToken);
  706. [ref listWithMaxResults:2
  707. pageToken:listResult.pageToken
  708. completion:^(FIRStorageListResult *_Nullable listResult,
  709. NSError *_Nullable error) {
  710. XCTAssertNotNil(listResult);
  711. XCTAssertNil(error);
  712. XCTAssertEqualObjects(listResult.items, @[]);
  713. XCTAssertEqualObjects(listResult.prefixes,
  714. @[ [ref child:@"prefix"] ]);
  715. XCTAssertNil(listResult.pageToken);
  716. [expectation fulfill];
  717. }];
  718. }];
  719. [self waitForExpectations];
  720. }
  721. - (void)testListAllFiles {
  722. XCTestExpectation *expectation = [self expectationWithDescription:@"testListAllFiles"];
  723. FIRStorageReference *ref = [self.storage referenceWithPath:@"ios/public/list"];
  724. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  725. NSError *_Nullable error) {
  726. XCTAssertNotNil(listResult);
  727. XCTAssertNil(error);
  728. XCTAssertEqualObjects(listResult.items, (@[ [ref child:@"a"], [ref child:@"b"] ]));
  729. XCTAssertEqualObjects(listResult.prefixes, @[ [ref child:@"prefix"] ]);
  730. XCTAssertNil(listResult.pageToken);
  731. [expectation fulfill];
  732. }];
  733. [self waitForExpectations];
  734. }
  735. - (void)testListFilesAtRoot {
  736. XCTestExpectation *expectation = [self expectationWithDescription:@"testListFilesAtRoot"];
  737. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  738. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  739. NSError *_Nullable error) {
  740. XCTAssertNotNil(listResult);
  741. XCTAssertNil(error);
  742. XCTAssertNil(listResult.pageToken);
  743. [expectation fulfill];
  744. }];
  745. [self waitForExpectations];
  746. }
  747. - (void)testCopyListResult {
  748. XCTestExpectation *expectation = [self expectationWithDescription:@"testCopyListResult"];
  749. FIRStorageReference *ref = [self.storage referenceWithPath:@""];
  750. [ref listAllWithCompletion:^(FIRStorageListResult *_Nullable listResult,
  751. NSError *_Nullable error) {
  752. XCTAssertNotNil(listResult);
  753. XCTAssertNil(error);
  754. XCTAssertNil(listResult.pageToken);
  755. FIRStorageListResult *listResult2 = listResult.copy;
  756. XCTAssertEqual(listResult.pageToken, listResult2.pageToken);
  757. XCTAssertNotEqual(listResult, listResult2);
  758. [expectation fulfill];
  759. }];
  760. [self waitForExpectations];
  761. }
  762. - (void)waitForExpectations {
  763. [self waitForExpectationsWithTimeout:kFIRStorageIntegrationTestTimeout
  764. handler:^(NSError *_Nullable error) {
  765. if (error) {
  766. NSLog(@"%@", error);
  767. }
  768. }];
  769. }
  770. @end