DownloadTests.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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: NSError?
  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: NSError?
  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. }
  204. // MARK: -
  205. class DownloadResumeDataTestCase: BaseTestCase {
  206. let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
  207. let destination: Request.DownloadFileDestination = {
  208. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  209. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  210. return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  211. }()
  212. func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
  213. // Given
  214. let expectation = expectationWithDescription("Download should be cancelled")
  215. var request: NSURLRequest?
  216. var response: NSHTTPURLResponse?
  217. var data: AnyObject?
  218. var error: NSError?
  219. // When
  220. let download = Alamofire.download(.GET, URLString, destination: destination)
  221. .response { responseRequest, responseResponse, responseData, responseError in
  222. request = responseRequest
  223. response = responseResponse
  224. data = responseData
  225. error = responseError
  226. expectation.fulfill()
  227. }
  228. download.cancel()
  229. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  230. // Then
  231. XCTAssertNotNil(request, "request should not be nil")
  232. XCTAssertNil(response, "response should be nil")
  233. XCTAssertNil(data, "data should be nil")
  234. XCTAssertNotNil(error, "error should not be nil")
  235. XCTAssertNil(download.resumeData, "resume data should be nil")
  236. }
  237. func testThatCancelledDownloadResponseDataMatchesResumeData() {
  238. // Given
  239. let expectation = expectationWithDescription("Download should be cancelled")
  240. var request: NSURLRequest?
  241. var response: NSHTTPURLResponse?
  242. var data: AnyObject?
  243. var error: NSError?
  244. // When
  245. let download = Alamofire.download(.GET, URLString, destination: destination)
  246. download.progress { _, _, _ in
  247. download.cancel()
  248. }
  249. download.response { responseRequest, responseResponse, responseData, responseError in
  250. request = responseRequest
  251. response = responseResponse
  252. data = responseData
  253. error = responseError
  254. expectation.fulfill()
  255. }
  256. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  257. // Then
  258. XCTAssertNotNil(request, "request should not be nil")
  259. XCTAssertNotNil(response, "response should not be nil")
  260. XCTAssertNotNil(data, "data should not be nil")
  261. XCTAssertNotNil(error, "error should not be nil")
  262. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  263. if let
  264. responseData = data as? NSData,
  265. resumeData = download.resumeData
  266. {
  267. XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
  268. } else {
  269. XCTFail("response data or resume data was unexpectedly nil")
  270. }
  271. }
  272. func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
  273. // Given
  274. let expectation = expectationWithDescription("Download should be cancelled")
  275. var request: NSURLRequest?
  276. var response: NSHTTPURLResponse?
  277. var result: Result<AnyObject>!
  278. // When
  279. let download = Alamofire.download(.GET, URLString, destination: destination)
  280. download.progress { _, _, _ in
  281. download.cancel()
  282. }
  283. download.responseJSON { responseRequest, responseResponse, responseResult in
  284. request = responseRequest
  285. response = responseResponse
  286. result = responseResult
  287. expectation.fulfill()
  288. }
  289. waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
  290. // Then
  291. XCTAssertNotNil(request, "request should not be nil")
  292. XCTAssertNotNil(response, "response should not be nil")
  293. XCTAssertTrue(result.isFailure, "result should be a failure")
  294. XCTAssertNotNil(result.data, "data should not be nil")
  295. XCTAssertNotNil(result.error, "error should not be nil")
  296. XCTAssertNotNil(download.resumeData, "resume data should not be nil")
  297. }
  298. }