How to use sample method of io.kotest.property.arbitrary.filter class

Best Kotest code snippet using io.kotest.property.arbitrary.filter.sample

ParseProperty.kt

Source:ParseProperty.kt Github

copy

Full Screen

...113    arbitrary(listOf(Codepoint('a'.code))) { rs ->114        val printableChars = (' '.code..'~'.code).asSequence()115        val codepoints = printableChars.map { Codepoint(it) }.toList()116        val ints = Arb.int(codepoints.indices)117        codepoints[ints.sample(rs).value]118    }119fun Arb.Companion.printableMultilinesIndentedAscii(): Arb<Codepoint> =120    arbitrary(listOf(Codepoint('a'.code))) { rs ->121        val indentings = sequenceOf(0xB)122        val endOfLines = sequenceOf(0xA, 0xD)123        val printableChars = (' '.code..'~'.code).asSequence()124        val codepoints = (indentings + endOfLines + printableChars).map { Codepoint(it) }.toList()125        val ints = Arb.int(codepoints.indices)126        codepoints[ints.sample(rs).value]127    }128fun Arb.Companion.unicode(): Arb<Codepoint> =129    arbitrary(listOf(Codepoint('a'.code))) { rs ->130        val ints = Arb.int(Character.MIN_CODE_POINT..Character.MAX_CODE_POINT)131        Codepoint(ints.sample(rs).value)132    }133val arbLevel =134    Arb.element(135        listOf<(Logger, String) -> Unit>(136            Logger::error,137            Logger::warn,138            Logger::info,139            Logger::debug,140            Logger::trace141        )142    )143val arbMessage =144    Arb.string(0, 1024, Arb.printableMultilinesIndentedAscii())145        .merge(Arb.string(0, 1024, Arb.unicode()))...

Full Screen

Full Screen

GraphProperties.kt

Source:GraphProperties.kt Github

copy

Full Screen

...173        }.toPersistentMap()174    }175val Arb.Companion.graphWithPairOfVertices176    get() = arbitrary { rs ->177        val graph = connectedGraph.sample(rs)178        val from = Arb.int(0 until graph.value.size).next(rs)179        val to = Arb.int(0 until graph.value.size).filter { it != from }.next(rs)180        graph.value to (from to to)181    }182val Arb.Companion.graphWithSubgraph: Arb<Pair<Graph<Int>, Graph<Int>>>183    get() = arbitrary { rs ->184        connectedGraph.sample(rs).let { graph ->185            graph.value to graph.value.mutate { g ->186                val subgraphSize = Arb.int(4 until graph.value.size).next(rs)187                g.keys.removeIf { it >= subgraphSize }188                g.replaceAll { _, v -> v.mutate { it.keys.removeIf { it >= subgraphSize } } }189            }190        }191    }...

Full Screen

Full Screen

ModelTest.kt

Source:ModelTest.kt Github

copy

Full Screen

...49        "Before all change webPage directory" {50            //Configuration.WebPageDirectory = "webPageTest"51            //clearDirectory(Configuration.WebPageDirectory)52        }53        "Instantiate sample test class" {54            //val webPage = WebPage("http://test.com")55        }56    }57}58class SentenceSpec : StringSpec() {59    override fun testCaseOrder(): TestCaseOrder? = TestCaseOrder.Sequential60    init {61        "beforeAll change configuration for test purposes" {62            Configuration.databaseFile = "sentenceTest.db"63            Configuration.SentenceDirectory = "sentenceTest"64            clearDirectory()65            Model.items = HashMap<String, Int>()66        }67        "Add test sentence to keyword test" {...

Full Screen

Full Screen

PasswordPhilosophyTest.kt

Source:PasswordPhilosophyTest.kt Github

copy

Full Screen

1import io.kotest.assertions.throwables.shouldThrow2import io.kotest.core.spec.style.DescribeSpec3import io.kotest.matchers.ints.shouldBeLessThanOrEqual4import io.kotest.matchers.shouldBe5import io.kotest.property.Arb6import io.kotest.property.arbitrary.*7import io.kotest.property.checkAll8import java.io.File9import java.lang.IllegalArgumentException10class PasswordPhilosophyTest : DescribeSpec({11    val p = PasswordPhilosophy()12    val inputFile: List<String> = File("input.txt").readLines()13    describe("passwordPhilosophy") {14        context("Sample test") {15            val ans = 58216            it("returns $ans") {17                val actual = p.passwordPhilosophy(inputFile)18                actual shouldBe ans19            }20        }21        context("One passport missing character") {22            it("returns 2") {23                val actual = p.passwordPhilosophy(24                    listOf(25                        "1-3 a: abcde",26                        "1-3 b: cdefg",27                        "2-9 c: ccccccccc"28                    )29                )30                actual shouldBe 231            }32        }33        context("Empty passcode") {34            it("returns 0") {35                val actual = p.passwordPhilosophy(listOf("1-2 a: "))36                actual shouldBe 037            }38        }39        context("Character count over limit") {40            it("Returns 0") {41                checkAll(Arb.list(Arb.stringPattern("1-[1-9] a: ([a]{10,20})"))) { s ->42                    p.passwordPhilosophy(s) shouldBe 043                }44            }45        }46        context("All passports valid") {47            it("Returns size of input") {48                checkAll(Arb.list(Arb.stringPattern("[a-z]{0,100}"))) { lines ->49                    p.passwordPhilosophy(lines.map { code -> "1-${code.length} ${code[0]}: " + code }) shouldBe lines.size50                }51            }52        }53        context("Any number of passports") {54            it("Number of valid passports less than total number of passports") {55                checkAll(Arb.list(Arb.stringPattern("[1-9]-[1-9][1-9] [a-z]: ([a-z]{1,50})"))) { l ->56                    p.passwordPhilosophy(l) shouldBeLessThanOrEqual l.size57                }58            }59        }60        context("Incorrect format") {61            it("throws IllegalArgumentException") {62                checkAll(Arb.list(Arb.string()).filter { it.isNotEmpty() }) { s ->63                    shouldThrow<IllegalArgumentException> {64                        p.passwordPhilosophy(s)65                    }66                }67            }68        }69    }70    describe("passwordPhilosophy2") {71        context("Sample test") {72            val ans = 72973            it("returns $ans") {74                val actual = p.passwordPhilosophy2(inputFile)75                actual shouldBe ans76            }77        }78        context("Zero, one, and two occurrences of the character") {79            it("Returns 1 valid passports") {80                val actual = p.passwordPhilosophy2(81                    listOf(82                        "1-3 c: abc",83                        "1-3 c: cbc",84                        "1-3 c: aba"85                    )86                )87                actual shouldBe 188            }89        }90        context("Occurrences at all indices except the specified") {91            it("Returns 0") {92                val actual = p.passwordPhilosophy2(93                    listOf(94                        "3-10 i: iiziiiiiiz",95                        "1-1 j: x",96                        "1-10 k: mkkkkkkkkm"97                    )98                )99                actual shouldBe 0100            }101        }102        context("Character count over limit") {103            it("Returns 0") {104                checkAll(Arb.list(Arb.stringPattern("1-[1-9] a: ([a]{10,20})"))) { s ->105                    p.passwordPhilosophy2(s) shouldBe 0106                }107            }108        }109        context("All passports valid") {110            it("Returns size of input") {111                checkAll(Arb.list(Arb.stringPattern("[a-z]{26}").map { it.toSet().fold("") { acc, element -> acc + element } })) { lines ->112                    p.passwordPhilosophy2(lines.map { code -> "1-${code.length} ${code[0]}: " + code }) shouldBe lines.size113                }114            }115        }116    }117})...

Full Screen

Full Screen

BatchMigrationGenerator.kt

Source:BatchMigrationGenerator.kt Github

copy

Full Screen

...45        val mig = validMigrationGenerator.next(rs)46        mig.sleepTime = Arb.long(0L, 10000L).orNull().next(rs)47        mig48    }49    val sampleMigrationGenerator = arbitrary { rs: RandomSource ->50        val change = BatchMigrationChange()51        change.tableName = identifierGen(1).orNull().next(rs)52        change.chunkSize = Arb.long(-100L, 10000L).orNull().next(rs)53        val upperBound = Arb.int(0, 5).next(rs)54        val minBound = Arb.int(0, 5).filter { it <= upperBound }.next(rs)55        change.fromColumns = fixedColumnStringSequenceGenerator(minBound, upperBound).orNull().next(rs)56        change.toColumns = fixedColumnStringSequenceGenerator(minBound, upperBound).orNull().next(rs)57        change.sleepTime = Arb.long(-100L, 10000L).orNull().next(rs)58        change59    }60    val invalidMigrationGenerator = sampleMigrationGenerator.filter { c: BatchMigrationChange ->61        val simplePredicate = c.fromColumns.isNullOrEmpty() ||62            c.toColumns.isNullOrEmpty() || (c.chunkSize ?: -1L) <= 0L || c.sleepTime?.let { it < 0L } ?: false63        if (simplePredicate) return@filter true64        else {65            val from = c.fromColumns!!.split(",")66            val to = c.toColumns!!.split(",").toSet()67            // check whether from and to columns are equal somewhere or crossing68            // check whether any to column is in primary keys69            from.size != to.size || from.any { it in to }70        }71    }72    private fun List<String>.toColumnList(): String = joinToString(separator = ",") { it }73    private val fixedColumnListGenerator = { lowerBound: Int, inclusiveUpperBound: Int ->74        Arb.list(identifierGen(1), IntRange(lowerBound, inclusiveUpperBound))...

Full Screen

Full Screen

BinaryBoardingTest.kt

Source:BinaryBoardingTest.kt Github

copy

Full Screen

1import io.kotest.assertions.throwables.shouldThrow2import io.kotest.core.spec.style.DescribeSpec3import io.kotest.inspectors.forAll4import io.kotest.matchers.ints.shouldBeGreaterThan5import io.kotest.matchers.ints.shouldBeInRange6import io.kotest.matchers.shouldBe7import io.kotest.property.Arb8import io.kotest.property.arbitrary.*9import io.kotest.property.checkAll10import java.io.File11import java.lang.IllegalArgumentException12class BinaryBoardingTest : DescribeSpec({13    val b = BinaryBoarding()14    val input = File("input.txt").readLines()15    describe("Test binaryBoarding") {16        context("Sample test") {17            val expected = 92618            it("Returns $expected") {19                b.binaryBoarding(input) shouldBe expected20            }21        }22        context("Bounds of seat ID") {23            checkAll(Arb.list(Arb.stringPattern("[BF]{7}[RL]{3}"), 1..100)) { l ->24                b.binaryBoarding(l) shouldBeInRange 0..(8 * BinaryBoarding.R_HIGH + BinaryBoarding.C_HIGH)25            }26        }27        context("Leading B yields larger seat ID") {28            checkAll(29                Arb.bind(30                    Arb.list(Arb.stringPattern("B[BF]{6}[LR]{3}"), 1..100),31                    Arb.list(Arb.stringPattern("F[BF]{6}[LR]{3}"), 1..100)32                ) { low, high -> Pair(low, high) }33            ) { p ->34                b.binaryBoarding(p.first) shouldBeGreaterThan b.binaryBoarding(p.second)35            }36        }37        context("Invalid input") {38            checkAll(Arb.list(Arb.string()).filter { it.size != 10 }) { l ->39                shouldThrow<IllegalArgumentException> {40                    b.binaryBoarding(l)41                }42            }43        }44    }45    describe("Test binaryBoarding2") {46        context("Sample test") {47            val expected = 65748            it("Returns $expected") {49                val actual = b.binaryBoarding2(input)50                actual shouldBe expected51            }52        }53        context("Only one seat taken") {54            it("Returns NoSuchElementException") {55                shouldThrow<NoSuchElementException> {56                    // Was guaranteed -1 and +1 are in the input57                    b.binaryBoarding2(listOf("BBBBBBBRRR"))58                }59            }60        }61    }62    describe("Test getSeatID helper") {63        context("Sample code to Seat ID mapping") {64            listOf(65                "BFFFBBFRRR" to 567,66                "FFFBBBFRRR" to 119,67                "BBFFBBFRLL" to 82068            ).forAll { (code, seatID) ->69                b.getSeatID(code) shouldBe seatID70            }71        }72    }73})...

Full Screen

Full Screen

FilterTest.kt

Source:FilterTest.kt Github

copy

Full Screen

...34   }35   test("should be stack safe") {36      val arb = object : Arb<Int>() {37         override fun edgecase(rs: RandomSource): Int? = null38         override fun sample(rs: RandomSource): Sample<Int> = Sample(rs.random.nextInt())39      }40      shouldNotThrow<StackOverflowError> {41         arb.filter { it % 2 == 0 }.take(1000000).toList()42      }43   }44   test("should apply filter to shrinks") {45      val arbEvenInts = Arb.int(-100..100).filter { it % 2 == 0 }46      val oddNumbers = (-100..100).filter { it % 2 != 0 }47      arbEvenInts.samples().take(100).forAll { sample ->48         sample.shrinks.value() shouldNotBeIn oddNumbers49         sample.shrinks.children.value.forAll {50            it.value() shouldNotBeIn oddNumbers51         }52      }53   }54   test("Arb.filter composition should not exhaust call stack") {55      var arb: Arb<Int> = Arb.of(0, 1)56      repeat(10000) {57         arb = arb.filter { it == 0 }58      }59      val result = shouldNotThrowAny { arb.single(RandomSource.seeded(1234L)) }60      result shouldBe 061   }62})...

Full Screen

Full Screen

Arb.kt

Source:Arb.kt Github

copy

Full Screen

...26    it.random.nextULong()27}28inline fun <reified T> Arb.Companion.arrayOf(value: Arb<T>, length: IntRange): Arb<Array<T>> = arbitrary { rs ->29    Array(rs.random.nextInt(length.first, length.last)) {30        value.sample(rs).value31    }32}...

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