RequestTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 URL = "http://httpbin.org/"
  29. // When
  30. let request = Alamofire.request(.GET, URL)
  31. // Then
  32. XCTAssertNotNil(request.request, "request should not be nil")
  33. XCTAssertEqual(request.request.URL!, NSURL(string: URL)!, "request URL should be equal")
  34. XCTAssertNil(request.response, "response should be nil")
  35. }
  36. func testRequestClassMethodWithMethodAndURLAndParameters() {
  37. // Given
  38. let URL = "http://httpbin.org/get"
  39. // When
  40. let request = Alamofire.request(.GET, URL, parameters: ["foo": "bar"])
  41. // Then
  42. XCTAssertNotNil(request.request, "request should not be nil")
  43. XCTAssertNotEqual(request.request.URL!, NSURL(string: URL)!, "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 URL = "http://httpbin.org/get"
  53. let serializer = Alamofire.Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
  54. let expectation = expectationWithDescription("\(URL)")
  55. var request: NSURLRequest?
  56. var response: NSHTTPURLResponse?
  57. var string: AnyObject?
  58. var error: NSError?
  59. // When
  60. Alamofire.request(.GET, URL, 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. }
  129. // MARK: -
  130. class RequestDescriptionTestCase: BaseTestCase {
  131. func testRequestDescription() {
  132. // Given
  133. let URL = "http://httpbin.org/get"
  134. let request = Alamofire.request(.GET, URL)
  135. let initialRequestDescription = request.description
  136. let expectation = expectationWithDescription("\(URL)")
  137. var finalRequestDescription: String?
  138. var response: NSHTTPURLResponse?
  139. // When
  140. request.response { _, responseResponse, _, _ in
  141. finalRequestDescription = request.description
  142. response = responseResponse
  143. expectation.fulfill()
  144. }
  145. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  146. // Then
  147. XCTAssertEqual(initialRequestDescription, "GET http://httpbin.org/get", "incorrect request description")
  148. XCTAssertEqual(finalRequestDescription ?? "", "GET http://httpbin.org/get (\(response?.statusCode ?? -1))", "incorrect request description")
  149. }
  150. }
  151. // MARK: -
  152. class RequestDebugDescriptionTestCase: BaseTestCase {
  153. // MARK: Properties
  154. let manager: Alamofire.Manager = {
  155. let manager = Alamofire.Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
  156. manager.startRequestsImmediately = false
  157. return manager
  158. }()
  159. // MARK: Tests
  160. func testGETRequestDebugDescription() {
  161. // Given
  162. let URL = "http://httpbin.org/get"
  163. // When
  164. let request = manager.request(.GET, URL)
  165. let components = cURLCommandComponents(request)
  166. // Then
  167. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  168. XCTAssertFalse(contains(components, "-X"), "command should not contain explicit -X flag")
  169. XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
  170. }
  171. func testPOSTRequestDebugDescription() {
  172. // Given
  173. let URL = "http://httpbin.org/post"
  174. // When
  175. let request = manager.request(.POST, URL)
  176. let components = cURLCommandComponents(request)
  177. // Then
  178. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  179. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  180. XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
  181. }
  182. func testPOSTRequestWithJSONParametersDebugDescription() {
  183. // Given
  184. let URL = "http://httpbin.org/post"
  185. // When
  186. let request = manager.request(.POST, URL, parameters: ["foo": "bar"], encoding: .JSON)
  187. let components = cURLCommandComponents(request)
  188. // Then
  189. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  190. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  191. XCTAssertTrue(request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil, "command should contain 'application/json' Content-Type")
  192. XCTAssertTrue(request.debugDescription.rangeOfString("-d \"{\\\"foo\\\":\\\"bar\\\"}\"") != nil, "command data should contain JSON encoded parameters")
  193. XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
  194. }
  195. func testPOSTRequestWithCookieDebugDescription() {
  196. // Given
  197. let URL = "http://httpbin.org/post"
  198. let properties = [
  199. NSHTTPCookieDomain: "httpbin.org",
  200. NSHTTPCookiePath: "/post",
  201. NSHTTPCookieName: "foo",
  202. NSHTTPCookieValue: "bar",
  203. ]
  204. let cookie = NSHTTPCookie(properties: properties)!
  205. manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)
  206. // When
  207. let request = manager.request(.POST, URL)
  208. let components = cURLCommandComponents(request)
  209. // Then
  210. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  211. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  212. XCTAssertEqual(components.last ?? "", "\"\(URL)\"", "URL component should be equal")
  213. #if !os(OSX)
  214. XCTAssertEqual(components[5..<6], ["-b"], "command should contain -b flag")
  215. #endif
  216. }
  217. // MARK: Test Helper Methods
  218. private func cURLCommandComponents(request: Request) -> [String] {
  219. return request.debugDescription.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter { $0 != "" && $0 != "\\" }
  220. }
  221. }