Best Fuel code snippet using com.github.kittinunf.fuel.reactor.Reactor.Request.monoUnit
ReactorTest.kt
Source:ReactorTest.kt  
1package com.github.kittinunf.fuel.reactor2import com.fasterxml.jackson.databind.exc.InvalidFormatException3import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException4import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper5import com.fasterxml.jackson.module.kotlin.readValue6import com.github.kittinunf.fuel.Fuel7import com.github.kittinunf.fuel.core.FuelError8import com.github.kittinunf.fuel.core.Response9import com.github.kittinunf.fuel.core.ResponseDeserializable10import com.github.kittinunf.fuel.test.MockHttpTestCase11import com.github.kittinunf.result.Result12import org.hamcrest.CoreMatchers.equalTo13import org.hamcrest.MatcherAssert.assertThat14import org.junit.Assert.assertEquals15import org.junit.Assert.assertTrue16import org.junit.Test17import reactor.core.publisher.Mono18import reactor.core.publisher.onErrorResume19import reactor.test.test20import java.util.UUID21class ReactorTest : MockHttpTestCase() {22    @Test23    fun monoBytes() {24        mock.chain(25            request = mock.request().withPath("/bytes"),26            response = mock.response().withBody(ByteArray(10))27        )28        Fuel.get(mock.path("bytes")).monoBytes()29            .test()30            .assertNext { assertEquals(10, it.size) }31            .verifyComplete()32    }33    @Test34    fun monoString() {35        mock.chain(36            request = mock.request().withPath("/ip"),37            response = mock.response().withBody("127.0.0.1")38        )39        Fuel.get(mock.path("ip")).monoString()40            .test()41            .assertNext { assertEquals("127.0.0.1", it) }42            .verifyComplete()43    }44    @Test45    fun monoObject() {46        mock.chain(47            request = mock.request().withPath("/ip"),48            response = mock.response()49                .withBody(jacksonObjectMapper().writeValueAsString(Ip("127.0.0.1")))50        )51        Fuel.get(mock.path("ip")).monoObject(IpDeserializerSuccess)52            .map(Ip::origin)53            .test()54            .assertNext { assertEquals("127.0.0.1", it) }55            .verifyComplete()56    }57    @Test58    fun monoObjectWithInvalidFormat() {59        mock.chain(60            request = mock.request().withPath("/ip"),61            response = mock.response()62                .withBody(jacksonObjectMapper().writeValueAsString(Ip("127.0.0.1")))63        )64        Fuel.get(mock.path("ip")).monoObject(IpLongDeserializer)65            .map(IpLong::origin)66            .test()67            .expectErrorMatches { (it as FuelError).exception is InvalidFormatException }68            .verify()69    }70    @Test71    fun monoObjectWithMissingProperty() {72        mock.chain(73            request = mock.request().withPath("/ip"),74            response = mock.response()75                .withBody(jacksonObjectMapper().writeValueAsString(Ip("127.0.0.1")))76        )77        val errorMessage = Fuel.get(mock.path("ip")).monoObject(IpAddressDeserializer)78            .map(IpAddress::address)79            .onErrorResume(FuelError::class) {80                assertTrue(it.exception is MissingKotlinParameterException)81                Mono.just(it.message.orEmpty())82            }83            .block()!!84        assertTrue(errorMessage.contains("value failed for JSON property address due to missing"))85    }86    @Test87    fun monoResponse() {88        mock.chain(89            request = mock.request().withPath("/status"),90            response = mock.response().withStatusCode(404)91        )92        Fuel.get(mock.path("status")).monoResponse()93            .map(Response::statusCode)94            .test()95            .assertNext { assertEquals(it, 404) }96            .verifyComplete()97    }98    @Test99    fun monoResultBytes() {100        mock.chain(101            request = mock.request().withPath("/bytes"),102            response = mock.response().withBody(ByteArray(20))103        )104        Fuel.get(mock.path("bytes")).monoResultBytes()105            .map(Result<ByteArray, FuelError>::get)106            .test()107            .assertNext { assertEquals(20, it.size) }108            .verifyComplete()109    }110    @Test111    fun monoResultString() {112        val randomUuid = UUID.randomUUID().toString()113        mock.chain(114            request = mock.request().withPath("/uuid"),115            response = mock.response().withBody(randomUuid)116        )117        Fuel.get(mock.path("uuid")).monoResultString()118            .map(Result<String, FuelError>::get)119            .test()120            .assertNext { assertEquals(randomUuid, it) }121            .verifyComplete()122    }123    @Test124    fun monoResultObject() {125        mock.chain(126            request = mock.request().withPath("/ip"),127            response = mock.response()128                .withBody(jacksonObjectMapper().writeValueAsString(Ip("192.168.0.1")))129        )130        Fuel.get(mock.path("ip")).monoResultObject(IpDeserializerSuccess)131            .map(Result<Ip, FuelError>::get)132            .map(Ip::origin)133            .test()134            .assertNext { assertEquals("192.168.0.1", it) }135            .verifyComplete()136    }137    @Test138    fun monoResultObjectWithInvalidFormat() {139        mock.chain(140            request = mock.request().withPath("/ip"),141            response = mock.response()142                .withBody(jacksonObjectMapper().writeValueAsString(Ip("192.168.0.1")))143        )144        Fuel.get(mock.path("ip")).monoResultObject(IpLongDeserializer)145            .map(Result<IpLong, FuelError>::component2)146            .test()147            .assertNext { assertTrue(it?.exception is InvalidFormatException) }148            .verifyComplete()149    }150    @Test151    fun monoResultObjectWithMissingProperty() {152        mock.chain(153            request = mock.request().withPath("/ip"),154            response = mock.response()155                .withBody(jacksonObjectMapper().writeValueAsString(Ip("192.168.0.1")))156        )157        Fuel.get(mock.path("ip")).monoResultObject(IpAddressDeserializer)158            .map(Result<IpAddress, FuelError>::component2)159            .test()160            .assertNext { assertTrue(it?.exception is MissingKotlinParameterException) }161            .verifyComplete()162    }163    @Test164    fun monoCancellation() {165        mock.chain(166                request = mock.request().withPath("/bytes"),167                response = mock.response().withBody(ByteArray(10))168        )169        val running = Fuel.get(mock.path("bytes"))170            .monoBytes()171            .toProcessor()172        running.cancel()173        assertThat(running.isCancelled, equalTo(true))174    }175    @Test176    fun monoUnit() {177        mock.chain(178            request = mock.request().withPath("/ip"),179            response = mock.response().withBody("127.0.0.1")180        )181        Fuel.get(mock.path("ip")).monoUnit()182            .test()183            .assertNext { assertThat(it, equalTo(Unit)) }184            .verifyComplete()185    }186    private data class IpLong(val origin: Long)187    private object IpLongDeserializer : ResponseDeserializable<IpLong> {188        override fun deserialize(content: String) = jacksonObjectMapper().readValue<IpLong>(content)189    }190    private data class IpAddress(val address: String)191    private object IpAddressDeserializer : ResponseDeserializable<IpAddress> {192        override fun deserialize(content: String) = jacksonObjectMapper().readValue<IpAddress>(content)193    }194    private data class Ip(val origin: String)195    private object IpDeserializerSuccess : ResponseDeserializable<Ip> {196        override fun deserialize(content: String) = jacksonObjectMapper().readValue<Ip>(content)197    }198}...OAuthApplication.kt
Source:OAuthApplication.kt  
1package gg.botlabs.oauth2import com.github.kittinunf.fuel.core.Request3import com.github.kittinunf.fuel.core.isSuccessful4import com.github.kittinunf.fuel.httpPost5import com.github.kittinunf.fuel.reactor.monoResponse6import com.github.kittinunf.fuel.reactor.monoUnit7import org.json.JSONObject8import reactor.core.publisher.Mono9import java.lang.IllegalStateException10import java.time.Instant11@Suppress("MemberVisibilityCanBePrivate", "unused")12class OAuthApplication(13    val tokenUrl: String,14    val clientId: String,15    val clientSecret: String,16    val redirectUri: String,17    val revocationUrl: String? = null18) {19    /** Exchanges the code for a new grant of type authorization_code */20    fun <T> exchangeCode(handler: GrantHandler<T>, code: String, scope: List<String>? = null): Mono<T> = tokenUrl.httpPost(21        listOfNotNull(22            "client_id" to clientId,23            "client_secret" to clientSecret,24            "grant_type" to "authorization_code",25            "code" to code,26            "redirect_uri" to redirectUri,27            scope?.let { "scope" to it.joinToString(" ") }28        )29    ).toGrantMono(handler, false)30    /** Attempts to refresh a grant */31    fun <T> refreshGrant(handler: RefreshHandler<T>, grant: TokenGrant): Mono<T> = refreshGrant(handler, grant.refreshToken)32    /** Attempts to refresh a grant */33    fun <T> refreshGrant(handler: RefreshHandler<T>, refreshToken: String): Mono<T> = tokenUrl.httpPost(34        listOfNotNull(35            "client_id" to clientId,36            "client_secret" to clientSecret,37            "grant_type" to "refresh_token",38            "refresh_token" to refreshToken,39            "redirect_uri" to redirectUri40        )41    ).toGrantMono(handler, true)42    fun refresh(refreshToken: String): Mono<TokenGrant> = tokenUrl.httpPost(43        listOfNotNull(44            "client_id" to clientId,45            "client_secret" to clientSecret,46            "grant_type" to "refresh_token",47            "refresh_token" to refreshToken,48            "redirect_uri" to redirectUri49        )50    ).toGrantMonoNoHandler()51    fun revoke(token: String): Mono<Unit> {52        if (revocationUrl == null) throw IllegalStateException("Revocation URL not provided")53        return revocationUrl.httpPost(54            listOf(55                "token" to token,56                "client_id" to clientId,57                "client_secret" to clientSecret58            )59        ).monoUnit()60    }61    /** Returns immediately if the bearer has not expired. Otherwise calls [refreshGrant] */62    fun <T> getFreshGrant(handler: RefreshHandler<T>, grant: TokenGrant, toleranceSeconds: Long = 300): Mono<T> {63        val expiry = grant.expires.minusSeconds(toleranceSeconds)64        if (Instant.now().isBefore(expiry)) return Mono.just(handler.onUnchanged()!!)65        return refreshGrant(handler, grant)66    }67    private fun <T> Request.toGrantMono(handler: GrantHandler<T>, isRefresh: Boolean): Mono<T> = header("Accept", "application/json")68        .monoResponse()69        .flatMap { res ->70            val bodyStr = res.data.decodeToString()71            val json: JSONObject72            try {73                json = JSONObject(bodyStr)74            } catch (e: Exception) {75                OAuthException.onInvalidJson(bodyStr)76            }77            if (json.optString("error") == "invalid_grant") {78                val refreshHandler = handler as RefreshHandler79                @Suppress("UNCHECKED_CAST") // Type cast safe as Mono<Void> returns empty80                return@flatMap refreshHandler.onInvalidGrant(res) as Mono<T>81            }82            if (!res.isSuccessful) OAuthException.onError(json)83            handler.handleTokenGrant(json.run {84                TokenGrant(85                    getString("access_token"),86                    getString("refresh_token"),87                    optString("scope")?.split(' '),88                    Instant.now().plusSeconds(getLong("expires_in"))89                )90            })91        }92    private fun Request.toGrantMonoNoHandler(): Mono<TokenGrant> = header("Accept", "application/json")93        .monoResponse()94        .map { res ->95            val bodyStr = res.data.decodeToString()96            val json: JSONObject97            try {98                json = JSONObject(bodyStr)99            } catch (e: Exception) {100                OAuthException.onInvalidJson(bodyStr)101            }102            if (!res.isSuccessful) OAuthException.onError(json)103            json.run {104                TokenGrant(105                    getString("access_token"),106                    getString("refresh_token"),107                    optString("scope")?.split(' '),108                    Instant.now().plusSeconds(getLong("expires_in"))109                )110            }111        }112}...Reactor.kt
Source:Reactor.kt  
1package com.github.kittinunf.fuel.reactor2import com.github.kittinunf.fuel.core.Deserializable3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer7import com.github.kittinunf.fuel.core.deserializers.EmptyDeserializer8import com.github.kittinunf.fuel.core.deserializers.StringDeserializer9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.core.response11import com.github.kittinunf.result.Result12import reactor.core.publisher.Mono13import reactor.core.publisher.MonoSink14import java.nio.charset.Charset15private fun <T : Any> Request.monoResult(async: Request.(MonoSink<T>) -> CancellableRequest): Mono<T> =16    Mono.create<T> { sink ->17        val cancellableRequest = async(sink)18        sink.onCancel { cancellableRequest.cancel() }19    }20private fun <T : Any> Request.monoResultFold(mapper: Deserializable<T>): Mono<T> =21    monoResult { sink ->22        response(mapper) { _, _, result ->23            result.fold(sink::success, sink::error)24        }25    }26private fun <T : Any> Request.monoResultUnFolded(mapper: Deserializable<T>): Mono<Result<T, FuelError>> =27    monoResult { sink ->28        response(mapper) { _, _, result ->29            sink.success(result)30        }31    }32/**33 * Get a single [Response]34 * @return [Mono<Response>] the [Mono]35 */36fun Request.monoResponse(): Mono<Response> =37    monoResult { sink ->38        response { _, res, _ -> sink.success(res) }39    }40/**41 * Get a single [ByteArray] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]42 *43 * @see monoResultBytes44 * @return [Mono<ByteArray>] the [Mono]45 */46fun Request.monoBytes(): Mono<ByteArray> = monoResultFold(ByteArrayDeserializer())47/**48 * Get a single [String] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]49 *50 * @see monoResultString51 *52 * @param charset [Charset] the charset to use for the string, defaults to [Charsets.UTF_8]53 * @return [Mono<String>] the [Mono]54 */55fun Request.monoString(charset: Charset = Charsets.UTF_8): Mono<String> = monoResultFold(StringDeserializer(charset))56/**57 * Get a single [T] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]58 *59 * @see monoResultObject60 *61 * @param mapper [Deserializable<T>] the deserializable that can turn the response int a [T]62 * @return [Mono<T>] the [Mono]63 */64fun <T : Any> Request.monoObject(mapper: Deserializable<T>): Mono<T> = monoResultFold(mapper)65/**66 * Get a single [ByteArray] or [FuelError] via [Result]67 *68 * @see monoBytes69 * @return [Mono<Result<ByteArray, FuelError>>] the [Mono]70 */71fun Request.monoResultBytes(): Mono<Result<ByteArray, FuelError>> =72    monoResultUnFolded(ByteArrayDeserializer())73/**74 * Get a single [String] or [FuelError] via [Result]75 *76 * @see monoString77 *78 * @param charset [Charset] the charset to use for the string, defaults to [Charsets.UTF_8]79 * @return [Mono<Result<ByteArray, FuelError>>] the [Mono]80 */81fun Request.monoResultString(charset: Charset = Charsets.UTF_8): Mono<Result<String, FuelError>> =82    monoResultUnFolded(StringDeserializer(charset))83/**84 * Get a single [T] or [FuelError] via [Result]85 *86 * @see monoObject87 * @return [Mono<Result<T, FuelError>>] the [Mono]88 */89fun <T : Any> Request.monoResultObject(mapper: Deserializable<T>): Mono<Result<T, FuelError>> =90    monoResultUnFolded(mapper)91/**92 * Get a complete signal(success with [Unit]) via a [MonoSink.success], or any [FuelError] via [MonoSink.error]93 */94fun Request.monoUnit(): Mono<Unit> = monoResultFold(EmptyDeserializer)...Request.monoUnit
Using AI Code Generation
1Request.monoUnit(url)2Request.mono(url)3Request.monoList(url)4Request.flux(url)5Request.fluxList(url)6Request.asFlowable(url)7Request.asFlowableList(url)8Request.asObservable(url)9Request.asObservableList(url)10Request.asSingle(url)11Request.asSingleList(url)12Request.asCompletable(url)13Request.asCompletableList(url)14Request.asMaybe(url)15Request.asMaybeList(url)16Request.asPublisher(url)17Request.asPublisherList(url)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!!
