DownloadTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // DownloadTests.swift
  2. //
  3. // Copyright (c) 2014–2015 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. func testDownloadRequest() {
  60. // Given
  61. let numberOfLines = 100
  62. let URLString = "https://httpbin.org/stream/\(numberOfLines)"
  63. let destination = Alamofire.Request.suggestedDownloadDestination(
  64. directory: searchPathDirectory,
  65. domain: searchPathDomain
  66. )
  67. let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
  68. var request: NSURLRequest?
  69. var response: NSHTTPURLResponse?
  70. var error: ErrorType?
  71. // When
  72. Alamofire.download(.GET, URLString, destination: destination)
  73. .response { responseRequest, responseResponse, _, responseError in
  74. request = responseRequest
  75. response = responseResponse
  76. error = responseError
  77. expectation.fulfill()
  78. }
  79. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  80. // Then
  81. XCTAssertNotNil(request, "request should not be nil")
  82. XCTAssertNotNil(response, "response should not be nil")
  83. XCTAssertNil(error, "error should be nil")
  84. let fileManager = NSFileManager.defaultManager()
  85. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  86. do {
  87. let contents = try fileManager.contentsOfDirectoryAtURL(
  88. directory,
  89. includingPropertiesForKeys: nil,
  90. options: .SkipsHiddenFiles
  91. )
  92. #if os(iOS)
  93. let suggestedFilename = "\(numberOfLines)"
  94. #elseif os(OSX)
  95. let suggestedFilename = "\(numberOfLines).json"
  96. #endif
  97. let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
  98. let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
  99. XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
  100. if let file = filteredContents.first as? NSURL {
  101. XCTAssertEqual(
  102. file.lastPathComponent ?? "",
  103. "\(suggestedFilename)",
  104. "filename should be \(suggestedFilename)"
  105. )
  106. if let data = NSData(contentsOfURL: file) {
  107. XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
  108. } else {
  109. XCTFail("data should exist for contents of URL")
  110. }
  111. do {
  112. try fileManager.removeItemAtURL(file)
  113. } catch {
  114. XCTFail("file manager should remove item at URL: \(file)")
  115. }
  116. } else {
  117. XCTFail("file should not be nil")
  118. }
  119. } catch {
  120. XCTFail("contents should not be nil")
  121. }
  122. }
  123. func testDownloadRequestWithProgress() {
  124. // Given
  125. let randomBytes = 4 * 1024 * 1024
  126. let URLString = "https://httpbin.org/bytes/\(randomBytes)"
  127. let fileManager = NSFileManager.defaultManager()
  128. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  129. let filename = "test_download_data"
  130. let fileURL = directory.URLByAppendingPathComponent(filename)
  131. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  132. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  133. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  134. var responseRequest: NSURLRequest?
  135. var responseResponse: NSHTTPURLResponse?
  136. var responseData: NSData?
  137. var responseError: ErrorType?
  138. // When
  139. let download = Alamofire.download(.GET, URLString) { _, _ in
  140. return fileURL
  141. }
  142. download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  143. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  144. byteValues.append(bytes)
  145. let progress = (
  146. completedUnitCount: download.progress.completedUnitCount,
  147. totalUnitCount: download.progress.totalUnitCount
  148. )
  149. progressValues.append(progress)
  150. }
  151. download.response { request, response, data, error in
  152. responseRequest = request
  153. responseResponse = response
  154. responseData = data
  155. responseError = error
  156. expectation.fulfill()
  157. }
  158. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  159. // Then
  160. XCTAssertNotNil(responseRequest, "response request should not be nil")
  161. XCTAssertNotNil(responseResponse, "response should not be nil")
  162. XCTAssertNil(responseData, "response data should be nil")
  163. XCTAssertNil(responseError, "response error should be nil")
  164. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  165. if byteValues.count == progressValues.count {
  166. for index in 0..<byteValues.count {
  167. let byteValue = byteValues[index]
  168. let progressValue = progressValues[index]
  169. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  170. XCTAssertEqual(
  171. byteValue.totalBytes,
  172. progressValue.completedUnitCount,
  173. "total bytes should be equal to completed unit count"
  174. )
  175. XCTAssertEqual(
  176. byteValue.totalBytesExpected,
  177. progressValue.totalUnitCount,
  178. "total bytes expected should be equal to total unit count"
  179. )
  180. }
  181. }
  182. if let
  183. lastByteValue = byteValues.last,
  184. lastProgressValue = progressValues.last
  185. {
  186. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  187. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  188. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  189. XCTAssertEqual(
  190. progressValueFractionalCompletion,
  191. 1.0,
  192. "progress value fractional completion should equal 1.0"
  193. )
  194. } else {
  195. XCTFail("last item in bytesValues and progressValues should not be nil")
  196. }
  197. do {
  198. try fileManager.removeItemAtURL(fileURL)
  199. } catch {
  200. XCTFail("file manager should remove item at URL: \(fileURL)")
  201. }
  202. }
  203. func testDownloadRequestWithParameters() {
  204. // Given
  205. let fileURL: NSURL = {
  206. let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
  207. let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true)
  208. let fileURL = cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")
  209. return fileURL
  210. }()
  211. let URLString = "https://httpbin.org/get"
  212. let parameters = ["foo": "bar"]
  213. let destination: Request.DownloadFileDestination = { _, _ in fileURL }
  214. let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
  215. var request: NSURLRequest?
  216. var response: NSHTTPURLResponse?
  217. var error: ErrorType?
  218. // When
  219. Alamofire.download(.GET, URLString, parameters: parameters, destination: destination)
  220. .response { responseRequest, responseResponse, _, responseError in
  221. request = responseRequest
  222. response = responseResponse
  223. error = responseError
  224. expectation.fulfill()
  225. }
  226. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  227. // Then
  228. XCTAssertNotNil(request, "request should not be nil")
  229. XCTAssertNotNil(response, "response should not be nil")
  230. XCTAssertNil(error, "error should be nil")
  231. if let
  232. data = NSData(contentsOfURL: fileURL),
  233. JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
  234. JSON = JSONObject as? [String: AnyObject],
  235. args = JSON["args"] as? [String: String]
  236. {
  237. XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
  238. } else {
  239. XCTFail("args parameter in JSON should not be nil")
  240. }
  241. }
  242. func testDownloadRequestWithHeaders() {
  243. // Given
  244. let fileURL: NSURL = {
  245. let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
  246. let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true)
  247. let fileURL = cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")
  248. return fileURL
  249. }()
  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: ErrorType?
  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(defaultTimeout, 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: ErrorType?
  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(defaultTimeout, 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: ErrorType?
  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(defaultTimeout, 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 request: NSURLRequest?
  354. var response: NSHTTPURLResponse?
  355. var result: Result<AnyObject>!
  356. // When
  357. let download = Alamofire.download(.GET, URLString, destination: destination)
  358. download.progress { _, _, _ in
  359. download.cancel()
  360. }
  361. download.responseJSON { responseRequest, responseResponse, responseResult in
  362. request = responseRequest
  363. response = responseResponse
  364. result = responseResult
  365. expectation.fulfill()
  366. }
  367. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  368. // Then
  369. XCTAssertNotNil(request, "request should not be nil")
  370. XCTAssertNotNil(response, "response should not be nil")
  371. XCTAssertTrue(result.isFailure, "result should be a failure")
  372. XCTAssertNotNil(result.data, "data should not be nil")
  373. XCTAssertTrue(result.error != nil, "error should not be nil")
  374. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  375. }
  376. }