RequestTests.swift 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. final class RequestResponseTestCase: BaseTestCase {
  28. func testRequestResponse() {
  29. // Given
  30. let urlString = "https://httpbin.org/get"
  31. let expectation = self.expectation(description: "GET request should succeed: \(urlString)")
  32. var response: DataResponse<Data?, AFError>?
  33. // When
  34. AF.request(urlString, parameters: ["foo": "bar"])
  35. .response { resp in
  36. response = resp
  37. expectation.fulfill()
  38. }
  39. waitForExpectations(timeout: timeout, handler: nil)
  40. // Then
  41. XCTAssertNotNil(response?.request)
  42. XCTAssertNotNil(response?.response)
  43. XCTAssertNotNil(response?.data)
  44. XCTAssertNil(response?.error)
  45. }
  46. func testRequestResponseWithProgress() {
  47. // Given
  48. let randomBytes = 1 * 25 * 1024
  49. let urlString = "https://httpbin.org/bytes/\(randomBytes)"
  50. let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)")
  51. var progressValues: [Double] = []
  52. var response: DataResponse<Data?, AFError>?
  53. // When
  54. AF.request(urlString)
  55. .downloadProgress { progress in
  56. progressValues.append(progress.fractionCompleted)
  57. }
  58. .response { resp in
  59. response = resp
  60. expectation.fulfill()
  61. }
  62. waitForExpectations(timeout: timeout, handler: nil)
  63. // Then
  64. XCTAssertNotNil(response?.request)
  65. XCTAssertNotNil(response?.response)
  66. XCTAssertNotNil(response?.data)
  67. XCTAssertNil(response?.error)
  68. var previousProgress: Double = progressValues.first ?? 0.0
  69. for progress in progressValues {
  70. XCTAssertGreaterThanOrEqual(progress, previousProgress)
  71. previousProgress = progress
  72. }
  73. if let lastProgressValue = progressValues.last {
  74. XCTAssertEqual(lastProgressValue, 1.0)
  75. } else {
  76. XCTFail("last item in progressValues should not be nil")
  77. }
  78. }
  79. func testPOSTRequestWithUnicodeParameters() {
  80. // Given
  81. let urlString = "https://httpbin.org/post"
  82. let parameters = ["french": "français",
  83. "japanese": "日本語",
  84. "arabic": "العربية",
  85. "emoji": "😃"]
  86. let expectation = self.expectation(description: "request should succeed")
  87. var response: DataResponse<Any, AFError>?
  88. // When
  89. AF.request(urlString, method: .post, parameters: parameters)
  90. .responseJSON { closureResponse in
  91. response = closureResponse
  92. expectation.fulfill()
  93. }
  94. waitForExpectations(timeout: timeout, handler: nil)
  95. // Then
  96. XCTAssertNotNil(response?.request)
  97. XCTAssertNotNil(response?.response)
  98. XCTAssertNotNil(response?.data)
  99. if let json = response?.result.success as? [String: Any], let form = json["form"] as? [String: String] {
  100. XCTAssertEqual(form["french"], parameters["french"])
  101. XCTAssertEqual(form["japanese"], parameters["japanese"])
  102. XCTAssertEqual(form["arabic"], parameters["arabic"])
  103. XCTAssertEqual(form["emoji"], parameters["emoji"])
  104. } else {
  105. XCTFail("form parameter in JSON should not be nil")
  106. }
  107. }
  108. #if !SWIFT_PACKAGE
  109. func testPOSTRequestWithBase64EncodedImages() {
  110. // Given
  111. let urlString = "https://httpbin.org/post"
  112. let pngBase64EncodedString: String = {
  113. let URL = url(forResource: "unicorn", withExtension: "png")
  114. let data = try! Data(contentsOf: URL)
  115. return data.base64EncodedString(options: .lineLength64Characters)
  116. }()
  117. let jpegBase64EncodedString: String = {
  118. let URL = url(forResource: "rainbow", withExtension: "jpg")
  119. let data = try! Data(contentsOf: URL)
  120. return data.base64EncodedString(options: .lineLength64Characters)
  121. }()
  122. let parameters = ["email": "user@alamofire.org",
  123. "png_image": pngBase64EncodedString,
  124. "jpeg_image": jpegBase64EncodedString]
  125. let expectation = self.expectation(description: "request should succeed")
  126. var response: DataResponse<Any, AFError>?
  127. // When
  128. AF.request(urlString, method: .post, parameters: parameters)
  129. .responseJSON { closureResponse in
  130. response = closureResponse
  131. expectation.fulfill()
  132. }
  133. waitForExpectations(timeout: timeout, handler: nil)
  134. // Then
  135. XCTAssertNotNil(response?.request)
  136. XCTAssertNotNil(response?.response)
  137. XCTAssertNotNil(response?.data)
  138. XCTAssertEqual(response?.result.isSuccess, true)
  139. if let json = response?.result.success as? [String: Any], let form = json["form"] as? [String: String] {
  140. XCTAssertEqual(form["email"], parameters["email"])
  141. XCTAssertEqual(form["png_image"], parameters["png_image"])
  142. XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"])
  143. } else {
  144. XCTFail("form parameter in JSON should not be nil")
  145. }
  146. }
  147. #endif
  148. // MARK: Queues
  149. func testThatResponseSerializationWorksWithSerializationQueue() {
  150. // Given
  151. let queue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
  152. let manager = Session(serializationQueue: queue)
  153. let expectation = self.expectation(description: "request should complete")
  154. var response: DataResponse<Any, AFError>?
  155. // When
  156. manager.request("https://httpbin.org/get").responseJSON { resp in
  157. response = resp
  158. expectation.fulfill()
  159. }
  160. waitForExpectations(timeout: timeout, handler: nil)
  161. // Then
  162. XCTAssertEqual(response?.result.isSuccess, true)
  163. }
  164. func testThatRequestsWorksWithRequestAndSerializationQueues() {
  165. // Given
  166. let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue")
  167. let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
  168. let manager = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
  169. let expectation = self.expectation(description: "request should complete")
  170. var response: DataResponse<Any, AFError>?
  171. // When
  172. manager.request("https://httpbin.org/get").responseJSON { resp in
  173. response = resp
  174. expectation.fulfill()
  175. }
  176. waitForExpectations(timeout: timeout, handler: nil)
  177. // Then
  178. XCTAssertEqual(response?.result.isSuccess, true)
  179. }
  180. func testThatRequestsWorksWithConcurrentRequestAndSerializationQueues() {
  181. // Given
  182. let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue", attributes: .concurrent)
  183. let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue", attributes: .concurrent)
  184. let session = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
  185. let count = 10
  186. let expectation = self.expectation(description: "request should complete")
  187. expectation.expectedFulfillmentCount = count
  188. var responses: [DataResponse<Any, AFError>] = []
  189. // When
  190. DispatchQueue.concurrentPerform(iterations: count) { _ in
  191. session.request("https://httpbin.org/get").responseJSON { resp in
  192. responses.append(resp)
  193. expectation.fulfill()
  194. }
  195. }
  196. waitForExpectations(timeout: timeout, handler: nil)
  197. // Then
  198. XCTAssertEqual(responses.count, count)
  199. XCTAssertTrue(responses.allSatisfy { $0.result.isSuccess })
  200. }
  201. // MARK: Encodable Parameters
  202. func testThatRequestsCanPassEncodableParametersAsJSONBodyData() {
  203. // Given
  204. let parameters = HTTPBinParameters(property: "one")
  205. let expect = expectation(description: "request should complete")
  206. var receivedResponse: DataResponse<HTTPBinResponse, AFError>?
  207. // When
  208. AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default)
  209. .responseDecodable(of: HTTPBinResponse.self) { response in
  210. receivedResponse = response
  211. expect.fulfill()
  212. }
  213. waitForExpectations(timeout: timeout, handler: nil)
  214. // Then
  215. XCTAssertEqual(receivedResponse?.result.success?.data, "{\"property\":\"one\"}")
  216. }
  217. func testThatRequestsCanPassEncodableParametersAsAURLQuery() {
  218. // Given
  219. let parameters = HTTPBinParameters(property: "one")
  220. let expect = expectation(description: "request should complete")
  221. var receivedResponse: DataResponse<HTTPBinResponse, AFError>?
  222. // When
  223. AF.request("https://httpbin.org/get", method: .get, parameters: parameters)
  224. .responseDecodable(of: HTTPBinResponse.self) { response in
  225. receivedResponse = response
  226. expect.fulfill()
  227. }
  228. waitForExpectations(timeout: timeout, handler: nil)
  229. // Then
  230. XCTAssertEqual(receivedResponse?.result.success?.args, ["property": "one"])
  231. }
  232. func testThatRequestsCanPassEncodableParametersAsURLEncodedBodyData() {
  233. // Given
  234. let parameters = HTTPBinParameters(property: "one")
  235. let expect = expectation(description: "request should complete")
  236. var receivedResponse: DataResponse<HTTPBinResponse, AFError>?
  237. // When
  238. AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
  239. .responseDecodable(of: HTTPBinResponse.self) { response in
  240. receivedResponse = response
  241. expect.fulfill()
  242. }
  243. waitForExpectations(timeout: timeout, handler: nil)
  244. // Then
  245. XCTAssertEqual(receivedResponse?.result.success?.form, ["property": "one"])
  246. }
  247. // MARK: Lifetime Events
  248. func testThatAutomaticallyResumedRequestReceivesAppropriateLifetimeEvents() {
  249. // Given
  250. let eventMonitor = ClosureEventMonitor()
  251. let session = Session(eventMonitors: [eventMonitor])
  252. let expect = expectation(description: "request should receive appropriate lifetime events")
  253. expect.expectedFulfillmentCount = 4
  254. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  255. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  256. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  257. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  258. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  259. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  260. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  261. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  262. // When
  263. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() }
  264. waitForExpectations(timeout: timeout, handler: nil)
  265. // Then
  266. XCTAssertEqual(request.state, .finished)
  267. }
  268. func testThatAutomaticallyAndManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  269. // Given
  270. let eventMonitor = ClosureEventMonitor()
  271. let session = Session(eventMonitors: [eventMonitor])
  272. let expect = expectation(description: "request should receive appropriate lifetime events")
  273. expect.expectedFulfillmentCount = 4
  274. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  275. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  276. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  277. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  278. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  279. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  280. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  281. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  282. // When
  283. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() }
  284. for _ in 0..<100 {
  285. request.resume()
  286. }
  287. waitForExpectations(timeout: timeout, handler: nil)
  288. // Then
  289. XCTAssertEqual(request.state, .finished)
  290. }
  291. func testThatManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  292. // Given
  293. let eventMonitor = ClosureEventMonitor()
  294. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  295. let expect = expectation(description: "request should receive appropriate lifetime events")
  296. expect.expectedFulfillmentCount = 3
  297. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  298. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  299. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  300. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  301. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  302. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  303. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  304. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  305. // When
  306. let request = session.request(URLRequest.makeHTTPBinRequest())
  307. for _ in 0..<100 {
  308. request.resume()
  309. }
  310. waitForExpectations(timeout: timeout, handler: nil)
  311. // Then
  312. XCTAssertEqual(request.state, .finished)
  313. }
  314. func testThatRequestManuallyResumedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  315. // Given
  316. let eventMonitor = ClosureEventMonitor()
  317. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  318. let expect = expectation(description: "request should receive appropriate lifetime events")
  319. expect.expectedFulfillmentCount = 4
  320. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  321. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  322. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  323. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  324. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  325. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  326. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  327. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  328. // When
  329. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() }
  330. for _ in 0..<100 {
  331. request.resume()
  332. }
  333. waitForExpectations(timeout: timeout, handler: nil)
  334. // Then
  335. XCTAssertEqual(request.state, .finished)
  336. }
  337. func testThatRequestManuallySuspendedManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  338. // Given
  339. let eventMonitor = ClosureEventMonitor()
  340. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  341. let expect = expectation(description: "request should receive appropriate lifetime events")
  342. expect.expectedFulfillmentCount = 2
  343. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  344. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  345. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  346. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  347. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  348. // When
  349. let request = session.request(URLRequest.makeHTTPBinRequest())
  350. for _ in 0..<100 {
  351. request.suspend()
  352. }
  353. waitForExpectations(timeout: timeout, handler: nil)
  354. // Then
  355. XCTAssertEqual(request.state, .suspended)
  356. }
  357. func testThatRequestManuallySuspendedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  358. // Given
  359. let eventMonitor = ClosureEventMonitor()
  360. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  361. let expect = expectation(description: "request should receive appropriate lifetime events")
  362. expect.expectedFulfillmentCount = 2
  363. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  364. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  365. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  366. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  367. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  368. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  369. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  370. // When
  371. let request = session.request(URLRequest.makeHTTPBinRequest())
  372. for _ in 0..<100 {
  373. request.suspend()
  374. }
  375. waitForExpectations(timeout: timeout, handler: nil)
  376. // Then
  377. XCTAssertEqual(request.state, .suspended)
  378. }
  379. func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  380. // Given
  381. let eventMonitor = ClosureEventMonitor()
  382. let session = Session(eventMonitors: [eventMonitor])
  383. let expect = expectation(description: "request should receive appropriate lifetime events")
  384. expect.expectedFulfillmentCount = 2
  385. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  386. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  387. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  388. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  389. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  390. // When
  391. let request = session.request(URLRequest.makeHTTPBinRequest())
  392. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  393. eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
  394. for _ in 0..<100 {
  395. request.cancel()
  396. }
  397. }
  398. waitForExpectations(timeout: timeout, handler: nil)
  399. // Then
  400. XCTAssertEqual(request.state, .cancelled)
  401. }
  402. func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  403. // Given
  404. let eventMonitor = ClosureEventMonitor()
  405. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  406. let expect = expectation(description: "request should receive appropriate lifetime events")
  407. expect.expectedFulfillmentCount = 2
  408. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  409. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  410. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  411. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  412. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  413. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  414. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  415. // When
  416. let request = session.request(URLRequest.makeHTTPBinRequest())
  417. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  418. eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
  419. for _ in 0..<100 {
  420. request.cancel()
  421. }
  422. }
  423. waitForExpectations(timeout: timeout, handler: nil)
  424. // Then
  425. XCTAssertEqual(request.state, .cancelled)
  426. }
  427. func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() {
  428. // Given
  429. let eventMonitor = ClosureEventMonitor()
  430. let session = Session(eventMonitors: [eventMonitor])
  431. let expect = expectation(description: "request should receive appropriate lifetime events")
  432. expect.expectedFulfillmentCount = 6
  433. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  434. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  435. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  436. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  437. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  438. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  439. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  440. // When
  441. let request = session.request(URLRequest.makeHTTPBinRequest(path: "delay/5")).response { _ in expect.fulfill() }
  442. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  443. eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
  444. DispatchQueue.concurrentPerform(iterations: 100) { i in
  445. request.cancel()
  446. if i == 99 { expect.fulfill() }
  447. }
  448. }
  449. waitForExpectations(timeout: timeout, handler: nil)
  450. // Then
  451. XCTAssertEqual(request.state, .cancelled)
  452. }
  453. func testThatRequestTriggersAllAppropriateLifetimeEvents() {
  454. // Given
  455. let eventMonitor = ClosureEventMonitor()
  456. let session = Session(eventMonitors: [eventMonitor])
  457. let didReceiveChallenge = expectation(description: "didReceiveChallenge should fire")
  458. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  459. let didReceiveData = expectation(description: "didReceiveData should fire")
  460. let willCacheResponse = expectation(description: "willCacheResponse should fire")
  461. let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  462. let didCreateTask = expectation(description: "didCreateTask should fire")
  463. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  464. let didComplete = expectation(description: "didComplete should fire")
  465. let didFinish = expectation(description: "didFinish should fire")
  466. let didResume = expectation(description: "didResume should fire")
  467. let didResumeTask = expectation(description: "didResumeTask should fire")
  468. let didParseResponse = expectation(description: "didParseResponse should fire")
  469. let responseHandler = expectation(description: "responseHandler should fire")
  470. var dataReceived = false
  471. eventMonitor.taskDidReceiveChallenge = { _, _, _ in didReceiveChallenge.fulfill() }
  472. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  473. eventMonitor.dataTaskDidReceiveData = { _, _, _ in
  474. guard !dataReceived else { return }
  475. // Data may be received many times, fulfill only once.
  476. dataReceived = true
  477. didReceiveData.fulfill()
  478. }
  479. eventMonitor.dataTaskWillCacheResponse = { _, _, _ in willCacheResponse.fulfill() }
  480. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  481. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  482. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  483. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  484. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  485. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  486. eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
  487. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  488. // When
  489. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in
  490. responseHandler.fulfill()
  491. }
  492. waitForExpectations(timeout: timeout, handler: nil)
  493. // Then
  494. XCTAssertEqual(request.state, .finished)
  495. }
  496. func testThatCancelledRequestTriggersAllAppropriateLifetimeEvents() {
  497. // Given
  498. let eventMonitor = ClosureEventMonitor()
  499. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  500. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  501. let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  502. let didCreateTask = expectation(description: "didCreateTask should fire")
  503. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  504. let didComplete = expectation(description: "didComplete should fire")
  505. let didFinish = expectation(description: "didFinish should fire")
  506. let didResume = expectation(description: "didResume should fire")
  507. let didResumeTask = expectation(description: "didResumeTask should fire")
  508. let didParseResponse = expectation(description: "didParseResponse should fire")
  509. let didCancel = expectation(description: "didCancel should fire")
  510. let didCancelTask = expectation(description: "didCancelTask should fire")
  511. let responseHandler = expectation(description: "responseHandler should fire")
  512. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  513. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  514. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  515. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  516. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  517. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  518. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  519. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  520. eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
  521. eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
  522. // When
  523. let request = session.request(URLRequest.makeHTTPBinRequest(path: "delay/5")).response { _ in
  524. responseHandler.fulfill()
  525. }
  526. eventMonitor.requestDidResumeTask = { [unowned request] _, _ in
  527. request.cancel()
  528. didResumeTask.fulfill()
  529. }
  530. request.resume()
  531. waitForExpectations(timeout: timeout, handler: nil)
  532. // Then
  533. XCTAssertEqual(request.state, .cancelled)
  534. }
  535. func testThatAppendingResponseSerializerToCancelledRequestCallsCompletion() {
  536. // Given
  537. let session = Session()
  538. var response1: DataResponse<Any, AFError>?
  539. var response2: DataResponse<Any, AFError>?
  540. let expect = expectation(description: "both response serializer completions should be called")
  541. expect.expectedFulfillmentCount = 2
  542. // When
  543. let request = session.request(URLRequest.makeHTTPBinRequest())
  544. request.responseJSON { resp in
  545. response1 = resp
  546. expect.fulfill()
  547. request.responseJSON { resp in
  548. response2 = resp
  549. expect.fulfill()
  550. }
  551. }
  552. request.cancel()
  553. waitForExpectations(timeout: timeout, handler: nil)
  554. // Then
  555. XCTAssertEqual(response1?.error?.isExplicitlyCancelledError, true)
  556. XCTAssertEqual(response2?.error?.isExplicitlyCancelledError, true)
  557. }
  558. func testThatAppendingResponseSerializerToCompletedRequestInsideCompletionResumesRequest() {
  559. // Given
  560. let session = Session()
  561. var response1: DataResponse<Any, AFError>?
  562. var response2: DataResponse<Any, AFError>?
  563. var response3: DataResponse<Any, AFError>?
  564. let expect = expectation(description: "all response serializer completions should be called")
  565. expect.expectedFulfillmentCount = 3
  566. // When
  567. let request = session.request(URLRequest.makeHTTPBinRequest())
  568. request.responseJSON { resp in
  569. response1 = resp
  570. expect.fulfill()
  571. request.responseJSON { resp in
  572. response2 = resp
  573. expect.fulfill()
  574. request.responseJSON { resp in
  575. response3 = resp
  576. expect.fulfill()
  577. }
  578. }
  579. }
  580. waitForExpectations(timeout: timeout, handler: nil)
  581. // Then
  582. XCTAssertNotNil(response1?.value)
  583. XCTAssertNotNil(response2?.value)
  584. XCTAssertNotNil(response3?.value)
  585. }
  586. func testThatAppendingResponseSerializerToCompletedRequestOutsideCompletionResumesRequest() {
  587. // Given
  588. let session = Session()
  589. let request = session.request(URLRequest.makeHTTPBinRequest())
  590. var response1: DataResponse<Any, AFError>?
  591. var response2: DataResponse<Any, AFError>?
  592. var response3: DataResponse<Any, AFError>?
  593. // When
  594. let expect1 = expectation(description: "response serializer 1 completion should be called")
  595. request.responseJSON { response1 = $0; expect1.fulfill() }
  596. waitForExpectations(timeout: timeout, handler: nil)
  597. let expect2 = expectation(description: "response serializer 2 completion should be called")
  598. request.responseJSON { response2 = $0; expect2.fulfill() }
  599. waitForExpectations(timeout: timeout, handler: nil)
  600. let expect3 = expectation(description: "response serializer 3 completion should be called")
  601. request.responseJSON { response3 = $0; expect3.fulfill() }
  602. waitForExpectations(timeout: timeout, handler: nil)
  603. // Then
  604. XCTAssertNotNil(response1?.value)
  605. XCTAssertNotNil(response2?.value)
  606. XCTAssertNotNil(response3?.value)
  607. }
  608. }
  609. // MARK: -
  610. class RequestDescriptionTestCase: BaseTestCase {
  611. func testRequestDescription() {
  612. // Given
  613. let urlString = "https://httpbin.org/get"
  614. let manager = Session(startRequestsImmediately: false)
  615. let request = manager.request(urlString)
  616. let expectation = self.expectation(description: "Request description should update: \(urlString)")
  617. var response: HTTPURLResponse?
  618. // When
  619. request.response { resp in
  620. response = resp.response
  621. expectation.fulfill()
  622. }.resume()
  623. waitForExpectations(timeout: timeout, handler: nil)
  624. // Then
  625. XCTAssertEqual(request.description, "GET https://httpbin.org/get (\(response?.statusCode ?? -1))")
  626. }
  627. }
  628. // MARK: -
  629. final class RequestCURLDescriptionTestCase: BaseTestCase {
  630. // MARK: Properties
  631. let manager: Session = {
  632. let manager = Session()
  633. return manager
  634. }()
  635. let managerWithAcceptLanguageHeader: Session = {
  636. var headers = HTTPHeaders.default
  637. headers["Accept-Language"] = "en-US"
  638. let configuration = URLSessionConfiguration.af.default
  639. configuration.headers = headers
  640. let manager = Session(configuration: configuration)
  641. return manager
  642. }()
  643. let managerWithContentTypeHeader: Session = {
  644. var headers = HTTPHeaders.default
  645. headers["Content-Type"] = "application/json"
  646. let configuration = URLSessionConfiguration.af.default
  647. configuration.headers = headers
  648. let manager = Session(configuration: configuration)
  649. return manager
  650. }()
  651. func managerWithCookie(_ cookie: HTTPCookie) -> Session {
  652. let configuration = URLSessionConfiguration.af.default
  653. configuration.httpCookieStorage?.setCookie(cookie)
  654. return Session(configuration: configuration)
  655. }
  656. let managerDisallowingCookies: Session = {
  657. let configuration = URLSessionConfiguration.af.default
  658. configuration.httpShouldSetCookies = false
  659. let manager = Session(configuration: configuration)
  660. return manager
  661. }()
  662. // MARK: Tests
  663. func testGETRequestCURLDescription() {
  664. // Given
  665. let urlString = "https://httpbin.org/get"
  666. let expectation = self.expectation(description: "request should complete")
  667. var components: [String]?
  668. // When
  669. manager.request(urlString).cURLDescription {
  670. components = self.cURLCommandComponents(from: $0)
  671. expectation.fulfill()
  672. }
  673. waitForExpectations(timeout: timeout, handler: nil)
  674. // Then
  675. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  676. XCTAssertTrue(components?.contains("-X") == true)
  677. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  678. }
  679. func testGETRequestCURLDescriptionSynchronous() {
  680. // Given
  681. let urlString = "https://httpbin.org/get"
  682. let expectation = self.expectation(description: "request should complete")
  683. var components: [String]?
  684. var syncComponents: [String]?
  685. // When
  686. let request = manager.request(urlString)
  687. request.cURLDescription {
  688. components = self.cURLCommandComponents(from: $0)
  689. syncComponents = self.cURLCommandComponents(from: request.cURLDescription())
  690. expectation.fulfill()
  691. }
  692. waitForExpectations(timeout: timeout, handler: nil)
  693. // Then
  694. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  695. XCTAssertTrue(components?.contains("-X") == true)
  696. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  697. XCTAssertEqual(components?.sorted(), syncComponents?.sorted())
  698. }
  699. func testGETRequestCURLDescriptionCanBeRequestedManyTimes() {
  700. // Given
  701. let urlString = "https://httpbin.org/get"
  702. let expectation = self.expectation(description: "request should complete")
  703. var components: [String]?
  704. var secondComponents: [String]?
  705. // When
  706. let request = manager.request(urlString)
  707. request.cURLDescription {
  708. components = self.cURLCommandComponents(from: $0)
  709. request.cURLDescription {
  710. secondComponents = self.cURLCommandComponents(from: $0)
  711. expectation.fulfill()
  712. }
  713. }
  714. waitForExpectations(timeout: timeout, handler: nil)
  715. // Then
  716. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  717. XCTAssertTrue(components?.contains("-X") == true)
  718. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  719. XCTAssertEqual(components?.sorted(), secondComponents?.sorted())
  720. }
  721. func testGETRequestWithCustomHeaderCURLDescription() {
  722. // Given
  723. let urlString = "https://httpbin.org/get"
  724. let expectation = self.expectation(description: "request should complete")
  725. var cURLDescription: String?
  726. // When
  727. let headers: HTTPHeaders = ["X-Custom-Header": "{\"key\": \"value\"}"]
  728. manager.request(urlString, headers: headers).cURLDescription {
  729. cURLDescription = $0
  730. expectation.fulfill()
  731. }
  732. waitForExpectations(timeout: timeout, handler: nil)
  733. // Then
  734. XCTAssertNotNil(cURLDescription?.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\""))
  735. }
  736. func testGETRequestWithDuplicateHeadersDebugDescription() {
  737. // Given
  738. let urlString = "https://httpbin.org/get"
  739. let expectation = self.expectation(description: "request should complete")
  740. var cURLDescription: String?
  741. var components: [String]?
  742. // When
  743. let headers: HTTPHeaders = ["Accept-Language": "en-GB"]
  744. managerWithAcceptLanguageHeader.request(urlString, headers: headers).cURLDescription {
  745. components = self.cURLCommandComponents(from: $0)
  746. cURLDescription = $0
  747. expectation.fulfill()
  748. }
  749. waitForExpectations(timeout: timeout, handler: nil)
  750. // Then
  751. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  752. XCTAssertTrue(components?.contains("-X") == true)
  753. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  754. let acceptLanguageCount = components?.filter { $0.contains("Accept-Language") }.count
  755. XCTAssertEqual(acceptLanguageCount, 1, "command should contain a single Accept-Language header")
  756. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Accept-Language: en-GB\""))
  757. }
  758. func testPOSTRequestCURLDescription() {
  759. // Given
  760. let urlString = "https://httpbin.org/post"
  761. let expectation = self.expectation(description: "request should complete")
  762. var components: [String]?
  763. // When
  764. manager.request(urlString, method: .post).cURLDescription {
  765. components = self.cURLCommandComponents(from: $0)
  766. expectation.fulfill()
  767. }
  768. waitForExpectations(timeout: timeout, handler: nil)
  769. // Then
  770. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  771. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  772. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  773. }
  774. func testPOSTRequestWithJSONParametersCURLDescription() {
  775. // Given
  776. let urlString = "https://httpbin.org/post"
  777. let expectation = self.expectation(description: "request should complete")
  778. var cURLDescription: String?
  779. var components: [String]?
  780. let parameters = ["foo": "bar",
  781. "fo\"o": "b\"ar",
  782. "f'oo": "ba'r"]
  783. // When
  784. manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).cURLDescription {
  785. components = self.cURLCommandComponents(from: $0)
  786. cURLDescription = $0
  787. expectation.fulfill()
  788. }
  789. waitForExpectations(timeout: timeout, handler: nil)
  790. // Then
  791. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  792. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  793. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: application/json\""))
  794. XCTAssertNotNil(cURLDescription?.range(of: "-d \"{"))
  795. XCTAssertNotNil(cURLDescription?.range(of: "\\\"f'oo\\\":\\\"ba'r\\\""))
  796. XCTAssertNotNil(cURLDescription?.range(of: "\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\""))
  797. XCTAssertNotNil(cURLDescription?.range(of: "\\\"foo\\\":\\\"bar\\"))
  798. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  799. }
  800. func testPOSTRequestWithCookieCURLDescription() {
  801. // Given
  802. let urlString = "https://httpbin.org/post"
  803. let properties = [HTTPCookiePropertyKey.domain: "httpbin.org",
  804. HTTPCookiePropertyKey.path: "/post",
  805. HTTPCookiePropertyKey.name: "foo",
  806. HTTPCookiePropertyKey.value: "bar"]
  807. let cookie = HTTPCookie(properties: properties)!
  808. let cookieManager = managerWithCookie(cookie)
  809. let expectation = self.expectation(description: "request should complete")
  810. var components: [String]?
  811. // When
  812. cookieManager.request(urlString, method: .post).cURLDescription {
  813. components = self.cURLCommandComponents(from: $0)
  814. expectation.fulfill()
  815. }
  816. waitForExpectations(timeout: timeout, handler: nil)
  817. // Then
  818. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  819. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  820. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  821. XCTAssertEqual(components?[5..<6], ["-b"])
  822. }
  823. func testPOSTRequestWithCookiesDisabledCURLDescriptionHasNoCookies() {
  824. // Given
  825. let urlString = "https://httpbin.org/post"
  826. let properties = [HTTPCookiePropertyKey.domain: "httpbin.org",
  827. HTTPCookiePropertyKey.path: "/post",
  828. HTTPCookiePropertyKey.name: "foo",
  829. HTTPCookiePropertyKey.value: "bar"]
  830. let cookie = HTTPCookie(properties: properties)!
  831. managerDisallowingCookies.session.configuration.httpCookieStorage?.setCookie(cookie)
  832. let expectation = self.expectation(description: "request should complete")
  833. var components: [String]?
  834. // When
  835. managerDisallowingCookies.request(urlString, method: .post).cURLDescription {
  836. components = self.cURLCommandComponents(from: $0)
  837. expectation.fulfill()
  838. }
  839. waitForExpectations(timeout: timeout, handler: nil)
  840. // Then
  841. let cookieComponents = components?.filter { $0 == "-b" }
  842. XCTAssertTrue(cookieComponents?.isEmpty == true)
  843. }
  844. func testMultipartFormDataRequestWithDuplicateHeadersCURLDescriptionHasOneContentTypeHeader() {
  845. // Given
  846. let urlString = "https://httpbin.org/post"
  847. let japaneseData = Data("日本語".utf8)
  848. let expectation = self.expectation(description: "multipart form data encoding should succeed")
  849. var cURLDescription: String?
  850. var components: [String]?
  851. // When
  852. managerWithContentTypeHeader.upload(multipartFormData: { data in
  853. data.append(japaneseData, withName: "japanese")
  854. }, to: urlString).cURLDescription {
  855. components = self.cURLCommandComponents(from: $0)
  856. cURLDescription = $0
  857. expectation.fulfill()
  858. }
  859. waitForExpectations(timeout: timeout, handler: nil)
  860. // Then
  861. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  862. XCTAssertTrue(components?.contains("-X") == true)
  863. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  864. let contentTypeCount = components?.filter { $0.contains("Content-Type") }.count
  865. XCTAssertEqual(contentTypeCount, 1, "command should contain a single Content-Type header")
  866. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: multipart/form-data;"))
  867. }
  868. func testThatRequestWithInvalidURLDebugDescription() {
  869. // Given
  870. let urlString = "invalid_url"
  871. let expectation = self.expectation(description: "request should complete")
  872. var cURLDescription: String?
  873. // When
  874. manager.request(urlString).cURLDescription {
  875. cURLDescription = $0
  876. expectation.fulfill()
  877. }
  878. waitForExpectations(timeout: timeout, handler: nil)
  879. // Then
  880. XCTAssertNotNil(cURLDescription, "debugDescription should not crash")
  881. }
  882. // MARK: Test Helper Methods
  883. private func cURLCommandComponents(from cURLString: String) -> [String] {
  884. cURLString.components(separatedBy: .whitespacesAndNewlines)
  885. .filter { $0 != "" && $0 != "\\" }
  886. }
  887. }