DownloadTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // DownloadTests.swift
  2. //
  3. // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Alamofire
  23. import Foundation
  24. import XCTest
  25. class DownloadInitializationTestCase: BaseTestCase {
  26. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  27. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  28. func testDownloadClassMethodWithMethodURLAndDestination() {
  29. // Given
  30. let URLString = "https://httpbin.org/"
  31. let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  32. // When
  33. let request = Alamofire.download(.GET, URLString, destination: destination)
  34. // Then
  35. XCTAssertNotNil(request.request, "request should not be nil")
  36. XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
  37. XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
  38. XCTAssertNil(request.response, "response should be nil")
  39. }
  40. func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
  41. // Given
  42. let URLString = "https://httpbin.org/"
  43. let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  44. // When
  45. let request = Alamofire.download(.GET, URLString, headers: ["Authorization": "123456"], destination: destination)
  46. // Then
  47. XCTAssertNotNil(request.request, "request should not be nil")
  48. XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
  49. XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
  50. let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
  51. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  52. XCTAssertNil(request.response, "response should be nil")
  53. }
  54. }
  55. // MARK: -
  56. class DownloadResponseTestCase: BaseTestCase {
  57. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  58. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  59. let cachesURL: NSURL = {
  60. let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
  61. let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true)
  62. return cachesURL
  63. }()
  64. var randomCachesFileURL: NSURL {
  65. return cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")
  66. }
  67. func testDownloadRequest() {
  68. // Given
  69. let numberOfLines = 100
  70. let URLString = "https://httpbin.org/stream/\(numberOfLines)"
  71. let destination = Alamofire.Request.suggestedDownloadDestination(
  72. directory: searchPathDirectory,
  73. domain: searchPathDomain
  74. )
  75. let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
  76. var request: NSURLRequest?
  77. var response: NSHTTPURLResponse?
  78. var error: NSError?
  79. // When
  80. Alamofire.download(.GET, URLString, destination: destination)
  81. .response { responseRequest, responseResponse, _, responseError in
  82. request = responseRequest
  83. response = responseResponse
  84. error = responseError
  85. expectation.fulfill()
  86. }
  87. waitForExpectationsWithTimeout(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 = NSFileManager.defaultManager()
  93. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  94. do {
  95. let contents = try fileManager.contentsOfDirectoryAtURL(
  96. 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).filteredArrayUsingPredicate(predicate)
  107. XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
  108. if let file = filteredContents.first as? NSURL {
  109. XCTAssertEqual(
  110. file.lastPathComponent ?? "",
  111. "\(suggestedFilename)",
  112. "filename should be \(suggestedFilename)"
  113. )
  114. if let data = NSData(contentsOfURL: file) {
  115. XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
  116. } else {
  117. XCTFail("data should exist for contents of URL")
  118. }
  119. do {
  120. try fileManager.removeItemAtURL(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 = NSFileManager.defaultManager()
  136. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  137. let filename = "test_download_data"
  138. let fileURL = directory.URLByAppendingPathComponent(filename)
  139. let expectation = expectationWithDescription("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: NSURLRequest?
  143. var responseResponse: NSHTTPURLResponse?
  144. var responseData: NSData?
  145. var responseError: ErrorType?
  146. // When
  147. let download = Alamofire.download(.GET, URLString) { _, _ in
  148. return fileURL
  149. }
  150. download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  151. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  152. byteValues.append(bytes)
  153. let progress = (
  154. completedUnitCount: download.progress.completedUnitCount,
  155. totalUnitCount: download.progress.totalUnitCount
  156. )
  157. progressValues.append(progress)
  158. }
  159. download.response { request, response, data, error in
  160. responseRequest = request
  161. responseResponse = response
  162. responseData = data
  163. responseError = error
  164. expectation.fulfill()
  165. }
  166. waitForExpectationsWithTimeout(timeout, handler: nil)
  167. // Then
  168. XCTAssertNotNil(responseRequest, "response request should not be nil")
  169. XCTAssertNotNil(responseResponse, "response should not be nil")
  170. XCTAssertNil(responseData, "response data should be nil")
  171. XCTAssertNil(responseError, "response error should be nil")
  172. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  173. if byteValues.count == progressValues.count {
  174. for index in 0..<byteValues.count {
  175. let byteValue = byteValues[index]
  176. let progressValue = progressValues[index]
  177. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  178. XCTAssertEqual(
  179. byteValue.totalBytes,
  180. progressValue.completedUnitCount,
  181. "total bytes should be equal to completed unit count"
  182. )
  183. XCTAssertEqual(
  184. byteValue.totalBytesExpected,
  185. progressValue.totalUnitCount,
  186. "total bytes expected should be equal to total unit count"
  187. )
  188. }
  189. }
  190. if let
  191. lastByteValue = byteValues.last,
  192. lastProgressValue = progressValues.last
  193. {
  194. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  195. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  196. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  197. XCTAssertEqual(
  198. progressValueFractionalCompletion,
  199. 1.0,
  200. "progress value fractional completion should equal 1.0"
  201. )
  202. } else {
  203. XCTFail("last item in bytesValues and progressValues should not be nil")
  204. }
  205. do {
  206. try fileManager.removeItemAtURL(fileURL)
  207. } catch {
  208. XCTFail("file manager should remove item at URL: \(fileURL)")
  209. }
  210. }
  211. func testDownloadRequestWithParameters() {
  212. // Given
  213. let fileURL = randomCachesFileURL
  214. let URLString = "https://httpbin.org/get"
  215. let parameters = ["foo": "bar"]
  216. let destination: Request.DownloadFileDestination = { _, _ in fileURL }
  217. let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
  218. var request: NSURLRequest?
  219. var response: NSHTTPURLResponse?
  220. var error: NSError?
  221. // When
  222. Alamofire.download(.GET, URLString, parameters: parameters, destination: destination)
  223. .response { responseRequest, responseResponse, _, responseError in
  224. request = responseRequest
  225. response = responseResponse
  226. error = responseError
  227. expectation.fulfill()
  228. }
  229. waitForExpectationsWithTimeout(timeout, handler: nil)
  230. // Then
  231. XCTAssertNotNil(request, "request should not be nil")
  232. XCTAssertNotNil(response, "response should not be nil")
  233. XCTAssertNil(error, "error should be nil")
  234. if let
  235. data = NSData(contentsOfURL: fileURL),
  236. JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
  237. JSON = JSONObject as? [String: AnyObject],
  238. args = JSON["args"] as? [String: String]
  239. {
  240. XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
  241. } else {
  242. XCTFail("args parameter in JSON should not be nil")
  243. }
  244. }
  245. func testDownloadRequestWithHeaders() {
  246. // Given
  247. let fileURL = randomCachesFileURL
  248. let URLString = "https://httpbin.org/get"
  249. let headers = ["Authorization": "123456"]
  250. let destination: Request.DownloadFileDestination = { _, _ in fileURL }
  251. let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
  252. var request: NSURLRequest?
  253. var response: NSHTTPURLResponse?
  254. var error: NSError?
  255. // When
  256. Alamofire.download(.GET, URLString, headers: headers, destination: destination)
  257. .response { responseRequest, responseResponse, _, responseError in
  258. request = responseRequest
  259. response = responseResponse
  260. error = responseError
  261. expectation.fulfill()
  262. }
  263. waitForExpectationsWithTimeout(timeout, handler: nil)
  264. // Then
  265. XCTAssertNotNil(request, "request should not be nil")
  266. XCTAssertNotNil(response, "response should not be nil")
  267. XCTAssertNil(error, "error should be nil")
  268. if let
  269. data = NSData(contentsOfURL: fileURL),
  270. JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
  271. JSON = JSONObject as? [String: AnyObject],
  272. headers = JSON["headers"] as? [String: String]
  273. {
  274. XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456")
  275. } else {
  276. XCTFail("headers parameter in JSON should not be nil")
  277. }
  278. }
  279. }
  280. // MARK: -
  281. class DownloadResumeDataTestCase: BaseTestCase {
  282. let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  283. let destination: Request.DownloadFileDestination = {
  284. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  285. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  286. return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  287. }()
  288. func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
  289. // Given
  290. let expectation = expectationWithDescription("Download should be cancelled")
  291. var request: NSURLRequest?
  292. var response: NSHTTPURLResponse?
  293. var data: AnyObject?
  294. var error: NSError?
  295. // When
  296. let download = Alamofire.download(.GET, URLString, destination: destination)
  297. .response { responseRequest, responseResponse, responseData, responseError in
  298. request = responseRequest
  299. response = responseResponse
  300. data = responseData
  301. error = responseError
  302. expectation.fulfill()
  303. }
  304. download.cancel()
  305. waitForExpectationsWithTimeout(timeout, handler: nil)
  306. // Then
  307. XCTAssertNotNil(request, "request should not be nil")
  308. XCTAssertNil(response, "response should be nil")
  309. XCTAssertNil(data, "data should be nil")
  310. XCTAssertNotNil(error, "error should not be nil")
  311. XCTAssertNil(download.resumeData, "resume data should be nil")
  312. }
  313. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  314. // Given
  315. let expectation = expectationWithDescription("Download should be cancelled")
  316. var request: NSURLRequest?
  317. var response: NSHTTPURLResponse?
  318. var data: AnyObject?
  319. var error: NSError?
  320. // When
  321. let download = Alamofire.download(.GET, URLString, destination: destination)
  322. download.progress { _, _, _ in
  323. download.cancel()
  324. }
  325. download.response { responseRequest, responseResponse, responseData, responseError in
  326. request = responseRequest
  327. response = responseResponse
  328. data = responseData
  329. error = responseError
  330. expectation.fulfill()
  331. }
  332. waitForExpectationsWithTimeout(timeout, handler: nil)
  333. // Then
  334. XCTAssertNotNil(request, "request should not be nil")
  335. XCTAssertNotNil(response, "response should not be nil")
  336. XCTAssertNotNil(data, "data should not be nil")
  337. XCTAssertNotNil(error, "error should not be nil")
  338. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  339. if let
  340. responseData = data as? NSData,
  341. resumeData = download.resumeData
  342. {
  343. XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
  344. } else {
  345. XCTFail("response data or resume data was unexpectedly nil")
  346. }
  347. }
  348. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  349. // Given
  350. let expectation = expectationWithDescription("Download should be cancelled")
  351. var response: Response<AnyObject, NSError>?
  352. // When
  353. let download = Alamofire.download(.GET, URLString, destination: destination)
  354. download.progress { _, _, _ in
  355. download.cancel()
  356. }
  357. download.responseJSON { closureResponse in
  358. response = closureResponse
  359. expectation.fulfill()
  360. }
  361. waitForExpectationsWithTimeout(timeout, handler: nil)
  362. // Then
  363. if let response = response {
  364. XCTAssertNotNil(response.request, "request should not be nil")
  365. XCTAssertNotNil(response.response, "response should not be nil")
  366. XCTAssertNotNil(response.data, "data should not be nil")
  367. XCTAssertTrue(response.result.isFailure, "result should be failure")
  368. XCTAssertNotNil(response.result.error, "result error should not be nil")
  369. } else {
  370. XCTFail("response should not be nil")
  371. }
  372. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  373. }
  374. }