DownloadTests.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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 { _ 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 { _ 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?.headers["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?, AFError>?
  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?, AFError>?
  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. XCTAssertNil(response?.response)
  114. XCTAssertNil(response?.fileURL)
  115. XCTAssertNotNil(response?.error)
  116. XCTAssertEqual(response?.error?.isExplicitlyCancelledError, true)
  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?, AFError>?
  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?, AFError>?
  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. if
  174. let data = try? Data(contentsOf: fileURL),
  175. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
  176. let json = jsonObject as? [String: Any],
  177. let args = json["args"] as? [String: String] {
  178. XCTAssertEqual(args["foo"], "bar")
  179. } else {
  180. XCTFail("args parameter in JSON should not be nil")
  181. }
  182. }
  183. func testDownloadRequestWithHeaders() {
  184. // Given
  185. let fileURL = randomCachesFileURL
  186. let urlString = "https://httpbin.org/get"
  187. let headers: HTTPHeaders = ["Authorization": "123456"]
  188. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  189. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  190. var response: DownloadResponse<URL?, AFError>?
  191. // When
  192. AF.download(urlString, headers: headers, to: destination)
  193. .response { resp in
  194. response = resp
  195. expectation.fulfill()
  196. }
  197. waitForExpectations(timeout: timeout, handler: nil)
  198. // Then
  199. XCTAssertNotNil(response?.request)
  200. XCTAssertNotNil(response?.response)
  201. XCTAssertNotNil(response?.fileURL)
  202. XCTAssertNil(response?.resumeData)
  203. XCTAssertNil(response?.error)
  204. if
  205. let data = try? Data(contentsOf: fileURL),
  206. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
  207. let json = jsonObject as? [String: Any],
  208. let headers = json["headers"] as? [String: String] {
  209. XCTAssertEqual(headers["Authorization"], "123456")
  210. } else {
  211. XCTFail("headers parameter in JSON should not be nil")
  212. }
  213. }
  214. func testThatDownloadingFileAndMovingToDirectoryThatDoesNotExistThrowsError() {
  215. // Given
  216. let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  217. let expectation = self.expectation(description: "Download request should download data but fail to move file")
  218. var response: DownloadResponse<URL?, AFError>?
  219. // When
  220. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, []) })
  221. .response { resp in
  222. response = resp
  223. expectation.fulfill()
  224. }
  225. waitForExpectations(timeout: timeout, handler: nil)
  226. // Then
  227. XCTAssertNotNil(response?.request)
  228. XCTAssertNotNil(response?.response)
  229. XCTAssertNil(response?.fileURL)
  230. XCTAssertNil(response?.resumeData)
  231. XCTAssertNotNil(response?.error)
  232. XCTAssertEqual((response?.error?.underlyingError as? CocoaError)?.code, .fileNoSuchFile)
  233. }
  234. func testThatDownloadOptionsCanCreateIntermediateDirectoriesPriorToMovingFile() {
  235. // Given
  236. let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  237. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  238. var response: DownloadResponse<URL?, AFError>?
  239. // When
  240. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.createIntermediateDirectories]) })
  241. .response { resp in
  242. response = resp
  243. expectation.fulfill()
  244. }
  245. waitForExpectations(timeout: timeout, handler: nil)
  246. // Then
  247. XCTAssertNotNil(response?.request)
  248. XCTAssertNotNil(response?.response)
  249. XCTAssertNotNil(response?.fileURL)
  250. XCTAssertNil(response?.resumeData)
  251. XCTAssertNil(response?.error)
  252. }
  253. func testThatDownloadingFileAndMovingToDestinationThatIsOccupiedThrowsError() throws {
  254. // Given
  255. let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder")
  256. let directoryCreated = FileManager.createDirectory(at: directoryURL)
  257. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  258. try "random_data".write(to: fileURL, atomically: true, encoding: .utf8)
  259. let expectation = self.expectation(description: "Download should complete but fail to move file")
  260. var response: DownloadResponse<URL?, AFError>?
  261. // When
  262. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, []) })
  263. .response { resp in
  264. response = resp
  265. expectation.fulfill()
  266. }
  267. waitForExpectations(timeout: timeout, handler: nil)
  268. // Then
  269. XCTAssertTrue(directoryCreated)
  270. XCTAssertNotNil(response?.request)
  271. XCTAssertNotNil(response?.response)
  272. XCTAssertNil(response?.fileURL)
  273. XCTAssertNil(response?.resumeData)
  274. XCTAssertNotNil(response?.error)
  275. XCTAssertEqual((response?.error?.underlyingError as? CocoaError)?.code, .fileWriteFileExists)
  276. }
  277. func testThatDownloadOptionsCanRemovePreviousFilePriorToMovingFile() {
  278. // Given
  279. let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder")
  280. let directoryCreated = FileManager.createDirectory(at: directoryURL)
  281. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  282. let expectation = self.expectation(description: "Download should complete and move file to URL: \(fileURL)")
  283. var response: DownloadResponse<URL?, AFError>?
  284. // When
  285. AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.removePreviousFile, .createIntermediateDirectories]) })
  286. .response { resp in
  287. response = resp
  288. expectation.fulfill()
  289. }
  290. waitForExpectations(timeout: timeout, handler: nil)
  291. // Then
  292. XCTAssertTrue(directoryCreated)
  293. XCTAssertNotNil(response?.request)
  294. XCTAssertNotNil(response?.response)
  295. XCTAssertNotNil(response?.fileURL)
  296. XCTAssertNil(response?.resumeData)
  297. XCTAssertNil(response?.error)
  298. }
  299. }
  300. final class DownloadRequestEventsTestCase: BaseTestCase {
  301. func testThatDownloadRequestTriggersAllAppropriateLifetimeEvents() {
  302. // Given
  303. let eventMonitor = ClosureEventMonitor()
  304. let session = Session(eventMonitors: [eventMonitor])
  305. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  306. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  307. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  308. let didCreateTask = expectation(description: "didCreateTask should fire")
  309. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  310. let didComplete = expectation(description: "didComplete should fire")
  311. let didWriteData = expectation(description: "didWriteData should fire")
  312. let didFinishDownloading = expectation(description: "didFinishDownloading should fire")
  313. let didFinishWithResult = expectation(description: "didFinishWithResult should fire")
  314. let didCreate = expectation(description: "didCreate should fire")
  315. let didFinish = expectation(description: "didFinish should fire")
  316. let didResume = expectation(description: "didResume should fire")
  317. let didResumeTask = expectation(description: "didResumeTask should fire")
  318. let didParseResponse = expectation(description: "didParseResponse should fire")
  319. let responseHandler = expectation(description: "responseHandler should fire")
  320. var wroteData = false
  321. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  322. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  323. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  324. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  325. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  326. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  327. eventMonitor.downloadTaskDidWriteData = { _, _, _, _, _ in
  328. guard !wroteData else { return }
  329. wroteData = true
  330. didWriteData.fulfill()
  331. }
  332. eventMonitor.downloadTaskDidFinishDownloadingToURL = { _, _, _ in didFinishDownloading.fulfill() }
  333. eventMonitor.requestDidFinishDownloadingUsingTaskWithResult = { _, _, _ in didFinishWithResult.fulfill() }
  334. eventMonitor.requestDidCreateDestinationURL = { _, _ in didCreate.fulfill() }
  335. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  336. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  337. eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
  338. eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() }
  339. // When
  340. let request = session.download(URLRequest.makeHTTPBinRequest()).response { _ in
  341. responseHandler.fulfill()
  342. }
  343. waitForExpectations(timeout: timeout, handler: nil)
  344. // Then
  345. XCTAssertEqual(request.state, .finished)
  346. }
  347. func testThatCancelledDownloadRequestTriggersAllAppropriateLifetimeEvents() {
  348. // Given
  349. let eventMonitor = ClosureEventMonitor()
  350. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  351. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  352. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  353. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  354. let didCreateTask = expectation(description: "didCreateTask should fire")
  355. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  356. let didComplete = expectation(description: "didComplete should fire")
  357. let didFinish = expectation(description: "didFinish should fire")
  358. let didResume = expectation(description: "didResume should fire")
  359. let didResumeTask = expectation(description: "didResumeTask should fire")
  360. let didParseResponse = expectation(description: "didParseResponse should fire")
  361. let didCancel = expectation(description: "didCancel should fire")
  362. let didCancelTask = expectation(description: "didCancelTask should fire")
  363. let responseHandler = expectation(description: "responseHandler should fire")
  364. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  365. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  366. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  367. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  368. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  369. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  370. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  371. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  372. eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() }
  373. eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
  374. eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
  375. // When
  376. let request = session.download(URLRequest.makeHTTPBinRequest()).response { _ in
  377. responseHandler.fulfill()
  378. }
  379. eventMonitor.requestDidResumeTask = { _, _ in
  380. request.cancel()
  381. didResumeTask.fulfill()
  382. }
  383. request.resume()
  384. waitForExpectations(timeout: timeout, handler: nil)
  385. // Then
  386. XCTAssertEqual(request.state, .cancelled)
  387. }
  388. }
  389. // MARK: -
  390. final class DownloadResumeDataTestCase: BaseTestCase {
  391. let urlString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  392. func testThatCancelledDownloadRequestDoesNotProduceResumeData() {
  393. // Given
  394. let expectation = self.expectation(description: "Download should be cancelled")
  395. var cancelled = false
  396. var response: DownloadResponse<URL?, AFError>?
  397. // When
  398. let download = AF.download(urlString)
  399. download.downloadProgress { progress in
  400. guard !cancelled else { return }
  401. if progress.fractionCompleted > 0.1 {
  402. download.cancel()
  403. cancelled = true
  404. }
  405. }
  406. download.response { resp in
  407. response = resp
  408. expectation.fulfill()
  409. }
  410. waitForExpectations(timeout: timeout, handler: nil)
  411. // Then
  412. XCTAssertNotNil(response?.request)
  413. XCTAssertNotNil(response?.response)
  414. XCTAssertNil(response?.fileURL)
  415. XCTAssertNotNil(response?.error)
  416. XCTAssertNil(response?.resumeData)
  417. XCTAssertNil(download.resumeData)
  418. }
  419. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  420. // Given
  421. let expectation = self.expectation(description: "Download should be cancelled")
  422. var cancelled = false
  423. var response: DownloadResponse<URL?, AFError>?
  424. // When
  425. let download = AF.download(urlString)
  426. download.downloadProgress { progress in
  427. guard !cancelled else { return }
  428. if progress.fractionCompleted > 0.1 {
  429. download.cancel(producingResumeData: true)
  430. cancelled = true
  431. }
  432. }
  433. download.response { resp in
  434. response = resp
  435. expectation.fulfill()
  436. }
  437. waitForExpectations(timeout: timeout, handler: nil)
  438. // Then
  439. XCTAssertNotNil(response?.request)
  440. XCTAssertNotNil(response?.response)
  441. XCTAssertNil(response?.fileURL)
  442. XCTAssertNotNil(response?.error)
  443. XCTAssertNotNil(response?.resumeData)
  444. XCTAssertNotNil(download.resumeData)
  445. XCTAssertEqual(response?.resumeData, download.resumeData)
  446. }
  447. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  448. // Given
  449. let expectation = self.expectation(description: "Download should be cancelled")
  450. var cancelled = false
  451. var response: DownloadResponse<Any, AFError>?
  452. // When
  453. let download = AF.download(urlString)
  454. download.downloadProgress { progress in
  455. guard !cancelled else { return }
  456. if progress.fractionCompleted > 0.1 {
  457. download.cancel(producingResumeData: true)
  458. cancelled = true
  459. }
  460. }
  461. download.responseJSON { resp in
  462. response = resp
  463. expectation.fulfill()
  464. }
  465. waitForExpectations(timeout: timeout, handler: nil)
  466. // Then
  467. XCTAssertNotNil(response?.request)
  468. XCTAssertNotNil(response?.response)
  469. XCTAssertNil(response?.fileURL)
  470. XCTAssertEqual(response?.result.isFailure, true)
  471. XCTAssertNotNil(response?.result.failure)
  472. XCTAssertNotNil(response?.resumeData)
  473. XCTAssertNotNil(download.resumeData)
  474. XCTAssertEqual(response?.resumeData, download.resumeData)
  475. }
  476. func testThatCancelledDownloadCanBeResumedWithResumeData() {
  477. // Given
  478. let expectation1 = expectation(description: "Download should be cancelled")
  479. var cancelled = false
  480. var response1: DownloadResponse<Data, AFError>?
  481. // When
  482. let download = AF.download(urlString)
  483. download.downloadProgress { progress in
  484. guard !cancelled else { return }
  485. if progress.fractionCompleted > 0.4 {
  486. download.cancel(producingResumeData: true)
  487. cancelled = true
  488. }
  489. }
  490. download.responseData { resp in
  491. response1 = resp
  492. expectation1.fulfill()
  493. }
  494. waitForExpectations(timeout: timeout, handler: nil)
  495. guard let resumeData = download.resumeData else {
  496. XCTFail("resumeData should not be nil")
  497. return
  498. }
  499. let expectation2 = expectation(description: "Download should complete")
  500. var progressValues: [Double] = []
  501. var response2: DownloadResponse<Data, AFError>?
  502. AF.download(resumingWith: resumeData)
  503. .downloadProgress { progress in
  504. progressValues.append(progress.fractionCompleted)
  505. }
  506. .responseData { resp in
  507. response2 = resp
  508. expectation2.fulfill()
  509. }
  510. waitForExpectations(timeout: timeout, handler: nil)
  511. // Then
  512. XCTAssertNotNil(response1?.request)
  513. XCTAssertNotNil(response1?.response)
  514. XCTAssertNil(response1?.fileURL)
  515. XCTAssertEqual(response1?.result.isFailure, true)
  516. XCTAssertNotNil(response1?.result.failure)
  517. XCTAssertNotNil(response2?.response)
  518. XCTAssertNotNil(response2?.fileURL)
  519. XCTAssertEqual(response2?.result.isSuccess, true)
  520. XCTAssertNil(response2?.result.failure)
  521. progressValues.forEach { XCTAssertGreaterThanOrEqual($0, 0.4) }
  522. }
  523. func testThatCancelledDownloadProducesMatchingResumeData() {
  524. // Given
  525. let expectation = self.expectation(description: "Download should be cancelled")
  526. var cancelled = false
  527. var receivedResumeData: Data?
  528. var response: DownloadResponse<URL?, AFError>?
  529. // When
  530. let download = AF.download(urlString)
  531. download.downloadProgress { progress in
  532. guard !cancelled else { return }
  533. if progress.fractionCompleted > 0.1 {
  534. download.cancel { receivedResumeData = $0 }
  535. cancelled = true
  536. }
  537. }
  538. download.response { resp in
  539. response = resp
  540. expectation.fulfill()
  541. }
  542. waitForExpectations(timeout: timeout, handler: nil)
  543. // Then
  544. XCTAssertNotNil(response?.request)
  545. XCTAssertNotNil(response?.response)
  546. XCTAssertNil(response?.fileURL)
  547. XCTAssertNotNil(response?.error)
  548. XCTAssertNotNil(response?.resumeData)
  549. XCTAssertNotNil(download.resumeData)
  550. XCTAssertEqual(response?.resumeData, download.resumeData)
  551. XCTAssertEqual(response?.resumeData, receivedResumeData)
  552. XCTAssertEqual(download.resumeData, receivedResumeData)
  553. }
  554. }
  555. // MARK: -
  556. class DownloadResponseMapTestCase: BaseTestCase {
  557. func testThatMapTransformsSuccessValue() {
  558. // Given
  559. let urlString = "https://httpbin.org/get"
  560. let expectation = self.expectation(description: "request should succeed")
  561. var response: DownloadResponse<String, AFError>?
  562. // When
  563. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  564. response = resp.map { json in
  565. // json["args"]["foo"] is "bar": use this invariant to test the map function
  566. ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid"
  567. }
  568. expectation.fulfill()
  569. }
  570. waitForExpectations(timeout: timeout, handler: nil)
  571. // Then
  572. XCTAssertNotNil(response?.request)
  573. XCTAssertNotNil(response?.response)
  574. XCTAssertNotNil(response?.fileURL)
  575. XCTAssertNil(response?.resumeData)
  576. XCTAssertNil(response?.error)
  577. XCTAssertEqual(response?.result.success, "bar")
  578. XCTAssertNotNil(response?.metrics)
  579. }
  580. func testThatMapPreservesFailureError() {
  581. // Given
  582. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  583. let expectation = self.expectation(description: "request should fail with 404")
  584. var response: DownloadResponse<String, AFError>?
  585. // When
  586. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  587. response = resp.map { _ in "ignored" }
  588. expectation.fulfill()
  589. }
  590. waitForExpectations(timeout: timeout, handler: nil)
  591. // Then
  592. XCTAssertNotNil(response?.request)
  593. XCTAssertNil(response?.response)
  594. XCTAssertNil(response?.fileURL)
  595. XCTAssertNil(response?.resumeData)
  596. XCTAssertNotNil(response?.error)
  597. XCTAssertEqual(response?.result.isFailure, true)
  598. XCTAssertNotNil(response?.metrics)
  599. }
  600. }
  601. // MARK: -
  602. class DownloadResponseTryMapTestCase: BaseTestCase {
  603. func testThatTryMapTransformsSuccessValue() {
  604. // Given
  605. let urlString = "https://httpbin.org/get"
  606. let expectation = self.expectation(description: "request should succeed")
  607. var response: DownloadResponse<String, Error>?
  608. // When
  609. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  610. response = resp.tryMap { json in
  611. // json["args"]["foo"] is "bar": use this invariant to test the map function
  612. ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid"
  613. }
  614. expectation.fulfill()
  615. }
  616. waitForExpectations(timeout: timeout, handler: nil)
  617. // Then
  618. XCTAssertNotNil(response?.request)
  619. XCTAssertNotNil(response?.response)
  620. XCTAssertNotNil(response?.fileURL)
  621. XCTAssertNil(response?.resumeData)
  622. XCTAssertNil(response?.error)
  623. XCTAssertEqual(response?.result.success, "bar")
  624. XCTAssertNotNil(response?.metrics)
  625. }
  626. func testThatTryMapCatchesTransformationError() {
  627. // Given
  628. struct TransformError: Error {}
  629. let urlString = "https://httpbin.org/get"
  630. let expectation = self.expectation(description: "request should succeed")
  631. var response: DownloadResponse<String, Error>?
  632. // When
  633. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  634. response = resp.tryMap { _ in
  635. throw TransformError()
  636. }
  637. expectation.fulfill()
  638. }
  639. waitForExpectations(timeout: timeout, handler: nil)
  640. // Then
  641. XCTAssertNotNil(response?.request)
  642. XCTAssertNotNil(response?.response)
  643. XCTAssertNotNil(response?.fileURL)
  644. XCTAssertNil(response?.resumeData)
  645. if let error = response?.result.failure {
  646. XCTAssertTrue(error is TransformError)
  647. } else {
  648. XCTFail("flatMap should catch the transformation error")
  649. }
  650. XCTAssertNotNil(response?.metrics)
  651. }
  652. func testThatTryMapPreservesFailureError() {
  653. // Given
  654. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  655. let expectation = self.expectation(description: "request should fail with 404")
  656. var response: DownloadResponse<String, Error>?
  657. // When
  658. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  659. response = resp.tryMap { _ in "ignored" }
  660. expectation.fulfill()
  661. }
  662. waitForExpectations(timeout: timeout, handler: nil)
  663. // Then
  664. XCTAssertNotNil(response?.request)
  665. XCTAssertNil(response?.response)
  666. XCTAssertNil(response?.fileURL)
  667. XCTAssertNil(response?.resumeData)
  668. XCTAssertNotNil(response?.error)
  669. XCTAssertEqual(response?.result.isFailure, true)
  670. XCTAssertNotNil(response?.metrics)
  671. }
  672. }
  673. class DownloadResponseMapErrorTestCase: BaseTestCase {
  674. func testThatMapErrorTransformsFailureValue() {
  675. // Given
  676. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  677. let expectation = self.expectation(description: "request should not succeed")
  678. var response: DownloadResponse<Any, TestError>?
  679. // When
  680. AF.download(urlString).responseJSON { resp in
  681. response = resp.mapError { error in
  682. TestError.error(error: error)
  683. }
  684. expectation.fulfill()
  685. }
  686. waitForExpectations(timeout: timeout, handler: nil)
  687. // Then
  688. XCTAssertNotNil(response?.request)
  689. XCTAssertNil(response?.response)
  690. XCTAssertNil(response?.fileURL)
  691. XCTAssertNil(response?.resumeData)
  692. XCTAssertNotNil(response?.error)
  693. XCTAssertEqual(response?.result.isFailure, true)
  694. guard let error = response?.error, case .error = error else { XCTFail(); return }
  695. XCTAssertNotNil(response?.metrics)
  696. }
  697. func testThatMapErrorPreservesSuccessValue() {
  698. // Given
  699. let urlString = "https://httpbin.org/get"
  700. let expectation = self.expectation(description: "request should succeed")
  701. var response: DownloadResponse<Data, TestError>?
  702. // When
  703. AF.download(urlString).responseData { resp in
  704. response = resp.mapError { TestError.error(error: $0) }
  705. expectation.fulfill()
  706. }
  707. waitForExpectations(timeout: timeout, handler: nil)
  708. // Then
  709. XCTAssertNotNil(response?.request)
  710. XCTAssertNotNil(response?.response)
  711. XCTAssertNotNil(response?.fileURL)
  712. XCTAssertNil(response?.resumeData)
  713. XCTAssertEqual(response?.result.isSuccess, true)
  714. XCTAssertNotNil(response?.metrics)
  715. }
  716. }
  717. // MARK: -
  718. class DownloadResponseTryMapErrorTestCase: BaseTestCase {
  719. func testThatTryMapErrorPreservesSuccessValue() {
  720. // Given
  721. let urlString = "https://httpbin.org/get"
  722. let expectation = self.expectation(description: "request should succeed")
  723. var response: DownloadResponse<Data, Error>?
  724. // When
  725. AF.download(urlString).responseData { resp in
  726. response = resp.tryMapError { TestError.error(error: $0) }
  727. expectation.fulfill()
  728. }
  729. waitForExpectations(timeout: timeout, handler: nil)
  730. // Then
  731. XCTAssertNotNil(response?.request)
  732. XCTAssertNotNil(response?.response)
  733. XCTAssertNotNil(response?.fileURL)
  734. XCTAssertNil(response?.resumeData)
  735. XCTAssertNil(response?.error)
  736. XCTAssertEqual(response?.result.isSuccess, true)
  737. XCTAssertNotNil(response?.metrics)
  738. }
  739. func testThatTryMapErrorCatchesTransformationError() {
  740. // Given
  741. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  742. let expectation = self.expectation(description: "request should fail")
  743. var response: DownloadResponse<Data, Error>?
  744. // When
  745. AF.download(urlString).responseData { resp in
  746. response = resp.tryMapError { _ in try TransformationError.error.alwaysFails() }
  747. expectation.fulfill()
  748. }
  749. waitForExpectations(timeout: timeout, handler: nil)
  750. // Then
  751. XCTAssertNotNil(response?.request)
  752. XCTAssertNil(response?.response)
  753. XCTAssertNil(response?.fileURL)
  754. XCTAssertNil(response?.resumeData)
  755. XCTAssertNotNil(response?.error)
  756. XCTAssertEqual(response?.result.isFailure, true)
  757. if let error = response?.result.failure {
  758. XCTAssertTrue(error is TransformationError)
  759. } else {
  760. XCTFail("flatMapError should catch the transformation error")
  761. }
  762. XCTAssertNotNil(response?.metrics)
  763. }
  764. func testThatTryMapErrorTransformsError() {
  765. // Given
  766. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  767. let expectation = self.expectation(description: "request should fail")
  768. var response: DownloadResponse<Data, Error>?
  769. // When
  770. AF.download(urlString).responseData { resp in
  771. response = resp.tryMapError { TestError.error(error: $0) }
  772. expectation.fulfill()
  773. }
  774. waitForExpectations(timeout: timeout, handler: nil)
  775. // Then
  776. XCTAssertNotNil(response?.request)
  777. XCTAssertNil(response?.response)
  778. XCTAssertNil(response?.fileURL)
  779. XCTAssertNil(response?.resumeData)
  780. XCTAssertNotNil(response?.error)
  781. XCTAssertEqual(response?.result.isFailure, true)
  782. guard let error = response?.error, case TestError.error = error else { XCTFail(); return }
  783. XCTAssertNotNil(response?.metrics)
  784. }
  785. }