RequestTests.swift 39 KB

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