DownloadTests.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. let destination = DownloadRequest.suggestedDownloadDestination(for: searchPathDirectory, in: searchPathDomain)
  34. // When
  35. let request = Alamofire.download(urlString, to: destination, withMethod: .get)
  36. // Then
  37. XCTAssertNotNil(request.request, "request should not be nil")
  38. XCTAssertEqual(request.request?.httpMethod ?? "", "GET", "request HTTP method should be GET")
  39. XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
  40. XCTAssertNil(request.response, "response should be nil")
  41. }
  42. func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
  43. // Given
  44. let urlString = "https://httpbin.org/"
  45. let headers = ["Authorization": "123456"]
  46. let destination = DownloadRequest.suggestedDownloadDestination(for: searchPathDirectory, in: searchPathDomain)
  47. // When
  48. let request = Alamofire.download(urlString, to: destination, withMethod: .get, headers: headers)
  49. // Then
  50. XCTAssertNotNil(request.request, "request should not be nil")
  51. XCTAssertEqual(request.request?.httpMethod ?? "", "GET", "request HTTP method should be GET")
  52. XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
  53. let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
  54. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  55. XCTAssertNil(request.response, "response should be nil")
  56. }
  57. }
  58. // MARK: -
  59. class DownloadResponseTestCase: BaseTestCase {
  60. let searchPathDirectory: FileManager.SearchPathDirectory = .cachesDirectory
  61. let searchPathDomain: FileManager.SearchPathDomainMask = .userDomainMask
  62. let cachesURL: URL = {
  63. let cachesDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
  64. let cachesURL = URL(fileURLWithPath: cachesDirectory, isDirectory: true)
  65. return cachesURL
  66. }()
  67. var randomCachesFileURL: URL {
  68. return cachesURL.appendingPathComponent("\(UUID().uuidString).json")
  69. }
  70. func testDownloadRequest() {
  71. // Given
  72. let numberOfLines = 100
  73. let urlString = "https://httpbin.org/stream/\(numberOfLines)"
  74. let destination = DownloadRequest.suggestedDownloadDestination(for: searchPathDirectory, in: searchPathDomain)
  75. let expectation = self.expectation(description: "Download request should download data to file: \(urlString)")
  76. var request: URLRequest?
  77. var response: HTTPURLResponse?
  78. var error: Error?
  79. // When
  80. Alamofire.download(urlString, to: destination, withMethod: .get)
  81. .response { responseRequest, responseResponse, _, responseError in
  82. request = responseRequest
  83. response = responseResponse
  84. error = responseError
  85. expectation.fulfill()
  86. }
  87. waitForExpectations(timeout: timeout, handler: nil)
  88. // Then
  89. XCTAssertNotNil(request, "request should not be nil")
  90. XCTAssertNotNil(response, "response should not be nil")
  91. XCTAssertNil(error, "error should be nil")
  92. let fileManager = FileManager.default
  93. let directory = fileManager.urls(for: searchPathDirectory, in: self.searchPathDomain)[0]
  94. do {
  95. let contents = try fileManager.contentsOfDirectory(
  96. at: directory,
  97. includingPropertiesForKeys: nil,
  98. options: .skipsHiddenFiles
  99. )
  100. #if os(iOS) || os(tvOS)
  101. let suggestedFilename = "\(numberOfLines)"
  102. #elseif os(OSX)
  103. let suggestedFilename = "\(numberOfLines).json"
  104. #endif
  105. let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
  106. let filteredContents = (contents as NSArray).filtered(using: predicate)
  107. XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
  108. if let file = filteredContents.first as? URL {
  109. XCTAssertEqual(
  110. file.lastPathComponent,
  111. "\(suggestedFilename)",
  112. "filename should be \(suggestedFilename)"
  113. )
  114. if let data = try? Data(contentsOf: file) {
  115. XCTAssertGreaterThan(data.count, 0, "data length should be non-zero")
  116. } else {
  117. XCTFail("data should exist for contents of URL")
  118. }
  119. do {
  120. try fileManager.removeItem(at: file)
  121. } catch {
  122. XCTFail("file manager should remove item at URL: \(file)")
  123. }
  124. } else {
  125. XCTFail("file should not be nil")
  126. }
  127. } catch {
  128. XCTFail("contents should not be nil")
  129. }
  130. }
  131. func testDownloadRequestWithProgress() {
  132. // Given
  133. let randomBytes = 4 * 1024 * 1024
  134. let urlString = "https://httpbin.org/bytes/\(randomBytes)"
  135. let fileManager = FileManager.default
  136. let directory = fileManager.urls(for: searchPathDirectory, in: self.searchPathDomain)[0]
  137. let filename = "test_download_data"
  138. let fileURL = directory.appendingPathComponent(filename)
  139. let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)")
  140. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  141. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  142. var responseRequest: URLRequest?
  143. var responseResponse: HTTPURLResponse?
  144. var responseData: Data?
  145. var responseError: Error?
  146. // When
  147. Alamofire.download(urlString, to: { _, _ in fileURL }, withMethod: .get)
  148. .downloadProgress { progress in
  149. progressValues.append((progress.completedUnitCount, progress.totalUnitCount))
  150. }
  151. .downloadProgress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  152. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  153. byteValues.append(bytes)
  154. }
  155. .response { request, response, data, error in
  156. responseRequest = request
  157. responseResponse = response
  158. responseData = data
  159. responseError = error
  160. expectation.fulfill()
  161. }
  162. waitForExpectations(timeout: timeout, handler: nil)
  163. // Then
  164. XCTAssertNotNil(responseRequest)
  165. XCTAssertNotNil(responseResponse)
  166. XCTAssertNil(responseData)
  167. XCTAssertNil(responseError)
  168. XCTAssertEqual(byteValues.count, progressValues.count)
  169. if byteValues.count == progressValues.count {
  170. for (byteValue, progressValue) in zip(byteValues, progressValues) {
  171. XCTAssertGreaterThan(byteValue.bytes, 0)
  172. print("\(byteValue.totalBytes) - \(progressValue.completedUnitCount)")
  173. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount)
  174. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount)
  175. }
  176. }
  177. if let lastByteValue = byteValues.last, let lastProgressValue = progressValues.last {
  178. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  179. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  180. XCTAssertEqual(byteValueFractionalCompletion, 1.0)
  181. XCTAssertEqual(progressValueFractionalCompletion, 1.0)
  182. } else {
  183. XCTFail("last item in bytesValues and progressValues should not be nil")
  184. }
  185. do {
  186. try fileManager.removeItem(at: fileURL)
  187. } catch {
  188. XCTFail("file manager should remove item at URL: \(fileURL)")
  189. }
  190. }
  191. func testDownloadRequestWithParameters() {
  192. // Given
  193. let fileURL = randomCachesFileURL
  194. let urlString = "https://httpbin.org/get"
  195. let parameters = ["foo": "bar"]
  196. let destination: DownloadRequest.DownloadFileDestination = { _, _ in fileURL }
  197. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  198. var request: URLRequest?
  199. var response: HTTPURLResponse?
  200. var error: Error?
  201. // When
  202. Alamofire.download(urlString, to: destination, withMethod: .get, parameters: parameters)
  203. .response { responseRequest, responseResponse, _, responseError in
  204. request = responseRequest
  205. response = responseResponse
  206. error = responseError
  207. expectation.fulfill()
  208. }
  209. waitForExpectations(timeout: timeout, handler: nil)
  210. // Then
  211. XCTAssertNotNil(request, "request should not be nil")
  212. XCTAssertNotNil(response, "response should not be nil")
  213. XCTAssertNil(error, "error should be nil")
  214. if
  215. let data = try? Data(contentsOf: fileURL),
  216. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)),
  217. let json = jsonObject as? [String: Any],
  218. let args = json["args"] as? [String: String]
  219. {
  220. XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
  221. } else {
  222. XCTFail("args parameter in JSON should not be nil")
  223. }
  224. }
  225. func testDownloadRequestWithHeaders() {
  226. // Given
  227. let fileURL = randomCachesFileURL
  228. let urlString = "https://httpbin.org/get"
  229. let headers = ["Authorization": "123456"]
  230. let destination: DownloadRequest.DownloadFileDestination = { _, _ in fileURL }
  231. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  232. var request: URLRequest?
  233. var response: HTTPURLResponse?
  234. var error: Error?
  235. // When
  236. Alamofire.download(urlString, to: destination, withMethod: .get, headers: headers)
  237. .response { responseRequest, responseResponse, _, responseError in
  238. request = responseRequest
  239. response = responseResponse
  240. error = responseError
  241. expectation.fulfill()
  242. }
  243. waitForExpectations(timeout: timeout, handler: nil)
  244. // Then
  245. XCTAssertNotNil(request, "request should not be nil")
  246. XCTAssertNotNil(response, "response should not be nil")
  247. XCTAssertNil(error, "error should be nil")
  248. if
  249. let data = try? Data(contentsOf: fileURL),
  250. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)),
  251. let json = jsonObject as? [String: Any],
  252. let headers = json["headers"] as? [String: String]
  253. {
  254. XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456")
  255. } else {
  256. XCTFail("headers parameter in JSON should not be nil")
  257. }
  258. }
  259. }
  260. // MARK: -
  261. class DownloadResumeDataTestCase: BaseTestCase {
  262. let urlString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  263. let destination: DownloadRequest.DownloadFileDestination = {
  264. let searchPathDirectory: FileManager.SearchPathDirectory = .cachesDirectory
  265. let searchPathDomain: FileManager.SearchPathDomainMask = .userDomainMask
  266. return DownloadRequest.suggestedDownloadDestination(for: searchPathDirectory, in: searchPathDomain)
  267. }()
  268. func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
  269. // Given
  270. let expectation = self.expectation(description: "Download should be cancelled")
  271. var request: URLRequest?
  272. var response: HTTPURLResponse?
  273. var data: Data?
  274. var error: Error?
  275. // When
  276. let download = Alamofire.download(urlString, to: destination, withMethod: .get)
  277. .response { responseRequest, responseResponse, responseData, responseError in
  278. request = responseRequest
  279. response = responseResponse
  280. data = responseData
  281. error = responseError
  282. expectation.fulfill()
  283. }
  284. download.cancel()
  285. waitForExpectations(timeout: timeout, handler: nil)
  286. // Then
  287. XCTAssertNotNil(request, "request should not be nil")
  288. XCTAssertNil(response, "response should be nil")
  289. XCTAssertNil(data, "data should be nil")
  290. XCTAssertNotNil(error, "error should not be nil")
  291. XCTAssertNil(download.resumeData, "resume data should be nil")
  292. }
  293. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  294. // Given
  295. let expectation = self.expectation(description: "Download should be cancelled")
  296. var request: URLRequest?
  297. var response: HTTPURLResponse?
  298. var data: Data?
  299. var error: Error?
  300. // When
  301. let download = Alamofire.download(urlString, to: destination, withMethod: .get)
  302. download.downloadProgress { _, _, _ in
  303. download.cancel()
  304. }
  305. download.response { responseRequest, responseResponse, responseData, responseError in
  306. request = responseRequest
  307. response = responseResponse
  308. data = responseData
  309. error = responseError
  310. expectation.fulfill()
  311. }
  312. waitForExpectations(timeout: timeout, handler: nil)
  313. // Then
  314. XCTAssertNotNil(request, "request should not be nil")
  315. XCTAssertNotNil(response, "response should not be nil")
  316. XCTAssertNotNil(data, "data should not be nil")
  317. XCTAssertNotNil(error, "error should not be nil")
  318. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  319. if let responseData = data, let resumeData = download.resumeData {
  320. XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
  321. } else {
  322. XCTFail("response data or resume data was unexpectedly nil")
  323. }
  324. }
  325. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  326. // Given
  327. let expectation = self.expectation(description: "Download should be cancelled")
  328. var response: Response<Any>?
  329. // When
  330. let download = Alamofire.download(urlString, to: destination, withMethod: .get)
  331. download.downloadProgress { _, _, _ in
  332. download.cancel()
  333. }
  334. download.responseJSON { closureResponse in
  335. response = closureResponse
  336. expectation.fulfill()
  337. }
  338. waitForExpectations(timeout: timeout, handler: nil)
  339. // Then
  340. if let response = response {
  341. XCTAssertNotNil(response.request, "request should not be nil")
  342. XCTAssertNotNil(response.response, "response should not be nil")
  343. XCTAssertNotNil(response.data, "data should not be nil")
  344. XCTAssertTrue(response.result.isFailure, "result should be failure")
  345. XCTAssertNotNil(response.result.error, "result error should not be nil")
  346. } else {
  347. XCTFail("response should not be nil")
  348. }
  349. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  350. }
  351. }