| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451 |
- //
- // RequestTests.swift
- //
- // Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/)
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
- import Alamofire
- import Foundation
- import XCTest
- final class RequestResponseTestCase: BaseTestCase {
- func testRequestResponse() {
- // Given
- let url = Endpoint.get.url
- let expectation = expectation(description: "GET request should succeed: \(url)")
- var response: DataResponse<Data?, AFError>?
- // When
- AF.request(url, parameters: ["foo": "bar"])
- .response { resp in
- response = resp
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(response?.request)
- XCTAssertNotNil(response?.response)
- XCTAssertNotNil(response?.data)
- XCTAssertNil(response?.error)
- }
- func testThatDataRequestReceivesInitialResponse() {
- // Given
- let url = Endpoint.get.url
- var initialResponse: HTTPURLResponse?
- let didReceiveResponse = expectation(description: "didReceiveResponse")
- let didComplete = expectation(description: "GET request should succeed: \(url)")
- var response: DataResponse<Data?, AFError>?
- // When
- AF.request(url, parameters: ["foo": "bar"])
- .onHTTPResponse { response in
- initialResponse = response
- didReceiveResponse.fulfill()
- }
- .response { resp in
- response = resp
- didComplete.fulfill()
- }
- wait(for: [didReceiveResponse, didComplete], timeout: timeout, enforceOrder: true)
- // Then
- XCTAssertEqual(initialResponse, response?.response)
- XCTAssertNotNil(response?.request)
- XCTAssertNotNil(response?.response)
- XCTAssertNotNil(response?.data)
- XCTAssertNil(response?.error)
- }
- func testThatDataRequestOnHTTPResponseCanAllow() {
- // Given
- let url = Endpoint.get.url
- var initialResponse: HTTPURLResponse?
- let didReceiveResponse = expectation(description: "didReceiveResponse")
- let didComplete = expectation(description: "GET request should succeed: \(url)")
- var response: DataResponse<Data?, AFError>?
- // When
- AF.request(url, parameters: ["foo": "bar"])
- .onHTTPResponse { response, completionHandler in
- initialResponse = response
- didReceiveResponse.fulfill()
- completionHandler(.allow)
- }
- .response { resp in
- response = resp
- didComplete.fulfill()
- }
- wait(for: [didReceiveResponse, didComplete], timeout: timeout, enforceOrder: true)
- // Then
- XCTAssertEqual(initialResponse, response?.response)
- XCTAssertNotNil(response?.request)
- XCTAssertNotNil(response?.response)
- XCTAssertNotNil(response?.data)
- XCTAssertNil(response?.error)
- }
- func testThatDataRequestOnHTTPResponseCanCancel() {
- // Given
- let url = Endpoint.get.url
- var initialResponse: HTTPURLResponse?
- let didReceiveResponse = expectation(description: "didReceiveResponse")
- let didComplete = expectation(description: "GET request should succeed: \(url)")
- var response: DataResponse<Data?, AFError>?
- // When
- let request = AF.request(url, parameters: ["foo": "bar"])
- .onHTTPResponse { response, completionHandler in
- initialResponse = response
- didReceiveResponse.fulfill()
- completionHandler(.cancel)
- }
- .response { resp in
- response = resp
- didComplete.fulfill()
- }
- wait(for: [didReceiveResponse, didComplete], timeout: timeout, enforceOrder: true)
- // Then
- XCTAssertEqual(initialResponse, response?.response)
- XCTAssertNotNil(response?.request)
- XCTAssertNotNil(response?.response)
- XCTAssertNil(response?.data)
- XCTAssertTrue(request.isCancelled, "onHTTPResponse cancelled request should have isCancelled == true")
- XCTAssertTrue(response?.error?.isExplicitlyCancelledError == true, "onHTTPResponse cancelled request should be explicitly cancelled")
- }
- func testRequestResponseWithProgress() {
- // Given
- let byteCount = 50 * 1024
- let url = Endpoint.bytes(byteCount).url
- let expectation = expectation(description: "Bytes download progress should be reported: \(url)")
- var progressValues: [Double] = []
- var response: DataResponse<Data?, AFError>?
- // When
- AF.request(url)
- .downloadProgress { progress in
- progressValues.append(progress.fractionCompleted)
- }
- .response { resp in
- response = resp
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(response?.request)
- XCTAssertNotNil(response?.response)
- XCTAssertNotNil(response?.data)
- XCTAssertNil(response?.error)
- var previousProgress: Double = progressValues.first ?? 0.0
- for progress in progressValues {
- XCTAssertGreaterThanOrEqual(progress, previousProgress)
- previousProgress = progress
- }
- if let lastProgressValue = progressValues.last {
- XCTAssertEqual(lastProgressValue, 1.0)
- } else {
- XCTFail("last item in progressValues should not be nil")
- }
- }
- func testPOSTRequestWithUnicodeParameters() {
- // Given
- let parameters = ["french": "français",
- "japanese": "日本語",
- "arabic": "العربية",
- "emoji": "😃"]
- let expectation = expectation(description: "request should succeed")
- var response: DataResponse<TestResponse, AFError>?
- // When
- AF.request(.method(.post), parameters: parameters)
- .responseDecodable(of: TestResponse.self) { closureResponse in
- response = closureResponse
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(response?.request)
- XCTAssertNotNil(response?.response)
- XCTAssertNotNil(response?.data)
- if let form = response?.result.success?.form {
- XCTAssertEqual(form["french"], parameters["french"])
- XCTAssertEqual(form["japanese"], parameters["japanese"])
- XCTAssertEqual(form["arabic"], parameters["arabic"])
- XCTAssertEqual(form["emoji"], parameters["emoji"])
- } else {
- XCTFail("form parameter in JSON should not be nil")
- }
- }
- func testPOSTRequestWithBase64EncodedImages() {
- // Given
- let pngBase64EncodedString: String = {
- let fileURL = url(forResource: "unicorn", withExtension: "png")
- let data = try! Data(contentsOf: fileURL)
- return data.base64EncodedString(options: .lineLength64Characters)
- }()
- let jpegBase64EncodedString: String = {
- let fileURL = url(forResource: "rainbow", withExtension: "jpg")
- let data = try! Data(contentsOf: fileURL)
- return data.base64EncodedString(options: .lineLength64Characters)
- }()
- let parameters = ["email": "user@alamofire.org",
- "png_image": pngBase64EncodedString,
- "jpeg_image": jpegBase64EncodedString]
- let expectation = expectation(description: "request should succeed")
- var response: DataResponse<TestResponse, AFError>?
- // When
- AF.request(Endpoint.method(.post), method: .post, parameters: parameters)
- .responseDecodable(of: TestResponse.self) { closureResponse in
- response = closureResponse
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(response?.request)
- XCTAssertNotNil(response?.response)
- XCTAssertNotNil(response?.data)
- XCTAssertEqual(response?.result.isSuccess, true)
- if let form = response?.result.success?.form {
- XCTAssertEqual(form["email"], parameters["email"])
- XCTAssertEqual(form["png_image"], parameters["png_image"])
- XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"])
- } else {
- XCTFail("form parameter in JSON should not be nil")
- }
- }
- // MARK: Queues
- func testThatResponseSerializationWorksWithSerializationQueue() {
- // Given
- let queue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
- let manager = Session(serializationQueue: queue)
- let expectation = expectation(description: "request should complete")
- var response: DataResponse<TestResponse, AFError>?
- // When
- manager.request(.get).responseDecodable(of: TestResponse.self) { resp in
- response = resp
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(response?.result.isSuccess, true)
- }
- func testThatRequestsWorksWithRequestAndSerializationQueues() {
- // Given
- let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue")
- let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
- let manager = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
- let expectation = expectation(description: "request should complete")
- var response: DataResponse<TestResponse, AFError>?
- // When
- manager.request(.get).responseDecodable(of: TestResponse.self) { resp in
- response = resp
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(response?.result.isSuccess, true)
- }
- func testThatRequestsWorksWithConcurrentRequestAndSerializationQueues() {
- // Given
- let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue", attributes: .concurrent)
- let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue", attributes: .concurrent)
- let session = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
- let count = 10
- let expectation = expectation(description: "request should complete")
- expectation.expectedFulfillmentCount = count
- var responses: [DataResponse<TestResponse, AFError>] = []
- // When
- DispatchQueue.concurrentPerform(iterations: count) { _ in
- session.request(.default).responseDecodable(of: TestResponse.self) { resp in
- responses.append(resp)
- expectation.fulfill()
- }
- }
- waitForExpectations(timeout: timeout, handler: nil)
- // Then
- XCTAssertEqual(responses.count, count)
- XCTAssertTrue(responses.allSatisfy(\.result.isSuccess))
- }
- // MARK: Encodable Parameters
- func testThatRequestsCanPassEncodableParametersAsJSONBodyData() {
- // Given
- let parameters = TestParameters(property: "one")
- let expect = expectation(description: "request should complete")
- var receivedResponse: DataResponse<TestResponse, AFError>?
- // When
- AF.request(.method(.post), parameters: parameters, encoder: JSONParameterEncoder.default)
- .responseDecodable(of: TestResponse.self) { response in
- receivedResponse = response
- expect.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(receivedResponse?.result.success?.data, "{\"property\":\"one\"}")
- }
- func testThatRequestsCanPassEncodableParametersAsAURLQuery() {
- // Given
- let parameters = TestParameters(property: "one")
- let expect = expectation(description: "request should complete")
- var receivedResponse: DataResponse<TestResponse, AFError>?
- // When
- AF.request(.method(.get), parameters: parameters)
- .responseDecodable(of: TestResponse.self) { response in
- receivedResponse = response
- expect.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(receivedResponse?.result.success?.args, ["property": "one"])
- }
- func testThatRequestsCanPassEncodableParametersAsURLEncodedBodyData() {
- // Given
- let parameters = TestParameters(property: "one")
- let expect = expectation(description: "request should complete")
- var receivedResponse: DataResponse<TestResponse, AFError>?
- // When
- AF.request(.method(.post), parameters: parameters)
- .responseDecodable(of: TestResponse.self) { response in
- receivedResponse = response
- expect.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(receivedResponse?.result.success?.form, ["property": "one"])
- }
- // MARK: Lifetime Events
- func testThatAutomaticallyResumedRequestReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 4
- eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidResume = { _ in expect.fulfill() }
- eventMonitor.requestDidFinish = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default).response { _ in expect.fulfill() }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .finished)
- }
- func testThatAutomaticallyAndManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 4
- eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidResume = { _ in expect.fulfill() }
- eventMonitor.requestDidFinish = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default).response { _ in expect.fulfill() }
- for _ in 0..<100 {
- request.resume()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .finished)
- }
- func testThatManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 3
- eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidResume = { _ in expect.fulfill() }
- eventMonitor.requestDidFinish = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default)
- for _ in 0..<100 {
- request.resume()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .finished)
- }
- func testThatRequestManuallyResumedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 4
- eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidResume = { _ in expect.fulfill() }
- eventMonitor.requestDidFinish = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default).response { _ in expect.fulfill() }
- for _ in 0..<100 {
- request.resume()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .finished)
- }
- func testThatRequestManuallySuspendedManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 2
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default)
- for _ in 0..<100 {
- request.suspend()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .suspended)
- }
- func testThatRequestManuallySuspendedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 2
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidResume = { _ in expect.fulfill() }
- eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default)
- for _ in 0..<100 {
- request.suspend()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .suspended)
- }
- func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 2
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default)
- // Cancellation stops task creation, so don't cancel the request until the task has been created.
- eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
- for _ in 0..<100 {
- request.cancel()
- }
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .cancelled)
- }
- func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 2
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidResume = { _ in expect.fulfill() }
- eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.default)
- // Cancellation stops task creation, so don't cancel the request until the task has been created.
- eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
- for _ in 0..<100 {
- request.cancel()
- }
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .cancelled)
- }
- func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(eventMonitors: [eventMonitor])
- let expect = expectation(description: "request should receive appropriate lifetime events")
- expect.expectedFulfillmentCount = 6
- eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
- eventMonitor.requestDidCancel = { _ in expect.fulfill() }
- eventMonitor.requestDidResume = { _ in expect.fulfill() }
- eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
- // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
- eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
- eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
- // When
- let request = session.request(.delay(5)).response { _ in expect.fulfill() }
- // Cancellation stops task creation, so don't cancel the request until the task has been created.
- eventMonitor.requestDidCreateTask = { [unowned request] _, _ in
- DispatchQueue.concurrentPerform(iterations: 100) { i in
- request.cancel()
- if i == 99 { expect.fulfill() }
- }
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .cancelled)
- }
- func testThatRequestTriggersAllAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(eventMonitors: [eventMonitor])
- // Disable event test until Firewalk support HTTPS.
- // let didReceiveChallenge = expectation(description: "didReceiveChallenge should fire")
- let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
- let didReceiveData = expectation(description: "didReceiveData should fire")
- let willCacheResponse = expectation(description: "willCacheResponse should fire")
- let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
- let didCreateTask = expectation(description: "didCreateTask should fire")
- let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
- let didComplete = expectation(description: "didComplete should fire")
- let didFinish = expectation(description: "didFinish should fire")
- let didResume = expectation(description: "didResume should fire")
- let didResumeTask = expectation(description: "didResumeTask should fire")
- let didParseResponse = expectation(description: "didParseResponse should fire")
- let responseHandler = expectation(description: "responseHandler should fire")
- var dataReceived = false
- // Disable event test until Firewalk supports HTTPS.
- // eventMonitor.taskDidReceiveChallenge = { _, _, _ in didReceiveChallenge.fulfill() }
- eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
- eventMonitor.dataTaskDidReceiveData = { _, _, _ in
- guard !dataReceived else { return }
- // Data may be received many times, fulfill only once.
- dataReceived = true
- didReceiveData.fulfill()
- }
- eventMonitor.dataTaskWillCacheResponse = { _, _, _ in willCacheResponse.fulfill() }
- eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
- eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
- eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
- eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
- eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
- eventMonitor.requestDidResume = { _ in didResume.fulfill() }
- eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
- eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
- // When
- let request = session.request(.default).response { _ in
- responseHandler.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .finished)
- }
- func testThatCancelledRequestTriggersAllAppropriateLifetimeEvents() {
- // Given
- let eventMonitor = ClosureEventMonitor()
- let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
- let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
- let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
- let didCreateTask = expectation(description: "didCreateTask should fire")
- let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
- let didComplete = expectation(description: "didComplete should fire")
- let didFinish = expectation(description: "didFinish should fire")
- let didResume = expectation(description: "didResume should fire")
- let didResumeTask = expectation(description: "didResumeTask should fire")
- let didParseResponse = expectation(description: "didParseResponse should fire")
- let didCancel = expectation(description: "didCancel should fire")
- let didCancelTask = expectation(description: "didCancelTask should fire")
- let responseHandler = expectation(description: "responseHandler should fire")
- eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
- eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
- eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
- eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
- eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
- eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
- eventMonitor.requestDidResume = { _ in didResume.fulfill() }
- eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
- eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
- eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
- // When
- let request = session.request(.delay(5)).response { _ in
- responseHandler.fulfill()
- }
- eventMonitor.requestDidResumeTask = { [unowned request] _, _ in
- request.cancel()
- didResumeTask.fulfill()
- }
- request.resume()
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.state, .cancelled)
- }
- func testThatAppendingResponseSerializerToCancelledRequestCallsCompletion() {
- // Given
- let session = Session()
- var response1: DataResponse<TestResponse, AFError>?
- var response2: DataResponse<TestResponse, AFError>?
- let expect = expectation(description: "both response serializer completions should be called")
- expect.expectedFulfillmentCount = 2
- // When
- let request = session.request(.default)
- request.responseDecodable(of: TestResponse.self) { resp in
- response1 = resp
- expect.fulfill()
- request.responseDecodable(of: TestResponse.self) { resp in
- response2 = resp
- expect.fulfill()
- }
- }
- request.cancel()
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(response1?.error?.isExplicitlyCancelledError, true)
- XCTAssertEqual(response2?.error?.isExplicitlyCancelledError, true)
- }
- func testThatAppendingResponseSerializerToCompletedRequestInsideCompletionResumesRequest() {
- // Given
- let session = Session()
- var response1: DataResponse<TestResponse, AFError>?
- var response2: DataResponse<TestResponse, AFError>?
- var response3: DataResponse<TestResponse, AFError>?
- let expect = expectation(description: "all response serializer completions should be called")
- expect.expectedFulfillmentCount = 3
- // When
- let request = session.request(.default)
- request.responseDecodable(of: TestResponse.self) { resp in
- response1 = resp
- expect.fulfill()
- request.responseDecodable(of: TestResponse.self) { resp in
- response2 = resp
- expect.fulfill()
- request.responseDecodable(of: TestResponse.self) { resp in
- response3 = resp
- expect.fulfill()
- }
- }
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(response1?.value)
- XCTAssertNotNil(response2?.value)
- XCTAssertNotNil(response3?.value)
- }
- func testThatAppendingResponseSerializerToCompletedRequestOutsideCompletionResumesRequest() {
- // Given
- let session = Session()
- let request = session.request(.default)
- var response1: DataResponse<TestResponse, AFError>?
- var response2: DataResponse<TestResponse, AFError>?
- var response3: DataResponse<TestResponse, AFError>?
- // When
- let expect1 = expectation(description: "response serializer 1 completion should be called")
- request.responseDecodable(of: TestResponse.self) { response1 = $0; expect1.fulfill() }
- waitForExpectations(timeout: timeout)
- let expect2 = expectation(description: "response serializer 2 completion should be called")
- request.responseDecodable(of: TestResponse.self) { response2 = $0; expect2.fulfill() }
- waitForExpectations(timeout: timeout)
- let expect3 = expectation(description: "response serializer 3 completion should be called")
- request.responseDecodable(of: TestResponse.self) { response3 = $0; expect3.fulfill() }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(response1?.value)
- XCTAssertNotNil(response2?.value)
- XCTAssertNotNil(response3?.value)
- }
- }
- // MARK: -
- final class RequestDescriptionTestCase: BaseTestCase {
- func testRequestDescription() {
- // Given
- let url = Endpoint().url
- let manager = Session(startRequestsImmediately: false)
- let request = manager.request(url)
- let expectation = expectation(description: "Request description should update: \(url)")
- var response: HTTPURLResponse?
- // When
- request.response { resp in
- response = resp.response
- expectation.fulfill()
- }.resume()
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(request.description, "GET \(url) (\(response?.statusCode ?? -1))")
- }
- }
- // MARK: -
- final class RequestCURLDescriptionTestCase: BaseTestCase {
- // MARK: Properties
- let session: Session = {
- let manager = Session()
- return manager
- }()
- let sessionWithAcceptLanguageHeader: Session = {
- var headers = HTTPHeaders.default
- headers["Accept-Language"] = "en-US"
- let configuration = URLSessionConfiguration.af.default
- configuration.headers = headers
- let manager = Session(configuration: configuration)
- return manager
- }()
- let sessionWithContentTypeHeader: Session = {
- var headers = HTTPHeaders.default
- headers["Content-Type"] = "application/json"
- let configuration = URLSessionConfiguration.af.default
- configuration.headers = headers
- let manager = Session(configuration: configuration)
- return manager
- }()
- func sessionWithCookie(_ cookie: HTTPCookie) -> Session {
- let configuration = URLSessionConfiguration.af.default
- configuration.httpCookieStorage?.setCookie(cookie)
- return Session(configuration: configuration)
- }
- let sessionDisallowingCookies: Session = {
- let configuration = URLSessionConfiguration.af.default
- configuration.httpShouldSetCookies = false
- let manager = Session(configuration: configuration)
- return manager
- }()
- // MARK: Tests
- func testGETRequestCURLDescription() {
- // Given
- let url = Endpoint().url
- let expectation = expectation(description: "request should complete")
- var components: [String]?
- // When
- session.request(url).cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertTrue(components?.contains("-X") == true)
- XCTAssertEqual(components?.last, "\"\(url)\"")
- }
- func testGETRequestCURLDescriptionOnMainQueue() {
- // Given
- let url = Endpoint().url
- let expectation = expectation(description: "request should complete")
- var isMainThread = false
- var components: [String]?
- // When
- session.request(url).cURLDescription(on: .main) {
- components = self.cURLCommandComponents(from: $0)
- isMainThread = Thread.isMainThread
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout, handler: nil)
- // Then
- XCTAssertTrue(isMainThread)
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertTrue(components?.contains("-X") == true)
- XCTAssertEqual(components?.last, "\"\(url)\"")
- }
- func testGETRequestCURLDescriptionSynchronous() {
- // Given
- let url = Endpoint().url
- let expectation = expectation(description: "request should complete")
- var components: [String]?
- var syncComponents: [String]?
- // When
- let request = session.request(url)
- request.cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- syncComponents = self.cURLCommandComponents(from: request.cURLDescription())
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertTrue(components?.contains("-X") == true)
- XCTAssertEqual(components?.last, "\"\(url)\"")
- XCTAssertEqual(components?.sorted(), syncComponents?.sorted())
- }
- func testGETRequestCURLDescriptionCanBeRequestedManyTimes() {
- // Given
- let url = Endpoint().url
- let expectation = expectation(description: "request should complete")
- var components: [String]?
- var secondComponents: [String]?
- // When
- let request = session.request(url)
- request.cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- request.cURLDescription {
- secondComponents = self.cURLCommandComponents(from: $0)
- expectation.fulfill()
- }
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertTrue(components?.contains("-X") == true)
- XCTAssertEqual(components?.last, "\"\(url)\"")
- XCTAssertEqual(components?.sorted(), secondComponents?.sorted())
- }
- func testGETRequestWithCustomHeaderCURLDescription() {
- // Given
- let url = Endpoint().url
- let expectation = expectation(description: "request should complete")
- var cURLDescription: String?
- // When
- let headers: HTTPHeaders = ["X-Custom-Header": "{\"key\": \"value\"}"]
- session.request(url, headers: headers).cURLDescription {
- cURLDescription = $0
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(cURLDescription?.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\""))
- }
- func testGETRequestWithDuplicateHeadersDebugDescription() {
- // Given
- let url = Endpoint().url
- let expectation = expectation(description: "request should complete")
- var cURLDescription: String?
- var components: [String]?
- // When
- let headers: HTTPHeaders = ["Accept-Language": "en-GB"]
- sessionWithAcceptLanguageHeader.request(url, headers: headers).cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- cURLDescription = $0
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertTrue(components?.contains("-X") == true)
- XCTAssertEqual(components?.last, "\"\(url)\"")
- let acceptLanguageCount = components?.filter { $0.contains("Accept-Language") }.count
- XCTAssertEqual(acceptLanguageCount, 1, "command should contain a single Accept-Language header")
- XCTAssertNotNil(cURLDescription?.range(of: "-H \"Accept-Language: en-GB\""))
- }
- func testPOSTRequestCURLDescription() {
- // Given
- let url = Endpoint.method(.post).url
- let expectation = expectation(description: "request should complete")
- var components: [String]?
- // When
- session.request(url, method: .post).cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertEqual(components?[3..<5], ["-X", "POST"])
- XCTAssertEqual(components?.last, "\"\(url)\"")
- }
- func testPOSTRequestWithJSONParametersCURLDescription() {
- // Given
- let url = Endpoint.method(.post).url
- let expectation = expectation(description: "request should complete")
- var cURLDescription: String?
- var components: [String]?
- let parameters = ["foo": "bar",
- "fo\"o": "b\"ar",
- "f'oo": "ba'r"]
- // When
- session.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- cURLDescription = $0
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertEqual(components?[3..<5], ["-X", "POST"])
- XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: application/json\""))
- XCTAssertNotNil(cURLDescription?.range(of: "-d \"{"))
- XCTAssertNotNil(cURLDescription?.range(of: "\\\"f'oo\\\":\\\"ba'r\\\""))
- XCTAssertNotNil(cURLDescription?.range(of: "\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\""))
- XCTAssertNotNil(cURLDescription?.range(of: "\\\"foo\\\":\\\"bar\\"))
- XCTAssertEqual(components?.last, "\"\(url)\"")
- }
- func testPOSTRequestWithCookieCURLDescription() {
- // Given
- let url = Endpoint.method(.post).url
- let cookie = HTTPCookie(properties: [.domain: url.host as Any,
- .path: url.path,
- .name: "foo",
- .value: "bar"])!
- let cookieManager = sessionWithCookie(cookie)
- let expectation = expectation(description: "request should complete")
- var components: [String]?
- // When
- cookieManager.request(url, method: .post).cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertEqual(components?[3..<5], ["-X", "POST"])
- XCTAssertEqual(components?.last, "\"\(url)\"")
- XCTAssertEqual(components?[5..<6], ["-b"])
- }
- func testPOSTRequestWithCookiesDisabledCURLDescriptionHasNoCookies() {
- // Given
- let url = Endpoint.method(.post).url
- let cookie = HTTPCookie(properties: [.domain: url.host as Any,
- .path: url.path,
- .name: "foo",
- .value: "bar"])!
- sessionDisallowingCookies.session.configuration.httpCookieStorage?.setCookie(cookie)
- let expectation = expectation(description: "request should complete")
- var components: [String]?
- // When
- sessionDisallowingCookies.request(url, method: .post).cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- let cookieComponents = components?.filter { $0 == "-b" }
- XCTAssertTrue(cookieComponents?.isEmpty == true)
- }
- func testMultipartFormDataRequestWithDuplicateHeadersCURLDescriptionHasOneContentTypeHeader() {
- // Given
- let url = Endpoint.method(.post).url
- let japaneseData = Data("日本語".utf8)
- let expectation = expectation(description: "multipart form data encoding should succeed")
- var cURLDescription: String?
- var components: [String]?
- // When
- sessionWithContentTypeHeader.upload(multipartFormData: { data in
- data.append(japaneseData, withName: "japanese")
- }, to: url).cURLDescription {
- components = self.cURLCommandComponents(from: $0)
- cURLDescription = $0
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
- XCTAssertTrue(components?.contains("-X") == true)
- XCTAssertEqual(components?.last, "\"\(url)\"")
- let contentTypeCount = components?.filter { $0.contains("Content-Type") }.count
- XCTAssertEqual(contentTypeCount, 1, "command should contain a single Content-Type header")
- XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: multipart/form-data;"))
- }
- func testThatRequestWithInvalidURLDebugDescription() {
- // Given
- let urlString = "invalid_url"
- let expectation = expectation(description: "request should complete")
- var cURLDescription: String?
- // When
- session.request(urlString).cURLDescription {
- cURLDescription = $0
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNotNil(cURLDescription, "debugDescription should not crash")
- }
- // MARK: Test Helper Methods
- private func cURLCommandComponents(from cURLString: String) -> [String] {
- cURLString.components(separatedBy: .whitespacesAndNewlines)
- .filter { $0 != "" && $0 != "\\" }
- }
- }
- final class RequestLifetimeTests: BaseTestCase {
- func testThatRequestProvidesURLRequestWhenCreated() {
- // Given
- let didReceiveRequest = expectation(description: "did receive task")
- let didComplete = expectation(description: "request did complete")
- var request: URLRequest?
- // When
- AF.request(.default)
- .onURLRequestCreation { request = $0; didReceiveRequest.fulfill() }
- .responseDecodable(of: TestResponse.self) { _ in didComplete.fulfill() }
- wait(for: [didReceiveRequest, didComplete], timeout: timeout, enforceOrder: true)
- // Then
- XCTAssertNotNil(request)
- }
- func testThatRequestProvidesTaskWhenCreated() {
- // Given
- let didReceiveTask = expectation(description: "did receive task")
- let didComplete = expectation(description: "request did complete")
- var task: URLSessionTask?
- // When
- AF.request(.default)
- .onURLSessionTaskCreation { task = $0; didReceiveTask.fulfill() }
- .responseDecodable(of: TestResponse.self) { _ in didComplete.fulfill() }
- wait(for: [didReceiveTask, didComplete], timeout: timeout, enforceOrder: true)
- // Then
- XCTAssertNotNil(task)
- }
- }
- // MARK: -
- final class RequestInvalidURLTestCase: BaseTestCase {
- func testThatDataRequestWithFileURLThrowsError() {
- // Given
- let fileURL = url(forResource: "valid_data", withExtension: "json")
- let expectation = expectation(description: "Request should succeed.")
- var response: DataResponse<Data?, AFError>?
- // When
- AF.request(fileURL)
- .response { resp in
- response = resp
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(response?.result.isSuccess, true)
- }
- func testThatDownloadRequestWithFileURLThrowsError() {
- // Given
- let fileURL = url(forResource: "valid_data", withExtension: "json")
- let expectation = expectation(description: "Request should succeed.")
- var response: DownloadResponse<URL?, AFError>?
- // When
- AF.download(fileURL)
- .response { resp in
- response = resp
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertEqual(response?.result.isSuccess, true)
- }
- func testThatDataStreamRequestWithFileURLThrowsError() {
- // Given
- let fileURL = url(forResource: "valid_data", withExtension: "json")
- let expectation = expectation(description: "Request should succeed.")
- var response: DataStreamRequest.Completion?
- // When
- AF.streamRequest(fileURL)
- .responseStream { stream in
- guard case let .complete(completion) = stream.event else { return }
- response = completion
- expectation.fulfill()
- }
- waitForExpectations(timeout: timeout)
- // Then
- XCTAssertNil(response?.response)
- }
- }
- #if canImport(zlib) // Same condition as `DeflateRequestCompressor`.
- @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
- final class RequestCompressionTests: BaseTestCase {
- func testThatRequestsCanBeCompressed() async {
- // Given
- let url = Endpoint.method(.post).url
- let parameters = TestParameters(property: "compressed")
- // When
- let result = await AF.request(url,
- method: .post,
- parameters: parameters,
- encoder: .json,
- interceptor: .deflateCompressor)
- .serializingDecodable(TestResponse.self)
- .result
- // Then
- XCTAssertTrue(result.isSuccess)
- }
- func testThatDeflateCompressorThrowsErrorByDefaultWhenRequestAlreadyHasHeader() async {
- // Given
- let url = Endpoint.method(.post).url
- let parameters = TestParameters(property: "compressed")
- // When
- let result = await AF.request(url,
- method: .post,
- parameters: parameters,
- encoder: .json,
- headers: [.contentEncoding("value")],
- interceptor: .deflateCompressor)
- .serializingDecodable(TestResponse.self)
- .result
- // Then
- XCTAssertFalse(result.isSuccess)
- XCTAssertNotNil(result.failure?.underlyingError as? DeflateRequestCompressor.DuplicateHeaderError)
- }
- func testThatDeflateCompressorThrowsErrorWhenConfigured() async {
- // Given
- let url = Endpoint.method(.post).url
- let parameters = TestParameters(property: "compressed")
- // When
- let result = await AF.request(url,
- method: .post,
- parameters: parameters,
- encoder: .json,
- headers: [.contentEncoding("value")],
- interceptor: .deflateCompressor(duplicateHeaderBehavior: .error))
- .serializingDecodable(TestResponse.self)
- .result
- // Then
- XCTAssertFalse(result.isSuccess)
- XCTAssertNotNil(result.failure?.underlyingError as? DeflateRequestCompressor.DuplicateHeaderError)
- }
- func testThatDeflateCompressorReplacesHeaderWhenConfigured() async {
- // Given
- let url = Endpoint.method(.post).url
- let parameters = TestParameters(property: "compressed")
- // When
- let result = await AF.request(url,
- method: .post,
- parameters: parameters,
- encoder: .json,
- headers: [.contentEncoding("value")],
- interceptor: .deflateCompressor(duplicateHeaderBehavior: .replace))
- .serializingDecodable(TestResponse.self)
- .result
- // Then
- XCTAssertTrue(result.isSuccess)
- }
- func testThatDeflateCompressorSkipsCompressionWhenConfigured() async {
- // Given
- let url = Endpoint.method(.post).url
- let parameters = TestParameters(property: "compressed")
- // When
- let result = await AF.request(url,
- method: .post,
- parameters: parameters,
- encoder: .json,
- headers: [.contentEncoding("gzip")],
- interceptor: .deflateCompressor(duplicateHeaderBehavior: .skip))
- .serializingDecodable(TestResponse.self)
- .result
- // Then
- // Request fails as the server expects gzip compression.
- XCTAssertFalse(result.isSuccess)
- }
- func testThatDeflateCompressorDoesNotCompressDataWhenClosureReturnsFalse() async {
- // Given
- let url = Endpoint.method(.post).url
- let parameters = TestParameters(property: "compressed")
- // When
- let result = await AF.request(url,
- method: .post,
- parameters: parameters,
- encoder: .json,
- interceptor: .deflateCompressor { _ in false })
- .serializingDecodable(TestResponse.self)
- .result
- // Then
- XCTAssertTrue(result.isSuccess)
- // With no compression, request headers reflected from server should have no Content-Encoding.
- XCTAssertNil(result.success?.headers["Content-Encoding"])
- }
- }
- #endif
|