Skip to content

Instantly share code, notes, and snippets.

@dokwork
Last active July 3, 2019 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dokwork/b0ecfae4fb870c299faff6f023463a45 to your computer and use it in GitHub Desktop.
Save dokwork/b0ecfae4fb870c299faff6f023463a45 to your computer and use it in GitHub Desktop.
Derivation of the org.scalacheck.Arbitrary for case classes which was generated by the scalapb
// libraryDependencies += "com.github.alexarchambault" %% "scalacheck-shapeless_1.14" % "1.2.0"
// libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.14.0"
// libraryDependencies += "com.thesamet.scalapb" %% "scalapb-runtime" % "0.8.4"
import org.scalacheck.{ Arbitrary, Gen, ScalacheckShapeless }
import scalapb.{ GeneratedEnum, GeneratedEnumCompanion, TypeMapper }
/**
* Derives `or.scalacheck.Arbitrary` for generated by `scalapb` classes.
*
* @example
* {{{
* // Example.proto
* syntax = "proto3";
*
* package scalacheck.scalapb.example;
*
* message Example {
* enum Variants {
* A = 0;
* B = 1;
* }
* int64 id = 1;
* Variants vars = 3;
* }
*
* // scala
* import ScalaPbArbitrary._
* println(Arbitrary.arbitrary[Example].sample)
*
* // output
* Some(Example(5387,B))
* }}}
*/
trait ScalaPbArbitrary extends ScalacheckShapeless {
implicit def arbitraryNewtype[A, B](implicit typeMapper: TypeMapper[A, B], arb: Arbitrary[A]): Arbitrary[B] =
Arbitrary(arb.arbitrary.map(typeMapper.toCustom))
implicit def arbitraryEnum[T <: GeneratedEnum](implicit companion: GeneratedEnumCompanion[T]): Arbitrary[T] =
Arbitrary(Gen.oneOf(companion.values))
}
object ScalaPbArbitrary extends ScalaPbArbitrary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment