DownloadTests.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. // MARK: - Properties
  58. let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
  59. let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
  60. // MARK: - Tests
  61. func testDownloadRequest() {
  62. // Given
  63. let numberOfLines = 100
  64. let URLString = "http://httpbin.org/stream/\(numberOfLines)"
  65. let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
  66. let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
  67. var request: NSURLRequest?
  68. var response: NSHTTPURLResponse?
  69. var error: NSError?
  70. // When
  71. Alamofire.download(.GET, URLString, destination: destination)
  72. .response { responseRequest, responseResponse, _, responseError in
  73. request = responseRequest
  74. response = responseResponse
  75. error = responseError
  76. expectation.fulfill()
  77. }
  78. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  79. // Then
  80. XCTAssertNotNil(request, "request should not be nil")
  81. XCTAssertNotNil(response, "response should not be nil")
  82. XCTAssertNil(error, "error should be nil")
  83. let fileManager = NSFileManager.defaultManager()
  84. let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
  85. var fileManagerError: NSError?
  86. if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
  87. XCTAssertNil(fileManagerError, "fileManagerError should be nil")
  88. #if os(iOS)
  89. let suggestedFilename = "\(numberOfLines)"
  90. #elseif os(OSX)
  91. let suggestedFilename = "\(numberOfLines).json"
  92. #endif
  93. let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
  94. let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
  95. XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
  96. if let file = filteredContents.first as? NSURL {
  97. XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
  98. if let data = NSData(contentsOfURL: file) {
  99. XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
  100. } else {
  101. XCTFail("data should exist for contents of URL")
  102. }
  103. fileManager.removeItemAtURL(file, error: nil)
  104. } else {
  105. XCTFail("file should not be nil")
  106. }
  107. } else {
  108. XCTFail("contents should not be nil")
  109. }
  110. }
  111. func testDownloadRequestWithProgress() {
  112. // Given
  113. let randomBytes = 4 * 1024 * 1024
  114. let URLString = "http://httpbin.org/bytes/\(randomBytes)"
  115. let fileManager = NSFileManager.defaultManager()
  116. let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
  117. let filename = "test_download_data"
  118. let fileURL = directory.URLByAppendingPathComponent(filename)
  119. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  120. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  121. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  122. var responseRequest: NSURLRequest?
  123. var responseResponse: NSHTTPURLResponse?
  124. var responseData: NSData?
  125. var responseError: NSError?
  126. // When
  127. let download = Alamofire.download(.GET, URLString) { _, _ in
  128. return fileURL
  129. }
  130. download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  131. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  132. byteValues.append(bytes)
  133. let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
  134. progressValues.append(progress)
  135. }
  136. download.response { request, response, data, error in
  137. responseRequest = request
  138. responseResponse = response
  139. responseData = data
  140. responseError = error
  141. expectation.fulfill()
  142. }
  143. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  144. // Then
  145. XCTAssertNotNil(responseRequest, "response request should not be nil")
  146. XCTAssertNotNil(responseResponse, "response response should not be nil")
  147. XCTAssertNil(responseData, "response data should be nil")
  148. XCTAssertNil(responseError, "response error should be nil")
  149. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  150. if byteValues.count == progressValues.count {
  151. for index in 0..<byteValues.count {
  152. let byteValue = byteValues[index]
  153. let progressValue = progressValues[index]
  154. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  155. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
  156. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
  157. }
  158. }
  159. if let
  160. lastByteValue = byteValues.last,
  161. lastProgressValue = progressValues.last
  162. {
  163. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  164. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  165. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  166. XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
  167. } else {
  168. XCTFail("last item in bytesValues and progressValues should not be nil")
  169. }
  170. var removalError: NSError?
  171. fileManager.removeItemAtURL(fileURL, error: &removalError)
  172. XCTAssertNil(removalError, "removal error should be nil")
  173. }
  174. }