DownloadTests.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. //
  2. // DownloadTests.swift
  3. //
  4. // Copyright (c) 2014-2017 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. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  466. XCTAssertNotNil(response?.metrics)
  467. }
  468. }
  469. func testThatMapPreservesFailureError() {
  470. // Given
  471. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  472. let expectation = self.expectation(description: "request should fail with 404")
  473. var response: DownloadResponse<String>?
  474. // When
  475. Alamofire.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  476. response = resp.map { _ in "ignored" }
  477. expectation.fulfill()
  478. }
  479. waitForExpectations(timeout: timeout, handler: nil)
  480. // Then
  481. XCTAssertNotNil(response?.request)
  482. XCTAssertNil(response?.response)
  483. XCTAssertNil(response?.temporaryURL)
  484. XCTAssertNil(response?.destinationURL)
  485. XCTAssertNil(response?.resumeData)
  486. XCTAssertNotNil(response?.error)
  487. XCTAssertEqual(response?.result.isFailure, true)
  488. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  489. XCTAssertNotNil(response?.metrics)
  490. }
  491. }
  492. }
  493. // MARK: -
  494. class DownloadResponseFlatMapTestCase: BaseTestCase {
  495. func testThatFlatMapTransformsSuccessValue() {
  496. // Given
  497. let urlString = "https://httpbin.org/get"
  498. let expectation = self.expectation(description: "request should succeed")
  499. var response: DownloadResponse<String>?
  500. // When
  501. Alamofire.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  502. response = resp.flatMap { json in
  503. // json["args"]["foo"] is "bar": use this invariant to test the map function
  504. return ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid"
  505. }
  506. expectation.fulfill()
  507. }
  508. waitForExpectations(timeout: timeout, handler: nil)
  509. // Then
  510. XCTAssertNotNil(response?.request)
  511. XCTAssertNotNil(response?.response)
  512. XCTAssertNotNil(response?.temporaryURL)
  513. XCTAssertNil(response?.destinationURL)
  514. XCTAssertNil(response?.resumeData)
  515. XCTAssertNil(response?.error)
  516. XCTAssertEqual(response?.result.value, "bar")
  517. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  518. XCTAssertNotNil(response?.metrics)
  519. }
  520. }
  521. func testThatFlatMapCatchesTransformationError() {
  522. // Given
  523. struct TransformError: Error {}
  524. let urlString = "https://httpbin.org/get"
  525. let expectation = self.expectation(description: "request should succeed")
  526. var response: DownloadResponse<String>?
  527. // When
  528. Alamofire.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  529. response = resp.flatMap { json in
  530. throw TransformError()
  531. }
  532. expectation.fulfill()
  533. }
  534. waitForExpectations(timeout: timeout, handler: nil)
  535. // Then
  536. XCTAssertNotNil(response?.request)
  537. XCTAssertNotNil(response?.response)
  538. XCTAssertNotNil(response?.temporaryURL)
  539. XCTAssertNil(response?.destinationURL)
  540. XCTAssertNil(response?.resumeData)
  541. if let error = response?.result.error {
  542. XCTAssertTrue(error is TransformError)
  543. } else {
  544. XCTFail("flatMap should catch the transformation error")
  545. }
  546. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  547. XCTAssertNotNil(response?.metrics)
  548. }
  549. }
  550. func testThatFlatMapPreservesFailureError() {
  551. // Given
  552. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  553. let expectation = self.expectation(description: "request should fail with 404")
  554. var response: DownloadResponse<String>?
  555. // When
  556. Alamofire.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  557. response = resp.flatMap { _ in "ignored" }
  558. expectation.fulfill()
  559. }
  560. waitForExpectations(timeout: timeout, handler: nil)
  561. // Then
  562. XCTAssertNotNil(response?.request)
  563. XCTAssertNil(response?.response)
  564. XCTAssertNil(response?.temporaryURL)
  565. XCTAssertNil(response?.destinationURL)
  566. XCTAssertNil(response?.resumeData)
  567. XCTAssertNotNil(response?.error)
  568. XCTAssertEqual(response?.result.isFailure, true)
  569. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  570. XCTAssertNotNil(response?.metrics)
  571. }
  572. }
  573. }
  574. class DownloadResponseMapErrorTestCase: BaseTestCase {
  575. func testThatMapErrorTransformsFailureValue() {
  576. // Given
  577. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  578. let expectation = self.expectation(description: "request should not succeed")
  579. var response: DownloadResponse<Any>?
  580. // When
  581. Alamofire.download(urlString).responseJSON { resp in
  582. response = resp.mapError { error in
  583. return TestError.error(error: error)
  584. }
  585. expectation.fulfill()
  586. }
  587. waitForExpectations(timeout: timeout, handler: nil)
  588. // Then
  589. XCTAssertNotNil(response?.request)
  590. XCTAssertNil(response?.response)
  591. XCTAssertNil(response?.temporaryURL)
  592. XCTAssertNil(response?.destinationURL)
  593. XCTAssertNil(response?.resumeData)
  594. XCTAssertNotNil(response?.error)
  595. XCTAssertEqual(response?.result.isFailure, true)
  596. guard let error = response?.error as? TestError, case .error = error else { XCTFail(); return }
  597. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  598. XCTAssertNotNil(response?.metrics)
  599. }
  600. }
  601. func testThatMapErrorPreservesSuccessValue() {
  602. // Given
  603. let urlString = "https://httpbin.org/get"
  604. let expectation = self.expectation(description: "request should succeed")
  605. var response: DownloadResponse<Data>?
  606. // When
  607. Alamofire.download(urlString).responseData { resp in
  608. response = resp.mapError { TestError.error(error: $0) }
  609. expectation.fulfill()
  610. }
  611. waitForExpectations(timeout: timeout, handler: nil)
  612. // Then
  613. XCTAssertNotNil(response?.request)
  614. XCTAssertNotNil(response?.response)
  615. XCTAssertNotNil(response?.temporaryURL)
  616. XCTAssertNil(response?.destinationURL)
  617. XCTAssertNil(response?.resumeData)
  618. XCTAssertEqual(response?.result.isSuccess, true)
  619. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  620. XCTAssertNotNil(response?.metrics)
  621. }
  622. }
  623. }
  624. // MARK: -
  625. class DownloadResponseFlatMapErrorTestCase: BaseTestCase {
  626. func testThatFlatMapErrorPreservesSuccessValue() {
  627. // Given
  628. let urlString = "https://httpbin.org/get"
  629. let expectation = self.expectation(description: "request should succeed")
  630. var response: DownloadResponse<Data>?
  631. // When
  632. Alamofire.download(urlString).responseData { resp in
  633. response = resp.flatMapError { TestError.error(error: $0) }
  634. expectation.fulfill()
  635. }
  636. waitForExpectations(timeout: timeout, handler: nil)
  637. // Then
  638. XCTAssertNotNil(response?.request)
  639. XCTAssertNotNil(response?.response)
  640. XCTAssertNotNil(response?.temporaryURL)
  641. XCTAssertNil(response?.destinationURL)
  642. XCTAssertNil(response?.resumeData)
  643. XCTAssertNil(response?.error)
  644. XCTAssertEqual(response?.result.isSuccess, true)
  645. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  646. XCTAssertNotNil(response?.metrics)
  647. }
  648. }
  649. func testThatFlatMapErrorCatchesTransformationError() {
  650. // Given
  651. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  652. let expectation = self.expectation(description: "request should fail")
  653. var response: DownloadResponse<Data>?
  654. // When
  655. Alamofire.download(urlString).responseData { resp in
  656. response = resp.flatMapError { _ in try TransformationError.error.alwaysFails() }
  657. expectation.fulfill()
  658. }
  659. waitForExpectations(timeout: timeout, handler: nil)
  660. // Then
  661. XCTAssertNotNil(response?.request)
  662. XCTAssertNil(response?.response)
  663. XCTAssertNil(response?.temporaryURL)
  664. XCTAssertNil(response?.destinationURL)
  665. XCTAssertNil(response?.resumeData)
  666. XCTAssertNotNil(response?.error)
  667. XCTAssertEqual(response?.result.isFailure, true)
  668. if let error = response?.result.error {
  669. XCTAssertTrue(error is TransformationError)
  670. } else {
  671. XCTFail("flatMapError should catch the transformation error")
  672. }
  673. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  674. XCTAssertNotNil(response?.metrics)
  675. }
  676. }
  677. func testThatFlatMapErrorTransformsError() {
  678. // Given
  679. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  680. let expectation = self.expectation(description: "request should fail")
  681. var response: DownloadResponse<Data>?
  682. // When
  683. Alamofire.download(urlString).responseData { resp in
  684. response = resp.flatMapError { TestError.error(error: $0) }
  685. expectation.fulfill()
  686. }
  687. waitForExpectations(timeout: timeout, handler: nil)
  688. // Then
  689. XCTAssertNotNil(response?.request)
  690. XCTAssertNil(response?.response)
  691. XCTAssertNil(response?.temporaryURL)
  692. XCTAssertNil(response?.destinationURL)
  693. XCTAssertNil(response?.resumeData)
  694. XCTAssertNotNil(response?.error)
  695. XCTAssertEqual(response?.result.isFailure, true)
  696. guard let error = response?.error as? TestError, case .error = error else { XCTFail(); return }
  697. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
  698. XCTAssertNotNil(response?.metrics)
  699. }
  700. }
  701. }