DownloadTests.swift 18 KB

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