RequestTests.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. //
  2. // RequestTests.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Alamofire
  25. import Foundation
  26. import XCTest
  27. // MARK: -
  28. class RequestResponseTestCase: BaseTestCase {
  29. func testRequestResponse() {
  30. // Given
  31. let urlString = "https://httpbin.org/get"
  32. let expectation = self.expectation(description: "GET request should succeed: \(urlString)")
  33. var response: DataResponse<Data?>?
  34. // When
  35. AF.request(urlString, parameters: ["foo": "bar"])
  36. .response { resp in
  37. response = resp
  38. expectation.fulfill()
  39. }
  40. waitForExpectations(timeout: timeout, handler: nil)
  41. // Then
  42. XCTAssertNotNil(response?.request)
  43. XCTAssertNotNil(response?.response)
  44. XCTAssertNotNil(response?.data)
  45. XCTAssertNil(response?.error)
  46. }
  47. func testRequestResponseWithProgress() {
  48. // Given
  49. let randomBytes = 1 * 1024 * 1024
  50. let urlString = "https://httpbin.org/bytes/\(randomBytes)"
  51. let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)")
  52. var progressValues: [Double] = []
  53. var response: DataResponse<Data?>?
  54. // When
  55. AF.request(urlString)
  56. .downloadProgress { progress in
  57. progressValues.append(progress.fractionCompleted)
  58. }
  59. .response { resp in
  60. response = resp
  61. expectation.fulfill()
  62. }
  63. waitForExpectations(timeout: timeout, handler: nil)
  64. // Then
  65. XCTAssertNotNil(response?.request)
  66. XCTAssertNotNil(response?.response)
  67. XCTAssertNotNil(response?.data)
  68. XCTAssertNil(response?.error)
  69. var previousProgress: Double = progressValues.first ?? 0.0
  70. for progress in progressValues {
  71. XCTAssertGreaterThanOrEqual(progress, previousProgress)
  72. previousProgress = progress
  73. }
  74. if let lastProgressValue = progressValues.last {
  75. XCTAssertEqual(lastProgressValue, 1.0)
  76. } else {
  77. XCTFail("last item in progressValues should not be nil")
  78. }
  79. }
  80. func testPOSTRequestWithUnicodeParameters() {
  81. // Given
  82. let urlString = "https://httpbin.org/post"
  83. let parameters = [
  84. "french": "français",
  85. "japanese": "日本語",
  86. "arabic": "العربية",
  87. "emoji": "😃"
  88. ]
  89. let expectation = self.expectation(description: "request should succeed")
  90. var response: DataResponse<Any>?
  91. // When
  92. AF.request(urlString, method: .post, parameters: parameters)
  93. .responseJSON { closureResponse in
  94. response = closureResponse
  95. expectation.fulfill()
  96. }
  97. waitForExpectations(timeout: timeout, handler: nil)
  98. // Then
  99. XCTAssertNotNil(response?.request)
  100. XCTAssertNotNil(response?.response)
  101. XCTAssertNotNil(response?.data)
  102. if let json = response?.result.value as? [String: Any], let form = json["form"] as? [String: String] {
  103. XCTAssertEqual(form["french"], parameters["french"])
  104. XCTAssertEqual(form["japanese"], parameters["japanese"])
  105. XCTAssertEqual(form["arabic"], parameters["arabic"])
  106. XCTAssertEqual(form["emoji"], parameters["emoji"])
  107. } else {
  108. XCTFail("form parameter in JSON should not be nil")
  109. }
  110. }
  111. func testPOSTRequestWithBase64EncodedImages() {
  112. // Given
  113. let urlString = "https://httpbin.org/post"
  114. let pngBase64EncodedString: String = {
  115. let URL = url(forResource: "unicorn", withExtension: "png")
  116. let data = try! Data(contentsOf: URL)
  117. return data.base64EncodedString(options: .lineLength64Characters)
  118. }()
  119. let jpegBase64EncodedString: String = {
  120. let URL = url(forResource: "rainbow", withExtension: "jpg")
  121. let data = try! Data(contentsOf: URL)
  122. return data.base64EncodedString(options: .lineLength64Characters)
  123. }()
  124. let parameters = [
  125. "email": "user@alamofire.org",
  126. "png_image": pngBase64EncodedString,
  127. "jpeg_image": jpegBase64EncodedString
  128. ]
  129. let expectation = self.expectation(description: "request should succeed")
  130. var response: DataResponse<Any>?
  131. // When
  132. AF.request(urlString, method: .post, parameters: parameters)
  133. .responseJSON { closureResponse in
  134. response = closureResponse
  135. expectation.fulfill()
  136. }
  137. waitForExpectations(timeout: timeout, handler: nil)
  138. // Then
  139. XCTAssertNotNil(response?.request)
  140. XCTAssertNotNil(response?.response)
  141. XCTAssertNotNil(response?.data)
  142. XCTAssertEqual(response?.result.isSuccess, true)
  143. if let json = response?.result.value as? [String: Any], let form = json["form"] as? [String: String] {
  144. XCTAssertEqual(form["email"], parameters["email"])
  145. XCTAssertEqual(form["png_image"], parameters["png_image"])
  146. XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"])
  147. } else {
  148. XCTFail("form parameter in JSON should not be nil")
  149. }
  150. }
  151. // MARK: Serialization Queue
  152. func testThatResponseSerializationWorksWithSerializationQueue() {
  153. // Given
  154. let queue = DispatchQueue(label: "org.alamofire.serializationQueue")
  155. let manager = Session(serializationQueue: queue)
  156. let expectation = self.expectation(description: "request should complete")
  157. var response: DataResponse<Any>?
  158. // When
  159. manager.request("https://httpbin.org/get").responseJSON { (resp) in
  160. response = resp
  161. expectation.fulfill()
  162. }
  163. waitForExpectations(timeout: timeout, handler: nil)
  164. // Then
  165. XCTAssertEqual(response?.result.isSuccess, true)
  166. }
  167. }
  168. // MARK: -
  169. class RequestDescriptionTestCase: BaseTestCase {
  170. func testRequestDescription() {
  171. // Given
  172. let urlString = "https://httpbin.org/get"
  173. let manager = Session(startRequestsImmediately: false)
  174. let request = manager.request(urlString)
  175. let initialRequestDescription = request.description
  176. let expectation = self.expectation(description: "Request description should update: \(urlString)")
  177. var response: HTTPURLResponse?
  178. // When
  179. request.response { resp in
  180. response = resp.response
  181. expectation.fulfill()
  182. }.resume()
  183. waitForExpectations(timeout: timeout, handler: nil)
  184. let finalRequestDescription = request.description
  185. // Then
  186. XCTAssertEqual(initialRequestDescription, "No request created yet.")
  187. XCTAssertEqual(finalRequestDescription, "GET https://httpbin.org/get (\(response?.statusCode ?? -1))")
  188. }
  189. }
  190. // MARK: -
  191. class RequestDebugDescriptionTestCase: BaseTestCase {
  192. // MARK: Properties
  193. let manager: Session = {
  194. let manager = Session()
  195. return manager
  196. }()
  197. let managerWithAcceptLanguageHeader: Session = {
  198. var headers = HTTPHeaders.defaultHTTPHeaders
  199. headers["Accept-Language"] = "en-US"
  200. let configuration = URLSessionConfiguration.alamofireDefault
  201. configuration.httpAdditionalHeaders = headers
  202. let manager = Session(configuration: configuration)
  203. return manager
  204. }()
  205. let managerWithContentTypeHeader: Session = {
  206. var headers = HTTPHeaders.defaultHTTPHeaders
  207. headers["Content-Type"] = "application/json"
  208. let configuration = URLSessionConfiguration.alamofireDefault
  209. configuration.httpAdditionalHeaders = headers
  210. let manager = Session(configuration: configuration)
  211. return manager
  212. }()
  213. func managerWithCookie(_ cookie: HTTPCookie) -> Session {
  214. let configuration = URLSessionConfiguration.alamofireDefault
  215. configuration.httpCookieStorage?.setCookie(cookie)
  216. return Session(configuration: configuration)
  217. }
  218. let managerDisallowingCookies: Session = {
  219. let configuration = URLSessionConfiguration.alamofireDefault
  220. configuration.httpShouldSetCookies = false
  221. let manager = Session(configuration: configuration)
  222. return manager
  223. }()
  224. // MARK: Tests
  225. func testGETRequestDebugDescription() {
  226. // Given
  227. let urlString = "https://httpbin.org/get"
  228. let expectation = self.expectation(description: "request should complete")
  229. // When
  230. let request = manager.request(urlString).response { _ in expectation.fulfill() }
  231. waitForExpectations(timeout: timeout, handler: nil)
  232. let components = cURLCommandComponents(for: request)
  233. // Then
  234. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  235. XCTAssertTrue(components.contains("-X"))
  236. XCTAssertEqual(components.last, "\"\(urlString)\"")
  237. }
  238. func testGETRequestWithJSONHeaderDebugDescription() {
  239. // Given
  240. let urlString = "https://httpbin.org/get"
  241. let expectation = self.expectation(description: "request should complete")
  242. // When
  243. let headers: [String: String] = [ "X-Custom-Header": "{\"key\": \"value\"}" ]
  244. let request = manager.request(urlString, headers: headers).response { _ in expectation.fulfill() }
  245. waitForExpectations(timeout: timeout, handler: nil)
  246. // Then
  247. XCTAssertNotNil(request.debugDescription.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\""))
  248. }
  249. func testGETRequestWithDuplicateHeadersDebugDescription() {
  250. // Given
  251. let urlString = "https://httpbin.org/get"
  252. let expectation = self.expectation(description: "request should complete")
  253. // When
  254. let headers = [ "Accept-Language": "en-GB" ]
  255. let request = managerWithAcceptLanguageHeader.request(urlString, headers: headers).response { _ in expectation.fulfill() }
  256. waitForExpectations(timeout: timeout, handler: nil)
  257. let components = cURLCommandComponents(for: request)
  258. // Then
  259. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  260. XCTAssertTrue(components.contains("-X"))
  261. XCTAssertEqual(components.last, "\"\(urlString)\"")
  262. let tokens = request.debugDescription.components(separatedBy: "Accept-Language:")
  263. XCTAssertTrue(tokens.count == 2, "command should contain a single Accept-Language header")
  264. XCTAssertNotNil(request.debugDescription.range(of: "-H \"Accept-Language: en-GB\""))
  265. }
  266. func testPOSTRequestDebugDescription() {
  267. // Given
  268. let urlString = "https://httpbin.org/post"
  269. let expectation = self.expectation(description: "request should complete")
  270. // When
  271. let request = manager.request(urlString, method: .post).response { _ in expectation.fulfill() }
  272. waitForExpectations(timeout: timeout, handler: nil)
  273. let components = cURLCommandComponents(for: request)
  274. // Then
  275. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  276. XCTAssertEqual(components[3..<5], ["-X", "POST"])
  277. XCTAssertEqual(components.last, "\"\(urlString)\"")
  278. }
  279. func testPOSTRequestWithJSONParametersDebugDescription() {
  280. // Given
  281. let urlString = "https://httpbin.org/post"
  282. let expectation = self.expectation(description: "request should complete")
  283. let parameters = [
  284. "foo": "bar",
  285. "fo\"o": "b\"ar",
  286. "f'oo": "ba'r"
  287. ]
  288. // When
  289. let request = manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).response {
  290. _ in expectation.fulfill()
  291. }
  292. waitForExpectations(timeout: timeout, handler: nil)
  293. let components = cURLCommandComponents(for: request)
  294. // Then
  295. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  296. XCTAssertEqual(components[3..<5], ["-X", "POST"])
  297. XCTAssertNotNil(request.debugDescription.range(of: "-H \"Content-Type: application/json\""))
  298. XCTAssertNotNil(request.debugDescription.range(of: "-d \"{"))
  299. XCTAssertNotNil(request.debugDescription.range(of: "\\\"f'oo\\\":\\\"ba'r\\\""))
  300. XCTAssertNotNil(request.debugDescription.range(of: "\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\""))
  301. XCTAssertNotNil(request.debugDescription.range(of: "\\\"foo\\\":\\\"bar\\"))
  302. XCTAssertEqual(components.last, "\"\(urlString)\"")
  303. }
  304. func testPOSTRequestWithCookieDebugDescription() {
  305. // Given
  306. let urlString = "https://httpbin.org/post"
  307. let properties = [
  308. HTTPCookiePropertyKey.domain: "httpbin.org",
  309. HTTPCookiePropertyKey.path: "/post",
  310. HTTPCookiePropertyKey.name: "foo",
  311. HTTPCookiePropertyKey.value: "bar",
  312. ]
  313. let cookie = HTTPCookie(properties: properties)!
  314. let cookieManager = managerWithCookie(cookie)
  315. let expectation = self.expectation(description: "request should complete")
  316. // When
  317. let request = cookieManager.request(urlString, method: .post).response { _ in expectation.fulfill() }
  318. waitForExpectations(timeout: timeout, handler: nil)
  319. let components = cURLCommandComponents(for: request)
  320. // Then
  321. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  322. XCTAssertEqual(components[3..<5], ["-X", "POST"])
  323. XCTAssertEqual(components.last, "\"\(urlString)\"")
  324. XCTAssertEqual(components[5..<6], ["-b"])
  325. }
  326. func testPOSTRequestWithCookiesDisabledDebugDescription() {
  327. // Given
  328. let urlString = "https://httpbin.org/post"
  329. let properties = [
  330. HTTPCookiePropertyKey.domain: "httpbin.org",
  331. HTTPCookiePropertyKey.path: "/post",
  332. HTTPCookiePropertyKey.name: "foo",
  333. HTTPCookiePropertyKey.value: "bar",
  334. ]
  335. let cookie = HTTPCookie(properties: properties)!
  336. managerDisallowingCookies.session.configuration.httpCookieStorage?.setCookie(cookie)
  337. // When
  338. let request = managerDisallowingCookies.request(urlString, method: .post)
  339. let components = cURLCommandComponents(for: request)
  340. // Then
  341. let cookieComponents = components.filter { $0 == "-b" }
  342. XCTAssertTrue(cookieComponents.isEmpty)
  343. }
  344. func testMultipartFormDataRequestWithDuplicateHeadersDebugDescription() {
  345. // Given
  346. let urlString = "https://httpbin.org/post"
  347. let japaneseData = Data("日本語".utf8)
  348. let expectation = self.expectation(description: "multipart form data encoding should succeed")
  349. // When
  350. let request = managerWithContentTypeHeader.upload(multipartFormData: { (data) in
  351. data.append(japaneseData, withName: "japanese")
  352. }, to: urlString)
  353. .response { _ in
  354. expectation.fulfill()
  355. }
  356. waitForExpectations(timeout: timeout, handler: nil)
  357. let components = cURLCommandComponents(for: request)
  358. // Then
  359. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  360. XCTAssertTrue(components.contains("-X"))
  361. XCTAssertEqual(components.last, "\"\(urlString)\"")
  362. let tokens = request.debugDescription.components(separatedBy: "Content-Type:")
  363. XCTAssertTrue(tokens.count == 2, "command should contain a single Content-Type header")
  364. XCTAssertNotNil(request.debugDescription.range(of: "-H \"Content-Type: multipart/form-data;"))
  365. }
  366. func testThatRequestWithInvalidURLDebugDescription() {
  367. // Given
  368. let urlString = "invalid_url"
  369. let expectation = self.expectation(description: "request should complete")
  370. // When
  371. let request = manager.request(urlString).response { _ in expectation.fulfill() }
  372. waitForExpectations(timeout: timeout, handler: nil)
  373. let debugDescription = request.debugDescription
  374. // Then
  375. XCTAssertNotNil(debugDescription, "debugDescription should not crash")
  376. }
  377. // MARK: Test Helper Methods
  378. private func cURLCommandComponents(for request: Request) -> [String] {
  379. let whitespaceCharacterSet = CharacterSet.whitespacesAndNewlines
  380. return request.debugDescription
  381. .components(separatedBy: whitespaceCharacterSet)
  382. .filter { $0 != "" && $0 != "\\" }
  383. }
  384. }