Skip to content

Commit

Permalink
prevent derivation of invalid seed via Seed.apply(0, 0, 0, 0)
Browse files Browse the repository at this point in the history
  • Loading branch information
nevillelyh committed Aug 13, 2020
1 parent 67d9054 commit fe0b747
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package magnolify.scalacheck.semiauto

import magnolia._
import magnolify.shims.Monadic
import org.scalacheck.rng.Seed
import org.scalacheck.{Arbitrary, Gen}

import scala.language.experimental.macros
Expand All @@ -36,14 +37,20 @@ object ArbitraryDerivation {
}

def dispatch[T: Fallback](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = Arbitrary {
Gen.sized { size =>
if (size > 0) {
Gen.resize(
size - 1,
Gen.oneOf(sealedTrait.subtypes.map(_.typeclass.arbitrary)).flatMap(identity)
)
} else {
implicitly[Fallback[T]].get
if (sealedTrait.typeName.full == classOf[Seed].getCanonicalName) {
// Prevent derivation of invalid seed via `Seed.apply(0, 0, 0, 0)`
// https://github.com/typelevel/scalacheck/pull/674
Arbitrary.arbLong.arbitrary.map(Seed(_)).asInstanceOf[Gen[T]]
} else {
Gen.sized { size =>
if (size > 0) {
Gen.resize(
size - 1,
Gen.oneOf(sealedTrait.subtypes.map(_.typeclass.arbitrary)).flatMap(identity)
)
} else {
implicitly[Fallback[T]].get
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ class ArbitraryDerivationSuite extends MagnolifySuite {
val prms = Gen.Parameters.default
// `forAll(Gen.listOfN(10, g))` fails for `Repeated` & `Collections` when size parameter <= 1
property(s"$name.uniqueness") {
Prop.forAll { l: Long =>
val seed = Seed(l) // prevent Magnolia from deriving `Seed`
Prop.forAll { seed: Seed =>
val xs = Gen.listOfN(10, g)(prms, seed).get
xs.iterator.map(f).toSet.size > 1
}
Expand Down Expand Up @@ -91,4 +90,10 @@ class ArbitraryDerivationSuite extends MagnolifySuite {

test[Shape]
test[Color]

property("Seed") {
Prop.forAll { seed: Seed =>
seed.next != seed
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,12 @@ class CogenDerivationSuite extends MagnolifySuite {
val name = className[T]
implicit val arbList: Arbitrary[List[T]] = Arbitrary(Gen.listOfN(10, arb.arbitrary))
property(s"$name.uniqueness") {
Prop.forAll { (l: Long, xs: List[T]) =>
val seed = Seed(l) // prevent Magnolia from deriving `Seed`
Prop.forAll { (seed: Seed, xs: List[T]) =>
xs.map(co.perturb(seed, _)).toSet.size == xs.map(f).toSet.size
}
}
property(s"$name.consistency") {
Prop.forAll { (l: Long, x: T) =>
val seed = Seed(l) // prevent Magnolia from deriving `Seed`
Prop.forAll { (seed: Seed, x: T) =>
co.perturb(seed, x) == co.perturb(seed, x)
}
}
Expand Down

0 comments on commit fe0b747

Please sign in to comment.