DownloadTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 = Request.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 = Request.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 = Alamofire.Request.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: NSError?
  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. let download = Alamofire.download(urlString, to: { _, _ in fileURL }, withMethod: .get)
  148. download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  149. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  150. byteValues.append(bytes)
  151. let progress = (
  152. completedUnitCount: download.progress.completedUnitCount,
  153. totalUnitCount: download.progress.totalUnitCount
  154. )
  155. progressValues.append(progress)
  156. }
  157. download.response { request, response, data, error in
  158. responseRequest = request
  159. responseResponse = response
  160. responseData = data
  161. responseError = error
  162. expectation.fulfill()
  163. }
  164. waitForExpectations(timeout: timeout, handler: nil)
  165. // Then
  166. XCTAssertNotNil(responseRequest, "response request should not be nil")
  167. XCTAssertNotNil(responseResponse, "response should not be nil")
  168. XCTAssertNil(responseData, "response data should be nil")
  169. XCTAssertNil(responseError, "response error should be nil")
  170. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  171. if byteValues.count == progressValues.count {
  172. for index in 0..<byteValues.count {
  173. let byteValue = byteValues[index]
  174. let progressValue = progressValues[index]
  175. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  176. XCTAssertEqual(
  177. byteValue.totalBytes,
  178. progressValue.completedUnitCount,
  179. "total bytes should be equal to completed unit count"
  180. )
  181. XCTAssertEqual(
  182. byteValue.totalBytesExpected,
  183. progressValue.totalUnitCount,
  184. "total bytes expected should be equal to total unit count"
  185. )
  186. }
  187. }
  188. if let lastByteValue = byteValues.last, let lastProgressValue = progressValues.last {
  189. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  190. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  191. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  192. XCTAssertEqual(
  193. progressValueFractionalCompletion,
  194. 1.0,
  195. "progress value fractional completion should equal 1.0"
  196. )
  197. } else {
  198. XCTFail("last item in bytesValues and progressValues should not be nil")
  199. }
  200. do {
  201. try fileManager.removeItem(at: fileURL)
  202. } catch {
  203. XCTFail("file manager should remove item at URL: \(fileURL)")
  204. }
  205. }
  206. func testDownloadRequestWithParameters() {
  207. // Given
  208. let fileURL = randomCachesFileURL
  209. let urlString = "https://httpbin.org/get"
  210. let parameters = ["foo": "bar"]
  211. let destination: Request.DownloadFileDestination = { _, _ in fileURL }
  212. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  213. var request: URLRequest?
  214. var response: HTTPURLResponse?
  215. var error: NSError?
  216. // When
  217. Alamofire.download(urlString, to: destination, withMethod: .get, parameters: parameters)
  218. .response { responseRequest, responseResponse, _, responseError in
  219. request = responseRequest
  220. response = responseResponse
  221. error = responseError
  222. expectation.fulfill()
  223. }
  224. waitForExpectations(timeout: timeout, handler: nil)
  225. // Then
  226. XCTAssertNotNil(request, "request should not be nil")
  227. XCTAssertNotNil(response, "response should not be nil")
  228. XCTAssertNil(error, "error should be nil")
  229. if
  230. let data = try? Data(contentsOf: fileURL),
  231. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)),
  232. let json = jsonObject as? [String: AnyObject],
  233. let args = json["args"] as? [String: String]
  234. {
  235. XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
  236. } else {
  237. XCTFail("args parameter in JSON should not be nil")
  238. }
  239. }
  240. func testDownloadRequestWithHeaders() {
  241. // Given
  242. let fileURL = randomCachesFileURL
  243. let urlString = "https://httpbin.org/get"
  244. let headers = ["Authorization": "123456"]
  245. let destination: Request.DownloadFileDestination = { _, _ in fileURL }
  246. let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)")
  247. var request: URLRequest?
  248. var response: HTTPURLResponse?
  249. var error: NSError?
  250. // When
  251. Alamofire.download(urlString, to: destination, withMethod: .get, headers: headers)
  252. .response { responseRequest, responseResponse, _, responseError in
  253. request = responseRequest
  254. response = responseResponse
  255. error = responseError
  256. expectation.fulfill()
  257. }
  258. waitForExpectations(timeout: timeout, handler: nil)
  259. // Then
  260. XCTAssertNotNil(request, "request should not be nil")
  261. XCTAssertNotNil(response, "response should not be nil")
  262. XCTAssertNil(error, "error should be nil")
  263. if
  264. let data = try? Data(contentsOf: fileURL),
  265. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)),
  266. let json = jsonObject as? [String: AnyObject],
  267. let headers = json["headers"] as? [String: String]
  268. {
  269. XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456")
  270. } else {
  271. XCTFail("headers parameter in JSON should not be nil")
  272. }
  273. }
  274. }
  275. // MARK: -
  276. class DownloadResumeDataTestCase: BaseTestCase {
  277. let urlString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  278. let destination: Request.DownloadFileDestination = {
  279. let searchPathDirectory: FileManager.SearchPathDirectory = .cachesDirectory
  280. let searchPathDomain: FileManager.SearchPathDomainMask = .userDomainMask
  281. return Request.suggestedDownloadDestination(for: searchPathDirectory, in: searchPathDomain)
  282. }()
  283. func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
  284. // Given
  285. let expectation = self.expectation(description: "Download should be cancelled")
  286. var request: URLRequest?
  287. var response: HTTPURLResponse?
  288. var data: AnyObject?
  289. var error: NSError?
  290. // When
  291. let download = Alamofire.download(urlString, to: destination, withMethod: .get)
  292. .response { responseRequest, responseResponse, responseData, responseError in
  293. request = responseRequest
  294. response = responseResponse
  295. data = responseData
  296. error = responseError
  297. expectation.fulfill()
  298. }
  299. download.cancel()
  300. waitForExpectations(timeout: timeout, handler: nil)
  301. // Then
  302. XCTAssertNotNil(request, "request should not be nil")
  303. XCTAssertNil(response, "response should be nil")
  304. XCTAssertNil(data, "data should be nil")
  305. XCTAssertNotNil(error, "error should not be nil")
  306. XCTAssertNil(download.resumeData, "resume data should be nil")
  307. }
  308. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  309. // Given
  310. let expectation = self.expectation(description: "Download should be cancelled")
  311. var request: URLRequest?
  312. var response: HTTPURLResponse?
  313. var data: AnyObject?
  314. var error: NSError?
  315. // When
  316. let download = Alamofire.download(urlString, to: destination, withMethod: .get)
  317. download.progress { _, _, _ in
  318. download.cancel()
  319. }
  320. download.response { responseRequest, responseResponse, responseData, responseError in
  321. request = responseRequest
  322. response = responseResponse
  323. data = responseData
  324. error = responseError
  325. expectation.fulfill()
  326. }
  327. waitForExpectations(timeout: timeout, handler: nil)
  328. // Then
  329. XCTAssertNotNil(request, "request should not be nil")
  330. XCTAssertNotNil(response, "response should not be nil")
  331. XCTAssertNotNil(data, "data should not be nil")
  332. XCTAssertNotNil(error, "error should not be nil")
  333. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  334. if let responseData = data as? Data, let resumeData = download.resumeData {
  335. XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
  336. } else {
  337. XCTFail("response data or resume data was unexpectedly nil")
  338. }
  339. }
  340. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  341. // Given
  342. let expectation = self.expectation(description: "Download should be cancelled")
  343. var response: Response<AnyObject, NSError>?
  344. // When
  345. let download = Alamofire.download(urlString, to: destination, withMethod: .get)
  346. download.progress { _, _, _ in
  347. download.cancel()
  348. }
  349. download.responseJSON { closureResponse in
  350. response = closureResponse
  351. expectation.fulfill()
  352. }
  353. waitForExpectations(timeout: timeout, handler: nil)
  354. // Then
  355. if let response = response {
  356. XCTAssertNotNil(response.request, "request should not be nil")
  357. XCTAssertNotNil(response.response, "response should not be nil")
  358. XCTAssertNotNil(response.data, "data should not be nil")
  359. XCTAssertTrue(response.result.isFailure, "result should be failure")
  360. XCTAssertNotNil(response.result.error, "result error should not be nil")
  361. } else {
  362. XCTFail("response should not be nil")
  363. }
  364. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  365. }
  366. }