All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.databob.Databob.kt Maven / Gradle / Ivy

There is a newer version: 1.9.0
Show newest version
package io.github.databob

import kotlin.reflect.KParameter
import kotlin.reflect.defaultType
import kotlin.reflect.jvm.javaType

class Databob(vararg overrides: Generator) {
    private val defaults = listOf(
            LanguageConstructsGenerator(),
            DateTimeGenerator.instances.random,
            FunktionaleGenerator(),
            CollectionGenerator.instances.random,
            PrimitiveGenerator(),
            CoinToss.generators.even)

    private val generator = defaults.plus(overrides.toList()).fold(CompositeGenerator()) { memo, next -> memo.with(next) }

    inline fun  mk(): R {
        return mk(R::class.java)
    }

    @Suppress("UNCHECKED_CAST")
    fun  mk(c: Class): R = (generator.mk(c.kotlin.defaultType.javaType, this) ?: fallback(c)) as R

    private fun  fallback(c: Class): R {
        val constructor = c.kotlin.constructors.iterator().next()
        val generatedParameters = constructor.parameters
                .map {
                    if (it.type.isMarkedNullable) {
                        if (mk().toss()) {
                            convert(it)
                        } else {
                            null
                        }
                    } else {
                        convert(it)
                    }
                }
        return constructor.call(*generatedParameters.toTypedArray())
    }

    private fun convert(it: KParameter) = generator.mk(it.type.javaType, this) ?: mk(Class.forName(it.type.toString().replace("?", "")))
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy