How to use Arb.Companion.char method of io.kotest.property.arbitrary.char class

Best Kotest code snippet using io.kotest.property.arbitrary.char.Arb.Companion.char

ParseProperty.kt

Source:ParseProperty.kt Github

copy

Full Screen

1package net.torommo.logspy2import io.kotest.core.spec.style.StringSpec3import io.kotest.property.Arb4import io.kotest.property.arbitrary.Codepoint5import io.kotest.property.arbitrary.arbitrary6import io.kotest.property.arbitrary.bind7import io.kotest.property.arbitrary.element8import io.kotest.property.arbitrary.filter9import io.kotest.property.arbitrary.int10import io.kotest.property.arbitrary.map11import io.kotest.property.arbitrary.merge12import io.kotest.property.arbitrary.single13import io.kotest.property.arbitrary.string14import io.kotest.property.checkAll15import kotlin.random.Random16import kotlin.random.nextInt17import kotlin.streams.asSequence18import kotlin.text.CharCategory.DECIMAL_DIGIT_NUMBER19import kotlin.text.CharCategory.LETTER_NUMBER20import kotlin.text.CharCategory.LOWERCASE_LETTER21import kotlin.text.CharCategory.MODIFIER_LETTER22import kotlin.text.CharCategory.OTHER_LETTER23import kotlin.text.CharCategory.TITLECASE_LETTER24import kotlin.text.CharCategory.UPPERCASE_LETTER25import net.torommo.logspy.ExceptionCreationAction.ADD_SUPPRESSED_TO_ROOT_EXCEPTION26import net.torommo.logspy.ExceptionCreationAction.RANDOM_ACTION_ON_RANDOM_SUPPRESSED_IN_ROOT_EXCEPTION27import net.torommo.logspy.ExceptionCreationAction.SET_NEW_ROOT_EXCEPTION28import org.junit.jupiter.api.Assertions.assertDoesNotThrow29import org.slf4j.Logger30import org.slf4j.LoggerFactory31class ParseProperty :32    StringSpec(33        {34            "logger name parsability" {35                checkAll(36                    arbitrary(PositionIndenpendentStringShrinker(1)) { rs ->37                        arbJavaIdentifier.merge(arbKotlinIdentifier).single(rs)38                    }39                ) { loggerName ->40                    val logger = LoggerFactory.getLogger(loggerName)41                    LogstashStdoutSpyProvider().createFor(loggerName)42                        .use {43                            logger.error("Test")44                            assertDoesNotThrow(it::events);45                        }46                }47            }48            "log level parsability" {49                checkAll(arbLevel) { logAction ->50                    val logger = LoggerFactory.getLogger("test")51                    LogstashStdoutSpyProvider().createFor("test")52                        .use {53                            logAction(logger, "Test")54                            assertDoesNotThrow(it::events);55                        }56                }57            }58            "log message parsability" {59                checkAll(60                    arbitrary(PositionIndenpendentStringShrinker()) { rs -> arbMessage.single(rs) }61                ) { message ->62                    val logger = LoggerFactory.getLogger("test")63                    LogstashStdoutSpyProvider().createFor("test")64                        .use {65                            logger.error(message)66                            assertDoesNotThrow(it::events);67                        }68                }69            }70            "exception message parsability" {71                val logger = LoggerFactory.getLogger("test")72                checkAll(73                    arbitrary(PositionIndenpendentStringShrinker()) { rs -> arbMessage.single(rs) }74                ) { message ->75                    LogstashStdoutSpyProvider().createFor("test")76                        .use {77                            val exception = RuntimeException(message)78                            exception.stackTrace = emptyArray()79                            logger.error("test", exception)80                            assertDoesNotThrow(it::events);81                        }82                }83            }84            "stack trace parsability" {85                val logger = LoggerFactory.getLogger("test")86                checkAll(87                    arbitrary(ArrayShrinker()) { rs ->88                        arbKotlinStackTraceElements.merge(arbJavaStackTraceElements).single(rs)89                    }90                ) { element: Array<StackTraceElement> ->91                    LogstashStdoutSpyProvider().createFor("test")92                        .use {93                            val exception = RuntimeException("test message")94                            exception.stackTrace = element95                            logger.error("test", exception)96                            assertDoesNotThrow(it::events);97                        }98                }99            }100            "exception tree parsability" {101                val logger = LoggerFactory.getLogger("test")102                checkAll(arbExceptionTree) { exception: Throwable ->103                    LogstashStdoutSpyProvider().createFor("test")104                        .use {105                            logger.error("test", exception)106                            assertDoesNotThrow(it::events);107                        }108                }109            }110        }111    )112fun Arb.Companion.printableAscii(): Arb<Codepoint> =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()))146val arbJavaIdentifier =147    Arb.string(minSize = 1, codepoints = Arb.printableAscii())148        .merge(Arb.string(minSize = 1, codepoints = Arb.unicode()))149        .filter { Character.isJavaIdentifierStart(it.codePoints().asSequence().first()) }150        .filter {151            it.codePoints()152                .asSequence()153                .all { codePoint -> Character.isJavaIdentifierPart(codePoint) }154        }155val arbJavaFileName = arbJavaIdentifier.map { "${it}.java" }156val arbJavaStackTraceElement =157    Arb.bind(arbJavaIdentifier, arbJavaIdentifier, arbJavaFileName, Arb.int(-65536, 65535))158        { className, methodName, fileName, lineNumber ->159            StackTraceElement(className, methodName, fileName, lineNumber)160        }161val arbJavaStackTraceElements = Arb.array(arbJavaStackTraceElement, 0..7)162val arbKotlinIdentifier =163    Arb.string(minSize = 1, codepoints = Arb.printableAscii())164        .merge(Arb.string(minSize = 1, codepoints = Arb.unicode()))165        .filter { isUnescapedIdentifier(it) || isEscapedIdentifier(it) }166val arbKotlinFileName = arbKotlinIdentifier.map { "${it}.kt" };167val arbKotlinStackTraceElement =168    Arb.bind(arbKotlinIdentifier, arbKotlinIdentifier, arbKotlinFileName, Arb.int(-65536, 65535))169        { className, methodName, fileName, lineNumber ->170            StackTraceElement(className, methodName, fileName, lineNumber)171        }172val arbKotlinStackTraceElements = Arb.array(arbKotlinStackTraceElement, 0..7)173val arbExceptionTree: Arb<Throwable> =174    arbitrary { rs ->175        val throwableGenerator = arbFlatException.generate(rs).iterator()176        val result = throwableGenerator.next().value177        repeat(rs.random.nextInt(1..7)) {178            val exceptionToPlace = throwableGenerator.next().value179            addExceptionToRandomPlace(rs.random, result, exceptionToPlace)180        }181        result182    }183private fun addExceptionToRandomPlace(random: Random, aggregator: Throwable, addition: Throwable) {184    when (ExceptionCreationAction.values()[random.nextInt(ExceptionCreationAction.values().size)]) {185        SET_NEW_ROOT_EXCEPTION -> {186            rootCauseOf(aggregator).initCause(addition)187        }188        ADD_SUPPRESSED_TO_ROOT_EXCEPTION -> {189            rootCauseOf(aggregator).addSuppressed(addition)190        }191        RANDOM_ACTION_ON_RANDOM_SUPPRESSED_IN_ROOT_EXCEPTION -> {192            val rootCause = rootCauseOf(aggregator)193            if (rootCause.suppressed.isNotEmpty()) {194                addExceptionToRandomPlace(195                    random,196                    rootCause.suppressed[random.nextInt(rootCause.suppressed.size)],197                    addition198                )199            }200        }201    }202}203private tailrec fun rootCauseOf(candidate: Throwable): Throwable {204    return if (candidate.cause == null) {205        candidate206    } else {207        rootCauseOf(candidate.cause!!)208    }209}210private enum class ExceptionCreationAction {211    SET_NEW_ROOT_EXCEPTION,212    ADD_SUPPRESSED_TO_ROOT_EXCEPTION,213    RANDOM_ACTION_ON_RANDOM_SUPPRESSED_IN_ROOT_EXCEPTION214}215val arbFlatException =216    Arb.bind(217        Arb.string(0, 255, Arb.printableMultilinesIndentedAscii()),218        arbKotlinStackTraceElements.merge(arbJavaStackTraceElements)219    ) { message, stackTrace ->220        val result: Exception = RuntimeException(message)221        result.stackTrace = stackTrace222        result223    }224private fun isUnescapedIdentifier(string: String): Boolean {225    return isLetterOrUnderscore(string.first()) &&226        string.toCharArray().all { char -> isLetterOrUnderscore(char) || isUnicodeDigit(char) }227}228private fun isLetterOrUnderscore(char: Char): Boolean {229    return LOWERCASE_LETTER.contains(char) || UPPERCASE_LETTER.contains(char) ||230        TITLECASE_LETTER.contains(char) || LETTER_NUMBER.contains(char) ||231        MODIFIER_LETTER.contains(char) || OTHER_LETTER.contains(char) || char == '_'232}233private fun isUnicodeDigit(char: Char): Boolean {234    return DECIMAL_DIGIT_NUMBER.contains(char)235}236private fun isEscapedIdentifier(string: String): Boolean {237    return string.all { it != '\r' && it != '\n' && it != '`' }238}...

Full Screen

Full Screen

benchmark.kt

Source:benchmark.kt Github

copy

Full Screen

1package prettyprinter2import io.kotest.property.Arb3import io.kotest.property.RandomSource4import io.kotest.property.arbitrary.alphanumeric5import io.kotest.property.arbitrary.bind6import io.kotest.property.arbitrary.flatMap7import io.kotest.property.arbitrary.int8import io.kotest.property.arbitrary.list9import io.kotest.property.arbitrary.map10import io.kotest.property.arbitrary.next11import io.kotest.property.arbitrary.string12import prettyprinter.symbols.lparen13import prettyprinter.symbols.rparen14import kotlin.math.max15import kotlin.math.min16import kotlin.test.BeforeTest17import kotlin.test.Test18import kotlin.time.Duration19import kotlin.time.ExperimentalTime20import kotlin.time.measureTime21data class Program(val binds: Binds)22data class Binds(val map: Map<String, LambdaForm>)23data class LambdaForm(val free: List<String>, val bound: List<String>, val body: Expr)24sealed class Expr {25    data class Let(val binds: Binds, val body: Expr): Expr()26    data class Case(val scrutinee: Expr, val alts: List<Alt>): Expr()27    data class AppF(val f: String, val args: List<String>): Expr()28    data class AppC(val c: String, val args: List<String>): Expr()29    data class AppP(val op: String, val x: String, val y: String): Expr()30    data class LitE(val lit: Int): Expr()31}32data class Alt(val con: String, val args: List<String>, val body: Expr)33/* Set up value generators. */34val keywordArb: Arb<String> = Arb.string(5..7, Arb.alphanumeric())35val keywordUcArb: Arb<String> = keywordArb.map { it.replaceFirstChar { c -> c.uppercaseChar() } }36val keywordsArb: Arb<List<String>> = Arb.list(keywordArb, 0..2)37fun programArb(size: Int): Arb<Program> =38    bindsArb(size).map(::Program)39fun bindsArb(size: Int): Arb<Binds> {40    val inSize = min(size, 60)41    return Arb.map(keywordArb, lambdaFormArb(inSize), 1, max(size, 2)).map(::Binds)42}43fun lambdaFormArb(size: Int): Arb<LambdaForm> =44    Arb.bind(keywordsArb, keywordsArb, exprArb(size), ::LambdaForm)45// Arb.choice is too eager.46fun exprArb(size: Int): Arb<Expr> {47    val inSize: Int = size * 2 / 348    return Arb.int(1..6).flatMap {49        when (it) {50            1 -> letArb(inSize)51            2 -> caseArb(inSize)52            3 -> appFArb53            4 -> appCArb54            5 -> appPArb55            else -> litEArb  // weight towards simple literals.56        }57    }58}59fun letArb(size: Int): Arb<Expr.Let> =60    Arb.bind(bindsArb(size), exprArb(size), Expr::Let)61fun caseArb(size: Int): Arb<Expr.Case> =62    Arb.bind(exprArb(size), Arb.list(altArb(size), 0..3)) { expr, alts -> Expr.Case(expr, alts) }63val appFArb = Arb.bind(keywordArb, keywordsArb, Expr::AppF)64val appCArb = Arb.bind(keywordArb, keywordsArb, Expr::AppC)65val appPArb = Arb.bind(keywordArb, keywordArb, keywordArb, Expr::AppP)66val litEArb = Arb.int(-1000, 1000).map(Expr::LitE)67fun altArb(size: Int): Arb<Alt> =68    Arb.bind(keywordUcArb, keywordsArb, exprArb(size), ::Alt)69fun pretty(program: Program) : DocNo = pretty(program.binds)70fun pretty(binds: Binds): DocNo = align(vsep(71    binds.map.entries.map { (variable, lambdaForm) ->72        text(variable) spc text("=") spc pretty(lambdaForm)73    }74))75/*76instance Pretty LambdaForm where77    pretty (LambdaForm free bound body) = (prettyExp . (<+> "->") . prettyBound . prettyFree) "\\"78      where79        prettyFree | null free = id80                   | otherwise = (<> lparen <> hsep (map pretty free) <> rparen)81        prettyBound | null bound = id82                    | null free = (<> hsep (map pretty bound))83                    | otherwise = (<+> hsep (map pretty bound))84        prettyExp = (<+> pretty body)85 */86fun pretty(lambdaForm: LambdaForm): DocNo {87    fun prettyFree(node: DocNo): DocNo = if (lambdaForm.free.isEmpty()) {88        node cat lparen cat hsep(lambdaForm.free.map(::pretty)) cat rparen89    } else {90        node91    }92    fun prettyBound(node: DocNo): DocNo = when {93        lambdaForm.bound.isEmpty() -> node94        lambdaForm.free.isEmpty() -> node cat hsep(lambdaForm.bound.map(::pretty))95        else -> node spc hsep(lambdaForm.bound.map(::pretty))96    }97    fun prettyExp(node: DocNo): DocNo = node spc pretty(lambdaForm.body)98    fun arrow(node: DocNo): DocNo = node spc text("->")99    return prettyExp(arrow(prettyBound(prettyFree(text("\\")))))100}101/*instance Pretty Expr where102    pretty = \expr -> case expr of103        Let binds body ->104            align (vsep [ "let" <+> align (pretty binds)105                        , "in" <+> pretty body ])106        Case scrutinee alts -> vsep107            [ "case" <+> pretty scrutinee <+> "of"108            , indent 4 (align (vsep (map pretty alts))) ]109        AppF f [] -> pretty f110        AppF f args -> pretty f <+> hsep (map pretty args)111        AppC c [] -> pretty c112        AppC c args -> pretty c <+> hsep (map pretty args)113        AppP op x y -> pretty op <+> pretty x <+> pretty y114        LitE lit -> pretty lit115*/116fun pretty(expr: Expr): DocNo = when(expr) {117    is Expr.Let -> align(vsep(text("let") spc align(pretty(expr.binds)), text("in") spc pretty(expr.body)))118    is Expr.Case -> vsep(119        text("case") spc pretty(expr.scrutinee) spc text("of"),120        indent(4, align(vsep(expr.alts.map(::pretty))))121    )122    is Expr.AppF -> if(expr.args.isEmpty()) { pretty(expr.f) } else { pretty(expr.f) spc hsep(expr.args.map(::pretty)) }123    is Expr.AppC -> if(expr.args.isEmpty()) { pretty(expr.c) } else { pretty(expr.c) spc hsep(expr.args.map(::pretty)) }124    is Expr.AppP -> text(expr.op) spc text(expr.x) spc text(expr.y)125    is Expr.LitE -> pretty(expr.lit)126}127fun pretty(alt: Alt): DocNo = if(alt.args.isEmpty()) {128    pretty(alt.con) spc text("->") spc pretty(alt.body)129} else {130    pretty(alt.con) spc hsep(alt.args.map(::pretty)) spc text("->") spc pretty(alt.body)131}132/** QuickCheck has [a size parameter] but we want to limit the number of internal bindings to avoid stack overflow.133 * [a size parameter]: https://hackage.haskell.org/package/QuickCheck-2.14.2/docs/Test-QuickCheck.html#v:getSize134 */135fun randomProgram(rs: RandomSource, size: Int): Program {136    return programArb(size).next(rs=rs)137}138enum class RenderStyle(val render: (Doc<Nothing>) -> SDS<Nothing>) {139    Pretty8050({doc -> layoutPretty(Opts.std(80, 0.5), doc)}),140    Smart8050({doc -> layoutSmart(Opts.std(80, 0.5), doc) }),141    PrettyUnbound({doc -> layoutPretty(Opts.unbounded, doc) }),142    SmartUnbound({doc -> layoutSmart(Opts.unbounded, doc) }),143    Compact({doc -> layoutCompact(doc) }),144}145class CountSink<A> : SimpleSink<A> {146    var count = 0147    override fun openAnn(ann: A) {148    }149    override fun closeAnn(ann: A) {150    }151    override fun emit(cs: CharSequence) {152        count += cs.length153    }154}155data class Times(156    val build: Duration,157    val render: Duration,158    val sink: Duration,159    val count: Int160)161/**162 * There are dedicated benchmarking modules out there, but at this stage I want to see if we can render large documents163 * without falling over.164 */165class Benchmark {166    @OptIn(ExperimentalTime::class)167    fun benchmark(subject: Program, style: RenderStyle) {168        val doc: DocNo169        val buildTime = measureTime {170            doc = pretty(subject)171        }172        val docStream: SDS<Nothing>173        val renderTime = measureTime {174            docStream = style.render(doc)175        }176        val counter = CountSink<Nothing>()177        val sinkTime = measureTime {178            counter.render(docStream)179        }180        // println(AppendableSink<Nothing>().toString(docStream))181        println(Times(buildTime, renderTime, sinkTime, counter.count))182    }183    @Test184    fun benchmark60Compact() {185        benchmark(p60, RenderStyle.Compact)186    }187    @Test188    fun benchmark60Pretty8050() {189        benchmark(p60, RenderStyle.Pretty8050)190    }191    @Test192    fun benchmark60Smart8050() {193        benchmark(p60, RenderStyle.Smart8050)194    }195    @Test196    fun benchmark60PrettyUnbound() {197        benchmark(p60, RenderStyle.PrettyUnbound)198    }199    @Test200    fun benchmark60SmartUnbound() {201        benchmark(p60, RenderStyle.SmartUnbound)202    }203    @Test204    fun benchmark120Compact() {205        benchmark(p120, RenderStyle.Compact)206    }207    @Test208    fun benchmark120Pretty8050() {209        benchmark(p120, RenderStyle.Pretty8050)210    }211    @Test212    fun benchmark120Smart8050() {213        benchmark(p120, RenderStyle.Smart8050)214    }215    @Test216    fun benchmark120PrettyUnbound() {217        benchmark(p120, RenderStyle.PrettyUnbound)218    }219    @Test220    fun benchmark120SmartUnbound() {221        benchmark(p120, RenderStyle.SmartUnbound)222    }223    @Test224    fun benchmark240Compact() {225        benchmark(p240, RenderStyle.Compact)226    }227    @Test228    fun benchmark240Pretty8050() {229        benchmark(p240, RenderStyle.Pretty8050)230    }231    @Test232    fun benchmark240Smart8050() {233        benchmark(p240, RenderStyle.Smart8050)234    }235    @Test236    fun benchmark240PrettyUnbound() {237        benchmark(p240, RenderStyle.PrettyUnbound)238    }239    @Test240    fun benchmark240SmartUnbound() {241        benchmark(p240, RenderStyle.SmartUnbound)242    }243    244    @Test245    fun benchmark480Compact() {246        benchmark(p480, RenderStyle.Compact)247    }248    @Test249    fun benchmark480Pretty8050() {250        benchmark(p480, RenderStyle.Pretty8050)251    }252    @Test253    fun benchmark480Smart8050() {254        benchmark(p480, RenderStyle.Smart8050)255    }256    @Test257    fun benchmark480PrettyUnbound() {258        benchmark(p480, RenderStyle.PrettyUnbound)259    }260    @Test261    fun benchmark480SmartUnbound() {262        benchmark(p480, RenderStyle.SmartUnbound)263    }264    companion object {265        private val p60 = randomProgram(RandomSource.seeded(1L), 60)266        private val p120 = randomProgram(RandomSource.seeded(1L), 120)267        private val p240 = randomProgram(RandomSource.seeded(1L), 240)268        private val p480 = randomProgram(RandomSource.seeded(1L), 480)269    }270}...

Full Screen

Full Screen

FListCompanionTest.kt

Source:FListCompanionTest.kt Github

copy

Full Screen

1package com.xrpn.immutable.flisttest2import com.xrpn.imapi.IMList3import com.xrpn.imapi.IMListEqual24import com.xrpn.immutable.*5import com.xrpn.immutable.FList.Companion.toIMList6import io.kotest.core.spec.style.FunSpec7import io.kotest.matchers.shouldBe8import io.kotest.matchers.shouldNotBe9import io.kotest.matchers.string.shouldStartWith10import io.kotest.property.Arb11import io.kotest.property.arbitrary.int12import io.kotest.property.arbitrary.list13import io.kotest.property.arbitrary.set14import io.kotest.property.checkAll15import io.kotest.xrpn.flist16private val intListOfNone = FList.of(*emptyArrayOfInt)17private val intListOfOne = FList.of(*arrayOf<Int>(1))18private val intListOfTwo = FList.of(*arrayOf<Int>(1,2))19private val intListOfThree = FList.of(*arrayOf<Int>(1,2,3))20private val strListOfNone = FList.of(*emptyArrayOfStr)21private val strListOfOne = FList.of(*arrayOf<String>("a"))22private val strListOfTwo = FList.of(*arrayOf<String>("a","b"))23private val strListOfThree = FList.of(*arrayOf<String>("a","b","c"))24class FListCompanionTest : FunSpec({25  val repeats = 1026  beforeTest {}27  test("equals") {28    FList.emptyIMList<Int>().equals(null) shouldBe false29    FList.emptyIMList<Int>().equals(emptyList<Int>()) shouldBe true30    FList.emptyIMList<Int>().equals(1) shouldBe false31    /* Sigh... */ intListOfNone.equals(strListOfNone) shouldBe true32    intListOfTwo.equals(null) shouldBe false33    intListOfTwo.equals(strListOfNone) shouldBe false34    intListOfTwo.equals(strListOfTwo) shouldBe false35    intListOfTwo.equals(emptyList<Int>()) shouldBe false36    intListOfTwo.equals(listOf("foobar")) shouldBe false37    intListOfTwo.equals(listOf("foobar","babar")) shouldBe false38    intListOfTwo.equals(1) shouldBe false39  }40  test("toString() hashCode()") {41    FList.emptyIMList<Int>().toString() shouldBe "FLNil"42    val aux = FList.emptyIMList<Int>().hashCode()43    for (i in (1..100)) {44       aux shouldBe FList.emptyIMList<Int>().hashCode()45    }46    intListOfTwo.toString() shouldStartWith "${FList::class.simpleName}@{"47    val aux2 = intListOfTwo.hashCode()48    for (i in (1..100)) {49      aux2 shouldBe intListOfTwo.hashCode()50    }51    for (i in (1..100)) {52      FLCons.hashCode(intListOfTwo as FLCons) shouldBe intListOfTwo.hashCode()53    }54  }55  // IMListCompanion56  test("co.emptyFList") {57    FList.emptyIMList<Int>().isEmpty() shouldBe true58    FList.emptyIMList<Int>().fempty() shouldBe true59  }60  test("co.[ IMListEqual2 ]") {61    IMListEqual2(intListOfNone, FList.of(*emptyArrayOfInt)) shouldBe true62    IMListEqual2(FList.of(*arrayOf(1)), FList.of(*emptyArrayOfInt)) shouldBe false63    IMListEqual2(intListOfNone, FList.of(*arrayOf(1))) shouldBe false64    IMListEqual2(intListOfOne, FList.of(*arrayOf<Int>(1))) shouldBe true65    IMListEqual2(FList.of(*arrayOf(1)), FList.of(*arrayOf<Int>(1, 2))) shouldBe false66    IMListEqual2(FList.of(*arrayOf<Int>(1, 2)), FList.of(*arrayOf(1))) shouldBe false67    IMListEqual2(FList.of(*arrayOf<Int>(1, 2)), FList.of(*arrayOf(1, 2))) shouldBe true68  }69  test("co.of varargs") {70    intListOfNone shouldBe FLNil71    intListOfOne shouldBe FLCons(1,FLNil)72    intListOfTwo shouldBe FLCons(1,FLCons(2,FLNil))73    intListOfThree shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))74  }75  test("co.of iterator") {76    FList.of(emptyArrayOfInt.iterator()) shouldBe FLNil77    FList.of(arrayOf<Int>(1).iterator()) shouldBe FLCons(1,FLNil)78    FList.of(arrayOf<Int>(1,2).iterator()) shouldBe FLCons(1,FLCons(2,FLNil))79    FList.of(arrayOf<Int>(1,2,3).iterator()) shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))80  }81  test("co.of List") {82    FList.of(emptyList()) shouldBe FLNil83    FList.of(listOf(1)) shouldBe FLCons(1,FLNil)84    FList.of(listOf(1,2)) shouldBe FLCons(1,FLCons(2,FLNil))85    FList.of(listOf(1,2,3)) shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))86  }87  test("co.of IMList") {88    FList.of(intListOfNone as IMList<Int>) shouldBe FLNil89    FList.of(intListOfOne as IMList<Int>) shouldBe FLCons(1,FLNil)90    FList.of(intListOfTwo as IMList<Int>) shouldBe FLCons(1,FLCons(2,FLNil))91    FList.of(intListOfThree as IMList<Int>) shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))92  }93  test("co.ofMap iterator") {94    strListOfNone shouldBe FList.ofMap(emptyArrayOfInt.iterator(), ::fidentity)95    strListOfOne shouldBe FList.ofMap(arrayOf(0).iterator()) { a -> (a+'a'.code).toChar().toString() }96    strListOfTwo shouldBe FList.ofMap(arrayOf(0, 1).iterator()) { a -> (a+'a'.code).toChar().toString() }97    strListOfThree shouldBe FList.ofMap(arrayOf(0, 1, 2).iterator()) { a -> (a+'a'.code).toChar().toString() }98  }99  test("co.ofMap List") {100    strListOfNone shouldBe FList.ofMap(emptyList<Int>()) { a -> a }101    strListOfOne shouldBe FList.ofMap(listOf(0)) { a -> (a+'a'.code).toChar().toString() }102    strListOfTwo shouldBe FList.ofMap(listOf(0, 1)) { a -> (a+'a'.code).toChar().toString() }103    strListOfThree shouldBe FList.ofMap(listOf(0, 1, 2)) { a -> (a+'a'.code).toChar().toString() }104  }105  test("co.toIMList") {106    Arb.list(Arb.int()).checkAll(repeats) { l ->107      l.toIMList() shouldBe FList.of(l)108    }109    Arb.set(Arb.int()).checkAll(repeats) { s ->110      s.toIMList() shouldBe FList.of(s.iterator())111    }112  }113  // implementation114  test("co.NOT_FOUND") {115    FList.NOT_FOUND shouldBe -1116  }117  test("co.isNested") {118    FList.isNested(FList.of(*arrayOf(FList.of(*emptyArrayOfInt)))) shouldBe true119    FList.isNested(FList.of(*arrayOf(FList.of(*arrayOf<Int>(1))))) shouldBe true120    FList.isNested(intListOfNone) shouldBe false121    FList.isNested(intListOfOne) shouldBe false122  }123  test("co.firstNotEmpty") {124    val aux0: FList<FList<Int>> = FList.of(*arrayOf(FList.of(*emptyArrayOfInt)))125    FList.firstNotEmpty(aux0) shouldBe null126    val aux1: FList<FList<Int>> = FList.of(*arrayOf(FList.of(*arrayOf<Int>(1))))127    FList.firstNotEmpty(aux1) shouldBe FLCons(1, FLNil)128    val aux1a: FList<FList<Int>> = FList.of(*arrayOf(FList.of(*emptyArrayOfInt)), *arrayOf(FList.of(*arrayOf<Int>(3))))129    FList.firstNotEmpty(aux1a) shouldBe FLCons(3, FLNil)130    val aux2: FList<FList<Int>> = FList.of(*arrayOf(FList.of(*emptyArrayOfInt)), *arrayOf(FList.of(*arrayOf<Int>(1, 2))))131    FList.firstNotEmpty(aux2) shouldBe FLCons( 1, FLCons(2, FLNil))132    val aux2a: FList<FList<Int>> = FList.of(*arrayOf(FList.of(*emptyArrayOfInt)), *arrayOf(FList.of(*emptyArrayOfInt)))133    FList.firstNotEmpty(aux2a) shouldBe null134    val aux_a = FLCons(aux0, FLCons(aux1, FLNil))135    FList.firstNotEmpty(aux_a) shouldBe aux0136    FList.firstNotEmpty(intListOfNone) shouldBe null137    FList.firstNotEmpty(intListOfOne) shouldBe null138  }139  test("co.fflatten") {140    FList.fflatten(FList.of(*arrayOf(FList.of(*emptyArrayOfInt)))) shouldBe FLNil141    FList.fflatten(FList.of(*arrayOf(FList.of(*arrayOf<Int>(1))))) shouldBe FLCons(1,FLNil)142    FList.fflatten(FList.of(*arrayOf(intListOfNone, FList.of(*emptyArrayOfInt)))) shouldBe FLNil143    FList.fflatten(FList.of(*arrayOf(intListOfNone, FList.of(*arrayOf<Int>(1))))) shouldBe FLCons(1,FLNil)144    FList.fflatten(FList.of(*arrayOf(intListOfOne, FList.of(*emptyArrayOfInt)))) shouldBe FLCons(1,FLNil)145    FList.fflatten(FList.of(*arrayOf(intListOfOne, FList.of(*arrayOf<Int>(2))))) shouldBe FLCons(1,FLCons(2,FLNil))146    FList.fflatten(FList.of(*arrayOf(intListOfTwo, FList.of(*arrayOf<Int>(3))))) shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))147    FList.fflatten(FList.of(*arrayOf(intListOfOne, FList.of(*arrayOf<Int>(2,3))))) shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))148    FList.fflatten(FList.of(*arrayOf(intListOfTwo, FList.of(*arrayOf<Int>(3,4))))) shouldBe FLCons(1,FLCons(2,FLCons(3,FLCons(4,FLNil))))149  }150  test("co.fappendNested") {151    FList.fappendNested(FList.of(*arrayOf(FList.of(*emptyArrayOfInt)))) shouldBe FLNil152    FList.fappendNested(FList.of(*arrayOf(FList.of(*arrayOf<Int>(1))))) shouldBe FLCons(1,FLNil)153    FList.fappendNested(FList.of(*arrayOf(intListOfNone, FList.of(*emptyArrayOfInt)))) shouldBe FLNil154    FList.fappendNested(FList.of(*arrayOf(intListOfNone, FList.of(*arrayOf<Int>(1))))) shouldBe FLCons(1,FLNil)155    FList.fappendNested(FList.of(*arrayOf(intListOfOne, FList.of(*emptyArrayOfInt)))) shouldBe FLCons(1,FLNil)156    FList.fappendNested(FList.of(*arrayOf(intListOfOne, FList.of(*arrayOf<Int>(2))))) shouldBe FLCons(1,FLCons(2,FLNil))157    FList.fappendNested(FList.of(*arrayOf(intListOfTwo, FList.of(*arrayOf<Int>(3))))) shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))158    FList.fappendNested(FList.of(*arrayOf(intListOfOne, FList.of(*arrayOf<Int>(2,3))))) shouldBe FLCons(1,FLCons(2,FLCons(3,FLNil)))159    FList.fappendNested(FList.of(*arrayOf(intListOfTwo, FList.of(*arrayOf<Int>(3,4))))) shouldBe FLCons(1,FLCons(2,FLCons(3,FLCons(4,FLNil))))160  }161  test("co.toArray") {162    Arb.flist<Int, Int>(Arb.int()).checkAll(repeats) { fl ->163      val ary: Array<Int> = FList.toArray(fl)164      fl shouldBe FList.of(ary.iterator())165      fl shouldBe FList.of(*ary)166      fl shouldNotBe FList.of(ary)167    }168  }169})...

Full Screen

Full Screen

predef-test.kt

Source:predef-test.kt Github

copy

Full Screen

1package arrow.fx.coroutines2import arrow.core.Either3import arrow.core.Validated4import arrow.core.ValidatedNel5import arrow.core.identity6import arrow.core.invalid7import arrow.core.invalidNel8import arrow.core.left9import arrow.core.right10import arrow.core.valid11import arrow.core.validNel12import io.kotest.assertions.fail13import io.kotest.matchers.Matcher14import io.kotest.matchers.MatcherResult15import io.kotest.matchers.equalityMatcher16import io.kotest.property.Arb17import io.kotest.property.arbitrary.bind18import io.kotest.property.arbitrary.char19import io.kotest.property.arbitrary.choice20import io.kotest.property.arbitrary.choose21import io.kotest.property.arbitrary.constant22import io.kotest.property.arbitrary.int23import io.kotest.property.arbitrary.list24import io.kotest.property.arbitrary.long25import io.kotest.property.arbitrary.map26import io.kotest.property.arbitrary.string27import kotlinx.coroutines.Dispatchers28import kotlinx.coroutines.flow.Flow29import kotlinx.coroutines.flow.asFlow30import kotlin.coroutines.Continuation31import kotlin.coroutines.CoroutineContext32import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED33import kotlin.coroutines.intrinsics.intercepted34import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn35import kotlin.coroutines.resume36import kotlin.coroutines.startCoroutine37import kotlinx.coroutines.channels.Channel38import kotlinx.coroutines.flow.buffer39import kotlinx.coroutines.flow.channelFlow40import kotlinx.coroutines.flow.emptyFlow41public data class SideEffect(var counter: Int = 0) {42  public fun increment() {43    counter++44  }45}46public fun <A> Arb.Companion.flow(arbA: Arb<A>): Arb<Flow<A>> =47  Arb.choose(48    10 to Arb.list(arbA).map { it.asFlow() },49    10 to Arb.list(arbA).map { channelFlow { it.forEach { send(it) } }.buffer(Channel.RENDEZVOUS) },50    1 to Arb.constant(emptyFlow()),51  )52public fun Arb.Companion.throwable(): Arb<Throwable> =53  Arb.string().map(::RuntimeException)54public fun <L, R> Arb.Companion.either(left: Arb<L>, right: Arb<R>): Arb<Either<L, R>> {55  val failure: Arb<Either<L, R>> = left.map { l -> l.left() }56  val success: Arb<Either<L, R>> = right.map { r -> r.right() }57  return Arb.choice(failure, success)58}59public fun <L, R> Arb.Companion.validated(left: Arb<L>, right: Arb<R>): Arb<Validated<L, R>> {60  val failure: Arb<Validated<L, R>> = left.map { l -> l.invalid() }61  val success: Arb<Validated<L, R>> = right.map { r -> r.valid() }62  return Arb.choice(failure, success)63}64public fun <L, R> Arb.Companion.validatedNel(left: Arb<L>, right: Arb<R>): Arb<ValidatedNel<L, R>> {65  val failure: Arb<ValidatedNel<L, R>> = left.map { l -> l.invalidNel() }66  val success: Arb<ValidatedNel<L, R>> = right.map { r -> r.validNel() }67  return Arb.choice(failure, success)68}69public fun Arb.Companion.intRange(min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE): Arb<IntRange> =70  Arb.bind(Arb.int(min, max), Arb.int(min, max)) { a, b ->71    if (a < b) a..b else b..a72  }73public fun Arb.Companion.longRange(min: Long = Long.MIN_VALUE, max: Long = Long.MAX_VALUE): Arb<LongRange> =74  Arb.bind(Arb.long(min, max), Arb.long(min, max)) { a, b ->75    if (a < b) a..b else b..a76  }77public fun Arb.Companion.charRange(): Arb<CharRange> =78  Arb.bind(Arb.char(), Arb.char()) { a, b ->79    if (a < b) a..b else b..a80  }81public fun <O> Arb.Companion.function(arb: Arb<O>): Arb<() -> O> =82  arb.map { { it } }83public fun Arb.Companion.unit(): Arb<Unit> =84  Arb.constant(Unit)85public fun <A, B> Arb.Companion.functionAToB(arb: Arb<B>): Arb<(A) -> B> =86  arb.map { b: B -> { _: A -> b } }87public fun <A> Arb.Companion.nullable(arb: Arb<A>): Arb<A?> =88  Arb.Companion.choice(arb, arb.map { null })89/** Useful for testing success & error scenarios with an `Either` generator **/90public fun <A> Either<Throwable, A>.rethrow(): A =91  fold({ throw it }, ::identity)92public fun <A> Result<A>.toEither(): Either<Throwable, A> =93  fold({ a -> Either.Right(a) }, { e -> Either.Left(e) })94public suspend fun Throwable.suspend(): Nothing =95  suspendCoroutineUninterceptedOrReturn { cont ->96    suspend { throw this }.startCoroutine(97      Continuation(Dispatchers.Default) {98        cont.intercepted().resumeWith(it)99      }100    )101    COROUTINE_SUSPENDED102  }103public suspend fun <A> A.suspend(): A =104  suspendCoroutineUninterceptedOrReturn { cont ->105    suspend { this }.startCoroutine(106      Continuation(Dispatchers.Default) {107        cont.intercepted().resumeWith(it)108      }109    )110    COROUTINE_SUSPENDED111  }112public fun <A> A.suspended(): suspend () -> A =113  suspend { suspend() }114/**115 * Example usage:116 * ```kotlin117 * import arrow.fx.coroutines.assertThrowable118 *119 * fun main() {120 *   val exception = assertThrowable<IllegalArgumentException> {121 *     throw IllegalArgumentException("Talk to a duck")122 *   }123 *   require("Talk to a duck" == exception.message)124 * }125 * ```126 * <!--- KNIT example-predef-test-01.kt -->127 * @see Assertions.assertThrows128 */129public inline fun <A> assertThrowable(executable: () -> A): Throwable {130  val a = try {131    executable.invoke()132  } catch (e: Throwable) {133    e134  }135  return if (a is Throwable) a else fail("Expected an exception but found: $a")136}137public suspend fun CoroutineContext.shift(): Unit =138  suspendCoroutineUninterceptedOrReturn { cont ->139    suspend { this }.startCoroutine(140      Continuation(this) {141        cont.resume(Unit)142      }143    )144    COROUTINE_SUSPENDED145  }146public fun leftException(e: Throwable): Matcher<Either<Throwable, *>> =147  object : Matcher<Either<Throwable, *>> {148    override fun test(value: Either<Throwable, *>): MatcherResult =149      when (value) {150        is Either.Left -> when {151          value.value::class != e::class -> MatcherResult(152            false,153            "Expected exception of type ${e::class} but found ${value.value::class}",154            "Should not be exception of type ${e::class}"155          )156          value.value.message != e.message -> MatcherResult(157            false,158            "Expected exception with message ${e.message} but found ${value.value.message}",159            "Should not be exception with message ${e.message}"160          )161          else -> MatcherResult(162            true,163            "Expected exception of type ${e::class} and found ${value.value::class}",164            "Expected exception of type ${e::class} and found ${value.value::class}"165          )166        }167        is Either.Right -> MatcherResult(168          false,169          "Expected Either.Left with exception of type ${e::class} and found Right with ${value.value}",170          "Should not be Either.Left with exception"171        )172      }173  }174public fun <A> either(e: Either<Throwable, A>): Matcher<Either<Throwable, A>> =175  object : Matcher<Either<Throwable, A>> {176    override fun test(value: Either<Throwable, A>): MatcherResult =177      when (value) {178        is Either.Left -> when {179          value.value::class != (e.swap().orNull() ?: Int)::class -> MatcherResult(180            false,181            "Expected $e but found $value",182            "Should not be $e"183          )184          value.value.message != (e.swap().orNull()?.message ?: -1) -> MatcherResult(185            false,186            "Expected $e but found $value",187            "Should not be $e"188          )189          else -> MatcherResult(190            true,191            "Expected exception of type ${e::class} and found ${value.value::class}",192            "Expected exception of type ${e::class} and found ${value.value::class}"193          )194        }195        is Either.Right -> equalityMatcher(e).test(value)196      }197  }...

Full Screen

Full Screen

strings.kt

Source:strings.kt Github

copy

Full Screen

1package io.kotest.property.arbitrary2import io.kotest.property.Arb3import io.kotest.property.Shrinker4import io.kotest.property.arbitrary.strings.StringClassifier5import kotlin.random.nextInt6/**7 * Returns an [Arb] where each random value is a String of length between minSize and maxSize.8 * By default, the arb uses a [ascii] codepoint generator, but this can be substituted9 * with any codepoint generator. There are many available, such as [katakana] and so on.10 *11 * The edge case values are a string of min length, using the first12 * edge case codepoint provided by the codepoints arb. If the min length is 0 and maxSize > 0, then13 * the edge cases will include a string of length 1 as well.14 */15fun Arb.Companion.string(16   minSize: Int = 0,17   maxSize: Int = 100,18   codepoints: Arb<Codepoint> = Codepoint.ascii()19): Arb<String> {20   return ArbitraryBuilder.create { rs ->21      val size = rs.random.nextInt(minSize..maxSize)22      codepoints.take(size, rs).joinToString("") { it.asString() }23   }.withEdgecaseFn { rs ->24      if (minSize == maxSize) null else {25         val lowCodePoint = codepoints.edgecase(rs)26         val min = lowCodePoint?.let { cp -> List(minSize) { cp.asString() }.joinToString("") }27         val minPlus1 = lowCodePoint?.let { cp -> List(minSize + 1) { cp.asString() }.joinToString("") }28         val edgeCases = listOfNotNull(min, minPlus1)29            .filter { it.length in minSize..maxSize }30         if (edgeCases.isEmpty()) null else edgeCases.random(rs.random)31      }32   }.withShrinker(StringShrinkerWithMin(minSize))33      .withClassifier(StringClassifier(minSize, maxSize))34      .build()35}36/**37 * Returns an [Arb] where each random value is a String which has a length in the given range.38 * By default the arb uses a [ascii] codepoint generator, but this can be substituted39 * with any codepoint generator. There are many available, such as [katakana] and so on.40 *41 * The edge case values are a string of the first value in the range, using the first edge case42 * codepoint provided by the codepoints arb.43 */44fun Arb.Companion.string(range: IntRange, codepoints: Arb<Codepoint> = Codepoint.ascii()): Arb<String> =45   Arb.string(range.first, range.last, codepoints)46/**47 * Returns an [Arb] where each random value is a String of length [size].48 * By default the arb uses a [ascii] codepoint generator, but this can be substituted49 * with any codepoint generator. There are many available, such as [katakana] and so on.50 *51 * There are no edge case values associated with this arb.52 */53fun Arb.Companion.string(size: Int, codepoints: Arb<Codepoint> = Codepoint.ascii()): Arb<String> =54   Arb.string(size, size, codepoints)55@Deprecated("This Shrinker does not take into account string lengths. Use StringShrinkerWithMin. This was deprecated in 4.5.")56object StringShrinker : Shrinker<String> {57   override fun shrink(value: String): List<String> {58      return when {59         value == "" -> emptyList()60         value == "a" -> listOf("")61         value.length == 1 -> listOf("", "a")62         else -> {63            val firstHalf = value.take(value.length / 2 + value.length % 2)64            val secondHalf = value.takeLast(value.length / 2)65            val secondHalfAs = firstHalf.padEnd(value.length, 'a')66            val firstHalfAs = secondHalf.padStart(value.length, 'a')67            val dropFirstChar = value.drop(1)68            val dropLastChar = value.dropLast(1)69            listOf(70               firstHalf,71               firstHalfAs,72               secondHalf,73               secondHalfAs,74               dropFirstChar,75               dropLastChar76            )77         }78      }79   }80}81/**82 * Shrinks a string. Shrunk variants will be shorter and simplified.83 *84 * Shorter strings will be at least [minLength] in length.85 *86 * Simplified strings will have characters replaced by a character (selected by [simplestCharSelector])87 * of each pre-shrunk value. By default, this is the first character of the pre-shrunk string.88 *89 * When [simplestCharSelector] returns null, no simpler variants will be created.90 */91class StringShrinkerWithMin(92   private val minLength: Int = 0,93   private val simplestCharSelector: (preShrinkValue: String) -> Char? = CharSequence::firstOrNull94) : Shrinker<String> {95//   @Deprecated("a static 'simplestChar' means invalid shrinks can be generated - use the alternative constructor instead, which allows for a dynamic 'simplestChar'")96//   constructor (97//      minLength: Int = 0,98//      simplestChar: Char,99//   ) : this(minLength, { simplestChar })100   override fun shrink(value: String): List<String> {101      val simplestChar: Char? = simplestCharSelector(value)102      val isShortest = value.length == minLength103      val isSimplest = value.all { it == simplestChar }104      return buildList {105         if (!isShortest) {106            addAll(shorterVariants(value))107         }108         if (!isSimplest && simplestChar != null) {109            addAll(simplerVariants(value, simplestChar))110         }111      }.mapNotNull {112         // ensure the variants are at least minLength long113         when {114            simplestChar != null -> it.padEnd(minLength, simplestChar)115            it.length >= minLength -> it116            else -> null // this string is too short, so filter it out117         }118      }.distinct()119   }120   private fun simplerVariants(value: String, simplestChar: Char): List<String> =121      listOfNotNull(122         // replace the first and last chars that aren't simplestChar with simplestChar123         replace(value, simplestChar, value.indexOfFirst { it != simplestChar }),124         replace(value, simplestChar, value.indexOfLast { it != simplestChar }),125      )126   private fun shorterVariants(value: String) =127      listOf(128         value.take(value.length / 2 + value.length % 2),129         value.takeLast(value.length / 2),130         value.drop(1),131         value.dropLast(1),132      )133   private fun replace(value: String, newChar: Char, index: Int) =134      if (index == -1) null else value.replaceRange(index..index, newChar.toString())135}...

Full Screen

Full Screen

TestDomain.kt

Source:TestDomain.kt Github

copy

Full Screen

1package arrow.optics2import arrow.core.Option3import arrow.core.Some4import arrow.core.left5import arrow.core.right6import io.kotest.property.Arb7import io.kotest.property.arbitrary.choice8import io.kotest.property.arbitrary.constant9import io.kotest.property.arbitrary.int10import io.kotest.property.arbitrary.map11import io.kotest.property.arbitrary.string12sealed class SumType {13  data class A(val string: String) : SumType()14  data class B(val int: Int) : SumType()15}16fun Arb.Companion.sumTypeA(): Arb<SumType.A> =17  Arb.string().map { SumType.A(it) }18fun Arb.Companion.sumType(): Arb<SumType> =19  Arb.choice(Arb.string().map { SumType.A(it) }, Arb.int().map { SumType.B(it) })20fun PPrism.Companion.sumType(): Prism<SumType, String> = Prism(21  { Option.fromNullable((it as? SumType.A)?.string) },22  SumType::A23)24fun PPrism.Companion.string(): Prism<String, List<Char>> = Prism(25  { Some(it.toList()) },26  { it.joinToString(separator = "") }27)28internal fun PLens.Companion.token(): Lens<Token, String> = PLens(29  { token: Token -> token.value },30  { token: Token, value: String -> token.copy(value = value) }31)32internal fun PIso.Companion.token(): Iso<Token, String> = Iso(33  { token: Token -> token.value },34  ::Token35)36internal fun PSetter.Companion.token(): Setter<Token, String> = Setter { token, s ->37  token.copy(value = s(token.value))38}39internal fun PIso.Companion.user(): Iso<User, Token> = Iso(40  { user: User -> user.token },41  ::User42)43internal fun PSetter.Companion.user(): Setter<User, Token> = Setter { user, s ->44  user.copy(token = s(user.token))45}46internal data class Token(val value: String) {47  companion object48}49internal fun Arb.Companion.token(): Arb<Token> =50  Arb.string().map { Token(it) }51internal data class User(val token: Token)52internal fun Arb.Companion.user(): Arb<User> =53  Arb.token().map { User(it) }54internal data class IncompleteUser(val token: Token?)55internal fun Arb.Companion.incompleteUser(): Arb<IncompleteUser> = Arb.constant(IncompleteUser(null))56internal fun Getter.Companion.token(): Getter<Token, String> =57  Getter { it.value }58internal fun PLens.Companion.user(): Lens<User, Token> = Lens(59  { user: User -> user.token },60  { user: User, token: Token -> user.copy(token = token) }61)62internal fun POptional.Companion.incompleteUserToken(): Optional<IncompleteUser, Token> = Optional(63  getOrModify = { user -> user.token?.right() ?: user.left() },64  set = { user, token -> user.copy(token = token) }65)66internal fun POptional.Companion.defaultHead(): Optional<Int, Int> = Optional(67  { Some(it) },68  { s, _ -> s }69)...

Full Screen

Full Screen

char.kt

Source:char.kt Github

copy

Full Screen

1package io.kotest.property.arbitrary2import io.kotest.property.Arb3import io.kotest.property.Gen4/**5 * Returns a [Arb] that generates randomly-chosen Chars. Custom characters can be generated by6 * providing CharRanges. Distribution will be even across the ranges of Chars.7 * For example:8 * Gen.char('A'..'C', 'D'..'E')9 * Ths will choose A, B, C, D, and E each 20% of the time.10 */11fun Arb.Companion.char(range: CharRange, vararg ranges: CharRange): Arb<Char> {12   return Arb.char(listOf(range) + ranges)13}14/**15 * Returns a [Arb] that generates randomly-chosen Chars. Custom characters can be generated by16 * providing a list of CharRanges. Distribution will be even across the ranges of Chars.17 * For example:18 * Gen.char(listOf('A'..'C', 'D'..'E')19 * Ths will choose A, B, C, D, and E each 20% of the time.20 *21 * If no parameter is given, ASCII characters will be generated.22 */23fun Arb.Companion.char(ranges: List<CharRange> = CharSets.BASIC_LATIN): Arb<Char> {24   require(ranges.all { !it.isEmpty() }) { "Ranges cannot be empty" }25   require(ranges.isNotEmpty()) { "List of ranges must have at least one range" }26   fun makeRangeWeightedGen(): Arb<CharRange> {27      val weightPairs = ranges.map { range ->28         val weight = range.last.code - range.first.code + 129         Pair(weight, range)30      }31      return Arb.choose(weightPairs[0], weightPairs[1], *weightPairs.drop(2).toTypedArray())32   }33   // Convert the list of CharRanges into a weighted Gen in which34   // the ranges are chosen from the list using the length of the35   // range as the weight.36   val arbRange: Arb<CharRange> =37      if (ranges.size == 1) Arb.constant(ranges.first())38      else makeRangeWeightedGen()39   return arbRange.flatMap { charRange ->40      arbitrary { charRange.random(it.random) }41   }42}43/**44 * Returns an [Arb] that produces [CharArray]s where [length] produces the length of the arrays and45 * [content] produces the content of the arrays.46 */47fun Arb.Companion.charArray(length: Gen<Int>, content: Arb<Char>): Arb<CharArray> =48   toPrimitiveArray(length, content, Collection<Char>::toCharArray)49private object CharSets {50   val CONTROL = listOf('\u0000'..'\u001F', '\u007F'..'\u007F')51   val WHITESPACE = listOf('\u0020'..'\u0020', '\u0009'..'\u0009', '\u000A'..'\u000A')52   val BASIC_LATIN = listOf('\u0021'..'\u007E')53}...

Full Screen

Full Screen

ConversionTest.kt

Source:ConversionTest.kt Github

copy

Full Screen

1import Canvas.Companion.unsigned_char2import io.kotest.core.spec.style.StringSpec3import io.kotest.property.Arb4import io.kotest.property.PropTestConfig5import io.kotest.property.arbitrary.arbitrary6import io.kotest.property.arbitrary.int7import io.kotest.property.checkAll8import kotlin.test.assertEquals9class ConversionTest : StringSpec({10    "Java bytes should be correctly converted to unsigned chars" {11        assertEquals(-1, unsigned_char(1f))12        assertEquals(0, unsigned_char(0f))13    }14    "the conversion from screen space to world space and back again shouldn't change the coords" {15        val model = CameraModel(16            offset = Vec2.screen(0.1, 0.27),17            zoomLevel = 3,18            windowSize = Vec2.screen(640.0, 480.0)19        )20        val ss = Vec2.screen(121.0, 43.0)21        assertEquals(ss, model.toScreenSpace(model.toWorldSpace(ss)).round(5))22    }23    "screen space -- world space conversion should work regardless of zoom and offset" {24        checkAll(100_000, PropTestConfig(seed = 42), arbitrary { rs ->25            fun Arb<Int>.sampleToDouble(): Double = sample(rs).value.toDouble()26            val model = Arb.primitiveModel().sample(rs).value27            val (winW, winH) = model.windowSize28            model to Vec2.screen(29                Arb.int(0..winW.toInt()).sampleToDouble(),30                Arb.int(0..winH.toInt()).sampleToDouble(),31            )32        }) { (model, ss) ->33            assertEquals(ss, model.toScreenSpace(model.toWorldSpace(ss)).round(5))34        }35    }36})...

Full Screen

Full Screen

Arb.Companion.char

Using AI Code Generation

copy

Full Screen

1import io.kotest.property.arbitrary.*2val charGen = Arb.char()3import io.kotest.property.arbitrary.*4val intGen = Arb.int()5import io.kotest.property.arbitrary.*6val longGen = Arb.long()7import io.kotest.property.arbitrary.*8val shortGen = Arb.short()9import io.kotest.property.arbitrary.*10val stringGen = Arb.string()11import io.kotest.property.arbitrary.*12val uuidGen = Arb.uuid()13import io.kotest.property.arbitrary.*14val uuidGen = Arb.uuid()15import io.kotest.property.arbitrary.*16val uuidGen = Arb.uuid()17import io.kotest.property.arbitrary.*18val uuidGen = Arb.uuid()19import io.kotest.property.arbitrary.*20val uuidGen = Arb.uuid()21import io.kotest.property.arbitrary.*22val uuidGen = Arb.uuid()23import io.kotest.property.arbitrary.*24val uuidGen = Arb.uuid()25import io.kotest.property.arbitrary.*26val uuidGen = Arb.uuid()27import io.kotest.property.arbitrary.*28val uuidGen = Arb.uuid()29import io.kotest.property.arbitrary

Full Screen

Full Screen

Arb.Companion.char

Using AI Code Generation

copy

Full Screen

1val charArb = Arb.char()2val charArbWithRange = Arb.char( 'a' , 'z' )3val charArbWithRangeAndEdgeCases = Arb.char( 'a' , 'z' , edgecases = listOf( 'a' , 'z' , 'A' , 'Z' ))4val charArbWithRangeAndEdgeCasesAndFilter = Arb.char( 'a' , 'z' , edgecases = listOf( 'a' , 'z' , 'A' , 'Z' ), filter = { it in 'a' .. 'z' })5val charArbWithRangeAndEdgeCasesAndFilterAndBlacklist = Arb.char( 'a' , 'z' , edgecases = listOf( 'a' , 'z' , 'A' , 'Z' ), filter = { it in 'a' .. 'z' }, blacklist = listOf( 'a' , 'z' , 'A' , 'Z' ))6val charArbWithRangeAndEdgeCasesAndFilterAndBlacklistAndWhitelist = Arb.char( 'a' , 'z' , edgecases = listOf( 'a' , 'z' , 'A' , 'Z' ), filter = { it in 'a' .. 'z' }, blacklist = listOf( 'a' , 'z' , 'A' , 'Z' ), whitelist = listOf( 'a' , 'z' , 'A' , 'Z' ))7val charArbWithRangeAndEdgeCasesAndFilterAndBlacklistAndWhitelistAndShrinker = Arb.char( 'a' , 'z' , edgecases = listOf( 'a' , 'z' , 'A' , 'Z' ), filter = { it in 'a' .. 'z' }, blacklist = listOf( 'a' , 'z' , 'A' , 'Z' ), whitelist = listOf( 'a' , 'z' , 'A' , 'Z' ), shrinker = Shrinker { it })8val charArbWithRangeAndEdgeCasesAndFilterAndBlacklistAndWhitelistAndShrinkerAndTransformer = Arb.char( 'a' , 'z' , edgecases = listOf( 'a' , 'z' , 'A' , 'Z' ), filter = { it in 'a' .. 'z' }, blacklist = listOf( '

Full Screen

Full Screen

Arb.Companion.char

Using AI Code Generation

copy

Full Screen

1        val randomChar = Arb.Companion.char()2        val randomString = Arb.Companion.string(10)3        val randomInt = Arb.Companion.int()4        val randomIntBetween1And10 = Arb.Companion.int(1..10)5        val randomIntBetween1And10 = Arb.Companion.int(1..10)6        val randomIntBetween1And10 = Arb.Companion.int(1..10)7        val randomIntBetween1And10 = Arb.Companion.int(1..10)8        val randomIntBetween1And10 = Arb.Companion.int(1..10)9        val randomIntBetween1And10 = Arb.Companion.int(1..10)10        val randomIntBetween1And10 = Arb.Companion.int(1..10)

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