DownloadTests.swift 29 KB

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