org.specs2.ScalaCheck Scala Examples

The following examples show how to use org.specs2.ScalaCheck. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: MountIT.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.manage

import com.ning.http.client.Response
import com.ning.http.client.providers.jdk.JDKResponse
import janstenpickle.vault.core.VaultSpec
import janstenpickle.vault.manage.Model.{Mount, MountConfig}
import org.scalacheck.{Gen, Prop}
import org.specs2.ScalaCheck
import uscala.result.Result

class MountIT extends VaultSpec with ScalaCheck {
  import MountIT._
  import VaultSpec._

  def is =
    s2"""
      Can enable, remount and disable a valid mount $happy
      Can enable, list and then disable valid mounts $listSuccess
      Cannot enable an invalid mount type $enableFail
    """

  lazy val underTest = new Mounts(config)

  def happy = Prop.forAllNoShrink(
    mountGen,
    longerStrGen,
    longerStrGen,
    Gen.option(longerStrGen))((mount, mountPoint, remountPoint, desc) => {
      (underTest.mount(mount.`type`, Some(mountPoint), desc, Some(mount))
      .attemptRun(_.getMessage()) must beOk) and
      (underTest.remount(mountPoint, remountPoint)
      .attemptRun(_.getMessage()) must beOk) and
      (underTest.delete(remountPoint)
      .attemptRun(_.getMessage()) must beOk) and
      (underTest.delete(mountPoint)
      .attemptRun(_.getMessage()) must beOk)
    })

  def listSuccess = (processMountTypes((acc, mount) =>
    acc.flatMap(_ => underTest.mount(mount)
    .attemptRun(_.getMessage()))) must beOk) and
    (underTest.list.attemptRun(_.getMessage()) must beOk.like {
      case a => a.map(_._2.`type`) must containAllOf(mountTypes)
    }) and
    (processMountTypes((acc, mount) =>
      acc.flatMap(_ =>
          underTest.delete(mount).attemptRun(_.getMessage()))
    ) must beOk)

  def enableFail = Prop.forAllNoShrink(
    longerStrGen.suchThat(!mountTypes.contains(_)),
    longerStrGen,
    Gen.option(longerStrGen))((`type`, mount, desc) =>
      underTest.mount(`type`, Some(mount), desc)
        .attemptRun(_.getMessage()) must beFail
  )

}

object MountIT {
  import VaultSpec._

  val mountTypes = List(
    "aws", "cassandra", "consul", "generic",
    "mssql", "mysql", "pki", "postgresql", "ssh", "transit"
  )
  val mount = Gen.oneOf(mountTypes)
  val mounts = Gen.listOf(mountTypes).suchThat(_.nonEmpty)

  val mountGen = for {
    mountType <- mount
    description <- Gen.option(longerStrGen)
    defaultTtl <- Gen.option(Gen.posNum[Int])
    maxTtl <- Gen.option(Gen.posNum[Int])
    forceNoCache <- Gen.option(Gen.oneOf(true, false))
  } yield Mount(mountType, description, Some(MountConfig(defaultTtl, maxTtl, forceNoCache)))

  def processMountTypes(op: (Result[String, Response], String) => Result[String,
    Response]) =
      mountTypes.foldLeft[Result[String, Response]](Result.ok(new
        JDKResponse(null, null, null)))(op)

} 
Example 2
Source File: TimeFunSpec.scala    From scalaz-reactive   with Apache License 2.0 5 votes vote down vote up
package scalaz.reactive

import org.scalacheck.Gen
import org.specs2.{ ScalaCheck, Specification }
import scalaz._
import scalaz.reactive.Time.T
import scalaz.reactive.TimeFun._
import scalaz.reactive.laws.ApplicativeLaws

class TimeFunSpec extends Specification with ScalaCheck with TimeFunInstances {

  def is = "TimeFunSpec".title ^ s2"""
   Generate a mix of K and Fun TimeFuns
      `TimeFun.ap` holds identity law. ${laws.apIdentityLaw}
      `TimeFun.ap` holds homomorphism law. ${laws.apHomomorphismLaw}
      `TimeFun.ap` holds interchange law. ${laws.apInterchangeLaw}
      `TimeFun.ap` holds derived map law. ${laws.apDerivedMapLaw}
    """

  // generate values for the a:A
  def aGen: Gen[Long] =
    Gen.choose(-100, 100)

  def faGen =
    for {
      v   <- aGen
      k   <- aGen
      fun <- Gen.oneOf(K(v), Fun(_.value * k * v))
    } yield fun

  def abGen: Gen[Long => Long] =
    for {
      k <- aGen
    } yield (l: Long) => l * k

  def fabGen: Gen[TimeFun[Long => Long]] =
    for {
      k <- aGen
    } yield K((l: Long) => l + k)

  def eqGen: Gen[TimeFun[Long] => Long] =
    for {
      l <- Gen.choose[Long](-100, 100)
      t = T(l)
    } yield (tf: TimeFun[Long]) => tf.apply(t)

  val laws =
    new ApplicativeLaws(Applicative[TimeFun], aGen, faGen, abGen, fabGen, eqGen)

} 
Example 3
Source File: FibonacciTest.scala    From coding-interview-questions-scala   with Apache License 2.0 5 votes vote down vote up
package org.questions

import org.questions.fibonacci.{Fibonacci, Iterative, Recursive, TailRecursion}
import org.scalacheck.Gen
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}


trait FibonacciTest extends Specification with FibonacciProperty {
  val fib: Fibonacci

  "negative input" should {
    "be invalid" in {
      fib.nth(-1) must throwA[IllegalArgumentException]
    }
  }

  "0th" should {
    "be 0" in {
      fib.nth(0) must be_===(0)
    }
  }

  "1st" should {
    "be 1" in {
      fib.nth(1) must be_===(1)
    }
  }

  "2nd" should {
    "be 1" in {
      fib.nth(2) must be_===(1)
    }
  }
}

trait BigN {
  self: FibonacciTest =>

  import scala.concurrent.ExecutionContext.Implicits.global

  "big N" should {
    "be computed in sub seconds" in {
      val calcBigN = Future.apply {
        fib.nth(100)
      }

      Await.ready(calcBigN, Duration("1 second")).isCompleted must beTrue
    }
  }
}

trait FibonacciProperty extends ScalaCheck {
  self: FibonacciTest =>

  val smallInteger = Gen.choose[Int](2,30)

  "fib(n)" should {
    "be equal to the sum of the results of last 2 elements" >> prop { n: Int =>
      fib.nth(n) must be_===(fib.nth(n - 1) + fib.nth(n - 2))
    }.setGen(smallInteger)
  }
}

class RecursiveTest extends FibonacciTest {
  override val fib = new Recursive
}

class IterativeTest extends FibonacciTest with BigN {
  override val fib = new Iterative
}

class TailRecursionTest extends FibonacciTest with BigN {
  override val fib: Fibonacci = new TailRecursion
} 
Example 4
Source File: ValidateCodec.scala    From scala-pathy   with Apache License 2.0 5 votes vote down vote up
package pathy

import slamdata.Predef._
import pathy.Path._
import pathy.scalacheck.PathyArbitrary._

import org.specs2.mutable.SpecLike
import org.specs2.specification.core.Fragment
import org.specs2.ScalaCheck

trait ValidateCodec extends SpecLike with ScalaCheck {

  
  @SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements"))
  protected def validateIsLossless(codec: PathCodec): Fragment = {
    "print and parse again should produce same Path" >> {
      "absolute file" >> prop { path: AbsFile[Sandboxed] =>
        codec.parseAbsFile(codec.printPath(path)) must_== Some(path)
      }
      "relative file" >> prop { path: RelFile[Sandboxed] =>
        codec.parseRelFile(codec.printPath(path)) must_== Some(path)
      }
      "absolute dir" >> prop { path: AbsDir[Sandboxed] =>
        codec.parseAbsDir(codec.printPath(path)) must_== Some(path)
      }
      "relative dir" >> prop { path: RelDir[Sandboxed] =>
        codec.parseRelDir(codec.printPath(path)) must_== Some(path)
      }
    }
  }
} 
Example 5
Source File: PathSpecs.scala    From scala-pathy   with Apache License 2.0 5 votes vote down vote up
package pathy

import slamdata.Predef._
import pathy.scalacheck._

import scala.Predef.identity

import org.scalacheck._, Arbitrary.arbitrary
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
import scalaz.scalacheck.ScalazProperties._
import scalaz.syntax.foldable._

class PathSpecs extends Specification with ScalaCheck {
  import Path._, PathyArbitrary._

  "FileName" in {
    "order laws" >> order.laws[FileName]
  }

  "DirName" in {
    "order laws" >> order.laws[DirName]
  }

  "Path" in {
    implicit val arbitraryPath: Arbitrary[Path[Any,Any,Sandboxed]] =
      Arbitrary(Gen.oneOf(
        arbitrary[AbsFile[Sandboxed]],
        arbitrary[RelFile[Sandboxed]],
        arbitrary[AbsDir[Sandboxed]],
        arbitrary[RelDir[Sandboxed]]))

    "order laws" >> order.laws[Path[Any,Any,Sandboxed]]
  }

  "</> - ./../foo/" in {
    posixCodec.unsafePrintPath(parentDir1(currentDir) </> unsandbox(dir("foo"))) must_== "./../foo/"
  }

  "parentDir1 - ./../foo/../" in {
    posixCodec.unsafePrintPath((parentDir1(currentDir) </> unsandbox(dir("foo"))) </> parentDir1(currentDir)) must_== "./../foo/../"
  }

  "<::>" >> {
    "./../" in {
      posixCodec.unsafePrintPath(currentDir <::> currentDir) must_== "./../"
    }

    "./../foo/" in {
      posixCodec.unsafePrintPath(currentDir <::> dir("foo")) must_== "./../foo/"
    }

    "./../foo/../" in {
      posixCodec.unsafePrintPath((currentDir <::> dir("foo")) <::> currentDir) must_== "./../foo/../"
    }
  }

  "canonicalize" >> {
    "1 down, 1 up" in {
      canonicalize(parentDir1(dir("foo"))) must_== currentDir
    }

    "2 down, 2 up" in {
      canonicalize(parentDir1(parentDir1(dir("foo") </> dir("bar")))) must_== currentDir
    }
  }

  "relativeTo" >> {
    "simple case" >> {
      (rootDir </> dir("foo")).relativeTo(rootDir) must_== Some(dir("foo"))
    }
    "return currentDir if same path" >> {
      (rootDir </> dir("foo")).relativeTo(rootDir </> dir("foo")) must_== Some(currentDir)
    }
  }

  "renameFile - single level deep" in {
    renameFile(file("image.png"), _.dropExtension) must_== file("image")
  }

  "sandbox - sandbox absolute dir to one level higher" in {
    sandbox(rootDir </> dir("foo"), rootDir </> dir("foo") </> dir("bar")) must beSome.which {
      _ must_== dir("bar")
    }
  }

  "depth - negative" in {
    depth(parentDir1(parentDir1(parentDir1(currentDir)))) must_== -3
  }

  "flatten - returns NEL of result of folding each layer of path" in {
    flatten(
      "r", "c", "p", identity, identity,
      currentDir </> dir("foo") </> dir("bar") </> file("flat.md")
    ).toList must_== List("c", "foo", "bar", "flat.md")
  }
} 
Example 6
Source File: PosixCodecJsonSpec.scala    From scala-pathy   with Apache License 2.0 5 votes vote down vote up
package pathy.argonaut

import slamdata.Predef._
import pathy.Path, Path._
import pathy.scalacheck.PathyArbitrary._

import argonaut._, Argonaut._
import org.specs2.mutable
import org.specs2.ScalaCheck

final class PosixCodecJsonSpec extends mutable.Specification with ScalaCheck {
  import PosixCodecJson._

  "RelFile Codec" ! prop { rf: RelFile[Sandboxed] =>
    CodecJson.codecLaw(CodecJson.derived[RelFile[Unsandboxed]])(unsandbox(rf))
  }

  "RelDir Codec" ! prop { rd: RelDir[Sandboxed] =>
    CodecJson.codecLaw(CodecJson.derived[RelDir[Unsandboxed]])(unsandbox(rd))
  }

  "AbsFile Codec" ! prop { af: AbsFile[Sandboxed] =>
    CodecJson.codecLaw(CodecJson.derived[AbsFile[Sandboxed]])(af)
  }

  "AbsDir Codec" ! prop { ad: AbsDir[Sandboxed] =>
    CodecJson.codecLaw(CodecJson.derived[AbsDir[Sandboxed]])(ad)
  }

  "RelFile encode" ! prop { rf: RelFile[Sandboxed] =>
    rf.asJson ==== jString(posixCodec.printPath(rf))
  }

  "RelDir encode" ! prop { rd: RelDir[Sandboxed] =>
    rd.asJson ==== jString(posixCodec.printPath(rd))
  }

  "AbsFile encode" ! prop { af: AbsFile[Sandboxed] =>
    af.asJson ==== jString(posixCodec.printPath(af))
  }

  "AbsFile encode" ! prop { ad: AbsDir[Sandboxed] =>
    ad.asJson ==== jString(posixCodec.printPath(ad))
  }

  "Decode failure" ! prop { s: String =>
    (!s.isEmpty && !s.contains('\\') && !s.contains('"')) ==> {

    val jstr = s""""$s""""

    def decodeAs[X: DecodeJson]: Either[String, X] =
      jstr.decodeWithEither[Either[String, X], X](
        Right(_),
        e => Left(e.fold(s => s, _._1)))

    (decodeAs[RelDir[Unsandboxed]] must beLeft("RelDir[Unsandboxed]")) and
    (decodeAs[AbsDir[Sandboxed]] must beLeft("AbsDir[Sandboxed]"))
  }}
} 
Example 7
Source File: potentialFailure.scala    From matryoshka   with Apache License 2.0 5 votes vote down vote up
package matryoshka.patterns

import slamdata.Predef._
import matryoshka._
import matryoshka.data.Fix
import matryoshka.exp._
import matryoshka.scalacheck.arbitrary._

import org.scalacheck._
import org.specs2.ScalaCheck
import org.specs2.mutable._
import scalaz._, Scalaz._
import scalaz.scalacheck.ScalazProperties._

class PotentialFailureSpec extends Specification with ScalaCheck {
  implicit def potentialFailureArbitrary[T[_[_]], F[_], E: Arbitrary](
    implicit T: Arbitrary[T[F]], F: Delay[Arbitrary, F]):
      Delay[Arbitrary, PotentialFailure[T, F, E, ?]] =
    new Delay[Arbitrary, PotentialFailure[T, F, E, ?]] {
      def apply[α](arb: Arbitrary[α]) =
        Arbitrary(Gen.oneOf(
          T.arbitrary.map(Success[T, F, E, α](_)),
          Arbitrary.arbitrary[E].map(Failure[T, F, E, α](_)),
          F(arb).arbitrary.map(PartialFailure[T, F, E, α](_))))
    }

  "PotentialFailure" >> {
    addFragments(properties(equal.laws[PotentialFailure[Fix, Exp, String, Int]]))
    addFragments(properties(bitraverse.laws[PotentialFailure[Fix, Exp, ?, ?]]))
    addFragments(properties(traverse.laws[PotentialFailure[Fix, Exp, String, ?]]))
  }
} 
Example 8
Source File: zygoSpec.scala    From matryoshka   with Apache License 2.0 5 votes vote down vote up
package matryoshka

import slamdata.Predef._
import matryoshka.data._
import matryoshka.exp._
import matryoshka.helpers._
import matryoshka.implicits._
import matryoshka.runners._

import org.scalacheck._, Prop._
import org.specs2.ScalaCheck
import org.specs2.mutable._
import org.specs2.scalaz.ScalazMatchers
import scalaz._, Scalaz._

class ZygoSpecs extends Specification with ScalaCheck with ScalazMatchers {

  def extractFactors2: Coalgebra[Exp, Int] = { x =>
    def sqrt(x: Int): Int = scala.math.sqrt(x.toDouble).toInt

    if (x > 1 && sqrt(x) * sqrt(x) == x) Mul(sqrt(x), sqrt(x))
    else if (x > 2 && x % 2 == 0) Mul(2, x/2)
    else Num(x)
  }

  "Recursive" >> {
    "zygo" >> {
      "eval and strings" in {
        testRec(
          mul(mul(num(0), num(0)), mul(num(2), num(5))),
          new RecRunner[Exp, String] {
            def run[T](implicit T: Recursive.Aux[T, Exp]) =
              _.zygo(eval, strings) must
            equal("0 (0), 0 (0) (0), 2 (2), 5 (5) (10)")
          })
      }
    }

    "zygoM" >> {
      "behave like zygo" >> prop { (i: Int) =>
        val factors = i.ana[Fix[Exp]](extractFactors)

        val a = factors.zygo(eval, strings)
        val b = factors.zygoM[String, Int, Int \/ ?](
          eval.generalizeM[Int \/ ?], strings(_).right)

        a.right ?= b
      }
    }

    "elgotZygo" >> {
      "eval and elgotStrings" in {
        testRec(
          mul(mul(num(0), num(0)), mul(num(2), num(5))),
          new RecRunner[Exp, Int \/ String] {
            def run[T](implicit T: Recursive.Aux[T, Exp]) =
              _.elgotZygoM[String, Int, Int \/ ?](
                eval.generalizeM[Int \/ ?],
                elgotStrings(_).right
              ) must equal("((0 * 0 = 0) * (2 * 5 = 10) = 0)".right)
          })
      }
    }

    "elgotZygoM" >> {
      "behave like elgotZygo" >> prop { (i: Int) =>
        val factors = i.ana[Fix[Exp]](extractFactors2)

        val a = factors.elgotZygo(eval, elgotStrings)
        val b = factors.elgotZygoM[String, Int, Int \/ ?](
          eval.generalizeM[Int \/ ?], elgotStrings(_).right)

        a.right ?= b
      }
    }
  }
} 
Example 9
Source File: list.scala    From matryoshka   with Apache License 2.0 5 votes vote down vote up
package matryoshka.instances.fixedpoint

import slamdata.Predef._
import matryoshka._
import matryoshka.data.list._
import matryoshka.implicits._
import matryoshka.patterns._
import matryoshka.scalacheck.arbitrary._

import org.specs2.ScalaCheck
import org.specs2.mutable._
import org.specs2.scalaz.ScalazMatchers
import scalaz._, Scalaz._
import scalaz.scalacheck.{ScalazProperties => Props}

class ListSpec extends Specification with ScalaCheck with ScalazMatchers {
  "List laws" >> {
    addFragments(properties(Props.equal.laws[List[Int]]))
    addFragments(properties(Props.foldable.laws[List]))
  }


  "apply" should {
    "be equivalent to scala.List.apply" in {
      List(1, 2, 3, 4).cata(ListF.listIso.get) must
        equal(scala.List(1, 2, 3, 4))
    }
  }

  "fill" should {
    "be equivalent to scala.List.fill" >> prop { (n: Nat, v: Int) =>
      List.fill[scala.List[Int]](n)(v) must
        equal(scala.List.fill(n.toInt)(v))
    }
  }

  "length" should {
    "count the number of elements" >> prop { (n: Nat, v: Int) =>
      List.fill[List[Int]](n)(v).length must equal(n.toInt)
    }
  }

  "headOption" should {
    "return the first element" in {
      List(1, 2, 3, 4).headOption must beSome(1)
    }

    "if there is one" in {
      List().headOption must beNone
    }
  }

  "tailOption" should {
    "return the remainder of the list" in {
      List(1, 2, 3, 4).tailOption must equal(List(2, 3, 4).some)
      List(1).tailOption must equal(List[Int]().some)
    }

    "if there is one" in {
      List().tailOption must beNone
    }
  }
} 
Example 10
Source File: stream.scala    From matryoshka   with Apache License 2.0 5 votes vote down vote up
package matryoshka.instances.fixedpoint

import slamdata.Predef._
import matryoshka._
import matryoshka.implicits._
import matryoshka.scalacheck.arbitrary._

import org.specs2.ScalaCheck
import org.specs2.mutable._
import org.specs2.scalaz.{ScalazMatchers}
import scalaz._, Scalaz._

class StreamSpec extends Specification with ScalaCheck with ScalazMatchers {
  
  def constantly[A]: Coalgebra[(A, ?), A] = i => (i, i)

  "fib" should {
    "begin with 1" in {
      fib.head must equal(1)
    }

    "lazily generate the correct sequence" in {
      5.anaM[Nat](Nat.fromInt) ∘ (fib.drop(_).head) must equal(8.some)
    }

    "have a proper prefix" in {
      5.anaM[Nat](Nat.fromInt) ∘ (fib.take[List[Int]](_)) must
        equal(List(1, 1, 2, 3, 5).some)
    }

    "get a subsequence" in {
      (10.anaM[Nat](Nat.fromInt) ⊛ 5.anaM[Nat](Nat.fromInt))((d, t) =>
        fib.drop(d).take[List[Int]](t)) must
        equal(List(89, 144, 233, 377, 610).some)
    }
  }

  "constantly" should {
    "begin with the given value" >> prop { (i: Int) =>
      i.ana[Stream[Int]](constantly).head must_== i
    }

    // FIXME: These two blow up the stack with much larger inputs

    "have the given value at an arbitrary point" >> prop { (i: Int, d: Int) =>
      350.anaM[Nat](Nat.fromInt) ∘
        (i.ana[Stream[Int]](constantly).drop(_).head) must
        equal(i.some)
    }

    "have subsequence of the given value" >> prop { (n: Nat, i: Int, t: Int) =>
      i.ana[Stream[Int]](constantly).take[List[Int]](n) must
        equal(List.fill[List[Int]](n)(i))
    }
  }
} 
Example 11
Source File: partial.scala    From matryoshka   with Apache License 2.0 5 votes vote down vote up
package matryoshka.instances.fixedpoint

import slamdata.Predef._
import matryoshka._
import matryoshka.implicits._
import matryoshka.scalacheck.arbitrary._

import scala.Predef.implicitly

import org.scalacheck._
import org.specs2.ScalaCheck
import org.specs2.mutable._
import org.specs2.scalaz.{ScalazMatchers}
import scalaz._, Scalaz._
import scalaz.scalacheck.{ScalazProperties => Props}

class PartialSpec extends Specification with ScalazMatchers with ScalaCheck {
  
  def sometimesNeverGen[A: Arbitrary]: Gen[Partial[A]] =
    Gen.oneOf(Arbitrary.arbitrary[Partial[A]], Gen.const(Partial.never[A]))

  "Partial laws" >> {

    addFragments(properties(Props.equal.laws[Partial[Int]](Partial.equal, implicitly)))
    addFragments(properties(Props.monad.laws[Partial](implicitly, implicitly, implicitly, implicitly, Partial.equal)))
    addFragments(properties(Props.foldable.laws[Partial]))
  }

  // https://en.wikipedia.org/wiki/McCarthy_91_function
  def mc91(n: Int): Partial[Int] =
    if (n > 100) Partial.now(n - 10)
    else mc91(n + 11) >>= mc91

  "never" should {
    "always have more steps" >> prop { (i: Conat) =>
      Partial.never[Int].runFor(i) must beRightDisjunction
    }
  }

  "runFor" should {
    "return now immediately" in {
      Partial.now(13).runFor(Nat.zero[Nat]) must beLeftDisjunction(13)
    }

    "return a value when it runs past the end" >> prop { (i: Conat) =>
      i.transAna[Partial[Int]](Partial.delay(7)).runFor(i) must
        beLeftDisjunction(7)
    }

    "return after multiple runs" >> prop { (a: Conat, b: Conat) =>
      b > Nat.zero[Conat] ==> {
        val first = (a + b).transAna[Partial[Int]](Partial.delay(27)).runFor(a)
        first must beRightDisjunction
        first.flatMap(_.runFor(b)) must beLeftDisjunction(27)
      }
    }

    "still pending one short" >> prop { (a: Conat) =>
      val first = (a + Nat.one[Conat]).transAna[Partial[Int]](Partial.delay(27)).runFor(a)
      first must beRightDisjunction
      first.flatMap(_.runFor(a + Nat.one[Conat])) must beLeftDisjunction(27)
    }

    "return exactly at the end" >> prop { (n: Conat, i: Int) =>
      n.transAna[Partial[Int]](Partial.delay(i)).runFor(n) must
        beLeftDisjunction(i)
    }
  }

  "unsafePerformSync" should {
    "return now immediately" in {
      Partial.now(12).unsafePerformSync must equal(12)
    }

    "return a value when it gets to the end" in {
      Partial.later(Partial.later(Partial.now(3))).unsafePerformSync must
        equal(3)
    }

    // NB: This test will depend on the size of your stack, you may have to
    //     increase the initial value on larger stacks.
    "return a value well after stack would overflow" in {
      100000000.ana[Partial[Unit]](i => if (i ≟ 0) ().left else (i - 1).right)
        .unsafePerformSync must
        equal(())
    }

    // NB: This is because the following test doesn't always get close to the
    //     lower bound, so we make sure changes don't make things worse.
    "check lower bound of mc91" in {
      mc91(-150000).unsafePerformSync must equal(91)
    }

    // TODO: Should work with any Int, but stack overflows on big negatives.
    "always terminate with mc91" >> prop { (n: Int) =>
      n > -150000 ==>
        (mc91(n).unsafePerformSync must equal(if (n <= 100) 91 else n - 10))
    }
  }
} 
Example 12
Source File: SpecHelper.scala    From finch-template   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.redbubble.finchtemplate.util.spec

import com.redbubble.util.async.singleThreadedFuturePool
import com.redbubble.util.json.CodecOps
import com.redbubble.util.log.Logger
import org.specs2.ScalaCheck
import org.specs2.execute.{Failure, Result}
import org.specs2.mutable.Specification
import org.specs2.specification.BeforeAll

trait SpecLogging {
  final val log = new Logger("finch-template-test")(singleThreadedFuturePool)
}

object SpecLogging extends SpecLogging

trait SpecHelper extends TestEnvironmentSetter with SpecLogging with ScalaCheck with FinchTemplateGenerators
    with CodecOps with BeforeAll {
  self: Specification =>
  override def beforeAll(): Unit = setEnvironment()

  final def fail(message: String, t: Throwable): Result = Failure(message, "", t.getStackTrace.toList)
} 
Example 13
Source File: UserPassIT.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.auth

import janstenpickle.vault.core.VaultSpec
import janstenpickle.vault.manage.Auth
import org.scalacheck.{Gen, Prop}
import org.specs2.ScalaCheck
import org.specs2.matcher.MatchResult

class UserPassIT extends VaultSpec with ScalaCheck {
  import VaultSpec._

  override def is =
    s2"""
      Can authenticate a user against a specific "client" path $authPass
      Fails to authenticate a user $end
        against a bad "client" path $badClient
        with a non-existent username $badUser
        with a bad password $badPassword
    """

  lazy val underTest = UserPass(config.wsClient)
  lazy val authAdmin = Auth(config)
  lazy val userAdmin = janstenpickle.vault.manage.UserPass(config)

  def setupClient(client: String) = authAdmin.enable("userpass", Some(client))
    .attemptRun(_.getMessage()) must beOk

  def setupUser(username: String, password: String, client: String) =
    userAdmin.create(username, password, 30, None, client)
    .attemptRun(_.getMessage())

  def removeClient(client: String) =
    authAdmin.disable(client).attemptRun(_.getMessage()) must beOk

  def authPass = test((username, password, client, ttl) =>
                        setupClient(client) and
    (setupUser(username, password, client) must beOk) and
    (underTest.authenticate(username, password, ttl, client)
    .attemptRun(_.getMessage()) must beOk) and
    removeClient(client)
  )

  // TODO: test below may fail rarely (e.g. client is same as badClientName)

  def badClient = test{ (username, password, client, ttl) =>
    val badClientName = "nic-kim-cage-client"
    setupClient(badClientName) and
    (setupUser(username, password, client) must beFail) and
    (underTest.authenticate(username, password, ttl, client)
    .attemptRun(_.getMessage()) must beFail) and
    removeClient(badClientName)
  }

  def badUser = test{ (username, password, client, ttl) =>
    val badUserName = "nic-kim-cage-user"
    setupClient(client) and
    (setupUser(username, password, client) must beOk) and
    (underTest.authenticate(badUserName, password, ttl, client)
    .attemptRun(_.getMessage()) must beFail) and
    removeClient(client)
  }

  def badPassword = test{ (username, password, client, ttl) =>
    val badPasswordValue = "nic-kim-cage-password"
    setupClient(client) and
    (setupUser(username, password, client) must beOk) and
    (underTest.authenticate(username, badPasswordValue, ttl, client)
    .attemptRun(_.getMessage()) must beFail) and
    removeClient(client)
  }

  def test(op: (String, String, String, Int) => MatchResult[Any]) =
    Prop.forAllNoShrink(
      longerStrGen,
      longerStrGen,
      Gen.numStr.suchThat(_.nonEmpty), Gen.posNum[Int]
    )(op)
} 
Example 14
Source File: AuthIT.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.manage

import janstenpickle.vault.core.VaultSpec
import org.scalacheck.{Prop, Gen}
import org.specs2.ScalaCheck

class AuthIT extends VaultSpec with ScalaCheck {
  import AuthIT._
  import VaultSpec._

  def is =
    s2"""
      Can enable and disable valid auth mount $happy
      Cannot enable an invalid auth type $enableFail
    """

  lazy val underTest = new Auth(config)

  def happy = Prop.forAllNoShrink(
    backends, longerStrGen, Gen.option(longerStrGen))((backend, mount, desc) =>
      (underTest.enable(backend, Some(mount), desc)
      .attemptRun(_.getMessage()) must beOk) and
      (underTest.disable(mount).attemptRun(_.getMessage()) must beOk)
  )

  def enableFail = Prop.forAllNoShrink(
    longerStrGen.suchThat(!backendNames.contains(_)),
    longerStrGen,
    Gen.option(longerStrGen))((backend, mount, desc) =>
      underTest.enable(mount).attemptRun(_.getMessage()) must beFail
  )

}

object AuthIT {
  val backendNames = List("github", "app-id", "ldap", "userpass")
  val backends = Gen.oneOf(backendNames)
} 
Example 15
Source File: PolicyIT.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.manage

import janstenpickle.vault.core.VaultSpec
import janstenpickle.vault.manage.Model.Rule
import org.scalacheck.{Gen, Prop}
import org.specs2.ScalaCheck
import uscala.result.Result

class PolicyIT extends VaultSpec with ScalaCheck {
  import PolicyIT._
  import VaultSpec._

  override def is =
    s2"""
      Can successfully set and get policies $happy
      Cannot set an invalid policy $sad
    """

  lazy val underTest = Policy(config)

  def happy = Prop.forAllNoShrink(
    longerStrGen,
    Gen.listOf(ruleGen(longerStrGen, policyGen, capabilitiesGen)).
    suchThat(_.nonEmpty)) { (name, rules) =>
      (underTest.set(name.toLowerCase, rules)
      .attemptRun(_.getMessage()) must beOk) and
      (underTest.inspect(name.toLowerCase)
      .attemptRun(_.getMessage()) must beOk) and
      (underTest.delete(name.toLowerCase).attemptRun(_.getMessage()) must beOk)
  }

  // cannot use generated values here as
  // vault seems to have a failure rate limit
  def sad = underTest.set(
    "nic", List(Rule("cage", Some(List("kim", "copolla"))))
  ).attemptRun(_.getMessage()) must beFail
}

object PolicyIT {
  val policyGen = Gen.option(Gen.oneOf("read", "write", "sudo", "deny"))
  val capabilitiesGen =
    Gen.listOf(Gen.oneOf(
      "create", "read", "update", "delete", "list", "sudo", "deny")).
      suchThat(_.nonEmpty).
      map(_.distinct)

  def ruleGen(
    pathGen: Gen[String],
    polGen: Gen[Option[String]],
    capGen: Gen[List[String]]
  ) = for {
    path <- pathGen
    policy <- polGen
    capabilities <- capGen
  } yield Rule(path, Some(capabilities), policy)
} 
Example 16
Source File: LoggingSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli

import org.mockito.{ArgumentCaptor, Matchers}
import org.scalacheck.Gen
import org.specs2.ScalaCheck
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

import scala.util.matching.Regex

class LoggingSpec extends Specification with Mockito with ScalaCheck {
  import logging._

  trait F[T] {
    def body(): T

    def log(message: String): Unit
  }

  "logging the execution time" should {

    "execute the block just once" in {
      val f = mock[F[Unit]]

      logExecutionTime("foo") {
        f.body()
      }(Function.const(()))

      there was one(f).body()
      there was no(f).log(Matchers.any[String]())
    }

    "invokes the log function" in prop { label: String =>
      val f = mock[F[Int]]

      logExecutionTime(label) {
        42
      }(f.log(_))

      val message = ArgumentCaptor.forClass(classOf[String])
      there was one(f).log(message.capture())
      message.getValue must beMatching(s"${Regex.quote(label)} took \\d+ ms")

      there was no(f).body()
    }.setGen(Gen.identifier.label("label"))

    "returns the result of the body" in prop { ret: Int =>
      logExecutionTime("foo") {
        ret
      }(Function.const(())) === ret
    }
  }

} 
Example 17
Source File: UserPassIT.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.manage

import janstenpickle.vault.core.VaultSpec
import org.scalacheck.{Gen, Prop}
import org.specs2.ScalaCheck

class UserPassIT extends VaultSpec with ScalaCheck {
  import UserPassIT._
  import VaultSpec._

  def is =
    s2"""
      Can create, update and delete a user $good
      Cannot create a user for a non-existent client $badClient
      Cannot create user with a bad policy $badPolicy
    """

  lazy val underTest = UserPass(config)
  lazy val authAdmin = Auth(config)

  def good = Prop.forAllNoShrink(longerStrGen, longerStrGen, longerStrGen, Gen.posNum[Int], longerStrGen, policyGen)(
    (username, password, newPassword, ttl, client, policy) =>
      (authAdmin.enable("userpass", Some(client)).attemptRun(_.getMessage()) must beOk) and
      (underTest.create(username, password, ttl, None, client).attemptRun(_.getMessage()) must beOk) and
      (underTest.setPassword(username, newPassword, client).attemptRun(_.getMessage()) must beOk) and
      (underTest.setPolicies(username, policy, client).attemptRun(_.getMessage()) must beOk) and
      (underTest.delete(username, client).attemptRun(_.getMessage()) must beOk) and
      (authAdmin.disable(client).attemptRun(_.getMessage()) must beOk)
  )

  def badClient = Prop.forAllNoShrink(longerStrGen, longerStrGen, Gen.posNum[Int], longerStrGen)(
    (username, password, ttl, client) =>
      underTest.create(username, password, ttl, None, client).attemptRun(_.getMessage()) must beFail
  )

  def badPolicy = Prop.forAllNoShrink(longerStrGen,
                                      longerStrGen,
                                      Gen.posNum[Int],
                                      longerStrGen,
                                      Gen.listOf(longerStrGen.suchThat(!policies.contains(_))))(
    (username, password, ttl, client, policy) =>
      (authAdmin.enable("userpass", Some(client)).attemptRun(_.getMessage()) must beOk) and
      (underTest.create(username, password, ttl, Some(policy), client).attemptRun(_.getMessage()) must beOk) and
      (authAdmin.disable(client).attemptRun(_.getMessage()) must beOk)
  )
}

object UserPassIT {
  val policies = List("default", "root")
  val policyGen = Gen.listOf(Gen.oneOf(policies))
} 
Example 18
Source File: RuleSpec.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.manage

import janstenpickle.vault.manage.Model.Rule
import org.scalacheck.{Gen, Prop}
import org.specs2.{ScalaCheck, Specification}
import uscala.result.specs2.ResultMatchers

class RuleSpec extends Specification with ScalaCheck with ResultMatchers {
  import RuleSpec._

  override def is =
    s2"""
      Can encode and decode policy strings $passes
      Cannot decode bad policy strings $fails
      """

  def passes = Prop.forAllNoShrink(Gen.listOf(ruleGen).suchThat(_.nonEmpty)) (rules =>
    Rule.decode(rules.map(_.encode).mkString("\n")) must beOk.like {
      case a => a must containAllOf(rules)
    }
  )

  def fails = Prop.forAllNoShrink(Gen.listOf(badRuleGen).suchThat(_.nonEmpty)) (rules =>
    Rule.decode(rules.mkString("\n")) must beFail
  )
}

object RuleSpec {
  val policyGen = Gen.option(Gen.oneOf("read", "write", "sudo", "deny"))
  val capabilitiesGen = Gen.option(
    Gen.listOf(Gen.oneOf("create", "read", "update", "delete", "list", "sudo", "deny")).
      suchThat(_.nonEmpty).
      map(_.distinct)
  )

  val ruleGen = for {
    path <- Gen.alphaStr.suchThat(_.nonEmpty)
    policy <- policyGen
    capabilities <- capabilitiesGen
  } yield Rule(path, capabilities, policy)

  val badRuleGen = for {
    path <- Gen.alphaStr.suchThat(_.nonEmpty)
    policy <- policyGen
    capabilities <- capabilitiesGen
  } yield
    s"""
       |path "$path"
       |   $policy cage
       |   $capabilities }""".stripMargin('|')
} 
Example 19
Source File: SecretsIT.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.core

import org.scalacheck.Prop
import org.specs2.ScalaCheck

class GenericIT extends SecretsTests {
  override def backend: String = "secret"
}

class CubbyHoleIT extends SecretsTests {
  override def backend: String = "cubbyhole"
}

trait SecretsTests extends VaultSpec with ScalaCheck {
  import VaultSpec._

  override def is =
    s2"""
      Can set a secret in vault $set
      Can set and get a secret in vault $get
      Can list keys $list
      Can set multiple subkeys $setMulti
      Can set and get multiple subKeys $getSetMulti
      Cannot get non-existent key $failGet
      Fails to perform actions on a non-vault server $failSetBadServer
      Fails to perform actions with a bad token $failSetBadToken
      """

  def backend: String

  lazy val good = Secrets(config, backend)
  lazy val badToken = Secrets(badTokenConfig, backend)
  lazy val badServer = Secrets(badServerConfig, backend)

  def set = Prop.forAllNoShrink(strGen, strGen) { (key, value) =>
    good.set(key, value).attemptRun(_.getMessage()) must beOk
  }

  def get = Prop.forAllNoShrink(strGen, strGen) { (key, value) =>
    (good.set(key, value).attemptRun(_.getMessage()) must beOk) and
    (good.get(key).attemptRun(_.getMessage()) must beOk.like {
      case a => a === value
    })
  }

  def list = Prop.forAllNoShrink(strGen, strGen, strGen) { (key1, key2, value) =>
    (good.set(key1, value).attemptRun(_.getMessage()) must beOk) and
    (good.set(key2, value).attemptRun(_.getMessage()) must beOk) and
    (good.list.attemptRun(_.getMessage()) must beOk[List[String]].like {
      case a => a must containAllOf(Seq(key1, key2))
    })
  }

  def setMulti = Prop.forAllNoShrink(strGen, strGen, strGen, strGen) {
    (key1, key2, value1, value2) =>
    good.set(
      "nicolas-cage",
      Map(key1 -> value1, key2 -> value2)
    ).attemptRun(_.getMessage()) must beOk
  }

  def getSetMulti = Prop.forAllNoShrink(
    strGen, strGen, strGen, strGen, strGen
  ) { (key1, key2, value1, value2, mainKey) =>
    val testData = Map(key1 -> value1, key2 -> value2)
    (good.set(mainKey, testData).attemptRun(_.getMessage()) must beOk) and
    (good.getAll(mainKey).attemptRun(_.getMessage()) must beOk.like {
      case a => a === testData
    })
  }

  def failGet = good.get("john").attemptRun(_.getMessage()) must beFail.
    like { case err =>
      err must contain("Received failure response from server: 404")
    }

  def failSetBadServer = badServer.set(
    "nic", "cage"
  ).attemptRun(_.getMessage()) must beFail

  def failSetBadToken = badToken.set(
    "nic", "cage"
  ).attemptRun(_.getMessage()) must beFail
} 
Example 20
Source File: CodecSpec.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.tests

import scala.math.BigInt

import org.specs2.{ScalaCheck, Specification}
import org.specs2.specification.core.Env

import org.scalacheck._
import org.scalacheck.Prop.forAll

import info.hupel.isabelle._
import info.hupel.isabelle.api.XML

class CodecSpec(val specs2Env: Env) extends Specification with BasicSetup with ScalaCheck { def is = s2"""

  Round-trip property of Codecs

  Values can be converted
    of type Unit                      ${propCodec[Unit]}
    of type Boolean                   ${propCodec[Boolean]}
    of type BigInt                    ${propCodec[BigInt]}
    of type String                    ${propCodec[String]}
    of type (BigInt, BigInt)          ${propCodec[(BigInt, BigInt)]}
    of type (String, Unit)            ${propCodec[(String, Unit)]}
    of type List[Unit]                ${propCodec[List[Unit]]}
    of type List[BigInt]              ${propCodec[List[BigInt]]}
    of type List[String]              ${propCodec[List[String]]}
    of type List[List[String]]        ${propCodec[List[List[String]]]}
    of type List[(BigInt, BigInt)]    ${propCodec[List[(BigInt, BigInt)]]}
    of type (BigInt, List[BigInt])    ${propCodec[(BigInt, List[BigInt])]}
    of type Option[BigInt]            ${propCodec[Option[BigInt]]}
    of type Option[List[BigInt]]      ${propCodec[Option[List[BigInt]]]}
    of type List[Option[BigInt]]      ${propCodec[List[Option[BigInt]]]}
    of type Either[String, BigInt]    ${propCodec[Either[String, BigInt]]}
  """

  def propCodec[A : Codec : Arbitrary] = properties(new Properties("props") {
    property("encode/decode") = forAll { (a: A) =>
      Codec[A].decode(Codec[A].encode(a)) must beRight(a)
    }

    property("YXML") = forAll { (a: A) =>
      val encoded = Codec[A].encode(a)
      XML.fromYXML(encoded.toYXML) must be_===(encoded)
    }
  })

} 
Example 21
Source File: RelatedResponseSpec.scala    From jsonapi-scala   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.qvantel.jsonapi

import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
import spray.json.{JsArray, JsNull, JsObject}
import _root_.spray.json._
import _root_.spray.json.DefaultJsonProtocol._

class RelatedResponseSpec extends Specification with ScalaCheck {
  implicit val apiRoot: com.qvantel.jsonapi.ApiRoot = ApiRoot(None)

  @jsonApiResource final case class Test(id: String, name: String, age: Int)
  @jsonApiResource final case class Test2(id: String, name: String, age: Int)

  val test: Option[Test]      = Some(Test("teståöä•Ωé®", "someName", 20)) // test UTF-8
  val emptyTest: Option[Test] = None
  val tests: List[Test]       = List(Test("test 1", "someName1", 20), Test("test 2", "someName2", 21))
  val emptyTests: List[Test]  = List.empty

  def transformToTest2(in: Test): Test2 = Test2(in.id + "-2", in.name, in.age)

  "correctly write to one none case" in {
    RelatedResponse(emptyTest).toResponse must be equalTo JsObject(
      "data" -> JsNull
    )

    RelatedResponse(emptyTest).map(transformToTest2).toResponse must be equalTo JsObject(
      "data" -> JsNull
    )
  }

  "correctly write to one some case" in {
    val answer = rawOne(test.get)

    RelatedResponse(test).toResponse must be equalTo answer
    RelatedResponse(test.get).toResponse must be equalTo answer

    val transformedAnswer = rawOne(transformToTest2(test.get))
    RelatedResponse(test).map(transformToTest2).toResponse must be equalTo transformedAnswer
    RelatedResponse(test.get).map(transformToTest2).toResponse must be equalTo transformedAnswer
  }

  "correctly write to many empty case" in {
    RelatedResponse(emptyTests).toResponse must be equalTo JsObject(
      "data" -> JsArray.empty
    )

    RelatedResponse(emptyTests).map(transformToTest2).toResponse must be equalTo JsObject(
      "data" -> JsArray.empty
    )
  }

  "correctly write to many non-empty case" in {
    val answer = rawCollection(tests)

    RelatedResponse(tests).toResponse must be equalTo answer
    RelatedResponse(tests.toSeq).toResponse must be equalTo answer
    RelatedResponse(tests.toIterable).toResponse must be equalTo answer
    RelatedResponse(tests.toSet).toResponse must be equalTo answer

    val transformedAnswer = rawCollection(tests.map(transformToTest2))

    RelatedResponse(tests).map(transformToTest2).toResponse must be equalTo transformedAnswer
    RelatedResponse(tests.toSeq).map(transformToTest2).toResponse must be equalTo transformedAnswer
    RelatedResponse(tests.toIterable).map(transformToTest2).toResponse must be equalTo transformedAnswer
    RelatedResponse(tests.toSet).map(transformToTest2).toResponse must be equalTo transformedAnswer
  }

  "correctly write sparse fieldsets" in {
    implicit val sparseFields: Map[String, List[String]] = Map("tests" -> List("age"), "test2s" -> List("age"))
    val answer                                           = rawOne(test.get)

    RelatedResponse(test).toResponse must be equalTo answer
    RelatedResponse(test.get).toResponse must be equalTo answer

    val transformedAnswer = rawOne(transformToTest2(test.get))

    RelatedResponse(test).map(transformToTest2).toResponse must be equalTo transformedAnswer
    RelatedResponse(test.get).map(transformToTest2).toResponse must be equalTo transformedAnswer
  }
} 
Example 22
package highperfscala.orderbook

import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{OrderCancelRejected, OrderCanceled}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class ListOrderBookCancelingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When cancel order arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (id, ci, ei) =>
    ListOrderBook.handle(
      () => ei, ListOrderBook.empty, CancelOrder(ci, id))._2 ====
      OrderCancelRejected(ei, id)
  }

  """Given empty book
    |and buy limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (o, ci, ei) =>
    (ListOrderBook.handle(
      () => ei, _: ListOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => ListOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(ListOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

  """Given empty book
    |and sell limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (o, ci, ei) =>
    (ListOrderBook.handle(
      () => ei, _: ListOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => ListOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(ListOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

} 
Example 23
package highperfscala.orderbook

import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{OrderCancelRejected, OrderCanceled}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class QueueOrderBookCancelingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When cancel order arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (id, ci, ei) =>
    QueueOrderBook.handle(
      () => ei, QueueOrderBook.empty, CancelOrder(ci, id))._2 ====
      OrderCancelRejected(ei, id)
  }

  """Given empty book
    |and buy limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (o, ci, ei) =>
    (QueueOrderBook.handle(
      () => ei, _: QueueOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => QueueOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(QueueOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

  """Given empty book
    |and sell limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (o, ci, ei) =>
    (QueueOrderBook.handle(
      () => ei, _: QueueOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => QueueOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(QueueOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

} 
Example 24
package highperfscala.orderbook

import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{LimitOrderAdded, OrderCancelRejected, OrderExecuted}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class LazyCancelOrderBookTradingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    LimitOrder.genLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (l, ci, ei) =>
    LazyCancelOrderBook.handle(
      () => ei, LazyCancelOrderBook.empty, AddLimitOrder(ci, l))._2 ====
      LimitOrderAdded(ei)
  }

  """Given empty book
    |and buy limit order added
    |When resting sell limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (buy, id, ci, ei) =>
    (LazyCancelOrderBook.handle(
      () => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, buy))).andThen {
      case (ob, _) => LazyCancelOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
        SellLimitOrder(id, Price(buy.price.value + 0.01))))._2
    }(LazyCancelOrderBook.empty) ==== LimitOrderAdded(ei)
  }

  """Given empty book
    |and sell limit order added
    |When resting buy limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (sell, id, ci, ei) =>
    (LazyCancelOrderBook.handle(() => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, sell)))
      .andThen {
        case (ob, _) => LazyCancelOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          BuyLimitOrder(id, Price(sell.price.value - 0.01))))._2
      }(LazyCancelOrderBook.empty) ==== LimitOrderAdded(ei)
  }

  """Given empty book
    |and buy limit order added
    |When crossing sell limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (buy, id, ci, ei) =>
    (LazyCancelOrderBook.handle(() => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, buy)))
      .andThen {
        case (ob, _) => LazyCancelOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          SellLimitOrder(id, Price(buy.price.value - 0.01))))._2
      }(LazyCancelOrderBook.empty) ==== OrderExecuted(ei,
      Execution(buy.id, buy.price), Execution(id, buy.price))
  }

  """Given empty book
    |and sell limit order added
    |When crossing buy limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (sell, id, ci, ei) =>
    (LazyCancelOrderBook.handle(() => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, sell)))
      .andThen {
        case (ob, _) => LazyCancelOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          BuyLimitOrder(id, Price(sell.price.value + 0.01))))._2
      }(LazyCancelOrderBook.empty) ==== OrderExecuted(ei,
      Execution(id, sell.price), Execution(sell.id, sell.price))
  }

  """Given empty book
    |When cancel order command arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (id, ci, ei) =>
    LazyCancelOrderBook.handle(() => ei, LazyCancelOrderBook.empty, CancelOrder(ci, id))
      ._2 ==== OrderCancelRejected(ei, id)
  }
} 
Example 25
package highperfscala.orderbook

import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{OrderCancelRejected, OrderCanceled}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class LazyCancelOrderBookCancelingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When cancel order arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (id, ci, ei) =>
    LazyCancelOrderBook.handle(
      () => ei, LazyCancelOrderBook.empty, CancelOrder(ci, id))._2 ====
      OrderCancelRejected(ei, id)
  }

  """Given empty book
    |and buy limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (o, ci, ei) =>
    (LazyCancelOrderBook.handle(
      () => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => LazyCancelOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(LazyCancelOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

  """Given empty book
    |and sell limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (o, ci, ei) =>
    (LazyCancelOrderBook.handle(
      () => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => LazyCancelOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(LazyCancelOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

} 
Example 26
package highperfscala.orderbook

import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{LimitOrderAdded, OrderCancelRejected, OrderExecuted}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class ListOrderBookTradingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    LimitOrder.genLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (l, ci, ei) =>
    ListOrderBook.handle(
      () => ei, ListOrderBook.empty, AddLimitOrder(ci, l))._2 ====
      LimitOrderAdded(ei)
  }

  """Given empty book
    |and buy limit order added
    |When resting sell limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (buy, id, ci, ei) =>
    (ListOrderBook.handle(
      () => ei, _: ListOrderBook, AddLimitOrder(ci, buy))).andThen {
      case (ob, _) => ListOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
        SellLimitOrder(id, Price(buy.price.value + 0.01))))._2
    }(ListOrderBook.empty) ==== LimitOrderAdded(ei)
  }

  """Given empty book
    |and sell limit order added
    |When resting buy limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (sell, id, ci, ei) =>
    (ListOrderBook.handle(() => ei, _: ListOrderBook, AddLimitOrder(ci, sell)))
      .andThen {
        case (ob, _) => ListOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          BuyLimitOrder(id, Price(sell.price.value - 0.01))))._2
      }(ListOrderBook.empty) ==== LimitOrderAdded(ei)
  }

  """Given empty book
    |and buy limit order added
    |When crossing sell limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (buy, id, ci, ei) =>
    (ListOrderBook.handle(() => ei, _: ListOrderBook, AddLimitOrder(ci, buy)))
      .andThen {
        case (ob, _) => ListOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          SellLimitOrder(id, Price(buy.price.value - 0.01))))._2
      }(ListOrderBook.empty) ==== OrderExecuted(ei,
      Execution(buy.id, buy.price), Execution(id, buy.price))
  }

  """Given empty book
    |and sell limit order added
    |When crossing buy limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (sell, id, ci, ei) =>
    (ListOrderBook.handle(() => ei, _: ListOrderBook, AddLimitOrder(ci, sell)))
      .andThen {
        case (ob, _) => ListOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          BuyLimitOrder(id, Price(sell.price.value + 0.01))))._2
      }(ListOrderBook.empty) ==== OrderExecuted(ei,
      Execution(id, sell.price), Execution(sell.id, sell.price))
  }

  """Given empty book
    |When cancel order command arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (id, ci, ei) =>
    ListOrderBook.handle(() => ei, ListOrderBook.empty, CancelOrder(ci, id))
      ._2 ==== OrderCancelRejected(ei, id)
  }
} 
Example 27
package highperfscala.orderbook

import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{LimitOrderAdded, OrderCancelRejected, OrderExecuted}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class QueueOrderBookTradingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    LimitOrder.genLimitOrder,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (l, ci, ei) =>
     QueueOrderBook.handle(
      () => ei,  QueueOrderBook.empty, AddLimitOrder(ci, l))._2 ====
      LimitOrderAdded(ei)
  }

  """Given empty book
    |and buy limit order added
    |When resting sell limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (buy, id, ci, ei) =>
    ( QueueOrderBook.handle(
      () => ei, _:  QueueOrderBook, AddLimitOrder(ci, buy))).andThen {
      case (ob, _) =>  QueueOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
        SellLimitOrder(id, Price(buy.price.value + 0.01))))._2
    }( QueueOrderBook.empty) ==== LimitOrderAdded(ei)
  }

  """Given empty book
    |and sell limit order added
    |When resting buy limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (sell, id, ci, ei) =>
    ( QueueOrderBook.handle(() => ei, _:  QueueOrderBook, AddLimitOrder(ci, sell)))
      .andThen {
        case (ob, _) =>  QueueOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          BuyLimitOrder(id, Price(sell.price.value - 0.01))))._2
      }( QueueOrderBook.empty) ==== LimitOrderAdded(ei)
  }

  """Given empty book
    |and buy limit order added
    |When crossing sell limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(
    BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (buy, id, ci, ei) =>
    ( QueueOrderBook.handle(() => ei, _:  QueueOrderBook, AddLimitOrder(ci, buy)))
      .andThen {
        case (ob, _) =>  QueueOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          SellLimitOrder(id, Price(buy.price.value - 0.01))))._2
      }( QueueOrderBook.empty) ==== OrderExecuted(ei,
      Execution(buy.id, buy.price), Execution(id, buy.price))
  }

  """Given empty book
    |and sell limit order added
    |When crossing buy limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(
    SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (sell, id, ci, ei) =>
    ( QueueOrderBook.handle(() => ei, _:  QueueOrderBook, AddLimitOrder(ci, sell)))
      .andThen {
        case (ob, _) =>  QueueOrderBook.handle(() => ei, ob, AddLimitOrder(ci,
          BuyLimitOrder(id, Price(sell.price.value + 0.01))))._2
      }( QueueOrderBook.empty) ==== OrderExecuted(ei,
      Execution(id, sell.price), Execution(sell.id, sell.price))
  }

  """Given empty book
    |When cancel order command arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(
    OrderId.genOrderId,
    CommandInstant.genCommandInstant,
    EventInstant.genEventInstant) { (id, ci, ei) =>
     QueueOrderBook.handle(() => ei,  QueueOrderBook.empty, CancelOrder(ci, id))
      ._2 ==== OrderCancelRejected(ei, id)
  }
} 
Example 28
Source File: OrderBookTradingSpec.scala    From Scala-High-Performance-Programming   with MIT License 5 votes vote down vote up
package highperfscala.orderbook

import highperfscala.orderbook.Commands.{CancelOrder, AddLimitOrder}
import highperfscala.orderbook.Events.{OrderCancelRejected, OrderExecuted, LimitOrderAdded}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class OrderBookTradingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(LimitOrder.genLimitOrder) { l =>
    OrderBook.handle(OrderBook.empty, AddLimitOrder(l))._2 ==== LimitOrderAdded
  }

  """Given empty book
    |and buy limit order added
    |When resting sell limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId) { (buy, id) =>
    (OrderBook.handle(_: OrderBook, AddLimitOrder(buy))).andThen {
      case (ob, _) => OrderBook.handle(ob, AddLimitOrder(
        SellLimitOrder(id, Price(buy.price.value + 0.01))))._2
    }(OrderBook.empty) ==== LimitOrderAdded
  }

  """Given empty book
    |and sell limit order added
    |When resting buy limit order arrives
    |Then LimitOrderAdded
  """.stripMargin ! Prop.forAll(SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId) { (sell, id) =>
    (OrderBook.handle(_: OrderBook, AddLimitOrder(sell))).andThen {
      case (ob, _) => OrderBook.handle(ob, AddLimitOrder(
        BuyLimitOrder(id, Price(sell.price.value - 0.01))))._2
    }(OrderBook.empty) ==== LimitOrderAdded
  }

  """Given empty book
    |and buy limit order added
    |When crossing sell limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(BuyLimitOrder.genBuyLimitOrder,
    OrderId.genOrderId) { (buy, id) =>
    (OrderBook.handle(_: OrderBook, AddLimitOrder(buy))).andThen {
      case (ob, _) => OrderBook.handle(ob, AddLimitOrder(
        SellLimitOrder(id, Price(buy.price.value - 0.01))))._2
    }(OrderBook.empty) ==== OrderExecuted(
      Execution(buy.id, buy.price), Execution(id, buy.price))
  }

  """Given empty book
    |and sell limit order added
    |When crossing buy limit order arrives
    |Then OrderExecuted
  """.stripMargin ! Prop.forAll(SellLimitOrder.genSellLimitOrder,
    OrderId.genOrderId) { (sell, id) =>
    (OrderBook.handle(_: OrderBook, AddLimitOrder(sell))).andThen {
      case (ob, _) => OrderBook.handle(ob, AddLimitOrder(
        BuyLimitOrder(id, Price(sell.price.value + 0.01))))._2
    }(OrderBook.empty) ==== OrderExecuted(
      Execution(id, sell.price), Execution(sell.id, sell.price))
  }

  """Given empty book
    |When cancel order command arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(OrderId.genOrderId) { id =>
    OrderBook.handle(OrderBook.empty, CancelOrder(id))._2 ====
      OrderCancelRejected
  }
} 
Example 29
Source File: OrderBookCancelingSpec.scala    From Scala-High-Performance-Programming   with MIT License 5 votes vote down vote up
package highperfscala
package orderbook

import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{OrderCanceled, OrderCancelRejected}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class OrderBookCancelingSpec extends Specification with ScalaCheck {

  """Given empty book
    |When cancel order arrives
    |Then OrderCancelRejected
  """.stripMargin ! Prop.forAll(OrderId.genOrderId) { id =>
    OrderBook.handle(OrderBook.empty, CancelOrder(id))._2 ====
      OrderCancelRejected
  }

  """Given empty book
    |and buy limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(BuyLimitOrder.genBuyLimitOrder) { o =>
    (OrderBook.handle(_: OrderBook, AddLimitOrder(o))).andThen {
      case (ob, _) => OrderBook.handle(ob, CancelOrder(o.id))._2
    }(OrderBook.empty) ==== OrderCanceled
  }

  """Given empty book
    |and sell limit order added
    |When cancel order arrives
    |Then OrderCanceled
  """.stripMargin ! Prop.forAll(SellLimitOrder.genSellLimitOrder) { o =>
    (OrderBook.handle(_: OrderBook, AddLimitOrder(o))).andThen {
      case (ob, _) => OrderBook.handle(ob, CancelOrder(o.id))._2
    }(OrderBook.empty) ==== OrderCanceled
  }

} 
Example 30
Source File: ThingsControllerSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

import dal.ThingsRepository
import de.leanovate.swaggercheck.playhelper._
import de.leanovate.swaggercheck.schema.model.ValidationSuccess
import models.{Thing, ThingType}
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.ScalaCheck
import org.specs2.mock.Mockito
import play.api.Application
import play.api.inject.bind
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test._
import support.{Arbitraries, ThingApi}

import scala.concurrent.Future

class ThingsControllerSpec extends PlaySpecification with ScalaCheck with ThingApi with Mockito with Arbitraries{

  "ThingController" should {
    "support all /things routes" in {
      implicit val arbitraryRequest = Arbitrary[PlayOperationVerifier](swaggerCheck.operationVerifier())
      val app = testApp()

      prop { requestVerifier: PlayOperationVerifier =>
        val Some(result) = route(app, requestVerifier.request)

        status(result) must between(200, 300)

        requestVerifier.responseVerifier.verify(result) must be equalTo ValidationSuccess
      }
    }
  }

  def testApp(): Application = {
    val mockThingsRepository = mock[ThingsRepository]

    mockThingsRepository.getPage(any[Option[ThingType.Value]], any[Int], any[Int]) answers { _ => Future.successful(Gen.nonEmptyListOf(Arbitrary.arbitrary[Thing]).sample.getOrElse(Seq.empty)) }
    mockThingsRepository.getById(any[UUID]) answers { _ => Future.successful(Arbitrary.arbitrary[Thing].sample)}

    new GuiceApplicationBuilder()
      .overrides(bind[ThingsRepository].toInstance(mockThingsRepository))
      .build()
  }
} 
Example 31
Source File: FUUIDQueryParamDecoder.scala    From fuuid   with MIT License 5 votes vote down vote up
package io.chrisdavenport.fuuid.http4s

import io.chrisdavenport.fuuid.{FUUID, FUUIDArbitraries}
import io.chrisdavenport.fuuid.http4s.implicits._
import org.http4s.dsl.io._
import org.scalacheck._
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class FUUIDQueryParamDecoder extends Specification with ScalaCheck with FUUIDArbitraries {

  object IdQueryParamMatcher extends QueryParamDecoderMatcher[FUUID]("id")

  "FUUID QueryParamDecoder" should {

    "work properly given a valid UUID" in prop { validFuuid: FUUID =>
      IdQueryParamMatcher.unapply(Map("id" -> List(validFuuid.show))) must beSome(validFuuid)
    }

    "fail given an invalid UUID" in prop { invalidUuid: String =>
      IdQueryParamMatcher.unapply(Map("id" -> List(invalidUuid))) must beNone
    }.setArbitrary(Arbitrary(Gen.alphaStr))
  }
} 
Example 32
Source File: H2TraversalSpec.scala    From fuuid   with MIT License 5 votes vote down vote up
package io.chrisdavenport.fuuid.doobie.h2

import cats.effect.{ContextShift, IO}
import cats.implicits._
import doobie._
import doobie.h2.implicits._
import doobie.implicits._
import io.chrisdavenport.fuuid.doobie.implicits._
import io.chrisdavenport.fuuid._
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
import org.specs2.specification.BeforeAll
import scala.concurrent.ExecutionContext.Implicits.global

class H2TraversalSpec extends Specification
  with BeforeAll with ScalaCheck with FUUIDArbitraries {

  implicit val contextShiftIO: ContextShift[IO] = IO.contextShift(global)

  lazy val transactor: Transactor[IO] =
    Transactor.fromDriverManager[IO](
      driver = "org.h2.Driver",
      url = "jdbc:h2:mem:testH2Table;DB_CLOSE_DELAY=-1",
      user = "sa",
      pass = ""
    )

  def beforeAll(): Unit = {
    sql"""
    CREATE TABLE testH2Table (
      id   UUID NOT NULL
    )
    """.update.run.transact(transactor).void.unsafeRunSync
  }

  def queryBy(fuuid: FUUID): Query0[FUUID] = {
    sql"""SELECT id from testH2Table where id = ${fuuid}""".query[FUUID]
  }

  def insertId(fuuid: FUUID): Update0 = {
    sql"""INSERT into testH2Table (id) VALUES ($fuuid)""".update
  }

  "Doobie H2 Meta" should {

    "traverse input and then extraction" in prop { fuuid: FUUID =>

      val action = for {
        _ <- insertId(fuuid).run.transact(transactor)
        fuuid <- queryBy(fuuid).unique.transact(transactor)
      } yield fuuid

      action.unsafeRunSync must_=== fuuid
    }

    "fail on a non-present value" in prop { fuuid: FUUID =>
      queryBy(fuuid)
        .unique
        .transact(transactor)
        .attempt
        .map(_.isLeft)
        .unsafeRunSync must_=== true
    }
  }

} 
Example 33
Source File: HillClimbingSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.search.local

import aima.core.search.Problem
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification


class HillClimbingSpec extends Specification with ScalaCheck {
  import HillClimbingSpec._

  implicit val arbXCoordinate: Arbitrary[XCoordinate] = Arbitrary {
    for {
      x <- Gen.choose[Double](0.00d, math.Pi)
    } yield XCoordinate(x)
  }

  "must find pi/2 on sin graph between zero and pi" >> prop { xCoord: XCoordinate =>
    val stateToValue: XCoordinate => Double = {
      case XCoordinate(x) => math.sin(x)
    }

    val sinProblem = new Problem[XCoordinate, StepAction] {
      override def initialState: XCoordinate                     = xCoord
      override def isGoalState(state: XCoordinate): Boolean      = false // Not used
      override def actions(state: XCoordinate): List[StepAction] = List(StepLeft, StepRight)
      override def result(state: XCoordinate, action: StepAction): XCoordinate = (state, action) match {
        case (XCoordinate(x), StepLeft) =>
          val newX = x - 0.001d
          if (x < 0) {
            XCoordinate(0)
          } else {
            XCoordinate(newX)
          }

        case (XCoordinate(x), StepRight) =>
          val newX = x + 0.001d
          if (x > math.Pi) {
            XCoordinate(math.Pi)
          } else {
            XCoordinate(newX)
          }
      }

      override def stepCost(state: XCoordinate, action: StepAction, childPrime: XCoordinate): Int = -1 // Not Used
    }

    val result = HillClimbing(stateToValue)(sinProblem)
    result match {
      case XCoordinate(x) => x must beCloseTo((math.Pi / 2) within 3.significantFigures)
      case other          => ko(other.toString)
    }
  }
}

object HillClimbingSpec {
  final case class XCoordinate(x: Double)
  sealed trait StepAction
  case object StepLeft  extends StepAction
  case object StepRight extends StepAction
} 
Example 34
Source File: GeneticAlgorithmSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.search.local

import aima.core.search.local.set.NonEmptySet
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

import scala.concurrent.duration._


class GeneticAlgorithmSpec extends Specification with GeneticAlgorithm[String] with ScalaCheck {

  import GeneticAlgorithm.StringIndividual._

  implicit val arbString: Arbitrary[String] = Arbitrary(
    Gen.listOfN(20, Gen.alphaChar).map(_.mkString)
  )

  implicit def arbSet[A: Arbitrary]: Arbitrary[NonEmptySet[A]] = Arbitrary {
    Gen.nonEmptyListOf(Arbitrary.arbitrary[A]).map(_.toSet).flatMap { set =>
      NonEmptySet.apply(set) match {
        case Right(nes) => Gen.const(nes)
        case Left(_)    => Gen.fail[NonEmptySet[A]]
      }
    }
  }

  "must find strings of at least 50% vowels" >> prop { population: NonEmptySet[String] =>
    def vowelFitness(individual: String): Fitness = {
      val u = individual.foldLeft(0.0d) {
        case (acc, 'a' | 'e' | 'i' | 'o' | 'u' | 'y' | 'A' | 'E' | 'I' | 'O' | 'U' | 'Y') => acc + 1.0d
        case (acc, _)                                                                     => acc
      }
      Fitness(u)
    }

    def fitEnough(individual: String): Boolean = {
      val length = individual.length
      if (length != 0) {
        vowelFitness(individual).value / length >= 0.50d
      } else {
        false
      }
    }

    val fitIndividual =
      geneticAlgorithm(population, vowelFitness)(fitEnough, 2.minutes, reproduce2, Probability(0.05), mutate)
    val fitness = vowelFitness(fitIndividual).value / fitIndividual.length
    fitness aka fitIndividual must be greaterThanOrEqualTo 0.50d
  }

} 
Example 35
Source File: ReflexVacuumAgentProgramSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.environment.vacuum

import aima.core.agent.{Actuator, Agent, AgentProgram, Environment, Sensor}
import org.scalacheck.Arbitrary
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

import scala.annotation.tailrec


class ReflexVacuumAgentProgramSpec extends Specification with ScalaCheck {

  implicit val arbVacuumEnvironment = Arbitrary(VacuumEnvironment())

  "should eventually clean environment" in prop { env: VacuumEnvironment =>
    val agent = new Agent[VacuumEnvironment, VacuumPercept, VacuumAction] {
      val agentProgram = new SimpleReflexVacuumAgentProgram
      val actuators    = List[Actuator[VacuumEnvironment, VacuumAction]](new SuckerActuator(this), new MoveActuator(this))
      lazy val sensors = List[Sensor[VacuumEnvironment, VacuumPercept]](
        new DirtSensor(this),
        new AgentLocationSensor(this)
      )
    }

    @tailrec def eventuallyClean(currentEnv: VacuumEnvironment): Boolean = {
      currentEnv match {
        case ve: VacuumEnvironment if ve.isClean() => true
        case _                                     => eventuallyClean(agent.run(currentEnv)._1)
      }
    }

    eventuallyClean(env.addAgent(agent)) must beTrue
  }

} 
Example 36
Source File: VaultSpec.scala    From vault   with MIT License 5 votes vote down vote up
package io.chrisdavenport.vault

// import cats._
// import cats.implicits._
import cats.effect._
import org.specs2.mutable.Specification
import org.specs2.ScalaCheck
// import org.scalacheck._

class VaultSpec extends Specification with ScalaCheck {

  "Vault" should {
     "contain a single value correctly" >> prop {
      i: Int => 
        val emptyVault : Vault = Vault.empty

        Key.newKey[IO, Int].map{k => 
          emptyVault.insert(k, i).lookup(k)
        }.unsafeRunSync === Some(i)

    }
    "contain only the last value after inserts" >> prop {
      l: List[String]=> 
        val emptyVault : Vault = Vault.empty
        val test : IO[Option[String]] = Key.newKey[IO, String].map{k => 
          l.reverse.foldLeft(emptyVault)((v, a) => v.insert(k, a)).lookup(k)
        }
        test.unsafeRunSync === l.headOption
    }

    "contain no value after being emptied" >> prop {
      l: List[String]=> 
        val emptyVault : Vault = Vault.empty
        val test : IO[Option[String]] = Key.newKey[IO, String].map{k => 
          l.reverse.foldLeft(emptyVault)((v, a) => v.insert(k, a)).empty.lookup(k)
        }
        test.unsafeRunSync === None
    }

    "not be accessible via a different key" >> prop { i: Int => 
        val test = for {
          key1 <- Key.newKey[IO, Int]
          key2 <- Key.newKey[IO, Int]
        } yield Vault.empty.insert(key1, i).lookup(key2)
        test.unsafeRunSync === None
    }
  }


} 
Example 37
Source File: JsonDecoderSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package types

import io.circe.generic.auto._
import io.circe.syntax._
import java.nio.charset.StandardCharsets
import jawn.ast.JParser
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.{ScalaCheck, Specification}
import roc.postgresql.Null
import roc.types.failures.{ElementDecodingFailure, NullDecodedFailure}
import roc.types.{decoders => Decoders}

final class JsonDecoderSpec extends Specification with ScalaCheck { def is = s2"""

  Json Decoder
    must correctly decode Text representation                              $testValidText
    must throw a ElementDecodingFailure when Text decoding invalid Json    $testInvalidText
    must correctly decode Binary representation                            $testValidBinary
    must throw a ElementDecodingFailure when Binary decoding invalid Json  $testInvalidBinary
    must throw a NullDecodedFailure when Null decoding Json                $testNullDecoding

                                                                               """

  private val testValidText = forAll { x: JsonContainer =>
    Decoders.jsonElementDecoder.textDecoder(x.text) must_== x.json
  }

  private val testInvalidText = forAll { x: String =>
    Decoders.jsonElementDecoder.textDecoder(x) must throwA[ElementDecodingFailure]
  }

  private val testValidBinary = forAll { x: BinaryJsonContainer =>
    Decoders.jsonElementDecoder.binaryDecoder(x.binary) must_== x.json
  }

  private val testInvalidBinary = forAll { xs: Array[Byte] =>
    Decoders.jsonElementDecoder.binaryDecoder(xs) must throwA[ElementDecodingFailure]
  }

  private val testNullDecoding =
    Decoders.jsonElementDecoder.nullDecoder(Null('doesnotmatter, -71)) must throwA[NullDecodedFailure]

  case class JsonContainer(text: String, json: Json)
  private lazy val genJsonContainer: Gen[JsonContainer] = for {
    jObject <- arbitrary[JsonObject]
  } yield {
    val text = jObject.asJson.noSpaces
    val json = JParser.parseUnsafe(text)
    new JsonContainer(text, json)
  }
  private implicit lazy val arbitraryJsonContainer: Arbitrary[JsonContainer] = 
    Arbitrary(genJsonContainer)

  case class BinaryJsonContainer(binary: Array[Byte], json: Json)
  private lazy val genBinaryJsonContainer: Gen[BinaryJsonContainer] = for {
    jObject <- arbitrary[JsonObject]
  } yield {
    val text = jObject.asJson.noSpaces
    val json = JParser.parseUnsafe(text)
    val bytes = text.getBytes(StandardCharsets.UTF_8)
    new BinaryJsonContainer(bytes, json)
  }
  private implicit lazy val arbitraryBinaryJsonContainer: Arbitrary[BinaryJsonContainer] =
    Arbitrary(genBinaryJsonContainer)

  case class JsonObject(name: String, first_names: List[String])

  private lazy val genJsonObject: Gen[JsonObject] = for {
    name <- arbitrary[String]
    first_names <- arbitrary[List[String]]
  } yield new JsonObject(name, first_names)
  private implicit lazy val arbitraryJsonObject: Arbitrary[JsonObject] = 
    Arbitrary(genJsonObject)
} 
Example 38
Source File: PostgresqlLexicalGen.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql

import java.nio.charset.StandardCharsets
import org.scalacheck.Gen
import org.specs2.ScalaCheck


trait PostgresqlLexicalGen extends ScalaCheck {
  // see http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html
  // for more on what constitues a valid SQL Identifier
  protected val UnicodeCapitalEnglish = '\u0041' to '\u005A'
  protected val UnicodeLowerEnglish   = '\u0061' to '\u007A'
  protected val UnicodeNonLatin       = '\u0400' to '\u1FFE'
  protected val UnicodeUnderscore     = "_".getBytes(StandardCharsets.UTF_8).map(_.toChar).head
  protected val UnicodeDollarSign     = "$".getBytes(StandardCharsets.UTF_8).map(_.toChar).head
  protected val UnicodeNumbers        = '\u0030' to '\u0039'
  protected val BeginningChars = UnicodeUnderscore :: List(UnicodeCapitalEnglish, 
    UnicodeLowerEnglish, UnicodeNonLatin).flatten
  protected val SubsequentChars = UnicodeDollarSign :: BeginningChars ::: UnicodeNumbers.toList

  protected lazy val genValidBeginningIdentifier: Gen[Char] = for {
    char    <-  Gen.oneOf(BeginningChars)
  } yield char
  protected lazy val genValidSubsequentIdentifier: Gen[Char] = for {
    char    <-  Gen.oneOf(SubsequentChars)
  } yield char

  protected lazy val genValidSQLIdentifier: Gen[String] = for {
    firstChar   <-  genValidBeginningIdentifier
    chars       <-  Gen.listOf(genValidSubsequentIdentifier)
  } yield {
    val xs = firstChar :: chars
    xs.map(_.toString).reduce(_ + _)
  }

  protected lazy val genValidNumberOfShortColumns: Gen[Short] = 
    Gen.chooseNum[Short](0, 1663) // the maximum number of Postgresql columns is 1663
  protected lazy val genValidNumberOfIntColumns: Gen[Int] =
    genValidNumberOfShortColumns.map(_.toInt)
  protected lazy val genValidNonZeroNumberOfShortColumns: Gen[Short] =
    Gen.chooseNum[Short](1, 1663) // the maximum number of Postgresql columns is 1663
} 
Example 39
Source File: PackageSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql

import java.nio.charset.StandardCharsets
import org.scalacheck.Prop.forAll
import org.specs2.{ScalaCheck, Specification}

final class PackageSpec extends Specification with ScalaCheck { def is = s2"""

  Postgresql Package
    should calculate length of C-Style String               $test0
    should calculate length of C-Style Strings              $test1
                                                                           """

  val test0 = forAll { (str: String) =>
    val bytes  = str.getBytes(StandardCharsets.UTF_8)
    val length = bytes.length + 1 // add 1 for null character
    lengthOfCStyleString(str) must_== length
  }

  val test1 = forAll { (xs: List[String]) =>
    val length = xs match {
      case h :: t => xs.map(lengthOfCStyleString).reduce(_ + _)
      case t      => 0
    }
    lengthOfCStyleStrings(xs) must_== length
  }
} 
Example 40
Source File: OptimizeSpec.scala    From skeuomorph   with Apache License 2.0 5 votes vote down vote up
package higherkindness.skeuomorph.mu

import org.scalacheck.Prop
import org.specs2.{ScalaCheck, Specification}
import higherkindness.droste._
import higherkindness.droste.data._
import higherkindness.skeuomorph.mu.MuF.TCoproduct
import higherkindness.skeuomorph.mu.Optimize._

class OptimizeSpec extends Specification with ScalaCheck {

  import higherkindness.skeuomorph.instances._

  def is =
    s2"""
  mu Optimize

  It should convert a TCoproduct into a TOption. $convertCoproduct2Option

  It should convert a TCoproduct into a TEither. $convertCoproduct2Either
  """

  def convertCoproduct2Option: Prop =
    Prop.forAll(muCoproductWithTNullGen[Mu[MuF]]) { coproduct: TCoproduct[Mu[MuF]] =>
      val transformation: Mu[MuF] = knownCoproductTypesTrans[Mu[MuF]].algebra.run(coproduct)

      val test = scheme.hylo(checkOptionalValue, Project[MuF, Mu[MuF]].coalgebra)

      test(transformation)
    }

  def convertCoproduct2Either: Prop =
    Prop.forAll(muCoproductWithoutTNullGen[Mu[MuF]]) { coproduct: TCoproduct[Mu[MuF]] =>
      val transformation: Mu[MuF] = knownCoproductTypesTrans[Mu[MuF]].algebra.run(coproduct)

      val test = scheme.hylo(checkEitherValue, Project[MuF, Mu[MuF]].coalgebra)

      test(transformation)
    }

  def checkEitherValue: Algebra[MuF, Boolean] =
    Algebra[MuF, Boolean] {
      case MuF.TEither(_, _) => true
      case _                 => false
    }

  def checkOptionalValue: Algebra[MuF, Boolean] =
    Algebra[MuF, Boolean] {
      case MuF.TOption(_) => true
      case _              => false
    }
} 
Example 41
Source File: OpenApiSchemaSpec.scala    From skeuomorph   with Apache License 2.0 5 votes vote down vote up
package higherkindness.skeuomorph.openapi

import higherkindness.skeuomorph.instances._
import org.typelevel.discipline.specs2.Discipline
import cats.laws.discipline._
import _root_.cats.implicits._
import org.specs2.{ScalaCheck, Specification}
import schema._
import org.scalacheck._
import _root_.io.circe._
import _root_.io.circe.testing._
import _root_.cats.kernel.CommutativeMonoid
import _root_.cats.laws.discipline.arbitrary._
import Spec._

class OpenApiSchemaSpec extends Specification with ScalaCheck with Discipline {

  implicit val miniIntMultiplication: CommutativeMonoid[MiniInt] = MiniInt.miniIntMultiplication

  def is = s2"""
      $shouldAbleCodecRoundTrip
      $shouldAbleToReadSpecExamples
      $functor
      $foldable
      $traverse
    """
  val traverse =
    checkAll(
      "Traverse[JsonSchemaF]",
      TraverseTests[JsonSchemaF].traverse[MiniInt, MiniInt, MiniInt, Set[MiniInt], Option, Option]
    )
  val functor  = checkAll("Functor[JsonSchemaF]", FunctorTests[JsonSchemaF].functor[MiniInt, MiniInt, String])
  val foldable = checkAll("Foldable[JsonSchemaF]", FoldableTests[JsonSchemaF].foldable[MiniInt, MiniInt])

  def shouldAbleCodecRoundTrip =
    Prop.forAll { (openApi: OpenApi[JsonSchemaF.Fixed]) =>
      import JsonEncoders._
      import JsonDecoders._

      CodecTests[OpenApi[JsonSchemaF.Fixed]].laws.codecRoundTrip(openApi)
    }

  def shouldAbleToReadSpecExamples =
    Prop.forAll { (format: Spec.Format) =>
      import JsonDecoders._
      import _root_.higherkindness.skeuomorph.openapi.yaml.{Decoder => YamlDecoder, _}
      format.fold(
        YamlDecoder[OpenApi[JsonSchemaF.Fixed]].apply(_).isRight,
        Decoder[OpenApi[JsonSchemaF.Fixed]].decodeJson(_).isRight
      )
    }
}

object Spec {
  type Yaml   = String
  type Format = Either[String, Json]

  private val examples =
    List("api-with-examples", "callback-example", "link-example", "petstore-expanded", "petstore", "uspto")

  private def fromResource(fileName: String): String =
    scala.io.Source
      .fromInputStream(getClass.getResourceAsStream(fileName))
      .getLines()
      .toList
      .mkString("\n")

  private def examplesArbitrary[A](f: String => String)(g: String => A): Gen[A] =
    Gen.oneOf(
      examples
        .map(x => g(fromResource(f(x))))
    )

  implicit val yamlArbitrary: Arbitrary[Format] =
    Arbitrary(
      eitherGen(
        examplesArbitrary(x => s"/openapi/yaml/$x.yaml")(identity),
        examplesArbitrary(x => s"/openapi/json/$x.json")(helpers.unsafeParse)
      )
    )

} 
Example 42
Source File: ThingSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package models

import de.leanovate.swaggercheck.schema.model.ValidationResult
import de.leanovate.swaggercheck.shrinkable.CheckJsValue
import org.scalacheck.Arbitrary
import org.specs2.ScalaCheck
import org.specs2.matcher.MustMatchers
import org.specs2.mutable.Specification
import play.api.libs.json.{JsSuccess, Json}
import support.{Arbitraries, ThingApi}

class ThingSpec extends Specification with ScalaCheck with MustMatchers with Arbitraries with ThingApi {
  "Thing" should {
    "be receivable" in {
      implicit val arbitraryJson = Arbitrary[CheckJsValue](swaggerCheck.jsonGenerator("Thing"))

      prop {
        json: CheckJsValue =>
          val JsSuccess(thing, path) = Json.parse(json.minified).validate[Thing]

          path.toString() must be equalTo ""
      }
    }

    "be sendable" in {
      val verifier = swaggerCheck.jsonVerifier("Thing")

      prop {
        thing: Thing =>
          verifier.verify(Json.stringify(Json.toJson(thing))) must be equalTo ValidationResult.success
      }
    }
  }
} 
Example 43
Source File: ThingsPageSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package models

import de.leanovate.swaggercheck.schema.model.ValidationResult
import org.specs2.ScalaCheck
import org.specs2.matcher.MustMatchers
import org.specs2.mutable.Specification
import play.api.libs.json.Json
import support.{Arbitraries, ThingApi}

class ThingsPageSpec extends Specification with ScalaCheck with MustMatchers with Arbitraries with ThingApi {
  "ThingsPage" should {
    // ThingsPage is never send to the server, so we just check writes here
    "be sendable" in {
      val verifier = swaggerCheck.jsonVerifier("ThingsPage")

      prop {
        thing: ThingsPage =>
          verifier.verify(Json.stringify(Json.toJson(thing))) must be equalTo ValidationResult.success
      }
    }
  }
} 
Example 44
Source File: ErrorSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package models

import de.leanovate.swaggercheck.schema.model.ValidationResult
import org.specs2.ScalaCheck
import org.specs2.matcher.MustMatchers
import org.specs2.mutable.Specification
import play.api.libs.json.Json
import support.{ThingApi, Arbitraries}

class ErrorSpec extends Specification with ScalaCheck with MustMatchers with Arbitraries with ThingApi {
  "Error" should {
    "be sendable" in {
      val verifier = swaggerCheck.jsonVerifier("Error")

      prop {
        error: Error =>
          verifier.verify(Json.stringify(Json.toJson(error))) must be equalTo ValidationResult.success
      }
    }
  }
} 
Example 45
Source File: FUUIDVarSpec.scala    From fuuid   with MIT License 5 votes vote down vote up
package io.chrisdavenport.fuuid.http4s

import io.chrisdavenport.fuuid.{FUUID, FUUIDArbitraries}
import org.http4s.dsl.io._
import org.scalacheck._
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class FUUIDVarSpec extends Specification with ScalaCheck with FUUIDArbitraries {

  "FUUID Extractor in Path" should {

    "work properly given a valid UUID" in prop { validFuuid: FUUID =>

      (Path(s"/v1/${validFuuid.show}") match {
        case Root / "v1" / FUUIDVar(uuid @ _) => uuid.eqv(validFuuid)
        case _ => false
      }) must beTrue

    }

    "fail given an invalid UUID" in prop { invalidUuid: String =>

      (Path(s"/v1/$invalidUuid") match {
        case Root / "v1" / FUUIDVar(uuid @ _) => true
        case _ => false
      }) must beFalse

    }.setArbitrary(Arbitrary(Gen.alphaStr))
  }
} 
Example 46
Source File: StreamingFormulaDemo1.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.spark.demo

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.ScalaCheck
import org.specs2.Specification
import org.specs2.matcher.ResultMatchers
import org.scalacheck.Arbitrary.arbitrary

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.Duration
import org.apache.spark.streaming.dstream.DStream

import es.ucm.fdi.sscheck.spark.streaming.SharedStreamingContextBeforeAfterEach
import es.ucm.fdi.sscheck.prop.tl.{Formula,DStreamTLProperty}
import es.ucm.fdi.sscheck.prop.tl.Formula._
import es.ucm.fdi.sscheck.gen.{PDStreamGen,BatchGen}

@RunWith(classOf[JUnitRunner])
class StreamingFormulaDemo1 
  extends Specification 
  with DStreamTLProperty
  with ResultMatchers
  with ScalaCheck {
  
  // Spark configuration
  override def sparkMaster : String = "local[*]"
  override def batchDuration = Duration(150)
  override def defaultParallelism = 4  

  def is = 
    sequential ^ s2"""
    Simple demo Specs2 example for ScalaCheck properties with temporal
    formulas on Spark Streaming programs
      - where a simple property for DStream.count is a success ${countForallAlwaysProp(_.count)}     
      - where a faulty implementation of the DStream.count is detected ${countForallAlwaysProp(faultyCount) must beFailing}
    """
      
  def faultyCount(ds : DStream[Double]) : DStream[Long] = 
    ds.count.transform(_.map(_ - 1))
      
  def countForallAlwaysProp(testSubject : DStream[Double] => DStream[Long]) = {
    type U = (RDD[Double], RDD[Long])
    val (inBatch, transBatch) = ((_ : U)._1, (_ : U)._2)
    val numBatches = 10
    val formula : Formula[U] = always { (u : U) =>
      transBatch(u).count === 1 and
      inBatch(u).count === transBatch(u).first 
    } during numBatches

    val gen = BatchGen.always(BatchGen.ofNtoM(10, 50, arbitrary[Double]), numBatches)
    
    forAllDStream(
      gen)(
      testSubject)(
      formula)
  }.set(minTestsOk = 10).verbose  
  
} 
Example 47
Source File: StreamingFormulaDemo2.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.spark.demo

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.ScalaCheck
import org.specs2.Specification
import org.specs2.matcher.ResultMatchers
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.Duration
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.dstream.DStream._

import scalaz.syntax.std.boolean._
    
import es.ucm.fdi.sscheck.spark.streaming.SharedStreamingContextBeforeAfterEach
import es.ucm.fdi.sscheck.prop.tl.{Formula,DStreamTLProperty}
import es.ucm.fdi.sscheck.prop.tl.Formula._
import es.ucm.fdi.sscheck.gen.{PDStreamGen,BatchGen}
import es.ucm.fdi.sscheck.gen.BatchGenConversions._
import es.ucm.fdi.sscheck.gen.PDStreamGenConversions._
import es.ucm.fdi.sscheck.matcher.specs2.RDDMatchers._

@RunWith(classOf[JUnitRunner])
class StreamingFormulaDemo2 
  extends Specification 
  with DStreamTLProperty
  with ResultMatchers
  with ScalaCheck {
  
  // Spark configuration
  override def sparkMaster : String = "local[*]"
  override def batchDuration = Duration(300)
  override def defaultParallelism = 3
  override def enableCheckpointing = true

  def is = 
    sequential ^ s2"""
    Check process to persistently detect and ban bad users
      - where a stateful implementation extracts the banned users correctly ${checkExtractBannedUsersList(listBannedUsers)}
      - where a trivial implementation ${checkExtractBannedUsersList(statelessListBannedUsers) must beFailing}
    """
  type UserId = Long
  
  def listBannedUsers(ds : DStream[(UserId, Boolean)]) : DStream[UserId] = 
    ds.updateStateByKey((flags : Seq[Boolean], maybeFlagged : Option[Unit]) =>
      maybeFlagged match {
        case Some(_) => maybeFlagged  
        case None => flags.contains(false) option {()}
      } 
    ).transform(_.keys)
      
  def statelessListBannedUsers(ds : DStream[(UserId, Boolean)]) : DStream[UserId] =
    ds.map(_._1)
    
  def checkExtractBannedUsersList(testSubject : DStream[(UserId, Boolean)] => DStream[UserId]) = {
    val batchSize = 20 
    val (headTimeout, tailTimeout, nestedTimeout) = (10, 10, 5) 
    val (badId, ids) = (15L, Gen.choose(1L, 50L))   
    val goodBatch = BatchGen.ofN(batchSize, ids.map((_, true)))
    val badBatch = goodBatch + BatchGen.ofN(1, (badId, false))
    val gen = BatchGen.until(goodBatch, badBatch, headTimeout) ++ 
               BatchGen.always(Gen.oneOf(goodBatch, badBatch), tailTimeout)
    
    type U = (RDD[(UserId, Boolean)], RDD[UserId])
    val (inBatch, outBatch) = ((_ : U)._1, (_ : U)._2)
    
    val formula = {
      val badInput = at(inBatch)(_ should existsRecord(_ == (badId, false)))
      val allGoodInputs = at(inBatch)(_ should foreachRecord(_._2 == true))
      val noIdBanned = at(outBatch)(_.isEmpty)
      val badIdBanned = at(outBatch)(_ should existsRecord(_ == badId))
      
      ( ( allGoodInputs and noIdBanned ) until badIdBanned on headTimeout ) and
      ( always { badInput ==> (always(badIdBanned) during nestedTimeout) } during tailTimeout )  
    }  
    
    forAllDStream(    
      gen)(
      testSubject)( 
      formula)
  }.set(minTestsOk = 10).verbose

} 
Example 48
Source File: ScalaCheckStreamingTest.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.spark.streaming

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.ScalaCheck
import org.specs2.execute.{AsResult, Result}

import org.scalacheck.{Prop, Gen}
import org.scalacheck.Arbitrary.arbitrary

import org.apache.spark._
import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.{Duration}
import org.apache.spark.streaming.dstream.DStream

import es.ucm.fdi.sscheck.prop.tl.Formula._
import es.ucm.fdi.sscheck.prop.tl.DStreamTLProperty
import es.ucm.fdi.sscheck.matcher.specs2.RDDMatchers._

@RunWith(classOf[JUnitRunner])
class ScalaCheckStreamingTest 
  extends org.specs2.Specification  
  with DStreamTLProperty
  with org.specs2.matcher.ResultMatchers
  with ScalaCheck {
    
  override def sparkMaster : String = "local[5]"
  override def batchDuration = Duration(350)
  override def defaultParallelism = 4  
  
  def is = 
    sequential ^ s2"""
    Simple properties for Spark Streaming
      - where the first property is a success $prop1
      - where a simple property for DStream.count is a success ${countProp(_.count)}
      - where a faulty implementation of the DStream.count is detected ${countProp(faultyCount) must beFailing}
    """    
      
  def prop1 = {
    val batchSize = 30   
    val numBatches = 10 
    val dsgenSeqSeq1 = {
      val zeroSeqSeq = Gen.listOfN(numBatches,  Gen.listOfN(batchSize, 0)) 
      val oneSeqSeq = Gen.listOfN(numBatches, Gen.listOfN(batchSize, 1))
      Gen.oneOf(zeroSeqSeq, oneSeqSeq)  
    } 
    type U = (RDD[Int], RDD[Int])
    
    forAllDStream[Int, Int](
      "inputDStream" |: dsgenSeqSeq1)(
      (inputDs : DStream[Int]) => {  
        val transformedDs = inputDs.map(_+1)
        transformedDs
      })(always ((u : U) => {
          val (inputBatch, transBatch) = u
          inputBatch.count === batchSize and 
          inputBatch.count === transBatch.count and
          (inputBatch.intersection(transBatch).isEmpty should beTrue) and
          ( inputBatch should foreachRecord(_ == 0) or 
            (inputBatch should foreachRecord(_ == 1)) 
          )
        }) during numBatches 
      )}.set(minTestsOk = 10).verbose
      
  def faultyCount(ds : DStream[Double]) : DStream[Long] = 
    ds.count.transform(_.map(_ - 1))
    
  def countProp(testSubject : DStream[Double] => DStream[Long]) = {
    type U = (RDD[Double], RDD[Long])
    val numBatches = 10 
    forAllDStream[Double, Long]( 
      Gen.listOfN(numBatches,  Gen.listOfN(30, arbitrary[Double])))(
      testSubject
      )(always ((u : U) => {
         val (inputBatch, transBatch) = u
         transBatch.count === 1 and
         inputBatch.count === transBatch.first
      }) during numBatches
    )}.set(minTestsOk = 10).verbose
    
} 
Example 49
Source File: CatenableSpec.scala    From parseback   with Apache License 2.0 5 votes vote down vote up
package parseback.util

import org.specs2.mutable._
import org.specs2.ScalaCheck
import org.scalacheck._

class CatenableSpec extends Specification with ScalaCheck {
  import Catenable.{+:, Syntax}
  import Prop._

  "catenable" should {
    "retain sequence semantics" in {
      "with left biasing" >> forAll { xs: List[Int] =>
        Catenable(xs: _*).toList mustEqual xs
      }

      "without biasing" >> forAll { xs: List[Int] =>
        def convert[A](xs: List[A]): Catenable[A] = {
          if (xs.isEmpty) {
            Catenable.empty
          } else if (xs.length == 1) {
            Catenable(xs: _*)
          } else {
            val (left, right) = xs splitAt (xs.length - 1)
            convert(left) ++ convert(right)
          }
        }

        convert(xs).toList mustEqual xs
      }

      "with right biasing" >> forAll { xs: List[Int] =>
        val c = xs.foldLeft(Catenable.empty[Int]) { (c, i) =>
          c ++ Catenable(i)
        }

        c.toList mustEqual xs
      }
    }

    "implement length matching list" in forAll { xs: List[Int] =>
      Catenable(xs: _*).length mustEqual xs.length
    }

    "implement isEmpty matching list" in forAll { xs: List[Int] =>
      Catenable(xs: _*).isEmpty mustEqual xs.isEmpty
    }

    "implement filter matching list" in forAll { (xs: List[Int], p: Int => Boolean) =>
      val actual = Catenable(xs: _*) filter p toList
      val expect = xs filter p

      actual mustEqual expect
    }

    "not evaluate the right when unconsing the left" in {
      var evaluated = false

      lazy val right: Catenable[Int] = {
        evaluated = true
        Catenable.empty
      }

      (Catenable(42, 24) ++ right) must beLike {
        case i +: tail =>
          i mustEqual 42
          evaluated must beFalse

          tail must beLike {
            case i2 +: tail =>
              i2 mustEqual 24
              evaluated must beFalse
          }
      }
    }
  }
} 
Example 50
Source File: CollectionsServiceSpec.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.api.services

import cats.data.OptionT
import cats.effect.IO
import cats.implicits._
import com.azavea.franklin.Generators
import com.azavea.franklin.api.{TestClient, TestServices}
import com.azavea.franklin.database.TestDatabaseSpec
import com.azavea.franklin.datamodel.CollectionsResponse
import com.azavea.stac4s.StacCollection
import com.azavea.stac4s.testing._
import org.http4s.circe.CirceEntityDecoder._
import org.http4s.{Method, Request, Uri}
import org.specs2.{ScalaCheck, Specification}

import java.net.URLEncoder
import java.nio.charset.StandardCharsets

class CollectionsServiceSpec
    extends Specification
    with ScalaCheck
    with TestDatabaseSpec
    with Generators {
  def is = s2"""
  This specification verifies that the collections service can run without crashing

  The collections service should:
    - create and delete collections $createDeleteCollectionExpectation
    - list collections              $listCollectionsExpectation
    - get collections by id         $getCollectionsExpectation
"""

  val testServices: TestServices[IO] = new TestServices[IO](transactor)

  val testClient: TestClient[IO] =
    new TestClient[IO](testServices.collectionsService, testServices.collectionItemsService)

  def listCollectionsExpectation = prop {
    (stacCollectionA: StacCollection, stacCollectionB: StacCollection) =>
      {
        val listIO = (
          testClient.getCollectionResource(stacCollectionA),
          testClient.getCollectionResource(stacCollectionB)
        ).tupled use { _ =>
          val request = Request[IO](method = Method.GET, Uri.unsafeFromString(s"/collections"))
          (for {
            resp    <- testServices.collectionsService.routes.run(request)
            decoded <- OptionT.liftF { resp.as[CollectionsResponse] }
          } yield decoded).value
        }

        val result = listIO.unsafeRunSync.get.collections map { _.id }

        (result must contain(stacCollectionA.id)) and (result must contain(stacCollectionB.id))
      }
  }

  def getCollectionsExpectation = prop { (stacCollection: StacCollection) =>
    val fetchIO =
      testClient.getCollectionResource(stacCollection) use { collection =>
        val encodedId = URLEncoder.encode(collection.id, StandardCharsets.UTF_8.toString)
        val request =
          Request[IO](method = Method.GET, Uri.unsafeFromString(s"/collections/$encodedId"))
        (for {
          resp    <- testServices.collectionsService.routes.run(request)
          decoded <- OptionT.liftF { resp.as[StacCollection] }
        } yield (decoded, collection)).value
      }

    val (fetched, inserted) = fetchIO.unsafeRunSync.get

    fetched must beTypedEqualTo(inserted)
  }

  // since creation / deletion is a part of the collection resource, and accurate creation is checked
  // in getCollectionsExpectation, this test just makes sure that if other tests are failing, it's
  // not because create/delete are broken
  def createDeleteCollectionExpectation = prop { (stacCollection: StacCollection) =>
    (testClient
      .getCollectionResource(stacCollection) use { _ => IO.unit }).unsafeRunSync must beTypedEqualTo(
      ()
    )
  }

} 
Example 51
Source File: SchemasSpec.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.api.schemas

import com.azavea.franklin.Generators
import com.azavea.franklin.datamodel.PaginationToken
import org.specs2.{ScalaCheck, Specification}
import sttp.tapir.Codec
import sttp.tapir.CodecFormat.TextPlain
import sttp.tapir.DecodeResult

class SchemasSpec extends Specification with ScalaCheck with Generators {

  def is = s2"""
  This specification verifies that the custom schemas pass basic round trip tests

  Custom schemas should round trip:
    - PaginationTokens         $paginationTokenExpectation
"""

  def paginationTokenExpectation = prop { (token: PaginationToken) =>
    val codec = implicitly[Codec[String, PaginationToken, TextPlain]]
    codec.decode(codec.encode(token)) ==== DecodeResult.Value(token)
  }
} 
Example 52
Source File: ValidationSpec.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.extensions.validation

import cats.implicits._
import com.azavea.stac4s.StacItem
import com.azavea.stac4s.syntax._
import com.azavea.stac4s.testing._
import eu.timepit.refined.types.string.NonEmptyString
import org.specs2.{ScalaCheck, Specification}

class ValidationSpec extends Specification with ScalaCheck {

  def is = s2"""
  This specification verifies that the Validation extension behaves sensibly

  The validation extension should:
    - report all the extensions it tries to validate   $validateSeveralExpectation
    - accumulate errors from checked extensions        $accumulateErrorsExpectation
"""

  def validateSeveralExpectation = prop { (item: StacItem) =>
    val validate = getItemValidator(List("label", "layer"))
    val test = validate(item)
      .getExtensionFields[ValidationExtension]
      .toEither
      .right
      .get
      .attemptedExtensions
      .toList
      .toSet
      .map { (s: NonEmptyString) => s.value }
    val expectation = Set(Label, Layer) map { _.repr }
    test should beTypedEqualTo(expectation)
  }

  def accumulateErrorsExpectation = prop { (item: StacItem) =>
    val validateLabel    = getItemValidator(List("label"))
    val validateLayer    = getItemValidator(List("layer"))
    val combinedValidate = getItemValidator(List("layer", "label"))

    val labelValidated    = validateLabel(item)
    val layerValidated    = validateLayer(item)
    val combinedValidated = combinedValidate(item)

    val test = (labelValidated.getExtensionFields[ValidationExtension] |+| layerValidated
      .getExtensionFields[ValidationExtension]).toEither.right.get.errors.toSet

    val expectation = combinedValidated
      .getExtensionFields[ValidationExtension]
      .toEither
      .right
      .get
      .errors
      .toSet

    test should beTypedEqualTo(expectation)
  }

} 
Example 53
Source File: OptionEffectSpec.scala    From eff   with MIT License 5 votes vote down vote up
package org.atnos.eff

import org.specs2.{ScalaCheck, Specification}
import org.scalacheck.Gen.posNum
import cats.syntax.all._
import cats.instances.all._
import cats.data._
import Eff._
import org.atnos.eff.all._
import org.atnos.eff.syntax.all._

class OptionEffectSpec extends Specification with ScalaCheck { def is = s2"""

 run the option monad                     $optionMonad
 run the option monad with nothing        $optionWithNothingMonad
 run the option monad with reader         $optionReader

 The Eff monad is stack safe with Option  $stacksafeOption

"""

  def optionMonad = {
    type S = Fx.fx1[Option]

    val option: Eff[S, String] =
      for {
        s1 <- OptionEffect.some("hello")
        s2 <- OptionEffect.some("world")
      } yield s1 + " " + s2

    option.runOption.run === Some("hello world")
  }

  def optionWithNothingMonad = {
    type S = Fx.fx1[Option]

    val option: Eff[S, String] =
      for {
        s1 <- OptionEffect.some[S, String]("hello")
        s2 <- OptionEffect.none[S, String]
      } yield s1 + " " + s2

    option.runOption.run === None
  }

  def optionReader = prop { (init: Int, someValue: Int) =>

    // define a Reader / Option stack
    type S = Fx.fx2[Option, ReaderInt]

    // create actions
    def readOption[R :_option :_readerInt]: Eff[R, Int] =
      for {
        j <- OptionEffect.some(someValue)
        i <- ask
      } yield i + j

    // run effects
    readOption[S].runOption.runReader(init).run must_== Some(init + someValue)
  }.setGens(posNum[Int], posNum[Int]).set(minTestsOk = 1)


  def stacksafeOption = {
    val list = (1 to 5000).toList
    val action = list.traverse(i => OptionEffect.some(i))

    action.runOption.run ==== Some(list)
  }

  type ReaderInt[A] = Reader[Int, A]

  type _readerInt[R] = ReaderInt |= R
} 
Example 54
Source File: BroccoliMessageHandlerSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.websocket

import cats.data.EitherT
import cats.instances.future._
import de.frosner.broccoli.auth.Account
import de.frosner.broccoli.instances.NomadInstances
import de.frosner.broccoli.models._
import de.frosner.broccoli.nomad
import de.frosner.broccoli.services.InstanceService
import org.scalacheck.Gen
import org.specs2.ScalaCheck
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

import scala.concurrent.Future

class BroccoliMessageHandlerSpec
    extends Specification
    with ScalaCheck
    with Mockito
    with nomad.ModelArbitraries
    with ModelArbitraries {

  "The Broccoli Message Handler" should {
    "send back instance tasks" in { implicit ee: ExecutionEnv =>
      prop {
        (account: Account,
         id: String,
         tasks: List[AllocatedTask],
         periodicRunTasks: Map[String, List[AllocatedTask]]) =>
          val instances = mock[NomadInstances]
          val instanceTasks = InstanceTasks(id, tasks, periodicRunTasks)
          instances.getInstanceTasks(account)(id) returns EitherT.pure[Future, InstanceError](instanceTasks)

          val outgoingMessage = new BroccoliMessageHandler(instances, mock[InstanceService])
            .processMessage(account)(IncomingMessage.GetInstanceTasks(id))

          outgoingMessage must beEqualTo(OutgoingMessage.GetInstanceTasksSuccess(instanceTasks)).await
      }.setGen2(Gen.identifier)
    }

    "send back an error if instance tasks failed" in { implicit ee: ExecutionEnv =>
      prop { (account: Account, id: String, error: InstanceError) =>
        val instances = mock[NomadInstances]
        instances.getInstanceTasks(account)(id) returns EitherT.leftT[Future, InstanceTasks](error)

        val outgoingMessage = new BroccoliMessageHandler(instances, mock[InstanceService])
          .processMessage(account)(IncomingMessage.GetInstanceTasks(id))

        outgoingMessage must beEqualTo(OutgoingMessage.GetInstanceTasksError(id, error)).await
      }.setGen2(Gen.identifier)
    }
  }
} 
Example 55
Source File: InstanceErrorSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.models

import de.frosner.broccoli.auth.Role
import de.frosner.broccoli.http.ToHTTPResult
import org.specs2.ScalaCheck
import org.scalacheck.Gen
import play.api.libs.json.Json
import play.api.test.PlaySpecification

import scala.concurrent.Future

class InstanceErrorSpec
    extends PlaySpecification
    with ScalaCheck
    with ModelArbitraries
    with ToHTTPResult.ToToHTTPResultOps {
  "InstanceError" should {
    "serialize reason to JSON" in prop { error: InstanceError =>
      Json.toJson(error) === Json.obj("reason" -> error.reason)
    }

    "convert to an HTTP result with JSON body" in prop { error: InstanceError =>
      contentAsJson(Future.successful(error.toHTTPResult)) === Json.toJson(error)
    }
  }

  "InstanceError.NotFound" should {
    "map to 404" in prop { (id: String, throwable: Option[Throwable]) =>
      val error: InstanceError = InstanceError.NotFound(id, throwable)
      status(Future.successful(error.toHTTPResult)) === NOT_FOUND
    }.setGens(Gen.identifier.label("id"), Gen.option(Gen.identifier.label("message").map(new Throwable(_))))
  }

  "InstanceError.IdMissing" should {
    "map to bad request" in {
      status(Future.successful((InstanceError.IdMissing: InstanceError).toHTTPResult)) === BAD_REQUEST
    }
  }

  "InstanceError.TemplateNotFound" should {
    "map to bad request" in prop { id: String =>
      val error: InstanceError = InstanceError.TemplateNotFound(id)
      status(Future.successful(error.toHTTPResult)) === BAD_REQUEST
    }.setGen(Gen.identifier.label("templateId"))
  }

  "InstanceError.InvalidParameters" should {
    "map to bad request" in prop { reason: String =>
      val error: InstanceError = InstanceError.InvalidParameters(reason)
      status(Future.successful(error.toHTTPResult)) === BAD_REQUEST
    }.setGen(Gen.identifier.label("reason"))
  }

  "InstanceError.UserRegexDenied" should {
    "map to forbidden" in prop { (id: String, regex: String) =>
      val error: InstanceError = InstanceError.UserRegexDenied(id, regex)
      status(Future.successful(error.toHTTPResult)) === FORBIDDEN
    }.setGens(Gen.identifier.label("instanceId"), Gen.identifier.label("regex"))
  }

  "InstanceError.RolesRequest" should {
    "map to forbidden" in prop { roles: Set[Role] =>
      val error: InstanceError = InstanceError.RolesRequired(roles)
      status(Future.successful(error.toHTTPResult)) === FORBIDDEN
    }
  }

  "InstanceError.Generic" should {
    "map to bad request" in prop { message: String =>
      val error: InstanceError = InstanceError.Generic(new Throwable(message))
      status(Future.successful(error.toHTTPResult)) === BAD_REQUEST
    }.setGen(Gen.identifier.label("message"))
  }

} 
Example 56
Source File: InstanceTasksSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.models

import de.frosner.broccoli.http.ToHTTPResult.ToToHTTPResultOps
import de.frosner.broccoli.nomad
import org.specs2.ScalaCheck
import play.api.libs.json.Json
import play.api.test.PlaySpecification

import scala.concurrent.Future

class InstanceTasksSpec
    extends PlaySpecification
    with ScalaCheck
    with ModelArbitraries
    with nomad.ModelArbitraries
    with ToToHTTPResultOps {
  "The ToHTTPResult instance" should {
    "convert in 200 OK result" in prop { (instanceTasks: InstanceTasks) =>
      status(Future.successful(instanceTasks.toHTTPResult)) === OK
    }

    "convert the tasks to a JSON body" in prop { (instanceTasks: InstanceTasks) =>
      contentAsJson(Future.successful(instanceTasks.toHTTPResult)) === Json.toJson(instanceTasks.allocatedTasks)
    }
  }
} 
Example 57
Source File: InstanceSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.models

import de.frosner.broccoli.RemoveSecrets.ToRemoveSecretsOps
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

class InstanceSpec extends Specification with ScalaCheck with ModelArbitraries with ToRemoveSecretsOps {

  "The RemoveSecrets instance" should {
    "remove secret instance parameters" in prop { (instance: Instance) =>
      val publicInstance = instance.removeSecrets
      val (secret, public) = publicInstance.parameterValues.partition {
        case (id, _) =>
          instance.template.parameterInfos(id).secret.getOrElse(false)
      }
      (secret.values must contain(beNull[ParameterValue]).foreach) and (public.values must contain(
        not(beNull[ParameterValue])).foreach)
    }
  }

  "An instance" should {
    "be possible to construct if the parameters to be filled match the ones in the template's parameter infos" in {
      val parameterInfos = Map("id" -> ParameterInfo("id", None, None, None, ParameterType.Raw, None))
      val instance1 =
        Instance("1", Template("1", "\"{{id}}\"", "desc", parameterInfos), Map("id" -> RawParameterValue("Heinz")))
      val instance2 =
        Instance("1", Template("1", "\"{{id}}\"", "desc", parameterInfos), Map("id" -> RawParameterValue("Heinz")))
      instance1 === instance2
    }

    "throw an exception during construction if not all variables are specified in the template's parameter infos" in {
      Instance("1", Template("1", "\"{{id}}\"", "desc", Map.empty), Map("id" -> RawParameterValue("Heinz"))) must throwA(
        new IllegalArgumentException(
          "requirement failed: The given parameters values (Set(id)) need to match the ones in the template (Set()) (instance id 1)."))
    }
  }

} 
Example 58
Source File: ToHTTPResultSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.http

import cats.syntax.either._
import org.scalacheck.Gen
import org.specs2.ScalaCheck
import play.api.mvc.Results
import play.api.test.PlaySpecification

import scala.concurrent.Future

class ToHTTPResultSpec extends PlaySpecification with ScalaCheck {
  import ToHTTPResult.ops._

  "ToHTTPResult.instance" should {
    "convert to a result with the given function" in prop { (body: String, statusCode: Int) =>
      implicit val instance = ToHTTPResult.instance[String](Results.Status(statusCode)(_))

      val result = Future.successful(body.toHTTPResult)
      (status(result) === statusCode) and (contentAsString(result) === body)
    }.setGens(Gen.identifier.label("value"), Gen.choose(200, 500).label("status"))
  }

  "ToHTTPResult Either instance" should {
    "convert to a result of either left or right" in prop { (value: Either[String, String]) =>
      implicit val stringToHTTPResult = ToHTTPResult.instance[String](Results.Ok(_))
      val result = Future.successful(value.toHTTPResult)
      contentAsString(result) === value.merge
    }.setGen(
      Gen.oneOf(Gen.identifier.map(Either.left).label("left"), Gen.identifier.map(Either.right).label("right"))
    )
  }
}