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

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

BuilderTest.kt

Source:BuilderTest.kt Github

copy

Full Screen

...119 val shrinker = IntShrinker(1..5)120 val edges = setOf(1, 2)121 val arb = arbitrary(edges.toList(), shrinker) { 5 }122 arb.edgecases() shouldContainExactlyInAnyOrder edges123 arb.sample(RandomSource.seeded(1234L)).shrinks.children.value.map { it.value() } shouldBe shrinker.shrink(5)124 }125 test("should use shrinker when provided") {126 val shrinker = IntShrinker(1..5)127 val arb = arbitrary(shrinker) { 5 }128 arb.classifier.shouldBeNull()129 val shrinks = arb.sample(RandomSource.seeded(1234L)).shrinks130 shrinks.children.value.map { it.value() } shouldContainExactly shrinker.shrink(5)131 }132 test("should use classifier when provided") {133 val classifier = IntClassifier(1..5)134 val arb = arbitrary(classifier) { 5 }135 arb.classifier shouldBeSameInstanceAs classifier136 }137 test("should use classifier and shrinker when provided") {138 val shrinker = IntShrinker(1..5)139 val classifier = IntClassifier(1..5)140 val arb = arbitrary(shrinker, classifier) { 5 }141 arb.classifier shouldBeSameInstanceAs classifier142 val shrinks = arb.sample(RandomSource.seeded(1234L)).shrinks143 shrinks.children.value.map { it.value() } shouldContainExactly shrinker.shrink(5)144 }145 test("should use edgecase function when provided") {146 val arb = arbitrary({ 5 }) { 10 }147 arb.edgecases() shouldContainExactlyInAnyOrder setOf(5)148 }149 test("should use edgecase function and shrinker when provided") {150 val shrinker = IntShrinker(1..5)151 val arb = arbitrary({ 5 }, shrinker) { 10 }152 arb.edgecases() shouldContainExactlyInAnyOrder setOf(5)153 val shrinks = arb.sample(RandomSource.seeded(1234L)).shrinks154 shrinks.children.value.map { it.value() } shouldContainExactly shrinker.shrink(10)155 }156 test("should support .bind() syntax") {157 val arb = Arb.constant(5)158 val shrinker = IntShrinker(1..5)159 val classifier = IntClassifier(1..5)160 arbitrary { arb.bind() }.single() shouldBe 5161 arbitrary(shrinker) { arb.bind() }.single() shouldBe 5162 arbitrary(classifier) { arb.bind() }.single() shouldBe 5163 arbitrary(shrinker, classifier) { arb.bind() }.single() shouldBe 5164 arbitrary(listOf(5)) { arb.bind() }.single() shouldBe 5165 arbitrary({ 5 }) { arb.bind() }.single() shouldBe 5166 arbitrary({ 5 }, shrinker) { arb.bind() }.single() shouldBe 5167 }168 }169 context("suspend arbitrary builder with unrestricted continuation") {170 suspend fun combineAsString(vararg values: Any?): String = values.joinToString(" ")171 test("should build arb on the parent coroutine context") {172 val arb = withContext(Foo("hello")) {173 generateArbitrary {174 val hello = coroutineContext[Foo]?.value175 val world = arbitrary { "world" }.bind()176 val first = Arb.int(1..10).bind()177 val second = Arb.int(11..20).bind()178 combineAsString(hello, world, first, second)179 }180 }181 arb.generate(RandomSource.seeded(1234L)).take(4).toList().map { it.value } shouldContainExactly listOf(182 "hello world 2 20",183 "hello world 6 12",184 "hello world 7 19",185 "hello world 9 13"186 )187 }188 test("should bind edgecases") {189 val arb: Arb<String> = generateArbitrary {190 val first = Arb.string(5, Codepoint.alphanumeric()).withEdgecases("edge1", "edge2").bind()191 val second = Arb.int(1..9).withEdgecases(5).bind()192 val third = Arb.int(101..109).withEdgecases(100 + second, 109).bind()193 combineAsString(first, second, third)194 }195 arb.edgecases() shouldContainExactlyInAnyOrder setOf(196 "edge1 5 105",197 "edge2 5 105",198 "edge1 5 109",199 "edge2 5 109",200 )201 }202 test("should preserve edgecases of dependent arbs, even when intermideary arb(s) have no edgecases") {203 val arb: Arb<String> = generateArbitrary {204 val first = Arb.string(5, Codepoint.alphanumeric()).withEdgecases("edge1", "edge2").bind()205 val second = Arb.int(1..4).withEdgecases(emptyList()).bind()206 val third = Arb.int(101..109).withEdgecases(100 + second).bind()207 combineAsString(first, second, third)208 }209 arb.edgecases() shouldContainExactlyInAnyOrder setOf(210 "edge1 1 101",211 "edge1 2 102",212 "edge1 3 103",213 "edge1 4 104",214 "edge2 1 101",215 "edge2 2 102",216 "edge2 3 103",217 "edge2 4 104"218 )219 }220 test("should propagate exception") {221 val throwingArb = generateArbitrary {222 val number = Arb.int(1..4).withEdgecases(emptyList()).bind()223 // try to throw something inside the arb224 number shouldBeGreaterThan 5225 }226 val assertionError = shouldThrow<AssertionError> { execute(RandomSource.seeded(1234L), throwingArb) }227 assertionError.message shouldBe "4 should be > 5"228 }229 test("should assign edgecases") {230 val edges = setOf("edge1", "edge2")231 val arb = generateArbitrary(edges.toList()) { "abcd" }232 arb.edgecases() shouldContainExactlyInAnyOrder edges233 }234 test("should assign edgecases and shrinker") {235 val shrinker = IntShrinker(1..5)236 val edges = setOf(1, 2)237 val arb = generateArbitrary(edges.toList(), shrinker) { 5 }238 arb.edgecases() shouldContainExactlyInAnyOrder edges239 arb.sample(RandomSource.seeded(1234L)).shrinks.children.value.map { it.value() } shouldBe shrinker.shrink(5)240 }241 test("should use shrinker when provided") {242 val shrinker = IntShrinker(1..5)243 val arb = generateArbitrary(shrinker) { 5 }244 arb.classifier.shouldBeNull()245 val shrinks = arb.sample(RandomSource.seeded(1234L)).shrinks246 shrinks.children.value.map { it.value() } shouldContainExactly shrinker.shrink(5)247 }248 test("should use classifier when provided") {249 val classifier = IntClassifier(1..5)250 val arb = generateArbitrary(classifier) { 5 }251 arb.classifier shouldBeSameInstanceAs classifier252 }253 test("should use classifier and shrinker when provided") {254 val shrinker = IntShrinker(1..5)255 val classifier = IntClassifier(1..5)256 val arb = generateArbitrary(shrinker, classifier) { 5 }257 arb.classifier shouldBeSameInstanceAs classifier258 val shrinks = arb.sample(RandomSource.seeded(1234L)).shrinks259 shrinks.children.value.map { it.value() } shouldContainExactly shrinker.shrink(5)260 }261 test("should use edgecase function when provided") {262 val arb = generateArbitrary({ 5 }) { 10 }263 arb.edgecases() shouldContainExactlyInAnyOrder setOf(5)264 }265 test("should use edgecase function and shrinker when provided") {266 val shrinker = IntShrinker(1..5)267 val arb = generateArbitrary({ 5 }, shrinker) { 10 }268 arb.edgecases() shouldContainExactlyInAnyOrder setOf(5)269 val shrinks = arb.sample(RandomSource.seeded(1234L)).shrinks270 shrinks.children.value.map { it.value() } shouldContainExactly shrinker.shrink(10)271 }272 test("should support .bind() syntax") {273 val arb = Arb.constant(5)274 val shrinker = IntShrinker(1..5)275 val classifier = IntClassifier(1..5)276 generateArbitrary { arb.bind() }.single() shouldBe 5277 generateArbitrary(shrinker) { arb.bind() }.single() shouldBe 5278 generateArbitrary(classifier) { arb.bind() }.single() shouldBe 5279 generateArbitrary(shrinker, classifier) { arb.bind() }.single() shouldBe 5280 generateArbitrary(listOf(5)) { arb.bind() }.single() shouldBe 5281 generateArbitrary({ 5 }) { arb.bind() }.single() shouldBe 5282 generateArbitrary({ 5 }, shrinker) { arb.bind() }.single() shouldBe 5283 }...

Full Screen

Full Screen

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

PassportProcessingTest.kt

Source:PassportProcessingTest.kt Github

copy

Full Screen

1import io.kotest.core.spec.style.DescribeSpec2import io.kotest.matchers.shouldBe3import io.kotest.property.Arb4import io.kotest.property.arbitrary.*5import io.kotest.property.checkAll6import java.io.File7class PassportProcessingTest : DescribeSpec({8 val p = PassportProcessing()9 val input: List<String> = File("input.txt").readLines()10 describe("Test PassportProcessing") {11 context("Sample test") {12 it("Returns 213") {13 val actual = p.passportProcessing(input)14 actual shouldBe 21315 }16 }17 context("No passports") {18 it("Returns 0") {19 val actual = p.passportProcessing(listOf())20 actual shouldBe 021 }22 }23 context("All valid passports") {24 it("Return size of input") {25 checkAll(Arb.list(passportStringGen)) { passports ->26 // Add newlines to separate passports, and remove last newline27 val withNewLine = passports28 .fold(listOf<String>()) { acc, element -> acc + element + "" }29 .dropLast(1)30 p.passportProcessing(withNewLine) shouldBe passports.size31 }32 }33 }34 }35 describe("Test PassportProcessing2") {36 context("Sample test") {37 it("Returns 147") {38 val actual = p.passportProcessing2(input)39 actual shouldBe 14740 }41 }42 context("No passports") {43 it("Returns 0") {44 val actual = p.passportProcessing(listOf())45 actual shouldBe 046 }47 }48 context("All valid passports") {49 it("Return size of input") {50 checkAll(Arb.list(passportStringGen)) { passports ->51 // Add newlines to separate passports, and remove last newline52 val withNewLine = passports53 .fold(listOf<String>()) { acc, element -> acc + element + "" }54 .dropLast(1)55 p.passportProcessing2(withNewLine) shouldBe passports.size56 }57 }58 }59 context("Valid Passport (control)") {60 it("Valid passport") {61 val actual = p.passportProcessing2(listOf(Passport(getValidPassportData()).toString()))62 actual shouldBe 163 }64 }65 context("Passport BYR out of range") {66 it("Invalid passport") {67 val data = getValidPassportData(byr = "0")68 val actual = p.passportProcessing2(listOf(Passport(data).toString()))69 actual shouldBe 070 }71 }72 context("Passport IYR out of range") {73 it("Invalid passport") {74 val data = getValidPassportData(byr = "2021")75 val actual = p.passportProcessing2(listOf(Passport(data).toString()))76 actual shouldBe 077 }78 }79 context("Passport EYR out of range") {80 it("Invalid passport") {81 val data = getValidPassportData(eyr = "2031")82 val actual = p.passportProcessing2(listOf(Passport(data).toString()))83 actual shouldBe 084 }85 }86 context("Passport HGT out of range") {87 it("Invalid passport") {88 val data = getValidPassportData(hgt = "200cm")89 val actual = p.passportProcessing2(listOf(Passport(data).toString()))90 actual shouldBe 091 }92 }93 context("Passport HCL out of range") {94 it("Invalid passport") {95 val data = getValidPassportData(hcl = "###0")96 val actual = p.passportProcessing2(listOf(Passport(data).toString()))97 actual shouldBe 098 }99 }100 context("Passport ECL out of range") {101 it("Invalid passport") {102 val data = getValidPassportData(ecl = "not color")103 val actual = p.passportProcessing2(listOf(Passport(data).toString()))104 actual shouldBe 0105 }106 }107 context("Passport PID out of range") {108 it("Invalid passport") {109 val data = getValidPassportData(pid = "0")110 val actual = p.passportProcessing2(listOf(Passport(data).toString()))111 actual shouldBe 0112 }113 }114 }115})116fun getValidPassportData(117 byr: String = "2000",118 iyr: String = "2010",119 eyr: String = "2020",120 hgt: String = "150cm",121 hcl: String = "#ffffff",122 ecl: String = "amb",123 pid: String = "123456789"124): MutableMap<String, String> = mutableMapOf(125 PassportFields.BYR.value to byr,126 PassportFields.IYR.value to iyr,127 PassportFields.EYR.value to eyr,128 PassportFields.HGT.value to hgt,129 PassportFields.HCL.value to hcl,130 PassportFields.ECL.value to ecl,131 PassportFields.PID.value to pid132)133val passportStringGen = Arb.bind(134 Arb.int(1920, 2002),135 Arb.int(2010, 2020),136 Arb.int(2020, 2030),137 Arb.int(150, 193),138 Arb.stringPattern("\\#([0-9]|[a-f]){6}"),139 Arb.stringPattern("amb|blu|brn|gry|grn|hzl|oth"),140 Arb.stringPattern("[0-9]{9,9}")141) { byr, iyr, eyr, hgt, hcl, ecl, pid ->142 "byr:$byr iyr:$iyr eyr:$eyr hgt:${hgt}cm hcl:$hcl ecl:$ecl pid:$pid"143}...

Full Screen

Full Screen

Generators.kt

Source:Generators.kt Github

copy

Full Screen

...31 zeroToOne, zeroToOne, zeroToOne, zeroToOne,32) { h, s, l, a -> Colour(h, s, l, a) }33fun Arb.Companion.quadtree(depth: Int): Arb<Quadtree> = arbitrary(TreeShrinker) { rs ->34 when (depth) {35 1 -> Leaf(Arb.colour().sample(rs).value)36 else -> {37 val deep = rs.random.nextInt(1..4)38 val children = Arb39 .quadtree(depth - 1)40 .many(4)41 .mapIndexed { i, deepArb ->42 val arb = if (i != deep && rs.random.nextDouble() < 0.5) Arb.quadtree(1)43 else deepArb44 arb.sample(rs).value45 }46 Node(children.toTypedArray())47 }48 }49}50object TreeShrinker : Shrinker<Quadtree> {51 override fun shrink(value: Quadtree): List<Quadtree> = when (value) {52 is Leaf -> listOf()53 is Node -> value.children.asList()54 }55}56fun GLFWAction.Companion.gen(): Gen<GLFWAction> = exhaustive(GLFWAction.values().asList())57fun CursorEvent.Companion.arb(): Arb<CursorEvent> = Arb.bind(58 Arb.positiveDoubles(), Arb.positiveDoubles(),...

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

RationalTest.kt

Source:RationalTest.kt Github

copy

Full Screen

...9 forAll(10 // 첫번째 인자로 Arb<Rational> 인스턴스를 넘김11 object : Arb<Rational>() {12 override fun edgecase(rs: RandomSource): Rational? = null // 에지 케이스 없음13 override fun sample(rs: RandomSource): Sample<Rational> =14 Sample(Rational.of(rs.random.nextInt(), rs.random.nextInt(0, Int.MAX_VALUE)))15 }16 ){ a: Rational ->17 (a - a).num == 018 }19 }20 val rationalArb = Arb.bind(Arb.int(),Arb.int(0,Int.MAX_VALUE)){x,y->Rational.of(x,y)}21 "Subtraction (Arb.int()와 Arb.bind() 사용)" {22 forAll(rationalArb){ a: Rational ->23 (a - a).num == 024 }25 }26 val rationalArb2 = arbitrary { Rational.of(it.random.nextInt(), it.random.nextInt(0,Int.MAX_VALUE)) }27 "Subtraction (arbitrary() 사용)" {...

Full Screen

Full Screen

NameTest.kt

Source:NameTest.kt Github

copy

Full Screen

1package jp.glory.domain2import io.kotest.core.spec.style.DescribeSpec3import io.kotest.matchers.shouldBe4import io.kotest.property.Arb5import io.kotest.property.arbitrary.bind6import io.kotest.property.arbitrary.string7import io.kotest.property.checkAll8class NameTest : DescribeSpec({9 describe("Sample Based Test") {10 describe("Get japan style") {11 it("Family name is first") {12 val sut = Name(13 familyName = "family",14 givenName = "given"15 )16 sut.getJapanStyle() shouldBe "${sut.familyName} ${sut.givenName}"17 }18 }19 describe("Get foreign style") {20 it("Given name is first") {21 val sut = Name(22 familyName = "family",23 givenName = "given"24 )25 sut.getForeignStyle() shouldBe "${sut.givenName} ${sut.familyName}"26 }27 }28 }29 describe("Property Based Test") {30 describe("Get japan style") {31 it("Family name is first") {32 val arb = Arb.bind(33 Arb.string(),34 Arb.string(),35 ) {36 familyName,37 givenName ->38 Name(39 familyName = familyName,40 givenName = givenName41 )42 }43 checkAll(arb) { sut ->44 sut.getJapanStyle() shouldBe "${sut.familyName} ${sut.givenName}"45 }46 }47 }48 describe("Get foreign style") {49 it("Given name is first") {50 val arb = Arb.bind(51 Arb.string(),52 Arb.string(),53 ) {54 familyName,55 givenName ->56 Name(57 familyName = familyName,58 givenName = givenName59 )60 }61 checkAll(arb) { sut ->62 sut.getForeignStyle() shouldBe "${sut.givenName} ${sut.familyName}"63 }64 }65 }66 }67})...

Full Screen

Full Screen

BindShrinkTest.kt

Source:BindShrinkTest.kt Github

copy

Full Screen

...30 }31 }32 "Arb.bind shrinks all components" {33 val arb = createArb { i -> listOf(0, i / 2, i - 1) }34 val sample = arb.sample(RandomSource.default())35 // Shrinker produces three new values for each component36 sample.shrinks.children.value shouldHaveSize 3 * 1437 }38 "Shrinks all components to minimum value" {39 val arb = createArb(IntShrinker(0..1000))40 val stdout = captureStandardOut {41 shouldThrowAny {42 checkAll(arb) {43 // Better ways to simulate a bug for some input value?44 it.m shouldBeLessThan 10045 }46 }47 }48 stdout shouldContain """Shrink result (after 45 shrinks) => MaximumComponents(a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0, j=0, k=0, l=0, m=100, n=0)"""49 }50 }...

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