RequestTests.swift 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. //
  2. // RequestTests.swift
  3. //
  4. // Copyright (c) 2014-2020 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 url = Endpoint.get.url
  31. let expectation = expectation(description: "GET request should succeed: \(url)")
  32. var response: DataResponse<Data?, AFError>?
  33. // When
  34. AF.request(url, parameters: ["foo": "bar"])
  35. .response { resp in
  36. response = resp
  37. expectation.fulfill()
  38. }
  39. waitForExpectations(timeout: timeout)
  40. // Then
  41. XCTAssertNotNil(response?.request)
  42. XCTAssertNotNil(response?.response)
  43. XCTAssertNotNil(response?.data)
  44. XCTAssertNil(response?.error)
  45. }
  46. func testThatDataRequestReceivesInitialResponse() {
  47. // Given
  48. let url = Endpoint.get.url
  49. var initialResponse: HTTPURLResponse?
  50. let didReceiveResponse = expectation(description: "didReceiveResponse")
  51. let didComplete = expectation(description: "GET request should succeed: \(url)")
  52. var response: DataResponse<Data?, AFError>?
  53. // When
  54. AF.request(url, parameters: ["foo": "bar"])
  55. .onHTTPResponse { response in
  56. initialResponse = response
  57. didReceiveResponse.fulfill()
  58. }
  59. .response { resp in
  60. response = resp
  61. didComplete.fulfill()
  62. }
  63. wait(for: [didReceiveResponse, didComplete], timeout: timeout, enforceOrder: true)
  64. // Then
  65. XCTAssertEqual(initialResponse, response?.response)
  66. XCTAssertNotNil(response?.request)
  67. XCTAssertNotNil(response?.response)
  68. XCTAssertNotNil(response?.data)
  69. XCTAssertNil(response?.error)
  70. }
  71. func testThatDataRequestOnHTTPResponseCanAllow() {
  72. // Given
  73. let url = Endpoint.get.url
  74. var initialResponse: HTTPURLResponse?
  75. let didReceiveResponse = expectation(description: "didReceiveResponse")
  76. let didComplete = expectation(description: "GET request should succeed: \(url)")
  77. var response: DataResponse<Data?, AFError>?
  78. // When
  79. AF.request(url, parameters: ["foo": "bar"])
  80. .onHTTPResponse { response, completionHandler in
  81. initialResponse = response
  82. didReceiveResponse.fulfill()
  83. completionHandler(.allow)
  84. }
  85. .response { resp in
  86. response = resp
  87. didComplete.fulfill()
  88. }
  89. wait(for: [didReceiveResponse, didComplete], timeout: timeout, enforceOrder: true)
  90. // Then
  91. XCTAssertEqual(initialResponse, response?.response)
  92. XCTAssertNotNil(response?.request)
  93. XCTAssertNotNil(response?.response)
  94. XCTAssertNotNil(response?.data)
  95. XCTAssertNil(response?.error)
  96. }
  97. func testThatDataRequestOnHTTPResponseCanCancel() {
  98. // Given
  99. let url = Endpoint.get.url
  100. var initialResponse: HTTPURLResponse?
  101. let didReceiveResponse = expectation(description: "didReceiveResponse")
  102. let didComplete = expectation(description: "GET request should succeed: \(url)")
  103. var response: DataResponse<Data?, AFError>?
  104. // When
  105. let request = AF.request(url, parameters: ["foo": "bar"])
  106. .onHTTPResponse { response, completionHandler in
  107. initialResponse = response
  108. didReceiveResponse.fulfill()
  109. completionHandler(.cancel)
  110. }
  111. .response { resp in
  112. response = resp
  113. didComplete.fulfill()
  114. }
  115. wait(for: [didReceiveResponse, didComplete], timeout: timeout, enforceOrder: true)
  116. // Then
  117. XCTAssertEqual(initialResponse, response?.response)
  118. XCTAssertNotNil(response?.request)
  119. XCTAssertNotNil(response?.response)
  120. XCTAssertNil(response?.data)
  121. XCTAssertTrue(request.isCancelled, "onHTTPResponse cancelled request should have isCancelled == true")
  122. XCTAssertTrue(response?.error?.isExplicitlyCancelledError == true, "onHTTPResponse cancelled request should be explicitly cancelled")
  123. }
  124. func testRequestResponseWithProgress() {
  125. // Given
  126. let byteCount = 50 * 1024
  127. let url = Endpoint.bytes(byteCount).url
  128. let expectation = expectation(description: "Bytes download progress should be reported: \(url)")
  129. var progressValues: [Double] = []
  130. var response: DataResponse<Data?, AFError>?
  131. // When
  132. AF.request(url)
  133. .downloadProgress { progress in
  134. progressValues.append(progress.fractionCompleted)
  135. }
  136. .response { resp in
  137. response = resp
  138. expectation.fulfill()
  139. }
  140. waitForExpectations(timeout: timeout)
  141. // Then
  142. XCTAssertNotNil(response?.request)
  143. XCTAssertNotNil(response?.response)
  144. XCTAssertNotNil(response?.data)
  145. XCTAssertNil(response?.error)
  146. var previousProgress: Double = progressValues.first ?? 0.0
  147. for progress in progressValues {
  148. XCTAssertGreaterThanOrEqual(progress, previousProgress)
  149. previousProgress = progress
  150. }
  151. if let lastProgressValue = progressValues.last {
  152. XCTAssertEqual(lastProgressValue, 1.0)
  153. } else {
  154. XCTFail("last item in progressValues should not be nil")
  155. }
  156. }
  157. func testPOSTRequestWithUnicodeParameters() {
  158. // Given
  159. let parameters = ["french": "français",
  160. "japanese": "日本語",
  161. "arabic": "العربية",
  162. "emoji": "😃"]
  163. let expectation = expectation(description: "request should succeed")
  164. var response: DataResponse<TestResponse, AFError>?
  165. // When
  166. AF.request(.method(.post), parameters: parameters)
  167. .responseDecodable(of: TestResponse.self) { closureResponse in
  168. response = closureResponse
  169. expectation.fulfill()
  170. }
  171. waitForExpectations(timeout: timeout)
  172. // Then
  173. XCTAssertNotNil(response?.request)
  174. XCTAssertNotNil(response?.response)
  175. XCTAssertNotNil(response?.data)
  176. if let form = response?.result.success?.form {
  177. XCTAssertEqual(form["french"], parameters["french"])
  178. XCTAssertEqual(form["japanese"], parameters["japanese"])
  179. XCTAssertEqual(form["arabic"], parameters["arabic"])
  180. XCTAssertEqual(form["emoji"], parameters["emoji"])
  181. } else {
  182. XCTFail("form parameter in JSON should not be nil")
  183. }
  184. }
  185. func testPOSTRequestWithBase64EncodedImages() {
  186. // Given
  187. let pngBase64EncodedString: String = {
  188. let fileURL = url(forResource: "unicorn", withExtension: "png")
  189. let data = try! Data(contentsOf: fileURL)
  190. return data.base64EncodedString(options: .lineLength64Characters)
  191. }()
  192. let jpegBase64EncodedString: String = {
  193. let fileURL = url(forResource: "rainbow", withExtension: "jpg")
  194. let data = try! Data(contentsOf: fileURL)
  195. return data.base64EncodedString(options: .lineLength64Characters)
  196. }()
  197. let parameters = ["email": "user@alamofire.org",
  198. "png_image": pngBase64EncodedString,
  199. "jpeg_image": jpegBase64EncodedString]
  200. let expectation = expectation(description: "request should succeed")
  201. var response: DataResponse<TestResponse, AFError>?
  202. // When
  203. AF.request(Endpoint.method(.post), method: .post, parameters: parameters)
  204. .responseDecodable(of: TestResponse.self) { closureResponse in
  205. response = closureResponse
  206. expectation.fulfill()
  207. }
  208. waitForExpectations(timeout: timeout)
  209. // Then
  210. XCTAssertNotNil(response?.request)
  211. XCTAssertNotNil(response?.response)
  212. XCTAssertNotNil(response?.data)
  213. XCTAssertEqual(response?.result.isSuccess, true)
  214. if let form = response?.result.success?.form {
  215. XCTAssertEqual(form["email"], parameters["email"])
  216. XCTAssertEqual(form["png_image"], parameters["png_image"])
  217. XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"])
  218. } else {
  219. XCTFail("form parameter in JSON should not be nil")
  220. }
  221. }
  222. // MARK: Queues
  223. func testThatResponseSerializationWorksWithSerializationQueue() {
  224. // Given
  225. let queue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
  226. let manager = Session(serializationQueue: queue)
  227. let expectation = expectation(description: "request should complete")
  228. var response: DataResponse<TestResponse, AFError>?
  229. // When
  230. manager.request(.get).responseDecodable(of: TestResponse.self) { resp in
  231. response = resp
  232. expectation.fulfill()
  233. }
  234. waitForExpectations(timeout: timeout)
  235. // Then
  236. XCTAssertEqual(response?.result.isSuccess, true)
  237. }
  238. func testThatRequestsWorksWithRequestAndSerializationQueues() {
  239. // Given
  240. let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue")
  241. let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
  242. let manager = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
  243. let expectation = expectation(description: "request should complete")
  244. var response: DataResponse<TestResponse, AFError>?
  245. // When
  246. manager.request(.get).responseDecodable(of: TestResponse.self) { resp in
  247. response = resp
  248. expectation.fulfill()
  249. }
  250. waitForExpectations(timeout: timeout)
  251. // Then
  252. XCTAssertEqual(response?.result.isSuccess, true)
  253. }
  254. func testThatRequestsWorksWithConcurrentRequestAndSerializationQueues() {
  255. // Given
  256. let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue", attributes: .concurrent)
  257. let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue", attributes: .concurrent)
  258. let session = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
  259. let count = 10
  260. let expectation = expectation(description: "request should complete")
  261. expectation.expectedFulfillmentCount = count
  262. var responses: [DataResponse<TestResponse, AFError>] = []
  263. // When
  264. DispatchQueue.concurrentPerform(iterations: count) { _ in
  265. session.request(.default).responseDecodable(of: TestResponse.self) { resp in
  266. responses.append(resp)
  267. expectation.fulfill()
  268. }
  269. }
  270. waitForExpectations(timeout: timeout, handler: nil)
  271. // Then
  272. XCTAssertEqual(responses.count, count)
  273. XCTAssertTrue(responses.allSatisfy(\.result.isSuccess))
  274. }
  275. // MARK: Encodable Parameters
  276. func testThatRequestsCanPassEncodableParametersAsJSONBodyData() {
  277. // Given
  278. let parameters = TestParameters(property: "one")
  279. let expect = expectation(description: "request should complete")
  280. var receivedResponse: DataResponse<TestResponse, AFError>?
  281. // When
  282. AF.request(.method(.post), parameters: parameters, encoder: JSONParameterEncoder.default)
  283. .responseDecodable(of: TestResponse.self) { response in
  284. receivedResponse = response
  285. expect.fulfill()
  286. }
  287. waitForExpectations(timeout: timeout)
  288. // Then
  289. XCTAssertEqual(receivedResponse?.result.success?.data, "{\"property\":\"one\"}")
  290. }
  291. func testThatRequestsCanPassEncodableParametersAsAURLQuery() {
  292. // Given
  293. let parameters = TestParameters(property: "one")
  294. let expect = expectation(description: "request should complete")
  295. var receivedResponse: DataResponse<TestResponse, AFError>?
  296. // When
  297. AF.request(.method(.get), parameters: parameters)
  298. .responseDecodable(of: TestResponse.self) { response in
  299. receivedResponse = response
  300. expect.fulfill()
  301. }
  302. waitForExpectations(timeout: timeout)
  303. // Then
  304. XCTAssertEqual(receivedResponse?.result.success?.args, ["property": "one"])
  305. }
  306. func testThatRequestsCanPassEncodableParametersAsURLEncodedBodyData() {
  307. // Given
  308. let parameters = TestParameters(property: "one")
  309. let expect = expectation(description: "request should complete")
  310. var receivedResponse: DataResponse<TestResponse, AFError>?
  311. // When
  312. AF.request(.method(.post), parameters: parameters)
  313. .responseDecodable(of: TestResponse.self) { response in
  314. receivedResponse = response
  315. expect.fulfill()
  316. }
  317. waitForExpectations(timeout: timeout)
  318. // Then
  319. XCTAssertEqual(receivedResponse?.result.success?.form, ["property": "one"])
  320. }
  321. // MARK: Lifetime Events
  322. func testThatAutomaticallyResumedRequestReceivesAppropriateLifetimeEvents() {
  323. // Given
  324. let eventMonitor = ClosureEventMonitor()
  325. let session = Session(eventMonitors: [eventMonitor])
  326. let expect = expectation(description: "request should receive appropriate lifetime events")
  327. expect.expectedFulfillmentCount = 4
  328. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  329. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  330. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  331. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  332. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  333. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  334. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  335. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  336. // When
  337. let request = session.request(.default).response { _ in expect.fulfill() }
  338. waitForExpectations(timeout: timeout)
  339. // Then
  340. XCTAssertEqual(request.state, .finished)
  341. }
  342. func testThatAutomaticallyAndManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  343. // Given
  344. let eventMonitor = ClosureEventMonitor()
  345. let session = Session(eventMonitors: [eventMonitor])
  346. let expect = expectation(description: "request should receive appropriate lifetime events")
  347. expect.expectedFulfillmentCount = 4
  348. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  349. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  350. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  351. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  352. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  353. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  354. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  355. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  356. // When
  357. let request = session.request(.default).response { _ in expect.fulfill() }
  358. for _ in 0..<100 {
  359. request.resume()
  360. }
  361. waitForExpectations(timeout: timeout)
  362. // Then
  363. XCTAssertEqual(request.state, .finished)
  364. }
  365. func testThatManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  366. // Given
  367. let eventMonitor = ClosureEventMonitor()
  368. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  369. let expect = expectation(description: "request should receive appropriate lifetime events")
  370. expect.expectedFulfillmentCount = 3
  371. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  372. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  373. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  374. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  375. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  376. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  377. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  378. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  379. // When
  380. let request = session.request(.default)
  381. for _ in 0..<100 {
  382. request.resume()
  383. }
  384. waitForExpectations(timeout: timeout)
  385. // Then
  386. XCTAssertEqual(request.state, .finished)
  387. }
  388. func testThatRequestManuallyResumedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  389. // Given
  390. let eventMonitor = ClosureEventMonitor()
  391. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  392. let expect = expectation(description: "request should receive appropriate lifetime events")
  393. expect.expectedFulfillmentCount = 4
  394. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  395. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  396. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  397. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  398. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  399. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  400. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  401. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  402. // When
  403. let request = session.request(.default).response { _ in expect.fulfill() }
  404. for _ in 0..<100 {
  405. request.resume()
  406. }
  407. waitForExpectations(timeout: timeout)
  408. // Then
  409. XCTAssertEqual(request.state, .finished)
  410. }
  411. func testThatRequestManuallySuspendedManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  412. // Given
  413. let eventMonitor = ClosureEventMonitor()
  414. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  415. let expect = expectation(description: "request should receive appropriate lifetime events")
  416. expect.expectedFulfillmentCount = 2
  417. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  418. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  419. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  420. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  421. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  422. // When
  423. let request = session.request(.default)
  424. for _ in 0..<100 {
  425. request.suspend()
  426. }
  427. waitForExpectations(timeout: timeout)
  428. // Then
  429. XCTAssertEqual(request.state, .suspended)
  430. }
  431. func testThatRequestManuallySuspendedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  432. // Given
  433. let eventMonitor = ClosureEventMonitor()
  434. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  435. let expect = expectation(description: "request should receive appropriate lifetime events")
  436. expect.expectedFulfillmentCount = 2
  437. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  438. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  439. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  440. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  441. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  442. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  443. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  444. // When
  445. let request = session.request(.default)
  446. for _ in 0..<100 {
  447. request.suspend()
  448. }
  449. waitForExpectations(timeout: timeout)
  450. // Then
  451. XCTAssertEqual(request.state, .suspended)
  452. }
  453. func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  454. // Given
  455. let eventMonitor = ClosureEventMonitor()
  456. let session = Session(eventMonitors: [eventMonitor])
  457. let expect = expectation(description: "request should receive appropriate lifetime events")
  458. expect.expectedFulfillmentCount = 2
  459. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  460. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  461. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  462. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  463. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  464. // When
  465. let request = session.request(.default)
  466. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  467. eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
  468. for _ in 0..<100 {
  469. request.cancel()
  470. }
  471. }
  472. waitForExpectations(timeout: timeout)
  473. // Then
  474. XCTAssertEqual(request.state, .cancelled)
  475. }
  476. func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  477. // Given
  478. let eventMonitor = ClosureEventMonitor()
  479. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  480. let expect = expectation(description: "request should receive appropriate lifetime events")
  481. expect.expectedFulfillmentCount = 2
  482. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  483. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  484. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  485. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  486. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  487. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  488. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  489. // When
  490. let request = session.request(.default)
  491. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  492. eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
  493. for _ in 0..<100 {
  494. request.cancel()
  495. }
  496. }
  497. waitForExpectations(timeout: timeout)
  498. // Then
  499. XCTAssertEqual(request.state, .cancelled)
  500. }
  501. func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() {
  502. // Given
  503. let eventMonitor = ClosureEventMonitor()
  504. let session = Session(eventMonitors: [eventMonitor])
  505. let expect = expectation(description: "request should receive appropriate lifetime events")
  506. expect.expectedFulfillmentCount = 6
  507. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  508. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  509. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  510. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  511. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  512. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  513. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  514. // When
  515. let request = session.request(.delay(5)).response { _ in expect.fulfill() }
  516. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  517. eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
  518. DispatchQueue.concurrentPerform(iterations: 100) { i in
  519. request.cancel()
  520. if i == 99 { expect.fulfill() }
  521. }
  522. }
  523. waitForExpectations(timeout: timeout)
  524. // Then
  525. XCTAssertEqual(request.state, .cancelled)
  526. }
  527. func testThatRequestTriggersAllAppropriateLifetimeEvents() {
  528. // Given
  529. let eventMonitor = ClosureEventMonitor()
  530. let session = Session(eventMonitors: [eventMonitor])
  531. // Disable event test until Firewalk support HTTPS.
  532. // let didReceiveChallenge = expectation(description: "didReceiveChallenge should fire")
  533. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  534. let didReceiveData = expectation(description: "didReceiveData should fire")
  535. let willCacheResponse = expectation(description: "willCacheResponse should fire")
  536. let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  537. let didCreateTask = expectation(description: "didCreateTask should fire")
  538. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  539. let didComplete = expectation(description: "didComplete should fire")
  540. let didFinish = expectation(description: "didFinish should fire")
  541. let didResume = expectation(description: "didResume should fire")
  542. let didResumeTask = expectation(description: "didResumeTask should fire")
  543. let didParseResponse = expectation(description: "didParseResponse should fire")
  544. let responseHandler = expectation(description: "responseHandler should fire")
  545. var dataReceived = false
  546. // Disable event test until Firewalk supports HTTPS.
  547. // eventMonitor.taskDidReceiveChallenge = { _, _, _ in didReceiveChallenge.fulfill() }
  548. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  549. eventMonitor.dataTaskDidReceiveData = { _, _, _ in
  550. guard !dataReceived else { return }
  551. // Data may be received many times, fulfill only once.
  552. dataReceived = true
  553. didReceiveData.fulfill()
  554. }
  555. eventMonitor.dataTaskWillCacheResponse = { _, _, _ in willCacheResponse.fulfill() }
  556. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  557. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  558. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  559. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  560. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  561. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  562. eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
  563. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  564. // When
  565. let request = session.request(.default).response { _ in
  566. responseHandler.fulfill()
  567. }
  568. waitForExpectations(timeout: timeout)
  569. // Then
  570. XCTAssertEqual(request.state, .finished)
  571. }
  572. func testThatCancelledRequestTriggersAllAppropriateLifetimeEvents() {
  573. // Given
  574. let eventMonitor = ClosureEventMonitor()
  575. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  576. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  577. let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  578. let didCreateTask = expectation(description: "didCreateTask should fire")
  579. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  580. let didComplete = expectation(description: "didComplete should fire")
  581. let didFinish = expectation(description: "didFinish should fire")
  582. let didResume = expectation(description: "didResume should fire")
  583. let didResumeTask = expectation(description: "didResumeTask should fire")
  584. let didParseResponse = expectation(description: "didParseResponse should fire")
  585. let didCancel = expectation(description: "didCancel should fire")
  586. let didCancelTask = expectation(description: "didCancelTask should fire")
  587. let responseHandler = expectation(description: "responseHandler should fire")
  588. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  589. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  590. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  591. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  592. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  593. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  594. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  595. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  596. eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
  597. eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
  598. // When
  599. let request = session.request(.delay(5)).response { _ in
  600. responseHandler.fulfill()
  601. }
  602. eventMonitor.requestDidResumeTask = { [unowned request] _, _ in
  603. request.cancel()
  604. didResumeTask.fulfill()
  605. }
  606. request.resume()
  607. waitForExpectations(timeout: timeout)
  608. // Then
  609. XCTAssertEqual(request.state, .cancelled)
  610. }
  611. func testThatAppendingResponseSerializerToCancelledRequestCallsCompletion() {
  612. // Given
  613. let session = Session()
  614. var response1: DataResponse<TestResponse, AFError>?
  615. var response2: DataResponse<TestResponse, AFError>?
  616. let expect = expectation(description: "both response serializer completions should be called")
  617. expect.expectedFulfillmentCount = 2
  618. // When
  619. let request = session.request(.default)
  620. request.responseDecodable(of: TestResponse.self) { resp in
  621. response1 = resp
  622. expect.fulfill()
  623. request.responseDecodable(of: TestResponse.self) { resp in
  624. response2 = resp
  625. expect.fulfill()
  626. }
  627. }
  628. request.cancel()
  629. waitForExpectations(timeout: timeout)
  630. // Then
  631. XCTAssertEqual(response1?.error?.isExplicitlyCancelledError, true)
  632. XCTAssertEqual(response2?.error?.isExplicitlyCancelledError, true)
  633. }
  634. func testThatAppendingResponseSerializerToCompletedRequestInsideCompletionResumesRequest() {
  635. // Given
  636. let session = Session()
  637. var response1: DataResponse<TestResponse, AFError>?
  638. var response2: DataResponse<TestResponse, AFError>?
  639. var response3: DataResponse<TestResponse, AFError>?
  640. let expect = expectation(description: "all response serializer completions should be called")
  641. expect.expectedFulfillmentCount = 3
  642. // When
  643. let request = session.request(.default)
  644. request.responseDecodable(of: TestResponse.self) { resp in
  645. response1 = resp
  646. expect.fulfill()
  647. request.responseDecodable(of: TestResponse.self) { resp in
  648. response2 = resp
  649. expect.fulfill()
  650. request.responseDecodable(of: TestResponse.self) { resp in
  651. response3 = resp
  652. expect.fulfill()
  653. }
  654. }
  655. }
  656. waitForExpectations(timeout: timeout)
  657. // Then
  658. XCTAssertNotNil(response1?.value)
  659. XCTAssertNotNil(response2?.value)
  660. XCTAssertNotNil(response3?.value)
  661. }
  662. func testThatAppendingResponseSerializerToCompletedRequestOutsideCompletionResumesRequest() {
  663. // Given
  664. let session = Session()
  665. let request = session.request(.default)
  666. var response1: DataResponse<TestResponse, AFError>?
  667. var response2: DataResponse<TestResponse, AFError>?
  668. var response3: DataResponse<TestResponse, AFError>?
  669. // When
  670. let expect1 = expectation(description: "response serializer 1 completion should be called")
  671. request.responseDecodable(of: TestResponse.self) { response1 = $0; expect1.fulfill() }
  672. waitForExpectations(timeout: timeout)
  673. let expect2 = expectation(description: "response serializer 2 completion should be called")
  674. request.responseDecodable(of: TestResponse.self) { response2 = $0; expect2.fulfill() }
  675. waitForExpectations(timeout: timeout)
  676. let expect3 = expectation(description: "response serializer 3 completion should be called")
  677. request.responseDecodable(of: TestResponse.self) { response3 = $0; expect3.fulfill() }
  678. waitForExpectations(timeout: timeout)
  679. // Then
  680. XCTAssertNotNil(response1?.value)
  681. XCTAssertNotNil(response2?.value)
  682. XCTAssertNotNil(response3?.value)
  683. }
  684. }
  685. // MARK: -
  686. final class RequestDescriptionTestCase: BaseTestCase {
  687. func testRequestDescription() {
  688. // Given
  689. let url = Endpoint().url
  690. let manager = Session(startRequestsImmediately: false)
  691. let request = manager.request(url)
  692. let expectation = expectation(description: "Request description should update: \(url)")
  693. var response: HTTPURLResponse?
  694. // When
  695. request.response { resp in
  696. response = resp.response
  697. expectation.fulfill()
  698. }.resume()
  699. waitForExpectations(timeout: timeout)
  700. // Then
  701. XCTAssertEqual(request.description, "GET \(url) (\(response?.statusCode ?? -1))")
  702. }
  703. }
  704. // MARK: -
  705. final class RequestCURLDescriptionTestCase: BaseTestCase {
  706. // MARK: Properties
  707. let session: Session = {
  708. let manager = Session()
  709. return manager
  710. }()
  711. let sessionWithAcceptLanguageHeader: Session = {
  712. var headers = HTTPHeaders.default
  713. headers["Accept-Language"] = "en-US"
  714. let configuration = URLSessionConfiguration.af.default
  715. configuration.headers = headers
  716. let manager = Session(configuration: configuration)
  717. return manager
  718. }()
  719. let sessionWithContentTypeHeader: Session = {
  720. var headers = HTTPHeaders.default
  721. headers["Content-Type"] = "application/json"
  722. let configuration = URLSessionConfiguration.af.default
  723. configuration.headers = headers
  724. let manager = Session(configuration: configuration)
  725. return manager
  726. }()
  727. func sessionWithCookie(_ cookie: HTTPCookie) -> Session {
  728. let configuration = URLSessionConfiguration.af.default
  729. configuration.httpCookieStorage?.setCookie(cookie)
  730. return Session(configuration: configuration)
  731. }
  732. let sessionDisallowingCookies: Session = {
  733. let configuration = URLSessionConfiguration.af.default
  734. configuration.httpShouldSetCookies = false
  735. let manager = Session(configuration: configuration)
  736. return manager
  737. }()
  738. // MARK: Tests
  739. func testGETRequestCURLDescription() {
  740. // Given
  741. let url = Endpoint().url
  742. let expectation = expectation(description: "request should complete")
  743. var components: [String]?
  744. // When
  745. session.request(url).cURLDescription {
  746. components = self.cURLCommandComponents(from: $0)
  747. expectation.fulfill()
  748. }
  749. waitForExpectations(timeout: timeout)
  750. // Then
  751. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  752. XCTAssertTrue(components?.contains("-X") == true)
  753. XCTAssertEqual(components?.last, "\"\(url)\"")
  754. }
  755. func testGETRequestCURLDescriptionOnMainQueue() {
  756. // Given
  757. let url = Endpoint().url
  758. let expectation = expectation(description: "request should complete")
  759. var isMainThread = false
  760. var components: [String]?
  761. // When
  762. session.request(url).cURLDescription(on: .main) {
  763. components = self.cURLCommandComponents(from: $0)
  764. isMainThread = Thread.isMainThread
  765. expectation.fulfill()
  766. }
  767. waitForExpectations(timeout: timeout, handler: nil)
  768. // Then
  769. XCTAssertTrue(isMainThread)
  770. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  771. XCTAssertTrue(components?.contains("-X") == true)
  772. XCTAssertEqual(components?.last, "\"\(url)\"")
  773. }
  774. func testGETRequestCURLDescriptionSynchronous() {
  775. // Given
  776. let url = Endpoint().url
  777. let expectation = expectation(description: "request should complete")
  778. var components: [String]?
  779. var syncComponents: [String]?
  780. // When
  781. let request = session.request(url)
  782. request.cURLDescription {
  783. components = self.cURLCommandComponents(from: $0)
  784. syncComponents = self.cURLCommandComponents(from: request.cURLDescription())
  785. expectation.fulfill()
  786. }
  787. waitForExpectations(timeout: timeout)
  788. // Then
  789. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  790. XCTAssertTrue(components?.contains("-X") == true)
  791. XCTAssertEqual(components?.last, "\"\(url)\"")
  792. XCTAssertEqual(components?.sorted(), syncComponents?.sorted())
  793. }
  794. func testGETRequestCURLDescriptionCanBeRequestedManyTimes() {
  795. // Given
  796. let url = Endpoint().url
  797. let expectation = expectation(description: "request should complete")
  798. var components: [String]?
  799. var secondComponents: [String]?
  800. // When
  801. let request = session.request(url)
  802. request.cURLDescription {
  803. components = self.cURLCommandComponents(from: $0)
  804. request.cURLDescription {
  805. secondComponents = self.cURLCommandComponents(from: $0)
  806. expectation.fulfill()
  807. }
  808. }
  809. waitForExpectations(timeout: timeout)
  810. // Then
  811. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  812. XCTAssertTrue(components?.contains("-X") == true)
  813. XCTAssertEqual(components?.last, "\"\(url)\"")
  814. XCTAssertEqual(components?.sorted(), secondComponents?.sorted())
  815. }
  816. func testGETRequestWithCustomHeaderCURLDescription() {
  817. // Given
  818. let url = Endpoint().url
  819. let expectation = expectation(description: "request should complete")
  820. var cURLDescription: String?
  821. // When
  822. let headers: HTTPHeaders = ["X-Custom-Header": "{\"key\": \"value\"}"]
  823. session.request(url, headers: headers).cURLDescription {
  824. cURLDescription = $0
  825. expectation.fulfill()
  826. }
  827. waitForExpectations(timeout: timeout)
  828. // Then
  829. XCTAssertNotNil(cURLDescription?.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\""))
  830. }
  831. func testGETRequestWithDuplicateHeadersDebugDescription() {
  832. // Given
  833. let url = Endpoint().url
  834. let expectation = expectation(description: "request should complete")
  835. var cURLDescription: String?
  836. var components: [String]?
  837. // When
  838. let headers: HTTPHeaders = ["Accept-Language": "en-GB"]
  839. sessionWithAcceptLanguageHeader.request(url, headers: headers).cURLDescription {
  840. components = self.cURLCommandComponents(from: $0)
  841. cURLDescription = $0
  842. expectation.fulfill()
  843. }
  844. waitForExpectations(timeout: timeout)
  845. // Then
  846. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  847. XCTAssertTrue(components?.contains("-X") == true)
  848. XCTAssertEqual(components?.last, "\"\(url)\"")
  849. let acceptLanguageCount = components?.filter { $0.contains("Accept-Language") }.count
  850. XCTAssertEqual(acceptLanguageCount, 1, "command should contain a single Accept-Language header")
  851. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Accept-Language: en-GB\""))
  852. }
  853. func testPOSTRequestCURLDescription() {
  854. // Given
  855. let url = Endpoint.method(.post).url
  856. let expectation = expectation(description: "request should complete")
  857. var components: [String]?
  858. // When
  859. session.request(url, method: .post).cURLDescription {
  860. components = self.cURLCommandComponents(from: $0)
  861. expectation.fulfill()
  862. }
  863. waitForExpectations(timeout: timeout)
  864. // Then
  865. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  866. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  867. XCTAssertEqual(components?.last, "\"\(url)\"")
  868. }
  869. func testPOSTRequestWithJSONParametersCURLDescription() {
  870. // Given
  871. let url = Endpoint.method(.post).url
  872. let expectation = expectation(description: "request should complete")
  873. var cURLDescription: String?
  874. var components: [String]?
  875. let parameters = ["foo": "bar",
  876. "fo\"o": "b\"ar",
  877. "f'oo": "ba'r"]
  878. // When
  879. session.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).cURLDescription {
  880. components = self.cURLCommandComponents(from: $0)
  881. cURLDescription = $0
  882. expectation.fulfill()
  883. }
  884. waitForExpectations(timeout: timeout)
  885. // Then
  886. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  887. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  888. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: application/json\""))
  889. XCTAssertNotNil(cURLDescription?.range(of: "-d \"{"))
  890. XCTAssertNotNil(cURLDescription?.range(of: "\\\"f'oo\\\":\\\"ba'r\\\""))
  891. XCTAssertNotNil(cURLDescription?.range(of: "\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\""))
  892. XCTAssertNotNil(cURLDescription?.range(of: "\\\"foo\\\":\\\"bar\\"))
  893. XCTAssertEqual(components?.last, "\"\(url)\"")
  894. }
  895. func testPOSTRequestWithCookieCURLDescription() {
  896. // Given
  897. let url = Endpoint.method(.post).url
  898. let cookie = HTTPCookie(properties: [.domain: url.host as Any,
  899. .path: url.path,
  900. .name: "foo",
  901. .value: "bar"])!
  902. let cookieManager = sessionWithCookie(cookie)
  903. let expectation = expectation(description: "request should complete")
  904. var components: [String]?
  905. // When
  906. cookieManager.request(url, method: .post).cURLDescription {
  907. components = self.cURLCommandComponents(from: $0)
  908. expectation.fulfill()
  909. }
  910. waitForExpectations(timeout: timeout)
  911. // Then
  912. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  913. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  914. XCTAssertEqual(components?.last, "\"\(url)\"")
  915. XCTAssertEqual(components?[5..<6], ["-b"])
  916. }
  917. func testPOSTRequestWithCookiesDisabledCURLDescriptionHasNoCookies() {
  918. // Given
  919. let url = Endpoint.method(.post).url
  920. let cookie = HTTPCookie(properties: [.domain: url.host as Any,
  921. .path: url.path,
  922. .name: "foo",
  923. .value: "bar"])!
  924. sessionDisallowingCookies.session.configuration.httpCookieStorage?.setCookie(cookie)
  925. let expectation = expectation(description: "request should complete")
  926. var components: [String]?
  927. // When
  928. sessionDisallowingCookies.request(url, method: .post).cURLDescription {
  929. components = self.cURLCommandComponents(from: $0)
  930. expectation.fulfill()
  931. }
  932. waitForExpectations(timeout: timeout)
  933. // Then
  934. let cookieComponents = components?.filter { $0 == "-b" }
  935. XCTAssertTrue(cookieComponents?.isEmpty == true)
  936. }
  937. func testMultipartFormDataRequestWithDuplicateHeadersCURLDescriptionHasOneContentTypeHeader() {
  938. // Given
  939. let url = Endpoint.method(.post).url
  940. let japaneseData = Data("日本語".utf8)
  941. let expectation = expectation(description: "multipart form data encoding should succeed")
  942. var cURLDescription: String?
  943. var components: [String]?
  944. // When
  945. sessionWithContentTypeHeader.upload(multipartFormData: { data in
  946. data.append(japaneseData, withName: "japanese")
  947. }, to: url).cURLDescription {
  948. components = self.cURLCommandComponents(from: $0)
  949. cURLDescription = $0
  950. expectation.fulfill()
  951. }
  952. waitForExpectations(timeout: timeout)
  953. // Then
  954. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  955. XCTAssertTrue(components?.contains("-X") == true)
  956. XCTAssertEqual(components?.last, "\"\(url)\"")
  957. let contentTypeCount = components?.filter { $0.contains("Content-Type") }.count
  958. XCTAssertEqual(contentTypeCount, 1, "command should contain a single Content-Type header")
  959. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: multipart/form-data;"))
  960. }
  961. func testThatRequestWithInvalidURLDebugDescription() {
  962. // Given
  963. let urlString = "invalid_url"
  964. let expectation = expectation(description: "request should complete")
  965. var cURLDescription: String?
  966. // When
  967. session.request(urlString).cURLDescription {
  968. cURLDescription = $0
  969. expectation.fulfill()
  970. }
  971. waitForExpectations(timeout: timeout)
  972. // Then
  973. XCTAssertNotNil(cURLDescription, "debugDescription should not crash")
  974. }
  975. // MARK: Test Helper Methods
  976. private func cURLCommandComponents(from cURLString: String) -> [String] {
  977. cURLString.components(separatedBy: .whitespacesAndNewlines)
  978. .filter { $0 != "" && $0 != "\\" }
  979. }
  980. }
  981. final class RequestLifetimeTests: BaseTestCase {
  982. func testThatRequestProvidesURLRequestWhenCreated() {
  983. // Given
  984. let didReceiveRequest = expectation(description: "did receive task")
  985. let didComplete = expectation(description: "request did complete")
  986. var request: URLRequest?
  987. // When
  988. AF.request(.default)
  989. .onURLRequestCreation { request = $0; didReceiveRequest.fulfill() }
  990. .responseDecodable(of: TestResponse.self) { _ in didComplete.fulfill() }
  991. wait(for: [didReceiveRequest, didComplete], timeout: timeout, enforceOrder: true)
  992. // Then
  993. XCTAssertNotNil(request)
  994. }
  995. func testThatRequestProvidesTaskWhenCreated() {
  996. // Given
  997. let didReceiveTask = expectation(description: "did receive task")
  998. let didComplete = expectation(description: "request did complete")
  999. var task: URLSessionTask?
  1000. // When
  1001. AF.request(.default)
  1002. .onURLSessionTaskCreation { task = $0; didReceiveTask.fulfill() }
  1003. .responseDecodable(of: TestResponse.self) { _ in didComplete.fulfill() }
  1004. wait(for: [didReceiveTask, didComplete], timeout: timeout, enforceOrder: true)
  1005. // Then
  1006. XCTAssertNotNil(task)
  1007. }
  1008. }
  1009. // MARK: -
  1010. final class RequestInvalidURLTestCase: BaseTestCase {
  1011. func testThatDataRequestWithFileURLThrowsError() {
  1012. // Given
  1013. let fileURL = url(forResource: "valid_data", withExtension: "json")
  1014. let expectation = expectation(description: "Request should succeed.")
  1015. var response: DataResponse<Data?, AFError>?
  1016. // When
  1017. AF.request(fileURL)
  1018. .response { resp in
  1019. response = resp
  1020. expectation.fulfill()
  1021. }
  1022. waitForExpectations(timeout: timeout)
  1023. // Then
  1024. XCTAssertEqual(response?.result.isSuccess, true)
  1025. }
  1026. func testThatDownloadRequestWithFileURLThrowsError() {
  1027. // Given
  1028. let fileURL = url(forResource: "valid_data", withExtension: "json")
  1029. let expectation = expectation(description: "Request should succeed.")
  1030. var response: DownloadResponse<URL?, AFError>?
  1031. // When
  1032. AF.download(fileURL)
  1033. .response { resp in
  1034. response = resp
  1035. expectation.fulfill()
  1036. }
  1037. waitForExpectations(timeout: timeout)
  1038. // Then
  1039. XCTAssertEqual(response?.result.isSuccess, true)
  1040. }
  1041. func testThatDataStreamRequestWithFileURLThrowsError() {
  1042. // Given
  1043. let fileURL = url(forResource: "valid_data", withExtension: "json")
  1044. let expectation = expectation(description: "Request should succeed.")
  1045. var response: DataStreamRequest.Completion?
  1046. // When
  1047. AF.streamRequest(fileURL)
  1048. .responseStream { stream in
  1049. guard case let .complete(completion) = stream.event else { return }
  1050. response = completion
  1051. expectation.fulfill()
  1052. }
  1053. waitForExpectations(timeout: timeout)
  1054. // Then
  1055. XCTAssertNil(response?.response)
  1056. }
  1057. }
  1058. #if canImport(zlib) && swift(>=5.6) // Same condition as `DeflateRequestCompressor`.
  1059. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1060. final class RequestCompressionTests: BaseTestCase {
  1061. func testThatRequestsCanBeCompressed() async {
  1062. // Given
  1063. let url = Endpoint.method(.post).url
  1064. let parameters = TestParameters(property: "compressed")
  1065. // When
  1066. let result = await AF.request(url,
  1067. method: .post,
  1068. parameters: parameters,
  1069. encoder: .json,
  1070. interceptor: .deflateCompressor)
  1071. .serializingDecodable(TestResponse.self)
  1072. .result
  1073. // Then
  1074. XCTAssertTrue(result.isSuccess)
  1075. }
  1076. func testThatDeflateCompressorThrowsErrorByDefaultWhenRequestAlreadyHasHeader() async {
  1077. // Given
  1078. let url = Endpoint.method(.post).url
  1079. let parameters = TestParameters(property: "compressed")
  1080. // When
  1081. let result = await AF.request(url,
  1082. method: .post,
  1083. parameters: parameters,
  1084. encoder: .json,
  1085. headers: [.contentEncoding("value")],
  1086. interceptor: .deflateCompressor)
  1087. .serializingDecodable(TestResponse.self)
  1088. .result
  1089. // Then
  1090. XCTAssertFalse(result.isSuccess)
  1091. XCTAssertNotNil(result.failure?.underlyingError as? DeflateRequestCompressor.DuplicateHeaderError)
  1092. }
  1093. func testThatDeflateCompressorThrowsErrorWhenConfigured() async {
  1094. // Given
  1095. let url = Endpoint.method(.post).url
  1096. let parameters = TestParameters(property: "compressed")
  1097. // When
  1098. let result = await AF.request(url,
  1099. method: .post,
  1100. parameters: parameters,
  1101. encoder: .json,
  1102. headers: [.contentEncoding("value")],
  1103. interceptor: .deflateCompressor(duplicateHeaderBehavior: .error))
  1104. .serializingDecodable(TestResponse.self)
  1105. .result
  1106. // Then
  1107. XCTAssertFalse(result.isSuccess)
  1108. XCTAssertNotNil(result.failure?.underlyingError as? DeflateRequestCompressor.DuplicateHeaderError)
  1109. }
  1110. func testThatDeflateCompressorReplacesHeaderWhenConfigured() async {
  1111. // Given
  1112. let url = Endpoint.method(.post).url
  1113. let parameters = TestParameters(property: "compressed")
  1114. // When
  1115. let result = await AF.request(url,
  1116. method: .post,
  1117. parameters: parameters,
  1118. encoder: .json,
  1119. headers: [.contentEncoding("value")],
  1120. interceptor: .deflateCompressor(duplicateHeaderBehavior: .replace))
  1121. .serializingDecodable(TestResponse.self)
  1122. .result
  1123. // Then
  1124. XCTAssertTrue(result.isSuccess)
  1125. }
  1126. func testThatDeflateCompressorSkipsCompressionWhenConfigured() async {
  1127. // Given
  1128. let url = Endpoint.method(.post).url
  1129. let parameters = TestParameters(property: "compressed")
  1130. // When
  1131. let result = await AF.request(url,
  1132. method: .post,
  1133. parameters: parameters,
  1134. encoder: .json,
  1135. headers: [.contentEncoding("gzip")],
  1136. interceptor: .deflateCompressor(duplicateHeaderBehavior: .skip))
  1137. .serializingDecodable(TestResponse.self)
  1138. .result
  1139. // Then
  1140. // Request fails as the server expects gzip compression.
  1141. XCTAssertFalse(result.isSuccess)
  1142. }
  1143. func testThatDeflateCompressorDoesNotCompressDataWhenClosureReturnsFalse() async {
  1144. // Given
  1145. let url = Endpoint.method(.post).url
  1146. let parameters = TestParameters(property: "compressed")
  1147. // When
  1148. let result = await AF.request(url,
  1149. method: .post,
  1150. parameters: parameters,
  1151. encoder: .json,
  1152. interceptor: .deflateCompressor { _ in false })
  1153. .serializingDecodable(TestResponse.self)
  1154. .result
  1155. // Then
  1156. XCTAssertTrue(result.isSuccess)
  1157. // With no compression, request headers reflected from server should have no Content-Encoding.
  1158. XCTAssertNil(result.success?.headers["Content-Encoding"])
  1159. }
  1160. }
  1161. #endif