StorageAsyncAwait.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Copyright 2021 Google LLC
  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
  15. import FirebaseCore
  16. import FirebaseStorage
  17. import XCTest
  18. @available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, *)
  19. class StorageAsyncAwait: StorageIntegrationCommon {
  20. func testGetMetadata() async throws {
  21. let ref = storage.reference().child("ios/public/1mb2")
  22. let result = try await ref.getMetadata()
  23. XCTAssertNotNil(result)
  24. }
  25. func testUpdateMetadata() async throws {
  26. let meta = StorageMetadata()
  27. meta.contentType = "lol/custom"
  28. meta.customMetadata = ["lol": "custom metadata is neat",
  29. "ちかてつ": "🚇",
  30. "shinkansen": "新幹線"]
  31. let ref = storage.reference(withPath: "ios/public/1mb2")
  32. let metadata = try await ref.updateMetadata(meta)
  33. XCTAssertEqual(meta.contentType, metadata.contentType)
  34. XCTAssertEqual(meta.customMetadata!["lol"], metadata.customMetadata!["lol"])
  35. XCTAssertEqual(meta.customMetadata!["ちかてつ"], metadata.customMetadata!["ちかてつ"])
  36. XCTAssertEqual(meta.customMetadata!["shinkansen"],
  37. metadata.customMetadata!["shinkansen"])
  38. }
  39. func testDelete() async throws {
  40. let objectLocation = "ios/public/fileToDelete"
  41. let ref = storage.reference(withPath: objectLocation)
  42. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  43. let result = try await ref.putDataAsync(data)
  44. XCTAssertNotNil(result)
  45. _ = try await ref.delete()
  46. // Next delete should fail and verify the first delete succeeded.
  47. var caughtError = false
  48. do {
  49. _ = try await ref.delete()
  50. } catch {
  51. caughtError = true
  52. let nsError = error as NSError
  53. XCTAssertEqual(nsError.code, StorageErrorCode.objectNotFound.rawValue)
  54. XCTAssertEqual(nsError.userInfo["ResponseErrorCode"] as? Int, 404)
  55. let underlyingError = try XCTUnwrap(nsError.userInfo[NSUnderlyingErrorKey] as? NSError)
  56. XCTAssertEqual(underlyingError.code, 404)
  57. XCTAssertEqual(underlyingError.domain, "com.google.HTTPStatus")
  58. }
  59. XCTAssertTrue(caughtError)
  60. }
  61. func testDeleteAfterPut() async throws {
  62. let ref = storage.reference(withPath: "ios/public/fileToDelete")
  63. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  64. let result = try await ref.putDataAsync(data)
  65. XCTAssertNotNil(result)
  66. let result2: Void = try await ref.delete()
  67. XCTAssertNotNil(result2)
  68. }
  69. func testSimplePutData() async throws {
  70. let ref = storage.reference(withPath: "ios/public/testBytesUpload")
  71. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  72. let result = try await ref.putDataAsync(data)
  73. XCTAssertNotNil(result)
  74. }
  75. func testSimplePutSpecialCharacter() async throws {
  76. let ref = storage.reference(withPath: "ios/public/-._~!$'()*,=:@&+;")
  77. let data = try XCTUnwrap("Hello Swift World-._~!$'()*,=:@&+;".data(using: .utf8),
  78. "Data construction failed")
  79. let result = try await ref.putDataAsync(data)
  80. XCTAssertNotNil(result)
  81. }
  82. func testSimplePutDataInBackgroundQueue() async throws {
  83. actor Background {
  84. func uploadData(_ ref: StorageReference) async throws -> StorageMetadata {
  85. let data = try XCTUnwrap(
  86. "Hello Swift World".data(using: .utf8),
  87. "Data construction failed"
  88. )
  89. XCTAssertFalse(Thread.isMainThread)
  90. return try await ref.putDataAsync(data)
  91. }
  92. }
  93. let ref = storage.reference(withPath: "ios/public/testBytesUpload")
  94. let result = try await Background().uploadData(ref)
  95. XCTAssertNotNil(result)
  96. }
  97. func testSimplePutEmptyData() async throws {
  98. let ref = storage.reference(withPath: "ios/public/testSimplePutEmptyData")
  99. let data = Data()
  100. let result = try await ref.putDataAsync(data)
  101. XCTAssertNotNil(result)
  102. }
  103. func testSimplePutDataUnauthorized() async throws {
  104. let objectLocation = "ios/private/secretfile.txt"
  105. let ref = storage.reference(withPath: objectLocation)
  106. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  107. do {
  108. _ = try await ref.putDataAsync(data)
  109. XCTFail("Unexpected success from unauthorized putData")
  110. } catch let StorageError.unauthorized(bucket, object) {
  111. XCTAssertEqual(bucket, "ios-opensource-samples.appspot.com")
  112. XCTAssertEqual(object, objectLocation)
  113. } catch {
  114. XCTFail("error failed to convert to StorageError.unauthorized")
  115. }
  116. }
  117. func testAttemptToUploadDirectoryShouldFail() async throws {
  118. // This `.numbers` file is actually a directory.
  119. let fileName = "HomeImprovement.numbers"
  120. let bundle = Bundle(for: StorageIntegrationCommon.self)
  121. let fileURL = try XCTUnwrap(bundle.url(forResource: fileName, withExtension: ""),
  122. "Failed to get filePath")
  123. let ref = storage.reference(withPath: "ios/public/" + fileName)
  124. do {
  125. _ = try await ref.putFileAsync(from: fileURL)
  126. XCTFail("Unexpected success from putFile of a directory")
  127. } catch let StorageError.unknown(reason) {
  128. XCTAssertTrue(reason.starts(with: "File at URL:"))
  129. XCTAssertTrue(reason.hasSuffix(
  130. "is not reachable. Ensure file URL is not a directory, symbolic link, or invalid url."
  131. ))
  132. } catch {
  133. XCTFail("error failed to convert to StorageError.unknown")
  134. }
  135. }
  136. func testPutFileWithSpecialCharacters() async throws {
  137. let fileName = "hello&+@_ .txt"
  138. let ref = storage.reference(withPath: "ios/public/" + fileName)
  139. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  140. let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory())
  141. let fileURL = tmpDirURL.appendingPathComponent(#function + "hello.txt")
  142. try data.write(to: fileURL, options: .atomicWrite)
  143. let metadata = try await ref.putFileAsync(from: fileURL)
  144. XCTAssertEqual(fileName, metadata.name)
  145. let result = try await ref.getMetadata()
  146. XCTAssertNotNil(result)
  147. }
  148. func testSimplePutDataNoMetadata() async throws {
  149. let ref = storage.reference(withPath: "ios/public/testSimplePutDataNoMetadata")
  150. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  151. let result = try await ref.putDataAsync(data)
  152. XCTAssertNotNil(result)
  153. }
  154. func testSimplePutFileNoMetadata() async throws {
  155. let fileName = "hello&+@_ .txt"
  156. let ref = storage.reference(withPath: "ios/public/" + fileName)
  157. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  158. let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory())
  159. let fileURL = tmpDirURL.appendingPathComponent("hello.txt")
  160. try data.write(to: fileURL, options: .atomicWrite)
  161. let result = try await ref.putFileAsync(from: fileURL)
  162. XCTAssertNotNil(result)
  163. }
  164. func testSimplePutFileWithAsyncProgress() async throws {
  165. var checkedProgress = false
  166. let ref = storage.reference(withPath: "ios/public/testSimplePutFile")
  167. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  168. let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory())
  169. let fileURL = tmpDirURL.appendingPathComponent(#function + "hello.txt")
  170. try data.write(to: fileURL, options: .atomicWrite)
  171. var uploadedBytes: Int64 = -1
  172. let successMetadata = try await ref.putFileAsync(from: fileURL) { progress in
  173. if let completed = progress?.completedUnitCount {
  174. checkedProgress = true
  175. XCTAssertGreaterThanOrEqual(completed, uploadedBytes)
  176. uploadedBytes = completed
  177. }
  178. }
  179. XCTAssertEqual(successMetadata.size, 17)
  180. XCTAssertTrue(checkedProgress)
  181. }
  182. func testSimpleGetData() async throws {
  183. let ref = storage.reference(withPath: "ios/public/1mb2")
  184. let result = try await ref.data(maxSize: 1024 * 1024)
  185. XCTAssertNotNil(result)
  186. }
  187. func testSimpleGetDataWithTask() async throws {
  188. let ref = storage.reference(withPath: "ios/public/1mb2")
  189. let result = try await ref.data(maxSize: 1024 * 1024)
  190. XCTAssertNotNil(result)
  191. }
  192. func testSimpleGetDataInBackgroundQueue() async throws {
  193. actor Background {
  194. func data(from ref: StorageReference) async throws -> Data {
  195. XCTAssertFalse(Thread.isMainThread)
  196. return try await ref.data(maxSize: 1024 * 1024)
  197. }
  198. }
  199. let ref = storage.reference(withPath: "ios/public/1mb2")
  200. let result = try await Background().data(from: ref)
  201. XCTAssertNotNil(result)
  202. }
  203. func testSimpleGetDataTooSmall() async {
  204. let ref = storage.reference(withPath: "ios/public/1mb2")
  205. let max: Int64 = 1024
  206. do {
  207. _ = try await ref.data(maxSize: max)
  208. XCTFail("Unexpected success from getData too small")
  209. } catch let StorageError.downloadSizeExceeded(total, maxSize) {
  210. XCTAssertEqual(total, 1_048_576)
  211. XCTAssertEqual(maxSize, max)
  212. } catch {
  213. XCTFail("error failed to convert to StorageError.downloadSizeExceeded")
  214. }
  215. }
  216. func testSimpleGetDownloadURL() async throws {
  217. let ref = storage.reference(withPath: "ios/public/1mb2")
  218. // Download URL format is
  219. // "https://firebasestorage.googleapis.com:443/v0/b/{bucket}/o/{path}?alt=media&token={token}"
  220. let downloadURLPattern =
  221. "^https:\\/\\/firebasestorage.googleapis.com:443\\/v0\\/b\\/[^\\/]*\\/o\\/" +
  222. "ios%2Fpublic%2F1mb2\\?alt=media&token=[a-z0-9-]*$"
  223. let downloadURL = try await ref.downloadURL()
  224. let testRegex = try NSRegularExpression(pattern: downloadURLPattern)
  225. let urlString = downloadURL.absoluteString
  226. let range = NSRange(location: 0, length: urlString.count)
  227. XCTAssertNotNil(testRegex.firstMatch(in: urlString, options: [], range: range))
  228. }
  229. func testAsyncWrite() async throws {
  230. let ref = storage.reference(withPath: "ios/public/helloworld" + #function)
  231. let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory())
  232. let fileURL = tmpDirURL.appendingPathComponent(#function + "hello.txt")
  233. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  234. _ = try await ref.putDataAsync(data)
  235. let url = try await ref.writeAsync(toFile: fileURL)
  236. XCTAssertEqual(url.lastPathComponent, #function + "hello.txt")
  237. }
  238. func testSimpleGetFile() throws {
  239. let expectation = self.expectation(description: #function)
  240. let ref = storage.reference(withPath: "ios/public/helloworld" + #function)
  241. let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory())
  242. let fileURL = tmpDirURL.appendingPathComponent(#function + "hello.txt")
  243. let data = try XCTUnwrap("Hello Swift World".data(using: .utf8), "Data construction failed")
  244. Task {
  245. _ = try await ref.putDataAsync(data)
  246. let task = ref.write(toFile: fileURL)
  247. task.observe(StorageTaskStatus.success) { snapshot in
  248. do {
  249. let stringData = try String(contentsOf: fileURL, encoding: .utf8)
  250. XCTAssertEqual(stringData, "Hello Swift World")
  251. XCTAssertEqual(snapshot.description, "<State: Success>")
  252. } catch {
  253. XCTFail("Error processing success snapshot")
  254. }
  255. expectation.fulfill()
  256. }
  257. task.observe(StorageTaskStatus.progress) { snapshot in
  258. XCTAssertNil(snapshot.error, "Error should be nil")
  259. guard snapshot.progress != nil else {
  260. XCTFail("Missing progress")
  261. return
  262. }
  263. }
  264. task.observe(StorageTaskStatus.failure) { snapshot in
  265. XCTAssertNil(snapshot.error, "Error should be nil")
  266. }
  267. }
  268. waitForExpectations()
  269. }
  270. func testSimpleGetFileWithAsyncProgressCallbackAPI() async throws {
  271. var checkedProgress = false
  272. let ref = storage.reference().child("ios/public/1mb")
  273. let url = URL(fileURLWithPath: "\(NSTemporaryDirectory())/hello.txt")
  274. let fileURL = url
  275. var downloadedBytes: Int64 = 0
  276. var resumeAtBytes = 256 * 1024
  277. let successURL = try await ref.writeAsync(toFile: fileURL) { progress in
  278. if let completed = progress?.completedUnitCount {
  279. checkedProgress = true
  280. XCTAssertGreaterThanOrEqual(completed, downloadedBytes)
  281. downloadedBytes = completed
  282. if completed > resumeAtBytes {
  283. resumeAtBytes = Int.max
  284. }
  285. }
  286. }
  287. XCTAssertTrue(checkedProgress)
  288. XCTAssertEqual(successURL, url)
  289. XCTAssertEqual(resumeAtBytes, Int.max)
  290. }
  291. private func assertMetadata(actualMetadata: StorageMetadata,
  292. expectedContentType: String,
  293. expectedCustomMetadata: [String: String]) {
  294. XCTAssertEqual(actualMetadata.cacheControl, "cache-control")
  295. XCTAssertEqual(actualMetadata.contentDisposition, "content-disposition")
  296. XCTAssertEqual(actualMetadata.contentEncoding, "gzip")
  297. XCTAssertEqual(actualMetadata.contentLanguage, "de")
  298. XCTAssertEqual(actualMetadata.contentType, expectedContentType)
  299. XCTAssertEqual(actualMetadata.md5Hash?.count, 24)
  300. for (key, value) in expectedCustomMetadata {
  301. XCTAssertEqual(actualMetadata.customMetadata![key], value)
  302. }
  303. }
  304. private func assertMetadataNil(actualMetadata: StorageMetadata) {
  305. XCTAssertNil(actualMetadata.cacheControl)
  306. XCTAssertNil(actualMetadata.contentDisposition)
  307. XCTAssertEqual(actualMetadata.contentEncoding, "identity")
  308. XCTAssertNil(actualMetadata.contentLanguage)
  309. XCTAssertNil(actualMetadata.contentType)
  310. XCTAssertEqual(actualMetadata.md5Hash?.count, 24)
  311. XCTAssertNil(actualMetadata.customMetadata)
  312. }
  313. func testUpdateMetadata2() async throws {
  314. let ref = storage.reference(withPath: "ios/public/1mb2")
  315. let metadata = StorageMetadata()
  316. metadata.cacheControl = "cache-control"
  317. metadata.contentDisposition = "content-disposition"
  318. metadata.contentEncoding = "gzip"
  319. metadata.contentLanguage = "de"
  320. metadata.contentType = "content-type-a"
  321. metadata.customMetadata = ["a": "b"]
  322. let updatedMetadata = try await ref.updateMetadata(metadata)
  323. assertMetadata(actualMetadata: updatedMetadata,
  324. expectedContentType: "content-type-a",
  325. expectedCustomMetadata: ["a": "b"])
  326. let metadata2 = updatedMetadata
  327. metadata2.contentType = "content-type-b"
  328. metadata2.customMetadata = ["a": "b", "c": "d"]
  329. let metadata3 = try await ref.updateMetadata(metadata2)
  330. assertMetadata(actualMetadata: metadata3,
  331. expectedContentType: "content-type-b",
  332. expectedCustomMetadata: ["a": "b", "c": "d"])
  333. metadata.cacheControl = nil
  334. metadata.contentDisposition = nil
  335. metadata.contentEncoding = nil
  336. metadata.contentLanguage = nil
  337. metadata.contentType = nil
  338. metadata.customMetadata = nil
  339. let metadata4 = try await ref.updateMetadata(metadata)
  340. XCTAssertNotNil(metadata4)
  341. }
  342. func testPagedListFiles() async throws {
  343. let ref = storage.reference(withPath: "ios/public/list")
  344. let listResult = try await ref.list(maxResults: 2)
  345. XCTAssertEqual(listResult.items, [ref.child("a"), ref.child("b")])
  346. XCTAssertEqual(listResult.prefixes, [])
  347. let pageToken = try XCTUnwrap(listResult.pageToken)
  348. let listResult2 = try await ref.list(maxResults: 2, pageToken: pageToken)
  349. XCTAssertEqual(listResult2.items, [])
  350. XCTAssertEqual(listResult2.prefixes, [ref.child("prefix")])
  351. XCTAssertNil(listResult2.pageToken, "pageToken should be nil")
  352. }
  353. func testPagedListFilesError() async throws {
  354. let ref = storage.reference(withPath: "ios/public/list")
  355. do {
  356. let _: StorageListResult = try await ref.list(maxResults: 22222)
  357. XCTFail("Unexpected success from ref.list")
  358. } catch let StorageError.invalidArgument(message) {
  359. XCTAssertEqual(message, "Argument 'maxResults' must be between 1 and 1000 inclusive.")
  360. } catch {
  361. XCTFail("Unexpected error")
  362. }
  363. }
  364. func testListAllFiles() async throws {
  365. let ref = storage.reference(withPath: "ios/public/list")
  366. let listResult = try await ref.listAll()
  367. XCTAssertEqual(listResult.items, [ref.child("a"), ref.child("b")])
  368. XCTAssertEqual(listResult.prefixes, [ref.child("prefix")])
  369. XCTAssertNil(listResult.pageToken, "pageToken should be nil")
  370. }
  371. private func waitForExpectations() {
  372. let kTestTimeout = 60.0
  373. waitForExpectations(timeout: kTestTimeout,
  374. handler: { error in
  375. if let error = error {
  376. print(error)
  377. }
  378. })
  379. }
  380. }