2
0

RequestTests.swift 51 KB

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