Best Fuel code snippet using com.github.kittinunf.fuel.jackson.ObjectBody
ControllerTest.kt
Source:ControllerTest.kt
1package no.nav.permitteringsportal.controller2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.jackson.objectBody4import BekreftelsePåArbeidsforholdHendelseOutboundDTO5import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule6import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper7import com.github.kittinunf.fuel.jackson.responseObject8import kotlinx.datetime.Clock9import kotlinx.datetime.TimeZone.Companion.UTC10import kotlinx.datetime.toLocalDateTime11import no.nav.permitteringsportal.database.BekreftelsePåArbeidsforhold12import no.nav.permitteringsportal.database.LokalDatabaseConfig13import no.nav.permitteringsportal.setup.issuerConfig14import no.nav.permitteringsportal.setup.medArbeidsgiverToken15import no.nav.permitteringsportal.startLokalApp16import no.nav.security.mock.oauth2.MockOAuth2Server17import org.junit.Test18import no.nav.security.mock.oauth2.http.objectMapper19import kotlin.test.assertEquals20import kotlin.test.assertNotNull21class ControllerTest {22 companion object {23 private val mockOAuth2Server = MockOAuth2Server()24 private val dataSource = LokalDatabaseConfig().dataSource25 val mapper = jacksonObjectMapper().apply {26 registerModule(JavaTimeModule())27 }28 init {29 mockOAuth2Server.shutdown()30 mockOAuth2Server.start()31 }32 }33 @Test34 fun skal_kunne_legge_til_å_hente_bekreftelse() {35 val startDato = Clock.System.now().toLocalDateTime(UTC)36 val sluttDato = Clock.System.now().toLocalDateTime(UTC)37 startLokalApp(dataSource, issuerConfig(mockOAuth2Server)).use {38 val nyBekreftelse = BekreftelsePåArbeidsforhold("", "123456789", "123456789", emptyList())39 val nyHendelse = BekreftelsePåArbeidsforholdHendelseOutboundDTO("", "", "NY", 100, startDato, sluttDato)40 val (_, _, result1) = Fuel.post("http://localhost:8080/bekreftelse")41 .medArbeidsgiverToken(mockOAuth2Server)42 .objectBody(nyBekreftelse, mapper = mapper)43 .responseString()44 val uuid = result1.component1()45 // Få tak på id og legg til en hendelse46 Fuel.put("http://localhost:8080/bekreftelse/${uuid}")47 .medArbeidsgiverToken(mockOAuth2Server)48 .objectBody(nyHendelse, mapper = mapper)49 .response()50 // Hent bekreftelse og verifiser at hendelse kommer med og har riktig data51 val bekreftelsePåArbeidsforholdLagret = Fuel.get("http://localhost:8080/bekreftelse/${uuid}")52 .medArbeidsgiverToken(mockOAuth2Server)53 .responseObject<BekreftelsePåArbeidsforhold>(mapper = objectMapper)54 .third55 .get()56 println(bekreftelsePåArbeidsforholdLagret)57 assertEquals(bekreftelsePåArbeidsforholdLagret.fnr, nyBekreftelse.fnr)58 assertEquals(bekreftelsePåArbeidsforholdLagret.orgnr, nyBekreftelse.orgnr)59 assertNotNull(bekreftelsePåArbeidsforholdLagret.hendelser)60 }61 }62 @Test63 fun skal_legge_bekreftelse_på_topic_etter_innsendelse() {64 // Legg til bekfreftelse65 // Oppdater med skjema-data (hendelse)66 // Send inn67 // Assert at det legges riktig bekreftelse på topic68 assert(true)69 }70 @Test71 fun skal_finnes_oppgave_å_hente_etter_konsumsjon_av_ping() {72 // Konsumere fra ping-topic73 // Hent fra api74 // Assert at det er riktig data75 assert(true)76 }77}...
util.kt
Source:util.kt
1package com.mktiti.fsearch.client.rest.fuel2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Parameters4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.RequestFactory.Convenience6import com.github.kittinunf.fuel.core.Response7import com.github.kittinunf.fuel.jackson.objectBody8import com.github.kittinunf.fuel.jackson.responseObject9import com.github.kittinunf.result.Result10import com.mktiti.fsearch.client.rest.ApiCallResult11private typealias FuelResp<T> = Triple<Request, Response, Result<T, FuelError>>12private typealias FuelConverter<T> = Request.() -> FuelResp<T>13internal inline fun <reified T> Convenience.getJson(path: String, params: Parameters = emptyList()): ApiCallResult<T> {14 return getJsonConv(path, params) {15 responseObject()16 }17}18private fun <T> Convenience.getJsonConv(19 path: String,20 params: Parameters,21 converter: FuelConverter<T>22): ApiCallResult<T> {23 val (_, resp, result) = get(path, params).converter()24 return when (result) {25 is Result.Success -> ApiCallResult.Success(result.value)26 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")27 }28}29internal inline fun <reified T> Convenience.postJson(path: String, body: Any): ApiCallResult<T> {30 return postJsonConv(path, body) {31 responseObject()32 }33}34private fun <T> Convenience.postJsonConv(path: String, body: Any, converter: FuelConverter<T>): ApiCallResult<T> {35 val (_, resp, result) = post(path)36 .header("Content-Type" to "application/json")37 .objectBody(body)38 .converter()39 return when (result) {40 is Result.Success -> ApiCallResult.Success(result.value)41 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")42 }43}44internal fun Convenience.postUnit(path: String, body: Any): ApiCallResult<Unit> {45 val (_, resp, result) = post(path)46 .header("Content-Type" to "application/json")47 .objectBody(body)48 .response()49 return when (result) {50 is Result.Success -> ApiCallResult.Success(Unit)51 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")52 }53}54internal fun Convenience.deleteBoolean(path: String): ApiCallResult<Boolean> {55 val (_, resp, result) = delete(path).responseObject<Boolean>()56 return when (result) {57 is Result.Success -> ApiCallResult.Success(result.value)58 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")59 }60}...
App.kt
Source:App.kt
1/*2 * This Kotlin source file was generated by the Gradle 'init' task.3 */4package Producer5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.coroutines.awaitObject7import com.github.kittinunf.fuel.coroutines.awaitUnit8import com.github.kittinunf.fuel.jackson.objectBody9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.delay11import kotlinx.coroutines.launch12import kotlinx.coroutines.runBlocking13import kotlin.random.Random14import kotlin.random.nextInt15import kotlin.time.DurationUnit16import kotlin.time.toDuration17class MainProducer(private val numberOfPoint: Int,) {18 private suspend fun fetchStations(): List<WeatherStationDTO> {19 val data = Fuel.get("http://localhost:8080/stations").awaitObject(WeatherStationDTODeserializer)20 println("Fetched ${data.size} stations")21 return data22 }23 fun start() {24 runBlocking(Dispatchers.Default) {25 println("Starting producer, getting stations lists ....")26 fetchStations().forEach {27 launch {28 println("Starting producer for station ${it.name}")29 StationProducer(it.id).generateWeatherPoints(numberOfPoint)30 }31 }32 }33 }34}35class StationProducer(private val stationId: String) {36 private val delay = Random.nextInt(100..800).toDuration(DurationUnit.MILLISECONDS)37 private val listWindDirection = listOf(38 "N",39 "NNE",40 "NE",41 "ENE",42 "E",43 "ESE",44 "SE",45 "SSE",46 "S",47 "SSW",48 "SW",49 "WSW",50 "W",51 "WNW",52 "NW",53 "NNW"54 )55 private fun generateWeatherPoint(temp: Double) = WeatherPointDTO(temp, "C", Random.nextInt(1..80).toString() + listWindDirection.random())56 suspend fun generateWeatherPoints(numberOfPoint: Int) {57 var previousTemp = Random.nextDouble(-10.0, 30.0)58 for (i in 1..numberOfPoint) {59 val temp = previousTemp.randomPercent()60 val weatherPoint = generateWeatherPoint(temp)61 println("$i --> $stationId: $weatherPoint")62 sendPoint(weatherPoint)63 previousTemp = temp64 delay(delay)65 }66 }67 private suspend fun sendPoint(weatherPoint: WeatherPointDTO) {68 Fuel.post("http://localhost:8080/stations/$stationId/points")69 .objectBody(weatherPoint)70 .awaitUnit()71 }72}73fun main() {74 MainProducer(100).start()75}...
ObjectBodyTest.kt
Source:ObjectBodyTest.kt
...10import org.hamcrest.CoreMatchers.equalTo11import org.hamcrest.MatcherAssert.assertThat12import org.junit.Test13import java.net.URL14class ObjectBodyTest {15 @Test16 fun setsBodyCorrectly() {17 val expectedBody = "{\"foo\":42,\"bar\":\"foo bar\",\"fooBar\":\"foo bar\"}"18 val bodyObject = FakeObject()19 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))20 .objectBody(bodyObject)21 assertThat(expectedBody, equalTo(String(request.body.toByteArray())))22 }23 @Test24 fun setsContentTypeCorrectly() {25 val bodyObject = listOf(26 42,27 mapOf("foo" to "bar")28 )...
LoginController.kt
Source:LoginController.kt
1package com.github.eventdrivenecomm.orderservice.application.restapi.controllers2import com.fasterxml.jackson.databind.ObjectMapper3import com.fasterxml.jackson.module.kotlin.registerKotlinModule4import com.github.kittinunf.fuel.Fuel5import com.github.kittinunf.fuel.core.Headers6import com.github.kittinunf.fuel.core.Request7import io.javalin.http.Context8import io.javalin.http.UnauthorizedResponse9import org.slf4j.LoggerFactory10import java.nio.charset.Charset11class LoginController {12 private val logger = LoggerFactory.getLogger(LoginController::class.java)13 /**14 * A lot of refactoring to be done here:15 *16 * 1. use konfig to get url to customer-service17 * 2. maybe use async request to avoid blocking18 * 3. extract DTOs to somewhere else19 * 4. extract fuel logic to some http client utils20 *21 */22 fun login(ctx: Context) {23 val credentials = ctx.bodyAsClass(LoginDTO::class.java)24 logger.info("Validation credentials for ${credentials.email}")25 val mapper = ObjectMapper().registerKotlinModule()26 Fuel27 .post("http://localhost:7002/login")28 .objectBody(bodyObject = credentials, mapper = mapper)29 .responseString()30 .let { (request, response, result) ->31 result.fold(32 success = { result ->33 ctx.json(mapper.readValue(result, TokenDTO::class.java))34 },35 failure = { failure ->36 logger.error("Failed to get credentials: ${failure.response}")37 throw UnauthorizedResponse()38 }39 )40 }41 }42}43data class LoginDTO(44 val email: String,45 val password: String46)47data class TokenDTO(48 val token: String49)50/**51 * Set the body to an Object to be serialized52 */53fun Request.objectBody(54 bodyObject: Any,55 charset: Charset = Charsets.UTF_8,56 mapper: ObjectMapper57): Request {58 val bodyString = mapper.writeValueAsString(bodyObject)59 this[Headers.CONTENT_TYPE] = "application/json"60 return body(bodyString, charset)61}...
WalletApiGateway.kt
Source:WalletApiGateway.kt
1import com.fasterxml.jackson.databind.DeserializationFeature2import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper3import com.github.kittinunf.fuel.httpPost4import com.github.kittinunf.fuel.jackson.objectBody5import com.github.kittinunf.fuel.jackson.responseObject6import com.lesbass.wallet.infrastructure.WalletCategory7import com.natpryce.konfig.*8data class CheckUserRequest(val userName: String)9data class CategoriesRequest(val userName: String)10class WalletApiGateway {11 private val objectMapper = jacksonObjectMapper()12 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)13 private val config = EnvironmentVariables() overriding14 ConfigurationProperties.fromResource("defaults.properties")15 private fun buildApiUrl(endpoint: String): String {16 val walletApiBaseUrl = config[Key("WALLET_BASE_URL", stringType)]17 return walletApiBaseUrl + endpoint18 }19 private fun getBearer(): String {20 return """Bearer ${config[Key("WALLET_API_KEY", stringType)]}"""21 }22 fun isAuthorized(checkUserRequest: CheckUserRequest): Boolean {23 val (_, _, result) = buildApiUrl("/check-user")24 .httpPost()25 .appendHeader("Authorization", getBearer())26 .objectBody(checkUserRequest)27 .responseString()28 return result is com.github.kittinunf.result.Result.Success29 }30 fun getCategories(categoriesRequest: CategoriesRequest): List<WalletCategory> {31 val (_, _, result) = buildApiUrl("/category")32 .httpPost()33 .appendHeader("Authorization", getBearer())34 .objectBody(categoriesRequest)35 .responseObject<List<WalletCategory>>(mapper = objectMapper)36 return result.fold(37 success = { it },38 failure = { error -> throw Exception(error.message ?: "Errore generico") }39 )40 }41}...
ScriptApiTest.kt
Source:ScriptApiTest.kt
1package lit.fass.server2import com.github.kittinunf.fuel.core.extensions.authentication3import com.github.kittinunf.fuel.httpPost4import com.github.kittinunf.fuel.jackson.jacksonDeserializerOf5import com.github.kittinunf.fuel.jackson.objectBody6import lit.fass.server.helper.TestTypes.ApiTest7import lit.fass.server.helper.TestcontainerSupport8import org.assertj.core.api.Assertions.assertThat9import org.junit.jupiter.api.Tag10import org.junit.jupiter.api.Test11import org.junit.jupiter.api.TestInstance12import org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS13/**14 * @author Michael Mair15 */16@Tag(ApiTest)17@TestInstance(PER_CLASS)18internal class ScriptApiTest : TestcontainerSupport() {19 @Test20 fun `script extension test POST endpoint returns result`() {21 "/script/groovy/test"22 .httpPost()23 .authentication().basic("admin", "admin")24 .objectBody(25 mapOf(26 "script" to """binding.data""",27 "data" to mapOf("foo" to "bar", "bar" to true)28 )29 )30 .responseObject<List<Map<String, Any?>>>(jacksonDeserializerOf())31 .apply {32 val response = second33 val result = third.component1()!!34 assertThat(result).hasSize(1)35 assertThat(result.first()["foo"]).isEqualTo("bar")36 assertThat(result.first()["bar"]).isEqualTo(true)37 assertThat(response.statusCode).isEqualTo(200)38 }39 }40}...
AbstractValidator.kt
Source:AbstractValidator.kt
1package br.com.idws.bank.accountvalidator.infrastructure.validators2import br.com.idws.bank.accountvalidator.domain.AccountCreateValidator3import br.com.idws.bank.accountvalidator.domain.model.account.Account4import br.com.idws.bank.accountvalidator.domain.model.validation.Error5import br.com.idws.bank.accountvalidator.infrastructure.fuel.getOrError6import com.fasterxml.jackson.databind.ObjectMapper7import com.github.kittinunf.fuel.Fuel8import com.github.kittinunf.fuel.jackson.objectBody9open class AbstractValidator(10 val url: String,11 val mapper: ObjectMapper12) : AccountCreateValidator {13 override fun validate(account: Account): List<Error> =14 Fuel.post(url)15 .objectBody(account, mapper = mapper)16 .getOrError { _, _, _ -> emptyList<Error>() } as List<Error>17}...
ObjectBody
Using AI Code Generation
1val (data, error) = result2data?.let { println(it) }3error?.let { println(it) }4val (data, error) = result5data?.let { println(it) }6error?.let { println(it) }7val (data, error) = result8data?.let { println(it) }9error?.let { println(it) }10val (data, error) = result11data?.let { println(it) }12error?.let { println(it) }13val (data, error) = result14data?.let { println(it) }15error?.let { println(it) }16val (data, error) = result17data?.let { println(it) }18error?.let { println(it) }19val (data,
ObjectBody
Using AI Code Generation
1val data = result.component1()2val exception = result.component3()3val data = result.component1()4val exception = result.component3()5at com.github.kittinunf.fuel.core.FuelManager$executeRequest$1.invoke(FuelManager.kt:267)6at com.github.kittinunf.fuel.core.FuelManager$executeRequest$1.invoke(FuelManager.kt:46)7at com.github.kittinunf.fuel.core.DeserializableKt.response(deserializable.kt:39)8at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:266)9at com.github.kittinunf.fuel.core.FuelManager.request(FuelManager.kt:149)10at com.github.kittinunf.fuel.core.FuelManager.request(FuelManager.kt:128)
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!!