DownloadTests.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 = "http://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 = "http://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 = "http://httpbin.org/stream/\(numberOfLines)"
  63. let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  64. let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
  65. var request: NSURLRequest?
  66. var response: NSHTTPURLResponse?
  67. var error: NSError?
  68. // When
  69. Alamofire.download(.GET, URLString, destination: destination)
  70. .response { responseRequest, responseResponse, _, responseError in
  71. request = responseRequest
  72. response = responseResponse
  73. error = responseError
  74. expectation.fulfill()
  75. }
  76. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  77. // Then
  78. XCTAssertNotNil(request, "request should not be nil")
  79. XCTAssertNotNil(response, "response should not be nil")
  80. XCTAssertNil(error, "error should be nil")
  81. let fileManager = NSFileManager.defaultManager()
  82. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  83. do {
  84. let contents = try fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)
  85. #if os(iOS)
  86. let suggestedFilename = "\(numberOfLines)"
  87. #elseif os(OSX)
  88. let suggestedFilename = "\(numberOfLines).json"
  89. #endif
  90. let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
  91. let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
  92. XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
  93. if let file = filteredContents.first as? NSURL {
  94. XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
  95. if let data = NSData(contentsOfURL: file) {
  96. XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
  97. } else {
  98. XCTFail("data should exist for contents of URL")
  99. }
  100. do {
  101. try fileManager.removeItemAtURL(file)
  102. } catch {
  103. XCTFail("file manager should remove item at URL: \(file)")
  104. }
  105. } else {
  106. XCTFail("file should not be nil")
  107. }
  108. } catch {
  109. XCTFail("contents should not be nil")
  110. }
  111. }
  112. func testDownloadRequestWithProgress() {
  113. // Given
  114. let randomBytes = 4 * 1024 * 1024
  115. let URLString = "http://httpbin.org/bytes/\(randomBytes)"
  116. let fileManager = NSFileManager.defaultManager()
  117. let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
  118. let filename = "test_download_data"
  119. let fileURL = directory.URLByAppendingPathComponent(filename)
  120. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  121. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  122. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  123. var responseRequest: NSURLRequest?
  124. var responseResponse: NSHTTPURLResponse?
  125. var responseData: NSData?
  126. var responseError: NSError?
  127. // When
  128. let download = Alamofire.download(.GET, URLString) { _, _ in
  129. return fileURL
  130. }
  131. download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  132. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  133. byteValues.append(bytes)
  134. let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
  135. progressValues.append(progress)
  136. }
  137. download.response { request, response, data, error in
  138. responseRequest = request
  139. responseResponse = response
  140. responseData = data
  141. responseError = error
  142. expectation.fulfill()
  143. }
  144. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  145. // Then
  146. XCTAssertNotNil(responseRequest, "response request should not be nil")
  147. XCTAssertNotNil(responseResponse, "response should not be nil")
  148. XCTAssertNil(responseData, "response data should be nil")
  149. XCTAssertNil(responseError, "response error should be nil")
  150. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  151. if byteValues.count == progressValues.count {
  152. for index in 0..<byteValues.count {
  153. let byteValue = byteValues[index]
  154. let progressValue = progressValues[index]
  155. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  156. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
  157. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
  158. }
  159. }
  160. if let
  161. lastByteValue = byteValues.last,
  162. lastProgressValue = progressValues.last
  163. {
  164. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  165. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  166. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  167. XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
  168. } else {
  169. XCTFail("last item in bytesValues and progressValues should not be nil")
  170. }
  171. do {
  172. try fileManager.removeItemAtURL(fileURL)
  173. } catch {
  174. XCTFail("file manager should remove item at URL: \(fileURL)")
  175. }
  176. }
  177. }
  178. // MARK: -
  179. class DownloadResumeDataTestCase: BaseTestCase {
  180. let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  181. let destination: Request.DownloadFileDestination = {
  182. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  183. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  184. return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  185. }()
  186. func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
  187. // Given
  188. let expectation = expectationWithDescription("Download should be cancelled")
  189. var request: NSURLRequest?
  190. var response: NSHTTPURLResponse?
  191. var data: AnyObject?
  192. var error: NSError?
  193. // When
  194. let download = Alamofire.download(.GET, URLString, destination: destination)
  195. .response { responseRequest, responseResponse, responseData, responseError in
  196. request = responseRequest
  197. response = responseResponse
  198. data = responseData
  199. error = responseError
  200. expectation.fulfill()
  201. }
  202. download.cancel()
  203. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  204. // Then
  205. XCTAssertNotNil(request, "request should not be nil")
  206. XCTAssertNil(response, "response should be nil")
  207. XCTAssertNil(data, "data should be nil")
  208. XCTAssertNotNil(error, "error should not be nil")
  209. XCTAssertNil(download.resumeData, "resume data should be nil")
  210. }
  211. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  212. // Given
  213. let expectation = expectationWithDescription("Download should be cancelled")
  214. var request: NSURLRequest?
  215. var response: NSHTTPURLResponse?
  216. var data: AnyObject?
  217. var error: NSError?
  218. // When
  219. let download = Alamofire.download(.GET, URLString, destination: destination)
  220. download.progress { _, _, _ in
  221. download.cancel()
  222. }
  223. download.response { responseRequest, responseResponse, responseData, responseError in
  224. request = responseRequest
  225. response = responseResponse
  226. data = responseData
  227. error = responseError
  228. expectation.fulfill()
  229. }
  230. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  231. // Then
  232. XCTAssertNotNil(request, "request should not be nil")
  233. XCTAssertNotNil(response, "response should not be nil")
  234. XCTAssertNotNil(data, "data should not be nil")
  235. XCTAssertNotNil(error, "error should not be nil")
  236. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  237. if let
  238. responseData = data as? NSData,
  239. resumeData = download.resumeData
  240. {
  241. XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
  242. } else {
  243. XCTFail("response data or resume data was unexpectedly nil")
  244. }
  245. }
  246. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  247. // Given
  248. let expectation = expectationWithDescription("Download should be cancelled")
  249. var request: NSURLRequest?
  250. var response: NSHTTPURLResponse?
  251. var JSON: AnyObject?
  252. var error: NSError?
  253. // When
  254. let download = Alamofire.download(.GET, URLString, destination: destination)
  255. download.progress { _, _, _ in
  256. download.cancel()
  257. }
  258. download.responseJSON { responseRequest, responseResponse, responseJSON, responseError in
  259. request = responseRequest
  260. response = responseResponse
  261. JSON = responseJSON
  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(JSON, "JSON should be nil")
  270. XCTAssertNotNil(error, "error should not be nil")
  271. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  272. }
  273. }