如何创建案例类的随机实例?

时间:2018-06-03 12:10:37

标签: scala random shapeless random-data

假设我有几个案例类,例如:

case class C(c1: Int, c2: Double, c3: Option[String])
case class B(b: Int, cs: Seq[C])
case class A(a: String, bs: Seq[B]) 

现在我想生成一些A的实例,其中包含测试的随机值。

我正在寻找一种泛型方式来做到这一点。我可以用运行时反射来做,但我更喜欢编译时解决方案。

def randomInstance[A](a: A): A = ???

我该怎么办?是否可以使用shapeless完成?

3 个答案:

答案 0 :(得分:9)

最简单的方法是使用ScalaCheck。您可以通过为实例定义Gen[A]来实现此目的:

import org.scalacheck.Gen

final case class C(c1: Int, c2: Double, c3: Option[String])
object C {
  val cGen: Gen[C] = for {
    c1 <- Gen.posNum[Int]
    c2 <- Gen.posNum[Double]
    c3 <- Gen.option(Gen.oneOf("foo", "bar", "hello"))
  } yield C(c1, c2, c3)
}

你消耗它:

object F {
  def main(args: Array[String]): Unit = {
    val randomC: C = C.cGen.sample.get
  }
}

最重要的是,您可以添加scalacheck-shapeless为您生成Gen[A],并使用完全随机的值(您无法控制它们)。

您可能还想查看random-data-generator(感谢@Gabriele Petronella),这进一步简化了事情。来自文档:

import com.danielasfregola.randomdatagenerator.RandomDataGenerator

object MyApp extends RandomDataGenerator {

  case class Example(text: String, n: Int)

  val example: Example = random[Example]
  // Example(ਈ䈦㈾钜㔪旅ꪔ墛炝푰⡨䌆ᵅ퍧咪, 73967257)
}

这在property based testing中也特别有用。

答案 1 :(得分:2)

我们已经开始使用Magnolia,与任意形状的任意实例派生相比,它提供了更快的类型类派生。

Here是要使用的库,下面是一个示例(docs):

case class Inner(int: Int, str: String)
case class Outer(inner: Inner)

// ScalaCheck Arbitrary
import magnolify.scalacheck.auto._
import org.scalacheck._ // implicit instances for Arbitrary[Int], etc.

val arb: Arbitrary[Outer] = implicitly[Arbitrary[Outer]]
arb.arbitrary.sample
// = Some(Outer(Inter(12345, abcde)))

答案 2 :(得分:1)

我们刚刚摆脱了scalacheck-shapeless,而改用Scala / Java反射。

主要原因是:(1)scalacheck-shapeless使用宏(编译缓慢),(2)API比我喜欢的更加冗长,(3)生成的值太野了(例如,生成带有日语字符)。

但是,设置起来要复杂得多。这是完整的工作代码,您可以将其复制到代码库中:

{{ "{:02d}:{:02d}".format(start_hours, start_minutes) }}

而且,当您要使用它时,可以致电:

import scala.reflect.api
import scala.reflect.api.{TypeCreator, Universe}
import scala.reflect.runtime.universe._

object Maker {
  val mirror = runtimeMirror(getClass.getClassLoader)

  var makerRunNumber = 1

  def apply[T: TypeTag]: T = {
    val method = typeOf[T].companion.decl(TermName("apply")).asMethod
    val params = method.paramLists.head
    val args = params.map { param =>
      makerRunNumber += 1
      param.info match {
        case t if t <:< typeOf[Enumeration#Value] => chooseEnumValue(convert(t).asInstanceOf[TypeTag[_ <: Enumeration]])
        case t if t =:= typeOf[Int] => makerRunNumber
        case t if t =:= typeOf[Long] => makerRunNumber
        case t if t =:= typeOf[Date] => new Date(Time.now.inMillis)
        case t if t <:< typeOf[Option[_]] => None
        case t if t =:= typeOf[String] && param.name.decodedName.toString.toLowerCase.contains("email") => s"random-$arbitrary@give.asia"
        case t if t =:= typeOf[String] => s"arbitrary-$makerRunNumber"
        case t if t =:= typeOf[Boolean] => false
        case t if t <:< typeOf[Seq[_]] => List.empty
        case t if t <:< typeOf[Map[_, _]] => Map.empty
        // Add more special cases here.
        case t if isCaseClass(t) => apply(convert(t))
        case t => throw new Exception(s"Maker doesn't support generating $t")
      }
    }

    val obj = mirror.reflectModule(typeOf[T].typeSymbol.companion.asModule).instance
    mirror.reflect(obj).reflectMethod(method)(args:_*).asInstanceOf[T]
  }

  def chooseEnumValue[E <: Enumeration: TypeTag]: E#Value = {
    val parentType = typeOf[E].asInstanceOf[TypeRef].pre
    val valuesMethod = parentType.baseType(typeOf[Enumeration].typeSymbol).decl(TermName("values")).asMethod
    val obj = mirror.reflectModule(parentType.termSymbol.asModule).instance

    mirror.reflect(obj).reflectMethod(valuesMethod)().asInstanceOf[E#ValueSet].head
  }

  def convert(tpe: Type): TypeTag[_] = {
    TypeTag.apply(
      runtimeMirror(getClass.getClassLoader),
      new TypeCreator {
        override def apply[U <: Universe with Singleton](m: api.Mirror[U]) = {
          tpe.asInstanceOf[U # Type]
        }
      }
    )
  }

  def isCaseClass(t: Type) = {
    t.companion.decls.exists(_.name.decodedName.toString == "apply") &&
      t.decls.exists(_.name.decodedName.toString == "copy")
  }
}

上面的代码生成任意和唯一的值。它们不是完全随机的。最好在测试中使用。

在此处阅读我们的完整博客文章:https://give.engineering/2018/08/24/instantiate-case-class-with-arbitrary-value.html

相关问题