How to use edgecases class of io.kotest.property.arbitrary package

Best Kotest code snippet using io.kotest.property.arbitrary.edgecases

Arb.kt

Source:Arb.kt Github

copy

Full Screen

...23  range: IntRange = 0..10024): Arb<Array<A>> {25  check(!range.isEmpty())26  check(range.first >= 0)27  return arb(edgecases = listOf(emptyArray<A>()) + gen.edgecases().map { arrayOf(it) }) {28    sequence {29      val genIter = gen.generate(it).iterator()30      while (true) {31        val targetSize = it.random.nextInt(range)32        val list = ArrayList<A>(targetSize)33        while (list.size < targetSize && genIter.hasNext()) {34          list.add(genIter.next().value)35        }36        check(list.size == targetSize)37        yield(list.toArray() as Array<A>)38      }39    }40  }41}42@PublishedApi43internal fun <A, B> arrayChunkGenerator(44  arb: Arb<A>,45  shrinker: Shrinker<B>,46  range: IntRange = 0..10,47  build: (values: List<A>, offset: Int, length: Int) -> B48): Arb<B> {49  check(!range.isEmpty())50  check(range.first >= 0)51  val edgecases =52    arb.edgecases().map { a -> build(listOf(a), 0, 1) } + build(emptyList(), 0, 0)53  return arb(edgecases, shrinker) {54    val genIter = arb.generate(it).iterator()55    sequence {56      while (true) {57        val targetSize = it.random.nextInt(range)58        val list = ArrayList<A>(targetSize)59        while (list.size < targetSize && genIter.hasNext()) {60          list.add(genIter.next().value)61        }62        val offset = (0..list.size).random(it.random)63        val length = (0..(list.size - offset)).random(it.random)64        yield(build(list, offset, length))65      }66    }67  }68}69class ChunkShrinker<A> : Shrinker<Chunk<A>> {70  override fun shrink(value: Chunk<A>): List<Chunk<A>> =71    if (value.isEmpty()) emptyList()72    else listOf(73      Chunk.empty(),74      value.takeLast(1),75      value.take(value.size() / 3),76      value.take(value.size() / 2),77      value.take(value.size() * 2 / 3),78      value.dropLast(1)79    )80}81inline fun <reified A> Arb.Companion.chunk(arb: Arb<A>): Arb<Chunk<A>> =82  object : Arb<Chunk<A>>() {83    override fun edgecases(): List<Chunk<A>> =84      listOf(Chunk.empty<A>()) + arb.edgecases().map { Chunk(it) }85    override fun values(rs: RandomSource): Sequence<Sample<Chunk<A>>> =86      Arb.choose(87        5 to arb.map { Chunk.just(it) },88        10 to Arb.list(arb, 0..20).map { Chunk.iterable(it) },89        10 to Arb.set(arb, 0..20).map { Chunk.iterable(it) },90        10 to Arb.array(arb, 0..20).map { Chunk.array(it) },91        10 to Arb.boxedChunk(arb)92      ).values(rs)93  }94inline fun <reified A> Arb.Companion.boxedChunk(arb: Arb<A>): Arb<Chunk<A>> =95  object : Arb<Chunk<A>>() {96    override fun edgecases(): List<Chunk<A>> =97      listOf(Chunk.empty<A>()) + arb.edgecases().map { Chunk(it) }98    override fun values(rs: RandomSource): Sequence<Sample<Chunk<A>>> =99      arrayChunkGenerator(arb, ChunkShrinker()) { values, offset, length ->100        Chunk.boxed(values.toTypedArray(), offset, length)101      }.values(rs)102  }103fun Arb.Companion.booleanChunk(): Arb<Chunk<Boolean>> =104  object : Arb<Chunk<Boolean>>() {105    override fun edgecases(): List<Chunk<Boolean>> =106      listOf(Chunk.empty<Boolean>()) + Arb.bool().edgecases().map { Chunk(it) }107    override fun values(rs: RandomSource): Sequence<Sample<Chunk<Boolean>>> =108      Arb.choice(109        arrayChunkGenerator(Arb.bool(), ChunkShrinker()) { values, offset, length ->110          Chunk.booleans(values.toBooleanArray(), offset, length)111        },112        arrayChunkGenerator(Arb.bool(), ChunkShrinker()) { values, _, _ ->113          Chunk.array(values.toTypedArray())114        }115      ).values(rs)116  }117fun Arb.Companion.byteChunk(): Arb<Chunk<Byte>> =118  object : Arb<Chunk<Byte>>() {119    override fun edgecases(): List<Chunk<Byte>> =120      listOf(Chunk.empty<Byte>()) + Arb.byte().edgecases().map { Chunk(it) }121    override fun values(rs: RandomSource): Sequence<Sample<Chunk<Byte>>> =122      Arb.choice(123        arrayChunkGenerator(Arb.byte(), ChunkShrinker()) { values, offset, length ->124          Chunk.bytes(values.toByteArray(), offset, length)125        },126        arrayChunkGenerator(Arb.byte(), ChunkShrinker()) { values, _, _ ->127          Chunk.array(values.toTypedArray())128        }129      ).values(rs)130  }131fun Arb.Companion.intChunk(): Arb<Chunk<Int>> =132  object : Arb<Chunk<Int>>() {133    override fun edgecases(): List<Chunk<Int>> =134      listOf(Chunk.empty<Int>()) + Arb.int().edgecases().map { Chunk(it) }135    override fun values(rs: RandomSource): Sequence<Sample<Chunk<Int>>> =136      Arb.choice(137        arrayChunkGenerator(Arb.int(), ChunkShrinker()) { values, offset, length ->138          Chunk.ints(values.toIntArray(), offset, length)139        },140        arrayChunkGenerator(Arb.int(), ChunkShrinker()) { values, _, _ ->141          Chunk.array(values.toTypedArray())142        }143      ).values(rs)144  }145fun Arb.Companion.longChunk(): Arb<Chunk<Long>> =146  object : Arb<Chunk<Long>>() {147    override fun edgecases(): List<Chunk<Long>> =148      listOf(Chunk.empty<Long>()) + Arb.long().edgecases().map { Chunk(it) }149    override fun values(rs: RandomSource): Sequence<Sample<Chunk<Long>>> =150      Arb.choice(151        arrayChunkGenerator(Arb.long(), ChunkShrinker()) { values, offset, length ->152          Chunk.longs(values.toLongArray(), offset, length)153        },154        arrayChunkGenerator(Arb.long(), ChunkShrinker()) { values, _, _ ->155          Chunk.array(values.toTypedArray())156        }157      ).values(rs)158  }159fun Arb.Companion.doubleChunk(): Arb<Chunk<Double>> =160  object : Arb<Chunk<Double>>() {161    override fun edgecases(): List<Chunk<Double>> =162      listOf(Chunk.empty<Double>()) + Arb.double().edgecases().map { Chunk(it) }163    override fun values(rs: RandomSource): Sequence<Sample<Chunk<Double>>> =164      Arb.choice(165        arrayChunkGenerator(Arb.double(), ChunkShrinker()) { values, offset, length ->166          Chunk.doubles(values.toDoubleArray(), offset, length)167        },168        arrayChunkGenerator(Arb.double(), ChunkShrinker()) { values, _, _ ->169          Chunk.array(values.toTypedArray())170        }171      ).values(rs)172  }173fun Arb.Companion.floatChunk(): Arb<Chunk<Float>> =174  object : Arb<Chunk<Float>>() {175    override fun edgecases(): List<Chunk<Float>> =176      listOf(Chunk.empty<Float>()) + Arb.float().edgecases().map { Chunk(it) }177    override fun values(rs: RandomSource): Sequence<Sample<Chunk<Float>>> =178      Arb.choice(179        arrayChunkGenerator(Arb.float(), ChunkShrinker()) { values, offset, length ->180          Chunk.floats(values.toFloatArray(), offset, length)181        },182        arrayChunkGenerator(Arb.float(), ChunkShrinker()) { values, _, _ ->183          Chunk.array(values.toTypedArray())184        }185      ).values(rs)186  }187fun Arb.Companion.shortChunk(): Arb<Chunk<Short>> =188  object : Arb<Chunk<Short>>() {189    override fun edgecases(): List<Chunk<Short>> =190      listOf(Chunk.empty<Short>()) + Arb.short().edgecases().map { Chunk(it) }191    override fun values(rs: RandomSource): Sequence<Sample<Chunk<Short>>> =192      Arb.choice(193        arrayChunkGenerator(Arb.short(), ChunkShrinker()) { values, offset, length ->194          Chunk.shorts(values.toShortArray(), offset, length)195        },196        arrayChunkGenerator(Arb.short(), ChunkShrinker()) { values, _, _ ->197          Chunk.array(values.toTypedArray())198        }199      ).values(rs)200  }...

Full Screen

Full Screen

StringTest.kt

Source:StringTest.kt Github

copy

Full Screen

1import io.kotest.matchers.shouldBe2import io.kotest.property.Arb3import io.kotest.property.RandomSource4import io.kotest.property.arbitrary.Codepoint5import io.kotest.property.arbitrary.arabic6import io.kotest.property.arbitrary.arbitrary7import io.kotest.property.arbitrary.asString8import io.kotest.property.arbitrary.ascii9import io.kotest.property.arbitrary.egyptianHieroglyphs10import io.kotest.property.arbitrary.string11import io.kotest.property.arbitrary.take12import io.kotest.property.checkAll13import io.harmor.msgpack.internal.MessageType.FIXSTRING14import io.harmor.msgpack.internal.MessageType.STRING1615import io.harmor.msgpack.internal.MessageType.STRING3216import io.harmor.msgpack.internal.MessageType.STRING817import io.harmor.msgpack.nextString18import io.harmor.msgpack.StringValue19import io.harmor.msgpack.msgpack.str20import utils.TypedElement21import utils.MessagePackerFactory22import utils.MessageUnpackerFactory23import utils.bytes24import utils.pack25import utils.plus26import utils.convert27import utils.with28import kotlin.experimental.or29import kotlin.random.nextInt30class StringTest : AbstractMessagePackTest() {31    init {32        "Packer" should {33            "use fixstr" {34                checkAll(byteString(0..31)) {35                    it with packer shouldBe fixstr(it)36                }37            }38            "use str8" {39                checkAll(byteString(32..255)) {40                    it with packer shouldBe str8(it)41                }42            }43            "use str16" {44                checkAll(100, byteString(256..65535)) {45                    it with packer shouldBe str16(it)46                }47            }48            "use str32" {49                checkAll(100, byteString(65536..100_000)) {50                    it with packer shouldBe str32(it)51                }52            }53        }54        "Unpacker" should {55            "decode fixstr" {56                checkAll(byteString(0..31)) {57                    str(it) with unpacker shouldBe str(it)58                }59            }60            "decode str8" {61                checkAll(100, byteString(32..255)) {62                    str(it) with unpacker shouldBe str(it)63                }64            }65            "decode str16" {66                checkAll(100, byteString(256..65535)) {67                    str(it) with unpacker shouldBe str(it)68                }69            }70            "decode str32" {71                checkAll(100, byteString(65536..100_000)) {72                    str(it) with unpacker shouldBe str(it)73                }74            }75            "decode utf-8" {76                checkAll(100, Arb.string(0..100_000, Arb.arabic() + Arb.egyptianHieroglyphs())) {77                    str(it) with unpacker shouldBe str(it)78                }79            }80        }81    }82}83private fun byteString(bytes: IntRange, codepoint: Arb<Codepoint> = Arb.ascii()): Arb<String> {84    val edgeCases = listOf(codepoint.toString(bytes.first), codepoint.toString(bytes.last))85    return arbitrary(edgeCases) { rs ->86        val count = rs.random.nextInt(bytes)87        codepoint.toString(count, rs)88    }89}90fun Arb<Codepoint>.toString(count: Int, rs: RandomSource = RandomSource.Default) =91    take(count, rs).joinToString("") { it.asString() }92private fun fixstr(value: String) = TypedElement(FIXSTRING.first.toByte() or value.bytes.toByte(), str(value))93private fun str8(value: String) = TypedElement(STRING8, str(value))94private fun str16(value: String) = TypedElement(STRING16, str(value))95private fun str32(value: String) = TypedElement(STRING32, str(value))96infix fun StringValue.with(unpacker: MessageUnpackerFactory): StringValue =97    unpacker(convert().pack()).nextString()98infix fun String.with(packerFactory: MessagePackerFactory): TypedElement =99    StringValue(this) with packerFactory...

Full Screen

Full Screen

StreamSpec.kt

Source:StreamSpec.kt Github

copy

Full Screen

...27  init {28    spec()29  }30  fun Arb.Companion.long(range: LongRange = Long.MIN_VALUE..Long.MAX_VALUE): Arb<Long> {31    val edgecases = listOf(0L, 1, -1, Long.MAX_VALUE, Long.MIN_VALUE).filter { it in range }32    return arb(LongShrinker(range), edgecases) { it.random.nextLong(range.first, range.last) }33  }34  class LongShrinker(private val range: LongRange) : Shrinker<Long> {35    override fun shrink(value: Long): List<Long> =36      when (value) {37        0L -> emptyList()38        1L, -1L -> listOf(0)39        else -> {40          val a = listOf(abs(value), value / 3, value / 2, value * 2 / 3)41          val b = (1..5L).map { value - it }.reversed().filter { it > 0 }42          (a + b).distinct().filter { it in range && it != value }43        }44      }45  }46  inline fun <reified O, R> Arb.Companion.pull(...

Full Screen

Full Screen

ItemGens.kt

Source:ItemGens.kt Github

copy

Full Screen

...28    /**29     * Edgecases for the minimum and maximum values, as well as some that30     * are centered around the expiration date of 0.31     */32    private val edgecases: List<Int> = (-2..2) + (Int.MAX_VALUE - 1) + (Int.MIN_VALUE + 1)33    // note- ignore integer overflow for now34    val nonExpired = Arb.intEdgecases(1, Int.MAX_VALUE - 1, edgecases)35    val expired = Arb.intEdgecases(Int.MIN_VALUE + 1, 0, edgecases)36    val any = Arb.intEdgecases(Int.MIN_VALUE + 1 until Int.MAX_VALUE, edgecases)37  }38  object Quality {39    val regularValidRange = 0..5040    /** Some additional edgecases around the min/max quality range */41    private val edgecases: List<Int> =42        regularValidRange.first.let { (it - 3)..(it + 3) } +43        regularValidRange.last.let { (it - 3)..(it + 3) }44    val any = Arb.intEdgecases(Int.MIN_VALUE + 1 until Int.MAX_VALUE, edgecases)45    val validRegular = Arb.intEdgecases(regularValidRange, edgecases)46    // note- ignore integer overflow for now47    val invalidRegular = any.filterNot { it in regularValidRange }48  }49  object Binds {50    fun itemArb(51        nameGen: Gen<String> = Names.all,52        sellInGen: Gen<Int> = SellIn.any,53        qualityGen: Gen<Int> = Quality.any,54    ) = Arb.bind(nameGen, sellInGen, qualityGen) { name, sellIn, quality ->55      Item(name, sellIn, quality)56    }57  }58}...

Full Screen

Full Screen

KotestConfig.kt

Source:KotestConfig.kt Github

copy

Full Screen

...31        min: Int = Int.MIN_VALUE,32        max: Int = Int.MAX_VALUE,33        additionalEdgecases: List<Int> = emptyList(),34    ) = Arb.intEdgecases(min..max, additionalEdgecases)35    /**  Helper method to initialise a [Arb.Companion.int] with some edgecases. */36    fun Arb.Companion.intEdgecases(37        range: IntRange = Int.MIN_VALUE..Int.MAX_VALUE,38        additionalEdgecases: List<Int> = emptyList(),39    ): Arb<Int> {40      val edgecases =41          (42              listOf(-1, 0, 1, range.first, range.last, Int.MIN_VALUE, Int.MAX_VALUE) +43              additionalEdgecases44          ).filter { it in range }45      return arbitrary(edgecases, IntShrinker(range)) { it.random.nextInt(range) }46    }47  }48}...

Full Screen

Full Screen

PulsarUrnTest.kt

Source:PulsarUrnTest.kt Github

copy

Full Screen

1package com.octaldata.session.pulsar2import com.octaldata.domain.topics.TopicName3import com.octaldata.domain.structure.DataRecordUrn4import io.kotest.core.spec.style.FunSpec5import io.kotest.matchers.shouldBe6import io.kotest.property.Arb7import io.kotest.property.arbitrary.positiveInt8import io.kotest.property.arbitrary.positiveLong9import io.kotest.property.arbitrary.string10import io.kotest.property.arbitrary.withEdgecases11import io.kotest.property.checkAll12class PulsarUrnTest : FunSpec({13   test("parse urn") {14      checkAll(15         100,16         Arb.string(1, 100),17         Arb.positiveInt().withEdgecases(-1),18         Arb.positiveLong().withEdgecases(-1),19         Arb.positiveLong().withEdgecases(-1),20      ) { topic, part, ledge, entryId ->21         parseUrn(DataRecordUrn("urn:pulsar:$topic:$part:$ledge:$entryId")).getOrThrow() shouldBe22            MessageIdentifier(TopicName(topic), part, ledge, entryId)23      }24   }25})...

Full Screen

Full Screen

MD5Test.kt

Source:MD5Test.kt Github

copy

Full Screen

1package com.github.durun.nitron.core2import io.kotest.core.spec.style.FreeSpec3import io.kotest.matchers.shouldBe4import io.kotest.property.Arb5import io.kotest.property.arbitrary.edgecases6import io.kotest.property.arbitrary.string7class MD5Test : FreeSpec({8    "toString" {9        val testData = Arb.string().edgecases() + listOf("hogehoge")10        testData.forEach {11            val md5 = MD5.digest("hogehoge")12            println(md5.toString())13            println(md5.toStringOld())14            md5.toString() shouldBe md5.toStringOld()15        }16    }17})18private fun MD5.toStringOld(): String = String.format(19    "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",20    bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],21    bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]22)...

Full Screen

Full Screen

RemoteDataGen.kt

Source:RemoteDataGen.kt Github

copy

Full Screen

1package com.github.torresmi.remotedata.test.util.generation2import com.github.torresmi.remotedata.RemoteData3import io.kotest.property.Arb4import io.kotest.property.arbitrary.choice5import io.kotest.property.arbitrary.map6import io.kotest.property.arbitrary.next7fun <E : Any, A : Any> Arb.Companion.remoteData(failureGen: Arb<E>, successGen: Arb<A>) = Arb.choice(8    successGen.map { RemoteData.succeed(it) },9    failureGen.map { RemoteData.fail(it) }10).plusEdgecases(11    RemoteData.NotAsked,12    RemoteData.Loading,13    RemoteData.succeed(successGen.next()),14    RemoteData.fail(failureGen.next())15)16fun <E : Any> Arb.Companion.remoteDataNonSuccess(failureGen: Arb<E>) = failureGen.map { RemoteData.fail(it) }17    .plusEdgecases(18        RemoteData.NotAsked,19        RemoteData.Loading20    )...

Full Screen

Full Screen

edgecases

Using AI Code Generation

copy

Full Screen

1val edgeCases = EdgeCases.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)2val arb = Arb.int(1..10, edgeCases)3val ints = arb.take(100).toList()4println(ints)5enum class Suit { CLUBS, DIAMONDS, HEARTS, SPADES }6val arbSuit = Arb.enum<Suit>()7val suits = arbSuit.take(10).toList()8println(suits)

Full Screen

Full Screen

edgecases

Using AI Code Generation

copy

Full Screen

1val edgecases = EdgeCases.of(1, 2, 3, 4, 5)2val arb = Arb.int(edgecases)3val arb = Arb.int().frequency(41 to Arb.int(1..10),52 to Arb.int(11..20),63 to Arb.int(21..30)7val arb = Arb.int().frequency(81 to Arb.int(1..10),92 to Arb.int(11..20),103 to Arb.int(21..30)11val arb = Arb.int().frequency(121 to Arb.int(1..10),132 to Arb.int(11..20),143 to Arb.int(21..30)15val arb = Arb.int().frequency(161 to Arb.int(1..10),172 to Arb.int(11..20),183 to Arb.int(21..30)19val arb = Arb.int().frequency(201 to Arb.int(1..10),212 to Arb.int(11..20),223 to Arb.int(21..30)23val arb = Arb.int().frequency(241 to Arb.int(1..10),252 to Arb.int(11..20),263 to Arb.int(21..30)27val arb = Arb.int().frequency(281 to Arb.int(1..10),292 to Arb.int(11..20),303 to Arb.int(21..30)31val arb = Arb.int().frequency(321 to Arb.int(1..10),332 to Arb.int(11..20),343 to Arb.int(21..30)35val arb = Arb.int().frequency(361 to Arb.int(1..10),372 to Arb.int(11..20),383 to Arb.int(21..30)

Full Screen

Full Screen

edgecases

Using AI Code Generation

copy

Full Screen

1        val edgeCases = EdgeCases.of("foo", "bar", "baz")2        val arb = Arb.string().withEdgecases(edgeCases)3        val sample = arb.sample(rs, 100)4        sample should containAll(edgeCases.values)5     }6  }7}8class StringLengthTest : WordSpec() {9  init {10    "string length" should {11      "be between 0 and 100" {12        checkAll<String> { s ->13          s.length shouldBe between(0, 100)14        }15      }16    }17  }18}19class StringLengthTest : WordSpec() {20  init {21    "string length" should {22      "be between 0 and 100" {23        checkAll<String> { s ->24          s.length shouldBe between(0, 100)25        }.edgecases(edgecases = listOf("", "a".repeat(100)))26      }27    }28  }29}

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