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

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

Generators.kt

Source:Generators.kt Github

copy

Full Screen

1package arrow.core.test.generators2import arrow.core.Const3import arrow.core.Either4import arrow.core.Endo5import arrow.core.Eval6import arrow.core.Ior7import arrow.core.Option8import arrow.core.Tuple109import arrow.core.Tuple410import arrow.core.Tuple511import arrow.core.Tuple612import arrow.core.Tuple713import arrow.core.Tuple814import arrow.core.Tuple915import arrow.core.Validated16import arrow.core.left17import arrow.core.right18import arrow.core.toOption19import io.kotest.property.Arb20import io.kotest.property.arbitrary.bind21import io.kotest.property.arbitrary.boolean22import io.kotest.property.arbitrary.byte23import io.kotest.property.arbitrary.choice24import io.kotest.property.arbitrary.constant25import io.kotest.property.arbitrary.filter26import io.kotest.property.arbitrary.flatMap27import io.kotest.property.arbitrary.int28import io.kotest.property.arbitrary.long29import io.kotest.property.arbitrary.map30import io.kotest.property.arbitrary.numericDoubles31import io.kotest.property.arbitrary.numericFloats32import io.kotest.property.arbitrary.of33import io.kotest.property.arbitrary.orNull34import io.kotest.property.arbitrary.short35import io.kotest.property.arbitrary.string36import kotlin.Result.Companion.failure37import kotlin.Result.Companion.success38import kotlin.math.abs39public fun <A, B> Arb.Companion.functionAToB(arb: Arb<B>): Arb<(A) -> B> =40  arb.map { b: B -> { _: A -> b } }41public fun <A> Arb.Companion.functionAAToA(arb: Arb<A>): Arb<(A, A) -> A> =42  arb.map { a: A -> { _: A, _: A -> a } }43public fun <A, B> Arb.Companion.functionBAToB(arb: Arb<B>): Arb<(B, A) -> B> =44  arb.map { b: B -> { _: B, _: A -> b } }45public fun <A, B> Arb.Companion.functionABToB(arb: Arb<B>): Arb<(A, B) -> B> =46  arb.map { b: B -> { _: A, _: B -> b } }47public fun <A> Arb.Companion.functionToA(arb: Arb<A>): Arb<() -> A> =48  arb.map { a: A -> { a } }49public fun Arb.Companion.throwable(): Arb<Throwable> =50  Arb.of(listOf(RuntimeException(), NoSuchElementException(), IllegalArgumentException()))51public fun <A> Arb.Companion.result(arbA: Arb<A>): Arb<Result<A>> =52  Arb.choice(arbA.map(::success), throwable().map(::failure))53public fun Arb.Companion.doubleSmall(): Arb<Double> =54  Arb.numericDoubles(from = 0.0, to = 100.0)55public fun Arb.Companion.floatSmall(): Arb<Float> =56  Arb.numericFloats(from = 0F, to = 100F)57public fun Arb.Companion.intSmall(factor: Int = 10000): Arb<Int> =58  Arb.int((Int.MIN_VALUE / factor)..(Int.MAX_VALUE / factor))59public fun Arb.Companion.byteSmall(): Arb<Byte> =60  Arb.byte(min = (Byte.MIN_VALUE / 10).toByte(), max = (Byte.MAX_VALUE / 10).toByte())61public fun Arb.Companion.shortSmall(): Arb<Short> {62  val range = (Short.MIN_VALUE / 1000)..(Short.MAX_VALUE / 1000)63  return Arb.short().filter { it in range }64}65public fun Arb.Companion.longSmall(): Arb<Long> =66  Arb.long((Long.MIN_VALUE / 100000L)..(Long.MAX_VALUE / 100000L))67public fun <A, B, C, D> Arb.Companion.tuple4(arbA: Arb<A>, arbB: Arb<B>, arbC: Arb<C>, arbD: Arb<D>): Arb<Tuple4<A, B, C, D>> =68  Arb.bind(arbA, arbB, arbC, arbD, ::Tuple4)69public fun <A, B, C, D, E> Arb.Companion.tuple5(70  arbA: Arb<A>,71  arbB: Arb<B>,72  arbC: Arb<C>,73  arbD: Arb<D>,74  arbE: Arb<E>75): Arb<Tuple5<A, B, C, D, E>> =76  Arb.bind(arbA, arbB, arbC, arbD, arbE, ::Tuple5)77public fun <A, B, C, D, E, F> Arb.Companion.tuple6(78  arbA: Arb<A>,79  arbB: Arb<B>,80  arbC: Arb<C>,81  arbD: Arb<D>,82  arbE: Arb<E>,83  arbF: Arb<F>84): Arb<Tuple6<A, B, C, D, E, F>> =85  Arb.bind(arbA, arbB, arbC, arbD, arbE, arbF, ::Tuple6)86public fun <A, B, C, D, E, F, G> Arb.Companion.tuple7(87  arbA: Arb<A>,88  arbB: Arb<B>,89  arbC: Arb<C>,90  arbD: Arb<D>,91  arbE: Arb<E>,92  arbF: Arb<F>,93  arbG: Arb<G>94): Arb<Tuple7<A, B, C, D, E, F, G>> =95  Arb.bind(arbA, arbB, arbC, arbD, arbE, arbF, arbG, ::Tuple7)96public fun <A, B, C, D, E, F, G, H> Arb.Companion.tuple8(97  arbA: Arb<A>,98  arbB: Arb<B>,99  arbC: Arb<C>,100  arbD: Arb<D>,101  arbE: Arb<E>,102  arbF: Arb<F>,103  arbG: Arb<G>,104  arbH: Arb<H>105): Arb<Tuple8<A, B, C, D, E, F, G, H>> =106  Arb.bind(107    Arb.tuple7(arbA, arbB, arbC, arbD, arbE, arbF, arbG),108    arbH109  ) { (a, b, c, d, e, f, g), h ->110    Tuple8(a, b, c, d, e, f, g, h)111  }112public fun <A, B, C, D, E, F, G, H, I> Arb.Companion.tuple9(113  arbA: Arb<A>,114  arbB: Arb<B>,115  arbC: Arb<C>,116  arbD: Arb<D>,117  arbE: Arb<E>,118  arbF: Arb<F>,119  arbG: Arb<G>,120  arbH: Arb<H>,121  arbI: Arb<I>122): Arb<Tuple9<A, B, C, D, E, F, G, H, I>> =123  Arb.bind(124    Arb.tuple8(arbA, arbB, arbC, arbD, arbE, arbF, arbG, arbH),125    arbI126  ) { (a, b, c, d, e, f, g, h), i ->127    Tuple9(a, b, c, d, e, f, g, h, i)128  }129public fun <A, B, C, D, E, F, G, H, I, J> Arb.Companion.tuple10(130  arbA: Arb<A>,131  arbB: Arb<B>,132  arbC: Arb<C>,133  arbD: Arb<D>,134  arbE: Arb<E>,135  arbF: Arb<F>,136  arbG: Arb<G>,137  arbH: Arb<H>,138  arbI: Arb<I>,139  arbJ: Arb<J>140): Arb<Tuple10<A, B, C, D, E, F, G, H, I, J>> =141  Arb.bind(142    Arb.tuple9(arbA, arbB, arbC, arbD, arbE, arbF, arbG, arbH, arbI),143    arbJ144  ) { (a, b, c, d, e, f, g, h, i), j ->145    Tuple10(a, b, c, d, e, f, g, h, i, j)146  }147public fun Arb.Companion.nonZeroInt(): Arb<Int> = Arb.int().filter { it != 0 }148public fun Arb.Companion.intPredicate(): Arb<(Int) -> Boolean> =149  Arb.nonZeroInt().flatMap { num ->150    val absNum = abs(num)151    Arb.of(152      listOf<(Int) -> Boolean>(153        { it > num },154        { it <= num },155        { it % absNum == 0 },156        { it % absNum == absNum - 1 }157      )158    )159  }160public fun <A> Arb.Companion.endo(arb: Arb<A>): Arb<Endo<A>> = arb.map { a: A -> Endo<A> { a } }161public fun <B> Arb.Companion.option(arb: Arb<B>): Arb<Option<B>> =162  arb.orNull().map { it.toOption() }163public fun <E, A> Arb.Companion.either(arbE: Arb<E>, arbA: Arb<A>): Arb<Either<E, A>> {164  val arbLeft = arbE.map { Either.Left(it) }165  val arbRight = arbA.map { Either.Right(it) }166  return Arb.choice(arbLeft, arbRight)167}168public fun <E, A> Arb<E>.or(arbA: Arb<A>): Arb<Either<E, A>> = Arb.either(this, arbA)169public fun <E, A> Arb.Companion.validated(arbE: Arb<E>, arbA: Arb<A>): Arb<Validated<E, A>> =170  Arb.either(arbE, arbA).map { Validated.fromEither(it) }171public fun Arb.Companion.unit(): Arb<Unit> =172  Arb.constant(Unit)173public fun <A, B> Arb.Companion.ior(arbA: Arb<A>, arbB: Arb<B>): Arb<Ior<A, B>> =174  arbA.alignWith(arbB) { it }175public fun <A, B> Arb.Companion.arbConst(arb: Arb<A>): Arb<Const<A, B>> =176  arb.map { Const<A, B>(it) }177public fun <A> Arb<A>.eval(): Arb<Eval<A>> =178  map { Eval.now(it) }179private fun <A, B, R> Arb<A>.alignWith(arbB: Arb<B>, transform: (Ior<A, B>) -> R): Arb<R> =180  Arb.bind(this, arbB) { a, b -> transform(Ior.Both(a, b)) }181public fun Arb.Companion.suspendFunThatReturnsEitherAnyOrAnyOrThrows(): Arb<suspend () -> Either<Any, Any>> =182  choice(183    suspendFunThatReturnsAnyRight(),184    suspendFunThatReturnsAnyLeft(),185    suspendFunThatThrows()186  )187public fun Arb.Companion.suspendFunThatReturnsAnyRight(): Arb<suspend () -> Either<Any, Any>> =188  any().map { suspend { it.right() } }189public fun Arb.Companion.suspendFunThatReturnsAnyLeft(): Arb<suspend () -> Either<Any, Any>> =190  any().map { suspend { it.left() } }191public fun Arb.Companion.suspendFunThatThrows(): Arb<suspend () -> Either<Any, Any>> =192  throwable().map { suspend { throw it } } as Arb<suspend () -> Either<Any, Any>>193public fun Arb.Companion.any(): Arb<Any> =194  choice(195    Arb.string() as Arb<Any>,196    Arb.int() as Arb<Any>,197    Arb.long() as Arb<Any>,198    Arb.boolean() as Arb<Any>,199    Arb.throwable() as Arb<Any>,200    Arb.unit() as Arb<Any>201  )...

Full Screen

Full Screen

ArrayStoreTests.kt

Source:ArrayStoreTests.kt Github

copy

Full Screen

1package edu.rice.fset2import io.kotest.core.spec.style.FreeSpec3import io.kotest.matchers.shouldBe4import io.kotest.property.Arb5import io.kotest.property.arbitrary.arbitrary6import io.kotest.property.arbitrary.int7import io.kotest.property.arbitrary.list8import io.kotest.property.arbitrary.map9import io.kotest.property.arbitrary.next10import io.kotest.property.checkAll11internal val listIntWithIndex = arbitrary { rs ->12    val length = Arb.int(1, 10).next(rs)13    val list = Arb.list(Arb.int(0, 10000), length..length).next(rs)14    val query = Arb.int(0, length - 1).next(rs)15    Pair(list, query)16}17internal val listKVWithIndex = arbitrary { rs ->18    val length = Arb.int(1, 10).next(rs)19    val list = Arb.list(20        Arb.int(0, 10000)21            .map { kv(it.toString(), it.toString().length) },22        length..length23    )24        .next(rs)25    val query = Arb.int(0, length - 1).next(rs)26    Pair(list, query)27}28class ArrayStoreTests : FreeSpec({29    "basic equality" {30        checkAll(listIntWithIndex) { (list, _) ->31            val as1 = list.toArrayStore()32            val as2 = list.toArrayStore()33            list shouldBe as1.toList()34            as1.deepEquals(as2) shouldBe true35            as1.hashCode() shouldBe as2.hashCode()36        }37    }38    "getting" {39        checkAll(listIntWithIndex) { (list, query) ->40            val as1 = list.toArrayStore()41            as1[query] shouldBe list.get(query)42        }43    }44    "withoutIndex" {45        checkAll(listIntWithIndex) { (list, query) ->46            val as1 = list.toArrayStore()47            as1.withoutIndex(query)48                .toList() shouldBe list.filterIndexed { index, _ -> query != index }49        }50    }51    "withoutElement" {52        checkAll(listIntWithIndex) { (list, query) ->53            val as1 = list.toArrayStore()54            // might be multiple copies; we're checking that withoutElement removes the first of them55            val firstOffsetOf = list.indexOf(list[query])56            as1.withoutElement(as1[firstOffsetOf])57                .toList() shouldBe list.filterIndexed { index, _ -> firstOffsetOf != index }58        }59    }60    "updateElement" {61        checkAll(listKVWithIndex) { (list, query) ->62            val as1 = list.toArrayStore()63            val firstOffsetOf = list.indexOf(list[query])64            val updateVal = kv(65                list[query].key,66                -list[query].value67            ) // keys are still equal, values are different68            val as2 = as1.updateElement(updateVal)69            as2.deepEquals(as2) shouldBe true70            as2[firstOffsetOf].key shouldBe as1[firstOffsetOf].key71            as2[firstOffsetOf].value shouldBe -as1[firstOffsetOf].value72            // now, we'll try something that's not there73            as1.updateElement(kv("-5", 5)).deepEquals(as1) shouldBe true74        }75    }76    "updateOffset" {77        checkAll(listIntWithIndex) { (list, query) ->78            val as1 = list.toArrayStore()79            val as2 = as1.updateOffset(query, -5)80            val expected = list.subList(0, query) + (-5) + (list.subList(query + 1, list.size))81            as2.toList() shouldBe expected82        }83    }84    "contains and find" {85        checkAll(listIntWithIndex) { (list, query) ->86            val as1 = list.toArrayStore()87            as1.contains(list[query]) shouldBe true88            as1.contains(-5) shouldBe false89            as1.find(list[query]) shouldBe list[query]90            as1.find(-5) shouldBe null91        }92    }93    "insert" {94        checkAll(listIntWithIndex) { (list, query) ->95            val as1 = list.toArrayStore()96            val as2 = as1.insert(-5, query)97            as2.size() shouldBe list.size + 198            as2.toList() shouldBe list.subList(0, query) + (-5) + list.subList(query, list.size)99        }100    }101    "mapIndexed" {102        checkAll(listIntWithIndex) { (list, _) ->103            val as1 = list.toArrayStore()104            val as2 = as1.mapIndexed { index, value -> index + value }105            as2.toList() shouldBe list.mapIndexed { index, value -> index + value }106        }107    }108    "append" {109        checkAll(listIntWithIndex) { (list, _) ->110            val as1 = list.toArrayStore()111            val as2 = as1.append(-5)112            as2.toList() shouldBe list + (-5)113        }114    }115    "flatMap" {116        checkAll(listIntWithIndex) { (list, _) ->117            val as1 = list.toArrayStore()118            as1.flatMap {119                sequenceOf("<", it.toString(), ">")120            }.toList() shouldBe list.flatMap {121                sequenceOf("<", it.toString(), ">")122            }.toList()123        }124    }125    "joinToString" {126        checkAll(listIntWithIndex) { (list, _) ->127            val as1 = list.toArrayStore()128            as1.joinToString(", ") shouldBe list.joinToString(separator = ", ")129        }130    }131    "toSet" {132        checkAll(listIntWithIndex) { (list, _) ->133            val as1 = list.toArrayStore()134            as1.toSet() shouldBe list.toSet()135        }136    }137})...

Full Screen

Full Screen

ValidatedTest.kt

Source:ValidatedTest.kt Github

copy

Full Screen

1package com.github.kold.validated2import io.kotest.core.spec.style.WordSpec3import io.kotest.matchers.shouldBe4import io.kotest.matchers.types.shouldBeSameInstanceAs5import io.kotest.property.Arb6import io.kotest.property.arbitrary.choice7import io.kotest.property.arbitrary.int8import io.kotest.property.arbitrary.list9import io.kotest.property.arbitrary.string10import io.kotest.property.checkAll11class ValidatedTest : WordSpec() {12    init {13        "Validated.flatMap" should {14            "transform value when Valid" {15                checkAll(validArb(Arb.string())) { valid ->16                    valid.flatMap {17                        Validated.Valid(it.toUpperCase())18                    } shouldBe Validated.Valid(valid.value.toUpperCase())19                }20            }21            "transform value when Valid but result is invalid" {22                checkAll(validArb(Arb.string()), invalidArb<Int>()) { valid, invalid ->23                    valid.flatMap {24                        invalid25                    } shouldBe invalid26                }27            }28            "doesn't modify Invalid" {29                checkAll(30                    invalidArb<Int>(),31                    Arb.choice<Validated<Int>>(validArb(Arb.int()), invalidArb<Int>())32                ) { invalid, transformation ->33                    invalid.flatMap {34                        transformation35                    } shouldBeSameInstanceAs (invalid)36                }37            }38        }39        "Validated.fold" should {40            "call onValid for Valid" {41                checkAll(validArb(Arb.string())) { valid ->42                    val value = valid.fold(43                        onValid = {44                            valid.value.toUpperCase()45                        },46                        onInvalid = {47                            throw Exception()48                        }49                    )50                    value shouldBe valid.value.toUpperCase()51                }52            }53            "call onInvalid for Invalid" {54                checkAll(Arb.string(), invalidArb<Int>()) { value, invalid ->55                    val expected = invalid.fold(56                        onValid = {57                            throw Exception()58                        },59                        onInvalid = {60                            value61                        }62                    )63                    expected shouldBe expected64                }65            }66        }67        "Validated.orNull" should {68            "return value for Valid" {69                checkAll(validArb(Arb.string())) { valid ->70                    val value = valid.orNull()71                    value shouldBe valid.value72                }73            }74            "return null for Invalid" {75                checkAll(invalidArb<Int>()) { invalid ->76                    val value = invalid.orNull()77                    value shouldBe null78                }79            }80        }81        "Validated.Invalid.flatten" should {82            "combine flatten results from each violation" {83                checkAll(Arb.list(violationArb(), 1..10), Arb.string(), Arb.string()) { violations, separator, suffix ->84                    val expected = violations.flatMap {85                        it.flatten(fieldNameSeparator = separator, arraySuffix = suffix)86                    }.toSet()87                    Validated.Invalid<Any>(violations)88                        .flatten(fieldNameSeparator = separator, arraySuffix = suffix) shouldBe expected89                }90            }91            "combine flatten results from each violation with default args" {92                checkAll(Arb.list(violationArb(), 1..10)) { violations ->93                    val expected = violations.flatMap {94                        it.flatten()95                    }.toSet()96                    Validated.Invalid<Any>(violations)97                        .flatten() shouldBe expected98                }99            }100        }101        "T.valid" should {102            "wrap T into Valid" {103                checkAll(Arb.string()) { value ->104                    value.valid() shouldBe Validated.Valid(value)105                }106            }107        }108        "Violation.invalid" should {109            "wrap Violation into Invalid" {110                checkAll(violationArb()) { violation ->111                    violation.invalid<Any>() shouldBe Validated.Invalid(listOf(violation))112                }113            }114        }115    }116}...

Full Screen

Full Screen

TestCodeGenerators.kt

Source:TestCodeGenerators.kt Github

copy

Full Screen

1import io.kotest.property.Arb2import io.kotest.property.Exhaustive3import io.kotest.property.arbitrary.bind4import io.kotest.property.arbitrary.list5import io.kotest.property.arbitrary.take6import io.kotest.property.exhaustive.azstring7import io.kotest.property.exhaustive.collection8import konnekt.HeadersDeclaration9import konnekt.MimeEncodingsDeclaration10import konnekt.SourcesDeclaration11import konnekt.names12import konnekt.prelude.FormUrlEncoded13import konnekt.prelude.Multipart14fun functions(source: SourcesDeclaration): List<String> {15  val annotations = annotationVariants(source)16  return when (source) {17    SourcesDeclaration.PATH -> annotations.mapIndexed { i, annotation ->18      """|@GET("/test/{p}")19         |suspend fun test${source.name}$i($annotation r: Int): String""".trimMargin()20    }21    SourcesDeclaration.BODY, SourcesDeclaration.QUERY, SourcesDeclaration.PART, SourcesDeclaration.FIELD, SourcesDeclaration.HEADER -> annotations.mapIndexed { i, annotation ->22      """|${source.optInAnnotation()}23         |@GET("/test")24         |suspend fun test${source.name}$i($annotation r: Int): String""".trimMargin()25    }26  }27}28fun headerFunctions(): Iterable<String> {29  val annotations = headerAnnotationVariants.take(50)30  return annotations.mapIndexed { i, annotation ->31    """|@GET("/test")32       |$annotation33       |suspend fun testHEADERS_$i(): String""".trimMargin()34  }.asIterable()35}36fun mimeEncodingFunctions(encoding: MimeEncodingsDeclaration): Iterable<String> {37  val annotations = encoding.names.map { "@$it" }38  return annotations.mapIndexed { i, annotation ->39    """|$annotation40       |@GET("/test")41       |suspend fun testMIME_ENCODING_$i(): String""".trimMargin()42  }43}44private fun annotationVariants(it: SourcesDeclaration): List<String> {45  return when (it) {46    SourcesDeclaration.BODY -> it.names.map { "@$it" }47    SourcesDeclaration.PATH -> (it.names product listOf("\"p\"").named("value"))48        .let { oneArg ->49          val stringOnly = oneArg.map { (name, str) -> "@$name($str)" }50          val complete = (oneArg product booleanLiterals.named("encoded")).map { (name, str, bool) -> "@$name($str, $bool)" }51          stringOnly + complete52        }53    SourcesDeclaration.QUERY, SourcesDeclaration.FIELD -> (it.names product stringLiterals.named("value"))54        .let { oneArg ->55          val stringOnly = oneArg.map { (name, str) -> "@$name($str)" }56          val complete = (oneArg product booleanLiterals.named("encoded")).map { (name, str, bool) -> "@$name($str, $bool)" }57          stringOnly + complete58        }59    SourcesDeclaration.PART, SourcesDeclaration.HEADER -> (it.names product stringLiterals.named("value"))60        .map { (name, str) -> "@$name($str)" }61  }62}63private fun SourcesDeclaration.optInAnnotation(): String {64  val name = when (this) {65    SourcesDeclaration.PART -> Multipart::class.java.simpleName66    SourcesDeclaration.FIELD -> FormUrlEncoded::class.java.simpleName67    else -> null68  }69  return name?.let { "@$it" } ?: ""70}71private val headerAnnotationVariants = Arb.bind(72    Exhaustive.collection(HeadersDeclaration.names),73    Arb.list(Exhaustive.azstring(1..10).toArb())74) { name, args ->75  val varargs = args.joinToString(", "){ "\"$it\"" }76  "@$name($varargs)"77}78private val stringLiterals = listOf(""""p"""", "\"\"")79private val booleanLiterals = listOf("true", "false")80infix fun <T, E> List<T>.product(other: List<E>): List<Pair<T, E>> {81  return flatMap { l -> other.map { r -> l to r  } }82}83@JvmName("productTriple")84infix fun <T, E, L> List<Pair<T, E>>.product(other: List<L>): List<Triple<T, E, L>> {85  return flatMap { (l1, l2) -> other.map { r -> Triple(l1, l2, r)  } }86}87private fun List<String>.named(name: String): List<Argument> = flatMap {88  listOf(Argument(it, null), Argument(it, name))89}90data class Argument(val value: String, val name: String? = null) {91  override fun toString(): String =92      if (name != null) {93        "$name = $value"94      } else {95        value96      }97}...

Full Screen

Full Screen

cluedo.kt

Source:cluedo.kt Github

copy

Full Screen

1package io.kotest.property.arbs.games2import io.kotest.property.Arb3import io.kotest.property.arbitrary.arbitrary4import io.kotest.property.arbitrary.flatMap5import io.kotest.property.arbitrary.of6data class CluedoSuspect(val name: String) {7  companion object {8    val all = listOf(9      CluedoSuspect("Colonel Mustard"),10      CluedoSuspect("Miss Scarlett"),11      CluedoSuspect("Mrs. Peacock"),12      CluedoSuspect("Mrs. White"),13      CluedoSuspect("Reverend Green"),14      CluedoSuspect("Professor Plum"),15    )16  }17}18data class CluedoWeapon(val name: String) {19  companion object {20    val all = listOf(21      CluedoWeapon("Revolver"),22      CluedoWeapon("Dagger"),23      CluedoWeapon("Spanner"),24      CluedoWeapon("Rope"),25      CluedoWeapon("Lead Piping"),26      CluedoWeapon("Candlestick"),27    )28  }29}30data class CluedoLocation(val name: String) {31  companion object {32    val all = listOf(33      CluedoLocation("Ballroom"),34      CluedoLocation("Billiard Room"),35      CluedoLocation("Conservatory"),36      CluedoLocation("Dining Room"),37      CluedoLocation("Hall"),38      CluedoLocation("Library"),39      CluedoLocation("Lounge"),40      CluedoLocation("Kitchen"),41      CluedoLocation("Study"),42    )43  }44}45data class CluedoAccusation(46  val suspect: CluedoSuspect,47  val weapon: CluedoWeapon,48  val location: CluedoLocation,49  val correctGuess: Boolean,50)51fun Arb.Companion.cluedoSuspects() = Arb.of(CluedoSuspect.all)52fun Arb.Companion.cluedoWeapons() = Arb.of(CluedoWeapon.all)53fun Arb.Companion.cluedoLocations() = Arb.of(CluedoLocation.all)54fun Arb.Companion.cluedoAccusations() = cluedoSuspects().flatMap { suspect ->55  cluedoWeapons().flatMap { weapon ->56    cluedoLocations().flatMap { location ->57      arbitrary {58        CluedoAccusation(suspect, weapon, location, it.random.nextDouble() < 0.05)59      }60    }61  }62}...

Full Screen

Full Screen

wine.kt

Source:wine.kt Github

copy

Full Screen

1package io.kotest.property.arbs.wine2import io.kotest.property.Arb3import io.kotest.property.arbitrary.flatMap4import io.kotest.property.arbitrary.map5import io.kotest.property.arbitrary.of6import io.kotest.property.arbitrary.take7import io.kotest.property.arbs.Name8import io.kotest.property.arbs.loadResourceAsLines9import io.kotest.property.arbs.name10import kotlin.random.Random11private val vineyards = lazy { loadResourceAsLines("/wine/vineyards.txt") }12private val regions = lazy { loadResourceAsLines("/wine/region.txt") }13private val wineries = lazy { loadResourceAsLines("/wine/winery.txt") }14private val varities = lazy { loadResourceAsLines("/wine/variety.txt") }15fun Arb.Companion.vineyards() = Arb.of(vineyards.value).map { Vineyard(it) }16fun Arb.Companion.wineRegions() = Arb.of(regions.value).map { WineRegion(it) }17fun Arb.Companion.wineries() = Arb.of(wineries.value).map { Winery(it) }18fun Arb.Companion.wineVarities() = Arb.of(varities.value).map { WineVariety(it) }19fun Arb.Companion.wines() = vineyards().flatMap { vineyard ->20  wineRegions().flatMap { region ->21    wineVarities().flatMap { variety ->22      wineries().map { winery ->23        Wine(vineyard, variety, winery, region, Random.nextInt(1920, 2020))24      }25    }26  }27}28fun Arb.Companion.wineReviews() = wines().  flatMap { wine ->29  name().map { name ->30    WineReview(wine, Random.nextDouble(0.1, 5.0), name)31  }32}33fun main() {34  Arb.wineReviews().take(100).forEach(::println)35}36data class Wine(37  val vineyard: Vineyard,38  val variety: WineVariety,39  val winery: Winery,40  val region: WineRegion,41  val year: Int42)43data class WineReview(val wine: Wine, val rating: Double, val name: Name)44data class Vineyard(val value: String)45data class WineVariety(val value: String)46data class Winery(val value: String)47data class WineRegion(val value: String)...

Full Screen

Full Screen

ResourceSpec.kt

Source:ResourceSpec.kt Github

copy

Full Screen

1package io.kotest.assertions.arrow.fx.coroutines2import arrow.fx.coroutines.ExitCase3import arrow.fx.coroutines.Resource4import io.kotest.core.spec.style.StringSpec5import io.kotest.matchers.shouldBe6import io.kotest.property.Arb7import io.kotest.property.arbitrary.int8import io.kotest.property.checkAll9import kotlinx.coroutines.CompletableDeferred10import io.kotest.matchers.collections.shouldContainExactly11import io.kotest.property.arbitrary.negativeInt12import io.kotest.property.arbitrary.positiveInt13class ResourceSpec : StringSpec({14  "resolves resource" {15    checkAll(Arb.int()) { n ->16      val r: Int by resource(Resource({ n }, { _, _ -> Unit }))17      (r + 1) shouldBe n + 118    }19  }20  "value resource is released with Completed" {21    checkAll(Arb.int()) { n: Int ->22      val p = CompletableDeferred<ExitCase>()23      val nn: Int by resource(Resource({ n }, { _, ex -> p.complete(ex) }))24      nn shouldBe n25      afterSpec {26        p.await().shouldBeCompleted()27      }28    }29  }30  "flatMap resource is released first" {31    checkAll(Arb.positiveInt(), Arb.negativeInt()) { a, b ->32      val l = mutableListOf<Int>()33      fun r(n: Int) = Resource({ n.also(l::add) }, { it, _ -> l.add(-it) })34      val c by resource(r(a).flatMap { r(it + b) })35      c shouldBe a + b36      afterSpec {37        l.shouldContainExactly(a, a + b, -a - b, -a)38      }39    }40  }41})...

Full Screen

Full Screen

LensPropertiesTest.kt

Source:LensPropertiesTest.kt Github

copy

Full Screen

1package it.twinsbrain.funkt.optics.lenses2import io.kotest.core.spec.style.StringSpec3import io.kotest.property.Arb4import io.kotest.property.arbitrary.arbitrary5import io.kotest.property.arbitrary.flatMap6import io.kotest.property.arbitrary.int7import io.kotest.property.arbitrary.map8import io.kotest.property.arbitrary.string9import io.kotest.property.forAll10class LensPropertiesTest : StringSpec({11    "modify" {12        forAll(personGenerator) { person ->13            val lens = Person.address.number14            val previousNumber = person.address.number15            val newPerson = lens.modify(person) { "43" }16            person.address.number == previousNumber &&17                newPerson.address.number == "43"18        }19    }20})21private val addressGenerator = arbitrary {22    val streetName = Arb.string(size = 30).bind()23    val city = Arb.string(size = 30).bind()24    val number = Arb.int(min = 1, max = 400).bind()25    Address(streetName, number.toString(), city)26}27private val personGenerator = addressGenerator.flatMap { address ->28    Arb.string(size = 30).map { name ->29        Person(name, address)30    }31}...

Full Screen

Full Screen

Arb.flatMap

Using AI Code Generation

copy

Full Screen

1    import io.kotest.property.arbitrary.flatMap2    import io.kotest.property.arbitrary.map3    import io.kotest.property.arbitrary.string4    import io.kotest.property.arbitrary.int5    import io.kotest.property.arbitrary.bind6    import io.kotest.property.arbitrary.choice7    import io.kotest.property.arbitrary.filter8    import io.kotest.property.arbitrary.list9    import io.kotest.property.arbitrary.double10    import io.kotest.property.arbitrary.constant

Full Screen

Full Screen

Arb.flatMap

Using AI Code Generation

copy

Full Screen

1    fun <A, B, C> flatMap(2       f: (A) -> Arb<B>,3       g: (A, B) -> C4    ): Arb<C> = map(f, g).flatMap { it }5    fun <A, B, C, D> flatMap(6       f: (A) -> Arb<B>,7       g: (A, B) -> Arb<C>,8       h: (A, B, C) -> D9    ): Arb<D> = map(f, g, h).flatMap { it }10    fun <A, B, C, D, E> flatMap(11       f: (A) -> Arb<B>,12       g: (A, B) -> Arb<C>,13       h: (A, B, C) -> Arb<D>,14       i: (A, B, C, D) -> E15    ): Arb<E> = map(f, g, h, i).flatMap { it }16    fun <A, B, C, D, E, F> flatMap(17       f: (A) -> Arb<B>,18       g: (A, B) -> Arb<C>,19       h: (A, B, C) -> Arb<D>,20       i: (A, B, C, D) -> Arb<E>,21       j: (A, B, C, D, E) -> F22    ): Arb<F> = map(f, g, h, i, j).flatMap { it }23    fun <A, B, C, D, E, F, G> flatMap(24       f: (A) -> Arb<B>,25       g: (A, B) -> Arb<C>,26       h: (A, B, C) -> Arb<D>,27       i: (A, B, C, D) -> Arb<E>,28       j: (A, B, C, D, E) -> Arb<F>,29       k: (A, B, C, D, E, F) -> G

Full Screen

Full Screen

Arb.flatMap

Using AI Code Generation

copy

Full Screen

1@JvmName ( "flatMap" )2fun < A , B > Arb < A > . flatMap ( f : ( A ) -> Arb < B > ) : Arb < B > = map ( f ). flatten ()3@JvmName ( "flatten" )4fun < A > Arb < Arb < A > > . flatten () : Arb < A > = object : Arb < A > {5override fun edgecases () : List < A > = emptyList ()6override fun values ( config : PropertyTestingConfig ) : Gen < Sequence < A > > = this . values ( config ). map { it . values ( config )}7}8@JvmName ( "map" )9fun < A , B > Arb < A > . map ( f : ( A ) -> B ) : Arb < B > = object : Arb < B > {10override fun edgecases () : List < B > = this @map . edgecases (). map ( f )11override fun values ( config : PropertyTestingConfig ) : Gen < Sequence < B > > = this @map . values ( config ). map { it . map ( f )}12}13@JvmName ( "map" )14fun < A , B > Arb < A > . map ( f : ( A ) -> Gen < B > ) : Arb < B > = object : Arb < B > {15override fun edgecases () : List < B > = emptyList ()16override fun values ( config : PropertyTestingConfig ) : Gen < Sequence < B > > = this @map . values ( config ). map { it . flatMap ( f )}17}18@JvmName ( "map" )

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