org.scalacheck.Prop Scala Examples

The following examples show how to use org.scalacheck.Prop. 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: GoldenCodecTests.scala    From circe-golden   with Apache License 2.0 5 votes vote down vote up
package io.circe.testing.golden

import cats.instances.string._
import cats.kernel.Eq
import cats.laws.IsEq
import cats.laws.discipline.catsLawsIsEqToProp
import io.circe.{ Decoder, Encoder, Json, Printer }
import io.circe.testing.CodecTests
import org.scalacheck.{ Arbitrary, Prop, Shrink }
import scala.reflect.runtime.universe.TypeTag
import scala.util.{ Failure, Success, Try }

trait GoldenCodecTests[A] extends CodecTests[A] {
  def laws: GoldenCodecLaws[A]

  private[this] def tryListToProp[A: Eq](result: Try[List[IsEq[A]]]): Prop = result match {
    case Failure(error)      => Prop.exception(error)
    case Success(equalities) => Prop.all(equalities.map(catsLawsIsEqToProp(_)): _*)
  }

  def goldenCodec(
    implicit
    arbitraryA: Arbitrary[A],
    shrinkA: Shrink[A],
    eqA: Eq[A],
    arbitraryJson: Arbitrary[Json],
    shrinkJson: Shrink[Json]
  ): RuleSet = new DefaultRuleSet(
    name = "goldenCodec",
    parent = Some(codec),
    "decoding golden files" -> tryListToProp(laws.goldenDecoding),
    "encoding golden files" -> tryListToProp(laws.goldenEncoding)
  )

  def unserializableGoldenCodec(
    implicit
    arbitraryA: Arbitrary[A],
    shrinkA: Shrink[A],
    eqA: Eq[A],
    arbitraryJson: Arbitrary[Json],
    shrinkJson: Shrink[Json]
  ): RuleSet = new DefaultRuleSet(
    name = "goldenCodec",
    parent = Some(unserializableCodec),
    "decoding golden files" -> tryListToProp(laws.goldenDecoding),
    "encoding golden files" -> tryListToProp(laws.goldenEncoding)
  )
}

object GoldenCodecTests {
  def apply[A: Decoder: Encoder: Arbitrary: TypeTag]: GoldenCodecTests[A] =
    apply[A](ResourceFileGoldenCodecLaws[A]())

  def apply[A: Decoder: Encoder: Arbitrary: TypeTag](printer: Printer): GoldenCodecTests[A] =
    apply[A](ResourceFileGoldenCodecLaws[A](printer = printer))

  def apply[A: Decoder: Encoder: Arbitrary: TypeTag](count: Int): GoldenCodecTests[A] =
    apply[A](ResourceFileGoldenCodecLaws[A](count = count))

  def apply[A: Decoder: Encoder: Arbitrary: TypeTag](count: Int, printer: Printer): GoldenCodecTests[A] =
    apply[A](ResourceFileGoldenCodecLaws[A](count = count, printer = printer))

  def apply[A: Decoder: Encoder: Arbitrary](laws0: GoldenCodecLaws[A]): GoldenCodecTests[A] =
    new GoldenCodecTests[A] {
      val laws: GoldenCodecLaws[A] = laws0
    }
} 
Example 2
Source File: SymmetricSerializationLaws.scala    From circe-yaml   with Apache License 2.0 5 votes vote down vote up
package io.circe.yaml

import cats.Eq
import cats.instances.either._
import cats.laws._
import cats.laws.discipline._
import io.circe.{ Decoder, Encoder, Json, ParsingFailure }
import org.scalacheck.{ Arbitrary, Prop, Shrink }
import org.typelevel.discipline.Laws

trait SymmetricSerializationLaws {

  def printerRoundTrip[A: Eq: Encoder: Decoder](
    parse: String => Either[ParsingFailure, Json],
    print: Json => String,
    a: A
  ): IsEq[Either[io.circe.Error, A]] =
    parse(print(Encoder[A].apply(a))).right.flatMap(_.as[A]) <-> Right(a)

}

object SymmetricSerializationLaws {

  def apply(): SymmetricSerializationLaws = new SymmetricSerializationLaws {}
}

trait SymmetricSerializationTests extends Laws {
  def laws: SymmetricSerializationLaws

  def symmetricPrinter[A: Eq: Arbitrary: Shrink: Encoder: Decoder](
    print: Json => String,
    parse: String => Either[ParsingFailure, Json]
  ): RuleSet =
    new DefaultRuleSet(
      name = "printer",
      parent = None,
      "roundTrip" -> Prop.forAll { (a: A) =>
        laws.printerRoundTrip(parse, print, a)
      }
    )
}

object SymmetricSerializationTests {
  def apply[A: Eq: Arbitrary: Decoder: Encoder](
    print: Json => String,
    parse: String => Either[ParsingFailure, Json]
  ): SymmetricSerializationTests =
    new SymmetricSerializationTests {
      val laws: SymmetricSerializationLaws = SymmetricSerializationLaws()
      symmetricPrinter[A](print, parse)
    }
} 
Example 3
Source File: RichLocalDateSpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import jp.ne.opt.chronoscala.Imports._
import org.scalacheck.{Prop, Properties}

object RichLocalDateSpec extends Properties("RichLocalDate") with Gens {
  import Prop.forAll

  property("totally ordered") = forAll(for {
    a <- localDateGen
    b <- localDateGen
    c <- localDateGen
  } yield (a, b, c)) {
    case (a, b, c) =>
      val antisymmetry = !(a <= b && b <= a) || a == b
      val transitivity = !(a <= b && b <= c) || a <= c
      val totality = a <= b || b <= a

      antisymmetry && transitivity && totality
  }
} 
Example 4
Source File: RichDurationSpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import org.scalacheck.{Prop, Properties}
import Imports._

object RichDurationSpec extends Properties("RichDuration") with Gens {
  import Prop.forAll

  property("totally ordered") = forAll(for {
    a <- durationGen
    b <- durationGen
    c <- durationGen
  } yield (a, b, c)) {
    case (a, b, c) =>
      val antisymmetry = !(a <= b && b <= a) || a == b
      val transitivity = !(a <= b && b <= c) || a <= c
      val totality = a <= b || b <= a

      antisymmetry && transitivity && totality
  }
} 
Example 5
Source File: RichZonedDateTimeSpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import org.scalacheck.{Prop, Properties}
import Imports._

object RichZonedDateTimeSpec extends Properties("RichZonedDateTime") with Gens {
  import Prop.forAll

  property("totally ordered") = forAll(for {
    a <- zonedDateTimeGen
    b <- zonedDateTimeGen
    c <- zonedDateTimeGen
  } yield (a, b, c)) {
    case (a, b, c) =>
      val antisymmetry = !(a <= b && b <= a) || a == b
      val transitivity = !(a <= b && b <= c) || a <= c
      val totality = a <= b || b <= a

      antisymmetry && transitivity && totality
  }
} 
Example 6
Source File: RichOffsetDateTimeSpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import jp.ne.opt.chronoscala.Imports._
import org.scalacheck.{Prop, Properties}

object RichOffsetDateTimeSpec extends Properties("RichOffsetDateTime") with Gens {
  import Prop.forAll

  property("totally ordered") = forAll(for {
    a <- offsetDateTimeGen
    b <- offsetDateTimeGen
    c <- offsetDateTimeGen
  } yield (a, b, c)) {
    case (a, b, c) =>
      val antisymmetry = !(a <= b && b <= a) || a == b
      val transitivity = !(a <= b && b <= c) || a <= c
      val totality = a <= b || b <= a

      antisymmetry && transitivity && totality
  }
} 
Example 7
Source File: RichLocalDateTimeSpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import jp.ne.opt.chronoscala.Imports._
import org.scalacheck.{Prop, Properties}

object RichLocalDateTimeSpec extends Properties("RichLocalDateTime") with Gens {
  import Prop.forAll

  property("totally ordered") = forAll(for {
    a <- localDateTimeGen
    b <- localDateTimeGen
    c <- localDateTimeGen
  } yield (a, b, c)) {
    case (a, b, c) =>
      val antisymmetry = !(a <= b && b <= a) || a == b
      val transitivity = !(a <= b && b <= c) || a <= c
      val totality = a <= b || b <= a

      antisymmetry && transitivity && totality
  }
} 
Example 8
Source File: RichLocalTimeSpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import jp.ne.opt.chronoscala.Imports._
import org.scalacheck.{Prop, Properties}

object RichLocalTimeSpec extends Properties("RichLocalTime") with Gens {
  import Prop.forAll

  property("totally ordered") = forAll(for {
    a <- localTimeGen
    b <- localTimeGen
    c <- localTimeGen
  } yield (a, b, c)) {
    case (a, b, c) =>
      val antisymmetry = !(a <= b && b <= a) || a == b
      val transitivity = !(a <= b && b <= c) || a <= c
      val totality = a <= b || b <= a

      antisymmetry && transitivity && totality
  }
} 
Example 9
Source File: BasicFunctionalitySpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import jp.ne.opt.chronoscala.Imports._
import org.scalacheck.Prop.forAll
import org.scalacheck.{Prop, Properties}

object BasicFunctionalitySpec extends Properties("ZonedDateTime") with Gens {

  property("LocalDateTime equality") = Prop.secure {
    forAll(localDateTimeGen) { localDateTime =>
      localDateTime == localDateTime
    }
  }

  property("ZonedDateTime equality") = Prop.secure {
    forAll(zonedDateTimeGen) { zonedDateTime =>
      zonedDateTime == zonedDateTime
    }
  }

  property("OffsetDateTime equality") = Prop.secure {
    forAll(offsetDateTimeGen) { offsetDateTime =>
      offsetDateTime == offsetDateTime
    }
  }

  property("localDateTime < (localDateTime + 1.hour)") = Prop.secure {
    forAll(localDateTimeGen) { localDateTime =>
      localDateTime < (localDateTime + 1.hour)
    }
  }

  property("zonedDateTime < (zonedDateTime + 1.hour)") = Prop.secure {
    forAll(zonedDateTimeGen) { zonedDateTime =>
      zonedDateTime < (zonedDateTime + 1.hour)
    }
  }

  property("offsetDateTime < (offsetDateTime + 1.hour)") = Prop.secure {
    forAll(offsetDateTimeGen) { offsetDateTime =>
      offsetDateTime < (offsetDateTime + 1.hour)
    }
  }
} 
Example 10
Source File: IntervalSpec.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import java.time.{Duration, Instant}

import org.scalacheck.{Gen, Prop, Properties}

object IntervalSpec extends Properties("Interval") with Gens {
  import Prop.forAll

  val startEndGen: Gen[(Instant, Instant)] = for {
    startEpochMillis <- Gen.choose(0L, Long.MaxValue)
    endEpochMillis <- Gen.choose(startEpochMillis, Long.MaxValue)
  } yield {
    val start = Instant.ofEpochMilli(startEpochMillis)
    val end = Instant.ofEpochMilli(endEpochMillis)

    (start, end)
  }

  property("empty interval") = forAll(instantGen) { instant =>
    Interval(instant, instant).duration == Duration.ZERO
  }

  property("contains itself") = forAll(startEndGen) {
    case (start, end) =>
      val interval = Interval(start, end)
      interval.contains(interval)
  }

  property("contains start and end") = forAll(startEndGen) {
    case (start, end) =>
      val interval = Interval(start, end)

      interval.contains(start) && interval.contains(end)
  }

  property("contains instant between start and end") = forAll(for {
    (start, end) <- startEndGen
    middleMillis <- Gen.choose(start.toEpochMilli, end.toEpochMilli)
  } yield (start, Instant.ofEpochMilli(middleMillis), end)) {
    case (start, middle, end) =>
      val interval = Interval(start, end)

      interval.contains(middle)
  }
} 
Example 11
Source File: reftype.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.api.{RefinedType, RefType, Validate}
import org.scalacheck.{Arbitrary, Cogen, Gen, Prop}

object reftype extends RefTypeInstances

trait RefTypeInstances {

  def arbitraryRefType[F[_, _], T, P](gen: Gen[T])(implicit rt: RefType[F]): Arbitrary[F[T, P]] =
    Arbitrary(gen.map(rt.unsafeWrap))

  def checkArbitraryRefType[F[_, _], T, P](
      implicit arb: Arbitrary[F[T, P]],
      rt: RefType[F],
      v: Validate[T, P]
  ): Prop =
    Prop.forAll((tp: F[T, P]) => v.isValid(rt.unwrap(tp)))

  def checkArbitraryRefinedType[FTP](implicit arb: Arbitrary[FTP], rt: RefinedType[FTP]): Prop =
    Prop.forAll((tp: FTP) => rt.validate.isValid(rt.refType.unwrap(rt.dealias(tp))))

  implicit def refTypeCogen[F[_, _], T: Cogen, P](implicit rt: RefType[F]): Cogen[F[T, P]] =
    Cogen[T].contramap(tp => rt.unwrap(tp))
} 
Example 12
Source File: PackageSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Positive
import eu.timepit.refined.types.all._
import org.scalacheck.{Cogen, Prop, Properties}

class PackageSpec extends Properties("Package") {
  // this is just copied from core since core’s test configuration is built for scalacheck 1.14 only
  def wellTyped[A](body: => A): Prop = Prop.secure {
    body
    true
  }

  property("Cogen[Short Refined Positive]") = wellTyped(Cogen[Short Refined Positive])

  property("Cogen[LowerCaseChar]") = wellTyped(Cogen[LowerCaseChar])

  property("Cogen[NonEmptyString]") = wellTyped(Cogen[NonEmptyString])

  property("Cogen[PosInt]") = wellTyped(Cogen[PosInt])
} 
Example 13
Source File: TestUtils.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Validate
import org.scalacheck.Prop

object TestUtils {

  def isValid[P]: IsValidPartiallyApplied[P] = new IsValidPartiallyApplied

  class IsValidPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): Boolean = v.isValid(t)
  }

  def notValid[P]: NotValidPartiallyApplied[P] = new NotValidPartiallyApplied

  class NotValidPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): Boolean = v.notValid(t)
  }

  def validate[P]: ValidatePartiallyApplied[P] = new ValidatePartiallyApplied

  class ValidatePartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): v.Res = v.validate(t)
  }

  def showExpr[P]: ShowExprPartiallyApplied[P] = new ShowExprPartiallyApplied

  class ShowExprPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): String = v.showExpr(t)
  }

  def showResult[P]: ShowResultPartiallyApplied[P] = new ShowResultPartiallyApplied

  class ShowResultPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): String = v.showResult(t, v.validate(t))
  }

  def wellTyped[A](body: => A): Prop = Prop.secure {
    body
    true
  }

  def getClassFile[C](c: C): String =
    c.getClass.getCanonicalName.replace('.', '/') + ".class"

  def getClassFilePath[C](c: C): java.net.URL =
    getClass.getClassLoader.getResource(getClassFile(c))

  def javapOutput[C](c: C, opts: String = ""): String =
    scala.sys.process
      .Process(s"javap $opts ${getClassFilePath(c)}")
      .!!
      .trim
      .replaceAll("""(?m)\s+$""", "")
} 
Example 14
Source File: ShiftSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

import eu.timepit.refined.api.{Max, Min}
import org.scalacheck.{Arbitrary, Prop, Properties}
import org.scalacheck.Prop._

class NonNegShiftSpec extends Properties("NonNegShift") {
  final def createProperty[A: Arbitrary: Min: NonNegShift](implicit num: Numeric[A]): Prop = {
    import num.{abs, gteq, lt, plus, zero}

    forAll { a: A =>
      gteq(a, zero) ==> (NonNegShift[A].shift(a) == a)
    } &&
    forAll { a: A => lt(a, zero) ==> (NonNegShift[A].shift(a) == plus(a, abs(Min[A].min))) }
  }

  property("shift Byte") = createProperty[Byte]
  property("shift Short") = createProperty[Short]
  property("shift Int") = createProperty[Int]
  property("shift Long") = createProperty[Long]
}

class NegShiftSpec extends Properties("NegShift") {
  final def createProperty[A: Arbitrary: Max: NegShift](implicit num: Numeric[A]): Prop = {
    import num.{gteq, lt, minus, one, zero}

    forAll { a: A =>
      lt(a, zero) ==> (NegShift[A].shift(a) == a)
    } &&
    forAll { a: A => gteq(a, zero) ==> (NegShift[A].shift(a) == minus(minus(a, Max[A].max), one)) }
  }

  property("shift Byte") = createProperty[Byte]
  property("shift Short") = createProperty[Short]
  property("shift Int") = createProperty[Int]
  property("shift Long") = createProperty[Long]
} 
Example 15
Source File: TestUtils.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton

import org.scalacheck.Prop
import singleton.ops._
import singleton.twoface._

object TestUtils {
  def sameType[A, B](implicit ev: A =:= B): Boolean = true

  def wellTyped(body: => Unit): Prop = Prop.secure {
    body
    true
  }

  def illRun(body: => Unit) : Prop = {
    val isIll = try {
      body
      false
    } catch {
      case _ : Throwable =>
        true
    }
    if (!isIll)
      assert(false, "Expected assertion did not occur")
    true
  }

  type Verify[OP, Expected] = Require[(OP == Expected) && (
        (IsNat[OP] && IsNat[Expected]) ||
        (IsChar[OP] && IsChar[Expected]) ||
        (IsInt[OP] && IsInt[Expected]) ||
        (IsLong[OP] && IsLong[Expected]) ||
        (IsFloat[OP] && IsFloat[Expected]) ||
        (IsDouble[OP] && IsDouble[Expected]) ||
        (IsString[OP] && IsString[Expected]) ||
        (IsBoolean[OP] && IsBoolean[Expected])
    )]

  def verifyOp[OP, Expected](implicit verify: Verify[OP, Expected]) : Prop = wellTyped {}
  def verifyOp1Args[OP[_],L,Expected](implicit verify: Verify[OP[L], Expected]) : Prop = wellTyped {}
  def verifyOp2Args[OP[_,_],L,R,Expected](implicit verify: Verify[OP[L,R], Expected]) : Prop = wellTyped {}

  type VerifyTF[OP, Expected] = Require[ITE[IsNonLiteral[Expected], IsNonLiteral[OP], OP == Expected]]

  def verifyTFChar[OP, Expected](opResult : TwoFace.Char[OP], expectedResult : TwoFace.Char[Expected])
                            (implicit verify : VerifyTF[OP, Expected]) : Prop = {
    opResult.getValue == expectedResult.getValue
  }
  def verifyTFInt[OP, Expected](opResult : TwoFace.Int[OP], expectedResult : TwoFace.Int[Expected])
                               (implicit verify : VerifyTF[OP, Expected]) : Prop = {
    opResult.getValue == expectedResult.getValue
  }
  def verifyTFLong[OP, Expected](opResult : TwoFace.Long[OP], expectedResult : TwoFace.Long[Expected])
                               (implicit verify : VerifyTF[OP, Expected]) : Prop = {
    opResult.getValue == expectedResult.getValue
  }
  def verifyTFFloat[OP, Expected](opResult : TwoFace.Float[OP], expectedResult : TwoFace.Float[Expected])
                                (implicit verify : VerifyTF[OP, Expected]) : Prop = {
    opResult.getValue == expectedResult.getValue
  }
  def verifyTFDouble[OP, Expected](opResult : TwoFace.Double[OP], expectedResult : TwoFace.Double[Expected])
                            (implicit verify : VerifyTF[OP, Expected]) : Prop = {
    opResult.getValue == expectedResult.getValue
  }
  def verifyTFString[OP, Expected](opResult : TwoFace.String[OP], expectedResult : TwoFace.String[Expected])
                            (implicit verify : VerifyTF[OP, Expected]) : Prop = {
    opResult.getValue == expectedResult.getValue
  }
  def verifyTFBoolean[OP, Expected](opResult : TwoFace.Boolean[OP], expectedResult : TwoFace.Boolean[Expected])
                            (implicit verify : VerifyTF[OP, Expected]) : Prop = {
    opResult.getValue == expectedResult.getValue
  }

  //nf = unsafe. used to force a not-final value. e.g., nf(3) returns a non-literal 3
  def us[T](t : T) : T = {
    var ret = t
    ret
  }

  //Use to get the type of an object, when t.type is impossible
  trait Me {
    type T
  }
  def me[T0](t : T0) = new Me {
    type T = T0
  }
} 
Example 16
Source File: Rules.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package laws

import scala.util.control.NonFatal
import cats.kernel.Eq
import cats.kernel.laws._
import cats.kernel.laws.discipline._
import org.scalacheck.{ Arbitrary, Prop }
import org.scalacheck.Prop._

object Rules extends Serialization {

  def serializable[A: Arbitrary]: (String, Prop) = {
    "serializable" -> forAll { (a: A) =>
      withCatchNonFatal {
        val _: A = roundtripSer(a)
        Prop(Result(status = True))
      }
    }
  }

  def equalitySerializable[A : Arbitrary : Eq]: (String, Prop) = {
    "serialize-roundtrip-Eq" -> forAll { (a: A) =>
      withCatchNonFatal {
        val r: A = roundtripSer(a)
        r <-> a
      }
    }
  }

  def identitySerializable[A <: AnyRef : Arbitrary](a: A): (String, Prop) = {
    "serializable-roundtrip-identity" -> forAll { (a: A) =>
      withCatchNonFatal {
        val r: A = roundtripSer(a)
        Prop(Result(status = if (r eq a) True else False))
      }
    }
  }

  private def withCatchNonFatal(block: => Prop): Prop = {
    try {
      block
    } catch {
      case NonFatal(ex) =>
        Prop(Result(status = Exception(ex)))
      case ex: Throwable =>
        throw ex // workaround for -Xstrict-patmat-analysis problem
    }
  }
} 
Example 17
Source File: EnumLikeLaws.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package laws

import cats.Eq
import cats.kernel.laws._
import cats.kernel.laws.discipline._
import cats.implicits._

import org.typelevel.discipline.Laws
import org.scalacheck.Arbitrary
import org.scalacheck.Prop
import org.scalacheck.Prop._

import core.EnumLike

object EnumLikeLaws {
  def apply[A](implicit arb: Arbitrary[A], enu: EnumLike[A], equ: Eq[A]): EnumLikeLaws[A] = {
    new EnumLikeLaws[A] {
      def Arb = arb
      def Enu = enu
      def Equ = equ
    }
  }
}

trait EnumLikeLaws[A] extends Laws {

  implicit def Arb: Arbitrary[A]
  implicit def Enu: EnumLike[A]
  implicit def Equ: Eq[A]

  def name: this.RuleSet = new EnumLikeRuleSet(
    "name",
    parent = None,
    "name-fromName" -> forAll { a: A =>
      Enu.fromName(Enu.name(a)) <-> Right(a)
    },
    "fromName-name" -> forAll { s: String =>
      Enu.fromName(s).fold(
        _ => provedIsEq[String],
        a => Enu.name(a) <-> s
      )
    }
  )

  def index: this.RuleSet = new EnumLikeRuleSet(
    "index",
    parent = Some(name),
    "index-fromIndex" -> forAll { a: A =>
      Enu.fromIndex(Enu.index(a)) <-> Right(a)
    },
    "fromIndex-index" -> forAll { i: Int =>
      Enu.fromIndex(i).fold(
        _ => provedIsEq[Int],
        a => Enu.index(a) <-> i
      )
    }
  )

  def all: this.RuleSet = new EnumLikeRuleSet(
    "all",
    parent = Some(index)
  )

  final class EnumLikeRuleSet(
    val name: String,
    val parent: Option[this.RuleSet],
    val props: (String, Prop)*
  ) extends RuleSet with HasOneParent {
    val bases = Nil
  }
} 
Example 18
Source File: KleeneLaws.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package laws

import cats.Eq
import cats.kernel.laws._
import cats.kernel.laws.discipline._
import cats.instances.all._
import org.typelevel.discipline.Laws
import org.scalacheck.Arbitrary
import org.scalacheck.Prop
import org.scalacheck.Prop._

object KleeneLaws {
  def apply[F[_], A](
    implicit
    arbA: Arbitrary[A],
    arbFA: Arbitrary[F[A]],
    arbVect: Arbitrary[Vector[A]],
    kle: Kleene[F],
    equA: Eq[A],
    equFA: Eq[F[A]]
  ): KleeneLaws[F, A] = new KleeneLaws[F, A] {
    def ArbA = arbA
    def ArbFA = arbFA
    def ArbVect = arbVect
    def Kle = kle
    def EquA = equA
    def EquFA = equFA
  }
}

trait KleeneLaws[F[_], A] extends Laws {

  implicit def Kle: Kleene[F]
  implicit def ArbA: Arbitrary[A]
  implicit def ArbFA: Arbitrary[F[A]]
  implicit def ArbVect: Arbitrary[Vector[A]]
  implicit def EquA: Eq[A]
  implicit def EquFA: Eq[F[A]]

  def roundtrip: this.RuleSet = new KleeneRuleSet(
    name = "roundtrip",
    "toVector-fromVector" -> forAll { (fa: F[A]) =>
      Kle.fromVector(Kle.toVector(fa)) <-> fa
    },
    "fromVector-toVector" -> forAll { (va: Vector[A]) =>
      Kle.toVector(Kle.fromVector(va)) <-> va
    }
  )

  final class KleeneRuleSet(
    val name: String,
    val props: (String, Prop)*
  ) extends RuleSet with HasOneParent {
    val parent = None
    val bases = Nil
  }
} 
Example 19
Source File: AnyLaws.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package laws

import cats.kernel.laws._
import cats.kernel.laws.discipline._
import cats.kernel.instances.boolean._
import cats.kernel.Eq

import org.typelevel.discipline.Laws
import org.scalacheck.Arbitrary
import org.scalacheck.Prop
import org.scalacheck.Prop._

object AnyLaws {

  def apply[A](implicit arb: Arbitrary[A]): AnyLaws[A] = new AnyLaws[A] {
    def Arb = arb
  }

  final class Dummy()
}

trait AnyLaws[A] extends Laws {

  import AnyLaws._

  implicit def Arb: Arbitrary[A]

  def equalsHashCode: this.RuleSet = new AnyRuleSet(
    name = "equals-hashCode",
    parent = None,
    bases = List(),
    "equals-hashCode-consistent" -> forAll { (x: A, y: A) =>
      ((!(x == y)) || (x.## == y.##)) <-> true
    },
    "equals-false-for-other-types" -> forAll { (x: A) =>
      val ok = (x != new Dummy)
      Prop(Result(status = if (ok) True else False))
    }
  )

  def serializability: this.RuleSet = new AnyRuleSet(
    name = "serializability",
    parent = Some(this.equalsHashCode),
    bases = List(),
    Rules.serializable[A]
  )

  def equality(implicit Equ: Eq[A]): this.RuleSet = new AnyRuleSet(
    name = "equality",
    parent = Some(this.serializability),
    bases = List(),
    "equals-Eq-consistent" -> forAll { (x: A, y: A) =>
      Equ.eqv(x, y) <-> (x == y)
    }
  )

  def any(implicit Equ: Eq[A]): this.RuleSet = new AnyRuleSet(
    name = "any",
    parent = Some(this.equality),
    bases = List()
  )

  def referenceEquality: this.RuleSet = new AnyRuleSet(
    name = "referenceEquality",
    parent = None,
    bases = List(),
    "reference-equals" -> forAll { (x: A, y: A) =>
      (x == y) <-> (x.asInstanceOf[AnyRef] eq y.asInstanceOf[AnyRef])
    },
    "identity-hashCode" -> forAll { (x: A, y: A) =>
      // we ignore collisions here, as
      // they should be sufficiently rare
      (x.## == y.##) <-> (x.asInstanceOf[AnyRef] eq y.asInstanceOf[AnyRef])
    }
  )

  def equalitySerializability(implicit Equ: Eq[A]): this.RuleSet = new AnyRuleSet(
    name = "equalitySerializability",
    parent = None,
    bases = List(),
    Rules.equalitySerializable[A]
  )

  final class AnyRuleSet(
    val name: String,
    val parent: Option[this.RuleSet],
    val bases: List[(String, Laws#RuleSet)],
    val props: (String, Prop)*
  ) extends RuleSet with HasOneParent
} 
Example 20
Source File: ZonedDateTimeLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws


import java.time.temporal.ChronoUnit
import java.time.{Duration, LocalDate, LocalTime}

import cats.kernel.laws.discipline.{catsLawsIsEqToProp => p}
import cats.kernel.laws._
import cats.instances.long._
import dtc._
import dtc.syntax.zoned._
import org.scalacheck.Prop._
import org.scalacheck.{Arbitrary, Gen, Prop}


trait ZonedDateTimeLaws[A] {
  implicit def D: Zoned[A]

  val genA: Gen[A]
  val genDateAndDurationWithinSameOffset: Gen[(A, Duration)]
  val genDataSuite: Gen[ZonedDateTimeTestData[A]]
  val genLocalDate: Gen[LocalDate]
  val genLocalTime: Gen[LocalTime]
  val genValidYear: Gen[Int]
  val genTimeZone: Gen[TimeZoneId]

  def crossOffsetAddition: Prop = forAll(genDataSuite) { data =>
    val target = D.plus(data.source, data.diff)
    p(D.offset(target) <-> data.targetOffset) &&
      (D.date(target) <-> data.targetDate) &&
      (D.time(target) <-> data.targetTime.truncatedTo(ChronoUnit.MILLIS))
  }

  def localTimeAndOffsetCorrelation: Prop = forAll(genA, genTimeZone) { (date: A, zone: TimeZoneId) =>
    val target = D.withZoneSameInstant(date, zone)
    D.time(date) <-> D.time(target).plusSeconds((date.offset.seconds - target.offset.seconds).toLong)
  }

  def withZoneSameInstantGivesSameInstant: Prop = forAll(genA, genTimeZone) { (date: A, zone: TimeZoneId) =>
    val target = D.withZoneSameInstant(date, zone)
    p(D.zone(target) <-> zone) &&
      (D.millisecondsUntil(date, target) <-> 0L)
  }
}

object ZonedDateTimeLaws {
  def apply[A](
    gDateAndDurationWithinSameDST: Gen[(A, Duration)],
    gDataSuite: Gen[ZonedDateTimeTestData[A]],
    gLocalTime: Gen[LocalTime],
    gLocalDate: Gen[LocalDate],
    gValidYear: Gen[Int],
    gTimeZone: Gen[TimeZoneId])(
    implicit ev: Zoned[A],
    arbA: Arbitrary[A]): ZonedDateTimeLaws[A] = new ZonedDateTimeLaws[A] {

    def D: Zoned[A] = ev

    val genTimeZone: Gen[TimeZoneId] = gTimeZone
    val genDateAndDurationWithinSameOffset: Gen[(A, Duration)] = gDateAndDurationWithinSameDST
    val genDataSuite: Gen[ZonedDateTimeTestData[A]] = gDataSuite
    val genLocalDate: Gen[LocalDate] = gLocalDate
    val genLocalTime: Gen[LocalTime] = gLocalTime
    val genValidYear: Gen[Int] = gValidYear
    val genA: Gen[A] = arbA.arbitrary
  }
} 
Example 21
Source File: LocalDateTimeLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws

import java.time.temporal.{ChronoField, ChronoUnit}
import java.time.{LocalDate, LocalTime}

import cats.kernel.laws._
import cats.kernel.laws.discipline.{catsLawsIsEqToProp => p}
import dtc.Local
import dtc.syntax.local._
import org.scalacheck.{Gen, Prop}
import org.scalacheck.Prop.forAll


trait LocalDateTimeLaws[A] {
  implicit def D: Local[A]

  val genLocalDate: Gen[LocalDate]
  val genLocalTime: Gen[LocalTime]

  def constructorConsistency: Prop = forAll(genLocalDate, genLocalTime) { (date: LocalDate, time: LocalTime) =>
    val dt = D.of(date, time)
    p(dt.date <-> date) && (dt.time <-> time.truncatedTo(ChronoUnit.MILLIS))
  }

  def plainConstructorConsistency: Prop = forAll(genLocalDate, genLocalTime) { (date: LocalDate, time: LocalTime) =>
    val dt = D.of(
      date.getYear, date.getMonthValue, date.getDayOfMonth,
      time.getHour, time.getMinute, time.getSecond, time.get(ChronoField.MILLI_OF_SECOND))
    p(dt.date <-> date) && (dt.time <-> time.truncatedTo(ChronoUnit.MILLIS))
  }
}

object LocalDateTimeLaws {
  def apply[A](
    gLocalTime: Gen[LocalTime],
    gLocalDate: Gen[LocalDate])(
    implicit ev: Local[A]): LocalDateTimeLaws[A] = new LocalDateTimeLaws[A] {
    def D: Local[A] = ev
    val genLocalDate: Gen[LocalDate] = gLocalDate
    val genLocalTime: Gen[LocalTime] = gLocalTime
  }
} 
Example 22
Source File: DateTimeLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws

import java.time.{Duration, LocalDate, LocalTime}

import dtc._
import cats.kernel.instances.int._
import cats.kernel.instances.long._
import cats.kernel.laws.discipline.catsLawsIsEqToProp
import dtc.TimePoint
import org.scalacheck.Prop._
import org.scalacheck.{Arbitrary, Gen, Prop}
import dtc.syntax.all._
import cats.kernel.laws._


trait DateTimeLaws[A] {
  implicit def D: TimePoint[A]

  val genA: Gen[A]
  val genAdditionSafeDateAndDuration: Gen[(A, Duration)]

  // take into account that nanos are always positive in the Duration.
  private def fullNumberOfSeconds(d: Duration) = {
    val seconds = d.getSeconds
    if (seconds >= 0 || d.getNano == 0) seconds
    else seconds + 1
  }

  def additionAndSubtractionOfSameDuration: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) =>
    D.plus(D.plus(x, d), d.negated()) <-> x
  }

  def additionOfZero: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, _) =>
    D.plus(x, Duration.ZERO) <-> x
  }

  def additionOfNonZero: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) =>
    Prop(d.isZero ||
      (d.isNegative && D.lt(D.plus(x, d), x)) || D.gt(D.plus(x, d), x))
  }

  def millisAddition: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) =>
    D.plus(x, d).millisecond <-> ((x.millisecond + d.toMillis) %% 1000)
  }

  def untilSelfIsAlwaysZero: Prop = forAll(genA) { x: A =>
    (D.millisecondsUntil(x, x) <-> 0L) &&
      (D.secondsUntil(x, x) <-> 0L) &&
      (D.minutesUntil(x, x) <-> 0L) &&
      (D.hoursUntil(x, x) <-> 0L) &&
      (D.daysUntil(x, x) <-> 0L) &&
      (D.monthsUntil(x, x) <-> 0L) &&
      (D.yearsUntil(x, x) <-> 0L)
  }

  def untilIsConsistentWithPlus: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) =>
    val altered = D.plus(x, d)
    val truncated = truncateToMillis(d)
    (D.millisecondsUntil(x, altered) <-> truncated.toMillis) &&
      (D.secondsUntil(x, altered) <-> fullNumberOfSeconds(truncated)) &&
      (D.minutesUntil(x, altered) <-> fullNumberOfSeconds(truncated) / SecondsInMinute) &&
      (D.hoursUntil(x, altered) <-> fullNumberOfSeconds(truncated) / (SecondsInMinute * MinutesInHour))
  }

  def dateMustNotThrow: Prop = forAll(genA) { x: A =>
    D.date(x)
    proved
  }

  def timeMustNotThrow: Prop = forAll(genA) { x: A =>
    D.time(x)
    proved
  }

  def dateFieldsAreConsistentWithToLocalDate: Prop = forAll(genA) { x: A =>
    catsLawsIsEqToProp(x.date.getDayOfWeek <-> x.dayOfWeek) &&
      (LocalDate.of(x.year, x.month, x.dayOfMonth) <-> x.date)

  }

  def timeFieldsAreConsistentWithToLocalTime: Prop = forAll(genA) { x: A =>
    LocalTime.of(x.hour, x.minute, x.second, millisToNanos(x.millisecond)) <-> x.time
  }

}

object DateTimeLaws {
  def apply[A](gDateAndDuration: Gen[(A, Duration)])(
    implicit
    ev: TimePoint[A],
    arbA: Arbitrary[A]): DateTimeLaws[A] = new DateTimeLaws[A] {
    def D: TimePoint[A] = ev
    val genA: Gen[A] = arbA.arbitrary
    val genAdditionSafeDateAndDuration: Gen[(A, Duration)] = gDateAndDuration
  }
} 
Example 23
Source File: ProviderLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws


import cats.Order
import cats.syntax.order._
import dtc.{Provider, TimeZoneId}
import org.scalacheck.Prop.forAll
import org.scalacheck.Prop
import org.scalacheck.{Arbitrary, Gen, Prop}

trait ProviderLaws[A] {

  implicit def P: Provider[A]
  implicit def O: Order[A]

  val genA: Gen[A]
  val genTimeZone: Gen[TimeZoneId]

  def twoConsequentNowCalls: Prop = forAll(genTimeZone) { zone: TimeZoneId =>
    val prev = P.currentTime(zone)
    val current = P.currentTime(zone)
    Prop(prev <= current)
  }
}

object ProviderLaws {
  def apply[A](
    gTimeZone: Gen[TimeZoneId])(
    implicit order: Order[A],
    provider: Provider[A],
    arbA: Arbitrary[A]): ProviderLaws[A] = new ProviderLaws[A] {

    implicit def P: Provider[A] = provider
    implicit def O: Order[A] = order

    val genTimeZone: Gen[TimeZoneId] = gTimeZone
    val genA: Gen[A] = arbA.arbitrary
  }
} 
Example 24
Source File: package.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc

import java.time.{DayOfWeek, LocalDate, LocalTime}

import cats.kernel.Eq
import org.scalacheck.Prop
import org.scalacheck.Prop._
import org.scalacheck.util.Pretty

package object laws {

  case class NotChangedValidator[T](before: T, after: T) {
    def apply[P](name: String, props: (T => P)*)(implicit E: Eq[P]): Prop = {
      val falsy = props.filter(prop => E.neqv(prop(before), prop(after)))
      if (falsy.isEmpty) proved
      else falsified :| {
        val b = Pretty.pretty(before, Pretty.Params(0))
        val a = Pretty.pretty(after, Pretty.Params(0))
        s"(Property $name changed. Before: $b, after: $a)"
      }
    }
  }

  def notChanged[T, P](before: T, after: T) = NotChangedValidator(before, after)

  // eq instances
  implicit val eqLocalTime: Eq[LocalTime] = Eq.fromUniversalEquals
  implicit val eqLocalDate: Eq[LocalDate] = Eq.fromUniversalEquals
  implicit val eqDayOfWeek: Eq[DayOfWeek] = Eq.fromUniversalEquals
} 
Example 25
Source File: QuickCheckSuite.scala    From Principles-of-Reactive-Programming   with GNU General Public License v3.0 5 votes vote down vote up
package quickcheck

import org.scalatest.FunSuite

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import org.scalatest.prop.Checkers
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop
import org.scalacheck.Prop._

import org.scalatest.exceptions.TestFailedException

object QuickCheckBinomialHeap extends QuickCheckHeap with BinomialHeap

@RunWith(classOf[JUnitRunner])
class QuickCheckSuite extends FunSuite with Checkers {
  def checkBogus(p: Prop) {
    var ok = false
    try {
      check(p)
    } catch {
      case e: TestFailedException =>
        ok = true
    }
    assert(ok, "A bogus heap should NOT satisfy all properties. Try to find the bug!")
  }

  test("Binomial heap satisfies properties.") {
    check(new QuickCheckHeap with BinomialHeap)
  }

  test("Bogus (1) binomial heap does not satisfy properties.") {
    checkBogus(new QuickCheckHeap with Bogus1BinomialHeap)
  }

  test("Bogus (2) binomial heap does not satisfy properties.") {
    checkBogus(new QuickCheckHeap with Bogus2BinomialHeap)
  }

  test("Bogus (3) binomial heap does not satisfy properties.") {
    checkBogus(new QuickCheckHeap with Bogus3BinomialHeap)
  }

  test("Bogus (4) binomial heap does not satisfy properties.") {
    checkBogus(new QuickCheckHeap with Bogus4BinomialHeap)
  }

  test("Bogus (5) binomial heap does not satisfy properties.") {
    checkBogus(new QuickCheckHeap with Bogus5BinomialHeap)
  }
} 
Example 26
Source File: laws.scala    From discipline-scalatest   with MIT License 5 votes vote down vote up
package org.typelevel.discipline.scalatest

import org.scalacheck.Prop
import org.typelevel.discipline.Laws

object Dummy {
  def prop = Prop(_ => Prop.Result(status = Prop.True))
  def prop2 = Prop(true)
}

object DummyLaws extends Laws {
  def dummy =
    new DefaultRuleSet(
      name = "dummy",
      parent = None,
      "true" -> Dummy.prop,
      "alsoTrue" -> Dummy.prop2
    )
} 
Example 27
Source File: TypeEqv.scala    From iota   with Apache License 2.0 5 votes vote down vote up
package iotatests

import cats._   //#=cats
import scalaz._ //#=scalaz
import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.{ Id => _, _ }
import shapeless.ops.hlist.{ ToList => HListToList }

import scala.reflect.runtime.universe._

sealed trait TypeEqv[A] {
  def check(x: A, y: A): Prop
}

object TypeEqv extends TypeEqvInstances0 {
  object syntax {
    final implicit class TypeEqvOps[A](x: A)(implicit eqv: TypeEqv[A]) {
      def ?=:=(y: A): Prop = eqv.check(x, y)
    }
  }
}

sealed class TypeEqvInstances0 extends TypeEqvInstances1 {
  implicit def idTypeEqv[A <: Type]: TypeEqv[A] = new TypeEqv[A] {
    def check(x: A, y: A): Prop =
      Prop(x =:= y) :| s"$x was not =:= to $y"
  }

  implicit def eitherTypeEqv[A, B](
    implicit eqv: TypeEqv[B]
  ): TypeEqv[Either[A, B]] = new TypeEqv[Either[A, B]] {
    def check(ex: Either[A, B], ey: Either[A, B]): Prop =
      (ex, ey) match {
        case (Right(bx), Right(by)) => eqv.check(bx, by)
        case _                      => ex ?= ey
      }
  }
}

sealed class TypeEqvInstances1 {
  implicit def foldableTypeEqv[F[_], A](
    implicit F: Foldable[F], eqv: TypeEqv[A]
  ): TypeEqv[F[A]] = new TypeEqv[F[A]] {
    def check(fx: F[A], fy: F[A]): Prop =
      (F.toList(fx) zip F.toList(fy)).foldLeft(proved)((acc, vv) =>
        acc && eqv.check(vv._1, vv._2))
  }

  implicit def genericTypeEqv[P, L <: HList, A](
    implicit
      gen: Generic.Aux[P, L],
      toList: HListToList[L, A],
      eqv: TypeEqv[List[A]]
  ): TypeEqv[P] = new TypeEqv[P] {
    def check(x: P, y: P): Prop =
      eqv.check(toList(gen.to(x)), toList(gen.to(y)))
  }
} 
Example 28
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 29
Source File: MTLSpecs.scala    From shims   with Apache License 2.0 5 votes vote down vote up
package shims.effect

import cats.effect.{ContextShift, IO}
import cats.effect.laws.discipline.{arbitrary, AsyncTests, ConcurrentEffectTests, ConcurrentTests}, arbitrary._
import cats.effect.laws.util.{TestContext, TestInstances}, TestInstances._

import cats.{Eq, Functor, Monad}
import cats.instances.either._
import cats.instances.int._
import cats.instances.option._
import cats.instances.tuple._
import cats.instances.unit._
import cats.syntax.functor._

import scalaz.{EitherT, Kleisli, OptionT, StateT, WriterT}

import org.scalacheck.{Arbitrary, Prop}

import org.specs2.Specification
import org.specs2.scalacheck.Parameters
import org.specs2.specification.core.Fragments

import org.typelevel.discipline.Laws
import org.typelevel.discipline.specs2.Discipline

import scala.concurrent.ExecutionContext
import scala.util.control.NonFatal

import java.io.{ByteArrayOutputStream, PrintStream}

object MTLSpecs extends Specification with Discipline {

  def is =
    br ^ checkAllAsync("OptionT[IO, ?]", implicit ctx => ConcurrentTests[OptionT[IO, ?]].concurrent[Int, Int, Int]) ^
    br ^ checkAllAsync("Kleisli[IO, Int, ?]", implicit ctx => ConcurrentTests[Kleisli[IO, Int, ?]].concurrent[Int, Int, Int]) ^
    br ^ checkAllAsync("EitherT[IO, Throwable, ?]", implicit ctx => ConcurrentEffectTests[EitherT[IO, Throwable, ?]].concurrentEffect[Int, Int, Int]) ^
    br ^ checkAllAsync("StateT[IO, Int, ?]", implicit ctx => AsyncTests[StateT[IO, Int, ?]].async[Int, Int, Int]) ^
    br ^ checkAllAsync("WriterT[IO, Int, ?]", implicit ctx => ConcurrentEffectTests[WriterT[IO, Int, ?]].concurrentEffect[Int, Int, Int])

  def checkAllAsync(name: String, f: TestContext => Laws#RuleSet)(implicit p: Parameters) = {
    val context = TestContext()
    val ruleSet = f(context)

    Fragments.foreach(ruleSet.all.properties.toList) {
      case (id, prop) =>
        s"$name.$id" ! check(Prop(p => silenceSystemErr(prop(p))), p, defaultFreqMapPretty) ^ br
    }
  }

  implicit def iocsForEC(implicit ec: ExecutionContext): ContextShift[IO] =
    IO.contextShift(ec)

  implicit def optionTArbitrary[F[_], A](implicit arbFA: Arbitrary[F[Option[A]]]): Arbitrary[OptionT[F, A]] =
    Arbitrary(arbFA.arbitrary.map(OptionT.optionT(_)))

  implicit def kleisliArbitrary[F[_], R, A](implicit arbRFA: Arbitrary[R => F[A]]): Arbitrary[Kleisli[F, R, A]] =
    Arbitrary(arbRFA.arbitrary.map(Kleisli(_)))

  implicit def eitherTArbitrary[F[_]: Functor, L, A](implicit arbEA: Arbitrary[F[Either[L, A]]]): Arbitrary[EitherT[F, L, A]] =
    Arbitrary(arbEA.arbitrary.map(fe => EitherT.eitherT(fe.map(_.asScalaz))))

  implicit def stateTArbitrary[F[_]: Monad, S, A](implicit arbSFA: Arbitrary[S => F[(S, A)]]): Arbitrary[StateT[F, S, A]] =
    Arbitrary(arbSFA.arbitrary.map(StateT(_)))

  implicit def writerTArbitrary[F[_], L, A](implicit arbFLA: Arbitrary[F[(L, A)]]): Arbitrary[WriterT[F, L, A]] =
    Arbitrary(arbFLA.arbitrary.map(WriterT(_)))

  implicit def kleisliEq[F[_], A](implicit eqv: Eq[F[A]]): Eq[Kleisli[F, Int, A]] =
    Eq.by(_(42))   // totally random and comprehensive seed

  implicit def stateTEq[F[_]: Monad, S, A](implicit eqv: Eq[F[(Int, A)]]): Eq[StateT[F, Int, A]] =
    Eq.by(_.run(42))   // totally random and comprehensive seed

  // copied from cats-effect
  private def silenceSystemErr[A](thunk: => A): A = synchronized {
    // Silencing System.err
    val oldErr = System.err
    val outStream = new ByteArrayOutputStream()
    val fakeErr = new PrintStream(outStream)
    System.setErr(fakeErr)
    try {
      val result = thunk
      System.setErr(oldErr)
      result
    } catch {
      case NonFatal(e) =>
        System.setErr(oldErr)
        // In case of errors, print whatever was caught
        fakeErr.close()
        val out = outStream.toString("utf-8")
        if (out.nonEmpty) oldErr.println(out)
        throw e
    }
  }
} 
Example 30
Source File: CodecEquivalenceTests.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.magnolia

import cats.instances.either._
import cats.kernel.Eq
import cats.laws._
import cats.laws.discipline._
import io.circe.magnolia.tags.{TaggedDecoder, TaggedEncoder}
import io.circe.{Decoder, Encoder, Json}
import org.scalacheck.{Arbitrary, Prop, Shrink}
import org.typelevel.discipline.Laws
import shapeless.tag.@@

trait CodecEquivalenceLaws[A] {
  def circeDecoder: Decoder[A] @@ tags.Circe
  def magnoliaDecoder: Decoder[A] @@ tags.Magnolia

  def circeEncoder: Encoder[A] @@ tags.Circe
  def magnoliaEncoder: Encoder[A] @@ tags.Magnolia

  def encoderEq(a: A): IsEq[Json] =
    circeEncoder(a) <-> magnoliaEncoder(a)

  def decoderEq(a: A): IsEq[Decoder.Result[A]] = {
    val encoded = magnoliaEncoder(a)
    encoded.as(circeDecoder) <-> encoded.as(magnoliaDecoder)
  }
}

object CodecEquivalenceLaws {

  def apply[A](
    implicit
    circeDecode: Decoder[A] @@ tags.Circe,
    magnoliaDecode: Decoder[A] @@ tags.Magnolia,
    circeEncode: Encoder[A] @@ tags.Circe,
    magnoliaEncode: Encoder[A] @@ tags.Magnolia) = new CodecEquivalenceLaws[A] {

    override val circeDecoder = circeDecode
    override val magnoliaDecoder = magnoliaDecode
    override val circeEncoder = circeEncode
    override val magnoliaEncoder = magnoliaEncode
  }
}

trait CodecEquivalenceTests[A] extends Laws {
  def laws: CodecEquivalenceLaws[A]

  def codecEquivalence(
    implicit
    arbitraryA: Arbitrary[A],
    shrinkA: Shrink[A],
    eqA: Eq[A]): RuleSet = new DefaultRuleSet(
    name = "codec equality",
    parent = None,
    "encoder equivalence" -> Prop.forAll { (a: A) =>
      laws.encoderEq(a)
    },
    "decoder equivalence" -> Prop.forAll { (a: A) =>
      laws.decoderEq(a)
    }
  )

  // Use codecEquivalence if possible. Use only when only
  // derived Encoder can be equivalent and should be documented
  def encoderEquivalence(
    implicit
    arbitraryA: Arbitrary[A],
    shrinkA: Shrink[A]
    ): RuleSet = new DefaultRuleSet(
    name = "codec equality",
    parent = None,
    "encoder equivalence" -> Prop.forAll { (a: A) =>
      laws.encoderEq(a)
    },
  )
}

object CodecEquivalenceTests {
  def apply[A](
    implicit
    circeDecode: Decoder[A] @@ tags.Circe,
    magnoliaDecode: Decoder[A] @@ tags.Magnolia,
    circeEncode: Encoder[A] @@ tags.Circe,
    magnoliaEncode: Encoder[A] @@ tags.Magnolia): CodecEquivalenceTests[A] = new CodecEquivalenceTests[A] {
    val laws: CodecEquivalenceLaws[A] = CodecEquivalenceLaws[A](
      circeDecode, magnoliaDecode, circeEncode, magnoliaEncode)
  }

  def useTagged[A](
    implicit
    circeDecode: TaggedDecoder[tags.Circe, A],
    magnoliaDecode: TaggedDecoder[tags.Magnolia, A],
    circeEncode: TaggedEncoder[tags.Circe, A],
    magnoliaEncode: TaggedEncoder[tags.Magnolia, A]): CodecEquivalenceTests[A] = new CodecEquivalenceTests[A] {
    val laws: CodecEquivalenceLaws[A] = CodecEquivalenceLaws[A](
      circeDecode.toTagged, magnoliaDecode.toTagged, circeEncode.toTagged, magnoliaEncode.toTagged)
  }
} 
Example 31
Source File: PropertyCheck.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airspec.spi

import org.scalacheck.Test.{Parameters, PropException, Result}
import org.scalacheck.util.Pretty
import org.scalacheck.{Arbitrary, Gen, Prop, Shrink, Test}
import wvlet.airspec.AirSpecSpi


trait PropertyCheck extends Asserts { this: AirSpecSpi =>

  protected def scalaCheckConfig: Parameters = Test.Parameters.default

  private def checkProperty(prop: Prop): Unit = {
    val result = Test.check(scalaCheckConfig, prop)
    if (!result.passed) {
      result match {
        case Result(PropException(args, e: AirSpecFailureBase, labels), succeeded, discarded, _, time) =>
          val reason = s"${e.message}\n${Pretty.prettyArgs(args)(Pretty.defaultParams)}"
          fail(reason)(e.code)
        case _ =>
          fail(Pretty.pretty(result))
      }
    }
  }

  private def OK: Any => Boolean = { x: Any => true }

  private def booleanProp = { x: Boolean => Prop(x) }

  protected def forAll[A1, U](checker: A1 => U)(implicit
      a1: Arbitrary[A1],
      s1: Shrink[A1],
      pp1: A1 => Pretty
  ): Unit = {
    val prop = Prop.forAll(checker.andThen(OK))(booleanProp, a1, s1, pp1)
    checkProperty(prop)
  }

  protected def forAll[A1, U](gen: Gen[A1])(checker: A1 => U)(implicit s1: Shrink[A1], pp1: A1 => Pretty): Unit = {
    val prop = Prop.forAll(gen)(checker.andThen(OK))(booleanProp, s1, pp1)
    checkProperty(prop)
  }

  protected def forAll[A1, A2, U](checker: (A1, A2) => U)(implicit
      a1: Arbitrary[A1],
      s1: Shrink[A1],
      pp1: A1 => Pretty,
      a2: Arbitrary[A2],
      s2: Shrink[A2],
      pp2: A2 => Pretty
  ): Unit = {
    val prop = Prop.forAll { (a1: A1, a2: A2) =>
      checker(a1, a2)
      true
    }(booleanProp, a1, s1, pp1, a2, s2, pp2)
    checkProperty(prop)
  }

  protected def forAll[A1, A2, U](g1: Gen[A1], g2: Gen[A2])(checker: (A1, A2) => U)(implicit
      s1: Shrink[A1],
      pp1: A1 => Pretty,
      s2: Shrink[A2],
      pp2: A2 => Pretty
  ): Unit = {
    val prop = Prop.forAll(g1, g2) { (a1: A1, a2: A2) =>
      checker(a1, a2)
      true
    }(booleanProp, s1, pp1, s2, pp2)
    checkProperty(prop)
  }

  protected def forAll[A1, A2, A3, U](checker: (A1, A2, A3) => U)(implicit
      a1: Arbitrary[A1],
      s1: Shrink[A1],
      pp1: A1 => Pretty,
      a2: Arbitrary[A2],
      s2: Shrink[A2],
      pp2: A2 => Pretty,
      a3: Arbitrary[A3],
      s3: Shrink[A3],
      pp3: A3 => Pretty
  ): Unit = {
    val prop = Prop.forAll { (a1: A1, a2: A2, a3: A3) =>
      checker(a1, a2, a3)
      true
    }(booleanProp, a1, s1, pp1, a2, s2, pp2, a3, s3, pp3)
    checkProperty(prop)
  }
} 
Example 32
Source File: Assesments.scala    From Learn-Scala-Programming   with MIT License 5 votes vote down vote up
import org.scalacheck.{Arbitrary, Gen, Prop}
import org.scalacheck.Prop.forAll

object Assesments extends App {
  def invariant[T: Ordering: Arbitrary]: Prop =
    forAll((l: List[T]) => l.sorted.length == l.length)

  invariant[Long].check
  invariant[String].check

  def idempotent[T: Ordering: Arbitrary]: Prop =
    forAll((l: List[T]) => l.sorted.sorted == l.sorted)

  idempotent[Long].check
  idempotent[String].check

  def inductive[T: Ordering: Arbitrary]: Prop = {
    def ordered(l: List[T]): Boolean =
      (l.length < 2) ||
        (ordered(l.tail) && implicitly[Ordering[T]].lteq(l.head, l.tail.head))
    forAll((l: List[T]) => ordered(l.sorted))
  }

  inductive[Int].check
  inductive[String].check


  val genListListInt = Gen.listOf(Gen.listOf(Gen.posNum[Int]))
  genListListInt.sample

  val pairGen = for {
    uuid <- Gen.uuid
    function0 <- Gen.function0(Gen.asciiStr)
  } yield (uuid, function0)

  val mapGen = Gen.mapOf(pairGen)
} 
Example 33
Source File: P23Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P23Check extends Properties("P23") {
  property("randomSelect()") = {
    val gen = for {
      n <- Gen.choose(0, 100)
      s <- Gen.listOfN(n, implicitly[Arbitrary[Int]].arbitrary)
    } yield (s, n)

    Prop.forAll(gen) {
      case (s, n) =>
        P23.randomSelect(n, s).length == n
    }
  }
} 
Example 34
Source File: P22Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P22Check extends Properties("P22") {
  property("range()") = {
    val gen = for {
      from <- implicitly[Arbitrary[Int]].arbitrary
      toByLong = from + 100L //to avoid overflow
      to <- Gen.choose(
        from,
        if (toByLong > Int.MaxValue) Int.MaxValue else from + 100
      )
    } yield (from, to)

    Prop.forAll(gen) {
      case (from, to) =>
        P22.range(from, to) == (from to to).toList
    }
  }
} 
Example 35
Source File: P28aCheck.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalacheck.{Prop, Properties}

class P28aCheck extends Properties("P28a") {
  property("lsort()") = {
    Prop.forAll { (s: List[List[Int]]) =>
      val a = P28a.lsort(s)
      if (a.length < 2) {
        true
      } else {
        a.zip(a.tail).forall { case (l, r) => l.length <= r.length }
      }
    }
  }
} 
Example 36
Source File: P27bCheck.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P27bCheck extends Properties("P27b") {
  property("group()") = {
    val gen = for {
      g1 <- Gen.listOfN(
        3,
        Gen.choose(1, 3)
      ) // To avoid StackOverflowError, small numbers are chosen
      g2 <- Gen.listOfN(g1.sum, implicitly[Arbitrary[Int]].arbitrary)
      if g2.distinct.length == g2.length
    } yield (g1, g2)

    Prop.forAll(gen) {
      case (s1: List[Int], s2: List[Int]) =>
        val a: List[List[List[Int]]] = P27b.group(s1, s2)
        a.forall { b =>
          s1.length == b.length && b.zip(s1).forall {
            case (c, n) => c.length == n && c.distinct.length == c.length
          }
        }
    }
  }
} 
Example 37
Source File: P27aCheck.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalacheck.{Prop, Properties, Gen}

class P27aCheck extends Properties("P27a") {
  property("group3()") = {
    val gen = for {
      g <- Gen.listOfN(9, Gen.choose(Int.MinValue, Int.MaxValue))
      if g.distinct.length == g.length
    } yield g
    Prop.forAll(gen) { (s: List[Int]) =>
      val sorted = s.sorted
      val a = P27a.group3(sorted)
      a.forall { b => b.flatten.sorted == sorted }
    }
  }
} 
Example 38
Source File: P21Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P21Check extends Properties("P21") {
  property("removeAt()") = {
    val gen = for {
      x <- Gen.choose(1, 10)
      y <- Gen.choose(0, x - 1)
      e <- implicitly[Arbitrary[Int]].arbitrary
      s <- Gen.listOfN(x, implicitly[Arbitrary[Int]].arbitrary)
    } yield (s, y, e)

    Prop.forAll(gen) {
      case (s, i, e) =>
        P21.insertAt(e, i, s) == {
          val buf = s.toBuffer
          buf.insert(i, e)
          buf.toList
        }
    }
  }
} 
Example 39
Source File: P28bCheck.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalacheck.{Prop, Properties}

class P28bCheck extends Properties("P28b") {
  property("lsortFreq()") = {
    Prop.forAll { (s: List[List[Int]]) =>
      val freqs = s.foldLeft(Map.empty[Int, Int]) {
        case (m, e) =>
          val value = m.getOrElse(e.length, 0)
          m.updated(e.length, value + 1)
      }
      val a = P28b.lsortFreq(s)
      if (a.length < 2) {
        true
      } else {
        a.zip(a.tail).forall {
          case (l, r) => freqs(l.length) <= freqs(r.length)
        }
      }
    }
  }
} 
Example 40
Source File: P20Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P20Check extends Properties("P20") {
  property("removeAt()") = {
    val gen = for {
      x <- Gen.choose(1, 10)
      y <- Gen.choose(0, x - 1)
      s <- Gen.listOfN(x, implicitly[Arbitrary[Int]].arbitrary)
    } yield (s, y)

    Prop.forAll(gen) {
      case (s, i) =>
        P20.removeAt(i, s)._1 == s.zipWithIndex
          .filterNot { case (_, j) => i == j }
          .map { _._1 }
    }
  }
} 
Example 41
Source File: P24Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalacheck.{Gen, Prop, Properties}

class P24Check extends Properties("P24") {
  property("lotto()") = {
    val gen = for {
      m <- Gen.choose(1, 100)
      n <- Gen.choose(0, m - 1)
    } yield (n, m)

    Prop.forAll(gen) {
      case (n, m) =>
        val lotto = P24.lotto(n, m)
        lotto.distinct == lotto
    }
  }
} 
Example 42
Source File: P57Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalacheck.{Prop, Properties}
import jp.co.dwango.s99.P57.Tree
import jp.co.dwango.s99.binary_trees.Node
import jp.co.dwango.s99.binary_trees.Tree
import jp.co.dwango.s99.binary_trees.End

class P57Check extends Properties("P57") {
  private type Min = Int
  private type Max = Int
  property("Tree.fromList") = {
    def isBinarySearchTree(node: Node[Int]): Option[(Min, Max)] =
      node match {
        case Node(v, End, End) => Some((v, v))
        case Node(v, End, r @ Node(_, _, _)) =>
          isBinarySearchTree(r)
          for (
            (rmin, rmax) <- isBinarySearchTree(r)
            if v <= rmin && rmin <= rmax
          )
            yield (v, rmax)
        case Node(v, l @ Node(_, _, _), End) =>
          for (
            (lmin, lmax) <- isBinarySearchTree(l)
            if lmin <= lmax && lmax <= v
          )
            yield (lmin, v)
        case Node(v, l @ Node(_, _, _), r @ Node(_, _, _)) =>
          for {
            (lmin, lmax) <- isBinarySearchTree(l)
            (rmin, rmax) <- isBinarySearchTree(r)
            if lmin <= lmax && lmax <= v && v <= rmin && rmin <= rmax
          } yield (lmin, rmax)
      }
    Prop.forAll { (s: List[Int]) =>
      Tree.fromList(s) match {
        case End => true
        case node @ Node(_, _, _) =>
          isBinarySearchTree(node).isDefined
      }
    }
  }
} 
Example 43
Source File: P26Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P26Check extends Properties("P26") {
  property("combinations()") = {
    val gen = for {
      n <- Gen.choose(0, 10)
      s <- Gen.listOfN(n + 5, implicitly[Arbitrary[Int]].arbitrary)
    } yield (s, n)

    Prop.forAll(gen) {
      case (s, n) =>
        val lc = P26.combinations(n, s).map { _.sorted }
        val rc = s.combinations(n).map { _.sorted }.toList
        lc.exists { l =>
          rc.contains(l)
        } && rc.exists { r => lc.contains(r) }
    }
  }
} 
Example 44
Source File: P03Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P03Check extends Properties("P03") {
  property("nth()") = {
    val gen = for {
      x <- Gen.choose(1, 10)
      y <- Gen.choose(0, x - 1)
      s <- Gen.listOfN(x, implicitly[Arbitrary[Int]].arbitrary)
    } yield (s, y)

    Prop.forAll(gen) {
      case (s, i) =>
        P03.nth(i, s) == s(i)
    }
  }
} 
Example 45
Source File: SerialIntegrationTest.scala    From finagle-serial   with Apache License 2.0 5 votes vote down vote up
package io.github.finagle.serial.tests

import com.twitter.finagle.{Client, ListeningServer, Server, Service}
import com.twitter.util.{Await, Future, Try}
import io.github.finagle.serial.Serial
import java.net.{InetAddress, InetSocketAddress}
import org.scalatest.Matchers
import org.scalatest.prop.Checkers
import org.scalacheck.{Arbitrary, Gen, Prop}


  def testFunctionService[I, O](
    f: I => O
  )(implicit
    inCodec: C[I],
    outCodec: C[O],
    arb: Arbitrary[I]
  ): Unit = {
    val (fServer, fClient) = createServerAndClient(f)(inCodec, outCodec)

    check(serviceFunctionProp(fClient)(f)(arb.arbitrary))

    Await.result(fServer.close())
  }
} 
Example 46
Source File: CodecSpec.scala    From hammock   with MIT License 5 votes vote down vote up
package hammock

import cats.Eq
import cats.instances.option._
import cats.instances.int._
import cats.laws._
import cats.laws.discipline._
import cats.syntax.either._

import org.scalacheck.{Arbitrary, Prop}
import org.scalatest.matchers.should.Matchers
import org.scalatest.funsuite.AnyFunSuite
import org.typelevel.discipline.Laws
import org.typelevel.discipline.scalatest.Discipline

import scala.util._

trait CodecLaws[A] {
  implicit def F: Codec[A]

  def decodeAfterEncodeEquality(a: A): IsEq[Option[A]] =
    F.decode(F.encode(a)).right.toOption <-> Some(a)
}

object CodecLaws {
  def apply[T](implicit ev: Codec[T]): CodecLaws[T] = new CodecLaws[T] { def F = ev }
}

trait CodecTests[A] extends Laws {
  def laws: CodecLaws[A]

  def codec(implicit A: Arbitrary[A], eq: Eq[A]): RuleSet =
    new DefaultRuleSet("Codec", None, "decodeAfterEncodeEquality" -> Prop.forAll { (a: A) =>
      laws.decodeAfterEncodeEquality(a)
    })
}

object CodecTests {

  def apply[A: Codec: Arbitrary: Eq]: CodecTests[A] = new CodecTests[A] {
    def laws: CodecLaws[A] = CodecLaws[A]
  }

}

class CodecSpec extends AnyFunSuite with Discipline with Matchers {
  import Encoder.ops._

  implicit val intCodec = new Codec[Int] {
    def encode(t: Int): Entity = Entity.StringEntity(t.toString)
    def decode(s: Entity): Either[CodecException, Int] = s match {
      case Entity.StringEntity(body, _) =>
        Either
          .catchOnly[NumberFormatException](body.toInt)
          .left
          .map(ex => CodecException.withMessageAndException(ex.getMessage, ex))
      case _ => Left(CodecException.withMessage("only StringEntities accepted"))
    }
  }

  checkAll("Codec[Int]", CodecTests[Int].codec)

  test("syntax should exist for types for which a Codec exist") {
    1.encode shouldEqual Entity.StringEntity("1")
  }
} 
Example 47
Source File: MerkleBlockSpec.scala    From bitcoin-s-spv-node   with MIT License 5 votes vote down vote up
package org.bitcoins.spvnode.block

import org.bitcoins.core.crypto.DoubleSha256Digest
import org.bitcoins.core.protocol.blockchain.Block
import org.bitcoins.core.util.BitcoinSLogger
import org.bitcoins.spvnode.bloom.BloomFilter
import org.bitcoins.spvnode.gen.MerkleGenerator
import org.scalacheck.{Prop, Properties}


class MerkleBlockSpec extends Properties("MerkleBlockSpec") with BitcoinSLogger {

  property("Serialization symmetry") =
    Prop.forAll(MerkleGenerator.merkleBlockWithInsertedTxIds) {
      case (merkleBlock: MerkleBlock, block: Block, txIds : Seq[DoubleSha256Digest]) =>
        MerkleBlock(merkleBlock.hex) == merkleBlock
    }

  property("contains all inserted txids when we directly create a merkle block from the txids") =
    Prop.forAllNoShrink(MerkleGenerator.merkleBlockWithInsertedTxIds) {
      case (merkleBlock: MerkleBlock, block: Block, txIds: Seq[DoubleSha256Digest]) =>
        val extractedMatches = merkleBlock.partialMerkleTree.extractMatches
        extractedMatches == txIds
    }

  property("contains all txids matched by a bloom filter") = {
    Prop.forAllNoShrink(MerkleGenerator.merkleBlockCreatedWithBloomFilter) {
      case (merkleBlock: MerkleBlock, block: Block, txIds: Seq[DoubleSha256Digest], loadedFilter: BloomFilter) =>
        val extractedMatches = merkleBlock.partialMerkleTree.extractMatches
        //note that intersection is paramount here, our bloom filter can have false positives
        //so we cannot do a straight up equality comparison
        //bloom filters cannot have false negatives though, so we should have ATLEAST
        //the txids specified by our generator in this set
        extractedMatches.intersect(txIds) == txIds
    }
  }
} 
Example 48
Source File: PartialMerkleTreeSpec.scala    From bitcoin-s-spv-node   with MIT License 5 votes vote down vote up
package org.bitcoins.spvnode.block

import org.bitcoins.core.crypto.DoubleSha256Digest
import org.bitcoins.spvnode.gen.MerkleGenerator
import org.scalacheck.{Prop, Properties}


class PartialMerkleTreeSpec extends Properties("PartialMerkleTreeSpec") {

  property("must be able to extract all of the txids we indicated to be matches") =
    Prop.forAll(MerkleGenerator.partialMerkleTree) {
      case (partialMerkleTree: PartialMerkleTree, txMatches: Seq[(Boolean,DoubleSha256Digest)]) =>
        val matchedTxs = txMatches.filter(_._1).map(_._2)
        partialMerkleTree.extractMatches == matchedTxs
    }

  property("must generate the same partial merkle tree from the same parameters") =
    Prop.forAll(MerkleGenerator.partialMerkleTree) {
      case (partialMerkleTree: PartialMerkleTree, _) =>
      val partialMerkleTree2 = PartialMerkleTree(partialMerkleTree.transactionCount,
        partialMerkleTree.hashes, partialMerkleTree.bits)
        partialMerkleTree2 == partialMerkleTree
    }


} 
Example 49
Source File: BlockHeaderStoreSpec.scala    From bitcoin-s-spv-node   with MIT License 5 votes vote down vote up
package org.bitcoins.spvnode.store

import org.bitcoins.core.gen.BlockchainElementsGenerator
import org.bitcoins.core.protocol.blockchain.BlockHeader
import org.scalacheck.{Gen, Prop, Properties}


class BlockHeaderStoreSpec extends Properties("BlockHeaderStoreSpec") {

  property("serialization symmetry to file") =
    Prop.forAll(Gen.listOf(BlockchainElementsGenerator.blockHeader)) { case headers : Seq[BlockHeader] =>
      val file = new java.io.File("src/test/resources/block_header_spec_1.dat")
      BlockHeaderStore.append(headers,file)
      val headersFromFile = BlockHeaderStore.read(file)
      val result = headersFromFile == headers
      file.delete()
      result
    }

  property("read the last stored blockheader stored in a file") =
    Prop.forAll(Gen.listOf(BlockchainElementsGenerator.blockHeader)) { case headers: Seq[BlockHeader] =>
      val file = new java.io.File("src/test/resources/block_header_spec_2.dat")
      BlockHeaderStore.append(headers,file)
      val lastHeader = BlockHeaderStore.lastHeader(file)
      val expectedLastHeader = if (headers.isEmpty) None else Some(headers.last)
      val result = lastHeader == expectedLastHeader
      file.delete()
      result
    }
} 
Example 50
Source File: ScriptNumberSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.script.constant

import org.bitcoins.testkit.core.gen.NumberGenerator
import org.scalacheck.{Prop, Properties}


class ScriptNumberSpec extends Properties("ScriptNumberSpec") {
  property("Additive identity") = Prop.forAll(NumberGenerator.scriptNumbers) {
    num: ScriptNumber =>
      num + ScriptNumber.zero == num
  }
  property("Subtraction identity") =
    Prop.forAll(NumberGenerator.scriptNumbers) { num: ScriptNumber =>
      num - ScriptNumber.zero == num
    }
  property("Multiplicative identity") =
    Prop.forAll(NumberGenerator.scriptNumbers) { num: ScriptNumber =>
      num * ScriptNumber.one == num
    }
  property("< >=") =
    Prop.forAll(NumberGenerator.scriptNumbers, NumberGenerator.scriptNumbers) {
      (num1: ScriptNumber, num2: ScriptNumber) =>
        if (num1.toLong < num2.toLong) num1 < num2
        else num1 >= num2
    }
  property("> <=") =
    Prop.forAll(NumberGenerator.scriptNumbers, NumberGenerator.scriptNumbers) {
      (num1: ScriptNumber, num2: ScriptNumber) =>
        if (num1.toLong > num2.toLong) num1 > num2
        else num1 <= num2
    }
  property("== & !=") =
    Prop.forAll(NumberGenerator.scriptNumbers, NumberGenerator.scriptNumbers) {
      (num1: ScriptNumber, num2: ScriptNumber) =>
        if (num1.toLong == num2.toLong) num1 == num2
        else num1 != num2
    }
  property("add two script numbers") =
    Prop.forAll(NumberGenerator.scriptNumbers, NumberGenerator.scriptNumbers) {
      (num1: ScriptNumber, num2: ScriptNumber) =>
        num1 + num2 == ScriptNumber(num1.toLong + num2.toLong)
    }
  property("subtract a script number from another script number") =
    Prop.forAll(NumberGenerator.scriptNumbers, NumberGenerator.scriptNumbers) {
      (num1: ScriptNumber, num2: ScriptNumber) =>
        num1 - num2 == ScriptNumber(num1.toLong - num2.toLong)
    }
  property("multiply two script numbers") =
    Prop.forAll(NumberGenerator.scriptNumbers, NumberGenerator.scriptNumbers) {
      (num1: ScriptNumber, num2: ScriptNumber) =>
        num1 * num2 == ScriptNumber(num1.toLong * num2.toLong)
    }
  property("multiply a script number by zero should return zero") =
    Prop.forAll(NumberGenerator.scriptNumbers) { (num1: ScriptNumber) =>
      num1 * ScriptNumber.zero == ScriptNumber.zero
    }
} 
Example 51
Source File: HashTypeSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.script.crypto

import org.bitcoins.testkit.core.gen.NumberGenerator
import org.bitcoins.core.util.BitcoinSLogger
import org.scalacheck.{Prop, Properties}

class HashTypeSpec extends Properties("HashTypeSpec") {
  private val logger = BitcoinSLogger.logger
  property("serialization symmetry") = {
    Prop.forAll(NumberGenerator.int32s) { i32 =>
      val hashType = HashType.fromBytes(i32.bytes)

      hashType.num == i32 &&
      i32.bytes.last == hashType.byte &&
      //this check cannot check the other 3 bytes in
      //hash type as they are discarded from inclusion
      //on a bitcoin digital signature. Not sure why satoshi
      //would have just used a uint8_t to represent a hash type
      //instead of a uint32_t.
      HashType.fromByte(hashType.byte).byte == hashType.byte

    }
  }
} 
Example 52
Source File: P2PKHScriptPubKeySpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.script

import org.bitcoins.testkit.core.gen.{CryptoGenerators, ScriptGenerators}
import org.scalacheck.{Prop, Properties}


class P2PKHScriptPubKeySpec extends Properties("P2PKHScriptPubKeySpec") {

  property("Serialization symmetry") =
    Prop.forAll(ScriptGenerators.p2pkhScriptPubKey) {
      case (p2pkhScriptPubKey, _) =>
        P2PKHScriptPubKey(p2pkhScriptPubKey.hex) == p2pkhScriptPubKey
    }

  property("find pubkeyhash in scriptPubKey") =
    Prop.forAll(CryptoGenerators.sha256Hash160Digest) { hash =>
      val scriptPubKey = P2PKHScriptPubKey(hash)
      scriptPubKey.pubKeyHash == hash
    }
} 
Example 53
Source File: ScriptWitnessSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.script

import org.bitcoins.testkit.core.gen.{ScriptGenerators, WitnessGenerators}
import org.bitcoins.core.util.BitcoinSLogger
import org.scalacheck.{Prop, Properties}

class ScriptWitnessSpec extends Properties("ScriptWitnessSpec") {
  private val logger = BitcoinSLogger.logger
  property("serialization symmetry") = {
    Prop.forAll(WitnessGenerators.scriptWitness) { scriptWit =>
      val x = ScriptWitness(scriptWit.stack)
      scriptWit == x
    }
  }

  property("pull redeem script out of p2wsh witness") = {
    Prop.forAll(ScriptGenerators.rawScriptPubKey) {
      case (spk, _) =>
        P2WSHWitnessV0(spk).redeemScript == spk
    }
  }

  property("pull script signature out of p2wsh witness") = {
    Prop.forAll(ScriptGenerators.rawScriptPubKey,
                ScriptGenerators.rawScriptSignature) {
      case ((spk, _), scriptSig) =>
        P2WSHWitnessV0(spk, scriptSig).scriptSignature == scriptSig
    }
  }
} 
Example 54
Source File: ScriptSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.script

import org.bitcoins.testkit.core.gen.ScriptGenerators
import org.scalacheck.{Prop, Properties}

class ScriptSpec extends Properties("ScriptSpec") {

  property(
    "serialization symmetry for ScriptFactory.fromAsmBytes with ScriptPubKeys") = {
    Prop.forAllNoShrink(ScriptGenerators.scriptPubKey) {
      case (spk, _) =>
        ScriptPubKey.fromAsmBytes(spk.asmBytes) == spk
    }
  }

  property(
    "serialization symmetry for ScriptFactory.fromAsmBytes with ScriptSignatures") = {
    Prop.forAllNoShrink(ScriptGenerators.scriptSignature) {
      case ss =>
        ScriptSignature.fromAsmBytes(ss.asmBytes) == ss
    }
  }
} 
Example 55
Source File: WitnessScriptPubKeySpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.script

import org.bitcoins.testkit.core.gen.ScriptGenerators
import org.scalacheck.{Prop, Properties}


class WitnessScriptPubKeySpec extends Properties("WitnessScriptPubKeySpec") {

  property("witnessScriptPubKeyV0 serialization symmetry") =
    Prop.forAll(ScriptGenerators.witnessScriptPubKeyV0) {
      case (witScriptPubKeyV0, _) =>
        witScriptPubKeyV0 match {
          case p2wpkh: P2WPKHWitnessSPKV0 =>
            P2WPKHWitnessSPKV0(p2wpkh.hex) == witScriptPubKeyV0
          case p2wsh: P2WSHWitnessSPKV0 =>
            P2WSHWitnessSPKV0(p2wsh.hex) == witScriptPubKeyV0
        }
    }

  property("witnessScriptPubKeyV0 fromAsm symmetry") =
    Prop.forAll(ScriptGenerators.witnessScriptPubKeyV0) {
      case (witScriptPubKeyV0, _) =>
        witScriptPubKeyV0 match {
          case p2wpkh: P2WPKHWitnessSPKV0 =>
            P2WPKHWitnessSPKV0.fromAsm(p2wpkh.asm) == witScriptPubKeyV0
          case p2wsh: P2WSHWitnessSPKV0 =>
            P2WSHWitnessSPKV0.fromAsm(p2wsh.asm) == witScriptPubKeyV0
        }
    }

  property("unassignedWitnessScriptPubKey serialization symmetry") =
    Prop.forAll(ScriptGenerators.unassignedWitnessScriptPubKey) {
      case (unassignedWitScriptPubKey, _) =>
        UnassignedWitnessScriptPubKey(
          unassignedWitScriptPubKey.hex) == unassignedWitScriptPubKey
    }

  property("unassignedWitnessScriptPubKey fromAsm symmetry") =
    Prop.forAll(ScriptGenerators.unassignedWitnessScriptPubKey) {
      case (unassignedWitScriptPubKey, _) =>
        UnassignedWitnessScriptPubKey.fromAsm(
          unassignedWitScriptPubKey.asm) == unassignedWitScriptPubKey
    }

  property("witnessScriptPubKey fromAsm symmetry") = {
    Prop.forAll(ScriptGenerators.witnessScriptPubKey) {
      case (witScriptPubKey, _) =>
        WitnessScriptPubKey(witScriptPubKey.asm) == witScriptPubKey
    }
  }
} 
Example 56
Source File: TransactionWitnessSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.transaction

import org.bitcoins.core.protocol.script._
import org.bitcoins.crypto.{DummyECDigitalSignature, ECPrivateKey}
import org.bitcoins.testkit.core.gen.WitnessGenerators
import org.bitcoins.testkit.util.BitcoinSUnitTest
import org.scalacheck.Prop


class TransactionWitnessSpec extends BitcoinSUnitTest {

  behavior of "TransactionWitness"

  it must "have serialization symmetry" in {
    Prop.forAll(WitnessGenerators.transactionWitness) { witness =>
      TransactionWitness(witness.hex, witness.witnesses.size) == witness
    }
  }

  it must "be able to resize a witness to the given index" in {
    val empty = EmptyWitness.fromN(0)
    val pubKey = ECPrivateKey.freshPrivateKey.publicKey
    val p2pkh = P2PKHScriptSignature(DummyECDigitalSignature, pubKey)
    val scriptWit = P2WPKHWitnessV0.fromP2PKHScriptSig(p2pkh)
    val updated = empty.updated(2, scriptWit)

    updated.witnesses.length must be(3)
  }

  it must "fail to update a negative index witness" in {
    intercept[IndexOutOfBoundsException] {
      EmptyWitness.fromN(0).updated(-1, EmptyScriptWitness)
    }
  }

} 
Example 57
Source File: Bech32Spec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol

import org.bitcoins.core.util.Bech32
import org.bitcoins.testkit.core.gen.ln.LnInvoiceGen
import org.bitcoins.testkit.core.gen.{
  AddressGenerator,
  ChainParamsGenerator,
  ScriptGenerators
}
import org.scalacheck.{Prop, Properties}

import scala.annotation.tailrec
import scala.util.{Random, Success}

class Bech32Spec extends Properties("Bech32Spec") {
  property("split all LN invoices into HRP and data") = {
    Prop.forAll(LnInvoiceGen.lnInvoice) { invoice =>
      val splitT = Bech32.splitToHrpAndData(invoice.toString)
      splitT.isSuccess
    }
  }

  property("split all Bech32 addresses into HRP and data") = {
    Prop.forAll(AddressGenerator.bech32Address) { address =>
      val splitT = Bech32.splitToHrpAndData(address.value)
      splitT.isSuccess
    }
  }

  property("serialization symmetry") = {
    Prop.forAll(ScriptGenerators.witnessScriptPubKey,
                ChainParamsGenerator.networkParams) {
      case ((witSPK, _), network) =>
        val addr = Bech32Address(witSPK, network)
        val spk = Bech32Address.fromStringToWitSPK(addr.value)
        spk == Success(witSPK)
    }
  }

  property("checksum must not work if we modify a char") = {
    Prop.forAll(AddressGenerator.bech32Address) { addr: Bech32Address =>
      val old = addr.value
      val rand = Math.abs(Random.nextInt)
      val idx = rand % old.length
      val (f, l) = old.splitAt(idx)
      val replacementChar = pickReplacementChar(l.head)
      val replaced = s"$f$replacementChar${l.tail}"
      //should fail because we replaced a char in the addr, so checksum invalid
      Bech32Address.fromStringT(replaced).isFailure
    }
  }

  property("must fail if we have a mixed case") = {
    Prop.forAllNoShrink(AddressGenerator.bech32Address) { addr: Bech32Address =>
      val old = addr.value
      val replaced = switchCaseRandChar(old)
      //should fail because we we switched the case of a random char
      val actual = Bech32Address.fromStringT(replaced)
      actual.isFailure
    }
  }

  @tailrec
  private def pickReplacementChar(oldChar: Char): Char = {
    val rand = Math.abs(Random.nextInt)
    val newChar = Bech32.charset(rand % Bech32.charset.size)
    //make sure we don't pick the same char we are replacing in the bech32 address
    if (oldChar == newChar) pickReplacementChar(oldChar)
    else newChar
  }

  @tailrec
  private def switchCaseRandChar(addr: String): String = {
    val rand = Math.abs(Random.nextInt)
    val idx = rand % addr.length
    val (f, l) = addr.splitAt(idx)
    if (l.head.isDigit) {
      switchCaseRandChar(addr)
    } else {
      val middle =
        if (l.head.isUpper) {
          l.head.toLower
        } else {
          l.head.toUpper
        }
      s"$f$middle${l.tail}"
    }
  }
} 
Example 58
Source File: BitcoinAddressSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol

import org.bitcoins.core.config.TestNet3
import org.bitcoins.testkit.core.gen.{
  AddressGenerator,
  CryptoGenerators,
  ScriptGenerators
}
import org.bitcoins.core.protocol.script.P2SHScriptPubKey
import org.bitcoins.crypto.CryptoUtil
import org.scalacheck.{Prop, Properties}


class BitcoinAddressSpec extends Properties("BitcoinAddressSpec") {

  property("get the same p2sh address no matter what factory function we use") =
    Prop.forAll(ScriptGenerators.randomNonP2SHScriptPubKey) {
      case (scriptPubKey, _) =>
        //we should get the same address no matter which factory function we use
        val p2shScriptPubKey = P2SHScriptPubKey(scriptPubKey)
        P2SHAddress(scriptPubKey, TestNet3) == P2SHAddress(p2shScriptPubKey,
                                                           TestNet3)

    }

  property("All p2sh addresses created from factory functions must be valid") =
    Prop.forAll(ScriptGenerators.randomNonP2SHScriptPubKey) {
      case (scriptPubKey, _) =>
        //we should get the same address no matter which factory function we use
        val addr = P2SHAddress(scriptPubKey, TestNet3)
        P2SHAddress.isValid(addr.toString)
    }

  property(
    "get the same p2pkh address no matter what factory function we use") =
    Prop.forAll(CryptoGenerators.publicKey) { pubKey =>
      val hash = CryptoUtil.sha256Hash160(pubKey.bytes)
      P2PKHAddress(pubKey, TestNet3) == P2PKHAddress(hash, TestNet3)
    }
  property("All p2pkh addresses created from factory functions must be valid") =
    Prop.forAll(CryptoGenerators.publicKey) { pubKey =>
      val addr = P2PKHAddress(pubKey, TestNet3)
      P2PKHAddress.isValid(addr.toString)
    }

  property("serialization symmetry between script and address") = {
    Prop.forAll(AddressGenerator.address) { addr =>
      val spk = addr.scriptPubKey
      val network = addr.networkParameters
      Address.fromScriptPubKey(spk, network) == addr
    }
  }
} 
Example 59
Source File: MerkleBlockSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.blockchain

import org.bitcoins.crypto.DoubleSha256Digest
import org.bitcoins.testkit.core.gen.MerkleGenerator
import org.scalacheck.{Prop, Properties}


class MerkleBlockSpec extends Properties("MerkleBlockSpec") {

  //TODO: This is *extremely* slow, this is currently the longest running property we have taking about 6 minutes to run
  //I think it is the generator MerkleGenerator.merkleBlockWithInsertTxIds
  property(
    "contains all inserted txids when we directly create a merkle block from the txids && " +
      "contains all txids matched by a bloom filter && " +
      "serialization symmetry") =
    Prop.forAllNoShrink(MerkleGenerator.merkleBlockWithInsertedTxIds) {
      case (merkleBlock: MerkleBlock, _, txIds: Seq[DoubleSha256Digest]) =>
        val extractedMatches = merkleBlock.partialMerkleTree.extractMatches
        extractedMatches == txIds &&
        extractedMatches.intersect(txIds) == txIds &&
        MerkleBlock(merkleBlock.hex) == merkleBlock
    }
} 
Example 60
Source File: PartialMerkleTreeSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.blockchain

import org.bitcoins.crypto.DoubleSha256Digest
import org.bitcoins.testkit.core.gen.MerkleGenerator
import org.scalacheck.{Prop, Properties}


class PartialMerkleTreeSpec extends Properties("PartialMerkleTreeSpec") {

  property(
    "must be able to extract all of the txids we indicated to be matches") =
    Prop.forAll(MerkleGenerator.partialMerkleTree) {
      case (partialMerkleTree: PartialMerkleTree,
            txMatches: Seq[(Boolean, DoubleSha256Digest)]) =>
        val matchedTxs = txMatches.filter(_._1).map(_._2)
        partialMerkleTree.extractMatches == matchedTxs
    }

  property(
    "must generate the same partial merkle tree from the same parameters") =
    Prop.forAll(MerkleGenerator.partialMerkleTree) {
      case (partialMerkleTree: PartialMerkleTree, _) =>
        val partialMerkleTree2 =
          PartialMerkleTree(partialMerkleTree.transactionCount,
                            partialMerkleTree.hashes,
                            partialMerkleTree.bits)
        partialMerkleTree2 == partialMerkleTree
    }

} 
Example 61
Source File: Int64Spec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.number

import org.bitcoins.testkit.core.gen.NumberGenerator
import org.scalacheck.{Prop, Properties}

import scala.util.Try


class Int64Spec extends Properties("Int64Spec") {

  property("Symmetrical serialization") = Prop.forAll(NumberGenerator.int64s) {
    int64: Int64 =>
      Int64(int64.hex) == int64
  }

  property("Additive identity") = Prop.forAll(NumberGenerator.int64s) {
    int64: Int64 =>
      int64 + Int64.zero == int64
  }
  property("Add two arbitrary int64s") =
    Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
      (num1: Int64, num2: Int64) =>
        val result = num1.toBigInt + num2.toBigInt
        if (result >= Int64.min.toLong && result <= Int64.max.toLong)
          num1 + num2 == Int64(result)
        else Try(num1 + num2).isFailure
    }

  property("Subtractive identity") = Prop.forAll(NumberGenerator.int64s) {
    int64: Int64 =>
      int64 - Int64.zero == int64
  }

  property("Subtract two arbitrary int64s") =
    Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
      (num1: Int64, num2: Int64) =>
        val result = num1.toBigInt - num2.toBigInt
        if (result >= Int64.min.toLong && result <= Int64.max.toLong)
          num1 - num2 == Int64(result)
        else Try(num1 - num2).isFailure
    }

  property("Multiplying by zero") = Prop.forAll(NumberGenerator.int64s) {
    int64: Int64 =>
      int64 * Int64.zero == Int64.zero
  }

  property("Multiplicative identity") = Prop.forAll(NumberGenerator.int64s) {
    int64: Int64 =>
      int64 * Int64.one == int64
  }

  property("Multiply two arbitrary int64s") =
    Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
      (num1: Int64, num2: Int64) =>
        val result = num1.toBigInt * num2.toBigInt
        if (result >= Int64.min.toLong && result <= Int64.max.toLong)
          num1 * num2 == Int64(result)
        else Try(num1 * num2).isFailure
    }

  property("<= & >") =
    Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
      (num1: Int64, num2: Int64) =>
        if (num1.toLong <= num2.toLong) num1 <= num2
        else num1 > num2

    }

  property("< & =>") =
    Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
      (num1: Int64, num2: Int64) =>
        if (num1.toLong < num2.toLong) num1 < num2
        else num1 >= num2

    }

  property("== & !=") =
    Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
      (num1: Int64, num2: Int64) =>
        if (num1.toLong == num2.toLong) num1 == num2
        else num1 != num2
    }

  property("|") = Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
    (num1: Int64, num2: Int64) =>
      Int64(num1.toLong | num2.toLong) == (num1 | num2)
  }

  property("&") = Prop.forAll(NumberGenerator.int64s, NumberGenerator.int64s) {
    (num1: Int64, num2: Int64) =>
      Int64(num1.toLong & num2.toLong) == (num1 & num2)
  }

  property("negation") = {
    Prop.forAll(NumberGenerator.int64s) { int64 =>
      -int64 == Int64(-int64.toLong)
    }
  }

} 
Example 62
Source File: UInt64Spec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.number

import org.bitcoins.testkit.core.gen.NumberGenerator
import org.scalacheck.{Prop, Properties}

import scala.util.Try


class UInt64Spec extends Properties("UInt64Spec") {

  property("Serialization symmetry") = Prop.forAll(NumberGenerator.uInt64s) {
    uInt64: UInt64 =>
      UInt64(uInt64.hex) == uInt64
      UInt64(uInt64.hex).hex == uInt64.hex
  }

  property("additive identity") = Prop.forAll(NumberGenerator.uInt64s) {
    uInt64: UInt64 =>
      if (uInt64.toBigInt <= UInt64.max.toBigInt)
        uInt64 + UInt64.zero == UInt64(uInt64.toBigInt)
      else uInt64 + UInt64.zero == uInt64
  }

  property("add two arbitrary uInt64s") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        val result: BigInt = num1.toBigInt + num2.toBigInt
        if (result <= UInt64.max.toBigInt) num1 + num2 == UInt64(result)
        else Try(num1 + num2).isFailure
    }

  property("subtractive identity") = Prop.forAll(NumberGenerator.uInt64s) {
    uInt64: UInt64 =>
      if (uInt64.toBigInt <= UInt64.max.toBigInt)
        uInt64 - UInt64.zero == UInt64(uInt64.toBigInt)
      else uInt64 - UInt64.zero == uInt64
  }

  property("subtract a uint64 from a uint64") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        val result = num1.toBigInt - num2.toBigInt
        if (result < 0) Try(num1 - num2).isFailure
        else num1 - num2 == UInt64(result)
    }

  property("multiplying by zero") = Prop.forAll(NumberGenerator.uInt64s) {
    uInt64: UInt64 =>
      uInt64 * UInt64.zero == UInt64.zero
  }

  property("multiplicative identity") = Prop.forAll(NumberGenerator.uInt64s) {
    uInt64: UInt64 =>
      if (uInt64 == UInt64.zero) uInt64 * UInt64.one == UInt64.zero
      else uInt64 * UInt64.one == uInt64
  }

  property("multiply two uInt64s") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        val result = num1.toBigInt * num2.toBigInt
        if (result <= UInt64.max.toBigInt) num1 * num2 == UInt64(result)
        else Try(num1 * num2).isFailure
    }

  property("< & >= for uInt64s") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        if (num1.toBigInt < num2.toBigInt) num1 < num2
        else num1 >= num2
    }

  property("<= & > with two uInt64s") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        if (num1.toBigInt <= num2.toBigInt) num1 <= num2
        else num1 > num2
    }

  property("== & != for two UInt64s") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        if (num1.toBigInt == num2.toBigInt) num1 == num2
        else num1 != num2
    }

  property("|") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        UInt64(num1.toBigInt | num2.toBigInt) == (num1 | num2)
    }

  property("&") =
    Prop.forAll(NumberGenerator.uInt64s, NumberGenerator.uInt64s) {
      (num1: UInt64, num2: UInt64) =>
        UInt64(num1.toBigInt & num2.toBigInt) == (num1 & num2)
    }
} 
Example 63
Source File: Int32Spec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.number

import org.bitcoins.testkit.core.gen.NumberGenerator
import org.scalacheck.{Prop, Properties}

import scala.util.Try


class Int32Spec extends Properties("Int32Spec") {

  property("Serialization symmetry") = Prop.forAll(NumberGenerator.int32s) {
    int32: Int32 =>
      Int32(int32.hex) == int32

  }
  property("Additive identity") = Prop.forAll(NumberGenerator.int32s) {
    int32: Int32 =>
      int32 + Int32.zero == int32
  }
  property("Add two arbitrary int32s") =
    Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
      (num1: Int32, num2: Int32) =>
        val result = num1.toLong + num2.toLong
        if (result <= Int32.max.toLong && result >= Int32.min.toLong)
          num1 + num2 == Int32(result)
        else Try(num1 + num2).isFailure
    }

  property("Subtractive identity") = Prop.forAll(NumberGenerator.int32s) {
    int32: Int32 =>
      int32 - Int32.zero == int32
  }

  property("Subtract two arbitrary int32s") =
    Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
      (num1: Int32, num2: Int32) =>
        val result = num1.toLong - num2.toLong
        if (result >= Int32.min.toLong && result <= Int32.max.toLong)
          num1 - num2 == Int32(result)
        else Try(num1 - num2).isFailure
    }

  property("Multiplying by zero") = Prop.forAll(NumberGenerator.int32s) {
    int32: Int32 =>
      int32 * Int32.zero == Int32.zero
  }

  property("Multiplicative identity") = Prop.forAll(NumberGenerator.int32s) {
    int32: Int32 =>
      int32 * Int32.one == int32
  }

  property("Multiply two int32s") =
    Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
      (num1: Int32, num2: Int32) =>
        val result = num1.toLong * num2.toLong
        if (result >= Int32.min.toLong && result <= Int32.max.toLong)
          num1 * num2 == Int32(result.toInt)
        else Try(num1 * num2).isFailure
    }

  property("<= & >") =
    Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
      (num1: Int32, num2: Int32) =>
        if (num1.toLong <= num2.toLong) num1 <= num2
        else num1 > num2

    }

  property("< & =>") =
    Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
      (num1: Int32, num2: Int32) =>
        if (num1.toLong < num2.toLong) num1 < num2
        else num1 >= num2

    }

  property("== & !=") =
    Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
      (num1: Int32, num2: Int32) =>
        if (num1.toLong == num2.toLong) num1 == num2
        else num1 != num2
    }

  property("|") = Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
    (num1: Int32, num2: Int32) =>
      Int32(num1.toLong | num2.toLong) == (num1 | num2)
  }

  property("&") = Prop.forAll(NumberGenerator.int32s, NumberGenerator.int32s) {
    (num1: Int32, num2: Int32) =>
      Int32(num1.toLong & num2.toLong) == (num1 & num2)
  }

  property("negation") = {
    Prop.forAll(NumberGenerator.int32s) { int32 =>
      -int32 == Int32(-int32.toLong)
    }
  }
} 
Example 64
Source File: UInt8Spec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.number

import org.bitcoins.testkit.core.gen.NumberGenerator
import org.bitcoins.core.util.BitcoinSLogger
import org.scalacheck.{Gen, Prop, Properties}

import scala.util.Try

class UInt8Spec extends Properties("UInt8Spec") {
  private val logger = BitcoinSLogger.logger
  property("convert uint8 -> byte -> uint8") = {
    Prop.forAll(NumberGenerator.uInt8) {
      case u8: UInt8 =>
        UInt8(UInt8.toByte(u8)) == u8
    }
  }

  property("serialization symmetry") = {
    Prop.forAll(NumberGenerator.uInt8) { u8 =>
      UInt8(u8.hex) == u8
    }
  }

  property("<<") = {
    Prop.forAllNoShrink(NumberGenerator.uInt8, Gen.choose(0, 8)) {
      case (u8: UInt8, shift: Int) =>
        val r = Try(u8 << shift)
        val expected = (u8.toLong << shift) & 0xffL
        if (expected <= UInt8.max.toLong) {
          r.get == UInt8(expected.toShort)
        } else {
          r.isFailure
        }
    }
  }

  property(">>") = {
    Prop.forAllNoShrink(NumberGenerator.uInt8, Gen.choose(0, 100)) {
      case (u8: UInt8, shift: Int) =>
        val r = u8 >> shift
        val expected =
          if (shift > 31) UInt8.zero else UInt8((u8.toLong >> shift).toShort)
        if (r != expected) {
          logger.warn("expected: " + expected)
          logger.warn("r: " + r)
        }
        r == expected

    }
  }
} 
Example 65
Source File: ExtKeySpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.crypto

import org.bitcoins.testkit.core.gen.CryptoGenerators
import org.bitcoins.core.number.UInt32
import org.bitcoins.core.util.BitcoinSLogger
import org.bitcoins.testkit.util.BitcoinSUnitTest
import org.scalacheck.{Gen, Prop, Properties}

import scala.util.Success

class ExtKeySpec extends BitcoinSUnitTest {

  private val nonHardened: Gen[UInt32] =
    Gen.choose(0L, ((1L << 31) - 1)).map(UInt32(_))

  private val hardened: Gen[UInt32] =
    Gen.choose(1L << 31, (1L << 32) - 1).map(UInt32(_))

  it must "have serialization symmetry" in {
    Prop.forAll(CryptoGenerators.extKey) { extKey =>
      ExtKey.fromString(extKey.toString) == Success(extKey) &&
      ExtKey(extKey.bytes) == extKey
    }
  }

  it must "have derivation identity 1" in {
    Prop.forAllNoShrink(CryptoGenerators.extPrivateKey,
                        nonHardened,
                        nonHardened,
                        nonHardened) { (m, a, b, c) =>
      //https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#the-key-tree
      //N(m/a/b/c) = N(m/a/b)/c = N(m/a)/b/c = N(m)/a/b/c = M/a/b/c
      val path1 = m
        .deriveChildPrivKey(a)
        .deriveChildPrivKey(b)
        .deriveChildPrivKey(c)
        .extPublicKey
      val path2 = m
        .deriveChildPrivKey(a)
        .deriveChildPrivKey(b)
        .extPublicKey
        .deriveChildPubKey(c)
        .get
      val path3 = m
        .deriveChildPrivKey(a)
        .extPublicKey
        .deriveChildPubKey(b)
        .get
        .deriveChildPubKey(c)
        .get
      val path4 = m.extPublicKey
        .deriveChildPubKey(a)
        .get
        .deriveChildPubKey(b)
        .get
        .deriveChildPubKey(c)
        .get
      path1 == path2 && path2 == path3 && path3 == path4
    }
  }

  it must "derivation identity 2" in {
    Prop.forAllNoShrink(CryptoGenerators.extPrivateKey,
                        hardened,
                        nonHardened,
                        nonHardened) { (m, aH, b, c) =>
      //https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#the-key-tree
      //N(m/aH/b/c) = N(m/aH/b)/c = N(m/aH)/b/c
      val path1 = m
        .deriveChildPrivKey(aH)
        .deriveChildPrivKey(b)
        .deriveChildPrivKey(c)
        .extPublicKey
      val path2 = m
        .deriveChildPrivKey(aH)
        .deriveChildPrivKey(b)
        .extPublicKey
        .deriveChildPubKey(c)
        .get
      val path3 = m
        .deriveChildPrivKey(aH)
        .extPublicKey
        .deriveChildPubKey(b)
        .get
        .deriveChildPubKey(c)
        .get
      path1 == path2 && path2 == path3
    }
  }
} 
Example 66
Source File: NumberUtilSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.util

import org.bitcoins.testkit.core.gen.NumberGenerator
import org.bitcoins.core.number.UInt8
import org.scalacheck.{Prop, Properties}


class NumberUtilSpec extends Properties("NumberUtilSpec") {
  private val logger = BitcoinSLogger.logger

  property("Serialization symmetry for BigInt") =
    Prop.forAll(NumberGenerator.bigInts) { bigInt: BigInt =>
      NumberUtil.toBigInt(BytesUtil.encodeHex(bigInt)) == bigInt
    }

  property("serialization symmetry for ints") = Prop.forAll { int: Int =>
    NumberUtil.toInt(BytesUtil.encodeHex(int)) == int
  }

  property("serialization symmetry for longs") = Prop.forAll { long: Long =>
    NumberUtil.toLong(BytesUtil.encodeHex(long)) == long
  }

  property("convertBits symmetry") = {
    Prop.forAllNoShrink(NumberGenerator.uInt8s) {
      case (u8s: Seq[UInt8]) =>
        val u5s = NumberUtil.convertUInt8sToUInt5s(u8s.toVector)
        val original: Vector[UInt8] = NumberUtil.convertUInt5sToUInt8(u5s = u5s)
        original == u8s
    }
  }
} 
Example 67
Source File: BitcoinSUtilSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.util

import org.bitcoins.testkit.core.gen.StringGenerators
import org.scalacheck.{Prop, Properties}


class BitcoinSUtilSpec extends Properties("BitcoinSUtilSpec") {

  property("Serialization symmetry for encodeHex & decodeHex") =
    Prop.forAll(StringGenerators.hexString) { hex: String =>
      BytesUtil.encodeHex(BytesUtil.decodeHex(hex)) == hex
    }

  property("Flipping endianness symmetry") =
    Prop.forAll(StringGenerators.hexString) { hex: String =>
      BytesUtil.flipEndianness(BytesUtil.flipEndianness(hex)) == hex
    }

  property(
    "Convert a byte to a bit vector, convert it back to the original byte") =
    Prop.forAll { byte: Byte =>
      BytesUtil
        .bitVectorToBytes(BytesUtil.byteToBitVector(byte))
        .toByte() == byte
    }
} 
Example 68
Source File: RawSerializerHelperSpec.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.serializers

import org.bitcoins.testkit.core.gen.TransactionGenerators
import org.bitcoins.core.protocol.transaction.TransactionOutput
import org.scalacheck.{Prop, Properties}
import scodec.bits.ByteVector

class RawSerializerHelperSpec extends Properties("RawSerializerHelperSpec") {

  property("serialization symmetry of txs") = {
    Prop.forAll(TransactionGenerators.smallOutputs) {
      txs: Seq[TransactionOutput] =>
        val serialized =
          RawSerializerHelper.writeCmpctSizeUInt(txs,
                                                 { tx: TransactionOutput =>
                                                   tx.bytes
                                                 })
        val (deserialized, remaining) = RawSerializerHelper
          .parseCmpctSizeUIntSeq(serialized, TransactionOutput(_: ByteVector))
        deserialized == txs && remaining == ByteVector.empty
    }
  }

} 
Example 69
Source File: UtilsProp.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.prop

import org.scalacheck.{Properties, Gen}
import org.scalacheck.Prop.{forAll, exists, AnyOperators}
import org.scalacheck.Prop
import org.scalatest._
import org.scalatest.Matchers._
import org.specs2.matcher.MatchFailureException
import scala.util.{Try, Success, Failure}
import org.scalacheck.util.Pretty

object UtilsProp {
  def safeProp[P <% Prop](p : => P) : Prop = {
    Try(p) match {
      case Success(pVal) => pVal
      case Failure(t) => t match {
        case _: TestFailedException => Prop.falsified
        case _: MatchFailureException[_] => Prop.falsified
        case _ => Prop.exception(t) 
      }
    }
  }
  
  def safeExists[A, P](g: Gen[A])(f: (A) => P)
                      (implicit pv: (P) => Prop, pp: (A) => Pretty): Prop = {    
    exists(g)((x : A) => safeProp(pv(f(x))))(identity[Prop], pp)
    // This doesn't work for reasons unknown
    // exists(g)((x : A) => Prop.secure(pv(f(x))))(identity[Prop], pp)
  }  
} 
Example 70
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 71
Source File: SemigroupalKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package laws
package discipline


import cats.{Eq, ~>}
import cats.data.Tuple2K
import cats.tagless.laws.discipline.SemigroupalKTests.IsomorphismsK
import org.scalacheck.Prop._
import org.scalacheck.{Arbitrary, Prop}
import org.typelevel.discipline.Laws

trait SemigroupalKTests[F[_[_]]] extends Laws {
  def laws: SemigroupalKLaws[F]

  def semigroupalK[A[_], B[_], C[_]](implicit
                                               ArbCF: Arbitrary[F[A]],
                                               ArbCG: Arbitrary[F[B]],
                                               ArbCH: Arbitrary[F[C]],
                                               iso: IsomorphismsK[F],
                                               EqFGH: Eq[F[Tuple3K[A, B, C]#λ]]
                                              ): RuleSet = {
    new DefaultRuleSet(
      name = "SemigroupalK",
      parent = None,
      "semigroupal associativity" -> forAll((af: F[A], ag: F[B], ah: F[C]) => iso.associativity(laws.semigroupalAssociativity[A, B, C](af, ag, ah))))
  }
}


object SemigroupalKTests {
  def apply[F[_[_]]: SemigroupalK]: SemigroupalKTests[F] =
    new SemigroupalKTests[F] { def laws: SemigroupalKLaws[F] = SemigroupalKLaws[F] }

  import IsomorphismsK._

  trait IsomorphismsK[F[_[_]]] {
    def associativity[A[_], B[_], C[_]](fs: (F[ProdA_BC[A, B, C]#λ], F[ProdAB_C[A, B, C]#λ]))
                                       (implicit EqFGH: Eq[F[Tuple3K[A, B, C]#λ]]): Prop
  }

  object IsomorphismsK {
    
    type ProdA_BC[A[_], B[_], C[_]]  = { type λ[T] = Tuple2K[A, Tuple2K[B, C, *], T] }
    type ProdAB_C[A[_], B[_], C[_]]  = { type λ[T] = Tuple2K[Tuple2K[A, B, *], C, T] }

    implicit def invariantK[F[_[_]]](implicit F: InvariantK[F]): IsomorphismsK[F] =
      new IsomorphismsK[F] {
        def associativity[A[_], B[_], C[_]](fs: (F[ProdA_BC[A, B, C]#λ], F[ProdAB_C[A, B, C]#λ]))
                                           (implicit EqFGH: Eq[F[Tuple3K[A, B, C]#λ]]): Prop = {

          val fkA_BC_T3 = λ[ProdA_BC[A, B, C]#λ ~> Tuple3K[A, B, C]#λ ]{ case Tuple2K(a, Tuple2K(b, c)) => (a, b, c) }
          val fkAB_C_T3 = λ[ProdAB_C[A, B, C]#λ ~> Tuple3K[A, B, C]#λ ]{ case Tuple2K(Tuple2K(a, b), c) => (a, b, c) }
          val fkT3_AB_C = λ[Tuple3K[A, B, C]#λ ~> ProdAB_C[A, B, C]#λ]{ case (a, b, c) => Tuple2K(Tuple2K(a, b), c) }
          val fkT3_A_BC = λ[Tuple3K[A, B, C]#λ ~> ProdA_BC[A, B, C]#λ]{ case (a, b, c) => Tuple2K(a, Tuple2K(b, c)) }

          EqFGH.eqv(
            F.imapK[ProdA_BC[A, B, C]#λ, Tuple3K[A, B, C]#λ](fs._1)(fkA_BC_T3)(fkT3_A_BC),
            F.imapK[ProdAB_C[A, B, C]#λ, Tuple3K[A, B, C]#λ](fs._2)(fkAB_C_T3)(fkT3_AB_C)
          )
        }

      }
  }
} 
Example 72
Source File: RoleJsonSpec.scala    From sbt-kubeyml   with MIT License 5 votes vote down vote up
package kubeyml.roles

import org.scalacheck.{Prop, Properties}
import io.circe.syntax._
import json_support._
class RoleJsonSpec extends Properties("rolejson") with KubernetesRole {

  property("validjson") = Prop.forAll(validDefinition) { validDefinition =>
    val expectedJson = roleToJson(validDefinition)
    val role = toRole(validDefinition)
    val actualJson = role.asJson
    if (actualJson != expectedJson) {
      println(actualJson)
      println(expectedJson)
    }
    actualJson == expectedJson
  }

} 
Example 73
Source File: KnownFormatsReaderTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv
package laws
package discipline

import org.scalacheck.Prop
import org.typelevel.discipline.Laws

trait KnownFormatsReaderTests extends Laws {
  def laws: KnownFormatsReaderLaws

  def knownFormats: RuleSet = new DefaultRuleSet(
    name = "knownFormats",
    parent = None,
    "excel for mac 12.0" -> Prop(laws.excelMac120),
    "numbers 1.0.3"      -> Prop(laws.numbers103),
    "google docs"        -> Prop(laws.googleDocs)
  )
} 
Example 74
Source File: SpectrumReaderTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv
package laws
package discipline

import org.scalacheck.Prop
import org.typelevel.discipline.Laws

trait SpectrumReaderTests extends Laws {
  def laws: SpectrumReaderLaws

  def csvSpectrum: RuleSet = new DefaultRuleSet(
    name = "csvSpectrum",
    parent = None,
    "comma in quotes"     -> Prop(laws.commaInQuotes),
    "empty"               -> Prop(laws.empty),
    "empty crlf"          -> Prop(laws.emptyCRLF),
    "escaped quotes"      -> Prop(laws.escapedQuotes),
    "json"                -> Prop(laws.json),
    "newlines"            -> Prop(laws.newLines),
    "newlines crlf"       -> Prop(laws.newLinesCRLF),
    "quotes and newlines" -> Prop(laws.quotesAndNewLines),
    "simple"              -> Prop(laws.simple),
    "simple crlf"         -> Prop(laws.simpleCRLF),
    "utf8"                -> Prop(laws.utf8)
  )
} 
Example 75
Source File: IsDateTimeLaws.scala    From cron4s   with Apache License 2.0 5 votes vote down vote up
package cron4s.testkit.laws

import cats.Eq
import cats.kernel.laws._
import cats.implicits._

import cron4s.CronField
import cron4s.datetime.IsDateTime
import cron4s.testkit._

import org.scalacheck.Prop
import Prop._


trait IsDateTimeLaws[DateTime] {
  implicit def DT: IsDateTime[DateTime]
  implicit def eq: Eq[DateTime]

  def gettable[F <: CronField](dt: DateTime, field: F): IsEq[Boolean] =
    DT.get(dt, field).isRight <-> DT.supportedFields(dt).contains(field)

  def immutability[F <: CronField](dt: DateTime, fieldValue: CronFieldValue[F]): Prop =
    if (DT.supportedFields(dt).contains(fieldValue.field)) {
      val check = for {
        current     <- DT.get(dt, fieldValue.field)
        newDateTime <- DT.set(dt, fieldValue.field, fieldValue.value)
      } yield {
        if (current === fieldValue.value) Prop.undecided
        else Prop(newDateTime =!= dt)
      }

      check.fold(Prop.exception(_), identity)
    } else Prop.proved

  def settable[F <: CronField](dt: DateTime, fieldValue: CronFieldValue[F]): Prop =
    if (DT.supportedFields(dt).contains(fieldValue.field)) {
      val check = for {
        newDateTime <- DT.set(dt, fieldValue.field, fieldValue.value)
        value       <- DT.get(newDateTime, fieldValue.field)
      } yield value

      check.fold(Prop.exception(_), _ ?= fieldValue.value)
    } else Prop.proved
}

object IsDateTimeLaws {
  def apply[DateTime](
      implicit
      dtEv: IsDateTime[DateTime],
      eqEv: Eq[DateTime]
  ): IsDateTimeLaws[DateTime] =
    new IsDateTimeLaws[DateTime] {
      implicit val eq: Eq[DateTime]         = eqEv
      implicit val DT: IsDateTime[DateTime] = dtEv
    }
} 
Example 76
Source File: BreezeCheck.scala    From nd4s   with Apache License 2.0 5 votes vote down vote up
package org.nd4s

import breeze.linalg._
import monocle.Prism
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.factory.Nd4j
import org.nd4s.Implicits._
import org.scalacheck.{Arbitrary, Gen, Prop}
import org.scalatest.FlatSpec
import org.scalatest.prop.Checkers


class BreezeCheck extends FlatSpec with Checkers {
  it should "work as same as NDArray slicing" in {
    check {
      Prop.forAll {
        (ndArray: INDArray) =>
          ndArray.setOrder('f')
          val shape = ndArray.shape()
          val Array(row, col) = shape
          Prop.forAll(Gen.choose(0, row - 1), Gen.choose(0, row - 1), Gen.choose(0, col - 1), Gen.choose(0, col - 1)) {
            (r1, r2, c1, c2) =>
              val rowRange = if (r1 > r2) r2 to r1 else r1 to r2
              val columnRange = if (c1 > c2) c2 to c1 else c1 to c2
              val slicedByND4S = ndArray(rowRange, columnRange)
              val slicedByBreeze = prism.getOption(ndArray).map(dm => prism.reverseGet(dm(rowRange, columnRange)))
              slicedByBreeze.exists(_ == slicedByND4S)
          }
      }
    }
  }

  //This supports only real value since ND4J drops complex number support temporary.
  lazy val prism = Prism[INDArray, DenseMatrix[Double]] { ndArray =>
    //Breeze DenseMatrix doesn't support tensor nor C order matrix.
    if (ndArray.rank() > 2 || ndArray.ordering() == 'c')
      None
    else {
      val shape = ndArray.shape()
      val linear = ndArray.linearView()
      val arr = (0 until ndArray.length()).map(linear.getDouble).toArray
      Some(DenseMatrix(arr).reshape(shape(0), shape(1)))
    }
  } {
    dm =>
      val shape = Array(dm.rows, dm.cols)
      dm.toArray.mkNDArray(shape, NDOrdering.Fortran)
  }

  implicit def arbNDArray: Arbitrary[INDArray] = Arbitrary {
    for {
      rows <- Gen.choose(1, 100)
      columns <- Gen.choose(1, 100)
    } yield {
      val nd = Nd4j.rand(rows, columns)
      nd.setOrder('f')
      nd
    }
  }

} 
Example 77
Source File: ApplicativeLaws.scala    From scalaz-reactive   with Apache License 2.0 5 votes vote down vote up
package scalaz.reactive.laws
import org.scalacheck.{ Gen, Prop }
import org.scalacheck.Prop.forAll
import org.specs2.matcher.{ MatchResult, MustMatchers }
import scalaz.Applicative

class ApplicativeLaws[F[_], A](
  applicative: Applicative[F],
  aGen: Gen[A],
  faGen: Gen[F[A]],
  abGen: Gen[A => A],
  fabGen: Gen[F[A => A]],
  valueForEqGen: Gen[F[A] => A]
)(implicit
  pa: MatchResult[A] => Prop,
  pfa: MatchResult[F[A]] => Prop)
    extends MustMatchers {

  implicit class Equalable(v: F[A]) {
    def valueForEq(f: F[A] => A) = f(v)
  }

  // ap(fa)(point(_)) == fa
  def apIdentityLaw = forAll(faGen, valueForEqGen) { (fa, v) =>
    applicative
      .ap(fa)(applicative.point(identity[A](_)))
      .valueForEq(v) must beEqualTo(fa.valueForEq(v))
  }

  // ap(point(a))(point(ab)) == point(ab(a))
  def apHomomorphismLaw = forAll(aGen, abGen) { (a, ab) =>
    applicative
      .ap(applicative.point(a))(applicative.point(ab)) must
      beEqualTo(applicative.point(ab(a)))
  }

  // ap(point(a))(fab) == ap(fab)(point(_.apply(a)))
  def apInterchangeLaw = forAll(aGen, fabGen) { (a, fab) =>
    applicative.ap(applicative.point(a))(fab) must
      beEqualTo(
        applicative.ap(fab)(applicative.point((x: A => A) => x.apply(a)))
      )
  }

  //map(fa)(ab) == ap(fa)(point(ab))
  def apDerivedMapLaw = forAll(faGen, abGen, valueForEqGen) { (fa, ab, v) =>
    applicative.map(fa)(ab).valueForEq(v) must
      beEqualTo(applicative.ap(fa)(applicative.point(ab)).valueForEq(v))
  }
} 
Example 78
Source File: ScalazLawsSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.scalaz

import com.typesafe.config.ConfigValue
import org.scalacheck.{ Prop, Properties }
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.scalacheck.Checkers
import pureconfig.error.ConfigReaderFailures
import pureconfig.module.scalaz.arbitrary._
import pureconfig.module.scalaz.equal._
import pureconfig.module.scalaz.instances._
import pureconfig.{ ConfigConvert, ConfigReader, ConfigWriter }
import scalaz.scalacheck.ScalazProperties._
import scalaz.std.anyVal.intInstance

class ScalazLawsSuite extends AnyFunSuite with Checkers {
  import ScalazLawsSuite._

  test("contravariant.laws[ConfigWriter]") {
    check(properties2prop(contravariant.laws[ConfigWriter]))
  }

  test("invariantFunctor.laws[ConfigConvert]") {
    check(properties2prop(invariantFunctor.laws[ConfigConvert]))
  }

  test("monadError.laws[ConfigReader, ConfigReaderFailures]") {
    check(properties2prop(monadError.laws[ConfigReader, ConfigReaderFailures]))
  }

  test("semigroup.laws[ConfigReaderFailures]") {
    check(properties2prop(semigroup.laws[ConfigReaderFailures]))
  }

  test("semigroup.laws[ConfigValue]") {
    check(properties2prop(semigroup.laws[ConfigValue]))
  }
}

object ScalazLawsSuite {
  def properties2prop(ps: Properties): Prop = Prop.all(ps.properties.map(_._2).toSeq: _*)
} 
Example 79
Source File: SemigroupalKTests.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
package mainecoon
package laws
package discipline


import cats.{Eq, ~>}
import cats.data.Tuple2K
import mainecoon.laws.discipline.SemigroupalKTests.IsomorphismsK
import org.scalacheck.Prop._
import org.scalacheck.{Arbitrary, Prop}
import org.typelevel.discipline.Laws

trait SemigroupalKTests[F[_[_]]] extends Laws {
  def laws: SemigroupalKLaws[F]

  def semigroupalK[A[_], B[_], C[_]](implicit
                                               ArbCF: Arbitrary[F[A]],
                                               ArbCG: Arbitrary[F[B]],
                                               ArbCH: Arbitrary[F[C]],
                                               iso: IsomorphismsK[F],
                                               EqFGH: Eq[F[Tuple3K[A, B, C]#λ]]
                                              ): RuleSet = {
    new DefaultRuleSet(
      name = "SemigroupalK",
      parent = None,
      "semigroupal associativity" -> forAll((af: F[A], ag: F[B], ah: F[C]) => iso.associativity(laws.semigroupalAssociativity[A, B, C](af, ag, ah))))
  }
}


object SemigroupalKTests {
  def apply[F[_[_]]: SemigroupalK]: SemigroupalKTests[F] =
    new SemigroupalKTests[F] { def laws: SemigroupalKLaws[F] = SemigroupalKLaws[F] }

  import IsomorphismsK._

  trait IsomorphismsK[F[_[_]]] {
    def associativity[A[_], B[_], C[_]](fs: (F[ProdA_BC[A, B, C]#λ], F[ProdAB_C[A, B, C]#λ]))
                                       (implicit EqFGH: Eq[F[Tuple3K[A, B, C]#λ]]): Prop
  }

  object IsomorphismsK {
    
    type ProdA_BC[A[_], B[_], C[_]]  = { type λ[T] = Tuple2K[A, Tuple2K[B, C, ?], T] }
    type ProdAB_C[A[_], B[_], C[_]]  = { type λ[T] = Tuple2K[Tuple2K[A, B, ?], C, T] }

    implicit def invariantK[F[_[_]]](implicit F: InvariantK[F]): IsomorphismsK[F] =
      new IsomorphismsK[F] {
        def associativity[A[_], B[_], C[_]](fs: (F[ProdA_BC[A, B, C]#λ], F[ProdAB_C[A, B, C]#λ]))
                                           (implicit EqFGH: Eq[F[Tuple3K[A, B, C]#λ]]): Prop = {

          val fkA_BC_T3 = λ[ProdA_BC[A, B, C]#λ ~> Tuple3K[A, B, C]#λ ]{ case Tuple2K(a, Tuple2K(b, c)) => (a, b, c) }
          val fkAB_C_T3 = λ[ProdAB_C[A, B, C]#λ ~> Tuple3K[A, B, C]#λ ]{ case Tuple2K(Tuple2K(a, b), c) => (a, b, c) }
          val fkT3_AB_C = λ[Tuple3K[A, B, C]#λ ~> ProdAB_C[A, B, C]#λ]{ case (a, b, c) => Tuple2K(Tuple2K(a, b), c) }
          val fkT3_A_BC = λ[Tuple3K[A, B, C]#λ ~> ProdA_BC[A, B, C]#λ]{ case (a, b, c) => Tuple2K(a, Tuple2K(b, c)) }

          EqFGH.eqv(
            F.imapK[ProdA_BC[A, B, C]#λ, Tuple3K[A, B, C]#λ](fs._1)(fkA_BC_T3)(fkT3_A_BC),
            F.imapK[ProdAB_C[A, B, C]#λ, Tuple3K[A, B, C]#λ](fs._2)(fkAB_C_T3)(fkT3_AB_C)
          )
        }

      }
  }
} 
Example 80
Source File: LoggerTests.scala    From odin   with Apache License 2.0 5 votes vote down vote up
package io.odin.loggers

import cats.laws.discipline._
import cats.{Eq, Monad}
import io.odin.{Level, Logger, LoggerMessage}
import org.scalacheck.{Arbitrary, Prop}
import org.typelevel.discipline.Laws

trait LoggerTests[F[_]] extends Laws {
  def loggerLaws: LoggerLaws[F]
  def logger: Logger[F]

  def all(
      implicit
      arbMsg: Arbitrary[LoggerMessage],
      arbLvl: Arbitrary[Level],
      eqF: Eq[List[LoggerMessage]]
  ): RuleSet = new SimpleRuleSet(
    "logger",
    "checks minLevel" -> Prop.forAll((msg: LoggerMessage, level: Level) => loggerLaws.checksMinLevel(logger, msg, level)
    ),
    "log(list) <-> list.traverse(log)" -> Prop.forAll((msgs: List[LoggerMessage]) =>
      loggerLaws.batchEqualsToTraverse(logger, msgs)
    )
  )
}

object LoggerTests {
  def apply[F[_]](l: Logger[F], extract: F[_] => List[LoggerMessage])(
      implicit monad: Monad[F]
  ): LoggerTests[F] = new LoggerTests[F] {
    def loggerLaws: LoggerLaws[F] = new LoggerLaws[F] {
      val F: Monad[F] = monad
      val written: F[Unit] => List[LoggerMessage] = extract
    }

    def logger: Logger[F] = l
  }
} 
Example 81
Source File: MorpheusLiteralTests.scala    From morpheus   with Apache License 2.0 5 votes vote down vote up
package org.opencypher.morpheus.impl.values

import claimant.Claim
import org.opencypher.morpheus.impl.acceptance.ScanGraphInit
import org.opencypher.morpheus.testing.MorpheusTestSuite
import org.opencypher.okapi.api.value.CypherValue.Format._
import org.opencypher.okapi.api.value.CypherValue.{CypherMap, _}
import org.opencypher.okapi.api.value.GenCypherValue._
import org.scalacheck.Gen.const
import org.scalacheck.{Gen, Prop}
import org.scalatestplus.scalacheck.Checkers

class MorpheusLiteralTests extends MorpheusTestSuite with Checkers with ScanGraphInit {

  val supportedLiteral: Gen[CypherValue] = Gen.oneOf(
    homogeneousScalarList, propertyMap, string, boolean, integer, float, const(CypherNull)
  )

  it("round trip for supported literals") {
    check(Prop.forAll(supportedLiteral) { v: CypherValue =>
      val query = s"RETURN ${v.toCypherString} AS result"
      val result = morpheus.cypher(query).records.collect.toList
      val expected = List(CypherMap("result" -> v))
      Claim(result == expected)
    }, minSuccessful(10))
  }

  it("round trip for nodes") {
    check(Prop.forAll(node) { n: Node[CypherInteger] =>
      val graph = initGraph(s"CREATE ${n.toCypherString}")
      val query = s"MATCH (n) RETURN n"
      val result = TestNode(graph.cypher(query).records.collect.head("n").cast[Node[_]])
      Claim(result == n)
    }, minSuccessful(10))
  }

  // TODO: Diagnose and fix error "AnalysisException: Reference 'node_L __ BOOLEAN' is ambiguous, could be: node_L __ BOOLEAN, node_L __ BOOLEAN.;"
  ignore("round trip for relationships") {
    check(Prop.forAll(nodeRelNodePattern()) { p: NodeRelNodePattern[_] =>
      val graph = initGraph(p.toCreateQuery)
      val query = s"MATCH ()-[r]->() RETURN r"
      val result = TestRelationship(graph.cypher(query).records.collect.head("r").cast[Relationship[_]])
      Claim(result == p.relationship)
    }, minSuccessful(1000))
  }

} 
Example 82
Source File: DropTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped

class DropTest extends TypedDatasetSuite {
  import DropTest._

  test("fail to compile on missing value") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XMissing] = f.drop[XMissing]('j)"""
    }
  }

  test("fail to compile on different column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XDifferentColumnName] = f.drop[XDifferentColumnName]('j)"""
    }
  }

  test("fail to compile on added column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XAdded] = f.drop[XAdded]('j)"""
    }
  }

  test("remove column in the middle") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    val fNew: TypedDataset[XGood] = f.drop[XGood]

    fNew.collect().run().foreach(xg => assert(xg === XGood(1, false)))
  }

  test("drop four columns") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d5 = TypedDataset.create(X5(value, value, value, value, value) :: Nil)
      val d4 = d5.drop[X4[A, A, A, A]]
      val d3 = d4.drop[X3[A, A, A]]
      val d2 = d3.drop[X2[A, A]]
      val d1 = d2.drop[X1[A]]

      X1(value) ?= d1.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }
}

object DropTest {
  case class X(i: Int, j: Int, k: Boolean)
  case class XMissing(i: Int)
  case class XDifferentColumnName(ij: Int, k: Boolean)
  case class XAdded(i: Int, j: Int, k: Boolean, l: Int)
  case class XGood(i: Int, k: Boolean)
} 
Example 83
Source File: ExplodeTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import frameless.functions.CatalystExplodableCollection
import org.scalacheck.{Arbitrary, Prop}
import org.scalacheck.Prop.forAll
import org.scalacheck.Prop._

import scala.reflect.ClassTag


class ExplodeTests extends TypedDatasetSuite {
  test("simple explode test") {
    val ds = TypedDataset.create(Seq((1,Array(1,2))))
    ds.explode('_2): TypedDataset[(Int,Int)]
  }

  test("explode on vectors/list/seq") {
    def prop[F[X] <: Traversable[X] : CatalystExplodableCollection, A: TypedEncoder](xs: List[X1[F[A]]])(implicit arb: Arbitrary[F[A]], enc: TypedEncoder[F[A]]): Prop = {
      val tds = TypedDataset.create(xs)

      val framelessResults = tds.explode('a).collect().run().toVector
      val scalaResults = xs.flatMap(_.a).map(Tuple1(_)).toVector

      framelessResults ?= scalaResults
    }

    check(forAll(prop[Vector, Long] _))
    check(forAll(prop[Seq, Int] _))
    check(forAll(prop[Vector, Char] _))
    check(forAll(prop[Vector, String] _))
    check(forAll(prop[List, Long] _))
    check(forAll(prop[List, Int] _))
    check(forAll(prop[List, Char] _))
    check(forAll(prop[List, String] _))
  }

  test("explode on arrays") {
    def prop[A: TypedEncoder: ClassTag](xs: List[X1[Array[A]]]): Prop = {
      val tds = TypedDataset.create(xs)

      val framelessResults = tds.explode('a).collect().run().toVector
      val scalaResults = xs.flatMap(_.a).map(Tuple1(_)).toVector

      framelessResults ?= scalaResults
    }

    check(forAll(prop[Long] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 84
Source File: FramelessSyntaxTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package syntax

import org.scalacheck.Prop
import org.scalacheck.Prop._
import frameless.functions.aggregate._

class FramelessSyntaxTests extends TypedDatasetSuite {
  // Hide the implicit SparkDelay[Job] on TypedDatasetSuite to avoid ambiguous implicits
  override val sparkDelay = null

  def prop[A, B](data: Vector[X2[A, B]])(
    implicit ev: TypedEncoder[X2[A, B]]
  ): Prop = {
    val dataset = TypedDataset.create(data).dataset
    val dataframe = dataset.toDF()

    val typedDataset = dataset.typed
    val typedDatasetFromDataFrame = dataframe.unsafeTyped[X2[A, B]]

    typedDataset.collect().run().toVector ?= typedDatasetFromDataFrame.collect().run().toVector
  }

  test("dataset typed - toTyped") {
    def prop[A, B](data: Vector[X2[A, B]])(
      implicit ev: TypedEncoder[X2[A, B]]
    ): Prop = {
      val dataset = session.createDataset(data)(TypedExpressionEncoder(ev)).typed
      val dataframe = dataset.toDF()

      dataset.collect().run().toVector ?= dataframe.unsafeTyped[X2[A, B]].collect().run().toVector
    }

    check(forAll(prop[Int, String] _))
    check(forAll(prop[X1[Long], String] _))
  }

  test("frameless typed column and aggregate") {
    def prop[A: TypedEncoder](a: A, b: A): Prop = {
      val d = TypedDataset.create((a, b) :: Nil)
      (d.select(d('_1).untyped.typedColumn).collect().run ?= d.select(d('_1)).collect().run).&&(
        d.agg(first(d('_1))).collect().run() ?= d.agg(first(d('_1)).untyped.typedAggregate).collect().run()
      )
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[X1[Long]] _))
  }
} 
Example 85
Source File: ColTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import shapeless.test.illTyped

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

class ColTests extends TypedDatasetSuite {
  test("col") {
    val x4 = TypedDataset.create[X4[Int, String, Long, Boolean]](Nil)
    val t4 = TypedDataset.create[(Int, String, Long, Boolean)](Nil)

    x4.col('a)
    t4.col('_1)

    x4.col[Int]('a)
    t4.col[Int]('_1)

    illTyped("x4.col[String]('a)", "No column .* of type String in frameless.X4.*")

    x4.col('b)
    t4.col('_2)

    x4.col[String]('b)
    t4.col[String]('_2)

    illTyped("x4.col[Int]('b)", "No column .* of type Int in frameless.X4.*")

    ()
  }

  test("colMany") {
    type X2X2 = X2[X2[Int, String], X2[Long, Boolean]]
    val x2x2 = TypedDataset.create[X2X2](Nil)

    val aa: TypedColumn[X2X2, Int] = x2x2.colMany('a, 'a)
    val ab: TypedColumn[X2X2, String] = x2x2.colMany('a, 'b)
    val ba: TypedColumn[X2X2, Long] = x2x2.colMany('b, 'a)
    val bb: TypedColumn[X2X2, Boolean] = x2x2.colMany('b, 'b)

    illTyped("x2x2.colMany('a, 'c)")
    illTyped("x2x2.colMany('a, 'a, 'a)")
  }

  test("select colMany") {
    def prop[A: TypedEncoder](x: X2[X2[A, A], A]): Prop = {
      val df = TypedDataset.create(x :: Nil)
      val got = df.select(df.colMany('a, 'a)).collect().run()

      got ?= (x.a.a :: Nil)
    }

    check(prop[Int] _)
    check(prop[X2[Int, Int]] _)
    check(prop[X2[X2[Int, Int], Int]] _)
  }
} 
Example 86
Source File: LitTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import frameless.functions.lit

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

class LitTests extends TypedDatasetSuite {
  def prop[A: TypedEncoder](value: A): Prop = {
    val df: TypedDataset[Int] = TypedDataset.create(1 :: Nil)

    // filter forces whole codegen
    val elems = df.deserialized.filter((_:Int) => true).select(lit(value))
      .collect()
      .run()
      .toVector

    // otherwise it uses local relation
    val localElems = df.select(lit(value))
      .collect()
      .run()
      .toVector


    (localElems ?= Vector(value)) && (elems ?= Vector(value))
  }

  test("select(lit(...))") {
    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)

    check(prop[Option[Int]] _)
    check(prop[Option[String]] _)

    check(prop[Vector[Long]] _)
    check(prop[Vector[X1[Long]]] _)

    check(prop[Vector[String]] _)
    check(prop[Vector[X1[String]]] _)

    check(prop[X1[Int]] _)
    check(prop[X1[X1[Int]]] _)

    check(prop[Food] _)

    // doesn't work, object has to be serializable
    // check(prop[frameless.LocalDateTime] _)
  }

  test("#205: comparing literals encoded using Injection") {
    import org.apache.spark.sql.catalyst.util.DateTimeUtils
    implicit val dateAsInt: Injection[java.sql.Date, Int] =
      Injection(DateTimeUtils.fromJavaDate, DateTimeUtils.toJavaDate)

    val today = new java.sql.Date(System.currentTimeMillis)
    val data = Vector(P(42, today))
    val tds = TypedDataset.create(data)

    tds.filter(tds('d) === today).collect().run()
  }
}

final case class P(i: Int, d: java.sql.Date) 
Example 87
Source File: ColumnTypesTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops

import org.scalacheck.Prop
import org.scalacheck.Prop.forAll
import shapeless.HNil
import shapeless.::

class ColumnTypesTest extends TypedDatasetSuite {
  test("test summoning") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder, D: TypedEncoder](data: Vector[X4[A, B, C, D]]): Prop = {
      val d: TypedDataset[X4[A, B, C, D]] = TypedDataset.create(data)
      val hlist = d('a) :: d('b) :: d('c) :: d('d) :: HNil

      type TC[N] = TypedColumn[X4[A,B,C,D], N]

      type IN = TC[A] :: TC[B] :: TC[C] :: TC[D] :: HNil
      type OUT = A :: B :: C :: D :: HNil

      implicitly[ColumnTypes.Aux[X4[A,B,C,D], IN, OUT]]
      Prop.passed // successful compilation implies test correctness
    }

    check(forAll(prop[Int, String, X1[String], Boolean] _))
    check(forAll(prop[Vector[Int], Vector[Vector[String]], X1[String], Option[String]] _))
  }
} 
Example 88
Source File: MapTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops
package deserialized

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

class MapTests extends TypedDatasetSuite {
  test("map") {
    def prop[A: TypedEncoder, B: TypedEncoder](mapFunction: A => B, data: Vector[A]): Prop =
      TypedDataset.create(data).
        deserialized.
        map(mapFunction).
        collect().run().toVector =? data.map(mapFunction)

    check(forAll(prop[Int, Int] _))
    check(forAll(prop[Int, String] _))
    check(forAll(prop[String, Int] _))
    check(forAll(prop[X1[Int], X1[Int]] _))
  }
} 
Example 89
Source File: MapPartitionsTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops
package deserialized

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

class MapPartitionsTests extends TypedDatasetSuite {
  test("mapPartitions") {
    def prop[A: TypedEncoder, B: TypedEncoder](mapFunction: A => B, data: Vector[A]): Prop = {
      val lifted: Iterator[A] => Iterator[B] = _.map(mapFunction)
      TypedDataset.create(data).
        deserialized.
        mapPartitions(lifted).
        collect().run().toVector =? data.map(mapFunction)
    }

    check(forAll(prop[Int, Int] _))
    check(forAll(prop[Int, String] _))
    check(forAll(prop[String, Int] _))
  }
} 
Example 90
Source File: FilterTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops
package deserialized

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

class FilterTests extends TypedDatasetSuite {
  test("filter") {
    def prop[A: TypedEncoder](filterFunction: A => Boolean, data: Vector[A]): Prop =
      TypedDataset.create(data).
        deserialized.
        filter(filterFunction).
        collect().run().toVector =? data.filter(filterFunction)

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 91
Source File: ReduceTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops
package deserialized

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

class ReduceTests extends TypedDatasetSuite {
  def prop[A: TypedEncoder](reduceFunction: (A, A) => A)(data: Vector[A]): Prop =
    TypedDataset.create(data).
      deserialized.
      reduceOption(reduceFunction).run() =? data.reduceOption(reduceFunction)

  test("reduce Int") {
    check(forAll(prop[Int](_ + _) _))
    check(forAll(prop[Int](_ * _) _))
  }

  test("reduce String") {
    def reduce(s1: String, s2: String): String = (s1 ++ s2).sorted
    check(forAll(prop[String](reduce) _))
  }
} 
Example 92
Source File: FlatMapTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops
package deserialized

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

class FlatMapTests extends TypedDatasetSuite {
  test("flatMap") {
    def prop[A: TypedEncoder, B: TypedEncoder](flatMapFunction: A => Vector[B], data: Vector[A]): Prop =
      TypedDataset.create(data).
        deserialized.
        flatMap(flatMapFunction).
        collect().run().toVector =? data.flatMap(flatMapFunction)

    check(forAll(prop[Int, Int] _))
    check(forAll(prop[Int, String] _))
    check(forAll(prop[String, Int] _))
  }
} 
Example 93
Source File: SmartProjectTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped


case class Foo(i: Int, j: Int, x: String)
case class Bar(i: Int, x: String)
case class InvalidFooProjectionType(i: Int, x: Boolean)
case class InvalidFooProjectionName(i: Int, xerr: String)

class SmartProjectTest extends TypedDatasetSuite {
  // Lazy needed to prevent initialization anterior to the `beforeAll` hook
  lazy val dataset = TypedDataset.create(Foo(1, 2, "hi") :: Foo(2, 3, "there") :: Nil)

  test("project Foo to Bar") {
    assert(dataset.project[Bar].count().run() === 2)
  }

  test("project to InvalidFooProjection should not type check") {
    illTyped("dataset.project[InvalidFooProjectionType]")
    illTyped("dataset.project[InvalidFooProjectionName]")
  }

  test("X4 to X1,X2,X3,X4 projections") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder, D: TypedEncoder](data: Vector[X4[A, B, C, D]]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.project[X4[A, B, C, D]].collect().run().toVector ?= data
      dataset.project[X3[A, B, C]].collect().run().toVector ?= data.map(x => X3(x.a, x.b, x.c))
      dataset.project[X2[A, B]].collect().run().toVector ?= data.map(x => X2(x.a, x.b))
      dataset.project[X1[A]].collect().run().toVector ?= data.map(x => X1(x.a))
    }

    check(forAll(prop[Int, String, X1[String], Boolean] _))
    check(forAll(prop[Short, Long, String, Boolean] _))
    check(forAll(prop[Short, (Boolean, Boolean), String, (Int, Int)] _))
    check(forAll(prop[X2[String, Boolean], (Boolean, Boolean), String, Boolean] _))
    check(forAll(prop[X2[String, Boolean], X3[Boolean, Boolean, Long], String, String] _))
  }

  test("X3U to X1,X2,X3 projections") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder](data: Vector[X3U[A, B, C]]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.project[X3[A, B, C]].collect().run().toVector ?= data.map(x => X3(x.a, x.b, x.c))
      dataset.project[X2[A, B]].collect().run().toVector ?= data.map(x => X2(x.a, x.b))
      dataset.project[X1[A]].collect().run().toVector ?= data.map(x => X1(x.a))
    }

    check(forAll(prop[Int, String, X1[String]] _))
    check(forAll(prop[Short, Long, String] _))
    check(forAll(prop[Short, (Boolean, Boolean), String] _))
    check(forAll(prop[X2[String, Boolean], (Boolean, Boolean), String] _))
    check(forAll(prop[X2[String, Boolean], X3[Boolean, Boolean, Long], String] _))
  }
} 
Example 94
Source File: PivotTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops

import frameless.functions.aggregate._
import org.apache.spark.sql.{functions => sparkFunctions}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop._
import org.scalacheck.{Gen, Prop}

class PivotTest extends TypedDatasetSuite {
  def withCustomGenX4: Gen[Vector[X4[String, String, Int, Boolean]]] = {
    val kvPairGen: Gen[X4[String, String, Int, Boolean]] = for {
      a <- Gen.oneOf(Seq("1", "2", "3", "4"))
      b <- Gen.oneOf(Seq("a", "b", "c"))
      c <- arbitrary[Int]
      d <- arbitrary[Boolean]
    } yield X4(a, b, c, d)

    Gen.listOfN(4, kvPairGen).map(_.toVector)
  }

  test("X4[Boolean, String, Int, Boolean] pivot on String") {
    def prop(data: Vector[X4[String, String, Int, Boolean]]): Prop = {
      val d = TypedDataset.create(data)
      val frameless = d.groupBy(d('a)).
        pivot(d('b)).on("a", "b", "c").
        agg(sum(d('c)), first(d('d))).collect().run().toVector

      val spark = d.dataset.groupBy("a")
        .pivot("b", Seq("a", "b", "c"))
        .agg(sparkFunctions.sum("c"), sparkFunctions.first("d")).collect().toVector

      (frameless.map(_._1) ?= spark.map(x => x.getAs[String](0))).&&(
        frameless.map(_._2) ?= spark.map(x => Option(x.getAs[Long](1)))).&&(
        frameless.map(_._3) ?= spark.map(x => Option(x.getAs[Boolean](2)))).&&(
        frameless.map(_._4) ?= spark.map(x => Option(x.getAs[Long](3)))).&&(
        frameless.map(_._5) ?= spark.map(x => Option(x.getAs[Boolean](4)))).&&(
        frameless.map(_._6) ?= spark.map(x => Option(x.getAs[Long](5)))).&&(
        frameless.map(_._7) ?= spark.map(x => Option(x.getAs[Boolean](6))))
    }

    check(forAll(withCustomGenX4)(prop))
  }

  test("Pivot on Boolean") {
    val x: Seq[X3[String, Boolean, Boolean]] = Seq(X3("a", true, true), X3("a", true, true), X3("a", true, false))
    val d = TypedDataset.create(x)
    d.groupByMany(d('a)).
      pivot(d('c)).on(true, false).
      agg(count[X3[String, Boolean, Boolean]]()).
      collect().run().toVector ?= Vector(("a", Some(2L), Some(1L))) // two true one false
  }

  test("Pivot with groupBy on two columns, pivot on Long") {
    val x: Seq[X3[String, String, Long]] = Seq(X3("a", "x", 1), X3("a", "x", 1), X3("a", "c", 20))
    val d = TypedDataset.create(x)
    d.groupBy(d('a), d('b)).
      pivot(d('c)).on(1L, 20L).
      agg(count[X3[String, String, Long]]()).
      collect().run().toSet ?= Set(("a", "x", Some(2L), None), ("a", "c", None, Some(1L)))
  }

  test("Pivot with cube on two columns, pivot on Long") {
    val x: Seq[X3[String, String, Long]] = Seq(X3("a", "x", 1), X3("a", "x", 1), X3("a", "c", 20))
    val d = TypedDataset.create(x)
    d.cube(d('a), d('b))
      .pivot(d('c)).on(1L, 20L)
      .agg(count[X3[String, String, Long]]())
      .collect().run().toSet ?= Set(("a", "x", Some(2L), None), ("a", "c", None, Some(1L)))
  }

  test("Pivot with cube on Boolean") {
    val x: Seq[X3[String, Boolean, Boolean]] = Seq(X3("a", true, true), X3("a", true, true), X3("a", true, false))
    val d = TypedDataset.create(x)
    d.cube(d('a)).
      pivot(d('c)).on(true, false).
      agg(count[X3[String, Boolean, Boolean]]()).
      collect().run().toVector ?= Vector(("a", Some(2L), Some(1L)))
  }

  test("Pivot with rollup on two columns, pivot on Long") {
    val x: Seq[X3[String, String, Long]] = Seq(X3("a", "x", 1), X3("a", "x", 1), X3("a", "c", 20))
    val d = TypedDataset.create(x)
    d.rollup(d('a), d('b))
      .pivot(d('c)).on(1L, 20L)
      .agg(count[X3[String, String, Long]]())
      .collect().run().toSet ?= Set(("a", "x", Some(2L), None), ("a", "c", None, Some(1L)))
  }

  test("Pivot with rollup on Boolean") {
    val x: Seq[X3[String, Boolean, Boolean]] = Seq(X3("a", true, true), X3("a", true, true), X3("a", true, false))
    val d = TypedDataset.create(x)
    d.rollupMany(d('a)).
      pivot(d('c)).on(true, false).
      agg(count[X3[String, Boolean, Boolean]]()).
      collect().run().toVector ?= Vector(("a", Some(2L), Some(1L)))
  }
} 
Example 95
Source File: CollectTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import frameless.CollectTests.{ prop, propArray }
import org.apache.spark.sql.SparkSession
import org.scalacheck.Prop
import org.scalacheck.Prop._
import scala.reflect.ClassTag

class CollectTests extends TypedDatasetSuite {
  test("collect()") {
    check(forAll(propArray[Int] _))
    check(forAll(propArray[Long] _))
    check(forAll(propArray[Boolean] _))
    check(forAll(propArray[Float] _))
    check(forAll(propArray[String] _))
    check(forAll(propArray[Byte] _))
    check(forAll(propArray[Option[Int]] _))
    check(forAll(propArray[Option[Long]] _))
    check(forAll(propArray[Option[Double]] _))
    check(forAll(propArray[Option[Float]] _))
    check(forAll(propArray[Option[Short]] _))
    check(forAll(propArray[Option[Byte]] _))
    check(forAll(propArray[Option[Boolean]] _))
    check(forAll(propArray[Option[String]] _))

    check(forAll(prop[X2[Int, Int]] _))
    check(forAll(prop[X2[String, String]] _))
    check(forAll(prop[X2[String, Int]] _))
    check(forAll(prop[X2[Long, Int]] _))

    check(forAll(prop[X2[X2[Int, String], Boolean]] _))
    check(forAll(prop[Tuple1[Option[Int]]] _))

    check(forAll(prop[Int] _))
    check(forAll(prop[Long] _))
    check(forAll(prop[Double] _))
    check(forAll(prop[Float] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[Char] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[Boolean] _))
    check(forAll(prop[String] _))
    check(forAll(prop[SQLDate] _))
    check(forAll(prop[SQLTimestamp] _))
    check(forAll(prop[Option[Int]] _))
    check(forAll(prop[Option[Long]] _))
    check(forAll(prop[Option[Double]] _))
    check(forAll(prop[Option[Float]] _))
    check(forAll(prop[Option[Short]] _))
    check(forAll(prop[Option[Byte]] _))
    check(forAll(prop[Option[Boolean]] _))
    check(forAll(prop[Option[String]] _))
    check(forAll(prop[Option[SQLDate]] _))
    check(forAll(prop[Option[SQLTimestamp]] _))

    check(forAll(prop[Vector[Int]] _))
    check(forAll(prop[List[Int]] _))
    check(forAll(prop[Seq[Int]] _))
    check(forAll(prop[Vector[Char]] _))
    check(forAll(prop[List[Char]] _))
    check(forAll(prop[Seq[Char]] _))
    check(forAll(prop[Seq[Seq[Seq[Char]]]] _))
    check(forAll(prop[Seq[Option[String]]] _))
    check(forAll(prop[Seq[Map[String, Long]]] _))
    check(forAll(prop[Seq[Map[String, X2[Option[Long], Vector[Boolean]]]]] _))
    check(forAll(prop[Option[Int]] _))
    check(forAll(prop[Vector[X2[Int, Int]]] _))

    check(forAll(prop[X1[Vector[Food]]] _))
    check(forAll(prop[X1[Vector[X1[Food]]]] _))
    check(forAll(prop[X1[Vector[X1[Int]]]] _))

    // TODO this doesn't work, and never worked...
    // check(forAll(prop[X1[Option[X1[Option[Int]]]]] _))

    check(forAll(prop[UdtEncodedClass] _))
    check(forAll(prop[Option[UdtEncodedClass]] _))
    check(forAll(prop[X1[UdtEncodedClass]] _))
    check(forAll(prop[X2[Int, UdtEncodedClass]] _))
    check(forAll(prop[(Long, UdtEncodedClass)] _))
  }
}

object CollectTests {
  import frameless.syntax._

  def prop[A: TypedEncoder : ClassTag](data: Vector[A])(implicit c: SparkSession): Prop =
    TypedDataset.create(data).collect().run().toVector ?= data

  def propArray[A: TypedEncoder : ClassTag](data: Vector[X1[Array[A]]])(implicit c: SparkSession): Prop =
    Prop(TypedDataset.create(data).collect().run().toVector.zip(data).forall {
      case (X1(l), X1(r)) => l.sameElements(r)
    })
} 
Example 96
Source File: AsTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class AsTests extends TypedDatasetSuite {
  test("as[X2[A, B]]") {
    def prop[A, B](data: Vector[(A, B)])(
      implicit
      eab: TypedEncoder[(A, B)],
      ex2: TypedEncoder[X2[A, B]]
    ): Prop = {
      val dataset = TypedDataset.create(data)

      val dataset2 = dataset.as[X2[A,B]]().collect().run().toVector
      val data2 = data.map { case (a, b) => X2(a, b) }

      dataset2 ?= data2
    }

    check(forAll(prop[Int, Int] _))
    check(forAll(prop[String, String] _))
    check(forAll(prop[String, Int] _))
    check(forAll(prop[Long, Int] _))
    check(forAll(prop[Seq[Seq[Option[Seq[Long]]]], Seq[Int]] _))
    check(forAll(prop[Seq[Option[Seq[String]]], Seq[Int]] _))
  }

  test("as[X2[X2[A, B], C]") {
    def prop[A, B, C](data: Vector[(A, B, C)])(
      implicit
      eab: TypedEncoder[((A, B), C)],
      ex2: TypedEncoder[X2[X2[A, B], C]]
    ): Prop = {
      val data2 = data.map {
        case (a, b, c) => ((a, b), c)
      }
      val dataset = TypedDataset.create(data2)

      val dataset2 = dataset.as[X2[X2[A,B], C]]().collect().run().toVector
      val data3 = data2.map { case ((a, b), c) => X2(X2(a, b), c) }

      dataset2 ?= data3
    }

    check(forAll(prop[String, Int, Int] _))
    check(forAll(prop[String, Int, String] _))
    check(forAll(prop[String, String, Int] _))
    check(forAll(prop[Long, Int, String] _))
    check(forAll(prop[Seq[Seq[Option[Seq[Long]]]], Seq[Int], Option[Seq[Option[Int]]]] _))
    check(forAll(prop[Seq[Option[Seq[String]]], Seq[Int], Seq[Option[String]]] _))
  }
} 
Example 97
Source File: TypedDatasetSuite.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{SQLContext, SparkSession}
import org.scalactic.anyvals.PosZInt
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.scalacheck.Checkers
import org.scalacheck.Prop
import org.scalacheck.Prop._
import scala.util.{Properties, Try}
import org.scalatest.funsuite.AnyFunSuite

trait SparkTesting { self: BeforeAndAfterAll =>

  val appID: String = new java.util.Date().toString + math.floor(math.random * 10E4).toLong.toString

  val conf: SparkConf = new SparkConf()
    .setMaster("local[*]")
    .setAppName("test")
    .set("spark.ui.enabled", "false")
    .set("spark.app.id", appID)

  private var s: SparkSession = _

  implicit def session: SparkSession = s
  implicit def sc: SparkContext = session.sparkContext
  implicit def sqlContext: SQLContext = session.sqlContext

  override def beforeAll(): Unit = {
    assert(s == null)
    s = SparkSession.builder().config(conf).getOrCreate()
  }

  override def afterAll(): Unit = {
    if (s != null) {
      s.stop()
      s = null
    }
  }
}


class TypedDatasetSuite extends AnyFunSuite with Checkers with BeforeAndAfterAll with SparkTesting {
  // Limit size of generated collections and number of checks to avoid OutOfMemoryError
  implicit override val generatorDrivenConfig: PropertyCheckConfiguration = {
    def getPosZInt(name: String, default: PosZInt) = Properties.envOrNone(s"FRAMELESS_GEN_${name}")
      .flatMap(s => Try(s.toInt).toOption)
      .flatMap(PosZInt.from)
      .getOrElse(default)
    PropertyCheckConfiguration(
      sizeRange = getPosZInt("SIZE_RANGE", PosZInt(20)),
      minSize = getPosZInt("MIN_SIZE", PosZInt(0))
    )
  }

  implicit val sparkDelay: SparkDelay[Job] = Job.framelessSparkDelayForJob

  def approximatelyEqual[A](a: A, b: A)(implicit numeric: Numeric[A]): Prop = {
    val da = numeric.toDouble(a)
    val db = numeric.toDouble(b)
    val epsilon = 1E-6
    // Spark has a weird behaviour concerning expressions that should return Inf
    // Most of the time they return NaN instead, for instance stddev of Seq(-7.827553978923477E227, -5.009124275715786E153)
    if((da.isNaN || da.isInfinity) && (db.isNaN || db.isInfinity)) proved
    else if (
      (da - db).abs < epsilon ||
      (da - db).abs < da.abs / 100)
        proved
    else falsified :| s"Expected $a but got $b, which is more than 1% off and greater than epsilon = $epsilon."
  }
} 
Example 98
Source File: WithColumnTupledTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class WithColumnTupledTest extends TypedDatasetSuite {
  test("append five columns") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d = TypedDataset.create(X1(value) :: Nil)
      val d1 = d.withColumnTupled(d('a))
      val d2 = d1.withColumnTupled(d1('_1))
      val d3 = d2.withColumnTupled(d2('_2))
      val d4 = d3.withColumnTupled(d3('_3))
      val d5 = d4.withColumnTupled(d4('_4))

      (value, value, value, value, value, value) ?= d5.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }
} 
Example 99
Source File: WithColumnTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped

class WithColumnTest extends TypedDatasetSuite {
  import WithColumnTest._

  test("fail to compile on missing value") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XMissing] = f.withColumn[XMissing](f('j) === 10)"""
    }
  }

  test("fail to compile on different column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XDifferentColumnName] = f.withColumn[XDifferentColumnName](f('j) === 10)"""
    }
  }

  test("fail to compile on added column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XAdded] = f.withColumn[XAdded](f('j) === 10)"""
    }
  }

  test("fail to compile on wrong typed column") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XWrongType] = f.withColumn[XWrongType](f('j) === 10)"""
    }
  }

  test("append four columns") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d = TypedDataset.create(X1(value) :: Nil)
      val d1 = d.withColumn[X2[A, A]](d('a))
      val d2 = d1.withColumn[X3[A, A, A]](d1('b))
      val d3 = d2.withColumn[X4[A, A, A, A]](d2('c))
      val d4 = d3.withColumn[X5[A, A, A, A, A]](d3('d))

      X5(value, value, value, value, value) ?= d4.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }

  test("update in place") {
    def prop[A : TypedEncoder](startValue: A, replaceValue: A): Prop = {
      val d = TypedDataset.create(X2(startValue, replaceValue) :: Nil)

      val X2(a, b) = d.withColumnReplaced('a, d('b))
        .collect()
        .run()
        .head

      a ?= b
    }
    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }
}

object WithColumnTest {
  case class X(i: Int, j: Int)
  case class XMissing(i: Int, k: Boolean)
  case class XDifferentColumnName(i: Int, ji: Int, k: Boolean)
  case class XAdded(i: Int, j: Int, k: Boolean, l: Int)
  case class XWrongType(i: Int, j: Int, k: Int)
  case class XGood(i: Int, j: Int, k: Boolean)
} 
Example 100
Source File: SchemaTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import frameless.functions.aggregate._
import frameless.functions._
import org.scalacheck.Prop
import org.scalacheck.Prop._
import org.scalatest.matchers.should.Matchers

class SchemaTests extends TypedDatasetSuite with Matchers {

  def prop[A](dataset: TypedDataset[A]): Prop = {
    val schema = dataset.dataset.schema

    Prop.all(
      dataset.schema ?= schema,
      TypedExpressionEncoder.targetStructType(dataset.encoder) ?= schema
    )
  }

  test("schema of groupBy('a).agg(sum('b))") {
    val df0 = TypedDataset.create(X2(1L, 1L) :: Nil)
    val _a = df0.col('a)
    val _b = df0.col('b)

    val df = df0.groupBy(_a).agg(sum(_b))

    check(prop(df))
  }

  test("schema of select(lit(1L))") {
    val df0 = TypedDataset.create("test" :: Nil)
    val df = df0.select(lit(1L))

    check(prop(df))
  }

  test("schema of select(lit(1L), lit(2L)).as[X2[Long, Long]]") {
    val df0 = TypedDataset.create("test" :: Nil)
    val df = df0.select(lit(1L), lit(2L)).as[X2[Long, Long]]

    check(prop(df))
  }
} 
Example 101
Source File: FlattenTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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


class FlattenTests extends TypedDatasetSuite {
  test("simple flatten test") {
    val ds: TypedDataset[(Int,Option[Int])] = TypedDataset.create(Seq((1,Option(1))))
    ds.flattenOption('_2): TypedDataset[(Int,Int)]
  }

  test("different Optional types") {
    def prop[A: TypedEncoder](xs: List[X1[Option[A]]]): Prop = {
      val tds: TypedDataset[X1[Option[A]]] = TypedDataset.create(xs)

      val framelessResults: Seq[Tuple1[A]] = tds.flattenOption('a).collect().run().toVector
      val scalaResults = xs.flatMap(_.a).map(Tuple1(_)).toVector

      framelessResults ?= scalaResults
    }

    check(forAll(prop[Long] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Char] _))
    check(forAll(prop[String] _))
  }
} 
Example 102
Source File: DropTupledTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class DropTupledTest extends TypedDatasetSuite {
  test("drop five columns") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d5 = TypedDataset.create(X5(value, value, value, value, value) :: Nil)
      val d4 = d5.dropTupled('a) //drops first column
      val d3 = d4.dropTupled('_4) //drops last column
      val d2 = d3.dropTupled('_2) //drops middle column
      val d1 = d2.dropTupled('_2)

      Tuple1(value) ?= d1.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }

  test("drop first column") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d3 = TypedDataset.create(X3(value, value, value) :: Nil)
      val d2 = d3.dropTupled('a)

      (value, value) ?= d2.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }

  test("drop middle column") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d3 = TypedDataset.create(X3(value, value, value) :: Nil)
      val d2 = d3.dropTupled('b)

      (value, value) ?= d2.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }

  test("drop last column") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d3 = TypedDataset.create(X3(value, value, value) :: Nil)
      val d2 = d3.dropTupled('c)

      (value, value) ?= d2.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }
} 
Example 103
Source File: ToJSONTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class ToJSONTests extends TypedDatasetSuite {
  test("toJSON") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.toJSON.collect().run() ?= dataset.dataset.toJSON.collect()
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 104
Source File: CheckpointTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop.{forAll, _}


class CheckpointTests extends TypedDatasetSuite {
  test("checkpoint") {
    def prop[A: TypedEncoder](data: Vector[A], isEager: Boolean): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.sparkSession.sparkContext.setCheckpointDir(TEST_OUTPUT_DIR)

      dataset.checkpoint(isEager).run().queryExecution.toString() =?
        dataset.dataset.checkpoint(isEager).queryExecution.toString()
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 105
Source File: IsLocalTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class IsLocalTests extends TypedDatasetSuite {
  test("isLocal") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.isLocal ?= dataset.dataset.isLocal
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 106
Source File: SparkSessionTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class SparkSessionTests extends TypedDatasetSuite {
  test("sparkSession") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop = {
      val dataset = TypedDataset.create[A](data)

      dataset.sparkSession =? dataset.dataset.sparkSession
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 107
Source File: UnionTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped

class UnionTests extends TypedDatasetSuite {

  test("fail to compile on not aligned schema") {
    val dataset1 = TypedDataset.create(Foo(1, 1) :: Nil)
    val dataset2 = TypedDataset.create(Wrong(1, 1, 1) :: Nil)

    illTyped {
      """val fNew = dataset1 union dataset2 """
    }
  }

  test("Union for simple data types") {
    def prop[A: TypedEncoder](data1: Vector[A], data2: Vector[A]): Prop = {
      val dataset1 = TypedDataset.create(data1)
      val dataset2 = TypedDataset.create(data2)
      val datasetUnion = dataset1.union(dataset2).collect().run().toVector
      val dataUnion = data1.union(data2)

      datasetUnion ?= dataUnion
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }

  test("Align fields for case classes") {
    def prop[A: TypedEncoder, B: TypedEncoder](data1: Vector[(A, B)], data2: Vector[(A, B)]): Prop = {

      val dataset1 = TypedDataset.create(data1.map((Foo.apply[A, B] _).tupled))
      val dataset2 = TypedDataset.create(data2.map { case (a, b) => Bar[A, B](b, a) })
      val datasetUnion = dataset1.union(dataset2).collect().run().map(foo => (foo.x, foo.y)).toVector
      val dataUnion = data1 union data2

      datasetUnion ?= dataUnion
    }

    check(forAll(prop[Int, String] _))
    check(forAll(prop[String, X1[Option[Long]]] _))
  }

  test("Align fields for different number of columns") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder](data1: Vector[(A, B, C)], data2: Vector[(A, B)]): Prop = {

      val dataset1 = TypedDataset.create(data2.map((Foo.apply[A, B] _).tupled))
      val dataset2 = TypedDataset.create(data1.map { case (a, b, c) => Baz[A, B, C](c, b, a) })
      val datasetUnion: Seq[(A, B)] = dataset1.union(dataset2).collect().run().map(foo => (foo.x, foo.y)).toVector
      val dataUnion = data2 union data1.map { case (a, b, _) => (a, b) }

      datasetUnion ?= dataUnion
    }

    check(forAll(prop[Option[Int], String, Array[Long]] _))
    check(forAll(prop[String, X1[Option[Int]], X2[String, Array[Int]]] _))
  }
}

final case class Foo[A, B](x: A, y: B)
final case class Bar[A, B](y: B, x: A)
final case class Baz[A, B, C](z: C, y: B, x: A)
final case class Wrong[A, B, C](a: A, b: B, c: C) 
Example 108
Source File: ToLocalIteratorTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import scala.collection.JavaConverters._
import org.scalatest.matchers.should.Matchers

class ToLocalIteratorTests extends TypedDatasetSuite with Matchers {
  test("toLocalIterator") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.toLocalIterator().run().asScala.toIterator sameElements dataset.dataset.toLocalIterator().asScala.toIterator
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 109
Source File: QueryExecutionTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop.{forAll, _}

class QueryExecutionTests extends TypedDatasetSuite {
  test("queryExecution") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop = {
      val dataset = TypedDataset.create[A](data)

      dataset.queryExecution =? dataset.dataset.queryExecution
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 110
Source File: WriteTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import java.util.UUID

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

class WriteTests extends TypedDatasetSuite {

  val genNested = for {
    d <- Arbitrary.arbitrary[Double]
    as <- Arbitrary.arbitrary[String]
  } yield Nested(d, as)

  val genOptionFieldsOnly = for {
    o1 <- Gen.option(Arbitrary.arbitrary[Int])
    o2 <- Gen.option(genNested)
  } yield OptionFieldsOnly(o1, o2)

  val genWriteExample = for {
    i <- Arbitrary.arbitrary[Int]
    s <- Arbitrary.arbitrary[String]
    on <- Gen.option(genNested)
    ooo <- Gen.option(genOptionFieldsOnly)
  } yield WriteExample(i, s, on, ooo)

  test("write csv") {
    def prop[A: TypedEncoder](data: List[A]): Prop = {
      val filePath = s"$TEST_OUTPUT_DIR/${UUID.randomUUID()}"
      val input = TypedDataset.create(data)
      input.write.csv(filePath)

      val dataset = TypedDataset.createUnsafe(sqlContext.read.schema(input.schema).csv(filePath))

      dataset.collect().run().groupBy(identity) ?= input.collect().run().groupBy(identity)
    }

    check(forAll(Gen.listOf(Gen.alphaNumStr.suchThat(_.nonEmpty)))(prop[String]))
    check(forAll(prop[Int] _))
  }

  test("write parquet") {
    def prop[A: TypedEncoder](data: List[A]): Prop = {
      val filePath = s"$TEST_OUTPUT_DIR/${UUID.randomUUID()}"
      val input = TypedDataset.create(data)
      input.write.parquet(filePath)

      val dataset = TypedDataset.createUnsafe(sqlContext.read.schema(input.schema).parquet(filePath))

      dataset.collect().run().groupBy(identity) ?= input.collect().run().groupBy(identity)
    }

    check(forAll(Gen.listOf(genWriteExample))(prop[WriteExample]))
  }
}

case class Nested(i: Double, v: String)
case class OptionFieldsOnly(o1: Option[Int], o2: Option[Nested])
case class WriteExample(i: Int, s: String, on: Option[Nested], ooo: Option[OptionFieldsOnly]) 
Example 111
Source File: FirstTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import org.scalatest.matchers.should.Matchers

class FirstTests extends TypedDatasetSuite with Matchers {
  test("first") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop =
      TypedDataset.create(data).firstOption().run() =? data.headOption

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }

  test("first on empty dataset should return None") {
    TypedDataset.create(Vector[Int]()).firstOption().run() shouldBe None
  }
} 
Example 112
Source File: IsStreamingTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class IsStreamingTests extends TypedDatasetSuite {
  test("isStreaming") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.isStreaming ?= dataset.dataset.isStreaming
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 113
Source File: LimitTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class LimitTests extends TypedDatasetSuite {
  test("limit") {
    def prop[A: TypedEncoder](data: Vector[A], n: Int): Prop = (n >= 0) ==> {
      val dataset = TypedDataset.create(data).limit(n).collect().run()

      Prop.all(
        dataset.length ?= Math.min(data.length, n),
        dataset.forall(data.contains)
      )
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 114
Source File: HeadTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless.forward

import frameless.{TypedDataset, TypedDatasetSuite, TypedEncoder, TypedExpressionEncoder, X1}
import org.apache.spark.sql.SparkSession
import org.scalacheck.Prop
import org.scalacheck.Prop._

import scala.reflect.ClassTag
import org.scalatest.matchers.should.Matchers

class HeadTests extends TypedDatasetSuite with Matchers {
  def propArray[A: TypedEncoder : ClassTag : Ordering](data: Vector[X1[A]])(implicit c: SparkSession): Prop = {
    import c.implicits._
    if(data.nonEmpty) {
      val tds = TypedDataset.
        create(c.createDataset(data)(
          TypedExpressionEncoder.apply[X1[A]]
        ).orderBy($"a".desc))
        (tds.headOption().run().get ?= data.max).
        &&(tds.head(1).run().head ?= data.max).
        &&(tds.head(4).run().toVector ?=
          data.sortBy(_.a)(implicitly[Ordering[A]].reverse).take(4))
    } else Prop.passed
  }

  test("headOption(), head(1), and head(4)") {
    check(propArray[Int] _)
    check(propArray[Char] _)
    check(propArray[String] _)
  }
} 
Example 115
Source File: InputFilesTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import java.util.UUID

import org.apache.spark.sql.SparkSession
import org.scalacheck.Prop
import org.scalacheck.Prop._
import org.scalatest.matchers.should.Matchers

class InputFilesTests extends TypedDatasetSuite with Matchers {
  test("inputFiles") {

    def propText[A: TypedEncoder](data: Vector[A]): Prop = {
      val filePath = s"$TEST_OUTPUT_DIR/${UUID.randomUUID()}.txt"

      TypedDataset.create(data).dataset.write.text(filePath)
      val dataset = TypedDataset.create(implicitly[SparkSession].sparkContext.textFile(filePath))

      dataset.inputFiles sameElements dataset.dataset.inputFiles
    }

    def propCsv[A: TypedEncoder](data: Vector[A]): Prop = {
      val filePath = s"$TEST_OUTPUT_DIR/${UUID.randomUUID()}.csv"
      val inputDataset = TypedDataset.create(data)
      inputDataset.dataset.write.csv(filePath)

      val dataset = TypedDataset.createUnsafe(
        implicitly[SparkSession].sqlContext.read.schema(inputDataset.schema).csv(filePath))

      dataset.inputFiles sameElements dataset.dataset.inputFiles
    }

    def propJson[A: TypedEncoder](data: Vector[A]): Prop = {
      val filePath = s"$TEST_OUTPUT_DIR/${UUID.randomUUID()}.json"
      val inputDataset = TypedDataset.create(data)
      inputDataset.dataset.write.json(filePath)

      val dataset = TypedDataset.createUnsafe(
        implicitly[SparkSession].sqlContext.read.schema(inputDataset.schema).json(filePath))

      dataset.inputFiles sameElements dataset.dataset.inputFiles
    }

    check(forAll(propText[String] _))
    check(forAll(propCsv[String] _))
    check(forAll(propJson[String] _))
  }
} 
Example 116
Source File: ColumnsTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class ColumnsTests extends TypedDatasetSuite {
  test("columns") {
    def prop(i: Int, s: String, b: Boolean, l: Long, d: Double, by: Byte): Prop = {
      val x1 = X1(i) :: Nil
      val x2 = X2(i, s) :: Nil
      val x3 = X3(i, s, b) :: Nil
      val x4 = X4(i, s, b, l) :: Nil
      val x5 = X5(i, s, b, l, d) :: Nil
      val x6 = X6(i, s, b, l, d, by) :: Nil

      val datasets = Seq(TypedDataset.create(x1), TypedDataset.create(x2),
        TypedDataset.create(x3), TypedDataset.create(x4),
        TypedDataset.create(x5), TypedDataset.create(x6))

      Prop.all(datasets.flatMap { dataset =>
        val columns = dataset.dataset.columns
        dataset.columns.map(col =>
          Prop.propBoolean(columns contains col)
        )
      }: _*)
    }

    check(forAll(prop _))
  }
} 
Example 117
Source File: ExceptTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

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

class ExceptTests extends TypedDatasetSuite {
  test("except") {
    def prop[A: TypedEncoder](data1: Set[A], data2: Set[A]): Prop = {
      val dataset1 = TypedDataset.create(data1.toSeq)
      val dataset2 = TypedDataset.create(data2.toSeq)
      val datasetSubtract = dataset1.except(dataset2).collect().run().toVector
      val dataSubtract = data1.diff(data2)

      Prop.all(
        datasetSubtract.size ?= dataSubtract.size,
        datasetSubtract.toSet ?= dataSubtract
      )
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 118
Source File: IntersectTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import math.Ordering

class IntersectTests extends TypedDatasetSuite {
  test("intersect") {
    def prop[A: TypedEncoder : Ordering](data1: Vector[A], data2: Vector[A]): Prop = {
      val dataset1 = TypedDataset.create(data1)
      val dataset2 = TypedDataset.create(data2)
      val datasetIntersect = dataset1.intersect(dataset2).collect().run().toVector

      // Vector `intersect` is the multiset intersection, while Spark throws away duplicates.
      val dataIntersect = data1.intersect(data2).distinct

      // Comparison done with `.sorted` because order is not preserved by Spark for this operation.
      datasetIntersect.sorted ?= dataIntersect.distinct.sorted
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 119
Source File: TakeTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import scala.reflect.ClassTag

class TakeTests extends TypedDatasetSuite {
  test("take") {
    def prop[A: TypedEncoder](n: Int, data: Vector[A]): Prop =
      (n >= 0) ==> (TypedDataset.create(data).take(n).run().toVector =? data.take(n))

    def propArray[A: TypedEncoder: ClassTag](n: Int, data: Vector[X1[Array[A]]]): Prop =
      (n >= 0) ==> {
        Prop {
          TypedDataset.create(data).take(n).run().toVector.zip(data.take(n)).forall {
            case (X1(l), X1(r)) => l sameElements r
          }
        }
      }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
    check(forAll(propArray[Int] _))
    check(forAll(propArray[String] _))
    check(forAll(propArray[Byte] _))
  }
} 
Example 120
Source File: SQLContextTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop.{forAll, _}

class SQLContextTests extends TypedDatasetSuite {
  test("sqlContext") {
    def prop[A: TypedEncoder](data: Vector[A]): Prop = {
      val dataset = TypedDataset.create[A](data)

      dataset.sqlContext =? dataset.dataset.sqlContext
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 121
Source File: ForeachTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package forward

import org.apache.spark.util.CollectionAccumulator

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

import scala.collection.JavaConverters._

class ForeachTests extends TypedDatasetSuite {
  test("foreach") {
    def prop[A: Ordering: TypedEncoder](data: Vector[A]): Prop = {
      val accu = new CollectionAccumulator[A]()
      sc.register(accu)

      TypedDataset.create(data).foreach(accu.add).run()

      accu.value.asScala.toVector.sorted ?= data.sorted
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }

  test("foreachPartition") {
    def prop[A: Ordering: TypedEncoder](data: Vector[A]): Prop = {
      val accu = new CollectionAccumulator[A]()
      sc.register(accu)

      TypedDataset.create(data).foreachPartition(_.foreach(accu.add)).run()

      accu.value.asScala.toVector.sorted ?= data.sorted
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }
} 
Example 122
Source File: CirceConfigLaws.scala    From circe-config   with Apache License 2.0 5 votes vote down vote up
package io.circe.config

import cats.instances.either._
import cats.laws._
import cats.laws.discipline._
import io.circe.{Decoder, Json, Parser, ParsingFailure}
import io.circe.testing.ParserTests
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.scalacheck.Checkers
import org.scalacheck.{Arbitrary, Prop}
import org.typelevel.discipline.Laws
import com.typesafe.config.{parser => _, _}

class CirceConfigLaws extends AnyFlatSpec {

  implicit val arbitraryConfigJson: Arbitrary[Json] = Arbitrary {
    def normalize(json: Json): Json =
      json.mapObject(_.filterKeys(_.nonEmpty).mapValues(normalize)).mapArray(_.map(normalize)).mapNumber { number =>
        // Lower the precision to the types used internally by
        // Lightbend Config to ensure that numbers are representable.
        val double: java.lang.Double = number.toDouble
        val long: java.lang.Long = double.toLong

        val json =
          if (double.isInfinite)
            // While +/+Infinity can be represented, it cannot be round-tripped.
            Json.fromInt(42)
          else if (long == double)
            // Emulate Lightbend Config's internal cast:
            // https://github.com/lightbend/config/blob/v1.3.4/config/src/main/java/com/typesafe/config/impl/ConfigNumber.java#L96-L104
            Json.fromLong(long)
          else
            Json.fromDouble(double).get

        json.asNumber.get
      }

    for (jsonObject <- io.circe.testing.instances.arbitraryJsonObject.arbitrary)
      yield normalize(Json.fromJsonObject(jsonObject))
  }

  def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach {
    case ((id, prop), 0) => name should s"obey $id" in Checkers.check(prop)
    case ((id, prop), _) => it should s"obey $id" in Checkers.check(prop)
  }

  checkLaws("Parser", ParserTests(parser).fromString)
  checkLaws(
    "Parser",
    ParserTests(parser).fromFunction[Config]("fromConfig")(
      ConfigFactory.parseString,
      _.parse,
      _.decode[Json],
      _.decodeAccumulating[Json]
    )
  )
  checkLaws("Printer", PrinterTests(parser).fromJson)
  checkLaws("Codec", CodecTests[Config](syntax.configDecoder, parser.parse).fromFunction("fromConfig"))
}

case class PrinterTests(parser: Parser) extends Laws {
  def fromJson(implicit A: Arbitrary[Json]): RuleSet =
    new DefaultRuleSet(
      name = "printer",
      parent = None,
      "roundTrip" -> Prop.forAll { (json: Json) =>
        parser.parse(printer.print(json)) <-> Right(json)
      }
    )
}

case class CodecTests[A](decoder: Decoder[A], parse: A => Either[ParsingFailure, Json]) extends Laws {
  def fromFunction(name: String)(implicit arbitraryJson: Arbitrary[Json]): RuleSet =
    new DefaultRuleSet(
      name = s"codec[$name]",
      parent = None,
      "decodingRoundTrip" -> Prop.forAll { (json: Json) =>
        decoder.decodeJson(json).flatMap(parse) <-> Right(json)
      }
    )
} 
Example 123
Source File: BloomFilterSpec.scala    From bloom-filter-scala   with MIT License 5 votes vote down vote up
package tests.bloomfilter.mutable

import bloomfilter.CanGenerateHashFrom
import bloomfilter.mutable.BloomFilter
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.Test.Parameters
import org.scalacheck.commands.Commands
import org.scalacheck.{Arbitrary, Gen, Prop, Properties}

class BloomFilterSpec extends Properties("BloomFilter") {

  property("for Long") = new BloomFilterCommands[Long].property()
  property("for String") = new BloomFilterCommands[String].property()
  property("for Array[Byte]") = new BloomFilterCommands[Array[Byte]].property()


  override def overrideParameters(p: Parameters): Parameters = {
    super.overrideParameters(p).withMinSuccessfulTests(100)
  }

  class BloomFilterCommands[T: Arbitrary](implicit canGenerateHash: CanGenerateHashFrom[T]) extends Commands {
    type Sut = BloomFilter[T]

    case class State(expectedItems: Long, addedItems: Long)

    override def canCreateNewSut(
        newState: State,
        initSuts: Traversable[State],
        runningSuts: Traversable[Sut]): Boolean = {
      initSuts.isEmpty && runningSuts.isEmpty ||
          newState.addedItems > newState.expectedItems ||
          newState.addedItems > 100
    }

    override def destroySut(sut: Sut): Unit =
      sut.dispose()

    override def genInitialState: Gen[State] =
      Gen.chooseNum[Long](1, Int.MaxValue).map(State(_, 0))

    override def newSut(state: State): Sut =
      BloomFilter[T](state.expectedItems, 0.01)

    def initialPreCondition(state: State): Boolean = true

    def genCommand(state: State): Gen[Command] =
      for {
        item <- Arbitrary.arbitrary[T]
      } yield commandSequence(AddItem(item), CheckItem(item))

    case class AddItem(item: T) extends UnitCommand {
      def run(sut: Sut): Unit = sut.synchronized(sut.add(item))
      def nextState(state: State) = state.copy(addedItems = state.addedItems + 1)
      def preCondition(state: State) = true
      def postCondition(state: State, success: Boolean) = success
    }

    case class CheckItem(item: T) extends SuccessCommand {
      type Result = Boolean
      def run(sut: Sut): Boolean = sut.synchronized(sut.mightContain(item))
      def nextState(state: State) = state
      def preCondition(state: State) = true
      def postCondition(state: State, result: Boolean): Prop = result
    }

  }

  private val elemsToAddGen = for {
    numberOfElemsToAdd <- Gen.chooseNum[Int](1, 1000)
    elemsToAdd <- Gen.listOfN(numberOfElemsToAdd, arbitrary[Long])
  } yield elemsToAdd

  // TODO fix elemsToAddGen.filter() below, why Gen.listOfN above generates empty lists?
  property("approximateElementCount") = forAll(elemsToAddGen.filter(x => x.size > 10 && x.toSet.size > 10)) { elemsToAdd: List[Long] =>
    val bf = BloomFilter[Long](elemsToAdd.size * 10, 0.0001)
    elemsToAdd.foreach(bf.add)
    val numberOfUnique = elemsToAdd.toSet.size
    math.abs(bf.approximateElementCount() - numberOfUnique) < numberOfUnique * 0.1
  }

} 
Example 124
Source File: BloomFiltersSpec.scala    From bloom-filter-scala   with MIT License 5 votes vote down vote up
package tests.bloomfilter.mutable

import bloomfilter.CanGenerateHashFrom
import bloomfilter.mutable.BloomFilter
import org.scalacheck.Test.Parameters
import org.scalacheck.commands.Commands
import org.scalacheck.{Arbitrary, Gen, Prop, Properties}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll

class BloomFiltersSpec extends Properties("BloomFilters") {

  val maxNumElems = 10

  def genListOfMaxTenElems[A](implicit aGen: Gen[A]): Gen[List[A]] =
    Gen.posNum[Int] map (_ % maxNumElems) flatMap (i => Gen.listOfN(i, aGen))

  property("union") =
    forAll(genListOfMaxTenElems(arbitrary[Long]), genListOfMaxTenElems(arbitrary[Long])) {
      (leftElements: List[Long], rightElements: List[Long]) =>
        val leftBloomFilter = BloomFilter[Long](maxNumElems, 0.01)
        leftElements foreach leftBloomFilter.add
        val rightBloomFilter = BloomFilter[Long](maxNumElems, 0.01)
        rightElements foreach rightBloomFilter.add
        val unionBloomFilter = leftBloomFilter union rightBloomFilter
        val result = (leftElements ++ rightElements) forall unionBloomFilter.mightContain
        leftBloomFilter.dispose()
        rightBloomFilter.dispose()
        unionBloomFilter.dispose()
        result
    }

  property("intersect") =
    forAll(genListOfMaxTenElems(arbitrary[Long]), genListOfMaxTenElems(arbitrary[Long])) {
      (leftElements: List[Long], rightElements: List[Long]) =>
        val leftBloomFilter = BloomFilter[Long](maxNumElems, 0.01)
        leftElements foreach leftBloomFilter.add
        val rightBloomFilter = BloomFilter[Long](maxNumElems, 0.01)
        rightElements foreach rightBloomFilter.add
        val unionBloomFilter = leftBloomFilter intersect rightBloomFilter
        val intersectElems = leftElements.toSet intersect rightElements.toSet
        val result = intersectElems forall unionBloomFilter.mightContain
        leftBloomFilter.dispose()
        rightBloomFilter.dispose()
        unionBloomFilter.dispose()
        result
    }
} 
Example 125
Source File: XGBoostFeatureBuilderSpec.scala    From featran   with Apache License 2.0 5 votes vote down vote up
package com.spotify.featran.xgboost

import com.spotify.featran.{FeatureBuilder, SerializableUtils, SparseArray}
import ml.dmlc.xgboost4j.LabeledPoint
import org.scalacheck.{Arbitrary, Gen, Prop, Properties}

import scala.reflect.ClassTag

object XGBoostFeatureBuilderSpec extends Properties("XGBoostFeatureBuilder") {
  private def list[T](implicit arb: Arbitrary[Option[T]]): Gen[List[Option[T]]] =
    Gen.listOfN(100, arb.arbitrary)

  private def test[T: ClassTag: Numeric, F](xs: List[Option[T]], builder: FeatureBuilder[F])(
    toSeq: F => Seq[Float]
  ): Prop = {
    val num = implicitly[Numeric[T]]
    val fb = SerializableUtils.ensureSerializable(builder)
    fb.init(xs.size + 4)
    fb.prepare(null)
    xs.zipWithIndex.foreach {
      case (Some(x), i) => fb.add("key" + i.toString, num.toDouble(x))
      case (None, _)    => fb.skip()
    }
    fb.add(Iterable("x", "y"), Seq(0.0, 0.0))
    fb.skip(2)
    // keep in mind that we force the RHS to be floats because that is what LabeledPoint stores
    toSeq(fb.result) == (xs.map(_.getOrElse(num.zero)) ++ List.fill(4)(num.zero)).map(num.toFloat)
  }

  property("LabeledPoint on Float input") = Prop.forAll(list[Float]) { xs =>
    test(xs, FeatureBuilder[LabeledPoint])(_.values.toSeq)
  }

  property("LabeledPoint on Double input") = Prop.forAll(list[Double]) { xs =>
    test(xs, FeatureBuilder[LabeledPoint])(_.values.toSeq)
  }

  property("Sparse LabeledPoint on Float input") = Prop.forAll(list[Float]) { xs =>
    test(xs, FeatureBuilder[SparseLabeledPoint])(r =>
      SparseArray(r.labeledPoint.indices, r.labeledPoint.values, 4 + xs.size).toDense.toSeq
    )
    val n = 1024 / xs.size + 1
    val xs2 = Seq.fill(n)(xs).reduce(_ ++ _)
    test(xs2, FeatureBuilder[SparseLabeledPoint])(r =>
      SparseArray(r.labeledPoint.indices, r.labeledPoint.values, 4 + xs2.size).toDense.toSeq
    )
  }

  property("Sparse LabeledPoint on Double input") = Prop.forAll(list[Double]) { xs =>
    test(xs, FeatureBuilder[SparseLabeledPoint])(r =>
      SparseArray(r.labeledPoint.indices, r.labeledPoint.values, 4 + xs.size).toDense.toSeq
    )
    val n = 1024 / xs.size + 1
    val xs2 = Seq.fill(n)(xs).reduce(_ ++ _)
    test(xs2, FeatureBuilder[SparseLabeledPoint])(r =>
      SparseArray(r.labeledPoint.indices, r.labeledPoint.values, 4 + xs2.size).toDense.toSeq
    )
  }
} 
Example 126
Source File: IQROutlierRejectorSpec.scala    From featran   with Apache License 2.0 5 votes vote down vote up
package com.spotify.featran.transformers

import com.twitter.algebird.{QTree, QTreeAggregator, QTreeSemigroup}
import org.scalacheck.{Arbitrary, Gen, Prop}

object IQROutlierRejectorSpec extends TransformerProp("IQROutlierRejector") {
  implicit private val arbPosDouble = Arbitrary(Gen.posNum[Double])

  def lowerUpper(xs: List[Double]): (Double, Double) = {
    val qt = xs.map(QTree(_)).reduce(new QTreeSemigroup[Double](QTreeAggregator.DefaultK).plus)
    val (lq, _) = qt.quantileBounds(0.75)
    val (_, fq) = qt.quantileBounds(0.25)
    val iqr = lq - fq
    val l = fq - (iqr * 1.5)
    val u = lq - (iqr * 1.5)
    (l, u)
  }

  property("default") = Prop.forAll(list[Double].arbitrary) { xs =>
    val (l, u) = lowerUpper(xs)
    val rejected = xs.filter(_ => xs.min < xs.max).filter(x => x > u || x < l).map(_ => Seq(0d))
    // records that are not within bounds should always be rejected
    val oob = List((lowerBound(xs.min), Seq(0d)), (upperBound(xs.max), Seq(0d)))
    val r = IQROutlierRejector("iqr")
    test(r, xs, Seq("iqr"), xs.map(_ => Seq(0d)), Seq(0.0), oob, rejected)
  }

  property("rejectLower don't rejectUpper") = Prop.forAll(list[Double].arbitrary) { xs =>
    val (l, _) = lowerUpper(xs)
    val rejected =
      xs.filter(_ => xs.min < xs.max).filter(_ < l).map(_ => Seq(0d))
    val r = IQROutlierRejector("iqr", rejectLower = true, rejectUpper = false)
    test(r, xs, Seq("iqr"), xs.map(_ => Seq(0d)), Seq(0.0), rejected = rejected)
  }

  property("rejectUpper don't rejectLower") = Prop.forAll(list[Double].arbitrary) { xs =>
    val (_, u) = lowerUpper(xs)
    val rejected =
      xs.filter(_ => xs.min < xs.max).filter(_ > u).map(_ => Seq(0d))
    val r = IQROutlierRejector("iqr", rejectLower = false, rejectUpper = true)
    test(r, xs, Seq("iqr"), xs.map(_ => Seq(0d)), Seq(0.0), rejected = rejected)
  }
} 
Example 127
Source File: PositionEncoderSpec.scala    From featran   with Apache License 2.0 5 votes vote down vote up
package com.spotify.featran.transformers

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

object PositionEncoderSpec extends TransformerProp("PositionEncoder") {
  implicit private val labelArb = Arbitrary(Gen.alphaStr)

  property("default") = Prop.forAll { xs: List[String] =>
    val cats = xs.distinct.sorted
    val expected =
      xs.map(s => Seq(cats.zipWithIndex.find(c => s == c._1).map(_._2).getOrElse(0).toDouble))
    val oob = List(("s1", Seq(0.0)), ("s2", Seq(0.0))) // unseen labels
    test(PositionEncoder("position"), xs, List("position"), expected, Seq(0.0), oob)
  }
} 
Example 128
Source File: NHotWeightedEncoderSpec.scala    From featran   with Apache License 2.0 5 votes vote down vote up
package com.spotify.featran.transformers

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

object NHotWeightedEncoderSpec extends TransformerProp("NHotWeightedEncoder") {
  implicit private val weightedVectors = Arbitrary {
    val weightedValueGen = for {
      value <- Gen.chooseNum(-1.0, 1.0)
      n <- Gen.alphaStr
    } yield WeightedLabel(n, value)

    Gen.choose(1, 5).flatMap(Gen.listOfN(_, weightedValueGen))
  }

  property("default") = Prop.forAll { xs: List[List[WeightedLabel]] =>
    val cats = xs.flatten.map(_.name).distinct.sorted
    val names = cats.map("n_hot_" + _)
    val expected =
      xs.map(s => cats.map(c => s.filter(_.name == c).map(_.value).sum))
    val missing = cats.map(_ => 0.0)
    val oob =
      List((List(WeightedLabel("s1", 0.2), WeightedLabel("s2", 0.1)), missing))
    test(NHotWeightedEncoder("n_hot"), xs, names, expected, missing, oob)
  }

  property("encodeMissingValue") = Prop.forAll { xs: List[List[WeightedLabel]] =>
    import MissingValue.MissingValueToken
    val cats = xs.flatten.map(_.name).distinct.sorted :+ MissingValueToken
    val names = cats.map("n_hot_" + _)
    val expected =
      xs.map(s => cats.map(c => s.filter(_.name == c).map(_.value).sum))
    val missingBase = cats.map(c => if (c == MissingValueToken) 1.0 else 0.0)

    val oob = List(
      (List(WeightedLabel("s1", 0.2), WeightedLabel("s2", 0.1)), missingBase.map(v => v * 0.3))
    )
    test(
      NHotWeightedEncoder("n_hot", encodeMissingValue = true),
      xs,
      names,
      expected,
      missingBase,
      oob
    )
  }
} 
Example 129
Source File: VectorIdentitySpec.scala    From featran   with Apache License 2.0 5 votes vote down vote up
package com.spotify.featran.transformers

import org.scalacheck.Prop

object VectorIdentitySpec extends TransformerProp("VectorIdentity") {
  property("default") = Prop.forAll { xs: List[List[Double]] =>
    val dim = xs.head.length
    val names = (0 until dim).map("id_" + _)
    val expected = xs.map(_.toSeq)
    val missing = (0 until dim).map(_ => 0.0)
    val oob = List((xs.head :+ 1.0, missing)) // vector of different dimension
    test[List[Double]](VectorIdentity("id"), xs, names, expected, missing, oob)
  }

  property("length") = Prop.forAll { xs: List[List[Double]] =>
    val msg = "requirement failed: Invalid input length, " +
      s"expected: ${xs.head.length + 1}, actual: ${xs.head.length}"
    testException[List[Double]](VectorIdentity("id", xs.head.length + 1), xs) { e =>
      e.isInstanceOf[IllegalArgumentException] && e.getMessage == msg
    }
  }
} 
Example 130
Source File: TypeEqv.scala    From scalaz-deriving   with GNU Lesser General Public License v3.0 5 votes vote down vote up
// Copyright: 2017 - 2020 Sam Halliday
// License: https://opensource.org/licenses/BSD-3-Clause

package scalaz
package iotatests

import scala._
import scalaz._
import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.{ Id => _, _ }
import shapeless.ops.hlist.{ ToList => HListToList }

import scala.reflect.runtime.universe._

sealed trait TypeEqv[A] {
  def check(x: A, y: A): Prop
}

object TypeEqv extends TypeEqvInstances0 {
  object syntax {
    final implicit class TypeEqvOps[A](x: A)(implicit eqv: TypeEqv[A]) {
      def ?=:=(y: A): Prop = eqv.check(x, y)
    }
  }
}

sealed class TypeEqvInstances0 extends TypeEqvInstances1 {
  implicit def idTypeEqv[A <: Type]: TypeEqv[A] =
    new TypeEqv[A] {
      def check(x: A, y: A): Prop =
        Prop(x =:= y) :| s"$x was not =:= to $y"
    }

  implicit def eitherTypeEqv[A, B](implicit
    eqv: TypeEqv[B]
  ): TypeEqv[Either[A, B]] =
    new TypeEqv[Either[A, B]] {
      def check(ex: Either[A, B], ey: Either[A, B]): Prop =
        (ex, ey) match {
          case (Right(bx), Right(by)) => eqv.check(bx, by)
          case _                      => ex ?= ey
        }
    }
}

sealed class TypeEqvInstances1 {
  implicit def foldableTypeEqv[F[_], A](implicit
    F: Foldable[F],
    eqv: TypeEqv[A]
  ): TypeEqv[F[A]] =
    new TypeEqv[F[A]] {
      def check(fx: F[A], fy: F[A]): Prop =
        F.toList(fx)
          .zip(F.toList(fy))
          .foldLeft(proved)((acc, vv) => acc && eqv.check(vv._1, vv._2))
    }

  implicit def genericTypeEqv[P, L <: HList, A](implicit
    gen: Generic.Aux[P, L],
    toList: HListToList[L, A],
    eqv: TypeEqv[List[A]]
  ): TypeEqv[P] =
    new TypeEqv[P] {
      def check(x: P, y: P): Prop =
        eqv.check(toList(gen.to(x)), toList(gen.to(y)))
    }
} 
Example 131
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 132
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 133
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 134
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 135
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 136
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 137
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 138
Source File: package.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc
package refined

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

package object types {
  private[types] val ints: Gen[Int]           = implicitly[Arbitrary[Int]].arbitrary
  private[types] val longs: Gen[Long]         = implicitly[Arbitrary[Long]].arbitrary
  private[types] val doubles: Gen[Double]     = implicitly[Arbitrary[Double]].arbitrary
  private[types] val strings: Gen[String]     = implicitly[Arbitrary[String]].arbitrary
  private[types] val intLists: Gen[List[Int]] = implicitly[Arbitrary[List[Int]]].arbitrary

  private[types] def keyLists(implicit k: Arbitrary[Key]): Gen[List[Key]] = listOf(k.arbitrary)

  private[types] def wightedKeyLists(implicit kv: Arbitrary[(Key, ValidDouble)]): Gen[List[(Key, ValidDouble)]] =
    listOf(kv.arbitrary)

  private[types] implicit val illegalArgumentException: IllegalArgumentException => Prop = _ => Prop.passed
} 
Example 139
Source File: testUtil.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.{Cmd, Expr, Replica, Val}
import eu.timepit.crjdt.core.syntax._
import io.circe.{Json, JsonObject}
import org.scalacheck.Prop
import org.scalacheck.Prop._

import scala.util.Random

object testUtil {
  def converged(a: Replica, b: Replica): Prop =
    (a.processedOps ?= b.processedOps) && (a.document ?= b.document)

  def converged(a: Replica, b: Replica, c: Replica): Prop =
    converged(a, b) && converged(b, c)

  def diverged(a: Replica, b: Replica): Prop =
    (a.processedOps != b.processedOps) && (a.document != b.document)

  def merge(a: Replica, b: Replica): Replica =
    a.applyRemoteOps(b.generatedOps)

  def randomPermutation[A](xs: Vector[A]): Vector[A] = {
    val permutations = xs.permutations.toStream.take(12)
    val index = Random.nextInt(permutations.size)
    permutations.lift(index).getOrElse(Vector.empty)
  }

  def assignCmds(expr: Expr, value: Json): Vector[Cmd] = {
    val assign = expr := jsonToVal(value)
    val fillEmptyArrayOrMap = value.arrayOrObject(
      Vector.empty,
      array => insertToArrayCmds(expr, array),
      obj => assignObjectFieldsCmds(expr, obj)
    )
    assign +: fillEmptyArrayOrMap
  }

  def insertToArrayCmds(expr: Expr, array: Vector[Json]): Vector[Cmd] = {
    val (_, commands) = array.foldLeft((expr.iter.next, Vector.empty[Cmd])) {
      (acc, item) =>
        val (position, commands) = acc
        val insert = position.insert(jsonToVal(item))
        val fillEmptyArrayOrMap = item.arrayOrObject(
          Vector.empty,
          array => insertToArrayCmds(position, array),
          obj => assignObjectFieldsCmds(position, obj)
        )
        (position.next, commands ++ (insert +: fillEmptyArrayOrMap))
    }
    commands
  }

  def assignObjectFieldsCmds(expr: Expr, obj: JsonObject): Vector[Cmd] =
    obj.toMap.flatMap {
      case (key, value) =>
        val field = expr.downField(key)
        assignCmds(field, value)
    }.toVector

  def jsonToVal(value: Json): Val =
    value.fold(
      Val.Null,
      bool => if (bool) Val.True else Val.False,
      number => Val.Num(number.toBigDecimal.getOrElse(number.toDouble)),
      string => Val.Str(string),
      array => Val.EmptyList,
      obj => Val.EmptyMap
    )
} 
Example 140
Source File: testUtil.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core

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

import scala.util.Random

object testUtil {
  def converged(a: Replica, b: Replica): Prop =
    (a.processedOps ?= b.processedOps) && (a.document ?= b.document)

  def converged(a: Replica, b: Replica, c: Replica): Prop =
    converged(a, b) && converged(b, c)

  def diverged(a: Replica, b: Replica): Prop =
    (a.processedOps != b.processedOps) && (a.document != b.document)

  def merge(a: Replica, b: Replica): Replica =
    a.applyRemoteOps(b.generatedOps)

  def randomPermutation[A](xs: Vector[A]): Vector[A] = {
    val permutations = xs.permutations.toStream.take(12)
    val index = Random.nextInt(permutations.size)
    permutations.lift(index).getOrElse(Vector.empty)
  }
} 
Example 141
Source File: ExtraMonadTests.scala    From interop-cats   with Apache License 2.0 5 votes vote down vote up
package zio.interop

import cats.kernel.laws.discipline.catsLawsIsEqToProp
import cats.{ Eq, Monad }
import org.scalacheck.{ Arbitrary, Prop }
import org.typelevel.discipline.Laws

trait ExtraMonadTests[F[_]] extends Laws {
  def laws: ExtraMonadLaws[F]

  def monadExtras[A: Arbitrary: Eq](
    implicit
    EqFInt: Eq[F[Int]]
  ): RuleSet =
    new RuleSet {
      def name: String                  = "monadExtras"
      def bases: Seq[(String, RuleSet)] = Nil
      def parents: Seq[RuleSet]         = Nil
      def props: Seq[(String, Prop)] =
        Seq[(String, Prop)]("tailRecM construction stack safety" -> Prop.lzy(laws.tailRecMConstructionStackSafety))
    }
}

object ExtraMonadTests {
  def apply[F[_]: Monad]: ExtraMonadTests[F] =
    new ExtraMonadTests[F] {
      def laws: ExtraMonadLaws[F] = ExtraMonadLaws[F]
    }
} 
Example 142
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 143
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 144
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 145
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 146
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 147
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 148
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 149
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
  }

}