org.scalacheck.Properties Scala Examples

The following examples show how to use org.scalacheck.Properties. 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: NodeToJsonFigure3Spec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.Replica
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.circe.syntax._
import eu.timepit.crjdt.circe.testUtil.{converged, diverged, merge}
import io.circe.Json
import org.scalacheck.Prop._
import org.scalacheck.Properties

object NodeToJsonFigure3Spec extends Properties("NodeToJsonFigure3Spec") {
  val p0 = Replica.empty("p")
  val q0 = Replica.empty("q")

  property("initial state") = secure {
    converged(p0, q0)
  }

  val grocery = doc.downField("grocery")

  val p1 = p0
    .applyCmd(grocery := `[]`)
    .applyCmd(grocery.iter.insert("eggs"))
    .applyCmd(grocery.iter.next.insert("ham"))
  val q1 = q0
    .applyCmd(grocery := `[]`)
    .applyCmd(grocery.iter.insert("milk"))
    .applyCmd(grocery.iter.next.insert("flour"))

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("toJson with last-writer-wins conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.LWW
    // Figure 3 shows list of the final state is ["eggs", "ham", "milk", "flour"]
    // but ["milk", "flour", "eggs", "ham"] is also valid order.
    q2.document.toJson ?= Json.obj(
      "grocery" -> Json.arr(
        List("milk", "flour", "eggs", "ham").map(Json.fromString): _*
      )
    )
  }

  property("toJson with preserve-all-as-array conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.PreserveAllAsArray
    q2.document.toJson ?= Json.obj(
      "grocery" -> Json.arr(
        List("milk", "flour", "eggs", "ham").map(v =>
          Json.arr(Json.fromString(v))
        ): _*
      )
    )
  }
} 
Example 2
Source File: CodecProperties.scala    From phobos   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.phobos.ast

import org.scalacheck.Prop.forAll
import org.scalacheck.Properties
import ru.tinkoff.phobos.decoding.XmlDecoder
import ru.tinkoff.phobos.encoding.XmlEncoder
import org.scalacheck.{Arbitrary, Gen}

class CodecProperties extends Properties("Ast codecs") {
  import CodecProperties._

  private val encoder = XmlEncoder.fromElementEncoder[XmlEntry]("test")
  private val decoder = XmlDecoder.fromElementDecoder[XmlEntry]("test")

  property("decode(encode(ast)) === ast") = forAll { entry: XmlEntry =>
    decoder.decode(
      encoder.encode(entry)
    ) == Right(entry)
  }

  property("encode(decode(xmlAst)) === xmlAst") = forAll { entry: XmlEntry =>
    val encoded = encoder.encode(entry)

    decoder.decode(encoded).map(encoder.encode(_)) == Right(encoded)
  }
}

object CodecProperties {
  implicit val arbitraryXmlLong: Arbitrary[XmlNumber.Aux[Long]] = Arbitrary(
    Arbitrary.arbitrary[Long].map(XmlNumber.integral))

  implicit val arbitraryXmlDouble: Arbitrary[XmlNumber.Aux[Double]] = Arbitrary(
    Arbitrary.arbitrary[Double].map(XmlNumber.double))

  implicit val arbitraryXmlNumber: Arbitrary[XmlNumber] =
    Arbitrary(
      Gen.oneOf(arbitraryXmlLong.arbitrary, arbitraryXmlDouble.arbitrary)
    )

  implicit val arbitraryXmlBoolean: Arbitrary[XmlBoolean] = Arbitrary(
    Arbitrary.arbitrary[Boolean].map(XmlBoolean.fromBoolean))

  implicit val arbNonEmptyString: Arbitrary[String] = Arbitrary {
    Gen.choose(1, 10).flatMap { n =>
      Gen
        .containerOfN[List, Char](n, Gen.oneOf("abcdefghijklmnopqrstuvwxyz".toList))
        .map(_.mkString)
    }
  }

  implicit val arbitraryXmlText: Arbitrary[XmlText] = Arbitrary(
    arbNonEmptyString.arbitrary.map(XmlText(_))
  )

  implicit val arbitraryXmlLeaf: Arbitrary[XmlLeaf] = Arbitrary(
    Gen.oneOf(arbitraryXmlNumber.arbitrary, arbitraryXmlBoolean.arbitrary, arbitraryXmlText.arbitrary)
  )

  class Depth(val value: Int) extends AnyVal

  def arbitraryXmlNode(depth: Depth): Arbitrary[XmlNode] = Arbitrary {
    val arbInt           = Gen.choose(0, 5)
    def arbNames(n: Int) = Gen.containerOfN[Set, String](n, arbNonEmptyString.arbitrary)

    def arbLeafs(n: Int) =
      for {
        names <- arbNames(n)
        leafs <- Gen.containerOfN[List, XmlLeaf](n, arbitraryXmlLeaf.arbitrary)
      } yield names.toList zip leafs

    val arbNodes: Gen[List[(String, XmlEntry)]] = arbInt.flatMap { n =>
      if (depth.value > 3) arbLeafs(n)
      else {
        val depth2: Depth = new Depth(depth.value + 1)
        val arbEntries = Gen
          .containerOfN[List, XmlEntry](n, arbitraryXmlNode(depth2).arbitrary)

        for {
          names   <- arbNames(n)
          entries <- arbEntries
        } yield names.toList zip entries
      }
    }
    for {
      nAttrs <- arbInt
      attrs  <- arbLeafs(nAttrs)
      nodes  <- arbNodes
    } yield XmlNode(attrs, nodes)
  }

  implicit val arbitraryXmlEntry: Arbitrary[XmlEntry] =
    Arbitrary(arbitraryXmlNode(new Depth(0)).arbitrary)
} 
Example 3
Source File: StringDiffSpecification.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.clippy

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

class StringDiffSpecification extends Properties("StringDiff") with TypeNamesGenerators {

  val S     = "S"
  val E     = "E"
  val AddSE = (s: String) => S + s + E

  def innerTypeDiffsCorrectly(fourTypes: List[String]): Boolean = {
    val List(x, y, v, z) = fourTypes
    val expected         = s"$x[$y[$z]]"
    val actual           = s"$x[$v[$z]]"
    val msg              = new StringDiff(expected, actual, AddSE).diff("expected: %s actual: %s")
    msg == s"""expected: $x[$S$y$E[$z]] actual: $x[$S$v$E[$z]]"""
  }

  def twoTypesAreFullyDiff(twoTypes: List[String]): Boolean = {
    val List(x, y) = twoTypes
    new StringDiff(x, y, AddSE).diff("expected: %s actual: %s") == s"""expected: $S$x$E actual: $S$y$E"""
  }

  property("X[Y[Z]] vs X[V[Z]] always gives X[<diff>[Z]] excluding packages") =
    forAll(different(singleTypeName)(4))(innerTypeDiffsCorrectly)

  property("X[Y[Z]] vs X[V[Z]] always gives X[<diff>[Z]] if Y and V have common prefix") =
    forAll(typesWithCommonPrefix(4))(innerTypeDiffsCorrectly)

  property("X[Y[Z]] vs X[V[Z]] always gives X[<diff>[Z]] if Y and V have common suffix") =
    forAll(typesWithCommonSuffix(4))(innerTypeDiffsCorrectly)

  property("A[X] vs B[X] always marks outer as diff for A != B when A and B have common prefix") =
    forAll(typesWithCommonPrefix(2), complexTypeName(maxDepth = 3)) { (outerTypes, x) =>
      val List(a, b) = outerTypes
      val expected   = s"$a[$x]"
      val actual     = s"$b[$x]"
      val msg        = new StringDiff(expected, actual, AddSE).diff("expected: %s actual: %s")
      msg == s"""expected: $S$a$E[$x] actual: $S$b$E[$x]"""
    }

  property("package.A[X] vs package.B[X] always gives package.<diff>A</diff>[X]") =
    forAll(javaPackage, different(singleTypeName)(2), complexTypeName(maxDepth = 3)) { (pkg, outerTypes, x) =>
      val List(a, b) = outerTypes
      val expected   = s"$pkg$a[$x]"
      val actual     = s"$pkg$b[$x]"
      val msg        = new StringDiff(expected, actual, AddSE).diff("expected: %s actual: %s")
      msg == s"""expected: $pkg$S$a$E[$x] actual: $pkg$S$b$E[$x]"""
    }

  property("any complex X vs Y is a full diff when X and Y don't have common suffix nor prefix") =
    forAll(different(complexTypeName(maxDepth = 4))(2).suchThat(noCommonPrefixSuffix))(twoTypesAreFullyDiff)

  property("any single X vs Y is a full diff") = forAll(different(singleTypeName)(2))(twoTypesAreFullyDiff)

  def noCommonPrefixSuffix(twoTypes: List[String]): Boolean = {
    val List(x, y) = twoTypes
    x.head != y.head && x.last != y.last
  }

} 
Example 4
Source File: NewtypeTests.scala    From http4s-poc-api   with MIT License 5 votes vote down vote up
package external

import cats.instances.int._
import cats.instances.list._
import cats.instances.option._
import cats.syntax.eq._
import external.library.newtype
import org.scalacheck.Prop.forAll
import org.scalacheck.Properties

final class NewtypeTests extends Properties("newtype") {
  property("unMk gives the original value") = forAll { i: Int => newtype[Int](i).unMk === i }

  property("unMkF gives the original values in F[_] for List") = forAll { xs: List[Int] =>
    val nt = newtype[Int]
    nt.unMkF(nt.mkF(xs)) === xs
  }

  property("unMkF gives the original values in F[_] for Option") = forAll { os: Option[Int] =>
    val nt = newtype[Int]
    nt.unMkF(nt.mkF(os)) === os
  }
} 
Example 5
Source File: SyntaxSpec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core

import eu.timepit.crjdt.core.Cmd.{Assign, Delete, Insert}
import eu.timepit.crjdt.core.Expr.{Doc, DownField, Iter, Var}
import eu.timepit.crjdt.core.Val.EmptyList
import eu.timepit.crjdt.core.syntax._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object SyntaxSpec extends Properties("syntax") {
  property("assign") = secure {
    v("list") := `[]` ?= Assign(Var("list"), EmptyList)
  }

  property("insert") = secure {
    doc.downField("key").iter.insert(Val.Null) ?=
      Insert(Iter(DownField(Doc, "key")), Val.Null)
  }

  property("delete") = secure {
    doc.delete ?= Delete(Doc)
  }
} 
Example 6
Source File: EvalExprSpec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core

import eu.timepit.crjdt.core.Key.{DocK, HeadK, IdK, StrK}
import eu.timepit.crjdt.core.TypeTag.{ListT, MapT}
import eu.timepit.crjdt.core.syntax._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object EvalExprSpec extends Properties("Replica.evalExpr") {
  val p0 = Replica.empty("p")

  property("doc") = secure {
    p0.evalExpr(doc) ?= Cursor.withFinalKey(DocK)
  }

  property("""doc["key"]""") = secure {
    p0.evalExpr(doc.downField("key")) ?=
      Cursor(Vector(MapT(DocK)), StrK("key"))
  }

  property("""doc["key"].iter""") = secure {
    p0.evalExpr(doc.downField("key").iter) ?=
      Cursor(Vector(MapT(DocK), ListT(StrK("key"))), HeadK)
  }

  property("doc.iter") = secure {
    p0.evalExpr(doc.iter) ?= Cursor(Vector(ListT(DocK)), HeadK)
  }

  property("doc.iter.next") = secure {
    p0.evalExpr(doc.iter.next) ?= Cursor(Vector(ListT(DocK)), HeadK)
  }

  property("list.iter.next") = secure {
    val list = doc.downField("list")
    val cmd = (list := `[]`) `;`
      list.iter.insert("item1") `;`
      list.iter.insert("item2") `;`
      list.iter.insert("item3")

    val p1 = p0.applyCmd(cmd)
    val e1 = list.iter.next
    val e2 = list.iter.next.next
    val e3 = list.iter.next.next.next
    val cur = p1.evalExpr(list.iter)

    (p1.evalExpr(e1) ?= cur.copy(finalKey = IdK(Id(4, "p")))) &&
    (p1.evalExpr(e2) ?= cur.copy(finalKey = IdK(Id(3, "p")))) &&
    (p1.evalExpr(e3) ?= cur.copy(finalKey = IdK(Id(2, "p"))))
  }
} 
Example 7
Source File: Figure1.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core
package examples

import eu.timepit.crjdt.core.Key.{DocK, StrK}
import eu.timepit.crjdt.core.Node.{MapNode, RegNode}
import eu.timepit.crjdt.core.TypeTag.{MapT, RegT}
import eu.timepit.crjdt.core.Val.Str
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.core.testUtil._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object Figure1 extends Properties("Figure1") {
  val p0 = Replica.empty("p").applyCmd(doc.downField("key") := "A")
  val q0 = merge(Replica.empty("q"), p0)

  property("initial state") = secure {
    converged(p0, q0)
  }

  val p1 = p0.applyCmd(doc.downField("key") := "B")
  val q1 = q0.applyCmd(doc.downField("key") := "C")

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("content") = secure {
    p2.document ?= MapNode(
      Map(
        MapT(DocK) -> MapNode(
          Map(
            RegT(StrK("key")) ->
              RegNode(Map(Id(2, "p") -> Str("B"), Id(2, "q") -> Str("C")))
          ),
          Map(StrK("key") -> Set(Id(1, "p"), Id(2, "p"), Id(2, "q")))
        )
      ),
      Map(DocK -> Set(Id(1, "p"), Id(2, "p"), Id(2, "q")))
    )
  }

  property("keys") = secure {
    p2.keys(doc) ?= Set("key")
  }

  property("values") = secure {
    p2.values(doc.downField("key")) ?= List("B", "C")
  }
} 
Example 8
Source File: Figure2.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core
package examples

import eu.timepit.crjdt.core.Key.{DocK, StrK}
import eu.timepit.crjdt.core.Node.{MapNode, RegNode}
import eu.timepit.crjdt.core.TypeTag.{MapT, RegT}
import eu.timepit.crjdt.core.Val.Str
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.core.testUtil._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object Figure2 extends Properties("Figure2") {
  val colors = doc.downField("colors")
  val p0 =
    Replica.empty("p").applyCmd(colors.downField("blue") := "#0000ff")
  val q0 = merge(Replica.empty("q"), p0)

  property("initial state") = secure {
    converged(p0, q0)
  }

  val p1 = p0.applyCmd(colors.downField("red") := "#ff0000")
  val q1 = q0
    .applyCmd(colors := `{}`)
    .applyCmd(colors.downField("green") := "#00ff00")

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("content") = secure {
    p2.document ?= MapNode(
      Map(
        MapT(DocK) ->
          MapNode(
            Map(
              MapT(StrK("colors")) ->
                MapNode(
                  Map(
                    RegT(StrK("blue")) -> RegNode(Map()),
                    RegT(StrK("red")) ->
                      RegNode(Map(Id(2, "p") -> Str("#ff0000"))),
                    RegT(StrK("green")) ->
                      RegNode(Map(Id(3, "q") -> Str("#00ff00")))
                  ),
                  Map(
                    StrK("red") -> Set(Id(2, "p")),
                    StrK("green") -> Set(Id(3, "q"))
                  )
                )
            ),
            Map(StrK("colors") -> Set(Id(2, "p"), Id(2, "q"), Id(3, "q")))
          )
      ),
      Map(DocK -> Set(Id(1, "p"), Id(2, "p"), Id(2, "q"), Id(3, "q")))
    )
  }

  property("keys") = secure {
    (p2.keys(doc) ?= Set("colors")) &&
    (p2.keys(colors) ?= Set("red", "green"))
  }
} 
Example 9
Source File: Figure4.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core
package examples

import eu.timepit.crjdt.core.Key.{DocK, IdK, StrK}
import eu.timepit.crjdt.core.ListRef.{HeadR, IdR, TailR}
import eu.timepit.crjdt.core.Node.{ListNode, MapNode, RegNode}
import eu.timepit.crjdt.core.TypeTag.{ListT, MapT, RegT}
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.core.testUtil._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object Figure4 extends Properties("Figure4") {
  val todo = doc.downField("todo").iter
  val cmd = todo.insert(`{}`) `;`
    (todo.next.downField("title") := "buy milk") `;`
    (todo.next.downField("done") := false)

  val p0 = Replica.empty("p").applyCmd(cmd)
  val q0 = merge(Replica.empty("q"), p0)

  property("initial state") = secure {
    converged(p0, q0)
  }

  val p1 = p0.applyCmd(todo.next.delete)
  val q1 = q0.applyCmd(todo.next.downField("done") := true)

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("content") = secure {
    val todoLists = ListNode(
      Map(
        MapT(IdK(Id(1, "p"))) -> MapNode(
          Map(
            RegT(StrK("title")) -> RegNode(Map()),
            RegT(StrK("done")) -> RegNode(Map(Id(4, "q") -> Val.True))
          ),
          Map(StrK("done") -> Set(Id(4, "q")))
        )
      ),
      Map(IdK(Id(1, "p")) -> Set(Id(4, "q"))),
      Map(HeadR -> IdR(Id(1, "p")), IdR(Id(1, "p")) -> TailR),
      Map()
    )

    p2.document ?= MapNode(
      Map(
        MapT(DocK) -> MapNode(
          Map(ListT(StrK("todo")) -> todoLists),
          Map(
            StrK("todo") -> Set(Id(1, "p"), Id(2, "p"), Id(3, "p"), Id(4, "q"))
          )
        )
      ),
      Map(DocK -> Set(Id(1, "p"), Id(2, "p"), Id(3, "p"), Id(4, "q")))
    )
  }

  property("keys") = secure {
    (p2.keys(doc) ?= Set("todo")) &&
    (p2.keys(todo.next) ?= Set("done")) &&
    (p2.keys(todo) ?= Set.empty) &&
    (p2.keys(doc.downField("foo").iter) ?= Set.empty)
  }

  property("values") = secure {
    (p2.values(todo.next.downField("done")) ?= List(Val.True)) &&
    (p2.values(todo) ?= List.empty) &&
    (p2.values(doc.downField("foo").iter) ?= List.empty)
  }
} 
Example 10
Source File: Figure6.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core
package examples

import eu.timepit.crjdt.core.Key.{DocK, IdK, StrK}
import eu.timepit.crjdt.core.ListRef.{HeadR, IdR, TailR}
import eu.timepit.crjdt.core.Node.{ListNode, MapNode, RegNode}
import eu.timepit.crjdt.core.TypeTag.{ListT, MapT, RegT}
import eu.timepit.crjdt.core.Val.Str
import eu.timepit.crjdt.core.syntax._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object Figure6 extends Properties("Figure6") {
  property("internal state") = secure {
    val list = v("list")
    val eggs = v("eggs")
    val cmd = (doc := `{}`) `;`
      (let(list) = doc.downField("shopping").iter) `;`
      list.insert("eggs") `;`
      (let(eggs) = list.next) `;`
      eggs.insert("milk") `;`
      list.insert("cheese")

    val shoppingNode = ListNode(
      Map(
        RegT(IdK(Id(4, ""))) -> RegNode(Map(Id(4, "") -> Str("cheese"))),
        RegT(IdK(Id(2, ""))) -> RegNode(Map(Id(2, "") -> Str("eggs"))),
        RegT(IdK(Id(3, ""))) -> RegNode(Map(Id(3, "") -> Str("milk")))
      ),
      Map(
        IdK(Id(4, "")) -> Set(Id(4, "")),
        IdK(Id(2, "")) -> Set(Id(2, "")),
        IdK(Id(3, "")) -> Set(Id(3, ""))
      ),
      Map(
        HeadR -> IdR(Id(4, "")),
        IdR(Id(4, "")) -> IdR(Id(2, "")),
        IdR(Id(2, "")) -> IdR(Id(3, "")),
        IdR(Id(3, "")) -> TailR
      ),
      Map()
    )

    val rootNode = MapNode(
      Map(
        MapT(DocK) -> MapNode(
          Map(ListT(StrK("shopping")) -> shoppingNode),
          Map(StrK("shopping") -> Set(Id(2, ""), Id(3, ""), Id(4, "")))
        )
      ),
      Map(DocK -> Set(Id(1, ""), Id(2, ""), Id(3, ""), Id(4, "")))
    )

    Replica.empty("").applyCmd(cmd).document ?= rootNode
  }
} 
Example 11
Source File: Figure3.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.core
package examples

import eu.timepit.crjdt.core.Key.{DocK, IdK, StrK}
import eu.timepit.crjdt.core.ListRef.{HeadR, IdR, TailR}
import eu.timepit.crjdt.core.Node.{ListNode, MapNode, RegNode}
import eu.timepit.crjdt.core.TypeTag.{ListT, MapT, RegT}
import eu.timepit.crjdt.core.Val.Str
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.core.testUtil._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object Figure3 extends Properties("Figure3") {
  val p0 = Replica.empty("p")
  val q0 = Replica.empty("q")

  property("initial state") = secure {
    converged(p0, q0)
  }

  val grocery = doc.downField("grocery")

  val p1 = p0
    .applyCmd(grocery := `[]`)
    .applyCmd(grocery.iter.insert("eggs"))
    .applyCmd(grocery.iter.next.insert("ham"))
  val q1 = q0
    .applyCmd(grocery := `[]`)
    .applyCmd(grocery.iter.insert("milk"))
    .applyCmd(grocery.iter.next.insert("flour"))

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("content") = secure {
    val groceryList = ListNode(
      Map(
        RegT(IdK(Id(2, "q"))) -> RegNode(Map(Id(2, "q") -> Str("milk"))),
        RegT(IdK(Id(3, "q"))) -> RegNode(Map(Id(3, "q") -> Str("flour"))),
        RegT(IdK(Id(2, "p"))) -> RegNode(Map(Id(2, "p") -> Str("eggs"))),
        RegT(IdK(Id(3, "p"))) -> RegNode(Map(Id(3, "p") -> Str("ham")))
      ),
      Map(
        IdK(Id(2, "p")) -> Set(Id(2, "p")),
        IdK(Id(3, "p")) -> Set(Id(3, "p")),
        IdK(Id(2, "q")) -> Set(Id(2, "q")),
        IdK(Id(3, "q")) -> Set(Id(3, "q"))
      ),
      Map(
        HeadR -> IdR(Id(2, "q")),
        IdR(Id(2, "q")) -> IdR(Id(3, "q")),
        IdR(Id(3, "q")) -> IdR(Id(2, "p")),
        IdR(Id(2, "p")) -> IdR(Id(3, "p")),
        IdR(Id(3, "p")) -> TailR
      ),
      Map()
    )
    val pres = Set(
      Id(2, "p"),
      Id(2, "q"),
      Id(1, "q"),
      Id(3, "q"),
      Id(3, "p"),
      Id(1, "p")
    )

    p2.document ?= MapNode(
      Map(
        MapT(DocK) -> MapNode(
          Map(ListT(StrK("grocery")) -> groceryList),
          Map(StrK("grocery") -> pres)
        )
      ),
      Map(DocK -> pres)
    )
  }
} 
Example 12
Source File: NodeToJsonSpec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import catalysts.Platform
import eu.timepit.crjdt.core._
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.circe.testUtil._
import io.circe._
import io.circe.testing.ArbitraryInstances
import org.scalacheck.Properties
import org.scalacheck.Prop._
import eu.timepit.crjdt.circe.syntax._
import eu.timepit.crjdt.circe.RegNodeConflictResolver.LWW
import eu.timepit.crjdt.core.Key.StrK
import eu.timepit.crjdt.core.Node.MapNode

object NodeToJsonSpec
    extends Properties("NodeToJsonSpec")
    with ArbitraryInstances {
  // avoid Scala.js test failure at travis CI
  override protected def maxJsonArraySize: Int = if (Platform.isJs) 3 else 10

  override protected def maxJsonDepth: Int = if (Platform.isJs) 2 else 5

  override protected def maxJsonObjectSize: Int = if (Platform.isJs) 1 else 10

  // filter out numbers BigDecimal (and Val.Num) cannot handle
  override def transformJsonNumber(n: JsonNumber): JsonNumber =
    if (
      n.toDouble == -0.0 || n.toDouble == Double.PositiveInfinity || n.toDouble == Double.NegativeInfinity
    )
      JsonNumber.fromDecimalStringUnsafe("0.0")
    else n

  property("root document to JSON") = forAllNoShrink { (obj: JsonObject) =>
    val json = Json.fromJsonObject(obj)
    val commands = assignObjectFieldsCmds(doc, obj)
    val document = Replica.empty("").applyCmds(commands.toList).document
    document.toJson ?= json
  }

  property("Node including ListNode and RegNode to JSON") = forAllNoShrink {
    (obj: JsonObject) =>
      val commands = assignObjectFieldsCmds(doc, obj)
      val document = Replica.empty("").applyCmds(commands.toList).document
      val childNodes: Map[String, Node] = document
        .findChild(TypeTag.MapT(Key.DocK))
        .collect {
          case node: MapNode =>
            node.children.collect {
              case (TypeTag.MapT(StrK(key)), value)  => (key, value)
              case (TypeTag.ListT(StrK(key)), value) => (key, value)
              case (TypeTag.RegT(StrK(key)), value)  => (key, value)
            }
        }
        .getOrElse(Map.empty)
      childNodes.mapValues(_.toJson) ?= obj.toMap
  }
} 
Example 13
Source File: MonoidSpec.scala    From tutorial-cat   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.tutorial.cat.monoid

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

import scala.reflect._

class IntMonoidSpec extends MonoidSpec[Int](MonoidInstances.intMonoid)
class StringMonoidSpec extends MonoidSpec[String](MonoidInstances.stringMonoid)

abstract class MonoidSpec[A: ClassTag](monoid: Monoid[A])(implicit arbitrary: Arbitrary[A]) extends Properties(s"Monoid for ${classTag[A]}") {

  val id = monoid.identity

  // n o id == id o n == n
  property("identity") = forAll { n: A =>
    monoid.compose(n, id) == n &&
    monoid.compose(id, n) == n
  }

  // forall x, y => x o y
  property("composition") = forAll { (x: A, y: A) =>
    monoid.compose(x, y).isInstanceOf[A]
  }

  // x o (y o z) == (x o y) o z
  property("associativity") = forAll { (x: A, y: A, z: A) =>
    val xY = monoid.compose(x,y)
    val yZ = monoid.compose(y,z)
    monoid.compose(xY, z) == monoid.compose(x, yZ)
  }
} 
Example 14
Source File: NodeToJsonFigure4Spec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.Replica
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.circe.syntax._
import eu.timepit.crjdt.circe.testUtil.{converged, diverged, merge}
import io.circe.Json
import org.scalacheck.Prop._
import org.scalacheck.Properties

object NodeToJsonFigure4Spec extends Properties("NodeToJsonFigure4Spec") {
  val todo = doc.downField("todo").iter
  val cmd = todo.insert(`{}`) `;`
    (todo.next.downField("title") := "buy milk") `;`
    (todo.next.downField("done") := false)

  val p0 = Replica.empty("p").applyCmd(cmd)
  val q0 = merge(Replica.empty("q"), p0)

  property("initial state") = secure {
    converged(p0, q0)
  }

  val p1 = p0.applyCmd(todo.next.delete)
  val q1 = q0.applyCmd(todo.next.downField("done") := true)

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("toJson with last-writer-wins conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.LWW
    p2.document.toJson ?= Json.obj(
      "todo" -> Json.arr(
        Json.obj(
          "done" -> Json.True
        )
      )
    )
  }

  property("toJson with preserve-all-as-array conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.PreserveAllAsArray
    p2.document.toJson ?= Json.obj(
      "todo" -> Json.arr(
        Json.obj(
          "done" -> Json.arr(Json.True)
        )
      )
    )
  }
} 
Example 15
Source File: NodeToJsonFigure2Spec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.Replica
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.circe.syntax._
import eu.timepit.crjdt.circe.testUtil.{converged, diverged, merge}
import io.circe.Json
import org.scalacheck.Prop._
import org.scalacheck.Properties

object NodeToJsonFigure2Spec extends Properties("NodeToJsonFigure2Spec") {
  val colors = doc.downField("colors")
  val p0 =
    Replica.empty("p").applyCmd(colors.downField("blue") := "#0000ff")
  val q0 = merge(Replica.empty("q"), p0)

  property("initial state") = secure {
    converged(p0, q0)
  }

  val p1 = p0.applyCmd(colors.downField("red") := "#ff0000")
  val q1 = q0
    .applyCmd(colors := `{}`)
    .applyCmd(colors.downField("green") := "#00ff00")

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("toJson with last-writer-wins conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.LWW
    p2.document.toJson ?= Json.obj(
      "colors" -> Json.obj(
        "red" -> Json.fromString("#ff0000"),
        "green" -> Json.fromString("#00ff00")
      )
    )
  }

  property("toJson with preserve-all-as-array conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.PreserveAllAsArray
    p2.document.toJson ?= Json.obj(
      "colors" -> Json.obj(
        "red" -> Json.arr(Json.fromString("#ff0000")),
        "green" -> Json.arr(Json.fromString("#00ff00"))
      )
    )
  }
} 
Example 16
Source File: NodeToJsonDeleteSpec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import org.scalacheck.Properties
import org.scalacheck.Prop._
import eu.timepit.crjdt.circe.RegNodeConflictResolver.LWW
import eu.timepit.crjdt.circe.syntax._
import eu.timepit.crjdt.core.Replica
import eu.timepit.crjdt.core.syntax._
import io.circe.Json

object NodeToJsonDeleteSpec extends Properties("NodeToJsonDeleteSpec") {
  // fix bug #19
  property("delete list items") = secure {
    val list = doc.downField("list")
    val p = Replica
      .empty("p")
      .applyCmd(list := `[]`)
      .applyCmd(list.iter.insert("1"))
      .applyCmd(list.iter.next.insert("2"))
      .applyCmd(list.iter.next.delete)
    p.document.toJson ?= Json.obj(
      "list" -> Json.arr(Json.fromString("2"))
    )
  }
} 
Example 17
Source File: NodeToJsonFigure1Spec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.Replica
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.circe.testUtil.{converged, diverged, merge}
import eu.timepit.crjdt.circe.syntax._
import io.circe.Json
import org.scalacheck.Prop._
import org.scalacheck.Properties

object NodeToJsonFigure1Spec extends Properties("NodeToJsonFigure1Spec") {
  val p0 = Replica.empty("p").applyCmd(doc.downField("key") := "A")
  val q0 = merge(Replica.empty("q"), p0)

  property("initial state") = secure {
    converged(p0, q0)
  }

  val p1 = p0.applyCmd(doc.downField("key") := "B")
  val q1 = q0.applyCmd(doc.downField("key") := "C")

  property("divergence") = secure {
    diverged(p1, q1)
  }

  val p2 = merge(p1, q1)
  val q2 = merge(q1, p1)

  property("convergence") = secure {
    converged(p2, q2)
  }

  property("toJson with last-writer-wins conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.LWW
    p2.document.toJson ?= Json.obj(
      "key" -> Json.fromString("C")
    )
  }

  property("toJson with preserve-all-as-array conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.PreserveAllAsArray
    p2.document.toJson ?= Json.obj(
      "key" -> Json.arr(List("B", "C").map(Json.fromString): _*)
    )
  }
} 
Example 18
Source File: NodeToJsonFigure6Spec.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.Replica
import eu.timepit.crjdt.core.syntax._
import eu.timepit.crjdt.circe.syntax._
import io.circe.Json
import org.scalacheck.Prop._
import org.scalacheck.Properties

object NodeToJsonFigure6Spec extends Properties("NodeToJsonFigure6Spec") {
  val list = v("list")
  val eggs = v("eggs")
  val cmd = (doc := `{}`) `;`
    (let(list) = doc.downField("shopping").iter) `;`
    list.insert("eggs") `;`
    (let(eggs) = list.next) `;`
    eggs.insert("milk") `;`
    list.insert("cheese")

  val document = Replica.empty("").applyCmd(cmd).document

  property("toJson with last-writer-wins conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.LWW
    document.toJson ?= Json.obj(
      "shopping" -> Json.arr(
        List("cheese", "eggs", "milk").map(Json.fromString): _*
      )
    )
  }

  property("toJson with preserve-all-as-array conflict resolution") = secure {
    implicit val resolver = RegNodeConflictResolver.PreserveAllAsArray
    document.toJson ?= Json.obj(
      "shopping" -> Json.arr(
        List("cheese", "eggs", "milk")
          .map(v => Json.arr(Json.fromString(v))): _*
      )
    )
  }
} 
Example 19
Source File: PeopleDecodersSpec.scala    From finch-template   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.redbubble.finchtemplate.backends.people

import com.redbubble.finchtemplate.model.Person
import com.redbubble.finchtemplate.util.spec.{FinchTemplateGenerators, SpecHelper}
import org.scalacheck.Prop._
import org.scalacheck.Properties
import org.specs2.mutable.Specification

final class PeopleDecodersSpec extends Specification with SpecHelper with FinchTemplateGenerators with PeopleApiJson {
  val decodingProp = new Properties("People decoding") {
    property("decoding a single person") = forAll(genPerson) { (person: Person) =>
      val json = personJson(person)
      val decoded = decode(json)(PeopleDecoders.personDecoder)
      decoded must beRight(person)
    }

    property("decoding a list of people") = forAll(genPerson) { (person: Person) =>
      val json = peopleJson(Seq(person))
      val decoded = decode(json)(PeopleDecoders.peopleDecoder)
      decoded must beRight(Seq(person))
    }
  }

  s2"Decoding people responses$decodingProp"
} 
Example 20
Source File: PeopleEncodersSpec.scala    From finch-template   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.redbubble.finchtemplate.api.v1.people

import com.redbubble.finchtemplate.model.Person
import com.redbubble.finchtemplate.util.spec.{FinchTemplateGenerators, SpecHelper}
import com.redbubble.util.http.ResponseOps.jsonBuf
import com.redbubble.util.json.JsonPrinter._
import io.circe.syntax._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import org.specs2.mutable.Specification

final class PeopleEncodersSpec extends Specification with SpecHelper with FinchTemplateGenerators {

  private implicit val personEncoder = PeopleEncoders.personEncoder

  val encodePersonProp = new Properties("Person encoding") {
    property("encode") = forAll(genPerson) { (p: Person) =>
      val expected = parse(s"""{"person":{"name":"${p.name}","birth_year":"${p.birthYear}","hair_colour":"${p.hairColour}"}}""")
      val actual = parse(jsonToString(p.asJson))
      expected must beEqualTo(actual)
    }
  }

  s2"Person can be encoded into JSON$encodePersonProp"

  private implicit val personResponseEncoder = PeopleEncoders.personResponseEncode

  val personResponseProp = new Properties("Person JSON response encoding") {
    property("encode") = forAll(genPerson) { (p: Person) =>
      val expected = parse(s"""{"data":{"person":{"name":"${p.name}","birth_year":"${p.birthYear}","hair_colour":"${p.hairColour}"}}}""")
      val actual = parse(jsonBuf(p))
      expected must beEqualTo(actual)
    }
  }

  s2"Person can be encoded into a response JSON$personResponseProp"

  private implicit val peopleEncoder = PeopleEncoders.peopleEncoder

  val encodePeopleProp = new Properties("People encoding") {
    property("encode") = forAll(genPerson) { (p: Person) =>
      val expected = parse(s"""{"people":[{"name":"${p.name}","birth_year":"${p.birthYear}","hair_colour":"${p.hairColour}"}]}""")
      val actual = parse(jsonToString(Seq(p).asJson))
      expected must beEqualTo(actual)
    }
  }

  s2"People can be encoded into JSON$encodePeopleProp"

  private implicit val peopleResponseEncoder = PeopleEncoders.peopleResponseEncode

  val peopleResponseProp = new Properties("People JSON response encoding") {
    property("encode") = forAll(genPerson) { (p: Person) =>
      val expected = parse(s"""{"data":{"people":[{"name":"${p.name}","birth_year":"${p.birthYear}","hair_colour":"${p.hairColour}"}]}}""")
      val actual = parse(jsonBuf(Seq(p)))
      expected must beEqualTo(actual)
    }
  }

  s2"People can be encoded into a response JSON$peopleResponseProp"
} 
Example 21
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 22
Source File: ApplicativeSpec.scala    From tutorial-cat   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.tutorial.cat.applicative

import com.danielasfregola.tutorial.cat.ArbitraryIntInstances._
import ApplicativeInstances._
import com.danielasfregola.tutorial.cat.functor.FunctorProperties
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Properties}

import scala.reflect._

class MaybeApplicativeSpec extends ApplicativeSpec(maybeApplicative)
class ZeroOrMoreApplicativeSpec extends ApplicativeSpec(zeroOrMoreApplicative)

abstract class ApplicativeSpec[Box[_]](val applicative: Applicative[Box])(implicit val arbitrary: Arbitrary[Box[Int]],
                                                                          tag: ClassTag[Box[_]])
    extends Properties(s"Applicative for $tag")
    with ApplicativeProperties[Box]

trait ApplicativeProperties[Box[_]] extends FunctorProperties[Box] { self: Properties =>

  val applicative: Applicative[Box]
  import applicative._

  val functor = applicative

  val pureIdentity: Box[A => A] = pure(identity)
  val pureF = pure(f)
  val toPureA = { a: A => pure(a)}

  // ap(id)(a) == a
  property("identity") = forAll { box: Box[A] =>
    ap(pureIdentity)(box) == box
  }

  // ap(pure(f))(pure(a)) == pure(f(a))
  property("homorphism") = forAll { a: A =>
    ap(pureF)(pure(a)) == pure(f(a))
  }

  // {x => pure(x)}(a) == pure(a)
  property("interchange") = forAll { a: A =>
    toPureA(a) == pure(a)
  }

  // pure(h o g o f) == ap(pure(h o g))(pure(f(a)))
  property("composition") = forAll { a: A =>
    val gH = g andThen h
    val fGH = f andThen gH
    val pureGH = pure(gH)
    val pureFA = pure(f(a))
    pure(fGH(a)) == ap(pureGH)(pureFA)
  }
} 
Example 23
Source File: FunctorSpec.scala    From tutorial-cat   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.tutorial.cat.functor

import com.danielasfregola.tutorial.cat._
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Properties}
import FunctorInstances._
import ArbitraryIntInstances._

import scala.reflect._

class MaybeFunctorSpec extends FunctorSpec(maybeFunctor)
class ZeroOrMoreFunctorSpec extends FunctorSpec(zeroOrMoreFunctor)

abstract class FunctorSpec[Box[_]](val functor: Functor[Box])(implicit val arbitrary: Arbitrary[Box[Int]],
                                                              tag: ClassTag[Box[_]])
    extends Properties(s"Functor for $tag")
    with FunctorProperties[Box]

trait FunctorProperties[Box[_]] extends SimpleCategoryUtils { self: Properties =>

  val functor: Functor[Box]
  import functor._

  implicit def arbitrary: Arbitrary[Box[A]]

  lazy val mapF: Box[A] => Box[B] = map(_)(f)
  lazy val mapG: Box[B] => Box[C] = map(_)(g)
  lazy val mapH: Box[C] => Box[D] = map(_)(h)

  // map_id == id
  property("identity") = forAll { box: Box[A] =>
    map(box)(identity) == box
  }

  // map_(g o f) == (map_g) o (map_f)
  property("composition") = forAll { boxA: Box[A] =>
    val fG = f andThen g
    val mapFG: Box[A] => Box[C] = map(_)(fG)
    mapFG(boxA) == (mapF andThen mapG)(boxA)
  }

  // map_(h o g) o map_f == map_h o map_(g o f)
  property("associativity") = forAll { boxA: Box[A] =>
    val fG = f andThen g
    val mapFG: Box[A] => Box[C] = map(_)(fG)
    val gH = g andThen h
    val mapGH: Box[B] => Box[D] = map(_)(gH)

    (mapF andThen mapGH)(boxA) == (mapFG andThen mapH)(boxA)
  }
} 
Example 24
Source File: StringSpecification.scala    From spark-tools   with Apache License 2.0 5 votes vote down vote up
package compare

import io.univalence.utils.StringUtils
import org.scalacheck.Gen
import org.scalacheck.Properties
import org.scalacheck.Prop._

object StringSpecification extends Properties("StringUtils") {

  private val asciiLetter: Gen[Char] =
    Gen.oneOf((0 to 127).map(_.toChar).filter(_.isLetterOrDigit))

  private val asciiLetterString: Gen[String] =
    Gen.listOf(asciiLetter).map(_.mkString)

  def isAsciiLetter(c: Char): Boolean = c.isLetter && c <= 127

  property("letterPairs") = forAll(asciiLetterString) { a: String =>
    (a.size > 1) ==>
      (StringUtils
        .letterPairs(a)
        .map(_.head)
        .mkString == a.dropRight(1))
  }

  property("compareStrings should be 1 for identical strings") = forAll { a: String =>
    StringUtils.compareStrings(a, a) == 1
  }

  property("compareStrings") = forAll { (a: String, b: String) =>
    val result = StringUtils.compareStrings(a, b)

    (a != b) ==> (result < 1 && result >= 0)
  }

} 
Example 25
Source File: ModelScalaCheck.scala    From spark-tools   with Apache License 2.0 5 votes vote down vote up
package io.univalence

import io.univalence.centrifuge.Result
import io.univalence.centrifuge._
import org.scalacheck.Prop.forAll
import org.scalacheck.Prop.all
import org.scalacheck.Properties

object ModelScalaCheck extends Properties("String") {

  property("isNotPure") = forAll { a: String =>
    all(
      !Result(Some(a), Vector(Annotation("msg", Some("oF"), Vector("fF"), false, 1))).isPure,
      !Result(None, Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1))).isPure,
      !Result(Some(a), Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1))).isPure,
      !Result(Some("msg"), Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1))).isPure
    )
  }
  property("isPure") = forAll { a: String =>
    Result(Some(a), Vector()).isPure
  }
  property("filter") = forAll { a: String =>
    Result(Some(a), Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1)))
      .filter(_.contains(a)) == Result(
      Some(a),
      Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1))
    )
  }
  property("map") = forAll { a: String =>
    all(
      Result(Some(a), Vector(Annotation("msg", Some("oF"), Vector("fF"), false, 1)))
        .map(_.toString) == Result(
        Some(a),
        Vector(Annotation("msg", Some("oF"), Vector("fF"), false, 1))
      ),
      Result(Some(a), Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1)))
        .map(_.toString) == Result(
        Some(a),
        Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1))
      ),
      Result(Some("msg"), Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1))) == Result(
        Some("msg"),
        Vector(Annotation(a, Some("oF"), Vector("fF"), false, 1))
      )
    )
  }

} 
Example 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
Source File: TypeableSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.shapeless.typeable

import eu.timepit.refined.W
import eu.timepit.refined.api.{Refined, RefinedTypeOps}
import eu.timepit.refined.string.MatchesRegex
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.Typeable

class TypeableSpec extends Properties("shapeless") {

  property("Typeable cast success") = secure {
    val value: PosInt = PosInt.unsafeFrom(5)
    typeableCast[PosInt](5) ?= Some(value)
  }

  property("Typeable cast fail") = secure {
    typeableCast[PosInt](0) ?= None
  }

  property("Typeable describe") = secure {
    typeableDescribe[PosInt] ?= "Refined[Int, Greater[_0]]"
  }

  property("Typeable cast success string regex") = secure {
    type Word = String Refined MatchesRegex[W.`"[a-zA-Z]*"`.T]
    object Word extends RefinedTypeOps[Word, String]
    val value: Word = Word.unsafeFrom("AlloweD")
    typeableCast[Word]("AlloweD") ?= Some(value)
  }

  property("Typeable cast fail string regex") = secure {
    type Word = String Refined MatchesRegex[W.`"[a-zA-Z]*"`.T]
    typeableCast[Word]("Not Allowed") ?= None
  }

  property("Typeable string regex describe") = secure {
    type Word = String Refined MatchesRegex[W.`"[a-zA-Z]*"`.T]
    typeableDescribe[Word] ?= """Refined[String, MatchesRegex[String([a-zA-Z]*)]]"""
  }

  private def typeableDescribe[T](implicit T: Typeable[T]): String = T.describe

  private def typeableCast[T](value: Any)(implicit T: Typeable[T]): Option[T] = T.cast(value)

} 
Example 35
Source File: RefTypeSpecScalazContravariant.scala    From refined   with MIT License 5 votes vote down vote up
// Copyright: 2018 Sam Halliday
// License: https://opensource.org/licenses/MIT

package eu.timepit.refined.scalaz

import _root_.scalaz.{@@, Contravariant}
import eu.timepit.refined.api._
import eu.timepit.refined.collection._
import org.scalacheck.Prop._
import org.scalacheck.Properties

trait Encoder[A] {
  def encode(a: A): String
}
object Encoder {
  @inline def apply[A](implicit A: Encoder[A]): Encoder[A] = A
  @inline def instance[A](f: A => String): Encoder[A] = new Encoder[A] {
    override def encode(a: A): String = f(a)
  }

  implicit val string: Encoder[String] = instance(identity)

  implicit val contravariant: Contravariant[Encoder] =
    new Contravariant[Encoder] {
      override def contramap[A, B](fa: Encoder[A])(f: B => A): Encoder[B] =
        instance(b => fa.encode(f(b)))
    }
}

class RefTypeSpecScalazContravariant extends Properties("scalaz.Contravariant") {
  // annoying that this import is needed!
  // https://github.com/scala/bug/issues/10753#issuecomment-369592913
  import Encoder._
  import eu.timepit.refined.scalaz.derivation._

  property("Refined via scalaz.Contravariant") = secure {
    import eu.timepit.refined.auto._

    val x: String Refined NonEmpty = "hello world"

    Encoder[String Refined NonEmpty].encode(x) == "hello world"
  }

  property("@@ via scalaz.Contravariant") = secure {
    import eu.timepit.refined.scalaz.auto._

    val x: String @@ NonEmpty = "hello world"

    Encoder[String @@ NonEmpty].encode(x) == "hello world"
  }

} 
Example 36
Source File: RefTypeSpecScalazMonadError.scala    From refined   with MIT License 5 votes vote down vote up
// Copyright: 2018 Sam Halliday
// License: https://opensource.org/licenses/MIT

package eu.timepit.refined.scalaz

import _root_.scalaz.{@@, \/, MonadError, ReaderT}
import _root_.scalaz.Isomorphism.{<~>, IsoFunctorTemplate}
import _root_.scalaz.syntax.either._
import eu.timepit.refined.api._
import eu.timepit.refined.collection._
import org.scalacheck.Prop._
import org.scalacheck.Properties

trait Decoder[A] {
  def decode(s: String): String \/ A
}
object Decoder {
  @inline def apply[A](implicit A: Decoder[A]): Decoder[A] = A
  @inline def instance[A](f: String => String \/ A): Decoder[A] =
    new Decoder[A] {
      override def decode(s: String): String \/ A = f(s)
    }

  implicit val string: Decoder[String] = instance(_.right)

  type Out[a] = String \/ a
  type MT[a] = ReaderT[Out, String, a]
  implicit val isoReaderT: Decoder <~> MT =
    new IsoFunctorTemplate[Decoder, MT] {
      def from[A](fa: MT[A]) = instance(fa.run(_))
      def to[A](fa: Decoder[A]) = ReaderT[Out, String, A](fa.decode)
    }
  implicit def monad: MonadError[Decoder, String] =
    MonadError.fromIso(isoReaderT)
}

class RefTypeSpecScalazMonadError extends Properties("scalaz.Contravariant") {
  // annoying that this import is needed!
  // https://github.com/scala/bug/issues/10753#issuecomment-369592913
  import Decoder.monad
  import eu.timepit.refined.scalaz.derivation._

  property("Refined via scalaz.MonadError[?, String]") = secure {
    val decoder = Decoder[String Refined NonEmpty]
    decoder.decode("").isLeft && decoder.decode("hello world").isRight
  }

  property("@@ via scalaz.MonadError[?, String]") = secure {
    val decoder = Decoder[String @@ NonEmpty]
    decoder.decode("").isLeft && decoder.decode("hello world").isRight
  }

} 
Example 37
Source File: ScalazSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalaz

import eu.timepit.refined.W
import eu.timepit.refined.api.{Refined, RefinedTypeOps}
import eu.timepit.refined.numeric.Interval
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scalaz.Validation

class ScalazSpec extends Properties("scalaz") {
  property("Validate when Valid") = secure {
    import syntax._
    PosInt.validate(5) ?= Validation.success(PosInt.unsafeFrom(5))
  }

  property("Validate when Invalid") = secure {
    import syntax._
    PosInt.validate(0) ?= Validation.failureNel("Predicate failed: (0 > 0).")
  }

  property("validate without import") = secure {
    type OneToTen = Int Refined Interval.Closed[W.`1`.T, W.`10`.T]
    object OneToTen extends RefinedTypeOps[OneToTen, Int] with ScalazRefinedTypeOpsSyntax
    OneToTen.validate(5) ?= Validation.success(OneToTen.unsafeFrom(5))
  }
} 
Example 38
Source File: RefTypeConfigConvertSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.pureconfig

import com.typesafe.config.ConfigValueType
import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import org.scalacheck.Prop._
import org.scalacheck.Properties
import pureconfig._
import pureconfig.error.{CannotConvert, ConfigReaderFailures, ConvertFailure, WrongType}
import pureconfig.generic.auto._

class RefTypeConfigConvertSpec extends Properties("RefTypeConfigConvert") {

  type PosInt = Int Refined Positive
  case class Config(value: PosInt)

  property("load success") = secure {
    loadConfigWithValue("1") ?=
      Right(Config(1))
  }

  property("load failure (predicate)") = secure {
    val expected1 = Left(
      ConfigReaderFailures(
        ConvertFailure(
          reason = CannotConvert(
            value = "0",
            toType =
              "eu.timepit.refined.api.Refined[Int,eu.timepit.refined.numeric.Greater[shapeless.nat._0]]",
            because = "Predicate failed: (0 > 0)."
          ),
          location = None,
          path = "value"
        )
      )
    )

    // Allow "scala.Int" instead of just "Int" in the toType parameter.
    // For some reason Scala 2.12 with sbt 1.1.2 uses the former.
    val expected2 = Left(
      ConfigReaderFailures(
        ConvertFailure(
          reason = CannotConvert(
            value = "0",
            toType =
              "eu.timepit.refined.api.Refined[scala.Int,eu.timepit.refined.numeric.Greater[shapeless.nat._0]]",
            because = "Predicate failed: (0 > 0)."
          ),
          location = None,
          path = "value"
        )
      )
    )

    val actual = loadConfigWithValue("0")
    (actual ?= expected1) ||
    (actual ?= expected2)
  }

  property("load failure (wrong type)") = secure {
    loadConfigWithValue("abc") =?
      Left(
        ConfigReaderFailures(
          ConvertFailure(
            reason = WrongType(
              foundType = ConfigValueType.STRING,
              expectedTypes = Set(ConfigValueType.NUMBER)
            ),
            location = None,
            path = "value"
          )
        )
      )
  }

  property("roundtrip success") = secure {
    val config = Config(1)
    val configValue = ConfigConvert[Config].to(config)
    ConfigConvert[Config].from(configValue) ?=
      Right(config)
  }

  def loadConfigWithValue(value: String): Either[ConfigReaderFailures, Config] =
    ConfigSource.string(s"value = $value").load[Config]
} 
Example 39
Source File: EvalValidateSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.Validate
import eu.timepit.refined.eval.Eval
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scala.tools.reflect.ToolBoxError
import shapeless.test.illTyped

class EvalValidateSpec extends Properties("EvalValidate") {

  type IsEven = Eval[W.`"(x: Int) => x % 2 == 0"`.T]

  property("Eval.isValid") = {
    val v = Validate[Int, IsEven]
    forAll((i: Int) => v.isValid(i) ?= (i % 2 == 0))
  }

  property("Eval.showExpr") = secure {
    Validate[Int, IsEven].showExpr(0) ?= "(x: Int) => x % 2 == 0"
  }

  property("Eval.refineMV") = wellTyped {
    refineMV[IsEven](2)
    illTyped("refineMV[IsEven](3)", "Predicate.*fail.*")
  }

  property("Eval.refineV.no parameter type") = {
    val v = Validate[List[Int], Eval[W.`"_.headOption.fold(false)(_ > 0)"`.T]]
    forAll((l: List[Int]) => v.isValid(l) ?= l.headOption.fold(false)(_ > 0))
  }

  property("Eval.refineMV.scope") = wellTyped {
    val two = 2
    illTyped(
      """refineMV[Eval[W.`"(x: Int) => x >= two"`.T]](2)""",
      "exception during macro expansion.*"
    )
  }

  property("Eval.refineV.scope") = secure {
    val two = 2
    throws(classOf[ToolBoxError])(refineV[Eval[W.`"(x: Int) => x >= two"`.T]](two))
  }
} 
Example 40
Source File: RefTypeRedSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scopt

import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scopt._

class RefTypeReadSpec extends Properties("RefTypeRead") {

  type PosInt = Int Refined Positive
  case class Config(foo: PosInt)

  val parser = new OptionParser[Config]("tests") {
    opt[PosInt]('f', "foo")
      .action((x, c) => c.copy(foo = x))
      .text("foo is a positive integer property")
  }

  property("load success") = secure {
    loadConfigWithValue("10") =?
      Some(Config(10))
  }

  property("load failure (predicate)") = secure {
    loadConfigWithValue("0") =?
      None
  }

  property("load failure (wrong type)") = secure {
    loadConfigWithValue("abc") =?
      None
  }

  def loadConfigWithValue(value: String): Option[Config] =
    parser.parse(Array("-f", value), Config(1))
} 
Example 41
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 42
Source File: CollectionArbitrarySpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.W
import eu.timepit.refined.api.Refined
import eu.timepit.refined.collection.{MaxSize, NonEmpty, Size}
import eu.timepit.refined.numeric.Interval
import eu.timepit.refined.scalacheck.collection._
import eu.timepit.refined.scalacheck.numeric._
import org.scalacheck.Properties
import shapeless.nat._

class CollectionArbitrarySpec extends Properties("CollectionArbitrary") {

  property("List[String] Refined MaxSize[42]") =
    checkArbitraryRefinedType[List[String] Refined MaxSize[W.`42`.T]]

  property("List[String] Refined MaxSize[_13]") =
    checkArbitraryRefinedType[List[String] Refined MaxSize[_13]]

  property("List[Int] Refined NonEmpty") = checkArbitraryRefinedType[List[Int] Refined NonEmpty]

  property("Vector[Int] Refined MaxSize[23]") =
    checkArbitraryRefinedType[Vector[Int] Refined MaxSize[W.`23`.T]]

  property("Vector[Double] Refined NonEmpty") =
    checkArbitraryRefinedType[Vector[Double] Refined NonEmpty]

  property("Size[Interval.Closed[23, 42]]") =
    checkArbitraryRefinedType[List[Char] Refined Size[Interval.Closed[W.`23`.T, W.`42`.T]]]
} 
Example 43
Source File: StringArbitrarySpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.W
import eu.timepit.refined.api.Refined
import eu.timepit.refined.collection.{MaxSize, Size}
import eu.timepit.refined.generic.Equal
import eu.timepit.refined.scalacheck.generic._
import eu.timepit.refined.scalacheck.numeric._
import eu.timepit.refined.scalacheck.string._
import eu.timepit.refined.string._
import eu.timepit.refined.types.string.{
  FiniteString,
  NonEmptyFiniteString,
  NonEmptyString,
  TrimmedString
}
import org.scalacheck.Properties

class StringArbitrarySpec extends Properties("StringArbitrary") {

  property("EndsWith[S]") = checkArbitraryRefinedType[String Refined EndsWith[W.`"abc"`.T]]

  property("StartsWith[S]") = checkArbitraryRefinedType[String Refined StartsWith[W.`"abc"`.T]]

  property("NonEmptyString") = checkArbitraryRefinedType[NonEmptyString]

  property("TrimmedString") = checkArbitraryRefinedType[TrimmedString]

  property("MaxSize[16]") = checkArbitraryRefinedType[String Refined MaxSize[W.`16`.T]]

  property("FiniteString[10]") = checkArbitraryRefinedType[FiniteString[W.`10`.T]]

  property("Size[Equal[8]]") = checkArbitraryRefinedType[String Refined Size[Equal[W.`8`.T]]]

  property("NonEmptyFiniteString[10]") = checkArbitraryRefinedType[NonEmptyFiniteString[W.`10`.T]]

  property("Uuid") = checkArbitraryRefinedType[String Refined Uuid]
} 
Example 44
Source File: CharArbitrarySpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.W
import eu.timepit.refined.api.Refined
import eu.timepit.refined.boolean.Or
import eu.timepit.refined.char._
import eu.timepit.refined.numeric.Interval
import eu.timepit.refined.scalacheck.boolean._
import eu.timepit.refined.scalacheck.char._
import eu.timepit.refined.scalacheck.numeric._
import eu.timepit.refined.types.char.{LowerCaseChar, UpperCaseChar}
import org.scalacheck.Properties

class CharArbitrarySpec extends Properties("CharArbitrary") {

  property("Digit") = checkArbitraryRefinedType[Char Refined Digit]

  property("Letter") = checkArbitraryRefinedType[Char Refined Letter]

  property("LowerCaseChar") = checkArbitraryRefinedType[LowerCaseChar]

  property("UpperCaseChar") = checkArbitraryRefinedType[UpperCaseChar]

  property("Whitespace") = checkArbitraryRefinedType[Char Refined Whitespace]

  property("LetterOrDigit") = checkArbitraryRefinedType[Char Refined LetterOrDigit]

  property("HexDigit") = {
    type HexDigit = Digit Or Interval.Closed[W.`'a'`.T, W.`'f'`.T]
    checkArbitraryRefinedType[Char Refined HexDigit]
  }
} 
Example 45
Source File: StringValidateSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.jsonpath

import eu.timepit.refined.TestUtils._
import eu.timepit.refined.jsonpath.string.JSONPath
import org.scalacheck.Prop._
import org.scalacheck.Properties

class StringValidateSpec extends Properties("JSONPathStringValidate") {

  property("JSONPath is valid") = secure {
    isValid[JSONPath]("$") && isValid[JSONPath]("@")
  }

  property("Illegal character at position 1 expected '.' or '[") = secure {
    showResult[JSONPath]("$X") ?= "JSONPath predicate failed: Illegal character at position 1 expected '.' or '["
  }

  property("Path must not end with a '.' or '..'") = secure {
    showResult[JSONPath]("$.") ?= "JSONPath predicate failed: Path must not end with a '.' or '..'"
  }
} 
Example 46
Source File: ByteVectorValidateSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scodec

import eu.timepit.refined.TestUtils._
import eu.timepit.refined.W
import eu.timepit.refined.collection.Size
import eu.timepit.refined.generic.Equal
import eu.timepit.refined.numeric.Greater
import eu.timepit.refined.scodec.byteVector._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

class ByteVectorValidateSpec extends Properties("ByteVectorValidate") {

  property("Size.isValid") = forAll { bytes: Array[Byte] =>
    val bv = ByteVector(bytes)
    isValid[Size[Greater[W.`5L`.T]]](bv) ?= (bv.size > 5L)
  }

  property("Size.showExpr") = secure {
    showExpr[Size[Equal[W.`5L`.T]]](ByteVector.fromValidHex("0xdeadbeef")) ?= "(4 == 5)"
  }

  property("Size.showResult") = secure {
    showResult[Size[Equal[W.`5L`.T]]](ByteVector.fromValidHex("0xdeadbeef")) ?=
      "Predicate taking size(ByteVector(4 bytes, 0xdeadbeef)) = 4 failed: Predicate failed: (4 == 5)."
  }

} 
Example 47
Source File: RefTypeCodecSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scodec

import eu.timepit.refined.TestUtils._
import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec._
import scodec.bits._
import scodec.codecs.int8
import shapeless.test.illTyped

class RefTypeCodecSpec extends Properties("RefTypeCodec") {

  type PosInt = Int Refined Positive
  implicit val intCodec = int8

  property("decode success") = secure {
    Codec[PosInt].decode(bin"00000101") ?=
      Attempt.successful(DecodeResult(5: PosInt, BitVector.empty))
  }

  property("decode failure") = secure {
    Codec[PosInt].decode(bin"10000101") ?=
      Attempt.failure(Err("Predicate failed: (-123 > 0)."))
  }

  property("encode success") = secure {
    Codec[PosInt].encode(5) ?=
      Attempt.successful(bin"00000101")
  }

  property("encode failure") = wellTyped {
    illTyped("""Codec[PosInt].encode(-5)""", "Predicate failed.*")
  }

  property("sizeBound") = secure {
    Codec[PosInt].sizeBound ?= intCodec.sizeBound
  }
} 
Example 48
Source File: StringUtilSpecJvm.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.auto._
import eu.timepit.refined.util.string._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.test.illTyped

class StringUtilSpecJvm extends Properties("util.string") {

  property("url success") = secure {
    url("http://example.com").toString ?= new java.net.URL("http://example.com").toString
  }

  property("url failure") = secure {
    illTyped("""url("http//example.com")""", "Url predicate failed.*")
    true
  }

  property("xml success") = secure {
    xml("<root></root>") == scala.xml.XML.loadString("<root></root>")
  }

  property("xml failure") = secure {
    illTyped("""xml("<root>")""", "Xml predicate failed.*")
    true
  }

  property("xpath success") = secure {
    xpath("A//B/*[1]")
    true
  }

  property("xpath failure") = secure {
    illTyped("""xpath("A//B/*[1")""", "XPath predicate failed.*")
    true
  }
} 
Example 49
Source File: StringValidateSpecJvm.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils._
import eu.timepit.refined.string._
import org.scalacheck.Prop._
import org.scalacheck.Properties

class StringValidateSpecJvm extends Properties("StringValidate") {

  property("Regex.showResult") = secure {
    showResult[Regex]("(a|b").take(56) ?=
      """Regex predicate failed: Unclosed group near index 4
        |(a|b""".stripMargin
  }

  property("Url.isValid") = secure {
    isValid[Url]("http://example.com")
  }

  property("Url.showResult") = secure {
    showResult[Url]("htp://example.com") ?= "Url predicate failed: unknown protocol: htp"
  }

  property("Xml.isValid") = secure {
    isValid[Xml]("<root></root>")
  }

  property("Xml.showResult") = secure {
    showResult[Xml]("<root>") ?=
      "Xml predicate failed: XML document structures must start and end within the same entity."
  }

  property("XPath.isValid") = secure {
    isValid[XPath]("A//B/*[1]")
  }

  property("XPath.showResult") = secure {
    showResult[XPath]("A//B/*[1") ?=
      "XPath predicate failed: javax.xml.transform.TransformerException: Expected ], but found: "
  }
} 
Example 50
Source File: GenericInferenceSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Inference
import eu.timepit.refined.generic.Equal
import eu.timepit.refined.numeric.Greater
import eu.timepit.refined.string.StartsWith
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.Nat

class GenericInferenceSpec extends Properties("GenericInference") {

  property("Equal[S1] ==> StartsWith[S2]") = secure {
    Inference[Equal[W.`"abcd"`.T], StartsWith[W.`"ab"`.T]].isValid
  }

  property("Equal[S1] =!> StartsWith[S2]") = secure {
    Inference[Equal[W.`"abcd"`.T], StartsWith[W.`"cd"`.T]].notValid
  }

  property("Equal[Nat] ==> Greater[I]") = secure {
    Inference[Equal[Nat._10], Greater[W.`5`.T]].isValid
  }

  property("Equal[Nat] =!> Greater[I]") = secure {
    Inference[Equal[Nat._5], Greater[W.`10`.T]].notValid
  }
} 
Example 51
Source File: AutoSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.char.{Digit, Letter}
import eu.timepit.refined.generic._
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.tag.@@
import shapeless.test.illTyped

class AutoSpec extends Properties("auto") {

  property("autoInfer") = secure {
    val a: Char Refined Equal[W.`'0'`.T] = '0'
    val b: Char Refined Digit = a
    illTyped(
      "val c: Char Refined Letter = a",
      """type mismatch \(invalid inference\):\s*eu.timepit.refined.generic.Equal\[Char\('0'\)\] does not imply\s*eu.timepit.refined.char.Letter"""
    )
    a == b
  }

  property("autoUnwrap: PosInt: Int") = secure {
    val a: PosInt = PosInt.unsafeFrom(1)
    val b: Int = a
    a.value == b
  }

  property("autoUnwrap: PosInt + PosInt") = secure {
    val a = PosInt.unsafeFrom(1)
    val b = PosInt.unsafeFrom(2)
    (a + b) == 3
  }

  property("autoRefineV") = secure {
    val a: Char Refined Equal[W.`'0'`.T] = '0'
    illTyped("val b: Char Refined Equal[W.`'0'`.T] = '1'", """Predicate failed: \(1 == 0\).""")
    a.value == '0'
  }

  property("autoRefineT") = secure {
    val a: Char @@ Equal[W.`'0'`.T] = '0'
    illTyped("val b: Char @@ Equal[W.`'0'`.T] = '1'", """Predicate failed: \(1 == 0\).""")
    a == '0'
  }

  property("#260") = secure {
    val somePosInt: Option[PosInt] = Some(5)
    somePosInt.isDefined
  }
} 
Example 52
Source File: RefineMSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.Refined
import eu.timepit.refined.char._
import eu.timepit.refined.collection._
import eu.timepit.refined.numeric._
import eu.timepit.refined.string.MatchesRegex
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.nat._
import shapeless.tag.@@
import shapeless.test.illTyped

class RefineMSpec extends Properties("refineM") {

  property("RefineMPartiallyApplied instance") = secure {
    val rv = refineMV[Digit]
    val rt = refineMT[Digit]
    rv('0') == Refined.unsafeApply('0') && rt('0') == '0'
  }

  property("refineM with Forall") = wellTyped {
    def ignore1: String Refined Forall[LowerCase] = refineMV[Forall[LowerCase]]("hello")
    def ignore2: String @@ Forall[LowerCase] = refineMT[Forall[LowerCase]]("hello")
    illTyped("""refineMV[Forall[UpperCase]]("hello")""", "Predicate.*fail.*")
    illTyped("""refineMT[Forall[UpperCase]]("hello")""", "Predicate.*fail.*")
  }

  property("refineM with Greater") = wellTyped {
    def ignore1: Int Refined Greater[_10] = refineMV[Greater[_10]](15)
    def ignore2: Int @@ Greater[_10] = refineMT[Greater[_10]](15)
    illTyped("""refineMV[Greater[_10]](5)""", "Predicate.*fail.*")
    illTyped("""refineMT[Greater[_10]](5)""", "Predicate.*fail.*")
  }

  property("refineM with Size") = wellTyped {
    type ShortString = Size[LessEqual[_10]]
    def ignore1: String Refined ShortString = refineMV[ShortString]("abc")
    def ignore2: String @@ ShortString = refineMT[ShortString]("abc")
    illTyped("""refineMV[ShortString]("abcdefghijklmnopqrstuvwxyz")""", "Predicate.*fail.*")
    illTyped("""refineMT[ShortString]("abcdefghijklmnopqrstuvwxyz")""", "Predicate.*fail.*")
  }

  property("refineM with LowerCase") = wellTyped {
    def ignore1: Char Refined LowerCase = refineMV[LowerCase]('c')
    def ignore2: Char @@ LowerCase = refineMT[LowerCase]('c')
    illTyped("refineMV[LowerCase]('C')", "Predicate.*failed.*")
    illTyped("refineMT[LowerCase]('C')", "Predicate.*failed.*")
  }

  property("refineM with MatchesRegex") = wellTyped {
    def ignore1: String Refined MatchesRegex[W.`"[0-9]+"`.T] = refineMV("123")
    def ignore2: String @@ MatchesRegex[W.`"[0-9]+"`.T] = refineMT("123")
    illTyped("""refineMV[MatchesRegex[W.`"[0-9]+"`.T]]("abc")""", "Predicate.*fail.*")
    illTyped("""refineMT[MatchesRegex[W.`"[0-9]+"`.T]]("abc")""", "Predicate.*fail.*")
  }

  property("refineM with Contains") = wellTyped {
    def ignore1: String Refined Contains[W.`'c'`.T] = refineMV("abcd")
    def ignore2: String @@ Contains[W.`'c'`.T] = refineMT("abcd")
    illTyped("""refineMV[Contains[W.`'c'`.T]]("abde")""", "Predicate.*fail.*")
    illTyped("""refineMT[Contains[W.`'c'`.T]]("abde")""", "Predicate.*fail.*")
  }

  property("refineM with Double Witness") = wellTyped {
    def ignore1: Double Refined Greater[W.`2.3`.T] = refineMV(2.4)
    def ignore2: Double @@ Greater[W.`2.3`.T] = refineMT(2.4)
    illTyped("refineMT[Greater[W.`2.3`.T]](2.2)", "Predicate.*fail.*")
    illTyped("refineMV[Greater[W.`2.3`.T]](2.2)", "Predicate.*fail.*")
  }

  property("refineM failure with non-literals") = wellTyped {
    illTyped("refineMV[NonEmpty](List(1, 2, 3))", "compile-time refinement.*")
    illTyped("refineMT[NonEmpty](List(1, 2, 3))", "compile-time refinement.*")
  }
} 
Example 53
Source File: StringInferenceSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Inference
import eu.timepit.refined.string._
import org.scalacheck.Prop._
import org.scalacheck.Properties

class StringInferenceSpec extends Properties("StringInference") {

  property("EndsWith ==> EndsWith") = secure {
    Inference[EndsWith[W.`"cde"`.T], EndsWith[W.`"de"`.T]].isValid
  }

  property("EndsWith =!> EndsWith") = secure {
    Inference[EndsWith[W.`"de"`.T], EndsWith[W.`"cde"`.T]].notValid
  }

  property("StartsWith ==> StartsWith") = secure {
    Inference[StartsWith[W.`"cde"`.T], StartsWith[W.`"cd"`.T]].isValid
  }

  property("StartsWith =!> StartsWith") = secure {
    Inference[StartsWith[W.`"cde"`.T], StartsWith[W.`"de"`.T]].notValid
  }
} 
Example 54
Source File: RefinedTypeOpsSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.api

import eu.timepit.refined.types.numeric.NonNegInt
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scala.util.{Failure, Success, Try}

class RefinedTypeOpsSpec extends Properties("RefinedTypeOps") {

  property("from ~= unapply") = forAll { i: Int =>
    NonNegInt.from(i).right.toOption ?= NonNegInt.unapply(i)
  }

  property("from ~= unsafeFrom") = forAll { i: Int =>
    val stringOrNonNegInt = Try(NonNegInt.unsafeFrom(i)) match {
      case Success(n) => Right(n)
      case Failure(t) => Left(t.getMessage)
    }
    NonNegInt.from(i) ?= stringOrNonNegInt
  }
} 
Example 55
Source File: BigLiteralsSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.issues

import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.test.illTyped

class BigLiteralsSpec extends Properties("BigLiterals") {

  property("autoRefineV") = secure {
    val ii: BigInt Refined Positive = BigInt(1)
    val il: BigInt Refined Positive = BigInt(0X7FFFFFFFFFFFFFFFL)
    val is: BigInt Refined Positive = BigInt("1")

    val dd: BigDecimal Refined Positive = BigDecimal(1.0)
    val di: BigDecimal Refined Positive = BigDecimal(1)
    val dl: BigDecimal Refined Positive = BigDecimal(1L)
    val ds: BigDecimal Refined Positive = BigDecimal("1.0")

    val ded: BigDecimal Refined Positive = BigDecimal.exact(0.1)
    val dei: BigDecimal Refined Positive = BigDecimal.exact(1)
    val del: BigDecimal Refined Positive = BigDecimal.exact(1L)
    val des: BigDecimal Refined Positive = BigDecimal.exact("0.1")

    val dvd: BigDecimal Refined Positive = BigDecimal.valueOf(0.3)
    val dvl: BigDecimal Refined Positive = BigDecimal.valueOf(1L)

    illTyped("val err: BigInt Refined Equal[W.`0`.T] = BigInt(\"0\")")
    illTyped("val err: BigInt Refined Equal[W.`1`.T] = BigInt(1)")
    illTyped("val err: BigDecimal Refined Equal[W.`0.0`.T] = BigDecimal(0.0)")
    illTyped("val err: BigDecimal Refined Equal[W.`0.0`.T] = BigDecimal.exact(\"0.0\")")

    illTyped("val err: BigInt Refined Positive = BigInt(0)", """Predicate failed: \(0 > 0\).""")
    illTyped(
      "val err: BigInt Refined Positive = BigInt(ii.value.toInt)",
      "compile-time refinement.*"
    )
    illTyped("val err: BigInt Refined Positive = BigInt(\"0.1\")", "compile-time refinement.*")
    illTyped(
      "val err: BigInt Refined Positive = BigInt(java.math.BigInteger.ZERO)",
      "compile-time refinement.*"
    )
    illTyped(
      "val err: BigDecimal Refined Positive = BigDecimal(java.math.BigDecimal.ZERO)",
      "compile-time refinement.*"
    )

    (ii.value ?= BigInt(1)) &&
    (il.value ?= BigInt(Long.MaxValue)) &&
    (is.value ?= BigInt(1)) &&
    (dd.value ?= BigDecimal(1.0)) &&
    (di.value ?= BigDecimal(1)) &&
    (dl.value ?= BigDecimal(1L)) &&
    (ds.value ?= BigDecimal("1.0")) &&
    (ded.value ?= BigDecimal.exact(0.1)) &&
    (dei.value ?= BigDecimal.exact(1)) &&
    (del.value ?= BigDecimal.exact(1L)) &&
    (des.value ?= BigDecimal.exact("0.1")) &&
    (dvd.value ?= BigDecimal.valueOf(0.3)) &&
    (dvl.value ?= BigDecimal.valueOf(1L))
  }

} 
Example 56
Source File: StringUtilSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.auto._
import eu.timepit.refined.util.string._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.test.illTyped

class StringUtilSpec extends Properties("util.string") {

  property("regex success") = secure {
    regex("(a|b)").toString ?= "(a|b)".r.toString
  }

  property("regex failure") = secure {
    illTyped("""regex("(a|b")""", "Regex predicate failed.*")
    true
  }

  property("uri success") = secure {
    uri("file:///dev/null") ?= new java.net.URI("file:///dev/null")
  }

  property("uri failure") = wellTyped {
    illTyped("""uri("file:// /dev/null")""", "Uri predicate failed.*")
  }

  property("uuid success") = secure {
    uuid("9ecce884-47fe-4ba4-a1bb-1a3d71ed6530") ?=
      java.util.UUID.fromString("9ecce884-47fe-4ba4-a1bb-1a3d71ed6530")
  }

  property("uuid failure") = wellTyped {
    illTyped("""uuid("whops")""", "Uuid predicate failed.*")
  }
} 
Example 57
Source File: CharTypesSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.types

import eu.timepit.refined.types.all._
import org.scalacheck.Prop._
import org.scalacheck.Properties

class CharTypesSpec extends Properties("CharTypes") {

  property("LowerCaseChar.from('a')") = secure {
    LowerCaseChar.from('a').isRight
  }

  property("LowerCaseChar.from('A')") = secure {
    LowerCaseChar.from('A') ?= Left("Predicate failed: isLower('A').")
  }

  property("UpperCaseChar.from('A')") = secure {
    UpperCaseChar.from('A').isRight
  }

  property("UpperCaseChar.from('a')") = secure {
    UpperCaseChar.from('a') ?= Left("Predicate failed: isUpper('a').")
  }
} 
Example 58
Source File: GenericValidateSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils._
import eu.timepit.refined.generic._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.Nat._

class GenericValidateSpec extends Properties("GenericValidate") {

  property("Equal.isValid") = secure {
    isValid[Equal[W.`1.4`.T]](1.4)
  }

  property("Equal.notValid") = secure {
    notValid[Equal[W.`1.4`.T]](2.4)
  }

  property("Equal.showExpr") = secure {
    showExpr[Equal[W.`1.4`.T]](0.4) ?= "(0.4 == 1.4)"
  }

  property("Equal.object.isValid") = secure {
    object Foo
    isValid[Equal[Foo.type]](Foo)
  }

  property("Equal.Symbol.isValid") = secure {
    isValid[Equal[W.`'foo`.T]](Symbol("foo"))
  }

  property("Equal.Symbol.notValid") = secure {
    notValid[Equal[W.`'foo`.T]](Symbol("bar"))
  }

  property("Equal.Symbol.showExpr") = secure {
    showExpr[Equal[W.`'foo`.T]](Symbol("bar")) ?= "('bar == 'foo)"
  }

  property("Equal.Nat.Int.isValid") = forAll((i: Int) => isValid[Equal[_0]](i) ?= (i == 0))

  property("Equal.Nat.Long.isValid") = forAll((l: Long) => isValid[Equal[_0]](l) ?= (l == 0L))

  property("Equal.Nat.Double.isValid") = forAll { (d: Double) =>
    isValid[Equal[_0]](d) ?= (d == 0.0)
  }

  property("Equal.Nat.showExpr") = secure {
    showExpr[Equal[_5]](0) ?= "(0 == 5)"
  }

  property("Equal.Nat ~= Equal.Int") = forAll { (i: Int) =>
    showResult[Equal[_1]](i) ?= showResult[Equal[W.`1`.T]](i)
  }
} 
Example 59
Source File: RefineSyntaxSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.tag.@@
import shapeless.test.illTyped

class RefineSyntaxSpec extends Properties("refine syntax") {

  def testRefineV(arg: Either[String, Int Refined Positive]): Boolean = true
  def testRefineT(arg: Either[String, Int @@ Positive]): Boolean = true
  def testRefineMV(arg: Int Refined Positive): Boolean = true
  def testRefineMT(arg: Int @@ Positive): Boolean = true

  property("refineV success") = secure {
    testRefineV(refineV(1))
    testRefineV(refineV[Positive](1))
    testRefineV(refineV[Positive][Int](1))
  }

  property("refineV failure") = secure {
    testRefineV(refineV(-1))
    testRefineV(refineV[Positive](-1))
    testRefineV(refineV[Positive][Int](-1))
  }

  property("refineT success") = secure {
    testRefineT(refineT(1))
    testRefineT(refineT[Positive](1))
    testRefineT(refineT[Positive][Int](1))
  }

  property("refineT failure") = secure {
    testRefineT(refineT(-1))
    testRefineT(refineT[Positive](-1))
    testRefineT(refineT[Positive][Int](-1))
  }

  property("refineMV success") = secure {
    testRefineMV(1)
    testRefineMV(refineMV(1))
    testRefineMV(refineMV[Positive](1))
    testRefineMV(refineMV[Positive][Int](1))
  }

  property("refineMT success") = secure {
    testRefineMT(1)
    testRefineMT(refineMT(1))
    testRefineMT(refineMT[Positive](1))
    testRefineMT(refineMT[Positive][Int](1))
  }

  property("refineMV failure") = wellTyped {
    illTyped("testRefineMV(-1)", "Predicate.*fail.*")
    // We don't check the compiler error in this case because it changed with 2.13.2,
    // see https://github.com/fthomas/refined/issues/718.
    illTyped("testRefineMV(refineMV(-1))")
    illTyped("testRefineMV(refineMV[Positive](-1))", "Predicate.*fail.*")
    illTyped("testRefineMV(refineMV[Positive][Int](-1))", "Predicate.*fail.*")
  }

  property("refineMT failure") = wellTyped {
    illTyped("testRefineMT(-1)", "Predicate.*fail.*")
    // We don't check the compiler error in this case because it changed with 2.13.2,
    // see https://github.com/fthomas/refined/issues/718.
    illTyped("testRefineMT(refineMT(-1))")
    illTyped("testRefineMT(refineMT[Positive](-1))", "Predicate.*fail.*")
    illTyped("testRefineMT(refineMT[Positive][Int](-1))", "Predicate.*fail.*")
  }
} 
Example 60
Source File: NumericInferenceSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Inference
import eu.timepit.refined.boolean._
import eu.timepit.refined.numeric._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.nat._

class NumericInferenceSpec extends Properties("NumericInference") {

  property("Less[A] ==> Less[B]") = secure {
    Inference[Less[W.`7.2`.T], Less[W.`7.5`.T]].isValid
  }

  property("Less[A] =!> Less[B]") = secure {
    Inference[Less[W.`7.5`.T], Less[W.`7.2`.T]].notValid
  }

  property("LessEqual[A] ==> LessEqual[B]") = secure {
    Inference[LessEqual[W.`7.2`.T], LessEqual[W.`7.5`.T]].isValid
  }

  // Does not compile on 2.10 without a warning.
  
} 
Example 61
Source File: ImplicitScopeSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.{Inference, Validate}
import org.scalacheck.Properties


class ImplicitScopeSpec extends Properties("implicit scope") {

  property("Validate[Char, LetterOrDigit]") = wellTyped {
    Validate[Char, char.LetterOrDigit]
  }

  property("Validate[Int, Positive]") = wellTyped {
    Validate[Int, numeric.Positive]
  }

  property("Validate[Int, NonPositive]") = wellTyped {
    Validate[Int, numeric.NonPositive]
  }

  property("Validate[Int, Interval.Closed[0, 10]]") = wellTyped {
    Validate[Int, numeric.Interval.Closed[W.`0`.T, W.`10`.T]]
  }

  property("Inference[And[UpperCase, Letter], And[Letter, UpperCase]]") = wellTyped {
    Inference[boolean.And[char.UpperCase, char.Letter], boolean.And[char.Letter, char.UpperCase]]
  }

  property("Inference[Greater[1], Greater[0]]") = wellTyped {
    Inference[numeric.Greater[W.`1`.T], numeric.Greater[W.`0`.T]]
  }
} 
Example 62
Source File: RefinedSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.Refined
import eu.timepit.refined.collection.NonEmpty
import eu.timepit.refined.types.string.NonEmptyString
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.test.illTyped

class RefinedSpec extends Properties("Refined") {

  property("apply") = wellTyped {
    illTyped(
      """ val x: NonEmptyString = Refined("") """,
      "eu.timepit.refined.api.Refined.type does not take parameters"
    )
  }

  property("copy") = wellTyped {
    val x: NonEmptyString = refineMV[NonEmpty]("abc")
    illTyped(
      """ x.copy("") """,
      "value copy is not a member of eu.timepit.refined.types.string.NonEmptyString"
    )
  }

  property("equals") = secure {
    (Refined.unsafeApply(1) ?= Refined.unsafeApply(1)) &&
    !Refined.unsafeApply(1).equals(1)
  }

  property("hashCode") = forAll { i: Int => Refined.unsafeApply(i).hashCode() ?= i.hashCode }

  property("unapply") = secure {
    val x: NonEmptyString = refineMV("Hi")
    val Refined(s) = x
    s ?= x.value
  }

  property("unapply in pattern matching") = secure {
    val x: NonEmptyString = refineMV("abc")
    x match {
      case Refined("abc") => true
      case _              => false
    }
  }
} 
Example 63
Source File: CollectionInferenceSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.Inference
import eu.timepit.refined.char._
import eu.timepit.refined.collection._
import eu.timepit.refined.numeric.{Greater, Interval}
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.nat._
import shapeless.test.illTyped

class CollectionInferenceSpec extends Properties("CollectionInference") {

  property("Exists[A] ==> Exists[B]") = secure {
    Inference[Contains[W.`'5'`.T], Exists[Digit]].isValid
  }

  property("Exists ==> NonEmpty") = secure {
    Inference[Exists[Digit], NonEmpty].isValid
  }

  property("NonEmpty =!> Exists") = wellTyped {
    illTyped("Inference[NonEmpty, Exists[Digit]]", "could not find.*Inference.*")
  }

  property("Head[A] ==> Head[B]") = secure {
    Inference[Head[Digit], Head[LetterOrDigit]].isValid
  }

  property("Head[A] ==> Exists[A]") = secure {
    Inference[Head[Digit], Exists[Digit]].isValid
  }

  property("Exists[A] =!> Head[A]") = wellTyped {
    illTyped("Inference[Exists[Digit], Head[Digit]]")
  }

  property("Index[N, A] ==> Index[N, B]") = secure {
    Inference[Index[_1, Letter], Index[_1, LetterOrDigit]].isValid
  }

  property("Index ==> Exists") = secure {
    Inference[Index[W.`1`.T, LowerCase], Exists[LowerCase]].isValid
  }

  property("Last[A] ==> Last[B]") = secure {
    Inference[Last[Letter], Last[LetterOrDigit]].isValid
  }

  property("Last ==> Exists") = secure {
    Inference[Last[Whitespace], Exists[Whitespace]].isValid
  }

  property("Last ==> NonEmpty") = secure {
    Inference[Last[Whitespace], NonEmpty].isValid
  }

  property("NonEmpty =!> Last") = wellTyped {
    illTyped("Inference[NonEmpty, Last[Whitespace]]", "could not find.*Inference.*")
  }

  property("Size[A] ==> Size[B]") = secure {
    Inference[Size[Greater[_5]], Size[Greater[_4]]].isValid
  }

  property("Size[Greater[_1]] ==> NonEmpty") = secure {
    Inference[Size[Greater[_1]], NonEmpty].isValid
  }

  property("Size[Interval.Closed[_2, _5]] ==> NonEmpty") = secure {
    Inference[Size[Interval.Closed[_2, _5]], NonEmpty].isValid
  }
} 
Example 64
Source File: Issue231.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.issues

import eu.timepit.refined.TestUtils._
import eu.timepit.refined.api.Validate
import eu.timepit.refined.auto._
import org.scalacheck.Properties
import shapeless.tag.@@
import shapeless.test.illTyped

final case class CrashOnTypeTag[A]()

object CrashOnTypeTag {
  implicit def crashValidate[A: reflect.runtime.universe.TypeTag]
      : Validate.Plain[String, CrashOnTypeTag[A]] =
    Validate.fromPredicate(_ => true, _ => "check failed", CrashOnTypeTag[A]())
}

class Issue231 extends Properties("issue/231") {

  property("CrashOnTypeTag[String]") = wellTyped {
    illTyped(
      """ val crash: String @@ CrashOnTypeTag[String] = "function" """,
      ".*java.lang.ClassNotFoundException.*"
    )
  }

  property("CrashOnTypeTag[Int => String]") = wellTyped {
    illTyped(
      """ val crash: String @@ CrashOnTypeTag[Int => String] = "function" """,
      ".*java.lang.ClassNotFoundException.*"
    )
  }
} 
Example 65
Source File: RefTypeMonadErrorSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

import _root_.cats.MonadError
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scala.annotation.tailrec
import scala.util.{Failure, Success, Try}

trait Decoder[A] {
  def decode(s: String): Either[String, A]
}

object Decoder {
  def apply[A](implicit d: Decoder[A]): Decoder[A] = d

  def instance[A](f: String => Either[String, A]): Decoder[A] =
    new Decoder[A] {
      override def decode(s: String): Either[String, A] = f(s)
    }

  implicit val decoderMonadError: MonadError[Decoder, String] =
    new MonadError[Decoder, String] {
      override def flatMap[A, B](fa: Decoder[A])(f: A => Decoder[B]): Decoder[B] =
        instance { s =>
          fa.decode(s) match {
            case Right(a)  => f(a).decode(s)
            case Left(err) => Left(err)
          }
        }

      override def tailRecM[A, B](a: A)(f: A => Decoder[Either[A, B]]): Decoder[B] = {
        @tailrec
        def step(s: String, a1: A): Either[String, B] =
          f(a1).decode(s) match {
            case Right(Right(b)) => Right(b)
            case Right(Left(a2)) => step(s, a2)
            case Left(err)       => Left(err)
          }

        instance(s => step(s, a))
      }

      override def raiseError[A](e: String): Decoder[A] =
        instance(_ => Left(e))

      override def handleErrorWith[A](fa: Decoder[A])(f: String => Decoder[A]): Decoder[A] =
        instance { s =>
          fa.decode(s) match {
            case Right(a)  => Right(a)
            case Left(err) => f(err).decode(s)
          }
        }

      override def pure[A](x: A): Decoder[A] =
        instance(_ => Right(x))
    }

  implicit val intDecoder: Decoder[Int] =
    instance(s =>
      Try(s.toInt) match {
        case Success(i) => Right(i)
        case Failure(t) => Left(t.getMessage)
      }
    )
}

class RefTypeMonadErrorSpec extends Properties("MonadError") {

  property("Decoder[Int]") = secure {
    Decoder[Int].decode("1") ?= Right(1)
  }

  property("derive Decoder[PosInt] via MonadError[Decoder, String]") = {
    // This import is needed because of https://github.com/scala/bug/issues/10753
    import Decoder.decoderMonadError
    import eu.timepit.refined.cats.derivation._

    val decoder = Decoder[PosInt]
    (decoder.decode("1") ?= Right(PosInt.unsafeFrom(1))) &&
    (decoder.decode("-1") ?= Left("Predicate failed: (-1 > 0)."))
  }
} 
Example 66
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 67
Source File: RefTypeContravariantSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

import _root_.cats.Contravariant
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.Prop._
import org.scalacheck.Properties

trait Encoder[A] {
  def encode(a: A): String
}

object Encoder {
  def apply[A](implicit e: Encoder[A]): Encoder[A] = e

  def instance[A](f: A => String): Encoder[A] = new Encoder[A] {
    override def encode(a: A): String = f(a)
  }

  implicit val encoderContravariant: Contravariant[Encoder] =
    new Contravariant[Encoder] {
      override def contramap[A, B](fa: Encoder[A])(f: B => A): Encoder[B] =
        instance(b => fa.encode(f(b)))
    }

  implicit val intEncoder: Encoder[Int] =
    instance(_.toString)
}

class RefTypeContravariantSpec extends Properties("Contravariant") {

  property("Encoder[Int]") = secure {
    Encoder[Int].encode(1) ?= "1"
  }

  property("derive Encoder[PosInt] via Contravariant[Encoder]") = secure {
    // This import is needed because of https://github.com/scala/bug/issues/10753
    import Encoder.encoderContravariant
    import eu.timepit.refined.cats.derivation._

    Encoder[PosInt].encode(PosInt.unsafeFrom(1)) ?= "1"
  }
} 
Example 68
Source File: CatsSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

import _root_.cats.implicits._
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.Prop._
import org.scalacheck.Properties

class CatsSpec extends Properties("cats") {

  property("Eq") = secure {
    val refTypeOrder: Unit = () // shadow the `Order` instance so the `Eq` instance is tested
    locally(refTypeOrder) // prevent a "unused" warning

    PosInt.unsafeFrom(5) === PosInt.unsafeFrom(5)
  }

  property("Order") = secure {
    val x = PosInt.unsafeFrom(5)
    val y = PosInt.unsafeFrom(6)
    x min y ?= x
  }

  property("Show") = secure {
    PosInt.unsafeFrom(5).show ?= "5"
  }
} 
Example 69
Source File: SyntaxSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

import _root_.cats.data.{NonEmptyList, Validated}
import eu.timepit.refined.W
import eu.timepit.refined.api.{Refined, RefinedTypeOps}
import eu.timepit.refined.numeric.{Interval, Positive}
import eu.timepit.refined.refineMV
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.Prop._
import org.scalacheck.Properties

class SyntaxSpec extends Properties("syntax") {

  property("ValidateNel when Valid") = secure {
    import syntax._
    PosInt.validateNel(5) ?= Validated.Valid(PosInt.unsafeFrom(5))
  }

  property("ValidateNel when Invalid") = secure {
    import syntax._
    PosInt.validateNel(-1) ?= Validated.invalidNel("Predicate failed: (-1 > 0).")
  }

  property("validateNel without import") = secure {
    type OneToTen = Int Refined Interval.Closed[W.`1`.T, W.`10`.T]
    object OneToTen extends RefinedTypeOps[OneToTen, Int] with CatsRefinedTypeOpsSyntax
    OneToTen.validateNel(5) ?= Validated.valid(OneToTen.unsafeFrom(5))
  }

  property("ValidateNec when Valid") = secure {
    import syntax._
    PosInt.validateNec(5) ?= Validated.Valid(PosInt.unsafeFrom(5))
  }

  property("ValidateNec when Invalid") = secure {
    import syntax._
    PosInt.validateNec(-1) ?= Validated.invalidNec("Predicate failed: (-1 > 0).")
  }

  property("validateNec without import") = secure {
    type OneToTen = Int Refined Interval.Closed[W.`1`.T, W.`10`.T]
    object OneToTen extends RefinedTypeOps[OneToTen, Int] with CatsRefinedTypeOpsSyntax
    OneToTen.validateNec(5) ?= Validated.valid(OneToTen.unsafeFrom(5))
  }

  property("NonEmptyList refinedSize (1)") = secure {
    import syntax._
    NonEmptyList.of("one").refinedSize ?= refineMV[Positive](1)
  }

  property("NonEmptyList refinedSize (> 1)") = secure {
    import syntax._
    NonEmptyList.of("one", "two", "three").refinedSize ?= refineMV[Positive](3)
  }

} 
Example 70
Source File: SemigroupSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

import cats.implicits._
import eu.timepit.refined.types.numeric._
import org.scalacheck.Prop.secure
import org.scalacheck.Properties

class SemigroupSpec extends Properties("Semigroup") {

  property("Positive Integral types overflow") =
    secure((PosByte.MaxValue |+| PosByte.unsafeFrom(1)) === PosByte.MinValue) &&
      secure((PosShort.MaxValue |+| PosShort.unsafeFrom(1)) === PosShort.MinValue) &&
      secure((PosInt.MaxValue |+| PosInt.unsafeFrom(1)) === PosInt.MinValue) &&
      secure((PosLong.MaxValue |+| PosLong.unsafeFrom(1)) === PosLong.MinValue)

  property("NonNegative Integral types overflow") =
    secure((NonNegByte.MaxValue |+| NonNegByte.unsafeFrom(1)) === NonNegByte.MinValue) &&
      secure((NonNegShort.MaxValue |+| NonNegShort.unsafeFrom(1)) === NonNegShort.MinValue) &&
      secure((NonNegInt.MaxValue |+| NonNegInt.unsafeFrom(1)) === NonNegInt.MinValue) &&
      secure((NonNegLong.MaxValue |+| NonNegLong.unsafeFrom(1)) === NonNegLong.MinValue)

  property("Negative Integral types overflow") =
    secure((NegByte.MinValue |+| NegByte.unsafeFrom(-1)) === NegByte.MaxValue) &&
      secure((NegShort.MinValue |+| NegShort.unsafeFrom(-1)) === NegShort.MaxValue) &&
      secure((NegInt.MinValue |+| NegInt.unsafeFrom(-1)) === NegInt.MaxValue) &&
      secure((NegLong.MinValue |+| NegLong.unsafeFrom(-1)) === NegLong.MaxValue)

} 
Example 71
Source File: ReverseSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import singleton.TestUtils._

class ReverseSpec extends Properties("Reverse") {
  property("abc.reverse == cba") = wellTyped {
    def reverse[P1 <: XString](implicit op : Reverse[P1]) : op.Out{} = op.value
    val r : W.`"cba"`.T = reverse[W.`"abc"`.T]
  }

  property("abc.reverse.reverse == abc") = wellTyped {
    def reverse[P1 <: XString](implicit op : Reverse[Reverse[P1]]) : op.Out{} = op.value
    val r : W.`"abc"`.T = reverse[W.`"abc"`.T]
  }
} 
Example 72
Source File: NegateSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import singleton.TestUtils._
import shapeless.test.illTyped

class NegateSpec extends Properties("Negate") {
  property("Nat argument") = wellTyped {
    implicitly[Require[Negate[shapeless.Nat._1] == W.`(-1)`.T]]
  }

  property("Char argument") = wellTyped {
    implicitly[Require[Negate[W.`'T'`.T] == W.`(-84)`.T]]
  }

  property("Int argument") = wellTyped {
    implicitly[Require[Negate[W.`2`.T] == W.`(-2)`.T]]
    implicitly[Require[Negate[W.`-2`.T] == W.`2`.T]]
  }

  property("Long argument") = wellTyped {
    implicitly[Require[Negate[W.`5L`.T] == W.`(-5L)`.T]]
    implicitly[Require[Negate[W.`-5L`.T] == W.`5L`.T]]
  }

  property("Float argument") = wellTyped {
    implicitly[Require[Negate[W.`1.5f`.T] == W.`(-1.5f)`.T]]
    implicitly[Require[Negate[W.`-1.5f`.T] == W.`1.5f`.T]]
  }

  property("Double argument") = wellTyped {
    implicitly[Require[Negate[W.`1.5`.T] == W.`(-1.5)`.T]]
    implicitly[Require[Negate[W.`-1.5`.T] == W.`1.5`.T]]
  }

  property("Boolean argument") = {
    illTyped("""implicitly[Negate[W.`true`.T]]""")
    true
  }

  property("String argument") = {
    illTyped("""implicitly[Negate[W.`"Something"`.T]]""")
    true
  }
} 
Example 73
Source File: GetLHSArgSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._

class GetLHSArgSpec extends Properties("GetLHSArgSpec") {
  abstract class Conv[T](val value : T) {
    type Out = T
  }

  implicit class ConvInt(val int : Int) {
    def ext(implicit g : GetLHSArg0) : g.Out = g.value
    def <= [T, Out](that : Conv[T])(implicit g : OpAuxGen[AcceptNonLiteral[GetLHSArg0], Out]) : Conv[Out] = new Conv[Out](g.value){}
    def := [T, Out](that : Conv[T])(implicit g : GetLHSArg.Aux[W.`0`.T, Out]) : Conv[Out] = new Conv[Out](g){}
  }

  property("implicit class argument with GetLHSArg0") = {
    val c = new Conv(2){}
    val out = 12 <= c
    implicitly[out.Out =:= W.`12`.T]
    val out2 : W.`12`.T = 12.ext
    out.value == 12
  }

  property("implicit class argument with GetLHSArg.Aux") = {
    val c = new Conv(2){}
    val out = 12 := c
    implicitly[out.Out =:= W.`12`.T]
    out.value == 12
  }

  def bad(i : Int)(implicit arg : GetLHSArg0) : Unit ={}

  property("no LHS arguments fails macro") = wellTyped {
    illTyped("""bad(4)""", "Left-hand-side tree not found")
  }

  property("Unsupported GetLHSArg") = wellTyped {
    illTyped("implicitly[GetLHSArg[W.`-1`.T]]") //Bad argument (Negative Int)
    illTyped("implicitly[GetLHSArg[W.`0.1`.T]]") //Bad argument (Double instead of Int)
  }

  class Foo(value0 : Any, value1 : Any)(value2 : Any)(value3 : Any){
    def getArg[I <: Int](idx : I)(implicit g : GetLHSArg[I]) : g.Out = g.value
  }

  property("Multiple LHS arguments") = wellTyped {
    val out0 : W.`1`.T = new Foo(1, "me")(3L)(true) getArg W(0).value
    val out1 : W.`"me"`.T  = new Foo(1, "me")(3L)(true) getArg W(1).value
    val out2 : W.`3L`.T  = new Foo(1, "me")(3L)(true) getArg W(2).value
    val out3 : W.`true`.T  = new Foo(1, "me")(3L)(true) getArg W(3).value
  }


} 
Example 74
Source File: StringOpsSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._

class StringOpsSpec extends Properties("StringOps") {
  property("Substring[foobar, 3] == bar") = wellTyped {
    def f[S <: XString, I <: XInt](implicit op : Substring[S, I]) : op.Out{} = op.value
    val r : W.`"bar"`.T = f[W.`"foobar"`.T, W.`3`.T]
  }
  property("Substring abort") = wellTyped {illTyped("""implicitly[Substring[W.`"abc"`.T, W.`4`.T]]""")}
  property("Substring unsupported") = wellTyped {illTyped("""implicitly[Substring[W.`true`.T, W.`2`.T]]""")}

  property("SubSequence[foobar, 1, 4] == oob") = wellTyped {
    def f[S <: XString, B <: XInt, E <: XInt](implicit op : SubSequence[S, B, E]) : op.Out{} = op.value
    val r : W.`"oob"`.T = f[W.`"foobar"`.T, W.`1`.T, W.`4`.T]
  }
  property("SubSequence abort") = wellTyped {illTyped("""implicitly[SubSequence[W.`"abc"`.T, W.`5`.T, W.`7`.T]]""")}
  property("SubSequence unsupported") = wellTyped {illTyped("""implicitly[SubSequence[W.`true`.T, W.`2`.T, W.`3`.T]]""")}

  property("StartsWith[foobar, foo] == true") = wellTyped {
    def f[S <: XString, Pre <: XString](implicit op : StartsWith[S, Pre]) : op.Out{} = op.value
    val r : W.`true`.T = f[W.`"foobar"`.T, W.`"foo"`.T]
  }
  property("StartsWith unsupported") = wellTyped {illTyped("""implicitly[StartsWith[W.`"foobar"`.T, W.`true`.T]]""")}

  property("EndsWith[foobar, bar] == true") = wellTyped {
    def f[S <: XString, Suf <: XString](implicit op : EndsWith[S, Suf]) : op.Out{} = op.value
    val r : W.`true`.T = f[W.`"foobar"`.T, W.`"bar"`.T]
  }
  property("EndsWith unsupported") = wellTyped {illTyped("""implicitly[EndsWith[W.`"foobar"`.T, W.`true`.T]]""")}

  property("Head[foobar] == f") = wellTyped {
    def f[S <: XString](implicit op : Head[S]) : op.Out{} = op.value
    val r : W.`'f'`.T = f[W.`"foobar"`.T]
  }
  property("Head abort") = wellTyped {illTyped("""implicitly[Head[W.`""`.T]]""")}
  property("Head unsupported") = wellTyped {illTyped("""implicitly[Head[W.`0`.T]]""")}

  property("Tail[foobar] == oobar") = wellTyped {
    def f[S <: XString](implicit op : Tail[S]) : op.Out{} = op.value
    val r : W.`"oobar"`.T = f[W.`"foobar"`.T]
  }
  property("Tail unsupported") = wellTyped {illTyped("""implicitly[Tail[W.`0`.T]]""")}

  property("CharAt[foobar, 3] == b") = wellTyped {
    def f[S <: XString, I <: XInt](implicit op : CharAt[S, I]) : op.Out{} = op.value
    val r : W.`'b'`.T = f[W.`"foobar"`.T, W.`3`.T]
  }
  property("CharAt abort") = wellTyped {illTyped("""implicitly[CharAt[W.`"abc"`.T, W.`5`.T]]""")}
  property("CharAt unsupported") = wellTyped {illTyped("""implicitly[CharAt[W.`true`.T, W.`2`.T]]""")}

  property("Length[foobar] == 6") = wellTyped {
    def f[S <: XString](implicit op : Length[S]) : op.Out{} = op.value
    val r : W.`6`.T = f[W.`"foobar"`.T]
  }
  property("Length unsupported") = wellTyped {illTyped("""implicitly[Length[W.`true`.T]]""")}

  property("Matches[foobar, fo+.*] == true") = wellTyped {
    def f[S <: XString, Regex <: XString](implicit op : Matches[S, Regex]) : op.Out{} = op.value
    val r : W.`true`.T = f[W.`"foobar"`.T, W.`"fo+.*"`.T]
  }
  property("Matches abort") = wellTyped {illTyped("""implicitly[Matches[W.`"abc"`.T, W.`"[a"`.T]]""")}
  property("Matches unsupported") = wellTyped {illTyped("""implicitly[Matches[W.`"foobar"`.T, W.`true`.T]]""")}

  property("FirstMatch[foobar, b[ar]+] == bar") = wellTyped {
    def f[S <: XString, Regex <: XString](implicit op : FirstMatch[S, Regex]) : op.Out{} = op.value
    val r : W.`"bar"`.T = f[W.`"foobar"`.T, W.`"b[ar]+"`.T]
  }
  property("FirstMatch abort") = wellTyped {illTyped("""implicitly[FirstMatch[W.`"abc"`.T, W.`"[a"`.T]]""")}
  property("FirstMatch unsupported") = wellTyped {illTyped("""implicitly[FirstMatch[W.`0`.T, W.`".*"`.T]]""")}

  property("PrefixMatch[foobar, fo+] == foo") = wellTyped {
    def f[S <: XString, Regex <: XString](implicit op : PrefixMatch[S, Regex]) : op.Out{} = op.value
    val r : W.`"foo"`.T = f[W.`"foobar"`.T, W.`"fo+"`.T]
  }
  property("PrefixMatch abort") = wellTyped {illTyped("""implicitly[PrefixMatch[W.`"abc"`.T, W.`"[a"`.T]]""")}
  property("PrefixMatch unsupported") = wellTyped {illTyped("""implicitly[PrefixMatch[W.`true`.T, W.`".*"`.T]]""")}

  property("ReplaceFirstMatch[foobar, [oa], z] == fzobar") = wellTyped {
    def f[S <: XString, Regex <: XString, R <: XString](implicit op : ReplaceFirstMatch[S, Regex, R]) : op.Out{} = op.value
    val r : W.`"fzobar"`.T = f[W.`"foobar"`.T, W.`"[oa]"`.T, W.`"z"`.T]
  }
  property("ReplaceFirstMatch abort") = wellTyped {illTyped("""implicitly[ReplaceFirstMatch[W.`"abc"`.T, W.`"[a"`.T, W.`"z"`.T]]""")}
  property("ReplaceFirstMatch unsupported") = wellTyped {illTyped("""implicitly[ReplaceFirstMatch[W.`0`.T, W.`".*"`.T, W.`"z"`.T]]""")}

  property("ReplaceAllMatches[foobar, [oa], z] == fzzbzr") = wellTyped {
    def f[S <: XString, Regex <: XString, R <: XString](implicit op : ReplaceAllMatches[S, Regex, R]) : op.Out{} = op.value
    val r : W.`"fzzbzr"`.T = f[W.`"foobar"`.T, W.`"[oa]"`.T, W.`"z"`.T]
  }  
  property("ReplaceAllMatches abort") = wellTyped {illTyped("""implicitly[ReplaceAllMatches[W.`"abc"`.T, W.`"[a"`.T, W.`"z"`.T]]""")}
  property("ReplaceAllMatches unsupported") = wellTyped {illTyped("""implicitly[ReplaceAllMatches[W.`0`.T, W.`".*"`.T, W.`"z"`.T]]""")}
} 
Example 75
Source File: RequireSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._

class RequireSpec extends Properties("Require") {
  val Testing123 = W("Testing 123")
  type Testing123 = Testing123.T
  
  property("True requirement") = wellTyped {
    implicitly[Require[True]]
  }
  property("False requirement") = wellTyped {
    illTyped("""implicitly[Require[False]]""")
  }
  property("False requirement with message") = wellTyped {
    illTyped("""implicitly[RequireMsg[False,Testing123]]""","Testing 123")
  }
  property("False requirement with message redirected to different symbol") = wellTyped {
    @scala.annotation.implicitNotFound("Will be replaced")
    trait TestRequireMsg
    object TestRequireMsg {
      implicit def ev(implicit r : RequireMsg[False, Testing123]) :
      TestRequireMsg = new TestRequireMsg {}
    }
    illTyped("""implicitly[TestRequireMsg]""","Testing 123")

    @scala.annotation.implicitNotFound("Not replaced")
    trait TestRequireMsgSymNotReplaced
    object TestRequireMsgSymNotReplaced {
      implicit def ev(implicit r : RequireMsgSym[False,Testing123,_]) :
      TestRequireMsgSymNotReplaced = new TestRequireMsgSymNotReplaced {}
    }
    illTyped("""implicitly[TestRequireMsgSymNotReplaced]""","Not replaced")

    @scala.annotation.implicitNotFound("Will be replaced")
    trait TestRequireMsgSym
    object TestRequireMsgSym {
      implicit def ev(implicit r : RequireMsgSym[False,Testing123,TestRequireMsgSym]) :
      TestRequireMsgSym = new TestRequireMsgSym {}
    }
    illTyped("""implicitly[TestRequireMsgSym]""","Testing 123")
  }
} 
Example 76
Source File: UnsupportedSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops.math._

//Unsupported operation check to increase coverage
class UnsupportedSpec extends Properties("UnsupportedSpec") {
  property("ToNat") = wellTyped {illTyped("""implicitly[ToNat[W.`true`.T]]""")}
  property("ToNat with negative number") = wellTyped {illTyped("""implicitly[ToNat[W.`-1`.T]]""","Nat cannot be a negative literal. Found: -1")}
  property("ToChar") = wellTyped {illTyped("""implicitly[ToChar[W.`true`.T]]""")}
  property("ToInt") = wellTyped {illTyped("""implicitly[ToInt[W.`true`.T]]""")}
  property("ToLong") = wellTyped {illTyped("""implicitly[ToLong[W.`true`.T]]""")}
  property("ToFloat") = wellTyped {illTyped("""implicitly[ToFloat[W.`true`.T]]""")}
  property("ToDouble") = wellTyped {illTyped("""implicitly[ToDouble[W.`true`.T]]""")}
  property("Negate") = wellTyped {illTyped("""implicitly[Negate[W.`true`.T]]""")}
  property("Abs") = wellTyped {illTyped("""implicitly[Abs[W.`true`.T]]""")}
  property("ToDouble") = wellTyped {illTyped("""implicitly[ToDouble[W.`true`.T]]""")}
  property("NumberOfLeadingZeros") = wellTyped {illTyped("""implicitly[NumberOfLeadingZeros[W.`true`.T]]""")}
  property("Floor") = wellTyped {illTyped("""implicitly[Floor[W.`true`.T]]""")}
  property("Ceil") = wellTyped {illTyped("""implicitly[Ceil[W.`true`.T]]""")}
  property("Round") = wellTyped {illTyped("""implicitly[Round[W.`true`.T]]""")}
  property("Sin") = wellTyped {illTyped("""implicitly[Sin[W.`true`.T]]""")}
  property("Cos") = wellTyped {illTyped("""implicitly[Cos[W.`true`.T]]""")}
  property("Tan") = wellTyped {illTyped("""implicitly[Tan[W.`true`.T]]""")}
  property("Sqrt") = wellTyped {illTyped("""implicitly[Sqrt[W.`true`.T]]""")}
  property("Log") = wellTyped {illTyped("""implicitly[Log[W.`true`.T]]""")}
  property("Log10") = wellTyped {illTyped("""implicitly[Log10[W.`true`.T]]""")}
  property("Reverse") = wellTyped {illTyped("""implicitly[Reverse[W.`true`.T]]""")}
  property("Not") = wellTyped {illTyped("""implicitly[![W.`"a"`.T]]""")}
  property("Require") = wellTyped {
    val a = W(true)
    illTyped("""implicitly[RequireMsg[W.`false`.T,W.`false`.T]]""")
//    illTyped("""implicitly[RequireMsg[a.T,W.`11`.T]]""")
    illTyped("""implicitly[RequireMsg[W.`1`.T,W.`false`.T]]""")
  }
  property("ITE") = wellTyped {illTyped("""implicitly[ITE[W.`1`.T,W.`1`.T,W.`true`.T]]""")}
  property("+") = wellTyped {illTyped("""implicitly[W.`true`.T + W.`2`.T]""")}
  property("-") = wellTyped {illTyped("""implicitly[W.`"a"`.T - W.`2`.T]""")}
  property("*") = wellTyped {illTyped("""implicitly[W.`true`.T * W.`2`.T]""")}
  property("/") = wellTyped {illTyped("""implicitly[W.`true`.T / W.`2`.T]""")}
  property("%") = wellTyped {illTyped("""implicitly[W.`true`.T % W.`2`.T]""")}
  property("<") = wellTyped {illTyped("""implicitly[W.`true`.T < W.`2`.T]""")}
  property(">") = wellTyped {illTyped("""implicitly[W.`true`.T > W.`2`.T]""")}
  property("<=") = wellTyped {illTyped("""implicitly[W.`true`.T <= W.`2`.T]""")}
  property(">=") = wellTyped {illTyped("""implicitly[W.`true`.T >= W.`2`.T]""")}
  property("==") = wellTyped {illTyped("""implicitly[W.`true`.T == W.`2`.T]""")}
  property("!=") = wellTyped {illTyped("""implicitly[W.`true`.T != W.`2`.T]""")}
  property("&&") = wellTyped {illTyped("""implicitly[W.`1`.T && W.`2`.T]""")}
  property("||") = wellTyped {illTyped("""implicitly[W.`1`.T || W.`2`.T]""")}
  property("Pow") = wellTyped {illTyped("""implicitly[Pow[W.`true`.T, W.`2`.T]]""")}
  property("Min") = wellTyped {illTyped("""implicitly[Min[W.`true`.T, W.`2`.T]]""")}
  property("Max") = wellTyped {illTyped("""implicitly[Max[W.`true`.T, W.`2`.T]]""")}
  property("Substring") = wellTyped {illTyped("""implicitly[Substring[W.`true`.T, W.`2`.T]]""")}
  property("CharAt") = wellTyped {illTyped("""implicitly[CharAt[W.`true`.T, W.`2`.T]]""")}
  property("Length") = wellTyped {illTyped("""implicitly[Length[W.`true`.T]]""")}
  property("No Extraction from Bad Num") = wellTyped {illTyped("""implicitly[Id[Int]]""")}
  property("No Extraction from Bad TwoFace") = wellTyped {illTyped("""implicitly[TwoFace.Int[Int]]""")}
} 
Example 77
Source File: MinSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import singleton.TestUtils._
import singleton.ops.math._

class MinSpec extends Properties("Min") {
  property("Nat, right is minimum") = verifyOp2Args[Min,shapeless.Nat._1, shapeless.Nat._2, W.`1`.T]
  property("Nat, left is minimum") = verifyOp2Args[Min,shapeless.Nat._3, shapeless.Nat._2, W.`2`.T]
  property("Nat, equal") = verifyOp2Args[Min,shapeless.Nat._3, shapeless.Nat._3, W.`3`.T]
  property("Int, right is minimum") = verifyOp2Args[Min, W.`1`.T, W.`2`.T, W.`1`.T]
  property("Int, left is minimum") = verifyOp2Args[Min, W.`3`.T, W.`2`.T, W.`2`.T]
  property("Int, equal") = verifyOp2Args[Min, W.`3`.T, W.`3`.T, W.`3`.T]
  property("Long, right is minimum") = verifyOp2Args[Min, W.`1L`.T, W.`2L`.T, W.`1L`.T]
  property("Long, left is minimum") = verifyOp2Args[Min, W.`3L`.T, W.`2L`.T, W.`2L`.T]
  property("Long, equal") = verifyOp2Args[Min, W.`3L`.T, W.`3L`.T, W.`3L`.T]
  property("Float, right is minimum") = verifyOp2Args[Min, W.`1.0f`.T, W.`2.0f`.T, W.`1.0f`.T]
  property("Float, left is minimum") = verifyOp2Args[Min, W.`3.0f`.T, W.`2.0f`.T, W.`2.0f`.T]
  property("Float, equal") = verifyOp2Args[Min, W.`3.0f`.T, W.`3.0f`.T, W.`3.0f`.T]
  property("Double, right is minimum") = verifyOp2Args[Min, W.`1.0`.T, W.`2.0`.T, W.`1.0`.T]
  property("Double, left is minimum") = verifyOp2Args[Min, W.`3.0`.T, W.`2.0`.T, W.`2.0`.T]
  property("Double, equal") = verifyOp2Args[Min, W.`3.0`.T, W.`3.0`.T, W.`3.0`.T]
} 
Example 78
Source File: MaxSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import singleton.TestUtils._
import singleton.ops.math._

class MaxSpec extends Properties("Max") {
  property("Nat, right is maximum") = verifyOp2Args[Max,shapeless.Nat._1, shapeless.Nat._2, W.`2`.T]
  property("Nat, left is maximum") = verifyOp2Args[Max,shapeless.Nat._3, shapeless.Nat._2, W.`3`.T]
  property("Nat, equal") = verifyOp2Args[Max,shapeless.Nat._3, shapeless.Nat._3, W.`3`.T]
  property("Int, right is maximum") = verifyOp2Args[Max, W.`1`.T, W.`2`.T, W.`2`.T]
  property("Int, left is maximum") = verifyOp2Args[Max, W.`3`.T, W.`2`.T, W.`3`.T]
  property("Int, equal") = verifyOp2Args[Max, W.`3`.T, W.`3`.T, W.`3`.T]
  property("Long, right is maximum") = verifyOp2Args[Max, W.`1L`.T, W.`2L`.T, W.`2L`.T]
  property("Long, left is maximum") = verifyOp2Args[Max, W.`3L`.T, W.`2L`.T, W.`3L`.T]
  property("Long, equal") = verifyOp2Args[Max, W.`3L`.T, W.`3L`.T, W.`3L`.T]
  property("Float, right is maximum") = verifyOp2Args[Max, W.`1.0f`.T, W.`2.0f`.T, W.`2.0f`.T]
  property("Float, left is maximum") = verifyOp2Args[Max, W.`3.0f`.T, W.`2.0f`.T, W.`3.0f`.T]
  property("Float, equal") = verifyOp2Args[Max, W.`3.0f`.T, W.`3.0f`.T, W.`3.0f`.T]
  property("Double, right is maximum") = verifyOp2Args[Max, W.`1.0`.T, W.`2.0`.T, W.`2.0`.T]
  property("Double, left is maximum") = verifyOp2Args[Max, W.`3.0`.T, W.`2.0`.T, W.`3.0`.T]
  property("Double, equal") = verifyOp2Args[Max, W.`3.0`.T, W.`3.0`.T, W.`3.0`.T]
} 
Example 79
Source File: IdSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import singleton.TestUtils._

class IdSpec extends Properties("Id") {
  property("Nat") = wellTyped {
    def getNat(implicit op : SafeNat[Id[shapeless.Nat._1]]) : op.Out = op.value
    val ret : shapeless.nat._1 = getNat
  }
  property("Char") = {
    val ret : Char = implicitly[SafeChar[Id[W.`'\u0001'`.T]]]
    ret == '\u0001'
  }
  property("Int") = {
    val ret : Int = implicitly[SafeInt[Id[W.`1`.T]]]
    ret == 1
  }
  property("Long") = {
    val ret : Long = implicitly[SafeLong[Id[W.`1L`.T]]]
    ret == 1L
  }
  property("Float") = {
    val ret : Float = implicitly[SafeFloat[Id[W.`1.0f`.T]]]
    ret == 1.0f
  }
  property("Double") = {
    val ret : Double = implicitly[SafeDouble[Id[W.`1.0`.T]]]
    ret == 1.0
  }
  property("String") = {
    val ret : String = implicitly[SafeString[Id[W.`"Something"`.T]]]
    ret == "Something"
  }
  property("Boolean") = {
    val ret : Boolean = implicitly[SafeBoolean[Id[W.`true`.T]]]
    ret == true
  }
  property("UpperBound") = {
    trait Foo[T] {
      type Width <: T
      val value : Int
    }
    val ret = new Foo[W.`1`.T]{
      val value : Int = implicitly[SafeInt[Id[Width]]]
    }
    ret.value == 1
  }
} 
Example 80
Source File: ToConversionSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._

class ToConversionSpec extends Properties("ToConversion") {
  property("Nat to Nat") = wellTyped {
    def getNat(implicit op : SafeNat[ToNat[shapeless.Nat._1]]) : op.Out = op.value
    val ret : shapeless.nat._1 = getNat
  }
  property("Char to Nat") = wellTyped {
    def getNat(implicit op : SafeNat[ToNat[W.`'\u0001'`.T]]) : op.Out = op.value
    val ret : shapeless.nat._1 = getNat
  }
  property("Int to Nat") = wellTyped {
    def getNat(implicit op : SafeNat[ToNat[W.`1`.T]]) : op.Out = op.value
    val ret : shapeless.nat._1 = getNat
  }
  property("Long to Nat") = wellTyped {
    def getNat(implicit op : SafeNat[ToNat[W.`1L`.T]]) : op.Out = op.value
    val ret : shapeless.nat._1 = getNat
  }
  property("Float to Nat") = wellTyped {
    def getNat(implicit op : SafeNat[ToNat[W.`1.0f`.T]]) : op.Out = op.value
    val ret : shapeless.nat._1 = getNat
  }
  property("Double to Nat") = wellTyped {
    def getNat(implicit op : SafeNat[ToNat[W.`1.0`.T]]) : op.Out = op.value
    val ret : shapeless.nat._1 = getNat
  }

  property("Nat to Char") = verifyOp1Args[ToChar,shapeless.Nat._1,W.`'\u0001'`.T]
  property("Char to Char") = verifyOp1Args[ToChar,W.`'\u0002'`.T,W.`'\u0002'`.T]
  property("Int to Char") = verifyOp1Args[ToChar,W.`3`.T,W.`'\u0003'`.T]
  property("Long to Char") = verifyOp1Args[ToChar,W.`4L`.T,W.`'\u0004'`.T]
  property("Float to Char") = verifyOp1Args[ToChar,W.`5.0f`.T,W.`'\u0005'`.T]
  property("Double to Char") = verifyOp1Args[ToChar,W.`6.0`.T,W.`'\u0006'`.T]
  property("String to Char") = {illTyped("""implicitly[ToChar[W.`"7"`.T]]"""); true}
  property("Boolean to Char") = {illTyped("""implicitly[ToChar[True]]"""); true}

  property("Nat to Int") = verifyOp1Args[ToInt,shapeless.Nat._1,W.`1`.T]
  property("Char to Int") = verifyOp1Args[ToInt,W.`'\u0002'`.T,W.`2`.T]
  property("Int to Int") = verifyOp1Args[ToInt,W.`3`.T,W.`3`.T]
  property("Long to Int") = verifyOp1Args[ToInt,W.`4L`.T,W.`4`.T]
  property("Float to Int") = verifyOp1Args[ToInt,W.`5.0f`.T,W.`5`.T]
  property("Double to Int") = verifyOp1Args[ToInt,W.`6.0`.T,W.`6`.T]
  property("String to Int") = verifyOp1Args[ToInt,W.`"7"`.T,W.`7`.T]
  property("Boolean to Int") = {illTyped("""implicitly[ToInt[True]]"""); true}

  property("Nat to Long") = verifyOp1Args[ToLong,shapeless.Nat._1,W.`1L`.T]
  property("Char to Long") = verifyOp1Args[ToLong,W.`'\u0002'`.T,W.`2L`.T]
  property("Int to Long") = verifyOp1Args[ToLong,W.`3`.T,W.`3L`.T]
  property("Long to Long") = verifyOp1Args[ToLong,W.`4L`.T,W.`4L`.T]
  property("Float to Long") = verifyOp1Args[ToLong,W.`5.0f`.T,W.`5L`.T]
  property("Double to Long") = verifyOp1Args[ToLong,W.`6.0`.T,W.`6L`.T]
  property("String to Long") = verifyOp1Args[ToLong,W.`"7"`.T,W.`7L`.T]
  property("Boolean to Long") = {illTyped("""implicitly[ToLong[True]]"""); true}

  property("Nat to Float") = verifyOp1Args[ToFloat,shapeless.Nat._1,W.`1.0f`.T]
  property("Char to Float") = verifyOp1Args[ToFloat,W.`'\u0002'`.T,W.`2.0f`.T]
  property("Int to Float") = verifyOp1Args[ToFloat,W.`3`.T,W.`3.0f`.T]
  property("Long to Float") = verifyOp1Args[ToFloat,W.`4L`.T,W.`4.0f`.T]
  property("Float to Float") = verifyOp1Args[ToFloat,W.`5.0f`.T,W.`5.0f`.T]
  property("Double to Float") = verifyOp1Args[ToFloat,W.`6.0`.T,W.`6.0f`.T]
  property("String to Float") = verifyOp1Args[ToFloat,W.`"7"`.T,W.`7.0f`.T]
  property("Boolean to Float") = {illTyped("""implicitly[ToFloat[True]]"""); true}

  property("Nat to Double") = verifyOp1Args[ToDouble,shapeless.Nat._1,W.`1.0`.T]
  property("Char to Double") = verifyOp1Args[ToDouble,W.`'\u0002'`.T,W.`2.0`.T]
  property("Int to Double") = verifyOp1Args[ToDouble,W.`3`.T,W.`3.0`.T]
  property("Long to Double") = verifyOp1Args[ToDouble,W.`4L`.T,W.`4.0`.T]
  property("Float to Double") = verifyOp1Args[ToDouble,W.`5.0f`.T,W.`5.0`.T]
  property("Double to Double") = verifyOp1Args[ToDouble,W.`6.0`.T,W.`6.0`.T]
  property("String to Double") = verifyOp1Args[ToDouble,W.`"7"`.T,W.`7.0`.T]
  property("Boolean to Double") = {illTyped("""implicitly[ToDouble[True]]"""); true}

  property("Nat to String") = verifyOp1Args[ToString,shapeless.Nat._1,W.`"1"`.T]
  property("Char to String") = verifyOp1Args[ToString,W.`'2'`.T,W.`"2"`.T]
  property("Int to String") = verifyOp1Args[ToString,W.`3`.T,W.`"3"`.T]
  property("Long to String") = verifyOp1Args[ToString,W.`4L`.T,W.`"4"`.T]
  property("Float to String") = verifyOp1Args[ToString,W.`5.0f`.T,W.`"5.0"`.T]
  property("Double to String") = verifyOp1Args[ToString,W.`6.0`.T,W.`"6.0"`.T]
  property("String to String") = verifyOp1Args[ToString,W.`"7"`.T,W.`"7"`.T]
  property("Boolean to String") = verifyOp1Args[ToString,True,W.`"true"`.T]

} 
Example 81
Source File: CheckedBooleanSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedBooleanSpec {
  object JustTrue extends Checked0Param.Boolean {
    type Cond[T] = T
    type Msg[T] = W.`"Failed Check"`.T
  }
}

class CheckedBooleanSpec extends Properties("Checked.Boolean") {
  import CheckedBooleanSpec._

  def condTrue[T](t : JustTrue.Checked[T]) : Unit = {t.unsafeCheck()}

  property("Compile-time checks") = wellTyped {
    condTrue(true)
    condTrue(TwoFace.Boolean(true))
    illTyped("""condTrue(false)""")
    illTyped("""condTrue(TwoFace.Boolean(false))""")
  }

  property("Run-time checks") = wellTyped {
    condTrue(us(true))
    condTrue(TwoFace.Boolean(us(true)))
    illRun{condTrue(us(false))}
    illRun{condTrue(TwoFace.Boolean(us(false)))}
  }

  def condTrueImpl[T](realValue : Boolean)(implicit t : JustTrue.CheckedShell[T]) : Unit = {t.unsafeCheck(realValue)}

  property("Shell compile-time checks") = wellTyped {
    condTrueImpl[True](true)
    illTyped("""condTrueImpl[False](true)""", "Failed Check")
    illTyped("""condTrueImpl[False](false)""", "Failed Check")
  }

  property("Shell run-time checks") = wellTyped {
    condTrueImpl[Boolean](true)
    illRun{condTrueImpl[Boolean](false)}
  }

  trait CheckedUse[T]
  object CheckedUse {
    implicit def ev[T](implicit checkedTrue: JustTrue.CheckedShellSym[CheckedUse[_], T]) : CheckedUse[T] =
      new CheckedUse[T] {}
  }

  property("Shell user message redirect checks") = wellTyped {
    implicitly[CheckedUse[True]]
    illTyped("""implicitly[CheckedUse[False]]""", "Failed Check")
  }
} 
Example 82
Source File: CheckedLongSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedLongSpec {
  object SmallerThan50 extends Checked0Param.Long {
    type Cond[T] = T < W.`50L`.T
    type Msg[T] = W.`"Failed Check"`.T
  }
}

class CheckedLongSpec extends Properties("Checked.Long") {
  import CheckedLongSpec._

  def smallerThan50[T](t : SmallerThan50.Checked[T]) : Unit = {t.unsafeCheck()}

  property("Compile-time checks") = wellTyped {
    smallerThan50(40L)
    smallerThan50(TwoFace.Long(40L))
    illTyped("""smallerThan50(50L)""")
    illTyped("""smallerThan50(TwoFace.Long(50L))""")
  }

  property("Run-time checks") = wellTyped {
    smallerThan50(us(40L))
    smallerThan50(TwoFace.Long(us(40L)))
    illRun{smallerThan50(us(50L))}
    illRun{smallerThan50(TwoFace.Long(us(50L)))}
  }
} 
Example 83
Source File: CheckedCharSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedCharSpec {
  object SmallerThan50 extends Checked0Param.Char {
    type Cond[T] = T < W.`'\u0032'`.T
    type Msg[T] = W.`"Failed Check"`.T
  }
}

class CheckedCharSpec extends Properties("Checked.Char") {
  import CheckedCharSpec._

  def smallerThan50[T](t : SmallerThan50.Checked[T]) : Unit = {t.unsafeCheck()}

  property("Compile-time checks") = wellTyped {
    smallerThan50('\u0020')
    smallerThan50(TwoFace.Char('\u0020'))
    illTyped("""smallerThan50('\u0032')""")
    illTyped("""smallerThan50(TwoFace.Char('\u0032'))""")
  }

  property("Run-time checks") = wellTyped {
    smallerThan50(us('\u0020'))
    smallerThan50(TwoFace.Char(us('\u0020')))
    illRun{smallerThan50(us('\u0032'))}
    illRun{smallerThan50(TwoFace.Char(us('\u0032')))}
  }
} 
Example 84
Source File: CheckedDoubleSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedDoubleSpec {
  object SmallerThan50 extends Checked0Param.Double {
    type Cond[T] = T < W.`50.0`.T
    type Msg[T] = W.`"Failed Check"`.T
  }
}

class CheckedDoubleSpec extends Properties("Checked.Double") {
  import CheckedDoubleSpec._

  def smallerThan50[T](t : SmallerThan50.Checked[T]) : Unit = {t.unsafeCheck()}

  property("Compile-time checks") = wellTyped {
    smallerThan50(40.0)
    smallerThan50(TwoFace.Double(40.0))
    illTyped("""smallerThan50(50.0)""")
    illTyped("""smallerThan50(TwoFace.Double(50.0))""")
  }

  property("Run-time checks") = wellTyped {
    smallerThan50(us(40.0))
    smallerThan50(TwoFace.Double(us(40.0)))
    illRun{smallerThan50(us(50.0))}
    illRun{smallerThan50(TwoFace.Double(us(50.0)))}
  }
} 
Example 85
Source File: CheckedFloatSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedFloatSpec {
  object SmallerThan50 extends Checked0Param.Float {
    type Cond[T] = T < W.`50.0f`.T
    type Msg[T] = W.`"Failed Check"`.T
  }
}

class CheckedFloatSpec extends Properties("Checked.Float") {
  import CheckedFloatSpec._

  def smallerThan50[T](t : SmallerThan50.Checked[T]) : Unit = {t.unsafeCheck()}

  property("Compile-time checks") = wellTyped {
    smallerThan50(40.0f)
    smallerThan50(TwoFace.Float(40.0f))
    illTyped("""smallerThan50(50.0f)""")
    illTyped("""smallerThan50(TwoFace.Float(50.0f))""")
  }

  property("Run-time checks") = wellTyped {
    smallerThan50(us(40.0f))
    smallerThan50(TwoFace.Float(us(40.0f)))
    illRun{smallerThan50(us(50.0f))}
    illRun{smallerThan50(TwoFace.Float(us(50.0f)))}
  }
} 
Example 86
Source File: CheckedIntSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedIntSpec {
  object SmallerThan50 extends Checked0Param.Int {
    type Cond[T] = T < W.`50`.T
    type Msg[T] = W.`"Failed Check"`.T
  }
}

class CheckedIntSpec extends Properties("Checked.Int") {
  import CheckedIntSpec._

  def foo[T](t : TwoFace.Int[T]) = t
  def smallerThan50[T](t : SmallerThan50.Checked[T]) = {
    val a : Int = t
    foo(t.unsafeCheck())
  }
  def smallerThan50Seq(tSeq : SmallerThan50.Checked[Int]*) = {
    for (t <- tSeq) {
      val a : Int = t
      foo(t.unsafeCheck())
    }
  }

  property("Compile-time checks") = wellTyped {
    implicitly[SmallerThan50.Checked[W.`5`.T]]
    val b = implicitly[SmallerThan50.Checked[W.`5`.T + W.`3`.T]]
    implicitly[b.Out <:< (W.`5`.T + W.`3`.T)]
    val c = smallerThan50(40)
    implicitly[c.Out <:< W.`40`.T]
    smallerThan50(TwoFace.Int(40))
    smallerThan50(TwoFace.Int[W.`30`.T])
    smallerThan50(implicitly[TwoFace.Int[W.`30`.T]])
    smallerThan50Seq(1,2,3)
    val widen : SmallerThan50.Checked[Int] = 5
    illTyped("""smallerThan50(50)""" ,"Failed Check")
    illTyped("""smallerThan50(TwoFace.Int(50))""", "Failed Check")
    illTyped("""implicitly[SmallerThan50.Checked[W.`60`.T]]""", "Failed Check")
    illTyped("""val widen2 : SmallerThan50.Checked[Int] = 50""" ,"Failed Check")
    illTyped("""smallerThan50Seq(1,us(70),60)""","Failed Check")
  }

  property("Run-time checks") = wellTyped {
    smallerThan50Seq(1,2,3)
    smallerThan50Seq(us(1),2,3)
    smallerThan50(us(40))
    smallerThan50(TwoFace.Int(us(40)))
    val us70 = 70
    val us60 = 60
    illRun{smallerThan50(us(50))}
    illRun{smallerThan50(TwoFace.Int(us(50)))}
    illRun{smallerThan50Seq(1,us70,us60)}
  }

  //Maybe at fault of Scalac, but some schemes prove better than others to avoid errors
  property("Stability check") = wellTyped {
    class Fooish[T]
    class Foo {
      final def foo : Fooish[W.`4`.T] = new Fooish[W.`4`.T]
      final def foo[T](value : SmallerThan50.Checked[T]) : Fooish[value.Out] = new Fooish[value.Out]
    }
    val a = new Foo
    val b : Fooish[W.`2`.T] = a.foo(2)
    val two = 2
    val c : Fooish[Int] = a.foo(two)
  }
} 
Example 87
Source File: CheckedStringSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedStringSpec {
  object LengthSmallerThan extends Checked1Param.String {
    type Cond[T, P] = Length[T] < P
    type Msg[T, P] = W.`"Length of string '"`.T + T + W.`"' is not smaller than "`.T + ToString[P]
    type ParamFace = Int
  }
}

class CheckedStringSpec extends Properties("Checked.String") {
  import CheckedStringSpec._

  def foo[T](t : TwoFace.String[T]) : Unit = {}
  def lengthSmallerThan5[T](t : LengthSmallerThan.Checked[T,Id[W.`5`.T]]) : Unit = {
    val temp : String = t
    foo(t.unsafeCheck(5))
  }
  def lengthSmallerThan5Seq(tSeq : LengthSmallerThan.Checked[String,W.`5`.T]*) : Unit = {
    for (t <- tSeq) {
      val temp : String = t
      foo(t.unsafeCheck(5))
    }
  }
  def lengthSmallerThanFive[T](t : LengthSmallerThan.Checked[T, Int]) : Unit = {
    val temp : String = t
    foo(t.unsafeCheck(5))
  }
  def lengthSmallerThanFiveImpl[T](implicit t : LengthSmallerThan.Checked[T, Int]) : Unit = {
    val temp : String = t
    foo(t.unsafeCheck(5))
  }

  property("Compile-time checks") = wellTyped {
    lengthSmallerThan5("Hi")
    lengthSmallerThan5(TwoFace.String("Hi"))
    implicitly[LengthSmallerThan.Checked[W.`"Hi"`.T,W.`5`.T]]
    lengthSmallerThan5Seq("Hi", "Hey")
    illTyped("""lengthSmallerThan5("Hello")""","Length of string 'Hello' is not smaller than 5")
    illTyped("""lengthSmallerThan5(TwoFace.String("Hello"))""","Length of string 'Hello' is not smaller than 5")
    illTyped("""implicitly[LengthSmallerThan.Checked[W.`"Hello"`.T,W.`5`.T]]""","Length of string 'Hello' is not smaller than 5")
    illTyped("""lengthSmallerThan5Seq("Hi", "Hey", "Hello")""","Length of string 'Hello' is not smaller than 5")
  }

  property("Run-time checks") = wellTyped {
    lengthSmallerThan5(us("Hi"))
    lengthSmallerThan5(TwoFace.String(us("Hi")))
    lengthSmallerThanFive("Hi")
    lengthSmallerThanFive(TwoFace.String("Hi"))
    lengthSmallerThan5Seq(us("Hi"), "Hey")
    lengthSmallerThanFiveImpl[W.`"Hi"`.T]
    illRun{lengthSmallerThan5(us("Hello"))}
    illRun{lengthSmallerThan5(TwoFace.String(us("Hello")))}
    illRun{lengthSmallerThanFive("Hello")}
    illRun{lengthSmallerThanFive(TwoFace.String("Hello"))}
    illRun{lengthSmallerThanFiveImpl[W.`"Hello"`.T]}
    val usHello = "Hello"
    illRun{lengthSmallerThan5Seq(us("Hi"), "Hey", usHello)}
  }

  def lengthSmallerThan5Impl[T](realValue : String)(implicit t : LengthSmallerThan.CheckedShell[T,W.`5`.T]) : Unit =
    {t.unsafeCheck(realValue, 5)}

  property("Shell compile-time checks") = wellTyped {
    lengthSmallerThan5Impl[W.`"Hi"`.T](us("Hi"))
    illTyped("""lengthSmallerThan5Impl[W.`"Hello"`.T](us("Hello"))""", "Length of string 'Hello' is not smaller than 5")
  }

  property("Shell run-time checks") = wellTyped {
    lengthSmallerThan5Impl[String](us("Hi"))
    illRun{lengthSmallerThan5Impl[String](us("Hello"))}
  }

  trait CheckedUse[T]
  object CheckedUse {
    implicit def ev[T](implicit checkedTrue: LengthSmallerThan.CheckedShellSym[CheckedUse[_], T, W.`5`.T]) : CheckedUse[T] =
      new CheckedUse[T] {}
  }

  property("Shell user message redirect checks") = wellTyped {
    implicitly[CheckedUse[W.`"Hi"`.T]]
    illTyped("""implicitly[CheckedUse[W.`"Hello"`.T]]""", "Length of string 'Hello' is not smaller than 5")
  }

} 
Example 88
Source File: CheckedIntSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.twoface

import org.scalacheck.Properties
import shapeless.test.illTyped
import singleton.TestUtils._
import singleton.ops._

object CheckedIntSpec {
  object SmallerThan50 extends Checked0Param.Int {
    type Cond[T] = T < W.`50`.T
    type Msg[T] = W.`"Failed Check"`.T
  }
}

class CheckedIntSpec extends Properties("Checked.Int") {
  import CheckedIntSpec._

  def foo[T](t : TwoFace.Int[T]) = t
  def smallerThan50[T](t : SmallerThan50.Checked[T]) = {
    val a : Int = t
    foo(t.unsafeCheck())
  }
  def smallerThan50Seq(tSeq : SmallerThan50.Checked[Int]*) = {
    for (t <- tSeq) {
      val a : Int = t
      foo(t.unsafeCheck())
    }
  }

  property("Compile-time checks") = wellTyped {
    implicitly[SmallerThan50.Checked[W.`5`.T]]
    val b = implicitly[SmallerThan50.Checked[W.`5`.T + W.`3`.T]]
    implicitly[b.Out <:< (W.`5`.T + W.`3`.T)]
    val c = smallerThan50(40)
    implicitly[c.Out <:< W.`40`.T]
    smallerThan50(TwoFace.Int(40))
    smallerThan50(TwoFace.Int[W.`30`.T])
    smallerThan50(implicitly[TwoFace.Int[W.`30`.T]])
    smallerThan50Seq(1,2,3)
    val widen : SmallerThan50.Checked[Int] = 5
    illTyped("""smallerThan50(50)""" ,"Failed Check")
    illTyped("""smallerThan50(TwoFace.Int(50))""", "Failed Check")
    illTyped("""implicitly[SmallerThan50.Checked[W.`60`.T]]""", "Failed Check")
    illTyped("""val widen2 : SmallerThan50.Checked[Int] = 50""" ,"Failed Check")
    illTyped("""smallerThan50Seq(1,us(70),60)""","Failed Check")
  }

  property("Run-time checks") = wellTyped {
    smallerThan50Seq(us(1),2,3)
    smallerThan50(us(40))
    smallerThan50(TwoFace.Int(us(40)))
    val us70 = 70
    val us60 = 60
    illRun{smallerThan50(us(50))}
    illRun{smallerThan50(TwoFace.Int(us(50)))}
    illRun{smallerThan50Seq(1,us70,us60)}
  }
} 
Example 89
Source File: NegatableArraySetCheck.scala    From abc   with Apache License 2.0 5 votes vote down vote up
package com.rklaehn.abc

import org.scalacheck.Properties
import org.scalacheck.Prop._
import algebra.lattice.Bool
import algebra.laws._
import cats.kernel.instances.all._
import cats.kernel.laws.OrderLaws
import Instances._
import arb._
import cogen._
import org.scalatest.FunSuite
import org.typelevel.discipline.scalatest.Discipline

class NegatableArraySetLawCheck extends FunSuite with Discipline {
  checkAll("LogicLaws[NegatableArraySet[Int]].bool", LogicLaws[NegatableArraySet[Int]].bool)
  checkAll("OrderLaws[NegatableArraySet[Int]].partialOrder", OrderLaws[NegatableArraySet[Int]].partialOrder)
}

object NegatableArraySetSampleCheck extends Properties("NegatableArraySet") {

  def unaryOp(a: NegatableArraySet[Int], r: NegatableArraySet[Int], op: Boolean ⇒ Boolean): Boolean = {
    val samples = a.elements0 :+ Int.MinValue
    samples.forall { e ⇒
      r(e) == op(a(e))
    }
  }

  def binaryOp(a: NegatableArraySet[Int], b: NegatableArraySet[Int], r: NegatableArraySet[Int], op: (Boolean, Boolean) ⇒ Boolean): Boolean = {
    val samples = (a.elements0 ++ b.elements0).distinct :+ Int.MinValue
    samples.forall { e ⇒
      r(e) == op(a(e), b(e))
    }
  }
  
  val bool = implicitly[Bool[NegatableArraySet[Int]]]

  property("and") = forAll { (x: NegatableArraySet[Int], y: NegatableArraySet[Int]) ⇒
    binaryOp(x, y, bool.and(x, y), _ & _)
  }

  property("or") = forAll { (x: NegatableArraySet[Int], y: NegatableArraySet[Int]) ⇒
    binaryOp(x, y, bool.or(x, y), _ | _)
  }

  property("xor") = forAll { (x: NegatableArraySet[Int], y: NegatableArraySet[Int]) ⇒
    binaryOp(x, y, bool.xor(x, y), _ ^ _)
  }

  property("diff") = forAll { (x: NegatableArraySet[Int], y: NegatableArraySet[Int]) ⇒
    binaryOp(x, y, x diff y, (x,y) ⇒ x & !y)
  }

  property("not") = forAll { x: NegatableArraySet[Int] ⇒
    unaryOp(x, bool.complement(x), !_)
  }

  property("subsetOf") = forAll { (x: NegatableArraySet[Int], y: NegatableArraySet[Int]) ⇒
    val r1 = x subsetOf y
    val r0 = (x union y) === y
    r0 == r1
  }

  property("intersects") = forAll { (x: NegatableArraySet[Int], y: NegatableArraySet[Int]) ⇒
    val r1 = x intersects y
    val r0 = !(x intersect y).isEmpty
    r0 == r1
  }

  property("toString") = forAll { x: NegatableArraySet[Int] ⇒
    !x.toString.isEmpty
  }

  property("isEmpty") = forAll { x: NegatableArraySet[Int] ⇒
    if(x.isEmpty)
      x.elements.isEmpty
    else
      true
  }

  property("+") = forAll { (x: NegatableArraySet[Int], y: Int) ⇒
    (x + y).apply(y)
  }

  property("-") = forAll { (x: NegatableArraySet[Int], y: Int) ⇒
    !(x - y).apply(y)
  }
} 
Example 90
Source File: ArraySetCheck.scala    From abc   with Apache License 2.0 5 votes vote down vote up
package com.rklaehn.abc

import algebra.Eq
import org.scalacheck.{Arbitrary, Properties}
import org.scalacheck.Prop._
import cats.kernel.instances.all._
import Instances._

object ArraySetSampleCheck extends Properties("ArraySet") {
  import arb._

  def unaryOp(a: ArraySet[Int], r: ArraySet[Int], op: Boolean ⇒ Boolean): Boolean = {
    val samples = a.elements :+ Int.MinValue
    samples.forall { e ⇒
      r(e) == op(a(e))
    }
  }

  def binaryOp(a: ArraySet[Int], b: ArraySet[Int], r: ArraySet[Int], op: (Boolean, Boolean) ⇒ Boolean): Boolean = {
    val samples = (a.elements ++ b.elements).distinct :+ Int.MinValue
    samples.forall { e ⇒
      r(e) == op(a(e), b(e))
    }
  }

  property("and") = forAll { (x: ArraySet[Int], y: ArraySet[Int]) ⇒
    binaryOp(x, y, x intersect y, _ & _)
  }

  property("or") = forAll { (x: ArraySet[Int], y: ArraySet[Int]) ⇒
    binaryOp(x, y, x union y, _ | _)
  }

  property("xor") = forAll { (x: ArraySet[Int], y: ArraySet[Int]) ⇒
    binaryOp(x, y, x xor y, _ ^ _)
  }

  property("diff") = forAll { (x: ArraySet[Int], y: ArraySet[Int]) ⇒
    binaryOp(x, y, x diff y, (x,y) ⇒ x & !y)
  }

  property("subsetOf") = forAll { (x: ArraySet[Int], y: ArraySet[Int]) ⇒
    val r1 = x subsetOf y
    val r0 = (x union y) === y
    r0 == r1
  }

  property("intersects") = forAll { (x: ArraySet[Int], y: ArraySet[Int]) ⇒
    val r1 = x intersects y
    val r0 = !(x intersect y).isEmpty
    r0 == r1
  }

  property("toString") = forAll { x: ArraySet[Int] ⇒
    !x.toString.isEmpty
  }

  property("iterator") = forAll { x: ArraySet[Int] ⇒
    x.iterator.toArray === x.elements
  }

  property("isEmpty") = forAll { x: ArraySet[Int] ⇒
    if(x.isEmpty)
      x.asArraySeq.isEmpty
    else
      true
  }

  property("+") = forAll { (x: ArraySet[Int], y: Int) ⇒
    (x + y).contains(y)
  }

  property("-") = forAll { (x: ArraySet[Int], y: Int) ⇒
    !(x - y).contains(y)
  }

  property("filter") = forAll { (x: ArraySet[Int], y: ArraySet[Int]) ⇒
    (x diff y) === (x filter(e ⇒ !y.contains(e)))
  }

  property("hash") = forAll { (x: Set[Int]) ⇒
    val a = ArraySet(x.toSeq: _*)
    val b = ArraySet(x.toSeq.reverse: _*)
    Eq.eqv(a, b) && Hash.hash(a) == Hash.hash(b)
  }
} 
Example 91
Source File: ArraySeqCheck.scala    From abc   with Apache License 2.0 5 votes vote down vote up
package com.rklaehn.abc

import algebra.Eq
import org.scalacheck.{Arbitrary, Properties}
import org.scalacheck.Prop._
 import cats.kernel.instances.all._
import Instances._

object ArraySeqSampleCheck extends Properties("ArraySet") {
  import arb._

  property("hash") = forAll { (x: Seq[Int]) ⇒
    val a = ArraySeq(x: _*)
    val b = ArraySeq(x: _*)
    Eq.eqv(a, b) && Hash.hash(a) == Hash.hash(b)
  }

  property("flatMap") = forAll { as: ArraySeq[Int] ⇒
    as.flatMap(x ⇒ ArraySeq(x, x + 1)).length == as.length * 2
  }
} 
Example 92
Source File: TransformBstProperties.scala    From functional-way   with GNU General Public License v3.0 5 votes vote down vote up
import org.scalacheck.{Gen, Properties}
import org.scalacheck.Gen._
import org.scalacheck.Prop.forAll
import org.scalacheck.Arbitrary.arbitrary
import tree.transformBst
import tree.MaybeNode

class TransformBstProperties extends Properties("TransformBST") {

  import tree.Node

  private val leafNodeGen : Gen[Node] = arbitrary[Int].map(v => Node(left = null, right = null, value = v))

  private val nodeGen = for {
    v <- arbitrary[Int]
    left <- genTree
    right <- genTree
  } yield Node(value = v, left = left, right = right)

  private val genTree : Gen[Node] = oneOf(nodeGen, leafNodeGen)

  
  private def isZeroPresent(node : MaybeNode) : Boolean = node match {
    case n: Node => if(n.value == 0) true else {
      isZeroPresent(n.left) || isZeroPresent(n.right)
    }
    case null => false
  }

  //Not a complete test here. But a good one to begin with
  property("transformBst") = forAll(genTree) { (root : Node) =>
    val transformedTreeRoot = transformBst(root)
    isZeroPresent(transformedTreeRoot)
  }

} 
Example 93
Source File: PreferenceListSpecification.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica

import justin.db.consistenthashing.Ring
import org.scalacheck.Prop._
import org.scalacheck.{Gen, Properties}

class PreferenceListSpecification extends Properties("PreferenceList") {

  property("head of preference-list is initial partitionId") = {
    val ring = Ring.apply(nodesSize = 5, partitionsSize = 64)
    val n = N(3)
    val partitionIdGen = Gen.choose(0, ring.size-1)

    forAll(partitionIdGen) { basePartitionId: Int =>
      PreferenceList(basePartitionId, n, ring).right.get.primaryNodeId == ring.getNodeId(basePartitionId).get
    }
  }
} 
Example 94
Source File: HCacheTests.scala    From dagon   with Apache License 2.0 5 votes vote down vote up
package com.stripe.dagon

import org.scalacheck.Prop._
import org.scalacheck.{Arbitrary, Cogen, Properties}

abstract class HCacheTests[K[_], V[_]](name: String)(implicit
  ka: Arbitrary[K[Int]], kc: Cogen[K[Int]],
  va: Arbitrary[V[Int]])
    extends Properties(name) {

  def buildHMap(c: HCache[K, V], ks: Iterable[K[Int]], f: K[Int] => V[Int]): HMap[K, V] =
    ks.iterator.foldLeft(HMap.empty[K, V]) {
      (m, k) => m.updated(k, c.getOrElseUpdate(k, f(k)))
    }

  property("getOrElseUpdate") =
    forAll { (f: K[Int] => V[Int], k: K[Int], v1: V[Int], v2: V[Int]) =>
      val c = HCache.empty[K, V]
      var count = 0
      val x = c.getOrElseUpdate(k, { count += 1; v1 })
      val y = c.getOrElseUpdate(k, { count += 1; v2 })
      x == v1 && y == v1 && count == 1
    }

  property("toHMap") =
    forAll { (f: K[Int] => V[Int], ks: Set[K[Int]]) =>
      val c = HCache.empty[K, V]
      val m = buildHMap(c, ks, f)
      c.toHMap == m
    }

  property("duplicate") =
    forAll { (f: K[Int] => V[Int], ks: Set[K[Int]]) =>
      val c = HCache.empty[K, V]
      val d = c.duplicate
      buildHMap(c, ks, f)
      d.toHMap.isEmpty
    }

  property("reset works") =
    forAll { (f: K[Int] => V[Int], ks: Set[K[Int]]) =>
      val c = HCache.empty[K, V]
      buildHMap(c, ks, f)
      val d = c.duplicate
      c.reset()
      c.toHMap.isEmpty && d.toHMap.size == ks.size
    }
}

object HCacheTestsLL extends HCacheTests[List, List]("HCacheTests[List, List]") 
Example 95
Source File: CacheTests.scala    From dagon   with Apache License 2.0 5 votes vote down vote up
package com.stripe.dagon

import org.scalacheck.Prop._
import org.scalacheck.{Arbitrary, Cogen, Properties}

abstract class CacheTests[K: Cogen: Arbitrary, V: Arbitrary](name: String) extends Properties(name) {

  def buildMap(c: Cache[K, V], ks: Iterable[K], f: K => V): Map[K, V] =
    ks.iterator.foldLeft(Map.empty[K, V]) {
      (m, k) => m.updated(k, c.getOrElseUpdate(k, f(k)))
    }

  property("getOrElseUpdate") =
    forAll { (f: K => V, k: K, v1: V, v2: V) =>
      val c = Cache.empty[K, V]
      var count = 0
      val x = c.getOrElseUpdate(k, { count += 1; v1 })
      val y = c.getOrElseUpdate(k, { count += 1; v2 })
      x == v1 && y == v1 && count == 1
    }

  property("toMap") =
    forAll { (f: K => V, ks: Set[K]) =>
      val c = Cache.empty[K, V]
      val m = buildMap(c, ks, f)
      c.toMap == m
    }

  property("duplicate") =
    forAll { (f: K => V, ks: Set[K]) =>
      val c = Cache.empty[K, V]
      val d = c.duplicate
      buildMap(c, ks, f)
      d.toMap.isEmpty
    }

  property("reset works") =
    forAll { (f: K => V, ks: Set[K]) =>
      val c = Cache.empty[K, V]
      buildMap(c, ks, f)
      val d = c.duplicate
      c.reset()
      c.toMap.isEmpty && d.toMap.size == ks.size
    }
}

object CacheTestsSL extends CacheTests[String, Long]("CacheTests[String, Long]") 
Example 96
Source File: CheckJsIntegerSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.shrinkable

import org.scalacheck.Prop.{BooleanOperators, forAll}
import org.scalacheck.{Arbitrary, Properties, Shrink}

object CheckJsIntegerSpecification extends Properties("JsInteger") {
  property("shrink no min/max") = forAll(Arbitrary.arbitrary[BigInt].suchThat(_ != 0)) {
    value =>
      val original = CheckJsInteger(None, None, value)

      val shrink = Shrink.shrink(original)

      shrink.nonEmpty :| "Shrink not empty" && shrink.forall {
        shrinked =>
          if (value < 0)
            shrinked.min.isEmpty && shrinked.max.isEmpty && shrinked.value > value
          else
            shrinked.min.isEmpty && shrinked.max.isEmpty && shrinked.value < value
      } :| "Shrink values valid"
  }

  property("shrink no max") = forAll(
    Arbitrary.arbitrary[BigInt].suchThat(_ != 0),
    Arbitrary.arbitrary[BigInt].suchThat(_ != 0).map(_.abs)) {
    (min, diff) =>
      val value = min + diff
      val original = CheckJsInteger(Some(min), None, value)

      val shrink = Shrink.shrink(original)

      if (value == 0)
        shrink.isEmpty :| "Shrink empty"
      else
        shrink.nonEmpty :| "Shrink not empty" && shrink.forall {
          shrinked =>
            if (value < 0)
              shrinked.min.contains(min) && shrinked.max.isEmpty && shrinked.value > value && shrinked.value >= min
            else
              shrinked.min.contains(min) && shrinked.max.isEmpty && shrinked.value < value && shrinked.value >= min
        } :| "Shrink values valid"
  }

  property("shrink no min") = forAll(
    Arbitrary.arbitrary[BigInt].suchThat(_ != 0),
    Arbitrary.arbitrary[BigInt].suchThat(_ != 0).map(_.abs)) {
    (max, diff) =>
      val value = max - diff
      val original = CheckJsInteger(None, Some(max), value)

      val shrink = Shrink.shrink(original)

      if (value == 0)
        shrink.isEmpty :| "Shrink empty"
      else
        shrink.nonEmpty :| "Shrink not empty" && shrink.forall {
          shrinked =>
            if (value < 0)
              shrinked.max.contains(max) && shrinked.min.isEmpty && shrinked.value > value && shrinked.value <= max
            else
              shrinked.max.contains(max) && shrinked.min.isEmpty && shrinked.value < value && shrinked.value <= max
        } :| "Shrink values valid"
  }


  property("shrink min/max") = forAll(
    Arbitrary.arbitrary[BigInt].suchThat(_ != 0),
    Arbitrary.arbitrary[BigInt].suchThat(_ != 0).map(_.abs),
    Arbitrary.arbitrary[BigInt].suchThat(_ != 0).map(_.abs)
  ) {
    (min, diff1, diff2) =>
      val max = min + diff1 + diff2
      val value = min + diff1
      val original = CheckJsInteger(Some(min), Some(max), value)

      val shrink = Shrink.shrink(original)

      if (value == 0)
        shrink.isEmpty :| "Shrink empty"
      else
        shrink.nonEmpty :| "Shrink not empty" && shrink.forall {
          shrinked =>
            if (value < 0)
              shrinked.min.contains(min) && shrinked.max.contains(max) && shrinked.value > value && shrinked.value <= max
            else
              shrinked.min.contains(min) && shrinked.max.contains(max) && shrinked.value < value && shrinked.value <= max
        } :| "Shrink values valid"
  }
} 
Example 97
Source File: CheckJsValueSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.shrinkable

import de.leanovate.swaggercheck.TestSchema
import org.scalacheck.Prop._
import org.scalacheck.Properties

object CheckJsValueSpecification extends Properties("CheckJsValueSpecification") {
  val schema = TestSchema()

  property("arbitraryObject") = forAllNoShrink(schema.arbitraryObj.map(_.minified)) {
    json: String =>
      val jsValue = CheckJsValue.parse(json)

      jsValue.isInstanceOf[CheckJsObject] && jsValue.minified == json
      CheckJsValue.parse(jsValue.prettyfied) == jsValue
  }

  property("arbitraryArray") = forAllNoShrink(schema.arbitraryArray.map(_.minified)) {
    json: String =>
      val jsValue = CheckJsValue.parse(json)

      jsValue.isInstanceOf[CheckJsArray] && jsValue.minified == json
      CheckJsValue.parse(jsValue.prettyfied) == jsValue
  }
} 
Example 98
Source File: GeneratorsSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.generators

import java.net.{URI, URL}

import de.leanovate.swaggercheck.schema.model.JsonPath
import de.leanovate.swaggercheck.schema.model.formats.StringFormats
import org.scalacheck.Prop.forAll
import org.scalacheck.Properties

import scala.util.Try

object GeneratorsSpecification extends Properties("Generators") {
  property("generate valid urls") = forAll(Generators.url) {
    url =>
      Try(new URL(url)).isSuccess
  }

  property("generate valid uris") = forAll(Generators.uri) {
    url =>
      Try(new URI(url)).isSuccess
  }

  property("generate valid emails") = forAll(Generators.email) {
    email =>
      StringFormats.EmailString.validate(JsonPath(), email).isSuccess
  }
} 
Example 99
Source File: GeneratableObjectSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen

import de.leanovate.swaggercheck.schema.model.{BooleanDefinition, IntegerDefinition, ObjectDefinition, StringDefinition}
import org.scalacheck.Properties

object GeneratableObjectSpecification extends Properties("GeneratableObject") with DefinitionChecks {
  property("any generates are valid") = {
    val definition = ObjectDefinition(None, None, Left(true))

    checkDefinition(definition)
  }

  property("generates with properties are valid") = {
    val definition = ObjectDefinition(Some(Set("field1")), Some(Map(
      "field1" -> StringDefinition(None, None, None, None, None),
      "field2" -> IntegerDefinition(None, None, None),
      "field3" -> BooleanDefinition
    )), Left(true))

    checkDefinition(definition)
  }

  property("generate with additional properties are valid") = {
    val definition = ObjectDefinition(Some(Set("field1")), Some(Map(
      "field1" -> StringDefinition(None, None, None, None, None),
      "field2" -> IntegerDefinition(None, None, None),
      "field3" -> BooleanDefinition
    )), Right(StringDefinition(None, None, None, None, None)))

    checkDefinition(definition)
  }
} 
Example 100
Source File: GeneratableIntegerSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen

import de.leanovate.swaggercheck.schema.gen.GeneratableDefinition._
import de.leanovate.swaggercheck.schema.model.IntegerDefinition
import org.scalacheck.Properties

object GeneratableIntegerSpecification extends Properties("GeneratableInteger") with DefinitionChecks {
  property("any generate are valid") = {
    val definition = IntegerDefinition(None, None, None)

    checkDefinition(definition)
  }

  property("generate with format are valid") = {
    val definition = IntegerDefinition(Some("int32"), None, None)

    checkDefinition(definition)
  }

  property("generate with min are valid") = {
    val definition = IntegerDefinition(None, Some(12345), None)

    checkDefinition(definition)
  }

  property("generate with max are valid") = {
    val definition = IntegerDefinition(None, None, Some(12345))

    checkDefinition(definition)
  }
} 
Example 101
Source File: GeneratableSchemaSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen

import de.leanovate.swaggercheck.TestSchema
import de.leanovate.swaggercheck.shrinkable._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object GeneratableSchemaSpecification extends Properties("GeneratableSchema"){
  val schema = TestSchema()

  property("arbitraryObject") = forAll(schema.arbitraryObj) {
    node: CheckJsValue =>
      node.isInstanceOf[CheckJsObject]
  }

  property("arbitraryArray") = forAll(schema.arbitraryArray) {
    node: CheckJsValue =>
      node.isInstanceOf[CheckJsArray]
  }

  property("arbitraryValue") = forAll(schema.arbitraryValue) {
    node: CheckJsValue =>
      node.isInstanceOf[CheckJsString] || node.isInstanceOf[CheckJsInteger] || node.isInstanceOf[CheckJsBoolean]
  }
} 
Example 102
Source File: GeneratableAllOfSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen

import de.leanovate.swaggercheck.schema.model._
import org.scalacheck.Properties

object GeneratableAllOfSpecification extends Properties("GeneratableAllOf") with DefinitionChecks {
  property("generated are value") = {
    val definition = AllOfDefinition(Seq(
      ObjectDefinition(Some(Set("field1")), Some(Map(
        "field1" -> StringDefinition(None, None, None, None, None),
        "field2" -> IntegerDefinition(None, None, None),
        "field3" -> BooleanDefinition
      )), Left(true)),
      ObjectDefinition(Some(Set("field4")), Some(Map(
        "field4" -> StringDefinition(None, None, None, None, None),
        "field5" -> IntegerDefinition(None, None, None)
      )), Left(true))
    ))

    checkDefinition(definition)
  }
} 
Example 103
Source File: GeneratableOneOfSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen

import de.leanovate.swaggercheck.schema.model._
import org.scalacheck.Properties

object GeneratableOneOfSpecification extends Properties("GeneratableOneOf") with DefinitionChecks {
  property("generated are value") = {
    val definition = OneOfDefinition(Seq(
      ObjectDefinition(Some(Set("field1")), Some(Map(
        "field1" -> StringDefinition(None, None, None, None, None),
        "field2" -> IntegerDefinition(None, None, None),
        "field3" -> BooleanDefinition
      )), Left(true)),
      ObjectDefinition(Some(Set("field4")), Some(Map(
        "field4" -> StringDefinition(None, None, None, None, None),
        "field5" -> IntegerDefinition(None, None, None)
      )), Left(true))
    ))

    checkDefinition(definition)
  }
} 
Example 104
Source File: ValidatingReadsSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.play

import de.leanovate.swaggercheck.schema.model.DefaultSchema
import de.leanovate.swaggercheck.schema.play.model.ProductModel
import de.leanovate.swaggercheck.shrinkable.CheckJsValue
import org.scalacheck.Properties
import org.scalacheck.Prop.forAll
import play.api.libs.json.Json
import de.leanovate.swaggercheck.schema.play.Implicits._
import de.leanovate.swaggercheck.schema.gen.GeneratableDefaultSchema._

object ValidatingReadsSpecification extends Properties("ValidatingReads") {
  val schema = Json.parse(getClass.getClassLoader.getResourceAsStream("schema/simple1.json")).as[DefaultSchema]

  val valdiatingReads = ValidatingReads.validating[Seq[ProductModel]](schema)

  property("any generated can be deserialized") = forAll(schema.generate) {
    json : CheckJsValue =>
      Json.parse(json.minified).validate[Seq[ProductModel]].isSuccess
  }

  property("any generated can be validated") = forAll(schema.generate) {
    json : CheckJsValue =>
      Json.parse(json.minified).validate[Seq[ProductModel]](valdiatingReads).isSuccess
  }
} 
Example 105
Source File: UberApiSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck

import de.leanovate.swaggercheck.fixtures.uber.{UberError, UberProduct}
import de.leanovate.swaggercheck.schema.ValidationResultToProp
import de.leanovate.swaggercheck.simple._
import org.scalacheck.Prop.{BooleanOperators, forAll}
import org.scalacheck.{Arbitrary, Gen, Properties}
import play.api.libs.json.Json
import ValidationResultToProp._

object UberApiSpecification extends Properties("Uber API") {
  val swaggerChecks = SwaggerChecks(getClass.getClassLoader.getResourceAsStream("uber_api.yaml"))

  property("Error can be read") = forAll(swaggerChecks.jsonGenerator("Error")) {
    json =>
      Json.parse(json.minified).validate[UberError].isSuccess
  }

  property("Error can be written") = {
    val verifier = swaggerChecks.jsonVerifier("Error")

    forAll(Arbitrary.arbitrary[UberError]) {
      error: UberError =>
        val json = Json.stringify(Json.toJson(error))

        verifier.verify(json)
    }
  }

  property("Product can be read") = forAll(swaggerChecks.jsonGenerator("Product")) {
    json =>
      Json.parse(json.minified).validate[UberProduct].isSuccess
  }

  property("Product can be written") = {
    val verifier = swaggerChecks.jsonVerifier("Product")

    forAll(Arbitrary.arbitrary[UberProduct]) {
      product: UberProduct =>
        val json = Json.stringify(Json.toJson(product))

        verifier.verify(json)
    }
  }

  property("Request endpoints exists") = forAll(swaggerChecks.requestGenerator[SimpleRequest]()) {
    case SimpleRequest("GET", "/v1/estimates/price", queryParameters, headers, _) =>
      val paramNames = queryParameters.map(_._1).toSet
      (headers.head == "Accept" -> "application/json") :| "Accept header" &&
        paramNames.contains("start_latitude") :| "paramNames contains start_latitude" &&
        paramNames.contains("start_longitude") :| "paramNames contains start_longitude" &&
        paramNames.contains("end_latitude") :| "paramNames contains end_latitude" &&
        paramNames.contains("end_longitude") :| "paramNames contains end_longitude" &&
        (paramNames.size == 4) :| "paramNames size 4"
    case SimpleRequest("GET", "/v1/estimates/time", queryParameters, headers, _) =>
      val paramNames = queryParameters.map(_._1).toSet
      (headers.head == "Accept" -> "application/json") :| "Accept header" &&
        paramNames.contains("start_latitude") :| "paramNames contains start_latitude" &&
        paramNames.contains("start_longitude") :| "paramNames contains start_longitude" &&
        (paramNames.size <= 4) :| "paramNames size 4"
    case SimpleRequest("GET", "/v1/me", queryParameters, headers, _) =>
      (headers.head == "Accept" -> "application/json") :| "Accept header" &&
        queryParameters.isEmpty :| "query parameter is empty"
    case SimpleRequest("GET", "/v1/history", queryParameters, headers, _) =>
      (headers.head == "Accept" -> "application/json") :| "Accept header" &&
        (queryParameters.size <= 2) :| "query parameter is empty"
    case SimpleRequest("GET", "/v1/products", queryParameters, headers, _) =>
      val paramNames = queryParameters.map(_._1).toSet
      (headers.head == "Accept" -> "application/json") :| "Accept header" &&
        paramNames.contains("latitude") :| "paramNames contains latitude" &&
        paramNames.contains("longitude") :| "paramNames contains longitude" &&
        (paramNames.size <= 2) :| "paramNames size 2"
    case _ => false :| "Does not match any request"
  }

  property("Responses can be verified") = {
    val verifier = swaggerChecks.responseVerifier[SimpleResponse]("GET", "/v1/products")
    val okRepsonseGen = Gen.listOf(Arbitrary.arbitrary[UberProduct])
      .map(products => SimpleResponse(200, Map.empty, Json.stringify(Json.toJson(products))))
    val errorResponseGen = for {
      status <- Gen.choose(400, 599)
      error <- Arbitrary.arbitrary[UberError]
    } yield SimpleResponse(status, Map.empty, Json.stringify(Json.toJson(error)))

    forAll(Gen.oneOf(okRepsonseGen, errorResponseGen)) {
      response: SimpleResponse =>
        verifier.verify(response)
    }
  }

  property("Operation verifier") = forAll(swaggerChecks.operationVerifier[SimpleRequest, SimpleResponse](_ == "/v1/me")) {
    operationVerifier: SimpleOperationVerifier =>
      val profileJson = swaggerChecks.jsonGenerator("Profile")
      val response = SimpleResponse(200, Map.empty, profileJson.sample.get.minified)

      (operationVerifier.request.path == "/v1/me") :| "Path" &&
        (operationVerifier.request.method == "GET") :| "Method" &&
        operationVerifier.responseVerifier.verify(response).isSuccess :| "Response verifier"
  }
} 
Example 106
Source File: BookDbApiSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck

import java.util.UUID

import de.leanovate.swaggercheck.fixtures.bookdb.Author
import de.leanovate.swaggercheck.schema.ValidationResultToProp._
import de.leanovate.swaggercheck.simple._
import org.scalacheck.Prop.{BooleanOperators, forAll}
import org.scalacheck.{Arbitrary, Properties, Shrink}
import play.api.libs.json.Json

object BookDbApiSpecification extends Properties("BookDB API") {
  val swaggerChecks = SwaggerChecks(getClass.getClassLoader.getResourceAsStream("bookdb_api.yaml"))

  property("Author is correctly written") = {
    val verifier = swaggerChecks.jsonVerifier("Author")

    forAll(Arbitrary.arbitrary[Author]) {
      author: Author =>
        val json = Json.stringify(Json.toJson(author))

        verifier.verify(json)
    }
  }

  property("Author can be correctly parsed") = {
    val verifier = swaggerChecks.jsonVerifier("Author")

    forAll(swaggerChecks.jsonGenerator("Author")) {
      json =>
        Json.parse(json.minified).validate[Author].isSuccess :| "Json can be deserialized" &&
          verifier.verify(json.minified).isSuccess :| "Json conforms to own schema" &&
          Shrink.shrink(json).forall {
            shrinked =>
              verifier.verify(shrinked.minified).isSuccess
          } :| "All shrinked variants conform to schema"
    }
  }

  property("Request generator POST /author") = {
    val verifier = swaggerChecks.jsonVerifier("Author")

    forAll(swaggerChecks.requestGenerator("POST", "/v1/authors")) {
      request =>
        (request.method == "POST") :| "Method" &&
          (request.path == "/v1/authors") :| "Path" &&
          request.body.isDefined :| "Has body" &&
          verifier.verify(request.body.get.minified).isSuccess :| "Body is author"
    }
  }

  property("Request generator GET /author/{id}") =
    forAll(swaggerChecks.requestGenerator("GET", "/v1/authors/{id}")) {
      request =>
        (request.method == "GET") :| "Method" &&
          request.path.startsWith("/v1/authors") :| "Path" &&
          (UUID.fromString(request.path.substring(12)) ne null) :| "Id is uuid" &&
          request.body.isEmpty :| "Has no body"
    }

  property("Operation verifier") = forAll(swaggerChecks.operationVerifier[SimpleRequest, SimpleResponse](_ == "/v1/authors")) {
    case operationVerifier: SimpleOperationVerifier if operationVerifier.request.method == "GET" =>
      val profileJson = swaggerChecks.jsonGenerator("AuthorsPage")
      val response = SimpleResponse(200, Map.empty, profileJson.sample.get.minified)

      (operationVerifier.request.path == "/v1/authors") :| "Path" &&
        (operationVerifier.request.method == "GET") :| "Method" &&
        operationVerifier.responseVerifier.verify(response).isSuccess :| "Response verifier"
    case operationVerifier: SimpleOperationVerifier =>
      val profileJson = swaggerChecks.jsonGenerator("Author")
      val response = SimpleResponse(201, Map.empty, "")

      (operationVerifier.request.path == "/v1/authors") :| "Path" &&
        (operationVerifier.request.method == "POST") :| "Method" &&
        operationVerifier.responseVerifier.verify(response).isSuccess :| "Response verifier"
      true :| "Just ok"
  }
} 
Example 107
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 108
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 109
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 110
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 111
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 112
Source File: P08Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

class P08Check extends Properties("P08") {
  def duplicates(list: List[Int]): Int = {
    @scala.annotation.tailrec
    def loop(list: List[Int], curr: Int, count: Int): Int =
      list match {
        case Nil => count
        case x :: xs =>
          if (curr == x) loop(xs, curr, count + 1) else loop(xs, x, count)
      }
    list match {
      case x :: xs => loop(xs, x, 0)
      case Nil     => 0
    }
  }
  property("compress()") = forAll { (s: List[Int]) =>
    P08.compress(s).length == s.length - duplicates(s)
  }
} 
Example 113
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 114
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 115
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 116
Source File: P16Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalacheck.{Gen, Properties}
import Gen.listOf, Gen.chooseNum
import org.scalacheck.Prop.forAll

class P16Check extends Properties("P16") {
  property("drop()") =
    forAll(listOf(chooseNum(Int.MinValue, Int.MaxValue)), chooseNum(1, 10)) {
      (s: List[Int], i: Int) =>
        (P16.drop(i, s) == s.zipWithIndex
          .map { case (e, j) => (e, j + 1) }
          .filterNot {
            case (e, j) =>
              j % i == 0
          }
          .map { _._1 })
    }
} 
Example 117
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 118
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 119
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 120
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 121
Source File: DeltaByteArrayEncoderSuite.scala    From OAP   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.execution.datasources.oap.io

import org.scalacheck.{Arbitrary, Gen, Properties}
import org.scalacheck.Prop.forAll
import org.scalatest.prop.Checkers

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.execution.datasources.oap.adapter.PropertiesAdapter
import org.apache.spark.sql.execution.datasources.oap.filecache.StringFiberBuilder
import org.apache.spark.sql.types.StringType
import org.apache.spark.unsafe.types.UTF8String

class DeltaByteArrayEncoderCheck extends Properties("DeltaByteArrayEncoder") {

  private val rowCountInEachGroup = Gen.choose(1, 1024)
  private val rowCountInLastGroup = Gen.choose(1, 1024)
  private val groupCount = Gen.choose(1, 100)

  property("Encoding/Decoding String Type") = forAll { (values: Array[String]) =>

    forAll(rowCountInEachGroup, rowCountInLastGroup, groupCount) {
      (rowCount, lastCount, groupCount) =>
        if (values.nonEmpty) {
          // This is the 'PLAIN' FiberBuilder to validate the 'Encoding/Decoding'
          // Normally, the test case should be:
          // values => encoded bytes => decoded bytes => decoded values (Using ColumnValues class)
          // Validate if 'values' and 'decoded values' are identical.
          // But ColumnValues only support read value form DataFile. So, we have to use another way
          // to validate.
          val referenceFiberBuilder = StringFiberBuilder(rowCount, 0)
          val fiberBuilder = DeltaByteArrayFiberBuilder(rowCount, 0, StringType)
          val fiberParser = DeltaByteArrayDataFiberParser(
            new OapDataFileMetaV1(rowCountInEachGroup = rowCount), StringType)
          !(0 until groupCount).exists { group =>
            // If lastCount > rowCount, assume lastCount = rowCount
            val count = if (group < groupCount - 1) {
              rowCount
            } else if (lastCount > rowCount) {
              rowCount
            } else {
              lastCount
            }
            (0 until count).foreach { row =>
              fiberBuilder.append(InternalRow(UTF8String.fromString(values(row % values.length))))
              referenceFiberBuilder
                .append(InternalRow(UTF8String.fromString(values(row % values.length))))
            }
            val bytes = fiberBuilder.build().fiberData
            val parsedBytes = fiberParser.parse(bytes, count)
            val referenceBytes = referenceFiberBuilder.build().fiberData
            referenceFiberBuilder.clear()
            fiberBuilder.clear()
            assert(parsedBytes.length == referenceBytes.length)
            parsedBytes.zip(referenceBytes).exists(byte => byte._1 != byte._2)
          }
        } else true
    }
  }
}

class DeltaByteArrayEncoderSuite extends SparkFunSuite with Checkers {

  test("Check Encoding/Decoding") {
    check(PropertiesAdapter.getProp(new DictionaryBasedEncoderCheck()))
  }
} 
Example 122
Source File: CodecFactorySuite.scala    From OAP   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.execution.datasources.oap.io

import org.apache.hadoop.conf.Configuration
import org.apache.parquet.format.CompressionCodec
import org.scalacheck.{Arbitrary, Gen, Properties}
import org.scalacheck.Prop.forAllNoShrink
import org.scalatest.prop.Checkers

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.execution.datasources.oap.adapter.PropertiesAdapter

class CodecFactoryCheck extends Properties("CodecFactory") {

  private val codecFactory = new CodecFactory(new Configuration())

  private val gen = Gen.sized { size =>
    for {
      codec <- Arbitrary.arbitrary[CompressionCodec]
      times <- Gen.posNum[Int]
      bytes <- Gen.containerOfN[Array, Byte](size * 100, Arbitrary.arbitrary[Byte])
    } yield (codec, times, bytes)
  }

  property("compress/decompress") = forAllNoShrink(gen) {
    // Array[Array[Byte]] means one group of fibers' data
    case (codec, times, bytes) =>
      val compressor = codecFactory.getCompressor(codec)
      val decompressor = codecFactory.getDecompressor(codec)

      (0 until times).forall(_ => decompressor.decompress(compressor.compress(bytes), bytes.length)
        .sameElements(bytes))
  }

  implicit lazy val arbCompressionCodec: Arbitrary[CompressionCodec] = {
    Arbitrary(genCompressionCodec)
  }
  private lazy val genCompressionCodec: Gen[CompressionCodec] = Gen.oneOf(
    CompressionCodec.UNCOMPRESSED, CompressionCodec.GZIP,
    CompressionCodec.SNAPPY, CompressionCodec.LZO)
}

class CodecFactorySuite extends SparkFunSuite with Checkers {

  test("Check CodecFactory Compress/Decompress") {
    check(PropertiesAdapter.getProp(new CodecFactoryCheck()))
  }
} 
Example 123
Source File: DictionaryBasedEncoderSuite.scala    From OAP   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.execution.datasources.oap.io

import org.apache.parquet.bytes.BytesInput
import org.apache.parquet.column.page.DictionaryPage
import org.apache.parquet.column.values.dictionary.PlainValuesDictionary.PlainBinaryDictionary
import org.scalacheck.{Arbitrary, Gen, Properties}
import org.scalacheck.Prop.forAll
import org.scalatest.prop.Checkers

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.execution.datasources.oap.adapter.PropertiesAdapter
import org.apache.spark.sql.execution.datasources.oap.filecache.StringFiberBuilder
import org.apache.spark.sql.types.StringType
import org.apache.spark.unsafe.types.UTF8String

class DictionaryBasedEncoderCheck extends Properties("DictionaryBasedEncoder") {
  private val rowCountInEachGroup = Gen.choose(1, 1024)
  private val rowCountInLastGroup = Gen.choose(1, 1024)
  private val groupCount = Gen.choose(1, 100)

  property("Encoding/Decoding String Type") = forAll { (values: Array[String]) =>

    forAll(rowCountInEachGroup, rowCountInLastGroup, groupCount) {
      (rowCount, lastCount, groupCount) =>
        if (values.nonEmpty) {
          // This is the 'PLAIN' FiberBuilder to validate the 'Encoding/Decoding'
          // Normally, the test case should be:
          // values => encoded bytes => decoded bytes => decoded values (Using ColumnValues class)
          // Validate if 'values' and 'decoded values' are identical.
          // But ColumnValues only support read value form DataFile. So, we have to use another way
          // to validate.
          val referenceFiberBuilder = StringFiberBuilder(rowCount, 0)
          val fiberBuilder = PlainBinaryDictionaryFiberBuilder(rowCount, 0, StringType)
          !(0 until groupCount).exists { group =>
            // If lastCount > rowCount, assume lastCount = rowCount
            val count =
              if (group < groupCount - 1) {
                rowCount
              } else if (lastCount > rowCount) {
                rowCount
              } else {
                lastCount
              }
            (0 until count).foreach { row =>
              fiberBuilder.append(InternalRow(UTF8String.fromString(values(row % values.length))))
              referenceFiberBuilder
                .append(InternalRow(UTF8String.fromString(values(row % values.length))))
            }
            val bytes = fiberBuilder.build().fiberData
            val dictionary = new PlainBinaryDictionary(
              new DictionaryPage(
                BytesInput.from(fiberBuilder.buildDictionary),
                fiberBuilder.getDictionarySize,
                org.apache.parquet.column.Encoding.PLAIN))
            val fiberParser = PlainDictionaryFiberParser(
              new OapDataFileMetaV1(rowCountInEachGroup = rowCount), dictionary, StringType)
            val parsedBytes = fiberParser.parse(bytes, count)
            val referenceBytes = referenceFiberBuilder.build().fiberData
            referenceFiberBuilder.clear()
            referenceFiberBuilder.resetDictionary()
            fiberBuilder.clear()
            fiberBuilder.resetDictionary()
            assert(parsedBytes.length == referenceBytes.length)
            parsedBytes.zip(referenceBytes).exists(byte => byte._1 != byte._2)
          }
        } else {
          true
        }
    }
  }
}

class DictionaryBasedEncoderSuite extends SparkFunSuite with Checkers {

  test("Check Encoding/Decoding") {
    check(PropertiesAdapter.getProp(new DictionaryBasedEncoderCheck()))
  }
} 
Example 124
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 125
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 126
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 127
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 128
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 129
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 130
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 131
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 132
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 133
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 134
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 135
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 136
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 137
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 138
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 139
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 140
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 141
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 142
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 143
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 144
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 145
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 146
Source File: ReGenTest.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.gen

import org.scalacheck.{Properties, Gen}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.{forAll, BooleanOperators, exists, atLeastOne}

object ReGenTest extends Properties("ReGen regex generators properties") {
 
  property("epsilon generates empty sequences") = 
    forAll (ReGen.epsilon) { (xs : Seq[Int]) =>
  	  xs.length == 0
  	}
  
  property("symbol generates a single element that contains the argument") = 
    forAll { x : String => 
      forAll (ReGen.symbol(x)) { xs : Seq[String] =>
        xs.length == 1 && xs(0) == x
      }
  }
  
   // def alt[A](gs : Gen[Seq[A]]*) : Gen[Seq[A]] = {
  property("alt is equivalent to epsilon if zero generators are provided") = 
    forAll (ReGen.alt()) { (xs : Seq[Int]) =>
      forAll (ReGen.epsilon) { (ys : Seq[Int]) =>
        xs == ys
      }
  }
  
  property("alt works for more than one argument, and generates values for some of the alternatives (weak, existential)") =  {
    val (g1, g2, g3) = (ReGen.symbol(0), ReGen.symbol(1), ReGen.symbol(2))
    forAll (ReGen.alt(g1, g2, g3)) { (xs : Seq[Int]) =>
      atLeastOne(
        exists (g1) { (ys : Seq[Int]) =>
        xs == ys
        },
        exists (g2) { (ys : Seq[Int]) =>
        xs == ys
        },
        exists (g3) { (ys : Seq[Int]) =>
        xs == ys
        }
      )
    }
  }

  // conc and star only have similar weak existential properties
} 
Example 147
Source File: UtilsGenTest.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.gen

import org.scalacheck.{Properties, Gen}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.{forAll, exists, BooleanOperators}
import Buildables.buildableSeq

object UtilsGenTest extends Properties("UtilsGenTest test") {  
  property("""containerOfNtoM is able to generate sequences of 
		  string with size between N and M strings for both N and M >= 0""")  = 
    forAll (Gen.choose(0, 10), Gen.choose(0, 10)) { (n : Int, m : Int) => 
      val g = UtilsGen.containerOfNtoM(n, m, arbitrary[String]) : Gen[Seq[String]]
      forAll (g) { ( xs : Seq[String]) =>   
       xs.length >= n && xs.length <= m 
      }
    }
  
  property("repN respects its lenght constraints") = 
    forAll (Gen.choose(0, 10), Gen.choose(0, 10)) { (n : Int, xsLen : Int) => 
      val g = UtilsGen.repN(n, Gen.listOfN(xsLen, Gen.alphaStr)) 
      forAll (g) { (xs : Seq[String])  =>
        xs.length == xsLen * n
      }
    }
  
  property("repNtoM respects its lenght constraints") = 
    forAll (Gen.choose(0, 10), Gen.choose(0, 10), Gen.choose(0, 10)) { (n : Int, m : Int, xsLen : Int) => 
      val g = UtilsGen.repNtoM(n, m, Gen.listOfN(xsLen, arbitrary[String])) 
      forAll (g) { (xs : Seq[String])  =>
        val xsLenObs = xs.length
        xsLenObs >= xsLen * n && xsLen * n <= xsLen * m 
      }
    }   
    
  property("""concSeq returns the result of concatenating the sequences 
generated by its arguments""") = {
    // In order for Prop.exists to be effective, we use a small domain.  
    // For all the lengths considered: this is very weak because very little lengths
    // are considered but it's better than nothing. 
    forAll (Gen.choose(0, 2)) { (xsLen : Int) =>
      // we consider two generators for lists of elements with that size
      val (gxs1, gxs2) = (Gen.listOfN(xsLen, Gen.choose(1, 3)), Gen.listOfN(xsLen, Gen.choose(4, 6)))
      // val g = UtilsGen.concSeq(gxs1, gxs2)
      forAll (UtilsGen.concSeq(gxs1, gxs2)) { (xs : Seq[Int]) =>
        // Prop.exists is not overloaded to support several generators
        // so we have to use zip
        exists (Gen.zip(gxs1, gxs2)) { (xs12 : (List[Int], List[Int])) =>
          xs == xs12._1 ++ xs12._2
        }
      }
    }    
  } 
} 
Example 148
Source File: RoleBindingSpec.scala    From sbt-kubeyml   with MIT License 5 votes vote down vote up
package kubeyml.roles

import org.scalacheck.Properties
import org.scalacheck.Prop.forAll
import json_support._
import io.circe.syntax._

class RoleBindingSpec extends Properties("RoleBinding") with KubernetesRoleBinding {

  property("validrolebinding") = forAll(roleBindingGen) {
    case (serviceAccount, roleBinding) =>
      val expectedJson = binding(
        roleBinding.metadata.namespace.value,
        roleBinding.metadata.name.value,
        serviceAccount,
        roleBinding.roleRef.role.metadata.name.value)

      val actualJson = Right(roleBinding.asJson)

      if (expectedJson != actualJson) {
        println(expectedJson)
        println(actualJson)
      }

      expectedJson == actualJson
  }

} 
Example 149
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 150
Source File: IntValues.scala    From scala-parallel-collections   with Apache License 2.0 5 votes vote down vote up
package scala.collection.parallel.ops

import org.scalacheck._
import org.scalacheck.Gen
import org.scalacheck.Gen._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import org.scalacheck.Arbitrary._

trait IntValues {
  def values = Seq(
      arbitrary[Int],
      arbitrary[Int] suchThat (_ >= 0),
      arbitrary[Int] suchThat (_ < 0),
      choose(0, 0),
      choose(0, 10),
      choose(0, 100),
      choose(0, 1000) suchThat (_ % 2 == 0),
      choose(0, 1000) suchThat (_ % 2 != 0),
      choose(0, 1000) suchThat (n => (n % 2 == 0) || (n % 3 == 0))
    )
} 
Example 151
Source File: ParallelVectorCheck.scala    From scala-parallel-collections   with Apache License 2.0 5 votes vote down vote up
package scala.collection
package parallel.immutable

import org.scalacheck._
import org.scalacheck.Gen
import org.scalacheck.Gen._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import org.scalacheck.Arbitrary._

import scala.collection._
import scala.collection.parallel.ops._

import immutable.Vector
import immutable.VectorBuilder

import scala.collection.parallel.TaskSupport

abstract class ParallelVectorCheck[T](tp: String) extends collection.parallel.ParallelSeqCheck[T]("ParVector[" + tp + "]") {
  // ForkJoinTasks.defaultForkJoinPool.setMaximumPoolSize(Runtime.getRuntime.availableProcessors * 2)
  // ForkJoinTasks.defaultForkJoinPool.setParallelism(Runtime.getRuntime.availableProcessors * 2)

  type CollType = ParVector[T]

  def isCheckingViews = false

  def hasStrictOrder = true

  def tasksupport: TaskSupport

  def ofSize(vals: Seq[Gen[T]], sz: Int) = {
    val vb = new immutable.VectorBuilder[T]()
    val gen = vals(rnd.nextInt(vals.size))
    for (i <- 0 until sz) vb += sample(gen)
    vb.result
  }

  def fromSeq(a: Seq[T]) = {
    val pc = ParVector.newCombiner[T]
    for (elem <- a.toList) pc += elem
    val pv = pc.result
    pv.tasksupport = tasksupport
    pv
  }

}

abstract class IntParallelVectorCheck(val tasksupport: TaskSupport) extends ParallelVectorCheck[Int]("Int") with IntSeqOperators with IntValues {
  override def instances(vals: Seq[Gen[Int]]) = oneOf(super.instances(vals), sized { sz =>
    (0 until sz).toArray.toSeq
  }, sized { sz =>
    (-sz until 0).toArray.toSeq
  })
} 
Example 152
Source File: PairValues.scala    From scala-parallel-collections   with Apache License 2.0 5 votes vote down vote up
package scala.collection.parallel.ops

import org.scalacheck._
import org.scalacheck.Gen
import org.scalacheck.Gen._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import org.scalacheck.Arbitrary._

trait PairValues[K, V] {
  def kvalues: Seq[Gen[K]]
  def vvalues: Seq[Gen[V]]

  def values = for {
    kg <- kvalues
    vg <- vvalues
  } yield for {
    k <- kg
    v <- vg
  } yield (k, v)
} 
Example 153
Source File: ParallelRangeCheck.scala    From scala-parallel-collections   with Apache License 2.0 5 votes vote down vote up
package scala.collection.parallel
package immutable

import org.scalacheck._
import org.scalacheck.Gen
import org.scalacheck.Gen._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import org.scalacheck.Arbitrary._

import scala.collection._
import scala.collection.parallel.ops._

abstract class ParallelRangeCheck(val tasksupport: TaskSupport) extends ParallelSeqCheck[Int]("ParallelRange[Int]") with ops.IntSeqOperators {
  // ForkJoinTasks.defaultForkJoinPool.setMaximumPoolSize(Runtime.getRuntime.availableProcessors * 2)
  // ForkJoinTasks.defaultForkJoinPool.setParallelism(Runtime.getRuntime.availableProcessors * 2)

  type CollType = collection.parallel.ParSeq[Int]

  def hasStrictOrder = true

  def isCheckingViews = false

  def ofSize(vals: Seq[Gen[Int]], sz: Int) = throw new UnsupportedOperationException

  override def instances(vals: Seq[Gen[Int]]): Gen[Seq[Int]] = sized { start =>
    sized { end =>
      sized { step =>
        Range(start, end, if (step != 0) step else 1)
      }
    }
  }

  def fromSeq(a: Seq[Int]) = a match {
    case r: Range =>
      val pr = ParRange(r.start, r.end, r.step, false)
      pr.tasksupport = tasksupport
      pr
    case _ =>
      val pa = new parallel.mutable.ParArray[Int](a.length)
      pa.tasksupport = tasksupport
      for (i <- 0 until a.length) pa(i) = a(i)
      pa
  }

  def values = Seq(choose(-100, 100))

} 
Example 154
Source File: ParallelSetCheck.scala    From scala-parallel-collections   with Apache License 2.0 5 votes vote down vote up
package scala.collection.parallel

import org.scalacheck._
import org.scalacheck.Gen
import org.scalacheck.Gen._
import org.scalacheck.Prop._
import org.scalacheck.Properties

import scala.collection._
import scala.collection.parallel._

abstract class ParallelSetCheck[T](collname: String) extends ParallelIterableCheck[T](collname) {

  type CollType <: ParSet[T]

  property("gets iterated keys") = forAllNoShrink(collectionPairs) {
    case (t, coll) =>
    val containsT = for (elem <- t) yield (coll.contains(elem))
    val containsSelf = for (elem <- coll) yield (coll.contains(elem))
    ("Par contains elements of seq map" |: containsT.forall(_ == true)) &&
    ("Par contains elements of itself" |: containsSelf.forall(_ == true))
  }

} 
Example 155
Source File: ParallelArrayCheck.scala    From scala-parallel-collections   with Apache License 2.0 5 votes vote down vote up
package scala.collection.parallel
package mutable

import org.scalacheck._
import org.scalacheck.Gen
import org.scalacheck.Gen._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import org.scalacheck.Arbitrary._

import scala.collection._
import scala.collection.parallel.ops._

abstract class ParallelArrayCheck[T](tp: String) extends ParallelSeqCheck[T]("ParArray[" + tp + "]") {
  // ForkJoinTasks.defaultForkJoinPool.setMaximumPoolSize(Runtime.getRuntime.availableProcessors * 2)
  // ForkJoinTasks.defaultForkJoinPool.setParallelism(Runtime.getRuntime.availableProcessors * 2)

  type CollType = ParArray[T]

  def isCheckingViews = false

  def hasStrictOrder = true

  def tasksupport: TaskSupport

  def ofSize(vals: Seq[Gen[T]], sz: Int) = {
    val a = new mutable.ArrayBuffer[T](sz)
    val gen = vals(rnd.nextInt(vals.size))
    for (i <- 0 until sz) a += sample(gen)
    a
  }

  def fromSeq(a: Seq[T]) = {
    val pa = new ParArray[T](a.size)
    pa.tasksupport = tasksupport
    var i = 0
    for (elem <- a.toList) {
      pa(i) = elem
      i += 1
    }
    pa
  }

  property("array mappings must be equal") = forAllNoShrink(collectionPairs) { case (t, coll) =>
    val results = for ((f, ind) <- mapFunctions.zipWithIndex)
      yield ("op index: " + ind) |: t.map(f).sameElements(coll.map(f))
    results.reduceLeft(_ && _)
  }

}

abstract class IntParallelArrayCheck(val tasksupport: TaskSupport) extends ParallelArrayCheck[Int]("Int") with IntSeqOperators with IntValues {
  override def instances(vals: Seq[Gen[Int]]) = oneOf(super.instances(vals), sized { sz =>
    (0 until sz).toArray.toSeq
  }, sized { sz =>
    (-sz until 0).toArray.toSeq
  })
} 
Example 156
Source File: PilotSpec.scala    From pizza-auth-3   with MIT License 5 votes vote down vote up
package moe.pizza.auth.models

import moe.pizza.auth.models.Pilot.CrestToken
import moe.pizza.eveapi.ApiKey
import org.scalacheck.Properties
import org.scalacheck.Prop.forAll


object PilotSpec extends Properties("Pilot") {

  property("getCrestKeys") = forAll { (charid: Long, token: String) =>
    val p = Pilot(null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  List("%d:%s".format(charid, token)),
                  null)
    p.getCrestTokens == List(new CrestToken(charid, token))
  }

  property("getApiKeys") = forAll { (id: Int, key: String) =>
    val p = Pilot(null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  List("%d:%s".format(id, key)))
    p.getApiKeys == List(new ApiKey(id, key))
  }

  property("toJson") = forAll {
    (uid: String, status: String, alliance: String, corp: String,
     character: String, email: String, meta: String, groups: List[String]) =>
      val p =
        Pilot(uid,
              Pilot.Status.lookup.getOrElse(status, Pilot.Status.ineligible),
              alliance,
              corp,
              character,
              email,
              Pilot.OM.readTree("{\"meta\": \"%s\"}".format(meta)),
              groups,
              List.empty,
              List.empty)
      val json = p.toJson
      val p2 = Pilot.fromJson(json)
      p2.contains(p)
  }

  property("getCrestKeys badinput") = forAll { (s: String) =>
    val p =
      Pilot(null, null, null, null, null, null, null, null, List(s), null)
    s.contains(":") == !p.getCrestTokens.isEmpty
  }

  property("getApiKeys, badinput") = forAll { (s: String) =>
    val p =
      Pilot(null, null, null, null, null, null, null, null, null, List(s))
    s.contains(":") == !p.getApiKeys.isEmpty
  }

  property("getGroups") = forAll { (g: String, g2: String) =>
    val p = Pilot(null, null, null, null, null, null, null, null, null, null)
    val p2 = p.copy(authGroups = List(g, g2 + "-pending"))
    p2.getGroups == List(g) && p2.getPendingGroups == List(g2)
  }

} 
Example 157
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 158
Source File: ExampleTableRowGenTest.scala    From ratatool   with Apache License 2.0 5 votes vote down vote up
package com.spotify.ratatool.examples

import com.google.api.services.bigquery.model.TableRow
import com.spotify.ratatool.examples.scalacheck.ExampleTableRowGen
import com.spotify.ratatool.scalacheck._
import org.scalacheck.{Gen, Properties}
import org.scalacheck.Prop.{AnyOperators, forAll}


object ExampleTableRowGenTest extends Properties("ExampleTableRowGenerator") {
  val gen: Gen[TableRow] = ExampleTableRowGen.tableRowGen
  val listGen: Gen[List[TableRow]] = Gen.listOfN(1000, gen)

  property("generates Foo and Bar more frequently than Fizz and Buzz") = forAll(listGen) { l =>
    val stringFields: Seq[String] = l.flatMap { r =>
      Option(r.getRecord("nullable_record"))
        .map(_.get("frequency_string_field").asInstanceOf[String])
    }

    stringFields.count(s => s == "Foo" || s == "Bar") >
      stringFields.count(s => s == "Fizz" || s == "Buzz")
  }

  property("generates valid dependent bytes") = forAll(gen) { r =>
    val s = r.getRecord("required_record").get("independent_string_field").asInstanceOf[String]
    val b = r.getRecord("required_record").get("dependent_bytes_field").asInstanceOf[Array[Byte]]
    new String(b) ?= s
  }

  property("the record id is the same when using amend2 generators") =
    forAll(ExampleTableRowGen.exampleRecordAmend2Gen) { case (gen1, gen2) =>
      gen1.get("record_id") == gen2.get("record_id")
    }

  property("the record id is the same when using amend2 for correlated fields") =
    forAll(ExampleTableRowGen.correlatedRecordGen) {
      case (correlatedRecord) => correlatedRecord.get("record_id") ==
        correlatedRecord.get("parent_record_id")
    }

} 
Example 159
Source File: ExampleAvroGenTest.scala    From ratatool   with Apache License 2.0 5 votes vote down vote up
package com.spotify.ratatool.examples

import java.util.UUID

import com.spotify.ratatool.avro.specific.{EnumField, ExampleRecord}
import com.spotify.ratatool.examples.scalacheck.ExampleAvroGen
import org.scalacheck.{Gen, Properties}
import org.scalacheck.Prop.{AnyOperators, BooleanOperators, forAll}

import scala.jdk.CollectionConverters._

object ExampleAvroGenTest extends Properties("ExampleAvroGenerator") {
  val gen: Gen[ExampleRecord] = ExampleAvroGen.exampleRecordGen

  property("round trips UUID") = forAll(gen) { m =>
    UUID.fromString(m.getRecordId.toString).toString ?= m.getRecordId.toString
  }

  property("generates valid dependent int") = forAll(gen) { m =>
    (m.getIndependentIntField == 0
      && m.getDependentIntField == Int.MaxValue) :| "Max if indep is 0" ||
    (m.getIndependentIntField != 0
      && m.getDependentIntField == m.getIndependentIntField/2) :| "Half when indep is not 0"
  }

  property("generates valid dependent enum") = forAll(gen) { m =>
    (m.getIndependentStringField.toString.startsWith("Exception") &&
      m.getDependentEnumField == EnumField.Failure) :| "Is Failure on Exception" ||
    (!m.getIndependentStringField.toString.startsWith("Exception") &&
      m.getDependentEnumField == EnumField.Success) :| "Is Success when non-Exception"
  }

  property("double field within bounds") = forAll(gen) { m =>
    m.getBoundedDoubleField <= 1.0 && m.getBoundedDoubleField >= -1.0
  }

  property("map field size within bounds") = forAll(gen) { m =>
    val size = m.getNestedRecordField.getMapField.asScala.size
    size <= 5 && size >= 0
  }

  property("the record id is the same when using amend2 generators") =
    forAll(ExampleAvroGen.exampleRecordAmend2Gen) {
      case (gen1, gen2) => gen1.getRecordId == gen2.getRecordId
    }

  property("the record id is the same when using amend2 for correlated fields") =
    forAll(ExampleAvroGen.correlatedRecordGen) {
      correlatedGen =>
        correlatedGen.getRecordId == correlatedGen.getNestedRecordField.getParentRecordId
    }
} 
Example 160
Source File: ProtoBufGeneratorTest.scala    From ratatool   with Apache License 2.0 5 votes vote down vote up
package com.spotify.ratatool.scalacheck

import com.spotify.ratatool.proto.Schemas.{OptionalNestedRecord, RequiredNestedRecord, TestRecord}
import org.scalacheck.{Gen, Properties}
import org.scalacheck.Prop.{BooleanOperators, all, forAll}


object ProtoBufGeneratorTest extends Properties("ProtoBufGenerator") {
  property("round trip") = forAll(protoBufOf[TestRecord]) { m =>
    m == TestRecord.parseFrom(m.toByteArray)
  }

  val optionalNestedRecordGen: Gen[OptionalNestedRecord] = protoBufOf[OptionalNestedRecord]
    .map(_.toBuilder)
    .amend(Gen.choose(10, 20))(_.setInt32Field)
    .amend(Gen.choose(10L, 20L))(_.setInt64Field)
    .amend(Gen.choose(10.0f, 20.0f))(_.setFloatField)
    .amend(Gen.choose(10.0, 20.0))(_.setDoubleField)
    .amend(Gen.const(true))(_.setBoolField)
    .amend(Gen.const("hello"))(_.setStringField, m => s => m.setUpperStringField(s.toUpperCase))
    .map(_.build())


  val richGen: Gen[TestRecord] = protoBufOf[TestRecord].map(_.toBuilder)
    .amend(optionalNestedRecordGen)(_.setOptionalFields)
    .map(_.build())

  val richTupGen =
    (protoBufOf[TestRecord].map(_.toBuilder), protoBufOf[TestRecord].map(_.toBuilder)).tupled
    .amend2(protoBufOf[RequiredNestedRecord])(_.setRequiredFields, _.setRequiredFields)
    .map{ case (a, b) => (a.build(), b.build()) }


  property("support RichProtoGen") = forAll (richGen) { r =>
    all(
      "Int" |:
        (r.getOptionalFields.getInt32Field >= 10 && r.getOptionalFields.getInt32Field <= 20),
      "Long" |:
        r.getOptionalFields.getInt64Field >= 10L && r.getOptionalFields.getInt64Field <= 20L,
      "Float" |:
        r.getOptionalFields.getFloatField >= 10.0f && r.getOptionalFields.getFloatField <= 20.0f,
      "Double" |:
        r.getOptionalFields.getDoubleField >= 10.0 && r.getOptionalFields.getDoubleField <= 20.0,
      "Boolean" |: r.getOptionalFields.getBoolField,
      "String" |: r.getOptionalFields.getStringField == "hello",
      "String" |: r.getOptionalFields.getUpperStringField == "HELLO"
    )
  }

  property("support RichProtoTupGen") = forAll (richTupGen) { case (a, b) =>
    (a.getRequiredFields.getBoolField == b.getRequiredFields.getBoolField
      && a.getRequiredFields.getInt32Field == b.getRequiredFields.getInt32Field
      && a.getRequiredFields.getFixed64Field == b.getRequiredFields.getFixed64Field
      && a.getRequiredFields.getStringField == b.getRequiredFields.getStringField
      && a.getRequiredFields.getUint32Field == b.getRequiredFields.getUint32Field)
  }
} 
Example 161
Source File: TableRowGeneratorTest.scala    From ratatool   with Apache License 2.0 5 votes vote down vote up
package com.spotify.ratatool.scalacheck

import com.google.api.services.bigquery.model.TableRow
import com.spotify.ratatool.Schemas
import org.scalacheck.{Arbitrary, Gen, Properties}
import org.scalacheck.Prop.{propBoolean, all, forAll}

object TableRowGeneratorTest extends Properties("TableRowGenerator") {
  property("round trip") = forAll(tableRowOf(Schemas.tableSchema)) { m =>
    m.setF(m.getF) == m
  }

  val n = "nullable_fields"
  val r = "required_fields"
  val richGen = tableRowOf(Schemas.tableSchema)
    .amend(Gen.choose(10L, 20L))(_.getRecord(n).set("int_field"))
    .amend(Gen.choose(10.0, 20.0))(_.getRecord(n).set("float_field"))
    .amend(Gen.const(true))(_.getRecord(n).set("boolean_field"))
    .amend(Gen.const("hello"))(_.getRecord(n).set("string_field"),
      m => s => m.getRecord(n).set("upper_string_field")(s.asInstanceOf[String].toUpperCase))

  val richTupGen = (tableRowOf(Schemas.tableSchema), tableRowOf(Schemas.tableSchema)).tupled
    .amend2(Gen.choose(10L, 20L))(_.getRecord(r).set("int_field"),
      a => a.getRecord(r).set("int_field"))
    .amend2(Arbitrary.arbString.arbitrary)(_.getRecord(r).set("string_field"),
      a => a.getRecord(r).set("string_field"))
    .amend2(Arbitrary.arbBool.arbitrary)(_.getRecord(r).set("boolean_field"),
      _.getRecord(r).set("boolean_field"))

  property("support RichTableRowGen") = forAll (richGen) { r =>
    val fields = r.get(n).asInstanceOf[java.util.LinkedHashMap[String, Any]]
    val i = fields.get("int_field").asInstanceOf[Long]
    val f = fields.get("float_field").asInstanceOf[Double]
    val b = fields.get("boolean_field").asInstanceOf[Boolean]
    val s = fields.get("string_field").asInstanceOf[String]
    val upper = fields.get("upper_string_field").asInstanceOf[String]
    all(
      "Int"     |: i >= 10L && i <= 20L,
      "Float"   |: f >= 10.0 && f <= 20.0,
      "Boolean" |: b == true,
      "String"  |: s == "hello",
      "String"  |: upper == "HELLO"
    )
  }

  property("support RichTableRowTupGen") = forAll(richTupGen) { case (a, b) =>
    val ar = a.get(r).asInstanceOf[java.util.LinkedHashMap[String, Any]]
    val br = b.get(r).asInstanceOf[java.util.LinkedHashMap[String, Any]]
    (a.get("int_field").asInstanceOf[Long] == b.get("int_field").asInstanceOf[Long]
      && a.get("string_field").asInstanceOf[String] == b.get("string_field").asInstanceOf[String] &&
      a.get("boolean_field").asInstanceOf[Boolean] == b.get("boolean_field").asInstanceOf[Boolean])
  }

} 
Example 162
Source File: TaggingTest.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.tests

import aecor.data.{ EventTag, Tagging }
import org.scalacheck.Prop.forAll
import org.scalacheck.{ Gen, Properties }

class TaggingTest extends Properties("Tagging") {
  property("Const Tagging") = {
    val tagging = Tagging.const[Int](EventTag("foo"))
    forAll { x: Int =>
      tagging.tag(x) == Set(EventTag("foo"))
    }
  }

  property("Partitioned Tagging") = forAll(Gen.posNum[Int]) { partitionCount =>
    val tagging = Tagging.partitioned[Int](partitionCount)(EventTag(""))

    forAll { x: Int =>
      tagging.tags.contains(tagging.tag(x).head)
    }

    tagging.tags.size == partitionCount
  }
} 
Example 163
Source File: ScheduleEventCodecSpec.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.tests

import java.time.temporal.{ ChronoField, Temporal }
import java.time.{ Instant, LocalDateTime }

import aecor.runtime.akkapersistence.serialization.{ PersistentDecoder, PersistentEncoder }
import aecor.schedule.ScheduleEvent
import org.scalacheck.{ Arbitrary, Gen, Properties, ScalacheckShapeless }
import org.scalacheck.Prop.forAll

class ScheduleEventCodecSpec extends Properties("ScheduleEventCodec") with ScalacheckShapeless {
  val encoder = PersistentEncoder[ScheduleEvent]
  val decoder = PersistentDecoder[ScheduleEvent]

  // OpenJDK 9+ offers more precise system clock than millisecond.
  // https://bugs.openjdk.java.net/browse/JDK-8068730
  def dropBelowMillis[A <: Temporal](t: A): A =
    t.`with`(ChronoField.MICRO_OF_SECOND, t.getLong(ChronoField.MILLI_OF_SECOND) * 1000L)
      .asInstanceOf[A]

  implicit val arbitraryLocalDateTime = Arbitrary(
    Gen.lzy(Gen.const(dropBelowMillis(LocalDateTime.now())))
  )
  implicit val arbitraryInstant = Arbitrary(Gen.lzy(Gen.const(dropBelowMillis(Instant.now()))))

  property("encode/decode") = forAll { e: ScheduleEvent =>
    val repr = encoder.encode(e)
    val decoded = decoder.decode(repr)
    decoded == Right(e)
  }

} 
Example 164
Source File: MatcherResolverProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.matchers

import cats.syntax.either._
import com.github.agourlay.cornichon.core.SessionProperties._
import org.scalacheck.{ Gen, Properties }
import org.scalacheck.Prop._
import org.typelevel.claimant.Claim

class MatcherResolverProperties extends Properties("MatcherResolver") {

  property("find matcher in content solely containing a matcher") = {
    forAll(keyGen) { key =>
      Claim {
        MatcherResolver.findMatcherKeys(s"*$key*") == Right(List(MatcherKey(key)))
      }
    }
  }

  property("find matcher in content starting with whitespace and containing a matcher") = {
    forAll(keyGen) { key =>
      Claim {
        MatcherResolver.findMatcherKeys(s" *$key*") == Right(List(MatcherKey(key)))
      }
    }
  }

  property("find matcher in content starting with 2 whitespaces and containing a matcher") = {
    forAll(keyGen) { key =>
      Claim {
        MatcherResolver.findMatcherKeys(s"  *$key*") == Right(List(MatcherKey(key)))
      }
    }
  }

  property("find matcher in content finishing with whitespace and containing a matcher") = {
    forAll(keyGen) { key =>
      Claim {
        MatcherResolver.findMatcherKeys(s"*$key* ") == Right(List(MatcherKey(key)))
      }
    }
  }

  property("find matcher in content finishing with 2 whitespaces and containing a matcher") = {
    forAll(keyGen) { key =>
      Claim {
        MatcherResolver.findMatcherKeys(s"*$key*  ") == Right(List(MatcherKey(key)))
      }
    }
  }

  property("resolveMatcherKeys detect duplicate matchers") = {
    val allMatchers = MatcherResolver.builtInMatchers
    forAll(Gen.oneOf(allMatchers)) { m =>
      val input = (m :: m :: Nil).groupBy(_.key)
      val expected = Left(s"there are 2 matchers named '${m.key}': '${m.description}' and '${m.description}'")
      Claim {
        MatcherResolver.resolveMatcherKeys(input)(MatcherKey(m.key)).leftMap(_.renderedMessage) == expected
      }
    }
  }
} 
Example 165
Source File: JsonPathParserProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.json

import org.scalacheck.{ Gen, Properties }
import org.scalacheck.Prop._
import org.typelevel.claimant.Claim
import com.github.agourlay.cornichon.json.JsonPathParserProperties._

class JsonPathParserProperties extends Properties("JsonPathParser") {

  property("parse JsonPath containing a field without index") = {
    forAll(fieldGen) { field =>
      Claim {
        JsonPathParser.parseJsonPath(field) == Right(List(FieldSelection(field)))
      }
    }
  }

  property("parse JsonPath containing a field with index") = {
    forAll(fieldGen, indexGen) { (field, index) =>
      Claim {
        JsonPathParser.parseJsonPath(s"$field[$index]") == Right(List(ArrayFieldSelection(field, index)))
      }
    }
  }

  property("parse JsonPath containing two fields without index") = {
    forAll(fieldGen, fieldGen) { (field1, field2) =>
      Claim {
        JsonPathParser.parseJsonPath(s"$field1.$field2") == Right(List(FieldSelection(field1), FieldSelection(field2)))
      }
    }
  }

  property("parse JsonPath containing a field with projection") = {
    forAll(fieldGen) { field =>
      Claim {
        JsonPathParser.parseJsonPath(s"$field[*]") == Right(List(ArrayFieldProjection(field)))
      }
    }
  }

  property("parse JsonPath with key containing a dot without index") = {
    forAll(fieldGen, fieldGen, fieldGen) { (field1, field2, field3) =>
      val composedPath = s"$field1.$field2"
      val fullPath = s"`$composedPath`.$field3"
      Claim {
        JsonPathParser.parseJsonPath(fullPath) == Right(List(FieldSelection(composedPath), FieldSelection(field3)))
      }
    }
  }

  property("parse JsonPath with key containing a dot with index") = {
    forAll(fieldGen, fieldGen, fieldGen, indexGen) { (field1, field2, field3, index) =>
      val composedPath = s"$field1.$field2"
      val fullPath = s"`$composedPath`.$field3[$index]"
      Claim {
        JsonPathParser.parseJsonPath(fullPath) == Right(List(FieldSelection(composedPath), ArrayFieldSelection(field3, index)))
      }
    }
  }

  property("return error if it starts with '.'") = {
    forAll(fieldGen) { field =>
      Claim {
        JsonPathParser.parseJsonPath(s".$field.").isLeft
      }
    }
  }

  property("parse JsonPath containing a missing field") = {
    forAll(fieldGen) { field =>
      Claim {
        JsonPathParser.parseJsonPath(s"$field.").isLeft
      }
    }
  }

  property("parse JsonPath containing a broken index bracket") = {
    forAll(fieldGen, indexGen) { (field, index) =>
      Claim {
        JsonPathParser.parseJsonPath(s"$field[$index[").isLeft
      }
    }
  }
}

object JsonPathParserProperties {
  val fieldGen = Gen.alphaStr.filter(_.trim.nonEmpty).filter(k => !JsonPathParser.notAllowedInField.exists(forbidden => k.contains(forbidden)))
  def fieldsGen(n: Int) = Gen.listOfN(n, fieldGen)

  val indexGen = Gen.choose(0, Int.MaxValue)
} 
Example 166
Source File: JsonStepsProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.json

import cats.instances.string._
import com.github.agourlay.cornichon.core.{ Scenario, ScenarioRunner, Session, SessionKey }
import com.github.agourlay.cornichon.json.JsonSteps.JsonStepBuilder
import com.github.agourlay.cornichon.testHelpers.TaskSpec
import io.circe.{ Json, JsonObject }
import io.circe.testing.ArbitraryInstances
import org.scalacheck.Properties
import org.scalacheck.Prop._
import org.typelevel.claimant.Claim

class JsonStepsProperties extends Properties("JsonSteps") with ArbitraryInstances with TaskSpec {

  private val testKey = "test-key"
  private val jsonStepBuilder = JsonStepBuilder(SessionKey(testKey), Some("test body"))

  property("JsonStepBuild is value") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.is(input)
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuild is value fail") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.is(input + "42")
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(!t.isSuccess)
    }

  property("JsonStepBuild isNot value") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.isNot(input + "42")
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuild isNot value fail") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.isNot(input)
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(!t.isSuccess)
    }

  property("JsonStepBuilder is any Circe jsonObject") =
    forAll { jsonOb: JsonObject =>
      val json = Json.fromJsonObject(jsonOb)
      val session = Session.newEmpty.addValuesUnsafe(testKey -> json.spaces2)
      val step = jsonStepBuilder.is(json)
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuilder is any Circe jsonObject with placeholder") =
    forAll { jsonOb: JsonObject =>
      val fullJsonObj = jsonOb.add("myKeyOther", Json.fromString("myOtherValue"))
      val session = Session.newEmpty.addValuesUnsafe(
        testKey -> Json.fromJsonObject(fullJsonObj).spaces2,
        "a-placeholder" -> "myOtherValue"
      )
      val fullPlaceholderJsonObj = jsonOb.add("myKeyOther", Json.fromString("<a-placeholder>"))
      val step = jsonStepBuilder.is(Json.fromJsonObject(fullPlaceholderJsonObj))
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuilder is Circe jsonObject with absent placeholder") =
    forAll { jsonOb: JsonObject =>
      val fullJsonObj = jsonOb.add("myKeyOther", Json.fromString("myOtherValue"))
      val session = Session.newEmpty.addValuesUnsafe(testKey -> Json.fromJsonObject(fullJsonObj).spaces2)
      val fullPlaceholderJsonObj = jsonOb.add("myKeyOther", Json.fromString("<a-placeholder>"))
      val step = jsonStepBuilder.is(Json.fromJsonObject(fullPlaceholderJsonObj))
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(!t.isSuccess)
    }
} 
Example 167
Source File: JsonPathProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.json

import io.circe.{ Json, JsonObject }
import org.scalacheck.{ Properties, Test }
import org.scalacheck.Prop._
import org.typelevel.claimant.Claim
import io.circe.testing.ArbitraryInstances

class JsonPathProperties extends Properties("JsonPath") with ArbitraryInstances {

  // avoid lists too long (default: 100)
  override def overrideParameters(p: Test.Parameters): Test.Parameters = super.overrideParameters(p.withMaxSize(10))

  property("select properly in any JsonObject") = {
    val targetValue = Json.fromString("target value")
    forAll { jos: List[JsonObject] =>
      val json = jos.foldRight(targetValue) { case (next, acc) => Json.fromJsonObject(next.add("stitch", acc)) }
      val path = List.fill(jos.size)(FieldSelection("stitch"))
      Claim {
        JsonPath(path).run(json).contains(targetValue)
      }
    }
  }
} 
Example 168
Source File: StringsUtilsProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.util

import org.scalacheck.{ Gen, Properties }
import org.scalacheck.Prop._
import org.typelevel.claimant.Claim

class StringsUtilsProperties extends Properties("StringsUtil") {

  property("levenshtein compute distance zero for identical String") =
    forAll(Gen.alphaStr.filter(_.trim.nonEmpty)) { s =>
      Claim {
        StringUtils.levenshtein(s, s) == 0
      }
    }

  property("compute distance one for String with one addition") =
    forAll(Gen.alphaStr.filter(_.trim.nonEmpty)) { s =>
      Claim {
        StringUtils.levenshtein(s, s + "a") == 1
      }
    }

  property("compute distance one for String with one deletion") =
    forAll(Gen.alphaStr.filter(_.trim.nonEmpty)) { s =>
      Claim {
        StringUtils.levenshtein(s, s.tail) == 1
      }
    }
} 
Example 169
Source File: ScenarioRunnerProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.core

import com.github.agourlay.cornichon.steps.cats.EffectStep
import com.github.agourlay.cornichon.testHelpers.CommonTesting
import monix.execution.atomic.AtomicBoolean
import org.scalacheck.Prop.forAll
import org.scalacheck.{ Properties, Test }
import org.typelevel.claimant.Claim

class ScenarioRunnerProperties extends Properties("ScenarioRunner") with CommonTesting {

  // avoid lists too long (default: 100)
  override def overrideParameters(p: Test.Parameters): Test.Parameters = super.overrideParameters(p.withMaxSize(10))

  property("a scenario containing only valid steps should not fail") =
    forAll(validStepsGen) { validSteps =>
      val s = Scenario("scenario with valid steps", validSteps)
      val r = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      Claim {
        r.isSuccess
      }
    }

  property("a scenario containing at least one invalid step should fail") =
    forAll(validStepsGen, invalidStepGen) { (validSteps, invalidStep) =>
      val s = Scenario("scenario with valid steps", validSteps :+ invalidStep)
      val r = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      Claim {
        !r.isSuccess
      }
    }

  property("a scenario stops at the first failed step") =
    forAll(validStepsGen, invalidStepGen) { (validSteps, invalidStep) =>
      val signal = AtomicBoolean(false)
      val signalingEffect = EffectStep.fromSync(
        "effect toggle signal",
        sc => {
          signal.set(true)
          sc.session
        }
      )
      val s = Scenario("scenario with valid steps", validSteps :+ invalidStep :+ signalingEffect)
      val r = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      Claim {
        !r.isSuccess && !signal.get()
      }
    }

  property("a scenario containing at least one invalid step should fail and always execute its finally clause") =
    forAll(validStepsGen, invalidStepGen) { (validSteps, invalidStep) =>
      val signal = AtomicBoolean(false)
      val signallingEffect = EffectStep.fromSync(
        "effect toggle signal",
        sc => {
          signal.set(true)
          sc.session
        }
      )
      val context = FeatureContext.empty.copy(finallySteps = signallingEffect :: Nil)
      val s = Scenario("scenario with valid steps", validSteps :+ invalidStep)
      val r = awaitTask(ScenarioRunner.runScenario(Session.newEmpty, context)(s))
      Claim {
        !r.isSuccess && signal.get()
      }
    }

  property("a scenario fails if its finally clause contains invalid steps") =
    forAll(validStepsGen, invalidStepGen) { (validSteps, invalidStep) =>
      val context = FeatureContext.empty.copy(finallySteps = invalidStep :: Nil)
      val s = Scenario("scenario with valid steps", validSteps)
      val r = awaitTask(ScenarioRunner.runScenario(Session.newEmpty, context)(s))
      Claim {
        !r.isSuccess
      }
    }

  property("runScenario runs `main steps` if there is no failure in `beforeSteps`") =
    forAll(validStepsGen) { validSteps =>
      val signal = AtomicBoolean(false)
      val signalingEffect = EffectStep.fromSync(
        "effect toggle signal",
        sc => {
          signal.set(true)
          sc.session
        }
      )
      val context = FeatureContext.empty.copy(beforeSteps = validSteps)
      val s = Scenario("scenario with valid steps", signalingEffect :: Nil)
      val r = awaitTask(ScenarioRunner.runScenario(Session.newEmpty, context)(s))
      Claim {
        r.isSuccess && signal.get()
      }
    }

} 
Example 170
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 171
Source File: BloomFilterSerializationSpec.scala    From bloom-filter-scala   with MIT License 5 votes vote down vote up
package tests.bloomfilter.mutable

import java.io._

import bloomfilter.mutable.BloomFilter
import org.scalacheck.Prop.forAll
import org.scalacheck.{Gen, Properties}
import org.scalatest.Matchers

class BloomFilterSerializationSpec extends Properties("BloomFilter") with Matchers {
  def genListElems[A](max: Long)(implicit aGen: Gen[A]): Gen[List[A]] = {
    Gen.posNum[Int].map(_ % max).flatMap(i => Gen.listOfN(math.min(i, Int.MaxValue).toInt, aGen))
  }

  val gen = for {
    size <- Gen.oneOf[Long](1, 1000 )
    indices <- genListElems[Long](size)(Gen.chooseNum(0, size - 1))
  } yield (size, indices)

  property("writeTo & readFrom") = forAll(gen) {
    case (size: Long, indices: List[Long]) =>
      val initial = BloomFilter[Long](size, 0.01)
      indices.foreach(initial.add)

      val file = File.createTempFile("bloomFilterSerialized", ".tmp")
      val out = new BufferedOutputStream(new FileOutputStream(file), 10 * 1000 * 1000)
      initial.writeTo(out)
      out.close()
      val in = new BufferedInputStream(new FileInputStream(file), 10 * 1000 * 1000)
      val sut = BloomFilter.readFrom[Long](in)
      in.close()

      sut.approximateElementCount() shouldEqual initial.approximateElementCount()

      val result = indices.forall(sut.mightContain)

      file.delete()
      initial.dispose()
      sut.dispose()

      result
  }

  property("supports java serialization") = {
    forAll(gen) {
      case (size, indices) =>
        val initial = BloomFilter[Long](size, 0.01)
        indices.foreach(initial.add)
        val file = File.createTempFile("bloomFilterSerialized", ".tmp")
        val out = new BufferedOutputStream(new FileOutputStream(file), 10 * 1000 * 1000)
        val oos = new ObjectOutputStream(out)
        oos.writeObject(initial)
        oos.close()
        out.close()
        val in = new BufferedInputStream(new FileInputStream(file), 10 * 1000 * 1000)
        val ois = new ObjectInputStream(in)
        val desrialized = ois.readObject()
        ois.close()
        in.close()

        desrialized should not be null
        desrialized should be(a[BloomFilter[Long]])
        val sut = desrialized.asInstanceOf[BloomFilter[Long]]

        sut.numberOfBits shouldEqual initial.numberOfBits
        sut.numberOfHashes shouldEqual initial.numberOfHashes
        sut.approximateElementCount() shouldEqual initial.approximateElementCount()


        val result = indices.forall(sut.mightContain)

        file.delete()
        initial.dispose()
        sut.dispose()

        result
    }
  }

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

import bloomfilter.mutable.UnsafeBitArray
import org.scalacheck.Prop._
import org.scalacheck.{Gen, Properties}

class UnsafeBitArraysSpec extends Properties("UnsafeBitArray") {
  def genListElems[A](max: Long)(implicit aGen: Gen[A]): Gen[List[A]] = {
    Gen.posNum[Int].map(_ % max).flatMap(i => Gen.listOfN(math.min(i, Int.MaxValue).toInt, aGen))
  }

  val genUnion = for {
    size <- Gen.oneOf[Long](1, 1000, Int.MaxValue, Int.MaxValue * 2L)
    indices <- genListElems[Long](size)(Gen.chooseNum(0, size))
    thatIndices <- genListElems[Long](size)(Gen.chooseNum(0, size))
  } yield (size, indices, thatIndices)

  val genIntersection = for {
    size <- Gen.oneOf[Long](1, 1000, Int.MaxValue, Int.MaxValue * 2L)
    indices <- genListElems[Long](size)(Gen.chooseNum(0, size))
    thatIndices <- genListElems[Long](size)(Gen.chooseNum(0, size))
    commonIndices <- genListElems[Long](size)(Gen.chooseNum(0, size))
  } yield (size, indices, thatIndices, commonIndices)


  property("|") = forAll(genUnion) {
    case (size: Long, indices: List[Long], thatIndices: List[Long]) =>
      val array = new UnsafeBitArray(size)
      indices.foreach(array.set)
      val thatArray = new UnsafeBitArray(size)
      thatIndices.foreach(thatArray.set)

      val sut = array | thatArray
      val result = (indices ++ thatIndices).forall(sut.get)

      array.dispose()
      thatArray.dispose()
      sut.dispose()

      result
  }

  property("&") = forAll(genIntersection) {
    case (size: Long, indices: List[Long], thatIndices: List[Long], commonIndices: List[Long]) =>
      val array = new UnsafeBitArray(size)
      indices.foreach(array.set)
      val thatArray = new UnsafeBitArray(size)
      thatIndices.foreach(thatArray.set)
      commonIndices.foreach(x => { array.set(x); thatArray.set(x) })

      val sut = array & thatArray
      val result = commonIndices.forall(sut.get)

      array.dispose()
      thatArray.dispose()
      sut.dispose()

      result
  }

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

import java.io._

import bloomfilter.mutable._128bit.BloomFilter
import org.scalacheck.Prop.forAll
import org.scalacheck.{Gen, Properties}
import org.scalatest.Matchers

class BloomFilterSerializationSpec extends Properties("BloomFilter") with Matchers {
  def genListElems[A](max: Long)(implicit aGen: Gen[A]): Gen[List[A]] = {
    Gen.posNum[Int].map(_ % max).flatMap(i => Gen.listOfN(math.min(i, Int.MaxValue).toInt, aGen))
  }

  val gen = for {
    size <- Gen.oneOf[Long](1, 1000)
    indices <- genListElems[Long](size)(Gen.chooseNum(0, size))
  } yield (size, indices)

  property("writeTo & readFrom") = forAll(gen) {
    case (size: Long, indices: List[Long]) =>
      val initial = BloomFilter[Long](size, 0.01)
      indices.foreach(initial.add)

      val file = File.createTempFile("bloomFilterSerialized", ".tmp")
      val out = new BufferedOutputStream(new FileOutputStream(file), 10 * 1000 * 1000)
      initial.writeTo(out)
      out.close()
      val in = new BufferedInputStream(new FileInputStream(file), 10 * 1000 * 1000)
      val sut = BloomFilter.readFrom[Long](in)
      in.close()

      sut.approximateElementCount() shouldEqual initial.approximateElementCount()

      val result = indices.forall(sut.mightContain)

      file.delete()
      initial.dispose()
      sut.dispose()

      result
  }

} 
Example 174
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 175
Source File: MonadSpec.scala    From tutorial-cat   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.tutorial.cat.monad

import com.danielasfregola.tutorial.cat.ArbitraryIntInstances._
import MonadInstances._
import com.danielasfregola.tutorial.cat.applicative.ApplicativeProperties
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Properties}

import scala.reflect._

class MaybeMonadSpec extends MonadSpec(maybeMonad)
class ZeroOrMoreMonadSpec extends MonadSpec(zeroOrMoreMonad)

abstract class MonadSpec[Box[_]](val monad: Monad[Box])(implicit val arbitrary: Arbitrary[Box[Int]],
                                                        tag: ClassTag[Box[_]])
    extends Properties(s"Monad for $tag")
    with MonadProperties[Box]

trait MonadProperties[Box[_]] extends ApplicativeProperties[Box] { self: Properties =>

  val monad: Monad[Box]
  import monad._

  lazy val applicative = monad

  lazy val toPureF = { a: A => pure(f(a)) }
  lazy val toPureG = { b: B => pure(g(b)) }

  // flatMap(pure(a))(f(a)) == f(a)
  property("left identity") = forAll { a: A =>
    flatMap(pure(a))(toPureF) == toPureF(a)
  }

  // flatMap(pure(f(a)))(pure) == pure(f(a))
  property("right identity") = forAll { a: A =>
    flatMap(toPureF(a))(pure) == toPureF(a)
  }

  // flatMap(flatMap(boxA)(boxF))(boxG) == flatMap(boxA)(boxF(_))(boxG)
  property("associativity") = forAll { boxA: Box[A] =>
    val left: Box[C] = flatMap(flatMap(boxA)(toPureF))(toPureG)
    val right: Box[C] = flatMap(boxA)(a => flatMap(toPureF(a))(toPureG))
    left == right
  }
} 
Example 176
Source File: T04PropertyBasedTest.scala    From big-data-rosetta-code   with Apache License 2.0 4 votes vote down vote up
package com.spotify.bdrc.testing

import com.google.common.collect.MinMaxPriorityQueue
import org.scalacheck.Prop._
import org.scalacheck.{Gen, Properties}
import org.scalatest.propspec.AnyPropSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

import scala.collection.JavaConverters._

object Utils {

  def top[T: Ordering](xs: Seq[T], num: Int): Seq[T] = {
    if (xs.isEmpty) {
      Seq.empty[T]
    } else {
      val size = math.min(num, xs.size)
      val ord = implicitly[Ordering[T]]
      MinMaxPriorityQueue
        .orderedBy(ord.reverse)
        .expectedSize(size)
        .maximumSize(size)
        .create[T](xs.asJava)
        .asScala
        .toSeq
        .sorted(ord.reverse)
    }
  }

  def split(input: String): Seq[String] =
    input
      .split("[^a-zA-Z']+")
      .filter(_.nonEmpty)
      .map(_.toLowerCase)

  def cosineSim(v1: Seq[Double], v2: Seq[Double]): Double = {
    require(v1.length == v2.length)
    var s1 = 0.0
    var s2 = 0.0
    var dp = 0.0
    var i = 0
    while (i < v1.length) {
      s1 += v1(i) * v1(i)
      s2 += v2(i) * v2(i)
      dp += v1(i) * v2(i)
      i += 1
    }
    dp / math.sqrt(s1 * s2)
  }

}


class PropertyBasedTest extends AnyPropSpec with ScalaCheckDrivenPropertyChecks with Matchers {

  property("top") {
    forAll { xs: Seq[Long] => Utils.top(xs, 5) shouldBe xs.sorted.reverse.take(5) }
  }

  property("split") {
    forAll { line: String => Utils.split(line).forall(_.matches("[a-z']+")) }
  }

  // Generator for List[Double] of 100 doubles between -100.0 and 100.0
  val genVector = Gen.listOfN(100, Gen.choose(-100.0, 100.0))

  property("cosineSim") {
    forAll(genVector, genVector) { (v1, v2) =>
      val s1 = Utils.cosineSim(v1, v2)
      val s2 = Utils.cosineSim(v2, v1)

      s1 should (be >= -1.0 and be <= 1.0)
      s1 shouldBe s2
      Utils.cosineSim(v1, v1) shouldBe 1.0
      Utils.cosineSim(v1, v1.map(-_)) shouldBe -1.0
    }
  }

}