StorageAsyncAwait.swift 15 KB

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