DownloadTests.swift 14 KB

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