DownloadTests.swift 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. final class DownloadInitializationTests: BaseTestCase {
  28. @MainActor
  29. func testDownloadClassMethodWithMethodURLAndDestination() {
  30. // Given
  31. let endpoint = Endpoint.get
  32. let expectation = expectation(description: "download should complete")
  33. // When
  34. let request = AF.download(endpoint).response { _ in
  35. expectation.fulfill()
  36. }
  37. waitForExpectations(timeout: timeout)
  38. // Then
  39. XCTAssertNotNil(request.request)
  40. XCTAssertEqual(request.request?.httpMethod, "GET")
  41. XCTAssertEqual(request.request?.url, endpoint.url)
  42. XCTAssertNotNil(request.response)
  43. }
  44. @MainActor
  45. func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
  46. // Given
  47. let endpoint = Endpoint.get
  48. let headers: HTTPHeaders = ["Authorization": "123456"]
  49. let expectation = expectation(description: "download should complete")
  50. // When
  51. let request = AF.download(endpoint, headers: headers).response { _ in
  52. expectation.fulfill()
  53. }
  54. waitForExpectations(timeout: timeout)
  55. // Then
  56. XCTAssertNotNil(request.request)
  57. XCTAssertEqual(request.request?.httpMethod, "GET")
  58. XCTAssertEqual(request.request?.url, endpoint.url)
  59. XCTAssertEqual(request.request?.headers["Authorization"], "123456")
  60. XCTAssertNotNil(request.response)
  61. }
  62. }
  63. // MARK: -
  64. final class DownloadResponseTests: BaseTestCase {
  65. private var randomCachesFileURL: URL {
  66. testDirectoryURL.appendingPathComponent("\(UUID().uuidString).json")
  67. }
  68. @MainActor
  69. func testDownloadRequest() {
  70. // Given
  71. let fileURL = randomCachesFileURL
  72. let numberOfLines = 10
  73. let endpoint = Endpoint.stream(numberOfLines)
  74. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  75. let expectation = expectation(description: "Download request should download data to file: \(endpoint.url.absoluteString)")
  76. var response: DownloadResponse<URL?, AFError>?
  77. // When
  78. AF.download(endpoint, to: destination)
  79. .response { resp in
  80. response = resp
  81. expectation.fulfill()
  82. }
  83. waitForExpectations(timeout: timeout)
  84. // Then
  85. XCTAssertNotNil(response?.request)
  86. XCTAssertNotNil(response?.response)
  87. XCTAssertNotNil(response?.fileURL)
  88. XCTAssertNil(response?.resumeData)
  89. XCTAssertNil(response?.error)
  90. if let destinationURL = response?.fileURL {
  91. XCTAssertTrue(FileManager.default.fileExists(atPath: destinationURL.path))
  92. if let data = try? Data(contentsOf: destinationURL) {
  93. XCTAssertGreaterThan(data.count, 0)
  94. } else {
  95. XCTFail("data should exist for contents of destinationURL")
  96. }
  97. }
  98. }
  99. @MainActor
  100. func testDownloadRequestResponseURLProducesURL() throws {
  101. // Given
  102. let expectation = expectation(description: "Download request should download data")
  103. var response: DownloadResponse<URL, AFError>?
  104. // When
  105. AF.download(.get)
  106. .responseURL { resp in
  107. response = resp
  108. expectation.fulfill()
  109. }
  110. waitForExpectations(timeout: timeout, handler: nil)
  111. // Then
  112. XCTAssertNotNil(response?.request)
  113. XCTAssertNotNil(response?.response)
  114. XCTAssertNotNil(response?.fileURL)
  115. XCTAssertNil(response?.resumeData)
  116. XCTAssertNil(response?.error)
  117. let url = try XCTUnwrap(response?.value)
  118. XCTAssertTrue(FileManager.default.fileExists(atPath: url.path))
  119. }
  120. @MainActor
  121. func testCancelledDownloadRequest() {
  122. // Given
  123. let fileURL = randomCachesFileURL
  124. let numberOfLines = 10
  125. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  126. let expectation = expectation(description: "Cancelled download request should not download data to file")
  127. var response: DownloadResponse<URL?, AFError>?
  128. // When
  129. AF.download(.stream(numberOfLines), to: destination)
  130. .response { resp in
  131. response = resp
  132. expectation.fulfill()
  133. }
  134. .cancel()
  135. waitForExpectations(timeout: timeout)
  136. // Then
  137. XCTAssertNil(response?.response)
  138. XCTAssertNil(response?.fileURL)
  139. XCTAssertNotNil(response?.error)
  140. XCTAssertEqual(response?.error?.isExplicitlyCancelledError, true)
  141. }
  142. @MainActor
  143. func testDownloadRequestWithProgress() {
  144. // Given
  145. let randomBytes = 256
  146. let endpoint = Endpoint.bytes(randomBytes)
  147. let expectation = expectation(description: "Bytes download progress should be reported: \(endpoint.url)")
  148. var progressValues: [Double] = []
  149. var response: DownloadResponse<URL?, AFError>?
  150. // When
  151. AF.download(endpoint)
  152. .downloadProgress { progress in
  153. progressValues.append(progress.fractionCompleted)
  154. }
  155. .response { resp in
  156. response = resp
  157. expectation.fulfill()
  158. }
  159. waitForExpectations(timeout: timeout)
  160. // Then
  161. XCTAssertNotNil(response?.request)
  162. XCTAssertNotNil(response?.response)
  163. XCTAssertNotNil(response?.fileURL)
  164. XCTAssertNil(response?.resumeData)
  165. XCTAssertNil(response?.error)
  166. var previousProgress: Double = progressValues.first ?? 0.0
  167. for progress in progressValues {
  168. XCTAssertGreaterThanOrEqual(progress, previousProgress)
  169. previousProgress = progress
  170. }
  171. if let lastProgressValue = progressValues.last {
  172. XCTAssertEqual(lastProgressValue, 1.0)
  173. } else {
  174. XCTFail("last item in progressValues should not be nil")
  175. }
  176. }
  177. @MainActor
  178. func testDownloadRequestWithParameters() {
  179. // Given
  180. let fileURL = randomCachesFileURL
  181. let parameters = ["foo": "bar"]
  182. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  183. let expectation = expectation(description: "Download request should download data to file")
  184. var response: DownloadResponse<URL?, AFError>?
  185. // When
  186. AF.download(Endpoint.get, parameters: parameters, to: destination)
  187. .response { resp in
  188. response = resp
  189. expectation.fulfill()
  190. }
  191. waitForExpectations(timeout: timeout)
  192. // Then
  193. XCTAssertNotNil(response?.request)
  194. XCTAssertNotNil(response?.response)
  195. XCTAssertNotNil(response?.fileURL)
  196. XCTAssertNil(response?.resumeData)
  197. XCTAssertNil(response?.error)
  198. if
  199. let data = try? Data(contentsOf: fileURL),
  200. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
  201. let json = jsonObject as? [String: Any],
  202. let args = json["args"] as? [String: String] {
  203. XCTAssertEqual(args["foo"], "bar")
  204. } else {
  205. XCTFail("args parameter in JSON should not be nil")
  206. }
  207. }
  208. @MainActor
  209. func testDownloadRequestWithHeaders() {
  210. // Given
  211. let fileURL = randomCachesFileURL
  212. let endpoint = Endpoint.get
  213. let headers: HTTPHeaders = ["Authorization": "123456"]
  214. let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) }
  215. let expectation = expectation(description: "Download request should download data to file: \(endpoint.url)")
  216. var response: DownloadResponse<URL?, AFError>?
  217. // When
  218. AF.download(endpoint, headers: headers, to: destination)
  219. .response { resp in
  220. response = resp
  221. expectation.fulfill()
  222. }
  223. waitForExpectations(timeout: timeout)
  224. // Then
  225. XCTAssertNotNil(response?.request)
  226. XCTAssertNotNil(response?.response)
  227. XCTAssertNotNil(response?.fileURL)
  228. XCTAssertNil(response?.resumeData)
  229. XCTAssertNil(response?.error)
  230. guard let data = try? Data(contentsOf: fileURL),
  231. let response = try? JSONDecoder().decode(TestResponse.self, from: data) else {
  232. XCTFail("headers parameter in JSON should not be nil")
  233. return
  234. }
  235. XCTAssertEqual(response.headers["Authorization"], "123456")
  236. }
  237. @MainActor
  238. func testThatDownloadingFileAndMovingToDirectoryThatDoesNotExistThrowsError() {
  239. // Given
  240. let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  241. let expectation = expectation(description: "Download request should download data but fail to move file")
  242. var response: DownloadResponse<URL?, AFError>?
  243. // When
  244. AF.download(.get, to: { _, _ in (fileURL, []) })
  245. .response { resp in
  246. response = resp
  247. expectation.fulfill()
  248. }
  249. waitForExpectations(timeout: timeout)
  250. // Then
  251. XCTAssertNotNil(response?.request)
  252. XCTAssertNotNil(response?.response)
  253. XCTAssertNil(response?.fileURL)
  254. XCTAssertNil(response?.resumeData)
  255. XCTAssertNotNil(response?.error)
  256. XCTAssertEqual((response?.error?.underlyingError as? CocoaError)?.code, .fileNoSuchFile)
  257. }
  258. @MainActor
  259. func testThatDownloadOptionsCanCreateIntermediateDirectoriesPriorToMovingFile() {
  260. // Given
  261. let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  262. let expectation = expectation(description: "Download request should download data to file: \(fileURL)")
  263. var response: DownloadResponse<URL?, AFError>?
  264. // When
  265. AF.download(.get, to: { _, _ in (fileURL, [.createIntermediateDirectories]) })
  266. .response { resp in
  267. response = resp
  268. expectation.fulfill()
  269. }
  270. waitForExpectations(timeout: timeout)
  271. // Then
  272. XCTAssertNotNil(response?.request)
  273. XCTAssertNotNil(response?.response)
  274. XCTAssertNotNil(response?.fileURL)
  275. XCTAssertNil(response?.resumeData)
  276. XCTAssertNil(response?.error)
  277. }
  278. @MainActor
  279. func testThatDownloadingFileAndMovingToDestinationThatIsOccupiedThrowsError() throws {
  280. // Given
  281. let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder")
  282. let directoryCreated = FileManager.createDirectory(at: directoryURL)
  283. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  284. try "random_data".write(to: fileURL, atomically: true, encoding: .utf8)
  285. let expectation = expectation(description: "Download should complete but fail to move file")
  286. var response: DownloadResponse<URL?, AFError>?
  287. // When
  288. AF.download(.get, to: { _, _ in (fileURL, []) })
  289. .response { resp in
  290. response = resp
  291. expectation.fulfill()
  292. }
  293. waitForExpectations(timeout: timeout)
  294. // Then
  295. XCTAssertTrue(directoryCreated)
  296. XCTAssertNotNil(response?.request)
  297. XCTAssertNotNil(response?.response)
  298. XCTAssertNil(response?.fileURL)
  299. XCTAssertNil(response?.resumeData)
  300. XCTAssertNotNil(response?.error)
  301. XCTAssertEqual((response?.error?.underlyingError as? CocoaError)?.code, .fileWriteFileExists)
  302. }
  303. @MainActor
  304. func testThatDownloadOptionsCanRemovePreviousFilePriorToMovingFile() {
  305. // Given
  306. let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder")
  307. let directoryCreated = FileManager.createDirectory(at: directoryURL)
  308. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  309. let expectation = expectation(description: "Download should complete and move file to URL: \(fileURL)")
  310. var response: DownloadResponse<URL?, AFError>?
  311. // When
  312. AF.download(.get,
  313. to: { _, _ in (fileURL, [.removePreviousFile, .createIntermediateDirectories]) })
  314. .response { resp in
  315. response = resp
  316. expectation.fulfill()
  317. }
  318. waitForExpectations(timeout: timeout)
  319. // Then
  320. XCTAssertTrue(directoryCreated)
  321. XCTAssertNotNil(response?.request)
  322. XCTAssertNotNil(response?.response)
  323. XCTAssertNotNil(response?.fileURL)
  324. XCTAssertNil(response?.resumeData)
  325. XCTAssertNil(response?.error)
  326. }
  327. }
  328. // MARK: -
  329. final class DownloadRequestEventsTestCase: BaseTestCase {
  330. @MainActor
  331. func testThatDownloadRequestTriggersAllAppropriateLifetimeEvents() {
  332. // Given
  333. let eventMonitor = ClosureEventMonitor()
  334. let session = Session(eventMonitors: [eventMonitor])
  335. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  336. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  337. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  338. let didCreateTask = expectation(description: "didCreateTask should fire")
  339. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  340. let didComplete = expectation(description: "didComplete should fire")
  341. let didWriteData = expectation(description: "didWriteData should fire")
  342. let didFinishDownloading = expectation(description: "didFinishDownloading should fire")
  343. let didFinishWithResult = expectation(description: "didFinishWithResult should fire")
  344. let didCreate = expectation(description: "didCreate should fire")
  345. let didFinish = expectation(description: "didFinish should fire")
  346. let didResume = expectation(description: "didResume should fire")
  347. let didResumeTask = expectation(description: "didResumeTask should fire")
  348. let didParseResponse = expectation(description: "didParseResponse should fire")
  349. let responseHandler = expectation(description: "responseHandler should fire")
  350. var wroteData = false
  351. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  352. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  353. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  354. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  355. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  356. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  357. eventMonitor.downloadTaskDidWriteData = { _, _, _, _, _ in
  358. guard !wroteData else { return }
  359. wroteData = true
  360. didWriteData.fulfill()
  361. }
  362. eventMonitor.downloadTaskDidFinishDownloadingToURL = { _, _, _ in didFinishDownloading.fulfill() }
  363. eventMonitor.requestDidFinishDownloadingUsingTaskWithResult = { _, _, _ in didFinishWithResult.fulfill() }
  364. eventMonitor.requestDidCreateDestinationURL = { _, _ in didCreate.fulfill() }
  365. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  366. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  367. eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
  368. eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() }
  369. // When
  370. let request = session.download(.get).response { _ in
  371. responseHandler.fulfill()
  372. }
  373. waitForExpectations(timeout: timeout)
  374. // Then
  375. XCTAssertEqual(request.state, .finished)
  376. }
  377. @MainActor
  378. func testThatCancelledDownloadRequestTriggersAllAppropriateLifetimeEvents() {
  379. // Given
  380. let eventMonitor = ClosureEventMonitor()
  381. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  382. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  383. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  384. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  385. let didCreateTask = expectation(description: "didCreateTask should fire")
  386. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  387. let didComplete = expectation(description: "didComplete should fire")
  388. let didFinish = expectation(description: "didFinish should fire")
  389. let didResume = expectation(description: "didResume should fire")
  390. let didResumeTask = expectation(description: "didResumeTask should fire")
  391. let didParseResponse = expectation(description: "didParseResponse should fire")
  392. let didCancel = expectation(description: "didCancel should fire")
  393. let didCancelTask = expectation(description: "didCancelTask should fire")
  394. let responseHandler = expectation(description: "responseHandler should fire")
  395. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  396. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  397. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  398. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  399. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  400. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  401. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  402. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  403. eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() }
  404. eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
  405. eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
  406. // When
  407. let request = session.download(.delay(5)).response { _ in
  408. responseHandler.fulfill()
  409. }
  410. eventMonitor.requestDidResumeTask = { [unowned request] _, _ in
  411. request.cancel()
  412. didResumeTask.fulfill()
  413. }
  414. request.resume()
  415. waitForExpectations(timeout: timeout)
  416. // Then
  417. XCTAssertEqual(request.state, .cancelled)
  418. }
  419. }
  420. // MARK: -
  421. final class DownloadResumeDataTestCase: BaseTestCase {
  422. @MainActor
  423. func testThatCancelledDownloadRequestDoesNotProduceResumeData() {
  424. // Given
  425. let expectation = expectation(description: "Download should be cancelled")
  426. var cancelled = false
  427. var response: DownloadResponse<URL?, AFError>?
  428. // When
  429. let download = AF.download(.download())
  430. download.downloadProgress { [unowned download] progress in
  431. guard !cancelled else { return }
  432. if progress.fractionCompleted > 0.1 {
  433. download.cancel()
  434. cancelled = true
  435. }
  436. }
  437. download.response { resp in
  438. response = resp
  439. expectation.fulfill()
  440. }
  441. waitForExpectations(timeout: timeout)
  442. // Then
  443. XCTAssertNotNil(response?.request)
  444. XCTAssertNotNil(response?.response)
  445. XCTAssertNil(response?.fileURL)
  446. XCTAssertNotNil(response?.error)
  447. XCTAssertNil(response?.resumeData)
  448. XCTAssertNil(download.resumeData)
  449. }
  450. func testThatDownloadRequestProducesResumeDataOnError() {
  451. // Given
  452. let expectation = expectation(description: "download complete")
  453. var response: DownloadResponse<URL?, AFError>?
  454. // When
  455. let download = AF.download(.download(produceError: true))
  456. download.response { resp in
  457. response = resp
  458. expectation.fulfill()
  459. }
  460. waitForExpectations(timeout: timeout)
  461. // Then
  462. XCTAssertNotNil(response?.request)
  463. XCTAssertNotNil(response?.response)
  464. XCTAssertNil(response?.fileURL)
  465. XCTAssertNotNil(response?.error)
  466. XCTAssertNotNil(response?.resumeData)
  467. XCTAssertNotNil(download.resumeData)
  468. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  469. XCTAssertNotNil(download.error?.downloadResumeData)
  470. XCTAssertEqual(download.error?.downloadResumeData, response?.resumeData)
  471. #endif
  472. XCTAssertEqual(response?.resumeData, download.resumeData)
  473. }
  474. @MainActor
  475. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  476. // Given
  477. let expectation = expectation(description: "Download should be cancelled")
  478. var cancelled = false
  479. var response: DownloadResponse<URL?, AFError>?
  480. // When
  481. let download = AF.download(.download())
  482. download.downloadProgress { [unowned download] progress in
  483. guard !cancelled else { return }
  484. if progress.fractionCompleted > 0.1 {
  485. download.cancel(producingResumeData: true)
  486. cancelled = true
  487. }
  488. }
  489. download.response { resp in
  490. response = resp
  491. expectation.fulfill()
  492. }
  493. waitForExpectations(timeout: timeout)
  494. // Then
  495. XCTAssertNotNil(response?.request)
  496. XCTAssertNotNil(response?.response)
  497. XCTAssertNil(response?.fileURL)
  498. XCTAssertNotNil(response?.error)
  499. XCTAssertNotNil(response?.resumeData)
  500. XCTAssertNotNil(download.resumeData)
  501. XCTAssertEqual(response?.resumeData, download.resumeData)
  502. }
  503. @MainActor
  504. func testThatCancelledDownloadResumeDataIsAvailableWithDecodableResponseSerializer() {
  505. // Given
  506. let expectation = expectation(description: "Download should be cancelled")
  507. var cancelled = false
  508. var response: DownloadResponse<TestResponse, AFError>?
  509. // When
  510. let download = AF.download(.download())
  511. download.downloadProgress { [unowned download] progress in
  512. guard !cancelled else { return }
  513. if progress.fractionCompleted > 0.1 {
  514. download.cancel(producingResumeData: true)
  515. cancelled = true
  516. }
  517. }
  518. download.responseDecodable(of: TestResponse.self) { resp in
  519. response = resp
  520. expectation.fulfill()
  521. }
  522. waitForExpectations(timeout: timeout)
  523. // Then
  524. XCTAssertNotNil(response?.request)
  525. XCTAssertNotNil(response?.response)
  526. XCTAssertNil(response?.fileURL)
  527. XCTAssertEqual(response?.result.isFailure, true)
  528. XCTAssertNotNil(response?.result.failure)
  529. XCTAssertNotNil(response?.resumeData)
  530. XCTAssertNotNil(download.resumeData)
  531. XCTAssertEqual(response?.resumeData, download.resumeData)
  532. }
  533. @MainActor
  534. func testThatCancelledDownloadCanBeResumedWithResumeData() {
  535. // Given
  536. let expectation1 = expectation(description: "Download should be cancelled")
  537. var cancelled = false
  538. var response1: DownloadResponse<Data, AFError>?
  539. // When
  540. let download = AF.download(.download())
  541. download.downloadProgress { [unowned download] progress in
  542. guard !cancelled else { return }
  543. if progress.fractionCompleted > 0.1 {
  544. download.cancel(producingResumeData: true)
  545. cancelled = true
  546. }
  547. }
  548. download.responseData { resp in
  549. response1 = resp
  550. expectation1.fulfill()
  551. }
  552. waitForExpectations(timeout: timeout)
  553. guard let resumeData = download.resumeData else {
  554. XCTFail("resumeData should not be nil")
  555. return
  556. }
  557. let expectation2 = expectation(description: "Download should complete")
  558. var progressValues: [Double] = []
  559. var response2: DownloadResponse<Data, AFError>?
  560. AF.download(resumingWith: resumeData)
  561. .downloadProgress { progress in
  562. progressValues.append(progress.fractionCompleted)
  563. }
  564. .responseData { resp in
  565. response2 = resp
  566. expectation2.fulfill()
  567. }
  568. waitForExpectations(timeout: timeout)
  569. // Then
  570. XCTAssertNotNil(response1?.request)
  571. XCTAssertNotNil(response1?.response)
  572. XCTAssertNil(response1?.fileURL)
  573. XCTAssertEqual(response1?.result.isFailure, true)
  574. XCTAssertNotNil(response1?.result.failure)
  575. XCTAssertNotNil(response2?.response)
  576. XCTAssertNotNil(response2?.fileURL)
  577. XCTAssertEqual(response2?.result.isSuccess, true)
  578. XCTAssertNil(response2?.result.failure)
  579. progressValues.forEach { XCTAssertGreaterThanOrEqual($0, 0.1) }
  580. }
  581. @MainActor
  582. func testThatCancelledDownloadProducesMatchingResumeData() {
  583. // Given
  584. let expectation = expectation(description: "Download should be cancelled")
  585. var cancelled = false
  586. var receivedResumeData: Data?
  587. var response: DownloadResponse<URL?, AFError>?
  588. // When
  589. let download = AF.download(.download())
  590. download.downloadProgress { [unowned download] progress in
  591. guard !cancelled else { return }
  592. if progress.fractionCompleted > 0.1 {
  593. download.cancel { receivedResumeData = $0 }
  594. cancelled = true
  595. }
  596. }
  597. download.response { resp in
  598. response = resp
  599. expectation.fulfill()
  600. }
  601. waitForExpectations(timeout: timeout)
  602. // Then
  603. XCTAssertNotNil(response?.request)
  604. XCTAssertNotNil(response?.response)
  605. XCTAssertNil(response?.fileURL)
  606. XCTAssertNotNil(response?.error)
  607. XCTAssertNotNil(response?.resumeData)
  608. XCTAssertNotNil(download.resumeData)
  609. XCTAssertEqual(response?.resumeData, download.resumeData)
  610. XCTAssertEqual(response?.resumeData, receivedResumeData)
  611. XCTAssertEqual(download.resumeData, receivedResumeData)
  612. }
  613. }
  614. // MARK: -
  615. final class DownloadResponseMapTestCase: BaseTestCase {
  616. @MainActor
  617. func testThatMapTransformsSuccessValue() {
  618. // Given
  619. let expectation = expectation(description: "request should succeed")
  620. var response: DownloadResponse<String, AFError>?
  621. // When
  622. AF.download(.get, parameters: ["foo": "bar"]).responseDecodable(of: TestResponse.self) { resp in
  623. response = resp.map { response in
  624. response.args["foo"] ?? "invalid"
  625. }
  626. expectation.fulfill()
  627. }
  628. waitForExpectations(timeout: timeout)
  629. // Then
  630. XCTAssertNotNil(response?.request)
  631. XCTAssertNotNil(response?.response)
  632. XCTAssertNotNil(response?.fileURL)
  633. XCTAssertNil(response?.resumeData)
  634. XCTAssertNil(response?.error)
  635. XCTAssertEqual(response?.result.success, "bar")
  636. XCTAssertNotNil(response?.metrics)
  637. }
  638. @MainActor
  639. func testThatMapPreservesFailureError() {
  640. // Given
  641. let urlString = String.invalidURL
  642. let expectation = expectation(description: "request should fail with invalid URL")
  643. var response: DownloadResponse<String, AFError>?
  644. // When
  645. AF.download(urlString, parameters: ["foo": "bar"]).responseDecodable(of: TestResponse.self) { resp in
  646. response = resp.map { _ in "ignored" }
  647. expectation.fulfill()
  648. }
  649. waitForExpectations(timeout: timeout)
  650. // Then
  651. XCTAssertNotNil(response?.request)
  652. XCTAssertNil(response?.response)
  653. XCTAssertNil(response?.fileURL)
  654. XCTAssertNil(response?.resumeData)
  655. XCTAssertNotNil(response?.error)
  656. XCTAssertEqual(response?.result.isFailure, true)
  657. XCTAssertNotNil(response?.metrics)
  658. }
  659. }
  660. // MARK: -
  661. final class DownloadResponseTryMapTestCase: BaseTestCase {
  662. @MainActor
  663. func testThatTryMapTransformsSuccessValue() {
  664. // Given
  665. let expectation = expectation(description: "request should succeed")
  666. var response: DownloadResponse<String, any Error>?
  667. // When
  668. AF.download(.get, parameters: ["foo": "bar"]).responseDecodable(of: TestResponse.self) { resp in
  669. response = resp.tryMap { response in
  670. response.args["foo"] ?? "invalid"
  671. }
  672. expectation.fulfill()
  673. }
  674. waitForExpectations(timeout: timeout)
  675. // Then
  676. XCTAssertNotNil(response?.request)
  677. XCTAssertNotNil(response?.response)
  678. XCTAssertNotNil(response?.fileURL)
  679. XCTAssertNil(response?.resumeData)
  680. XCTAssertNil(response?.error)
  681. XCTAssertEqual(response?.result.success, "bar")
  682. XCTAssertNotNil(response?.metrics)
  683. }
  684. @MainActor
  685. func testThatTryMapCatchesTransformationError() {
  686. // Given
  687. struct TransformError: Error {}
  688. let expectation = expectation(description: "request should succeed")
  689. var response: DownloadResponse<String, any Error>?
  690. // When
  691. AF.download(.get, parameters: ["foo": "bar"]).responseDecodable(of: TestResponse.self) { resp in
  692. response = resp.tryMap { _ in
  693. throw TransformError()
  694. }
  695. expectation.fulfill()
  696. }
  697. waitForExpectations(timeout: timeout)
  698. // Then
  699. XCTAssertNotNil(response?.request)
  700. XCTAssertNotNil(response?.response)
  701. XCTAssertNotNil(response?.fileURL)
  702. XCTAssertNil(response?.resumeData)
  703. if let error = response?.result.failure {
  704. XCTAssertTrue(error is TransformError)
  705. } else {
  706. XCTFail("flatMap should catch the transformation error")
  707. }
  708. XCTAssertNotNil(response?.metrics)
  709. }
  710. @MainActor
  711. func testThatTryMapPreservesFailureError() {
  712. // Given
  713. let urlString = String.invalidURL
  714. let expectation = expectation(description: "request should fail with 404")
  715. var response: DownloadResponse<String, any Error>?
  716. // When
  717. AF.download(urlString, parameters: ["foo": "bar"]).responseDecodable(of: TestResponse.self) { resp in
  718. response = resp.tryMap { _ in "ignored" }
  719. expectation.fulfill()
  720. }
  721. waitForExpectations(timeout: timeout)
  722. // Then
  723. XCTAssertNotNil(response?.request)
  724. XCTAssertNil(response?.response)
  725. XCTAssertNil(response?.fileURL)
  726. XCTAssertNil(response?.resumeData)
  727. XCTAssertNotNil(response?.error)
  728. XCTAssertEqual(response?.result.isFailure, true)
  729. XCTAssertNotNil(response?.metrics)
  730. }
  731. }
  732. final class DownloadResponseMapErrorTestCase: BaseTestCase {
  733. @MainActor
  734. func testThatMapErrorTransformsFailureValue() {
  735. // Given
  736. let urlString = String.invalidURL
  737. let expectation = expectation(description: "request should not succeed")
  738. var response: DownloadResponse<TestResponse, TestError>?
  739. // When
  740. AF.download(urlString).responseDecodable(of: TestResponse.self) { resp in
  741. response = resp.mapError { error in
  742. TestError.error(error: error)
  743. }
  744. expectation.fulfill()
  745. }
  746. waitForExpectations(timeout: timeout)
  747. // Then
  748. XCTAssertNotNil(response?.request)
  749. XCTAssertNil(response?.response)
  750. XCTAssertNil(response?.fileURL)
  751. XCTAssertNil(response?.resumeData)
  752. XCTAssertNotNil(response?.error)
  753. XCTAssertEqual(response?.result.isFailure, true)
  754. guard let error = response?.error, case .error = error else { XCTFail(); return }
  755. XCTAssertNotNil(response?.metrics)
  756. }
  757. @MainActor
  758. func testThatMapErrorPreservesSuccessValue() {
  759. // Given
  760. let expectation = expectation(description: "request should succeed")
  761. var response: DownloadResponse<Data, TestError>?
  762. // When
  763. AF.download(.get).responseData { resp in
  764. response = resp.mapError { TestError.error(error: $0) }
  765. expectation.fulfill()
  766. }
  767. waitForExpectations(timeout: timeout)
  768. // Then
  769. XCTAssertNotNil(response?.request)
  770. XCTAssertNotNil(response?.response)
  771. XCTAssertNotNil(response?.fileURL)
  772. XCTAssertNil(response?.resumeData)
  773. XCTAssertEqual(response?.result.isSuccess, true)
  774. XCTAssertNotNil(response?.metrics)
  775. }
  776. }
  777. // MARK: -
  778. final class DownloadResponseTryMapErrorTestCase: BaseTestCase {
  779. @MainActor
  780. func testThatTryMapErrorPreservesSuccessValue() {
  781. // Given
  782. let expectation = expectation(description: "request should succeed")
  783. var response: DownloadResponse<Data, any Error>?
  784. // When
  785. AF.download(.get).responseData { resp in
  786. response = resp.tryMapError { TestError.error(error: $0) }
  787. expectation.fulfill()
  788. }
  789. waitForExpectations(timeout: timeout)
  790. // Then
  791. XCTAssertNotNil(response?.request)
  792. XCTAssertNotNil(response?.response)
  793. XCTAssertNotNil(response?.fileURL)
  794. XCTAssertNil(response?.resumeData)
  795. XCTAssertNil(response?.error)
  796. XCTAssertEqual(response?.result.isSuccess, true)
  797. XCTAssertNotNil(response?.metrics)
  798. }
  799. @MainActor
  800. func testThatTryMapErrorCatchesTransformationError() {
  801. // Given
  802. let urlString = String.invalidURL
  803. let expectation = expectation(description: "request should fail")
  804. var response: DownloadResponse<Data, any Error>?
  805. // When
  806. AF.download(urlString).responseData { resp in
  807. response = resp.tryMapError { _ in try TransformationError.error.alwaysFails() }
  808. expectation.fulfill()
  809. }
  810. waitForExpectations(timeout: timeout)
  811. // Then
  812. XCTAssertNotNil(response?.request)
  813. XCTAssertNil(response?.response)
  814. XCTAssertNil(response?.fileURL)
  815. XCTAssertNil(response?.resumeData)
  816. XCTAssertNotNil(response?.error)
  817. XCTAssertEqual(response?.result.isFailure, true)
  818. if let error = response?.result.failure {
  819. XCTAssertTrue(error is TransformationError)
  820. } else {
  821. XCTFail("flatMapError should catch the transformation error")
  822. }
  823. XCTAssertNotNil(response?.metrics)
  824. }
  825. @MainActor
  826. func testThatTryMapErrorTransformsError() {
  827. // Given
  828. let urlString = String.invalidURL
  829. let expectation = expectation(description: "request should fail")
  830. var response: DownloadResponse<Data, any Error>?
  831. // When
  832. AF.download(urlString).responseData { resp in
  833. response = resp.tryMapError { TestError.error(error: $0) }
  834. expectation.fulfill()
  835. }
  836. waitForExpectations(timeout: timeout)
  837. // Then
  838. XCTAssertNotNil(response?.request)
  839. XCTAssertNil(response?.response)
  840. XCTAssertNil(response?.fileURL)
  841. XCTAssertNil(response?.resumeData)
  842. XCTAssertNotNil(response?.error)
  843. XCTAssertEqual(response?.result.isFailure, true)
  844. guard let error = response?.error, case TestError.error = error else { XCTFail(); return }
  845. XCTAssertNotNil(response?.metrics)
  846. }
  847. }