RequestTests.swift 19 KB

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