DownloadTests.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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 * 25 * 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. // MARK: -
  301. final class DownloadRequestEventsTestCase: BaseTestCase {
  302. func testThatDownloadRequestTriggersAllAppropriateLifetimeEvents() {
  303. // Given
  304. let eventMonitor = ClosureEventMonitor()
  305. let session = Session(eventMonitors: [eventMonitor])
  306. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  307. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  308. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  309. let didCreateTask = expectation(description: "didCreateTask should fire")
  310. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  311. let didComplete = expectation(description: "didComplete should fire")
  312. let didWriteData = expectation(description: "didWriteData should fire")
  313. let didFinishDownloading = expectation(description: "didFinishDownloading should fire")
  314. let didFinishWithResult = expectation(description: "didFinishWithResult should fire")
  315. let didCreate = expectation(description: "didCreate should fire")
  316. let didFinish = expectation(description: "didFinish should fire")
  317. let didResume = expectation(description: "didResume should fire")
  318. let didResumeTask = expectation(description: "didResumeTask should fire")
  319. let didParseResponse = expectation(description: "didParseResponse should fire")
  320. let responseHandler = expectation(description: "responseHandler should fire")
  321. var wroteData = false
  322. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  323. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  324. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  325. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  326. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  327. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  328. eventMonitor.downloadTaskDidWriteData = { _, _, _, _, _ in
  329. guard !wroteData else { return }
  330. wroteData = true
  331. didWriteData.fulfill()
  332. }
  333. eventMonitor.downloadTaskDidFinishDownloadingToURL = { _, _, _ in didFinishDownloading.fulfill() }
  334. eventMonitor.requestDidFinishDownloadingUsingTaskWithResult = { _, _, _ in didFinishWithResult.fulfill() }
  335. eventMonitor.requestDidCreateDestinationURL = { _, _ in didCreate.fulfill() }
  336. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  337. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  338. eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
  339. eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() }
  340. // When
  341. let request = session.download(URLRequest.makeHTTPBinRequest()).response { _ in
  342. responseHandler.fulfill()
  343. }
  344. waitForExpectations(timeout: timeout, handler: nil)
  345. // Then
  346. XCTAssertEqual(request.state, .finished)
  347. }
  348. func testThatCancelledDownloadRequestTriggersAllAppropriateLifetimeEvents() {
  349. // Given
  350. let eventMonitor = ClosureEventMonitor()
  351. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  352. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  353. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  354. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  355. let didCreateTask = expectation(description: "didCreateTask should fire")
  356. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  357. let didComplete = expectation(description: "didComplete should fire")
  358. let didFinish = expectation(description: "didFinish should fire")
  359. let didResume = expectation(description: "didResume should fire")
  360. let didResumeTask = expectation(description: "didResumeTask should fire")
  361. let didParseResponse = expectation(description: "didParseResponse should fire")
  362. let didCancel = expectation(description: "didCancel should fire")
  363. let didCancelTask = expectation(description: "didCancelTask should fire")
  364. let responseHandler = expectation(description: "responseHandler should fire")
  365. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  366. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  367. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  368. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  369. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  370. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  371. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  372. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  373. eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() }
  374. eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
  375. eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
  376. // When
  377. let request = session.download(URLRequest.makeHTTPBinRequest(path: "delay/5")).response { _ in
  378. responseHandler.fulfill()
  379. }
  380. eventMonitor.requestDidResumeTask = { _, _ in
  381. request.cancel()
  382. didResumeTask.fulfill()
  383. }
  384. request.resume()
  385. waitForExpectations(timeout: timeout, handler: nil)
  386. // Then
  387. XCTAssertEqual(request.state, .cancelled)
  388. }
  389. }
  390. // MARK: -
  391. final class DownloadResumeDataTestCase: BaseTestCase {
  392. let urlString = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5f/HubbleDeepField.800px.jpg/2048px-HubbleDeepField.800px.jpg"
  393. func testThatCancelledDownloadRequestDoesNotProduceResumeData() {
  394. // Given
  395. let expectation = self.expectation(description: "Download should be cancelled")
  396. var cancelled = false
  397. var response: DownloadResponse<URL?, AFError>?
  398. // When
  399. let download = AF.download(urlString)
  400. download.downloadProgress { progress in
  401. guard !cancelled else { return }
  402. if progress.fractionCompleted > 0.1 {
  403. download.cancel()
  404. cancelled = true
  405. }
  406. }
  407. download.response { resp in
  408. response = resp
  409. expectation.fulfill()
  410. }
  411. waitForExpectations(timeout: timeout, handler: nil)
  412. // Then
  413. XCTAssertNotNil(response?.request)
  414. XCTAssertNotNil(response?.response)
  415. XCTAssertNil(response?.fileURL)
  416. XCTAssertNotNil(response?.error)
  417. XCTAssertNil(response?.resumeData)
  418. XCTAssertNil(download.resumeData)
  419. }
  420. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  421. // Given
  422. let expectation = self.expectation(description: "Download should be cancelled")
  423. var cancelled = false
  424. var response: DownloadResponse<URL?, AFError>?
  425. // When
  426. let download = AF.download(urlString)
  427. download.downloadProgress { progress in
  428. guard !cancelled else { return }
  429. if progress.fractionCompleted > 0.1 {
  430. download.cancel(producingResumeData: true)
  431. cancelled = true
  432. }
  433. }
  434. download.response { resp in
  435. response = resp
  436. expectation.fulfill()
  437. }
  438. waitForExpectations(timeout: timeout, handler: nil)
  439. // Then
  440. XCTAssertNotNil(response?.request)
  441. XCTAssertNotNil(response?.response)
  442. XCTAssertNil(response?.fileURL)
  443. XCTAssertNotNil(response?.error)
  444. XCTAssertNotNil(response?.resumeData)
  445. XCTAssertNotNil(download.resumeData)
  446. XCTAssertEqual(response?.resumeData, download.resumeData)
  447. }
  448. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  449. // Given
  450. let expectation = self.expectation(description: "Download should be cancelled")
  451. var cancelled = false
  452. var response: DownloadResponse<Any, AFError>?
  453. // When
  454. let download = AF.download(urlString)
  455. download.downloadProgress { progress in
  456. guard !cancelled else { return }
  457. if progress.fractionCompleted > 0.1 {
  458. download.cancel(producingResumeData: true)
  459. cancelled = true
  460. }
  461. }
  462. download.responseJSON { resp in
  463. response = resp
  464. expectation.fulfill()
  465. }
  466. waitForExpectations(timeout: timeout, handler: nil)
  467. // Then
  468. XCTAssertNotNil(response?.request)
  469. XCTAssertNotNil(response?.response)
  470. XCTAssertNil(response?.fileURL)
  471. XCTAssertEqual(response?.result.isFailure, true)
  472. XCTAssertNotNil(response?.result.failure)
  473. XCTAssertNotNil(response?.resumeData)
  474. XCTAssertNotNil(download.resumeData)
  475. XCTAssertEqual(response?.resumeData, download.resumeData)
  476. }
  477. func testThatCancelledDownloadCanBeResumedWithResumeData() {
  478. // Given
  479. let expectation1 = expectation(description: "Download should be cancelled")
  480. var cancelled = false
  481. var response1: DownloadResponse<Data, AFError>?
  482. // When
  483. let download = AF.download(urlString)
  484. download.downloadProgress { progress in
  485. guard !cancelled else { return }
  486. if progress.fractionCompleted > 0.1 {
  487. download.cancel(producingResumeData: true)
  488. cancelled = true
  489. }
  490. }
  491. download.responseData { resp in
  492. response1 = resp
  493. expectation1.fulfill()
  494. }
  495. waitForExpectations(timeout: timeout, handler: nil)
  496. guard let resumeData = download.resumeData else {
  497. XCTFail("resumeData should not be nil")
  498. return
  499. }
  500. let expectation2 = expectation(description: "Download should complete")
  501. var progressValues: [Double] = []
  502. var response2: DownloadResponse<Data, AFError>?
  503. AF.download(resumingWith: resumeData)
  504. .downloadProgress { progress in
  505. progressValues.append(progress.fractionCompleted)
  506. }
  507. .responseData { resp in
  508. response2 = resp
  509. expectation2.fulfill()
  510. }
  511. waitForExpectations(timeout: timeout, handler: nil)
  512. // Then
  513. XCTAssertNotNil(response1?.request)
  514. XCTAssertNotNil(response1?.response)
  515. XCTAssertNil(response1?.fileURL)
  516. XCTAssertEqual(response1?.result.isFailure, true)
  517. XCTAssertNotNil(response1?.result.failure)
  518. XCTAssertNotNil(response2?.response)
  519. XCTAssertNotNil(response2?.fileURL)
  520. XCTAssertEqual(response2?.result.isSuccess, true)
  521. XCTAssertNil(response2?.result.failure)
  522. progressValues.forEach { XCTAssertGreaterThanOrEqual($0, 0.1) }
  523. }
  524. func testThatCancelledDownloadProducesMatchingResumeData() {
  525. // Given
  526. let expectation = self.expectation(description: "Download should be cancelled")
  527. var cancelled = false
  528. var receivedResumeData: Data?
  529. var response: DownloadResponse<URL?, AFError>?
  530. // When
  531. let download = AF.download(urlString)
  532. download.downloadProgress { progress in
  533. guard !cancelled else { return }
  534. if progress.fractionCompleted > 0.1 {
  535. download.cancel { receivedResumeData = $0 }
  536. cancelled = true
  537. }
  538. }
  539. download.response { resp in
  540. response = resp
  541. expectation.fulfill()
  542. }
  543. waitForExpectations(timeout: timeout, handler: nil)
  544. // Then
  545. XCTAssertNotNil(response?.request)
  546. XCTAssertNotNil(response?.response)
  547. XCTAssertNil(response?.fileURL)
  548. XCTAssertNotNil(response?.error)
  549. XCTAssertNotNil(response?.resumeData)
  550. XCTAssertNotNil(download.resumeData)
  551. XCTAssertEqual(response?.resumeData, download.resumeData)
  552. XCTAssertEqual(response?.resumeData, receivedResumeData)
  553. XCTAssertEqual(download.resumeData, receivedResumeData)
  554. }
  555. }
  556. // MARK: -
  557. final class DownloadResponseMapTestCase: BaseTestCase {
  558. func testThatMapTransformsSuccessValue() {
  559. // Given
  560. let urlString = "https://httpbin.org/get"
  561. let expectation = self.expectation(description: "request should succeed")
  562. var response: DownloadResponse<String, AFError>?
  563. // When
  564. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  565. response = resp.map { json in
  566. // json["args"]["foo"] is "bar": use this invariant to test the map function
  567. ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid"
  568. }
  569. expectation.fulfill()
  570. }
  571. waitForExpectations(timeout: timeout, handler: nil)
  572. // Then
  573. XCTAssertNotNil(response?.request)
  574. XCTAssertNotNil(response?.response)
  575. XCTAssertNotNil(response?.fileURL)
  576. XCTAssertNil(response?.resumeData)
  577. XCTAssertNil(response?.error)
  578. XCTAssertEqual(response?.result.success, "bar")
  579. XCTAssertNotNil(response?.metrics)
  580. }
  581. func testThatMapPreservesFailureError() {
  582. // Given
  583. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  584. let expectation = self.expectation(description: "request should fail with 404")
  585. var response: DownloadResponse<String, AFError>?
  586. // When
  587. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  588. response = resp.map { _ in "ignored" }
  589. expectation.fulfill()
  590. }
  591. waitForExpectations(timeout: timeout, handler: nil)
  592. // Then
  593. XCTAssertNotNil(response?.request)
  594. XCTAssertNil(response?.response)
  595. XCTAssertNil(response?.fileURL)
  596. XCTAssertNil(response?.resumeData)
  597. XCTAssertNotNil(response?.error)
  598. XCTAssertEqual(response?.result.isFailure, true)
  599. XCTAssertNotNil(response?.metrics)
  600. }
  601. }
  602. // MARK: -
  603. final class DownloadResponseTryMapTestCase: BaseTestCase {
  604. func testThatTryMapTransformsSuccessValue() {
  605. // Given
  606. let urlString = "https://httpbin.org/get"
  607. let expectation = self.expectation(description: "request should succeed")
  608. var response: DownloadResponse<String, Error>?
  609. // When
  610. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  611. response = resp.tryMap { json in
  612. // json["args"]["foo"] is "bar": use this invariant to test the map function
  613. ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid"
  614. }
  615. expectation.fulfill()
  616. }
  617. waitForExpectations(timeout: timeout, handler: nil)
  618. // Then
  619. XCTAssertNotNil(response?.request)
  620. XCTAssertNotNil(response?.response)
  621. XCTAssertNotNil(response?.fileURL)
  622. XCTAssertNil(response?.resumeData)
  623. XCTAssertNil(response?.error)
  624. XCTAssertEqual(response?.result.success, "bar")
  625. XCTAssertNotNil(response?.metrics)
  626. }
  627. func testThatTryMapCatchesTransformationError() {
  628. // Given
  629. struct TransformError: Error {}
  630. let urlString = "https://httpbin.org/get"
  631. let expectation = self.expectation(description: "request should succeed")
  632. var response: DownloadResponse<String, Error>?
  633. // When
  634. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  635. response = resp.tryMap { _ in
  636. throw TransformError()
  637. }
  638. expectation.fulfill()
  639. }
  640. waitForExpectations(timeout: timeout, handler: nil)
  641. // Then
  642. XCTAssertNotNil(response?.request)
  643. XCTAssertNotNil(response?.response)
  644. XCTAssertNotNil(response?.fileURL)
  645. XCTAssertNil(response?.resumeData)
  646. if let error = response?.result.failure {
  647. XCTAssertTrue(error is TransformError)
  648. } else {
  649. XCTFail("flatMap should catch the transformation error")
  650. }
  651. XCTAssertNotNil(response?.metrics)
  652. }
  653. func testThatTryMapPreservesFailureError() {
  654. // Given
  655. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  656. let expectation = self.expectation(description: "request should fail with 404")
  657. var response: DownloadResponse<String, Error>?
  658. // When
  659. AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in
  660. response = resp.tryMap { _ in "ignored" }
  661. expectation.fulfill()
  662. }
  663. waitForExpectations(timeout: timeout, handler: nil)
  664. // Then
  665. XCTAssertNotNil(response?.request)
  666. XCTAssertNil(response?.response)
  667. XCTAssertNil(response?.fileURL)
  668. XCTAssertNil(response?.resumeData)
  669. XCTAssertNotNil(response?.error)
  670. XCTAssertEqual(response?.result.isFailure, true)
  671. XCTAssertNotNil(response?.metrics)
  672. }
  673. }
  674. final class DownloadResponseMapErrorTestCase: BaseTestCase {
  675. func testThatMapErrorTransformsFailureValue() {
  676. // Given
  677. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  678. let expectation = self.expectation(description: "request should not succeed")
  679. var response: DownloadResponse<Any, TestError>?
  680. // When
  681. AF.download(urlString).responseJSON { resp in
  682. response = resp.mapError { error in
  683. TestError.error(error: error)
  684. }
  685. expectation.fulfill()
  686. }
  687. waitForExpectations(timeout: timeout, handler: nil)
  688. // Then
  689. XCTAssertNotNil(response?.request)
  690. XCTAssertNil(response?.response)
  691. XCTAssertNil(response?.fileURL)
  692. XCTAssertNil(response?.resumeData)
  693. XCTAssertNotNil(response?.error)
  694. XCTAssertEqual(response?.result.isFailure, true)
  695. guard let error = response?.error, case .error = error else { XCTFail(); return }
  696. XCTAssertNotNil(response?.metrics)
  697. }
  698. func testThatMapErrorPreservesSuccessValue() {
  699. // Given
  700. let urlString = "https://httpbin.org/get"
  701. let expectation = self.expectation(description: "request should succeed")
  702. var response: DownloadResponse<Data, TestError>?
  703. // When
  704. AF.download(urlString).responseData { resp in
  705. response = resp.mapError { TestError.error(error: $0) }
  706. expectation.fulfill()
  707. }
  708. waitForExpectations(timeout: timeout, handler: nil)
  709. // Then
  710. XCTAssertNotNil(response?.request)
  711. XCTAssertNotNil(response?.response)
  712. XCTAssertNotNil(response?.fileURL)
  713. XCTAssertNil(response?.resumeData)
  714. XCTAssertEqual(response?.result.isSuccess, true)
  715. XCTAssertNotNil(response?.metrics)
  716. }
  717. }
  718. // MARK: -
  719. final class DownloadResponseTryMapErrorTestCase: BaseTestCase {
  720. func testThatTryMapErrorPreservesSuccessValue() {
  721. // Given
  722. let urlString = "https://httpbin.org/get"
  723. let expectation = self.expectation(description: "request should succeed")
  724. var response: DownloadResponse<Data, Error>?
  725. // When
  726. AF.download(urlString).responseData { resp in
  727. response = resp.tryMapError { TestError.error(error: $0) }
  728. expectation.fulfill()
  729. }
  730. waitForExpectations(timeout: timeout, handler: nil)
  731. // Then
  732. XCTAssertNotNil(response?.request)
  733. XCTAssertNotNil(response?.response)
  734. XCTAssertNotNil(response?.fileURL)
  735. XCTAssertNil(response?.resumeData)
  736. XCTAssertNil(response?.error)
  737. XCTAssertEqual(response?.result.isSuccess, true)
  738. XCTAssertNotNil(response?.metrics)
  739. }
  740. func testThatTryMapErrorCatchesTransformationError() {
  741. // Given
  742. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  743. let expectation = self.expectation(description: "request should fail")
  744. var response: DownloadResponse<Data, Error>?
  745. // When
  746. AF.download(urlString).responseData { resp in
  747. response = resp.tryMapError { _ in try TransformationError.error.alwaysFails() }
  748. expectation.fulfill()
  749. }
  750. waitForExpectations(timeout: timeout, handler: nil)
  751. // Then
  752. XCTAssertNotNil(response?.request)
  753. XCTAssertNil(response?.response)
  754. XCTAssertNil(response?.fileURL)
  755. XCTAssertNil(response?.resumeData)
  756. XCTAssertNotNil(response?.error)
  757. XCTAssertEqual(response?.result.isFailure, true)
  758. if let error = response?.result.failure {
  759. XCTAssertTrue(error is TransformationError)
  760. } else {
  761. XCTFail("flatMapError should catch the transformation error")
  762. }
  763. XCTAssertNotNil(response?.metrics)
  764. }
  765. func testThatTryMapErrorTransformsError() {
  766. // Given
  767. let urlString = "https://invalid-url-here.org/this/does/not/exist"
  768. let expectation = self.expectation(description: "request should fail")
  769. var response: DownloadResponse<Data, Error>?
  770. // When
  771. AF.download(urlString).responseData { resp in
  772. response = resp.tryMapError { TestError.error(error: $0) }
  773. expectation.fulfill()
  774. }
  775. waitForExpectations(timeout: timeout, handler: nil)
  776. // Then
  777. XCTAssertNotNil(response?.request)
  778. XCTAssertNil(response?.response)
  779. XCTAssertNil(response?.fileURL)
  780. XCTAssertNil(response?.resumeData)
  781. XCTAssertNotNil(response?.error)
  782. XCTAssertEqual(response?.result.isFailure, true)
  783. guard let error = response?.error, case TestError.error = error else { XCTFail(); return }
  784. XCTAssertNotNil(response?.metrics)
  785. }
  786. }