Skip to content

Instantly share code, notes, and snippets.

@puffnfresh
Created August 9, 2014 17:17
Show Gist options
  • Save puffnfresh/20666ff1077ba92f91e1 to your computer and use it in GitHub Desktop.
Save puffnfresh/20666ff1077ba92f91e1 to your computer and use it in GitHub Desktop.
Allow setting the specs2's ScalaCheck seed one sbt's command line
package com.simpleenergy
import java.util.Random
import org.specs2.ScalaCheck
import org.specs2.execute.{AsResult, Failure, Result}
import org.specs2.main.CommandLineArguments
import org.specs2.matcher.Parameters
import org.specs2.mutable.Specification
import org.specs2.specification.{Example, ExampleFactory}
import scalaz.syntax.monoid._
import scalaz.syntax.std.string._
/**
* Allow setting specs2's ScalaCheck seed on sbt's command line
*
* When running tests in sbt, you can now do this:
*
* > test-only *.ExampleTest -- seed 1407603641933
*
* When a test fails or errors, the seed will be printed:
*
* [info] double addition should
* [info] x be associative
* [error] A counter-example is [-8.988465674311579E307, 8.988465674311579E307, 1.0] (after 37 tries)
* [error] (Prop.scala:623)
* [error] ; Failed with seed of 1407604405985 (ExampleTest.scala:6)
**/
trait SimpleCheck extends Specification with ScalaCheck with CommandLineArguments {
lazy val seed =
arguments.commandLine.value("seed").flatMap(_.parseLong.toOption).getOrElse {
System.currentTimeMillis()
}
implicit lazy val simpleParams =
Parameters(rng = new Random(seed))
override def exampleFactory: ExampleFactory = new MutableExampleFactory {
override def newExample[T: AsResult](description: String, t: => T): Example = {
import Result.ResultFailureMonoid
val result = AsResult(t)
val updated =
if (result.isFailure || result.isError)
result |+| Failure(s"Failed with seed of ${seed}")
else
result
super.newExample(description, updated)
}
}
}
@etorreborre
Copy link

Hi Brian,

You probably you can trim it down to just overriding one implicit:

  val outer = this

  override implicit def propAsResult[P <: Prop](implicit p: Parameters): AsResult[P] = {
    new AsResult[P] {
      def asResult(prop: =>P): execute.Result = 
        outer.propAsResult(p.copy(rng = new Random(seed)))
          .asResult(prop).mapMessage(_+" with seed "+seed)
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment