Best Fuel code snippet using com.github.kittinunf.fuel.core.Client.executeRequest
FuelExtensionsTest.kt
Source:FuelExtensionsTest.kt
...34 }35 @Test36 fun `responseStringWithRetries returns final response when succeeding within retry count`() {37 val client = mock<Client>()38 `when`(client.executeRequest(any()))39 .thenReturn(basicRetryResponse)40 .thenReturn(41 Response(42 statusCode = 200,43 url = URL("https://example.com"),44 body = DefaultBody.from({ ByteArrayInputStream("final".toByteArray()) }, null)45 )46 )47 FuelManager.instance.client = client48 val (_, response, result) = Fuel.get("https://example.com")49 .responseStringWithRetries(1, 1L)50 assertEquals(200, response.statusCode)51 assertEquals("final", result.get())52 }53 @Test54 fun `responseStringWithRetries returns the last response when a non-throttle response is not received within retry count`() {55 val client = mock<Client>()56 `when`(client.executeRequest(any()))57 .thenReturn(basicRetryResponse)58 .thenReturn(basicRetryResponse)59 .thenReturn(basicRetryResponse) // One more than retry count60 .thenReturn(Response(statusCode = 200, url = URL("https://example.com")))61 FuelManager.instance.client = client62 val (_, response, result) = Fuel.get("https://example.com")63 .responseStringWithRetries(2, 1L) // Would have to be 3 to succeed64 assertEquals(429, response.statusCode) // Status code of last response65 assertTrue(result is Result.Failure)66 }67 @Test68 fun `responseStringWithRetries throws when an invalid Retry-After header is received`() {69 val client = mock<Client>()70 `when`(client.executeRequest(any())).thenReturn(createRetryResponse("INVALID VALUE"))71 FuelManager.instance.client = client72 assertThrows<NumberFormatException> {73 Fuel.get("https://example.com").responseStringWithRetries(1, 1L) // Would have to be 2 to succeed74 }75 }76 @Test77 fun `responseStringWithRetries throws when no Retry-After header is received in HTTP 429 response`() {78 val client = mock<Client>()79 `when`(client.executeRequest(any())).thenReturn(createRetryResponse("", Headers())) // No Retry-After header80 FuelManager.instance.client = client81 assertThrows<IllegalStateException> {82 Fuel.get("https://example.com").responseStringWithRetries(1)83 }84 }85 @Test86 fun `responseStringWithRetries returns non-throttled error by default`() {87 val client = mock<Client>()88 `when`(client.executeRequest(any())).thenReturn(89 Response(90 statusCode = 400,91 url = URL("https://example.com"),92 body = DefaultBody.from({ ByteArrayInputStream("unhandled error".toByteArray()) }, null)93 )94 )95 FuelManager.instance.client = client96 val (_, response, _) = Fuel.get("https://example.com").responseStringWithRetries(1)97 assertEquals(400, response.statusCode)98 assertEquals("unhandled error", response.body().asString("text/html"))99 }100 @Test101 fun `responseStringWithRetries returns fallback error handler's response when faced with a non-throttled error response`() {102 val client = mock<Client>()103 `when`(client.executeRequest(any())).thenReturn(104 Response(105 statusCode = 400,106 url = URL("https://example.com"),107 body = DefaultBody.from({ ByteArrayInputStream("unhandled error".toByteArray()) }, null)108 )109 )110 FuelManager.instance.client = client111 val (_, response, _) = Fuel.get("https://example.com").responseStringWithRetries(1) { r, _ ->112 ResponseResultOf(113 r.first,114 Response(115 statusCode = 400,116 url = URL("https://example.com"),117 body = DefaultBody.from({ ByteArrayInputStream("handled error".toByteArray()) }, null)...
ProfilePictureRuleTest.kt
Source:ProfilePictureRuleTest.kt
...18 val testUser = SlackTestUsers.testBot(userProfile)19 val rule = ProfilePictureRule(setOf("TEST_DEFAULT_HASH"))20 val inputStream = getResource("/empty.jpg")21 val client = mock<Client> {22 onGeneric { executeRequest(any()) } doReturn Response(23 statusCode = 200,24 responseMessage = "ok",25 dataStream = inputStream,26 url = URL(testUrl)27 )28 }29 FuelManager.instance.client = client30 val result = rule.checkProfile(testUser)31 assertTrue(result.result)32 }33 @Test34 fun `should return false for redirected default picture`() {35 val testUrl = "https://secure.gravatar.com/TEST_URL"36 val redirectedUrl = "https://DEFAULT_URL"37 val userProfile = SlackTestProfiles.botProfile().copy(image_24 = testUrl)38 val testUser = SlackTestUsers.testBot(userProfile)39 val rule = ProfilePictureRule(setOf("TEST_DEFAULT_HASH"))40 val inputStream = getResource("/empty.jpg")41 val client = mock<Client> {42 onGeneric { executeRequest(any()) } doReturn Response(43 statusCode = 200,44 responseMessage = "ok",45 dataStream = inputStream,46 url = URL(redirectedUrl)47 )48 }49 FuelManager.instance.client = client50 val result = rule.checkProfile(testUser)51 assertFalse(result.result)52 }53 @Test54 fun `should return false for non user-uploaded picture`() {55 val testUrl = "https://secure.gravatar.com/TEST_URL"56 val userProfile = SlackTestProfiles.botProfile().copy(image_24 = testUrl)57 val testUser = SlackTestUsers.testBot(userProfile)58 val rule = ProfilePictureRule(setOf("0e9c7b8f33e92621323f0a2f4892ff7c"))59 val inputStream = getResource("/empty.jpg")60 val client = mock<Client> {61 onGeneric { executeRequest(any()) } doReturn Response(62 statusCode = 200,63 responseMessage = "ok",64 dataStream = inputStream,65 url = URL(testUrl)66 )67 }68 FuelManager.instance.client = client69 val result = rule.checkProfile(testUser)70 assertFalse(result.result)71 }72 @Test73 fun `should return false for missing picture`() {74 val userProfile = SlackTestProfiles.botProfile().copy(image_24 = null)75 val testUser = SlackTestUsers.testBot(userProfile)76 val rule = ProfilePictureRule(setOf("TEST_HASH"))77 val result = rule.checkProfile(testUser)78 assertFalse(result.result)79 }80 @Test81 fun `should return false for error picture`() {82 val testUrl = "https://secure.gravatar.com/TEST_URL"83 val userProfile = SlackTestProfiles.botProfile().copy(image_24 = testUrl)84 val testUser = SlackTestUsers.testBot(userProfile)85 val rule = ProfilePictureRule(setOf("TEST_DEFAULT_HASH"))86 val inputStream = getResource("/empty.jpg")87 val client = mock<Client> {88 onGeneric { executeRequest(any()) } doReturn Response(89 statusCode = 404,90 responseMessage = "not found",91 dataStream = inputStream,92 url = URL(testUrl)93 )94 }95 FuelManager.instance.client = client96 val thrown = assertThrows(Exception::class.java,97 { rule.checkProfile(testUser) },98 "Expected rule.checkProfile(testUser) to throw, but it didn't")99 val expectedMessageThrown = thrown.message!!.contains("Unable to retrieve Profile Picture for user TEST_BOT_USER - https://secure.gravatar.com/TEST_URL {com.github.kittinunf.fuel.core.HttpException: HTTP Exception 404 not found}")100 assertTrue(expectedMessageThrown)101 }102 private fun getResource(resource: String) = javaClass.getResourceAsStream(resource)...
RequestTask.kt
Source:RequestTask.kt
...14 private val executor by lazy { request.executionOptions }15 private val client by lazy { executor.client }16 private fun prepareRequest(request: Request): Request = executor.requestTransformer(request)17 @Throws(FuelError::class)18 private fun executeRequest(request: Request): RequestTaskResult {19 return runCatching { Pair(request, client.executeRequest(request)) }20 .recover { error -> throw FuelError.wrap(error, Response(request.url)) }21 .getOrThrow()22 }23 @Throws(FuelError::class)24 private fun prepareResponse(result: RequestTaskResult): Response {25 val (request, response) = result26 return runCatching { executor.responseTransformer(request, response) }27 .mapCatching { transformedResponse ->28 val valid = executor.responseValidator(transformedResponse)29 if (valid) transformedResponse30 else throw FuelError.wrap(HttpException(transformedResponse.statusCode, transformedResponse.responseMessage), transformedResponse)31 }32 .recover { error -> throw FuelError.wrap(error, response) }33 .getOrThrow()34 }35 @Throws(FuelError::class)36 override fun call(): Response {37 return runCatching { prepareRequest(request) }38 .mapCatching { executeRequest(it) }39 .mapCatching { pair ->40 // Nested runCatching so response can be rebound41 runCatching { prepareResponse(pair) }42 .recover { error ->43 error.also { Fuel.trace { "[RequestTask] execution error\n\r\t$error" } }44 throw FuelError.wrap(error, pair.second)45 }46 .getOrThrow()47 }48 .onFailure { error ->49 Fuel.trace { "[RequestTask] on failure (interrupted=${(error as? FuelError)?.causedByInterruption ?: error})" }50 if (error is FuelError && error.causedByInterruption) {51 Fuel.trace { "[RequestTask] execution error\n\r\t$error" }52 interruptCallback.invoke(request)...
LibraryTest.kt
Source:LibraryTest.kt
...23 @Test24 fun testLog() {25 val classUnderTest = Library()26 val client = mock<Client> {27 onGeneric { executeRequest(any()) } doReturn Response(28 statusCode = 200,29 responseMessage = "ok",30 url = URL("https://httpbin.org/post")31 )32 }33 FuelManager.instance.client = client34 assertTrue("Initial Requests should be empty", classUnderTest.requests.isEmpty())35 classUnderTest.log(36 LocationEvent(0F, 0F, System.currentTimeMillis() / 1000L, "empty"),37 false38 )39 assertTrue("Requests should not be empty", classUnderTest.requests.isNotEmpty())40 classUnderTest.process {41 assertTrue("Requests should be completed", classUnderTest.requests.isEmpty())42 }43 }44 @Test45 fun testFailedRequestsAreRetried() {46 val classUnderTest = Library()47 // mock failed response48 var client = mock<Client> {49 onGeneric { executeRequest(any()) } doReturn Response(50 statusCode = -1,51 responseMessage = "bad",52 url = URL("https://httpbin.org/post")53 )54 }55 FuelManager.instance.client = client56 assertTrue("Initial Requests should be empty", classUnderTest.requests.isEmpty())57 classUnderTest.log(58 LocationEvent(0F, 0F, System.currentTimeMillis() / 1000L, "empty"),59 false60 )61 classUnderTest.process {62 assertTrue("Request should fail", classUnderTest.requests.isNotEmpty())63 }64 // mock success response65 client = mock {66 onGeneric { executeRequest(any()) } doReturn Response(67 statusCode = 200,68 responseMessage = "ok",69 url = URL("https://httpbin.org/post")70 )71 }72 FuelManager.instance.client = client73 // process failed requests74 classUnderTest.process {75 assertTrue("Requests should be completed", classUnderTest.requests.isEmpty())76 }77 }78}...
ViaCepConsumerTest.kt
Source:ViaCepConsumerTest.kt
...22 FuelManager.instance.client = clientMock23 }24 describe("ViaCepConsumer.getAddress(cep: String): AddressConvertable") {25 it("should return an address from ViaCep.com.br") {26 every { clientMock.executeRequest(any()).statusCode } returns OK_20027 every { clientMock.executeRequest(any()).responseMessage } returns "OK"28 every { clientMock.executeRequest(any()).data } returns "viacep-payload.json".payload().toByteArray()29 val result = consumer.getAddress(cep)30 assertThat(result).isNotNull31 assertThat(result.toDomain().cep).isEqualTo(cep)32 }33 it("should return an exception when fetching an address") {34 every { clientMock.executeRequest(any()).statusCode } returns BAD_REQUEST_40035 every { clientMock.executeRequest(any()).responseMessage } returns "BAD_REQUEST"36 every {37 clientMock.executeRequest(any()).data38 } returns "viacep-bad-request-payload.html".payload().toByteArray()39 assertThatThrownBy {40 consumer.getAddress(cep)41 }.isInstanceOf(APIException::class.java)42 .hasMessage("<h3>ViaCEP Bad Request (400)</h3>")43 }44 }45 }46})...
MockTestHelper.kt
Source:MockTestHelper.kt
...26 json: String = "",27 headers: List<Pair<String,String>> = emptyList()): CapturingSlot<Request> {28 val slot = slot<Request>()29 val client = mockk<Client>()30 every { client.executeRequest(capture(slot)).statusCode } returns statusCode31 every { client.executeRequest(capture(slot)).responseMessage } returns message32 every { client.executeRequest(capture(slot)).data } returns json.toByteArray()33 every { client.executeRequest(capture(slot)).dataStream } returns json.toByteArray().inputStream()34 every { client.executeRequest(capture(slot)).headers } returns headers.associateBy({it.first},{ listOf(it.second)})35 FuelManager.instance.client = client36 return slot37}...
ToggleApiClientTest.kt
Source:ToggleApiClientTest.kt
...11 "{\"name\":\"propJoselito\",\"type\":\"release\",\"value\":true}]}"12 @BeforeEach13 fun setup() {14 val client = mockk<Client>()15 every { client.executeRequest(any()).statusCode } returns 20016 every { client.executeRequest(any()).responseMessage } returns "OK"17 every { client.executeRequest(any()).data } returns someJson.toByteArray()18 FuelManager.instance.client = client19 }20 @Test21 fun testApiClientReturnOk() {22 sut.getToggles(ToggleApiClient.baseUrl)23 }24}
PdlConsumerExplore.kt
Source:PdlConsumerExplore.kt
...4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6fun main() {7 FuelManager.instance.client = object : Client {8 override fun executeRequest(request: Request): Response {9 println(String(request.body.toByteArray()))10 return Response.error()11 }12 }13 val pdl = PdlConsumer(14 "http://localhost:4321",15 object : TokenProvider {16 override fun token() = "a token"17 }18 )19 val person = pdl.person("en person", "en saksbehandler")20 println("I am $person")21}...
executeRequest
Using AI Code Generation
1val (request, response, result) = FuelManager.instance.executeRequest(Method.GET, "/get")2val (request, response, result) = FuelManager.instance.executeRequest(Method.GET, "/get", parameters = listOf("foo" to "bar"))3val (request, response, result) = FuelManager.instance.executeRequest(Method.GET, "/get", parameters = listOf("foo" to "bar"), headers = listOf("foo" to "bar"))4val (request, response, result) = FuelManager.instance.executeRequest(Method.GET, "/get", parameters = listOf("foo" to "bar"), headers = listOf("foo" to "bar"), body = "foo".toByteArray())5val (request, response, result) = FuelManager.instance.executeRequest(Method.GET, "/get", parameters = listOf("foo" to "bar"), headers = listOf("foo" to "bar"), body = "foo".toByteArray(), timeoutInMillisecond = 5000)6val (request, response, result) = FuelManager.instance.executeRequest(Method.GET, "/get", parameters = listOf("foo" to "bar"), headers = listOf("foo" to "bar"), body = "foo".toByteArray(), timeoutInMillisecond = 5000, followRedirects: Boolean = true)
executeRequest
Using AI Code Generation
1FuelManager.instance.client = object : Client {2 override fun executeRequest(request: Request): Response {3 val url = request.url.toString()4 return Response()5 }6}7FuelManager.instance.client = object : Client {8 override fun executeRequest(request: Request): Response {9 val url = request.url.toString()10 return Response()11 }12}13FuelManager.instance.client = object : Client {14 override fun executeRequest(request: Request): Response {15 val url = request.url.toString()16 return Response()17 }18}19FuelManager.instance.client = object : Client {20 override fun executeRequest(request: Request): Response {21 val url = request.url.toString()22 return Response()23 }24}25FuelManager.instance.client = object : Client {26 override fun executeRequest(request: Request
executeRequest
Using AI Code Generation
1val (request, response, result) = request.executeRequest()2val (request, response, result) = request.execute()3X-Xss-Protection: 1; mode=block4Result data: {5 "args": {}, 6 "headers": {7 },
executeRequest
Using AI Code Generation
1val client = Client()2val response = client.executeRequest(request)3println(response)4val client = Client()5val response = client.executeRequest(request)6println(response)7val client = Client()8val response = client.executeRequest(request)9println(response)10val client = Client()11val response = client.executeRequest(request)12println(response)13val client = Client()14val response = client.executeRequest(request)15println(response)16val client = Client()17val response = client.executeRequest(request)18println(response)19val client = Client()20val response = client.executeRequest(request)21println(response)22val client = Client()23val response = client.executeRequest(request)24println(response)25val client = Client()26val response = client.executeRequest(request)27println(response)28val client = Client()29val response = client.executeRequest(request)30println(response)
executeRequest
Using AI Code Generation
1import com.github.kittinunf.fuel.core.Client2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import com.github.kittinunf.result.Result7fun main(args: Array<String>) {8 val client = Client()9 val request = Request(Method.POST, url)10 val (request, response, result) = client.executeRequest(request)11 when (result) {12 is Result.Success -> {13 println(response)14 println(result.value)15 }16 is Result.Failure -> {17 println(result.getException())18 }19 }20}21{22 "args": {}, 23 "files": {}, 24 "form": {}, 25 "headers": {26 },
executeRequest
Using AI Code Generation
1val client = Client()2val (_, _, result) = client.executeRequest { request = url.httpGet() }3val client = Client()4val (_, _, result) = client.executeRequest { request = url.httpGet() }5val client = Client()6val (_, _, result) = client.executeRequest { request = url.httpGet() }7val client = Client()8val (_, _, result) = client.executeRequest { request = url.httpGet() }9val client = Client()10val (_, _, result) = client.executeRequest { request = url.httpGet() }11val client = Client()12val (_, _, result) = client.executeRequest { request = url.httpGet() }13val client = Client()14val (_, _, result) = client.executeRequest { request = url.httpGet() }15val client = Client()16val (_, _, result) = client.executeRequest { request = url.httpGet() }
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!