RequestTests.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // RequestTests.swift
  2. //
  3. // Copyright (c) 2014 Alamofire (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 RequestInitializationTestCase: BaseTestCase {
  26. func testRequestClassMethodWithMethodAndURL() {
  27. // Given
  28. let URLString = "http://httpbin.org/"
  29. // When
  30. let request = Alamofire.request(.GET, URLString)
  31. // Then
  32. XCTAssertNotNil(request.request, "request should not be nil")
  33. XCTAssertEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  34. XCTAssertNil(request.response, "response should be nil")
  35. }
  36. func testRequestClassMethodWithMethodAndURLAndParameters() {
  37. // Given
  38. let URLString = "http://httpbin.org/get"
  39. // When
  40. let request = Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
  41. // Then
  42. XCTAssertNotNil(request.request, "request should not be nil")
  43. XCTAssertNotEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  44. XCTAssertEqual(request.request.URL?.query ?? "", "foo=bar", "query is incorrect")
  45. XCTAssertNil(request.response, "response should be nil")
  46. }
  47. }
  48. // MARK: -
  49. class RequestResponseTestCase: BaseTestCase {
  50. func testRequestResponse() {
  51. // Given
  52. let URLString = "http://httpbin.org/get"
  53. let serializer = Alamofire.Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
  54. let expectation = expectationWithDescription("GET request should succeed: \(URLString)")
  55. var request: NSURLRequest?
  56. var response: NSHTTPURLResponse?
  57. var string: AnyObject?
  58. var error: NSError?
  59. // When
  60. Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
  61. .response(serializer: serializer) { responseRequest, responseResponse, responseString, responseError in
  62. request = responseRequest
  63. response = responseResponse
  64. string = responseString
  65. error = responseError
  66. expectation.fulfill()
  67. }
  68. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  69. // Then
  70. XCTAssertNotNil(request, "request should not be nil")
  71. XCTAssertNotNil(response, "response should not be nil")
  72. XCTAssertNotNil(string, "string should not be nil")
  73. XCTAssertNil(error, "error should be nil")
  74. }
  75. func testRequestResponseWithProgress() {
  76. // Given
  77. let randomBytes = 4 * 1024 * 1024
  78. let URLString = "http://httpbin.org/bytes/\(randomBytes)"
  79. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  80. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  81. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  82. var responseRequest: NSURLRequest?
  83. var responseResponse: NSHTTPURLResponse?
  84. var responseData: AnyObject?
  85. var responseError: NSError?
  86. // When
  87. let request = Alamofire.request(.GET, URLString)
  88. request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  89. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  90. byteValues.append(bytes)
  91. let progress = (completedUnitCount: request.progress.completedUnitCount, totalUnitCount: request.progress.totalUnitCount)
  92. progressValues.append(progress)
  93. }
  94. request.response { request, response, data, error in
  95. responseRequest = request
  96. responseResponse = response
  97. responseData = data
  98. responseError = error
  99. expectation.fulfill()
  100. }
  101. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  102. // Then
  103. XCTAssertNotNil(responseRequest, "response request should not be nil")
  104. XCTAssertNotNil(responseResponse, "response response should not be nil")
  105. XCTAssertNotNil(responseData, "response data should not be nil")
  106. XCTAssertNil(responseError, "response error should be nil")
  107. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  108. if byteValues.count == progressValues.count {
  109. for index in 0..<byteValues.count {
  110. let byteValue = byteValues[index]
  111. let progressValue = progressValues[index]
  112. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  113. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
  114. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
  115. }
  116. }
  117. if let lastByteValue = byteValues.last,
  118. lastProgressValue = progressValues.last
  119. {
  120. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  121. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  122. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  123. XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
  124. } else {
  125. XCTFail("last item in bytesValues and progressValues should not be nil")
  126. }
  127. }
  128. func testRequestResponseWithStream() {
  129. // Given
  130. let randomBytes = 4 * 1024 * 1024
  131. let URLString = "http://httpbin.org/bytes/\(randomBytes)"
  132. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  133. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  134. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  135. var responseRequest: NSURLRequest?
  136. var responseResponse: NSHTTPURLResponse?
  137. var responseData: AnyObject?
  138. var responseError: NSError?
  139. var accumulatedData = [NSData]()
  140. // When
  141. let request = Alamofire.request(.GET, URLString)
  142. request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  143. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  144. byteValues.append(bytes)
  145. let progress = (completedUnitCount: request.progress.completedUnitCount, totalUnitCount: request.progress.totalUnitCount)
  146. progressValues.append(progress)
  147. }
  148. request.stream { data in accumulatedData.append(data) }
  149. request.response { request, response, data, error in
  150. responseRequest = request
  151. responseResponse = response
  152. responseData = data
  153. responseError = error
  154. expectation.fulfill()
  155. }
  156. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  157. // Then
  158. XCTAssertNotNil(responseRequest, "response request should not be nil")
  159. XCTAssertNotNil(responseResponse, "response response should not be nil")
  160. XCTAssertNil(responseData, "response data should be nil")
  161. XCTAssertNil(responseError, "response error should be nil")
  162. XCTAssertGreaterThanOrEqual(accumulatedData.count, 1, "accumulated data should have one or more parts")
  163. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  164. if byteValues.count == progressValues.count {
  165. for index in 0..<byteValues.count {
  166. let byteValue = byteValues[index]
  167. let progressValue = progressValues[index]
  168. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  169. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
  170. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
  171. }
  172. }
  173. if let lastByteValue = byteValues.last,
  174. lastProgressValue = progressValues.last
  175. {
  176. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  177. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  178. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  179. XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
  180. XCTAssertEqual(reduce(accumulatedData, 0) { $0 + $1.length }, lastByteValue.totalBytes, "accumulated data length should match byte count")
  181. } else {
  182. XCTFail("last item in bytesValues and progressValues should not be nil")
  183. }
  184. }
  185. }
  186. // MARK: -
  187. class RequestDescriptionTestCase: BaseTestCase {
  188. func testRequestDescription() {
  189. // Given
  190. let URLString = "http://httpbin.org/get"
  191. let request = Alamofire.request(.GET, URLString)
  192. let initialRequestDescription = request.description
  193. let expectation = expectationWithDescription("Request description should update: \(URLString)")
  194. var finalRequestDescription: String?
  195. var response: NSHTTPURLResponse?
  196. // When
  197. request.response { _, responseResponse, _, _ in
  198. finalRequestDescription = request.description
  199. response = responseResponse
  200. expectation.fulfill()
  201. }
  202. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  203. // Then
  204. XCTAssertEqual(initialRequestDescription, "GET http://httpbin.org/get", "incorrect request description")
  205. XCTAssertEqual(finalRequestDescription ?? "", "GET http://httpbin.org/get (\(response?.statusCode ?? -1))", "incorrect request description")
  206. }
  207. }
  208. // MARK: -
  209. class RequestDebugDescriptionTestCase: BaseTestCase {
  210. // MARK: Properties
  211. let manager: Alamofire.Manager = {
  212. let manager = Alamofire.Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
  213. manager.startRequestsImmediately = false
  214. return manager
  215. }()
  216. let managerDisallowingCookies: Alamofire.Manager = {
  217. let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  218. configuration.HTTPShouldSetCookies = false
  219. let manager = Alamofire.Manager(configuration: configuration)
  220. manager.startRequestsImmediately = false
  221. return manager
  222. }()
  223. // MARK: Tests
  224. func testGETRequestDebugDescription() {
  225. // Given
  226. let URLString = "http://httpbin.org/get"
  227. // When
  228. let request = manager.request(.GET, URLString)
  229. let components = cURLCommandComponents(request)
  230. // Then
  231. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  232. XCTAssertFalse(contains(components, "-X"), "command should not contain explicit -X flag")
  233. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  234. }
  235. func testPOSTRequestDebugDescription() {
  236. // Given
  237. let URLString = "http://httpbin.org/post"
  238. // When
  239. let request = manager.request(.POST, URLString)
  240. let components = cURLCommandComponents(request)
  241. // Then
  242. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  243. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  244. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  245. }
  246. func testPOSTRequestWithJSONParametersDebugDescription() {
  247. // Given
  248. let URLString = "http://httpbin.org/post"
  249. // When
  250. let request = manager.request(.POST, URLString, parameters: ["foo": "bar"], encoding: .JSON)
  251. let components = cURLCommandComponents(request)
  252. // Then
  253. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  254. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  255. XCTAssertTrue(request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil, "command should contain 'application/json' Content-Type")
  256. XCTAssertTrue(request.debugDescription.rangeOfString("-d \"{\\\"foo\\\":\\\"bar\\\"}\"") != nil, "command data should contain JSON encoded parameters")
  257. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  258. }
  259. func testPOSTRequestWithCookieDebugDescription() {
  260. // Given
  261. let URLString = "http://httpbin.org/post"
  262. let properties = [
  263. NSHTTPCookieDomain: "httpbin.org",
  264. NSHTTPCookiePath: "/post",
  265. NSHTTPCookieName: "foo",
  266. NSHTTPCookieValue: "bar",
  267. ]
  268. let cookie = NSHTTPCookie(properties: properties)!
  269. manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)
  270. // When
  271. let request = manager.request(.POST, URLString)
  272. let components = cURLCommandComponents(request)
  273. // Then
  274. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  275. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  276. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  277. #if !os(OSX)
  278. XCTAssertEqual(components[5..<6], ["-b"], "command should contain -b flag")
  279. #endif
  280. }
  281. func testPOSTRequestWithCookiesDisabledDebugDescription() {
  282. // Given
  283. let URLString = "http://httpbin.org/post"
  284. let properties = [
  285. NSHTTPCookieDomain: "httpbin.org",
  286. NSHTTPCookiePath: "/post",
  287. NSHTTPCookieName: "foo",
  288. NSHTTPCookieValue: "bar",
  289. ]
  290. let cookie = NSHTTPCookie(properties: properties)!
  291. managerDisallowingCookies.session.configuration.HTTPCookieStorage?.setCookie(cookie)
  292. // When
  293. let request = managerDisallowingCookies.request(.POST, URLString)
  294. let components = cURLCommandComponents(request)
  295. // Then
  296. let cookieComponents = components.filter { $0 == "-b" }
  297. XCTAssertTrue(cookieComponents.isEmpty, "command should not contain -b flag")
  298. }
  299. // MARK: Test Helper Methods
  300. private func cURLCommandComponents(request: Request) -> [String] {
  301. return request.debugDescription.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter { $0 != "" && $0 != "\\" }
  302. }
  303. }