How to use Arb.trampoline method of io.kotest.property.arbitrary.map class

Best Kotest code snippet using io.kotest.property.arbitrary.map.Arb.trampoline

RetrieveShakespeareDescriptionUseCaseTest.kt

Source:RetrieveShakespeareDescriptionUseCaseTest.kt Github

copy

Full Screen

1package com.example.sdk.usecases2import com.example.sdk.*3import com.example.sdk.api.PokemonAPI4import com.example.sdk.api.ShakespeareAPI5import com.example.sdk.api.requests.ShakespeareTranslateRequest6import com.example.sdk.api.responses.PokemonSpeciesResponse7import com.example.sdk.api.responses.PokemonSpeciesResponse.FlavorObject8import com.example.sdk.api.responses.PokemonSpeciesResponse.Language9import com.example.sdk.api.responses.ShakespeareTranslateResponse10import com.example.sdk.api.responses.ShakespeareTranslateResponse.Contents11import io.kotest.assertions.fail12import io.kotest.core.spec.style.FunSpec13import io.kotest.matchers.collections.shouldBeEmpty14import io.kotest.property.Arb15import io.kotest.property.arbitrary.of16import io.kotest.property.forAll17import io.reactivex.rxjava3.core.Single18import io.reactivex.rxjava3.observers.TestObserver19import io.reactivex.rxjava3.schedulers.Schedulers20import org.mockito.kotlin.any21import org.mockito.kotlin.argThat22import org.mockito.kotlin.mock23import org.mockito.kotlin.whenever24import retrofit2.HttpException25import java.net.SocketTimeoutException26class RetrieveShakespeareDescriptionUseCaseTest : FunSpec({27 val validSpeciesResponse = listOf(28 PokemonSpeciesResponse(listOf(FlavorObject("first", Language("en")))),29 PokemonSpeciesResponse(30 listOf(31 FlavorObject("secondo", Language("it")),32 FlavorObject("zweite", Language("de")),33 FlavorObject("second", Language("en"))34 )35 ),36 PokemonSpeciesResponse(37 listOf(38 FlavorObject("third", Language("en")),39 FlavorObject("terzo", Language("it"))40 )41 )42 )43 val invalidSpeciesResponse = listOf(44 PokemonSpeciesResponse(listOf()),45 PokemonSpeciesResponse(46 listOf(47 FlavorObject("quarto", Language("it")),48 FlavorObject("vierte", Language("de"))49 )50 )51 )52 val possibleShakespeareRequests = listOf(53 ShakespeareTranslateRequest("first"),54 ShakespeareTranslateRequest("second"),55 ShakespeareTranslateRequest("third")56 )57 val shakespeareApiResponse = ShakespeareTranslateResponse(Contents("success"))58 // Errors59 val pokemonApiError = IllegalArgumentException("Pokemon API error")60 val shakespeareApiError = IllegalArgumentException("Shakespeare API error")61 // Generators62 val speciesResponseGenerator = Arb.of(validSpeciesResponse + invalidSpeciesResponse)63 val shakespeareResponseGenerator = Arb.of(64 listOf(65 Single.just(shakespeareApiResponse),66 Single.error(shakespeareApiError)67 )68 )69 test("RetrieveShakespeareDescriptionUseCase Property-Based test") {70 forAll(71 pokemonNameGenerator,72 speciesResponseGenerator,73 shakespeareResponseGenerator74 ) { pokemonName, speciesResponse, shakespeareResponse ->75 // Mocks76 val pokemonClient: PokemonAPI = mock()77 whenever(pokemonClient.getPokemonSpecies(argThat {78 validPokemonList.map { it.lowercase() }.contains(this.lowercase())79 }))80 .thenReturn(Single.just(speciesResponse))81 whenever(pokemonClient.getPokemonSpecies(argThat {82 invalidPokemonList.map { it.lowercase() }.contains(this.lowercase())83 }))84 .thenReturn(Single.error(pokemonApiError))85 val shakespeareClient: ShakespeareAPI = mock()86 whenever(shakespeareClient.getShakespeareText(argThat {87 possibleShakespeareRequests.contains(this)88 }))89 .thenReturn(shakespeareResponse)90 // Observer-test91 val testObserver = TestObserver.create<String>()92 // Test execution93 RetrieveShakespeareDescriptionUseCase(94 pokemonClient,95 shakespeareClient,96 Schedulers.trampoline()97 )98 .execute(pokemonName)99 .subscribe(testObserver)100 // Checks101 when {102 testObserver.values().isEmpty() -> testObserver.assertError {103 when (it) {104 is SdkError.Generic -> {105 invalidPokemonList.contains(pokemonName) ||106 shakespeareResponse.test().values().isEmpty()107 }108 is SdkError.NoEnglishDescriptionFound ->109 invalidSpeciesResponse.contains(speciesResponse)110 else -> fail("Unexpected error, $it")111 }112 }113 testObserver.values().isNotEmpty() -> testObserver.assertValueCount(1)114 .assertValue {115 shakespeareResponse.blockingGet() == shakespeareApiResponse &&116 it == "success"117 }118 else -> fail("Unexpected result, ${testObserver.values()}")119 }120 true121 }122 }123 test("RetrieveShakespeareDescriptionUseCase pokemon api ERROR test") {124 forAll(createApiExceptionGenerator<PokemonSpeciesResponse>()) { exception ->125 val client: PokemonAPI = mock()126 whenever(client.getPokemonSpecies(any()))127 .thenReturn(Single.error(exception))128 val shakespeareClient: ShakespeareAPI = mock()129 whenever(shakespeareClient.getShakespeareText(any()))130 .thenReturn(Single.just(shakespeareApiResponse))131 val testObserver = TestObserver.create<String>()132 RetrieveShakespeareDescriptionUseCase(133 client,134 shakespeareClient,135 Schedulers.trampoline()136 )137 .execute("")138 .subscribe(testObserver)139 testObserver.values().shouldBeEmpty()140 testObserver.assertError { errorAssert(it, exception) }141 true142 }143 }144 test("RetrieveShakespeareDescriptionUseCase shakespeare api ERROR test") {145 forAll(createApiExceptionGenerator<ShakespeareTranslateResponse>()) { exception ->146 val client: PokemonAPI = mock()147 whenever(client.getPokemonSpecies(any()))148 .thenReturn(149 Single.just(150 PokemonSpeciesResponse(listOf(FlavorObject("first", Language("en"))))151 )152 )153 val shakespeareClient: ShakespeareAPI = mock()154 whenever(shakespeareClient.getShakespeareText(any()))155 .thenReturn(Single.error(exception))156 val testObserver = TestObserver.create<String>()157 RetrieveShakespeareDescriptionUseCase(158 client,159 shakespeareClient,160 Schedulers.trampoline()161 )162 .execute("")163 .subscribe(testObserver)164 testObserver.values().shouldBeEmpty()165 testObserver.assertError { errorAssert(it, exception) }166 true167 }168 }169})170private fun errorAssert(it: Throwable, exception: Exception) = when (it) {171 is SdkError.Http -> {172 when (it._message) {173 "Too many request done" -> (exception as HttpException).code() == 429174 "Internal server error" -> (exception as HttpException).code() == 500175 "Resource not found" -> (exception as HttpException).code() == 404176 else -> fail("Unexpected exception, $it")177 }178 }179 is SdkError.Generic -> exception is NullPointerException180 SdkError.TimeOut -> exception is SocketTimeoutException181 else -> fail("Unexpected exception, $it")182}...

Full Screen

Full Screen

RetrievePokemonSpriteUseCaseTest.kt

Source:RetrievePokemonSpriteUseCaseTest.kt Github

copy

Full Screen

1package com.example.sdk.usecases2import com.example.sdk.*3import com.example.sdk.api.PokemonAPI4import com.example.sdk.api.responses.PokemonDetailResponse5import com.example.sdk.api.responses.PokemonDetailResponse.Sprites6import io.kotest.assertions.fail7import io.kotest.core.spec.style.FunSpec8import io.kotest.property.Arb9import io.kotest.property.arbitrary.of10import io.kotest.property.forAll11import io.reactivex.rxjava3.core.Single12import io.reactivex.rxjava3.observers.TestObserver13import io.reactivex.rxjava3.schedulers.Schedulers14import org.mockito.kotlin.any15import org.mockito.kotlin.argThat16import org.mockito.kotlin.mock17import org.mockito.kotlin.whenever18import retrofit2.HttpException19import java.net.SocketTimeoutException20import java.net.URL21class RetrievePokemonSpriteUseCaseTest : FunSpec({22 val validResponse = listOf(23 PokemonDetailResponse(Sprites("https://mysite.com", "w.site.c")),24 PokemonDetailResponse(Sprites("https://mysite.com", null)),25 PokemonDetailResponse(Sprites(null, "https://www.google.it")),26 PokemonDetailResponse(Sprites("www.malformed.c", "https://www.google.it")),27 PokemonDetailResponse(Sprites("https://mysite.com", "https://www.google.it"))28 )29 val invalidUrlResponse = listOf(30 PokemonDetailResponse(Sprites(null, null)),31 PokemonDetailResponse(Sprites(null, "ww.invalid-url.com")),32 PokemonDetailResponse(Sprites("htp:wwww-yr", "ww.invalid-url.com")),33 PokemonDetailResponse(Sprites("htp:wwww-yr", null))34 )35 // Generators36 val responseGenerator = Arb.of(validResponse + invalidUrlResponse)37 // Errors38 val apiError = IllegalArgumentException("API error")39 test("RetrievePokemonSpriteUseCase Property-Based test") {40 forAll(pokemonNameGenerator, responseGenerator) { pokemonName, response ->41 // Mocks42 val client: PokemonAPI = mock()43 whenever(client.getPokemonDetail(argThat {44 validPokemonList.map { it.lowercase() }.contains(this.lowercase())45 }))46 .thenReturn(Single.just(response))47 whenever(client.getPokemonDetail(argThat {48 invalidPokemonList.map { it.lowercase() }.contains(this.lowercase())49 }))50 .thenReturn(Single.error(apiError))51 // Observer-test52 val testObserver = TestObserver.create<URL>()53 // Test execution54 RetrievePokemonSpriteUseCase(55 client,56 Schedulers.trampoline(),57 Dependencies.urlValidator58 )59 .execute(pokemonName)60 .subscribe(testObserver)61 // Checks62 when {63 testObserver.values().isEmpty() -> testObserver.assertError {64 when (it) {65 is SdkError.Generic -> invalidPokemonList.contains(pokemonName)66 is SdkError.NoValidPokemonSpriteFound ->67 invalidUrlResponse.contains(response)68 else -> fail("Unexpected error, $it")69 }70 }71 testObserver.values().isNotEmpty() -> testObserver.assertValueCount(1)72 .assertValue {73 when (it) {74 URL("https://mysite.com") ->75 response.sprites.frontDefault == "https://mysite.com"76 URL("https://www.google.it") ->77 response.sprites.frontDefault == null ||78 response.sprites.frontDefault == "www.malformed.c"79 else -> fail("Unexpected URL, $it")80 }81 }82 else -> fail("Unexpected result, ${testObserver.values()}")83 }84 true85 }86 }87 test("RetrievePokemonSpriteUseCase ERROR test") {88 forAll(createApiExceptionGenerator<PokemonDetailResponse>()) { exception ->89 val client: PokemonAPI = mock()90 whenever(client.getPokemonDetail(any()))91 .thenReturn(Single.error(exception))92 val testObserver = TestObserver.create<URL>()93 RetrievePokemonSpriteUseCase(94 client,95 Schedulers.trampoline(),96 Dependencies.urlValidator97 )98 .execute("")99 .subscribe(testObserver)100 testObserver.assertError {101 when (it) {102 is SdkError.Http -> {103 when (it._message) {104 "Too many request done" -> (exception as HttpException).code() == 429105 "Internal server error" -> (exception as HttpException).code() == 500106 "Resource not found" -> (exception as HttpException).code() == 404107 else -> fail("Unexpected exception, $it")108 }109 }110 is SdkError.Generic -> exception is NullPointerException111 SdkError.TimeOut -> exception is SocketTimeoutException112 else -> fail("Unexpected exception, $it")113 }114 }115 true116 }117 }118})...

Full Screen

Full Screen

map.kt

Source:map.kt Github

copy

Full Screen

1package io.kotest.property.arbitrary2import io.kotest.property.Arb3import io.kotest.property.RandomSource4import io.kotest.property.Sample5import io.kotest.property.map6/**7 * Returns a new [Arb] which takes its elements from the receiver and maps them using the supplied function.8 */9fun <A, B> Arb<A>.map(fn: (A) -> B): Arb<B> = trampoline { sampleA ->10 object : Arb<B>() {11 override fun edgecase(rs: RandomSource): B? = fn(sampleA.value)12 override fun sample(rs: RandomSource): Sample<B> {13 val value = fn(sampleA.value)14 val shrinks = sampleA.shrinks.map(fn)15 return Sample(value, shrinks)16 }17 }18}19/**20 * Returns a new [Arb] which takes its elements from the receiver and maps them using the supplied function.21 */22fun <A, B> Arb<A>.flatMap(fn: (A) -> Arb<B>): Arb<B> = trampoline { fn(it.value) }23/**24 * Returns a new [TrampolineArb] from the receiver [Arb] which composes the operations of [next] lambda25 * using a trampoline method. This allows [next] function to be executed without exhausting call stack.26 */27internal fun <A, B> Arb<A>.trampoline(next: (Sample<A>) -> Arb<B>): Arb<B> = when (this) {28 is TrampolineArb -> this.thunk(next)29 else -> TrampolineArb(this).thunk(next)30}31/**32 * The [TrampolineArb] is a special Arb that exchanges call stack with heap.33 * In a nutshell, this arb stores command chains to be applied to the original arb inside a list.34 * This technique is an imperative reduction of Free Monads. This eliminates the need of creating intermediate35 * Trampoline Monad and tail-recursive function on those which can be expensive.36 * This minimizes the amount of code and unnecessary object allocation during sample generation in the expense of typesafety.37 *38 * This is an internal implementation. Do not use this TrampolineArb as is and please do not expose this39 * to users outside of the library. For library maintainers, please use the [Arb.trampoline] extension function.40 * The extension function will provide some type-guardrails to workaround the loss of types within this Arb.41 */42@Suppress("UNCHECKED_CAST")43internal class TrampolineArb<A> private constructor(44 private val first: Arb<A>,45 private val commands: List<(Sample<Any>) -> Arb<Any>>46) : Arb<A>() {47 constructor(first: Arb<A>) : this(first, emptyList())48 fun <A, B> thunk(fn: (Sample<A>) -> Arb<B>): TrampolineArb<B> =49 TrampolineArb(50 first,51 commands + (fn as (Sample<Any>) -> Arb<Any>)52 ) as TrampolineArb<B>53 override fun edgecase(rs: RandomSource): A? =54 commands55 .fold(first as Arb<Any>) { currentArb, next ->56 val currentEdge = currentArb.edgecase(rs) ?: currentArb.sample(rs).value57 next(Sample(currentEdge))58 }59 .edgecase(rs) as A?60 override fun sample(rs: RandomSource): Sample<A> =61 commands62 .fold(first as Arb<Any>) { currentArb, next ->63 next(currentArb.sample(rs))64 }65 .sample(rs) as Sample<A>66}...

Full Screen

Full Screen

filter.kt

Source:filter.kt Github

copy

Full Screen

1package io.kotest.property.arbitrary2import io.kotest.property.Arb3import io.kotest.property.PropertyTesting4import io.kotest.property.RTree5import io.kotest.property.RandomSource6import io.kotest.property.Sample7import io.kotest.property.filter8/**9 * Returns a new [Arb] which takes its elements from the receiver and filters them using the supplied10 * predicate. This gen will continue to request elements from the underlying gen until one satisfies11 * the predicate.12 */13fun <A> Arb<A>.filter(predicate: (A) -> Boolean): Arb<A> = trampoline { sampleA ->14 object : Arb<A>() {15 override fun edgecase(rs: RandomSource): A? =16 sequenceOf(sampleA.value)17 .plus(generateSequence { this@filter.edgecase(rs) })18 .take(PropertyTesting.maxFilterAttempts)19 .filter(predicate)20 .firstOrNull()21 override fun sample(rs: RandomSource): Sample<A> {22 val sample = sequenceOf(sampleA).plus(this@filter.samples(rs)).filter { predicate(it.value) }.first()23 return Sample(sample.value, sample.shrinks.filter(predicate) ?: RTree({ sample.value }))24 }25 }26}27/**28 * @return a new [Arb] by filtering this arbs output by the negated function [f]29 */30fun <A> Arb<A>.filterNot(f: (A) -> Boolean): Arb<A> = filter { !f(it) }31/**32 * Create a new [Arb] by keeping only instances of B generated by this gen.33 * This is useful if you have a type hierarchy and only want to retain34 * a particular subtype.35 */36@Suppress("UNCHECKED_CAST")37inline fun <A, reified B : A> Arb<A>.filterIsInstance(): Arb<B> = filter { it is B }.map { it as B }...

Full Screen

Full Screen

Arb.trampoline

Using AI Code Generation

copy

Full Screen

1val arb = Arb . trampoline ( Arb . int ( ) )2val arb = Arb . trampoline ( Arb . int ( ) )3val arb = Arb . trampoline ( Arb . int ( ) )4val arb = Arb . trampoline ( Arb . int ( ) )5val arb = Arb . trampoline ( Arb . int ( ) )6val arb = Arb . trampoline ( Arb . int ( ) )7val arb = Arb . trampoline ( Arb . int ( ) )

Full Screen

Full Screen

Arb.trampoline

Using AI Code Generation

copy

Full Screen

1val arbB = Arb.trampoline { arbA.map { a -> listOf(a) } }2arbB.generate(rs).take(100).forEach { println(it) }3val arbB = Arb.trampoline { arbA.map { a -> listOf(a) } }4arbB.generate(rs).take(100).forEach { println(it) }5val arbB = Arb.trampoline { arbA.map { a -> listOf(a) } }6arbB.generate(rs).take(100).forEach { println(it) }7val arbB = Arb.trampoline { arbA.map { a -> listOf(a) } }8arbB.generate(rs).take(100).forEach { println(it) }9val arbB = Arb.trampoline { arbA.map { a -> listOf(a) } }10arbB.generate(rs).take(100).forEach { println(it) }

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful