DownloadTests.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. //
  2. // DownloadTests.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Alamofire
  25. import Foundation
  26. import XCTest
  27. class DownloadInitializationTestCase: BaseTestCase {
  28. func testDownloadClassMethodWithMethodURLAndDestination() {
  29. // Given
  30. let urlString = "https://httpbin.org/get"
  31. let expectation = self.expectation(description: "download should complete")
  32. // When
  33. let request = AF.download(urlString).response { (resp) in
  34. expectation.fulfill()
  35. }
  36. waitForExpectations(timeout: timeout, handler: nil)
  37. // Then
  38. XCTAssertNotNil(request.request)
  39. XCTAssertEqual(request.request?.httpMethod, "GET")
  40. XCTAssertEqual(request.request?.url?.absoluteString, urlString)
  41. XCTAssertNotNil(request.response)
  42. }
  43. func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
  44. // Given
  45. let urlString = "https://httpbin.org/get"
  46. let headers: HTTPHeaders = ["Authorization": "123456"]
  47. let expectation = self.expectation(description: "download should complete")
  48. // When
  49. let request = AF.download(urlString, headers: headers).response { (resp) in
  50. expectation.fulfill()
  51. }
  52. waitForExpectations(timeout: timeout, handler: nil)
  53. // Then
  54. XCTAssertNotNil(request.request)
  55. XCTAssertEqual(request.request?.httpMethod, "GET")
  56. XCTAssertEqual(request.request?.url?.absoluteString, urlString)
  57. XCTAssertEqual(request.request?.value(forHTTPHeaderField: "Authorization"), "123456")
  58. XCTAssertNotNil(request.response)
  59. }
  60. }
  61. // MARK: -
  62. class DownloadResponseTestCase: BaseTestCase {
  63. private var randomCachesFileURL: URL {
  64. return testDirectoryURL.appendingPathComponent("\(UUID().uuidString).json")
  65. }
  66. func testDownloadRequest() {
  67. // Given
  68. let fileURL = randomCachesFileURL
  69. let numberOfLines = 10
  70. let urlString = "https://httpbin.org/stream/\(numberOfLines)"
  71. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  72. let expectation = self.expectation(description: "Download request should download data to file: \(urlString)")
  73. var response: DownloadResponse<URL?>?
  74. // When
  75. AF.download(urlString, to: destination)
  76. .response { resp in
  77. response = resp
  78. expectation.fulfill()
  79. }
  80. waitForExpectations(timeout: timeout, handler: nil)
  81. // Then
  82. XCTAssertNotNil(response?.request)
  83. XCTAssertNotNil(response?.response)
  84. XCTAssertNotNil(response?.fileURL)
  85. XCTAssertNil(response?.resumeData)
  86. XCTAssertNil(response?.error)
  87. if let destinationURL = response?.fileURL {
  88. XCTAssertTrue(FileManager.default.fileExists(atPath: destinationURL.path))
  89. if let data = try? Data(contentsOf: destinationURL) {
  90. XCTAssertGreaterThan(data.count, 0)
  91. } else {
  92. XCTFail("data should exist for contents of destinationURL")
  93. }
  94. }
  95. }
  96. func testCancelledDownloadRequest() {
  97. // Given
  98. let fileURL = randomCachesFileURL
  99. let numberOfLines = 10
  100. let urlString = "https://httpbin.org/stream/\(numberOfLines)"
  101. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  102. let expectation = self.expectation(description: "Cancelled download request should not download data to file")
  103. var response: DownloadResponse<URL?>?
  104. // When
  105. AF.download(urlString, to: destination)
  106. .response { resp in
  107. response = resp
  108. expectation.fulfill()
  109. }
  110. .cancel()
  111. waitForExpectations(timeout: timeout, handler: nil)
  112. // Then
  113. XCTAssertNotNil(response?.request)
  114. XCTAssertNil(response?.response)
  115. XCTAssertNil(response?.fileURL)
  116. XCTAssertNotNil(response?.error)
  117. }
  118. func testDownloadRequestWithProgress() {
  119. // Given
  120. let randomBytes = 1 * 1024 * 1024
  121. let urlString = "https://httpbin.org/bytes/\(randomBytes)"
  122. let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)")
  123. var progressValues: [Double] = []
  124. var response: DownloadResponse<URL?>?
  125. // When
  126. AF.download(urlString)
  127. .downloadProgress { progress in
  128. progressValues.append(progress.fractionCompleted)
  129. }
  130. .response { resp in
  131. response = resp
  132. expectation.fulfill()
  133. }
  134. waitForExpectations(timeout: timeout, handler: nil)
  135. // Then
  136. XCTAssertNotNil(response?.request)
  137. XCTAssertNotNil(response?.response)
  138. XCTAssertNotNil(response?.fileURL)
  139. XCTAssertNil(response?.resumeData)
  140. XCTAssertNil(response?.error)
  141. var previousProgress: Double = progressValues.first ?? 0.0
  142. for progress in progressValues {
  143. XCTAssertGreaterThanOrEqual(progress, previousProgress)
  144. previousProgress = progress
  145. }
  146. if let lastProgressValue = progressValues.last {
  147. XCTAssertEqual(lastProgressValue, 1.0)
  148. } else {
  149. XCTFail("last item in progressValues should not be nil")
  150. }
  151. }
  152. func testDownloadRequestWithParameters() {
  153. // Given
  154. let fileURL = randomCachesFileURL
  155. let urlString = "https://httpbin.org/get"
  156. let parameters = ["foo": "bar"]
  157. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  158. let expectation = self.expectation(description: "Download request should download data to file")
  159. var response: DownloadResponse<URL?>?
  160. // When
  161. AF.download(urlString, parameters: parameters, to: destination)
  162. .response { resp in
  163. response = resp
  164. expectation.fulfill()
  165. }
  166. waitForExpectations(timeout: timeout, handler: nil)
  167. // Then
  168. XCTAssertNotNil(response?.request)
  169. XCTAssertNotNil(response?.response)
  170. XCTAssertNotNil(response?.fileURL)
  171. XCTAssertNil(response?.resumeData)
  172. XCTAssertNil(response?.error)
  173. // TODO: Fails since the file is deleted by the time we get here?
  174. if
  175. let data = try? Data(contentsOf: fileURL),
  176. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
  177. let json = jsonObject as? [String: Any],
  178. let args = json["args"] as? [String: String]
  179. {
  180. XCTAssertEqual(args["foo"], "bar")
  181. } else {
  182. XCTFail("args parameter in JSON should not be nil")
  183. }
  184. }
  185. func testDownloadRequestWithHeaders() {
  186. // Given
  187. let fileURL = randomCachesFileURL
  188. let urlString = "https://httpbin.org/get"
  189. let headers: HTTPHeaders = ["Authorization": "123456"]
  190. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  191. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  192. var response: DownloadResponse<URL?>?
  193. // When
  194. AF.download(urlString, headers: headers, to: destination)
  195. .response { resp in
  196. response = resp
  197. expectation.fulfill()
  198. }
  199. waitForExpectations(timeout: timeout, handler: nil)
  200. // Then
  201. XCTAssertNotNil(response?.request)
  202. XCTAssertNotNil(response?.response)
  203. XCTAssertNotNil(response?.fileURL)
  204. XCTAssertNil(response?.resumeData)
  205. XCTAssertNil(response?.error)
  206. if
  207. let data = try? Data(contentsOf: fileURL),
  208. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
  209. let json = jsonObject as? [String: Any],
  210. let headers = json["headers"] as? [String: String]
  211. {
  212. XCTAssertEqual(headers["Authorization"], "123456")
  213. } else {
  214. XCTFail("headers parameter in JSON should not be nil")
  215. }
  216. }
  217. func testThatDownloadingFileAndMovingToDirectoryThatDoesNotExistThrowsError() {
  218. // Given
  219. let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  220. let expectation = self.expectation(description: "Download request should download data but fail to move file")
  221. var response: DownloadResponse<URL?>?
  222. // When
  223. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [])})
  224. .response { resp in
  225. response = resp
  226. expectation.fulfill()
  227. }
  228. waitForExpectations(timeout: timeout, handler: nil)
  229. // Then
  230. XCTAssertNotNil(response?.request)
  231. XCTAssertNotNil(response?.response)
  232. XCTAssertNil(response?.fileURL)
  233. XCTAssertNil(response?.resumeData)
  234. XCTAssertNotNil(response?.error)
  235. if let error = response?.error as? CocoaError {
  236. XCTAssertEqual(error.code, .fileNoSuchFile)
  237. } else {
  238. XCTFail("error should not be nil")
  239. }
  240. }
  241. func testThatDownloadOptionsCanCreateIntermediateDirectoriesPriorToMovingFile() {
  242. // Given
  243. let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  244. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  245. var response: DownloadResponse<URL?>?
  246. // When
  247. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.createIntermediateDirectories])})
  248. .response { resp in
  249. response = resp
  250. expectation.fulfill()
  251. }
  252. waitForExpectations(timeout: timeout, handler: nil)
  253. // Then
  254. XCTAssertNotNil(response?.request)
  255. XCTAssertNotNil(response?.response)
  256. XCTAssertNotNil(response?.fileURL)
  257. XCTAssertNil(response?.resumeData)
  258. XCTAssertNil(response?.error)
  259. }
  260. func testThatDownloadingFileAndMovingToDestinationThatIsOccupiedThrowsError() {
  261. do {
  262. // Given
  263. let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder")
  264. let directoryCreated = FileManager.createDirectory(at: directoryURL)
  265. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  266. try "random_data".write(to: fileURL, atomically: true, encoding: .utf8)
  267. let expectation = self.expectation(description: "Download should complete but fail to move file")
  268. var response: DownloadResponse<URL?>?
  269. // When
  270. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [])})
  271. .response { resp in
  272. response = resp
  273. expectation.fulfill()
  274. }
  275. waitForExpectations(timeout: timeout, handler: nil)
  276. // Then
  277. XCTAssertTrue(directoryCreated)
  278. XCTAssertNotNil(response?.request)
  279. XCTAssertNotNil(response?.response)
  280. XCTAssertNil(response?.fileURL)
  281. XCTAssertNil(response?.resumeData)
  282. XCTAssertNotNil(response?.error)
  283. if let error = response?.error as? CocoaError {
  284. XCTAssertEqual(error.code, .fileWriteFileExists)
  285. } else {
  286. XCTFail("error should not be nil")
  287. }
  288. } catch {
  289. XCTFail("Test encountered unexpected error: \(error)")
  290. }
  291. }
  292. func testThatDownloadOptionsCanRemovePreviousFilePriorToMovingFile() {
  293. // Given
  294. let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder")
  295. let directoryCreated = FileManager.createDirectory(at: directoryURL)
  296. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  297. let expectation = self.expectation(description: "Download should complete and move file to URL: \(fileURL)")
  298. var response: DownloadResponse<URL?>?
  299. // When
  300. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.removePreviousFile, .createIntermediateDirectories])})
  301. .response { resp in
  302. response = resp
  303. expectation.fulfill()
  304. }
  305. waitForExpectations(timeout: timeout, handler: nil)
  306. // Then
  307. XCTAssertTrue(directoryCreated)
  308. XCTAssertNotNil(response?.request)
  309. XCTAssertNotNil(response?.response)
  310. XCTAssertNotNil(response?.fileURL)
  311. XCTAssertNil(response?.resumeData)
  312. XCTAssertNil(response?.error)
  313. }
  314. }
  315. // MARK: -
  316. class DownloadResumeDataTestCase: BaseTestCase {
  317. let urlString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  318. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  319. // Given
  320. let expectation = self.expectation(description: "Download should be cancelled")
  321. var cancelled = false
  322. var response: DownloadResponse<URL?>?
  323. // When
  324. let download = AF.download(urlString)
  325. download.downloadProgress { progress in
  326. guard !cancelled else { return }
  327. if progress.fractionCompleted > 0.1 {
  328. download.cancel()
  329. cancelled = true
  330. }
  331. }
  332. download.response { resp in
  333. response = resp
  334. expectation.fulfill()
  335. }
  336. waitForExpectations(timeout: timeout, handler: nil)
  337. // Then
  338. XCTAssertNotNil(response?.request)
  339. XCTAssertNotNil(response?.response)
  340. XCTAssertNil(response?.fileURL)
  341. XCTAssertNotNil(response?.error)
  342. XCTAssertNotNil(response?.resumeData)
  343. XCTAssertNotNil(download.resumeData)
  344. XCTAssertEqual(response?.resumeData, download.resumeData)
  345. }
  346. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  347. // Given
  348. let expectation = self.expectation(description: "Download should be cancelled")
  349. var cancelled = false
  350. var response: DownloadResponse<Any>?
  351. // When
  352. let download = AF.download(urlString)
  353. download.downloadProgress { progress in
  354. guard !cancelled else { return }
  355. if progress.fractionCompleted > 0.1 {
  356. download.cancel()
  357. cancelled = true
  358. }
  359. }
  360. download.responseJSON { resp in
  361. response = resp
  362. expectation.fulfill()
  363. }
  364. waitForExpectations(timeout: timeout, handler: nil)
  365. // Then
  366. XCTAssertNotNil(response?.request)
  367. XCTAssertNotNil(response?.response)
  368. XCTAssertNil(response?.fileURL)
  369. XCTAssertEqual(response?.result.isFailure, true)
  370. XCTAssertNotNil(response?.result.error)
  371. XCTAssertNotNil(response?.resumeData)
  372. XCTAssertNotNil(download.resumeData)
  373. XCTAssertEqual(response?.resumeData, download.resumeData)
  374. }
  375. func testThatCancelledDownloadCanBeResumedWithResumeData() {
  376. // Given
  377. let expectation1 = self.expectation(description: "Download should be cancelled")
  378. var cancelled = false
  379. var response1: DownloadResponse<Data>?
  380. // When
  381. let download = AF.download(urlString)
  382. download.downloadProgress { progress in
  383. guard !cancelled else { return }
  384. if progress.fractionCompleted > 0.4 {
  385. download.cancel()
  386. cancelled = true
  387. }
  388. }
  389. download.responseData { resp in
  390. response1 = resp
  391. expectation1.fulfill()
  392. }
  393. waitForExpectations(timeout: timeout, handler: nil)
  394. guard let resumeData = download.resumeData else {
  395. XCTFail("resumeData should not be nil")
  396. return
  397. }
  398. let expectation2 = self.expectation(description: "Download should complete")
  399. var progressValues: [Double] = []
  400. var response2: DownloadResponse<Data>?
  401. let destination = DownloadRequest.suggestedDownloadDestination(options: [.removePreviousFile, .createIntermediateDirectories])
  402. // TODO: Added destination because temp file was being deleted very quickly.
  403. AF.download(resumingWith: resumeData,
  404. to: destination)
  405. .downloadProgress { progress in
  406. progressValues.append(progress.fractionCompleted)
  407. }
  408. .responseData { resp in
  409. response2 = resp
  410. expectation2.fulfill()
  411. }
  412. waitForExpectations(timeout: timeout, handler: nil)
  413. // Then
  414. XCTAssertNotNil(response1?.request)
  415. XCTAssertNotNil(response1?.response)
  416. XCTAssertNil(response1?.fileURL)
  417. XCTAssertEqual(response1?.result.isFailure, true)
  418. XCTAssertNotNil(response1?.result.error)
  419. XCTAssertNotNil(response2?.response)
  420. XCTAssertNotNil(response2?.fileURL)
  421. XCTAssertEqual(response2?.result.isSuccess, true)
  422. XCTAssertNil(response2?.result.error)
  423. progressValues.forEach { XCTAssertGreaterThanOrEqual($0, 0.4) }
  424. }
  425. }
  426. // MARK: -
  427. class DownloadResponseMapTestCase: BaseTestCase {
  428. func testThatMapTransformsSuccessValue() {
  429. // Given
  430. let urlString = "https://httpbin.org/get"
  431. let expectation = self.expectation(description: "request should succeed")
  432. var response: DownloadResponse<String>?
  433. // When
  434. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  435. response = resp.map { json in
  436. // json["args"]["foo"] is "bar": use this invariant to test the map function
  437. return ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid"
  438. }
  439. expectation.fulfill()
  440. }
  441. waitForExpectations(timeout: timeout, handler: nil)
  442. // Then
  443. XCTAssertNotNil(response?.request)
  444. XCTAssertNotNil(response?.response)
  445. XCTAssertNotNil(response?.fileURL)
  446. XCTAssertNil(response?.resumeData)
  447. XCTAssertNil(response?.error)
  448. XCTAssertEqual(response?.result.value, "bar")
  449. XCTAssertNotNil(response?.metrics)
  450. }
  451. func testThatMapPreservesFailureError() {
  452. // Given
  453. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  454. let expectation = self.expectation(description: "request should fail with 404")
  455. var response: DownloadResponse<String>?
  456. // When
  457. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  458. response = resp.map { _ in "ignored" }
  459. expectation.fulfill()
  460. }
  461. waitForExpectations(timeout: timeout, handler: nil)
  462. // Then
  463. XCTAssertNotNil(response?.request)
  464. XCTAssertNil(response?.response)
  465. XCTAssertNil(response?.fileURL)
  466. XCTAssertNil(response?.resumeData)
  467. XCTAssertNotNil(response?.error)
  468. XCTAssertEqual(response?.result.isFailure, true)
  469. XCTAssertNotNil(response?.metrics)
  470. }
  471. }
  472. // MARK: -
  473. class DownloadResponseFlatMapTestCase: BaseTestCase {
  474. func testThatFlatMapTransformsSuccessValue() {
  475. // Given
  476. let urlString = "https://httpbin.org/get"
  477. let expectation = self.expectation(description: "request should succeed")
  478. var response: DownloadResponse<String>?
  479. // When
  480. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  481. response = resp.flatMap { json in
  482. // json["args"]["foo"] is "bar": use this invariant to test the map function
  483. return ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid"
  484. }
  485. expectation.fulfill()
  486. }
  487. waitForExpectations(timeout: timeout, handler: nil)
  488. // Then
  489. XCTAssertNotNil(response?.request)
  490. XCTAssertNotNil(response?.response)
  491. XCTAssertNotNil(response?.fileURL)
  492. XCTAssertNil(response?.resumeData)
  493. XCTAssertNil(response?.error)
  494. XCTAssertEqual(response?.result.value, "bar")
  495. XCTAssertNotNil(response?.metrics)
  496. }
  497. func testThatFlatMapCatchesTransformationError() {
  498. // Given
  499. struct TransformError: Error {}
  500. let urlString = "https://httpbin.org/get"
  501. let expectation = self.expectation(description: "request should succeed")
  502. var response: DownloadResponse<String>?
  503. // When
  504. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  505. response = resp.flatMap { json in
  506. throw TransformError()
  507. }
  508. expectation.fulfill()
  509. }
  510. waitForExpectations(timeout: timeout, handler: nil)
  511. // Then
  512. XCTAssertNotNil(response?.request)
  513. XCTAssertNotNil(response?.response)
  514. XCTAssertNotNil(response?.fileURL)
  515. XCTAssertNil(response?.resumeData)
  516. if let error = response?.result.error {
  517. XCTAssertTrue(error is TransformError)
  518. } else {
  519. XCTFail("flatMap should catch the transformation error")
  520. }
  521. XCTAssertNotNil(response?.metrics)
  522. }
  523. func testThatFlatMapPreservesFailureError() {
  524. // Given
  525. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  526. let expectation = self.expectation(description: "request should fail with 404")
  527. var response: DownloadResponse<String>?
  528. // When
  529. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  530. response = resp.flatMap { _ in "ignored" }
  531. expectation.fulfill()
  532. }
  533. waitForExpectations(timeout: timeout, handler: nil)
  534. // Then
  535. XCTAssertNotNil(response?.request)
  536. XCTAssertNil(response?.response)
  537. XCTAssertNil(response?.fileURL)
  538. XCTAssertNil(response?.resumeData)
  539. XCTAssertNotNil(response?.error)
  540. XCTAssertEqual(response?.result.isFailure, true)
  541. XCTAssertNotNil(response?.metrics)
  542. }
  543. }
  544. class DownloadResponseMapErrorTestCase: BaseTestCase {
  545. func testThatMapErrorTransformsFailureValue() {
  546. // Given
  547. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  548. let expectation = self.expectation(description: "request should not succeed")
  549. var response: DownloadResponse<Any>?
  550. // When
  551. AF.download(urlString).responseJSON { resp in
  552. response = resp.mapError { error in
  553. return TestError.error(error: error)
  554. }
  555. expectation.fulfill()
  556. }
  557. waitForExpectations(timeout: timeout, handler: nil)
  558. // Then
  559. XCTAssertNotNil(response?.request)
  560. XCTAssertNil(response?.response)
  561. XCTAssertNil(response?.fileURL)
  562. XCTAssertNil(response?.resumeData)
  563. XCTAssertNotNil(response?.error)
  564. XCTAssertEqual(response?.result.isFailure, true)
  565. guard let error = response?.error as? TestError, case .error = error else { XCTFail(); return }
  566. XCTAssertNotNil(response?.metrics)
  567. }
  568. func testThatMapErrorPreservesSuccessValue() {
  569. // Given
  570. let urlString = "https://httpbin.org/get"
  571. let expectation = self.expectation(description: "request should succeed")
  572. var response: DownloadResponse<Data>?
  573. // When
  574. AF.download(urlString).responseData { resp in
  575. response = resp.mapError { TestError.error(error: $0) }
  576. expectation.fulfill()
  577. }
  578. waitForExpectations(timeout: timeout, handler: nil)
  579. // Then
  580. XCTAssertNotNil(response?.request)
  581. XCTAssertNotNil(response?.response)
  582. XCTAssertNotNil(response?.fileURL)
  583. XCTAssertNil(response?.resumeData)
  584. XCTAssertEqual(response?.result.isSuccess, true)
  585. XCTAssertNotNil(response?.metrics)
  586. }
  587. }
  588. // MARK: -
  589. class DownloadResponseFlatMapErrorTestCase: BaseTestCase {
  590. func testThatFlatMapErrorPreservesSuccessValue() {
  591. // Given
  592. let urlString = "https://httpbin.org/get"
  593. let expectation = self.expectation(description: "request should succeed")
  594. var response: DownloadResponse<Data>?
  595. // When
  596. AF.download(urlString).responseData { resp in
  597. response = resp.flatMapError { TestError.error(error: $0) }
  598. expectation.fulfill()
  599. }
  600. waitForExpectations(timeout: timeout, handler: nil)
  601. // Then
  602. XCTAssertNotNil(response?.request)
  603. XCTAssertNotNil(response?.response)
  604. XCTAssertNotNil(response?.fileURL)
  605. XCTAssertNil(response?.resumeData)
  606. XCTAssertNil(response?.error)
  607. XCTAssertEqual(response?.result.isSuccess, true)
  608. XCTAssertNotNil(response?.metrics)
  609. }
  610. func testThatFlatMapErrorCatchesTransformationError() {
  611. // Given
  612. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  613. let expectation = self.expectation(description: "request should fail")
  614. var response: DownloadResponse<Data>?
  615. // When
  616. AF.download(urlString).responseData { resp in
  617. response = resp.flatMapError { _ in try TransformationError.error.alwaysFails() }
  618. expectation.fulfill()
  619. }
  620. waitForExpectations(timeout: timeout, handler: nil)
  621. // Then
  622. XCTAssertNotNil(response?.request)
  623. XCTAssertNil(response?.response)
  624. XCTAssertNil(response?.fileURL)
  625. XCTAssertNil(response?.resumeData)
  626. XCTAssertNotNil(response?.error)
  627. XCTAssertEqual(response?.result.isFailure, true)
  628. if let error = response?.result.error {
  629. XCTAssertTrue(error is TransformationError)
  630. } else {
  631. XCTFail("flatMapError should catch the transformation error")
  632. }
  633. XCTAssertNotNil(response?.metrics)
  634. }
  635. func testThatFlatMapErrorTransformsError() {
  636. // Given
  637. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  638. let expectation = self.expectation(description: "request should fail")
  639. var response: DownloadResponse<Data>?
  640. // When
  641. AF.download(urlString).responseData { resp in
  642. response = resp.flatMapError { TestError.error(error: $0) }
  643. expectation.fulfill()
  644. }
  645. waitForExpectations(timeout: timeout, handler: nil)
  646. // Then
  647. XCTAssertNotNil(response?.request)
  648. XCTAssertNil(response?.response)
  649. XCTAssertNil(response?.fileURL)
  650. XCTAssertNil(response?.resumeData)
  651. XCTAssertNotNil(response?.error)
  652. XCTAssertEqual(response?.result.isFailure, true)
  653. guard let error = response?.error as? TestError, case .error = error else { XCTFail(); return }
  654. XCTAssertNotNil(response?.metrics)
  655. }
  656. }