StorageAsyncAwait.swift 16 KB

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