RequestTests.swift 19 KB

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