DownloadTests.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //
  2. // DownloadTests.swift
  3. //
  4. // Copyright (c) 2014-2016 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. let searchPathDirectory: FileManager.SearchPathDirectory = .cachesDirectory
  29. let searchPathDomain: FileManager.SearchPathDomainMask = .userDomainMask
  30. func testDownloadClassMethodWithMethodURLAndDestination() {
  31. // Given
  32. let urlString = "https://httpbin.org/"
  33. // When
  34. let request = Alamofire.download(urlString)
  35. // Then
  36. XCTAssertNotNil(request.request)
  37. XCTAssertEqual(request.request?.httpMethod, "GET")
  38. XCTAssertEqual(request.request?.url?.urlString, urlString)
  39. XCTAssertNil(request.response)
  40. }
  41. func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
  42. // Given
  43. let urlString = "https://httpbin.org/"
  44. let headers = ["Authorization": "123456"]
  45. // When
  46. let request = Alamofire.download(urlString, headers: headers)
  47. // Then
  48. XCTAssertNotNil(request.request)
  49. XCTAssertEqual(request.request?.httpMethod, "GET")
  50. XCTAssertEqual(request.request?.url?.urlString, urlString)
  51. XCTAssertEqual(request.request?.value(forHTTPHeaderField: "Authorization"), "123456")
  52. XCTAssertNil(request.response)
  53. }
  54. }
  55. // MARK: -
  56. class DownloadResponseTestCase: BaseTestCase {
  57. private var randomCachesFileURL: URL {
  58. return FileManager.cachesDirectoryURL.appendingPathComponent("\(UUID().uuidString).json")
  59. }
  60. func testDownloadRequest() {
  61. // Given
  62. let fileURL = randomCachesFileURL
  63. let numberOfLines = 100
  64. let urlString = "https://httpbin.org/stream/\(numberOfLines)"
  65. let destination: DownloadRequest.DownloadFileDestination = { _, _ in (fileURL, []) }
  66. let expectation = self.expectation(description: "Download request should download data to file: \(urlString)")
  67. var response: DefaultDownloadResponse?
  68. // When
  69. Alamofire.download(urlString, to: destination)
  70. .response { resp in
  71. response = resp
  72. expectation.fulfill()
  73. }
  74. waitForExpectations(timeout: timeout, handler: nil)
  75. // Then
  76. XCTAssertNotNil(response?.request)
  77. XCTAssertNotNil(response?.response)
  78. XCTAssertNotNil(response?.destinationURL)
  79. XCTAssertNil(response?.resumeData)
  80. XCTAssertNil(response?.error)
  81. if let destinationURL = response?.destinationURL {
  82. XCTAssertTrue(FileManager.default.fileExists(atPath: destinationURL.path))
  83. if let data = try? Data(contentsOf: destinationURL) {
  84. XCTAssertGreaterThan(data.count, 0)
  85. } else {
  86. XCTFail("data should exist for contents of destinationURL")
  87. }
  88. }
  89. }
  90. func testDownloadRequestWithProgress() {
  91. // Given
  92. let randomBytes = 4 * 1024 * 1024
  93. let urlString = "https://httpbin.org/bytes/\(randomBytes)"
  94. let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)")
  95. var progressValues: [Double] = []
  96. var response: DefaultDownloadResponse?
  97. // When
  98. Alamofire.download(urlString)
  99. .downloadProgress { progress in
  100. progressValues.append(progress.fractionCompleted)
  101. }
  102. .response { resp in
  103. response = resp
  104. expectation.fulfill()
  105. }
  106. waitForExpectations(timeout: timeout, handler: nil)
  107. // Then
  108. XCTAssertNotNil(response?.request)
  109. XCTAssertNotNil(response?.response)
  110. XCTAssertNotNil(response?.temporaryURL)
  111. XCTAssertNil(response?.destinationURL)
  112. XCTAssertNil(response?.resumeData)
  113. XCTAssertNil(response?.error)
  114. var previousProgress: Double = progressValues.first ?? 0.0
  115. for progress in progressValues {
  116. XCTAssertGreaterThanOrEqual(progress, previousProgress)
  117. previousProgress = progress
  118. }
  119. if let lastProgressValue = progressValues.last {
  120. XCTAssertEqual(lastProgressValue, 1.0)
  121. } else {
  122. XCTFail("last item in progressValues should not be nil")
  123. }
  124. }
  125. func testDownloadRequestWithParameters() {
  126. // Given
  127. let urlString = "https://httpbin.org/get"
  128. let parameters = ["foo": "bar"]
  129. let expectation = self.expectation(description: "Download request should download data to file")
  130. var response: DefaultDownloadResponse?
  131. // When
  132. Alamofire.download(urlString, parameters: parameters)
  133. .response { resp in
  134. response = resp
  135. expectation.fulfill()
  136. }
  137. waitForExpectations(timeout: timeout, handler: nil)
  138. // Then
  139. XCTAssertNotNil(response?.request)
  140. XCTAssertNotNil(response?.response)
  141. XCTAssertNotNil(response?.temporaryURL)
  142. XCTAssertNil(response?.destinationURL)
  143. XCTAssertNil(response?.resumeData)
  144. XCTAssertNil(response?.error)
  145. if
  146. let temporaryURL = response?.temporaryURL,
  147. let data = try? Data(contentsOf: temporaryURL),
  148. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)),
  149. let json = jsonObject as? [String: Any],
  150. let args = json["args"] as? [String: String]
  151. {
  152. XCTAssertEqual(args["foo"], "bar")
  153. } else {
  154. XCTFail("args parameter in JSON should not be nil")
  155. }
  156. }
  157. func testDownloadRequestWithHeaders() {
  158. // Given
  159. let fileURL = randomCachesFileURL
  160. let urlString = "https://httpbin.org/get"
  161. let headers = ["Authorization": "123456"]
  162. let destination: DownloadRequest.DownloadFileDestination = { _, _ in (fileURL, []) }
  163. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  164. var response: DefaultDownloadResponse?
  165. // When
  166. Alamofire.download(urlString, headers: headers, to: destination)
  167. .response { resp in
  168. response = resp
  169. expectation.fulfill()
  170. }
  171. waitForExpectations(timeout: timeout, handler: nil)
  172. // Then
  173. XCTAssertNotNil(response?.request)
  174. XCTAssertNotNil(response?.response)
  175. XCTAssertNotNil(response?.destinationURL)
  176. XCTAssertNil(response?.resumeData)
  177. XCTAssertNil(response?.error)
  178. if
  179. let data = try? Data(contentsOf: fileURL),
  180. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
  181. let json = jsonObject as? [String: Any],
  182. let headers = json["headers"] as? [String: String]
  183. {
  184. XCTAssertEqual(headers["Authorization"], "123456")
  185. } else {
  186. XCTFail("headers parameter in JSON should not be nil")
  187. }
  188. }
  189. func testThatDownloadingFileAndMovingToDirectoryThatDoesNotExistThrowsError() {
  190. // Given
  191. let fileURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  192. let expectation = self.expectation(description: "Download request should download data but fail to move file")
  193. var response: DefaultDownloadResponse?
  194. // When
  195. Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [])})
  196. .response { resp in
  197. response = resp
  198. expectation.fulfill()
  199. }
  200. waitForExpectations(timeout: timeout, handler: nil)
  201. // Then
  202. XCTAssertNotNil(response?.request)
  203. XCTAssertNotNil(response?.response)
  204. XCTAssertNotNil(response?.temporaryURL)
  205. XCTAssertNotNil(response?.destinationURL)
  206. XCTAssertNil(response?.resumeData)
  207. XCTAssertNotNil(response?.error)
  208. if let error = response?.error as? CocoaError {
  209. XCTAssertEqual(error.code, .fileNoSuchFile)
  210. } else {
  211. XCTFail("error should not be nil")
  212. }
  213. }
  214. func testThatDownloadOptionsCanCreateIntermediateDirectoriesPriorToMovingFile() {
  215. // Given
  216. let fileURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder/test_output.json")
  217. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  218. var response: DefaultDownloadResponse?
  219. // When
  220. Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.createIntermediateDirectories])})
  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. XCTAssertNotNil(response?.temporaryURL)
  230. XCTAssertNotNil(response?.destinationURL)
  231. XCTAssertNil(response?.resumeData)
  232. XCTAssertNil(response?.error)
  233. }
  234. func testThatDownloadingFileAndMovingToDestinationThatIsOccupiedThrowsError() {
  235. do {
  236. // Given
  237. let directoryURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder")
  238. try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
  239. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  240. try "random_data".write(to: fileURL, atomically: true, encoding: .utf8)
  241. let expectation = self.expectation(description: "Download should complete but fail to move file")
  242. var response: DefaultDownloadResponse?
  243. // When
  244. Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [])})
  245. .response { resp in
  246. response = resp
  247. expectation.fulfill()
  248. }
  249. waitForExpectations(timeout: timeout, handler: nil)
  250. // Then
  251. XCTAssertNotNil(response?.request)
  252. XCTAssertNotNil(response?.response)
  253. XCTAssertNotNil(response?.temporaryURL)
  254. XCTAssertNotNil(response?.destinationURL)
  255. XCTAssertNil(response?.resumeData)
  256. XCTAssertNotNil(response?.error)
  257. if let error = response?.error as? CocoaError {
  258. XCTAssertEqual(error.code, .fileWriteFileExists)
  259. } else {
  260. XCTFail("error should not be nil")
  261. }
  262. } catch {
  263. XCTFail("Test encountered unexpected error: \(error)")
  264. }
  265. }
  266. func testThatDownloadOptionsCanRemovePreviousFilePriorToMovingFile() {
  267. do {
  268. // Given
  269. let directoryURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder")
  270. try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
  271. let fileURL = directoryURL.appendingPathComponent("test_output.json")
  272. let expectation = self.expectation(description: "Download should complete and move file to URL: \(fileURL)")
  273. var response: DefaultDownloadResponse?
  274. // When
  275. Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.removePreviousFile])})
  276. .response { resp in
  277. response = resp
  278. expectation.fulfill()
  279. }
  280. waitForExpectations(timeout: timeout, handler: nil)
  281. // Then
  282. XCTAssertNotNil(response?.request)
  283. XCTAssertNotNil(response?.response)
  284. XCTAssertNotNil(response?.temporaryURL)
  285. XCTAssertNotNil(response?.destinationURL)
  286. XCTAssertNil(response?.resumeData)
  287. XCTAssertNil(response?.error)
  288. } catch {
  289. XCTFail("Test encountered unexpected error: \(error)")
  290. }
  291. }
  292. }
  293. // MARK: -
  294. class DownloadResumeDataTestCase: BaseTestCase {
  295. let urlString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  296. func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
  297. // Given
  298. let expectation = self.expectation(description: "Download should be cancelled")
  299. var response: DefaultDownloadResponse?
  300. // When
  301. let download = Alamofire.download(urlString)
  302. .response { resp in
  303. response = resp
  304. expectation.fulfill()
  305. }
  306. download.cancel()
  307. waitForExpectations(timeout: timeout, handler: nil)
  308. // Then
  309. XCTAssertNotNil(response?.request)
  310. XCTAssertNil(response?.response)
  311. XCTAssertNil(response?.destinationURL)
  312. XCTAssertNil(response?.resumeData)
  313. XCTAssertNotNil(response?.error)
  314. XCTAssertNil(download.resumeData)
  315. }
  316. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  317. // Given
  318. let expectation = self.expectation(description: "Download should be cancelled")
  319. var cancelled = false
  320. var response: DefaultDownloadResponse?
  321. // When
  322. let download = Alamofire.download(urlString)
  323. download.downloadProgress { progress in
  324. guard !cancelled else { return }
  325. if progress.fractionCompleted > 0.1 {
  326. download.cancel()
  327. cancelled = true
  328. }
  329. }
  330. download.response { resp in
  331. response = resp
  332. expectation.fulfill()
  333. }
  334. waitForExpectations(timeout: timeout, handler: nil)
  335. // Then
  336. XCTAssertNotNil(response?.request)
  337. XCTAssertNotNil(response?.response)
  338. XCTAssertNil(response?.destinationURL)
  339. XCTAssertNotNil(response?.error)
  340. XCTAssertNotNil(response?.resumeData)
  341. XCTAssertNotNil(download.resumeData)
  342. XCTAssertEqual(response?.resumeData, download.resumeData)
  343. }
  344. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  345. // Given
  346. let expectation = self.expectation(description: "Download should be cancelled")
  347. var cancelled = false
  348. var response: DownloadResponse<Any>?
  349. // When
  350. let download = Alamofire.download(urlString)
  351. download.downloadProgress { progress in
  352. guard !cancelled else { return }
  353. if progress.fractionCompleted > 0.1 {
  354. download.cancel()
  355. cancelled = true
  356. }
  357. }
  358. download.responseJSON { resp in
  359. response = resp
  360. expectation.fulfill()
  361. }
  362. waitForExpectations(timeout: timeout, handler: nil)
  363. // Then
  364. XCTAssertNotNil(response?.request)
  365. XCTAssertNotNil(response?.response)
  366. XCTAssertNil(response?.destinationURL)
  367. XCTAssertEqual(response?.result.isFailure, true)
  368. XCTAssertNotNil(response?.result.error)
  369. XCTAssertNotNil(response?.resumeData)
  370. XCTAssertNotNil(download.resumeData)
  371. XCTAssertEqual(response?.resumeData, download.resumeData)
  372. }
  373. }