DownloadTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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: NSSearchPathDirectory = .CachesDirectory
  29. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  30. func testDownloadClassMethodWithMethodURLAndDestination() {
  31. // Given
  32. let URLString = "https://httpbin.org/"
  33. let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  34. // When
  35. let request = Alamofire.download(.GET, URLString, destination: destination)
  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 destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  46. // When
  47. let request = Alamofire.download(.GET, URLString, headers: ["Authorization": "123456"], destination: destination)
  48. // Then
  49. XCTAssertNotNil(request.request, "request should not be nil")
  50. XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
  51. XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
  52. let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
  53. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  54. XCTAssertNil(request.response, "response should be nil")
  55. }
  56. }
  57. // MARK: -
  58. class DownloadResponseTestCase: BaseTestCase {
  59. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  60. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  61. let cachesURL: NSURL = {
  62. let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
  63. let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true)
  64. return cachesURL
  65. }()
  66. var randomCachesFileURL: NSURL {
  67. #if swift(>=2.3)
  68. return cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")!
  69. #else
  70. return cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")
  71. #endif
  72. }
  73. func testDownloadRequest() {
  74. // Given
  75. let numberOfLines = 100
  76. let URLString = "https://httpbin.org/stream/\(numberOfLines)"
  77. let destination = Alamofire.Request.suggestedDownloadDestination(
  78. directory: searchPathDirectory,
  79. domain: searchPathDomain
  80. )
  81. let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
  82. var request: NSURLRequest?
  83. var response: NSHTTPURLResponse?
  84. var error: NSError?
  85. // When
  86. Alamofire.download(.GET, URLString, destination: destination)
  87. .response { responseRequest, responseResponse, _, responseError in
  88. request = responseRequest
  89. response = responseResponse
  90. error = responseError
  91. expectation.fulfill()
  92. }
  93. waitForExpectationsWithTimeout(timeout, handler: nil)
  94. // Then
  95. XCTAssertNotNil(request, "request should not be nil")
  96. XCTAssertNotNil(response, "response should not be nil")
  97. XCTAssertNil(error, "error should be nil")
  98. let fileManager = NSFileManager.defaultManager()
  99. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  100. do {
  101. let contents = try fileManager.contentsOfDirectoryAtURL(
  102. directory,
  103. includingPropertiesForKeys: nil,
  104. options: .SkipsHiddenFiles
  105. )
  106. #if os(iOS) || os(tvOS)
  107. let suggestedFilename = "\(numberOfLines)"
  108. #elseif os(OSX)
  109. let suggestedFilename = "\(numberOfLines).json"
  110. #endif
  111. let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
  112. let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
  113. XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
  114. if let file = filteredContents.first as? NSURL {
  115. XCTAssertEqual(
  116. file.lastPathComponent ?? "",
  117. "\(suggestedFilename)",
  118. "filename should be \(suggestedFilename)"
  119. )
  120. if let data = NSData(contentsOfURL: file) {
  121. XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
  122. } else {
  123. XCTFail("data should exist for contents of URL")
  124. }
  125. do {
  126. try fileManager.removeItemAtURL(file)
  127. } catch {
  128. XCTFail("file manager should remove item at URL: \(file)")
  129. }
  130. } else {
  131. XCTFail("file should not be nil")
  132. }
  133. } catch {
  134. XCTFail("contents should not be nil")
  135. }
  136. }
  137. func testDownloadRequestWithProgress() {
  138. // Given
  139. let randomBytes = 4 * 1024 * 1024
  140. let URLString = "https://httpbin.org/bytes/\(randomBytes)"
  141. let fileManager = NSFileManager.defaultManager()
  142. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  143. let filename = "test_download_data"
  144. #if swift(>=2.3)
  145. let fileURL = directory.URLByAppendingPathComponent(filename)!
  146. #else
  147. let fileURL = directory.URLByAppendingPathComponent(filename)
  148. #endif
  149. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  150. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  151. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  152. var responseRequest: NSURLRequest?
  153. var responseResponse: NSHTTPURLResponse?
  154. var responseData: NSData?
  155. var responseError: ErrorType?
  156. // When
  157. let download = Alamofire.download(.GET, URLString) { _, _ in
  158. return fileURL
  159. }
  160. download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  161. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  162. byteValues.append(bytes)
  163. let progress = (
  164. completedUnitCount: download.progress.completedUnitCount,
  165. totalUnitCount: download.progress.totalUnitCount
  166. )
  167. progressValues.append(progress)
  168. }
  169. download.response { request, response, data, error in
  170. responseRequest = request
  171. responseResponse = response
  172. responseData = data
  173. responseError = error
  174. expectation.fulfill()
  175. }
  176. waitForExpectationsWithTimeout(timeout, handler: nil)
  177. // Then
  178. XCTAssertNotNil(responseRequest, "response request should not be nil")
  179. XCTAssertNotNil(responseResponse, "response should not be nil")
  180. XCTAssertNil(responseData, "response data should be nil")
  181. XCTAssertNil(responseError, "response error should be nil")
  182. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  183. if byteValues.count == progressValues.count {
  184. for index in 0..<byteValues.count {
  185. let byteValue = byteValues[index]
  186. let progressValue = progressValues[index]
  187. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  188. XCTAssertEqual(
  189. byteValue.totalBytes,
  190. progressValue.completedUnitCount,
  191. "total bytes should be equal to completed unit count"
  192. )
  193. XCTAssertEqual(
  194. byteValue.totalBytesExpected,
  195. progressValue.totalUnitCount,
  196. "total bytes expected should be equal to total unit count"
  197. )
  198. }
  199. }
  200. if let
  201. lastByteValue = byteValues.last,
  202. lastProgressValue = progressValues.last
  203. {
  204. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  205. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  206. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  207. XCTAssertEqual(
  208. progressValueFractionalCompletion,
  209. 1.0,
  210. "progress value fractional completion should equal 1.0"
  211. )
  212. } else {
  213. XCTFail("last item in bytesValues and progressValues should not be nil")
  214. }
  215. do {
  216. try fileManager.removeItemAtURL(fileURL)
  217. } catch {
  218. XCTFail("file manager should remove item at URL: \(fileURL)")
  219. }
  220. }
  221. func testDownloadRequestWithParameters() {
  222. // Given
  223. let fileURL = randomCachesFileURL
  224. let URLString = "https://httpbin.org/get"
  225. let parameters = ["foo": "bar"]
  226. let destination: Request.DownloadFileDestination = { _, _ in fileURL }
  227. let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
  228. var request: NSURLRequest?
  229. var response: NSHTTPURLResponse?
  230. var error: NSError?
  231. // When
  232. Alamofire.download(.GET, URLString, parameters: parameters, destination: destination)
  233. .response { responseRequest, responseResponse, _, responseError in
  234. request = responseRequest
  235. response = responseResponse
  236. error = responseError
  237. expectation.fulfill()
  238. }
  239. waitForExpectationsWithTimeout(timeout, handler: nil)
  240. // Then
  241. XCTAssertNotNil(request, "request should not be nil")
  242. XCTAssertNotNil(response, "response should not be nil")
  243. XCTAssertNil(error, "error should be nil")
  244. if let
  245. data = NSData(contentsOfURL: fileURL),
  246. JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
  247. JSON = JSONObject as? [String: AnyObject],
  248. args = JSON["args"] as? [String: String]
  249. {
  250. XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
  251. } else {
  252. XCTFail("args parameter in JSON should not be nil")
  253. }
  254. }
  255. func testDownloadRequestWithHeaders() {
  256. // Given
  257. let fileURL = randomCachesFileURL
  258. let URLString = "https://httpbin.org/get"
  259. let headers = ["Authorization": "123456"]
  260. let destination: Request.DownloadFileDestination = { _, _ in fileURL }
  261. let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
  262. var request: NSURLRequest?
  263. var response: NSHTTPURLResponse?
  264. var error: NSError?
  265. // When
  266. Alamofire.download(.GET, URLString, headers: headers, destination: destination)
  267. .response { responseRequest, responseResponse, _, responseError in
  268. request = responseRequest
  269. response = responseResponse
  270. error = responseError
  271. expectation.fulfill()
  272. }
  273. waitForExpectationsWithTimeout(timeout, handler: nil)
  274. // Then
  275. XCTAssertNotNil(request, "request should not be nil")
  276. XCTAssertNotNil(response, "response should not be nil")
  277. XCTAssertNil(error, "error should be nil")
  278. if let
  279. data = NSData(contentsOfURL: fileURL),
  280. JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
  281. JSON = JSONObject as? [String: AnyObject],
  282. headers = JSON["headers"] as? [String: String]
  283. {
  284. XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456")
  285. } else {
  286. XCTFail("headers parameter in JSON should not be nil")
  287. }
  288. }
  289. }
  290. // MARK: -
  291. class DownloadResumeDataTestCase: BaseTestCase {
  292. let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  293. let destination: Request.DownloadFileDestination = {
  294. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  295. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  296. return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  297. }()
  298. func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
  299. // Given
  300. let expectation = expectationWithDescription("Download should be cancelled")
  301. var request: NSURLRequest?
  302. var response: NSHTTPURLResponse?
  303. var data: AnyObject?
  304. var error: NSError?
  305. // When
  306. let download = Alamofire.download(.GET, URLString, destination: destination)
  307. .response { responseRequest, responseResponse, responseData, responseError in
  308. request = responseRequest
  309. response = responseResponse
  310. data = responseData
  311. error = responseError
  312. expectation.fulfill()
  313. }
  314. download.cancel()
  315. waitForExpectationsWithTimeout(timeout, handler: nil)
  316. // Then
  317. XCTAssertNotNil(request, "request should not be nil")
  318. XCTAssertNil(response, "response should be nil")
  319. XCTAssertNil(data, "data should be nil")
  320. XCTAssertNotNil(error, "error should not be nil")
  321. XCTAssertNil(download.resumeData, "resume data should be nil")
  322. }
  323. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  324. // Given
  325. let expectation = expectationWithDescription("Download should be cancelled")
  326. var request: NSURLRequest?
  327. var response: NSHTTPURLResponse?
  328. var data: AnyObject?
  329. var error: NSError?
  330. // When
  331. let download = Alamofire.download(.GET, URLString, destination: destination)
  332. download.progress { _, _, _ in
  333. download.cancel()
  334. }
  335. download.response { responseRequest, responseResponse, responseData, responseError in
  336. request = responseRequest
  337. response = responseResponse
  338. data = responseData
  339. error = responseError
  340. expectation.fulfill()
  341. }
  342. waitForExpectationsWithTimeout(timeout, handler: nil)
  343. // Then
  344. XCTAssertNotNil(request, "request should not be nil")
  345. XCTAssertNotNil(response, "response should not be nil")
  346. XCTAssertNotNil(data, "data should not be nil")
  347. XCTAssertNotNil(error, "error should not be nil")
  348. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  349. if let
  350. responseData = data as? NSData,
  351. resumeData = download.resumeData
  352. {
  353. XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
  354. } else {
  355. XCTFail("response data or resume data was unexpectedly nil")
  356. }
  357. }
  358. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  359. // Given
  360. let expectation = expectationWithDescription("Download should be cancelled")
  361. var response: Response<AnyObject, NSError>?
  362. // When
  363. let download = Alamofire.download(.GET, URLString, destination: destination)
  364. download.progress { _, _, _ in
  365. download.cancel()
  366. }
  367. download.responseJSON { closureResponse in
  368. response = closureResponse
  369. expectation.fulfill()
  370. }
  371. waitForExpectationsWithTimeout(timeout, handler: nil)
  372. // Then
  373. if let response = response {
  374. XCTAssertNotNil(response.request, "request should not be nil")
  375. XCTAssertNotNil(response.response, "response should not be nil")
  376. XCTAssertNotNil(response.data, "data should not be nil")
  377. XCTAssertTrue(response.result.isFailure, "result should be failure")
  378. XCTAssertNotNil(response.result.error, "result error should not be nil")
  379. } else {
  380. XCTFail("response should not be nil")
  381. }
  382. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  383. }
  384. }