org.scalacheck.Gen Scala Examples

The following examples show how to use org.scalacheck.Gen. 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: Generators.scala    From daml   with Apache License 2.0 6 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.extractor.config

import org.scalacheck.{Arbitrary, Gen}
import scalaz.OneAnd
import scalaz.Scalaz._

object Generators {

  implicit def arbTemplateConfig: Arbitrary[TemplateConfig] = Arbitrary(genTemplateConfig)

  def genTemplateConfig: Gen[TemplateConfig] =
    for {
      moduleName <- Gen.identifier
      entityName <- Gen.identifier
    } yield TemplateConfig(moduleName, entityName)

  def templateConfigUserInput(templateConfig: TemplateConfig): String =
    templateConfig.moduleName + ':'.toString + templateConfig.entityName

  def templateConfigUserInput(templateConfigs: OneAnd[List, TemplateConfig]): String =
    templateConfigUserInput(templateConfigs.toList)

  def templateConfigUserInput(templateConfigs: List[TemplateConfig]): String =
    templateConfigs.map(templateConfigUserInput).mkString(",")
} 
Example 2
Source File: HttpServiceIntegrationTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http

import java.io.File
import java.nio.file.Files

import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpMethods, HttpRequest, StatusCodes, Uri}
import com.daml.http.Statement.discard
import com.daml.http.util.TestUtil.writeToFile
import org.scalacheck.Gen
import org.scalatest.{Assertion, BeforeAndAfterAll}

import scala.concurrent.Future

class HttpServiceIntegrationTest extends AbstractHttpServiceIntegrationTest with BeforeAndAfterAll {

  private val staticContent: String = "static"

  private val staticContentDir: File =
    Files.createTempDirectory("integration-test-static-content").toFile

  override def staticContentConfig: Option[StaticContentConfig] =
    Some(StaticContentConfig(prefix = staticContent, directory = staticContentDir))

  override def jdbcConfig: Option[JdbcConfig] = None

  private val expectedDummyContent: String = Gen
    .listOfN(100, Gen.identifier)
    .map(_.mkString(" "))
    .sample
    .getOrElse(throw new IllegalStateException(s"Cannot create dummy text content"))

  private val dummyFile: File =
    writeToFile(new File(staticContentDir, "dummy.txt"), expectedDummyContent).get
  require(dummyFile.exists)

  override protected def afterAll(): Unit = {
    // clean up temp directory
    discard { dummyFile.delete() }
    discard { staticContentDir.delete() }
    super.afterAll()
  }

  "should serve static content from configured directory" in withHttpService { (uri: Uri, _, _) =>
    Http()
      .singleRequest(
        HttpRequest(
          method = HttpMethods.GET,
          uri = uri.withPath(Uri.Path(s"/$staticContent/${dummyFile.getName}"))))
      .flatMap { resp =>
        discard { resp.status shouldBe StatusCodes.OK }
        val bodyF: Future[String] = getResponseDataBytes(resp, debug = false)
        bodyF.flatMap { body =>
          body shouldBe expectedDummyContent
        }
      }: Future[Assertion]
  }

  "Forwarded" - {
    import Endpoints.Forwarded
    "can 'parse' sample" in {
      Forwarded("for=192.168.0.1;proto=http;by=192.168.0.42").proto should ===(Some("http"))
    }

    "can 'parse' quoted sample" in {
      Forwarded("for=192.168.0.1;proto = \"https\" ;by=192.168.0.42").proto should ===(
        Some("https"))
    }
  }
} 
Example 3
Source File: ContractStreamStepTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http
package util

import com.daml.scalatest.FlatSpecCheckLaws

import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import scalaz.scalacheck.ScalaCheckBinding._
import scalaz.scalacheck.ScalazProperties
import scalaz.syntax.apply._
import scalaz.syntax.semigroup._
import scalaz.{@@, Equal, Tag}

class ContractStreamStepTest
    extends FlatSpec
    with FlatSpecCheckLaws
    with Matchers
    with GeneratorDrivenPropertyChecks
    with TableDrivenPropertyChecks {

  import ContractStreamStepTest._, ContractStreamStep._
  import InsertDeleteStepTest._

  override implicit val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 100)

  behavior of "append"

  it should "be associative for valid streams" in forAll(validStreamGen) { csses =>
    whenever(csses.size >= 3) {
      forEvery(
        Table(("a", "b", "c"), csses.sliding(3).map { case Seq(a, b, c) => (a, b, c) }.toSeq: _*)) {
        case (a, b, c) =>
          (a |+| (b |+| c)) should ===((a |+| b) |+| c)
      }
    }
  }

  it should "report the last offset" in forAll { (a: CSS, b: CSS) =>
    def off(css: ContractStreamStep[_, _]) = css match {
      case Acs(_) => None
      case LiveBegin(off) => off.toOption
      case Txn(_, off) => Some(off)
    }

    off(a |+| b) should ===(off(b) orElse off(a))
  }

  it should "preserve append across toInsertDelete" in forAll { (a: CSS, b: CSS) =>
    (a |+| b).toInsertDelete should ===(a.toInsertDelete |+| b.toInsertDelete)
  }

  behavior of "append semigroup"

  checkLaws(ScalazProperties.semigroup.laws[CSS])
}

object ContractStreamStepTest {
  import InsertDeleteStepTest._, InsertDeleteStep.Inserts, ContractStreamStep._
  import org.scalacheck.{Arbitrary, Gen}
  import Arbitrary.arbitrary

  type CSS = ContractStreamStep[Unit, Cid]

  private val offGen: Gen[domain.Offset] = Tag subst Tag.unsubst(arbitrary[String @@ Alpha])
  private val acsGen = arbitrary[Inserts[Cid]] map (Acs(_))
  private val noAcsLBGen = Gen const LiveBegin(LedgerBegin)
  private val postAcsGen = offGen map (o => LiveBegin(AbsoluteBookmark(o)))
  private val txnGen = ^(arbitrary[IDS], offGen)(Txn(_, _))

  private val validStreamGen: Gen[Seq[CSS]] = for {
    beforeAfter <- Gen.zip(
      Gen.containerOf[Vector, CSS](acsGen),
      Gen.containerOf[Vector, CSS](txnGen))
    (acsSeq, txnSeq) = beforeAfter
    liveBegin <- if (acsSeq.isEmpty) noAcsLBGen else postAcsGen
  } yield (acsSeq :+ liveBegin) ++ txnSeq

  private implicit val `CSS eq`: Equal[CSS] = Equal.equalA

  private implicit val `anyCSS arb`: Arbitrary[CSS] =
    Arbitrary(Gen.frequency((4, acsGen), (1, noAcsLBGen), (1, postAcsGen), (4, txnGen)))
} 
Example 4
Source File: FlowUtilTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http.util

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.stream.scaladsl.Source
import org.scalacheck.{Gen, Arbitrary}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import scalaz.{-\/, \/, \/-}

import scala.concurrent.Future

class FlowUtilTest
    extends FlatSpec
    with ScalaFutures
    with Matchers
    with GeneratorDrivenPropertyChecks {
  import FlowUtil._

  implicit val asys: ActorSystem = ActorSystem(this.getClass.getSimpleName)
  implicit val materializer: Materializer = Materializer(asys)

  "allowOnlyFirstInput" should "pass 1st message through and replace all others with errors" in forAll(
    nonEmptyVectorOfInts) { xs: Vector[Int] =>
    val error = "Error"
    val errorNum = Math.max(xs.size - 1, 0)
    val expected: Vector[String \/ Int] =
      xs.take(1).map(\/-(_)) ++ Vector.fill(errorNum)(-\/(error))
    val input: Source[String \/ Int, NotUsed] =
      Source.fromIterator(() => xs.toIterator).map(\/-(_))

    val actualF: Future[Vector[String \/ Int]] =
      input
        .via(allowOnlyFirstInput[String, Int](error))
        .runFold(Vector.empty[String \/ Int])(_ :+ _)

    whenReady(actualF) { actual =>
      actual shouldBe expected
    }
  }

  private val nonEmptyVectorOfInts: Gen[Vector[Int]] =
    Gen.nonEmptyBuildableOf[Vector[Int], Int](Arbitrary.arbitrary[Int])
} 
Example 5
Source File: InsertDeleteStepTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http.util

import com.daml.scalatest.FlatSpecCheckLaws

import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import scalaz.scalacheck.ScalazProperties
import scalaz.syntax.semigroup._
import scalaz.{@@, Equal, Tag}

class InsertDeleteStepTest
    extends FlatSpec
    with Matchers
    with FlatSpecCheckLaws
    with GeneratorDrivenPropertyChecks {
  import InsertDeleteStepTest._

  override implicit val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 100)

  behavior of "append monoid"

  checkLaws(ScalazProperties.monoid.laws[IDS])

  behavior of "append"

  it should "never insert a deleted item" in forAll { (x: IDS, y: IDS) =>
    val xy = x |+| y.copy(inserts = y.inserts filterNot Cid.subst(x.deletes.keySet))
    xy.inserts.toSet intersect Cid.subst(xy.deletes.keySet) shouldBe empty
  }

  it should "preserve every left delete" in forAll { (x: IDS, y: IDS) =>
    val xy = x |+| y
    xy.deletes.keySet should contain allElementsOf x.deletes.keySet
  }

  it should "preserve at least right deletes absent in left inserts" in forAll { (x: IDS, y: IDS) =>
    val xy = x |+| y
    // xy.deletes _may_ contain x.inserts; it is semantically irrelevant
    xy.deletes.keySet should contain allElementsOf (y.deletes.keySet -- Cid.unsubst(x.inserts))
  }

  it should "preserve append absent deletes" in forAll { (x: Vector[Cid], y: Vector[Cid]) =>
    val xy = InsertDeleteStep(x, Map.empty[String, Unit]) |+| InsertDeleteStep(y, Map.empty)
    xy.inserts should ===(x ++ y)
  }
}

object InsertDeleteStepTest {
  import org.scalacheck.{Arbitrary, Gen, Shrink}
  import Arbitrary.arbitrary

  type IDS = InsertDeleteStep[Unit, Cid]
  sealed trait Alpha
  type Cid = String @@ Alpha
  val Cid = Tag.of[Alpha]

  implicit val `Alpha arb`: Arbitrary[Cid] = Cid subst Arbitrary(
    Gen.alphaUpperChar map (_.toString))

  private[util] implicit val `test Cid`: InsertDeleteStep.Cid[Cid] = Cid.unwrap

  implicit val `IDS arb`: Arbitrary[IDS] =
    Arbitrary(arbitrary[(Vector[Cid], Map[Cid, Unit])] map {
      case (is, ds) =>
        InsertDeleteStep(is filterNot ds.keySet, Cid.unsubst[Map[?, Unit], String](ds))
    })

  implicit val `IDS shr`: Shrink[IDS] =
    Shrink.xmap[(Vector[Cid], Map[Cid, Unit]), IDS](
      { case (is, ds) => InsertDeleteStep(is, Cid.unsubst[Map[?, Unit], String](ds)) },
      step => (step.inserts, Cid.subst[Map[?, Unit], String](step.deletes)),
    )

  implicit val `IDS eq`: Equal[IDS] = Equal.equalA
} 
Example 6
Source File: ApiValueToLfValueConverterTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http
package util

import com.daml.lf.data.{Numeric => LfNumeric}
import com.daml.lf.value.test.TypedValueGenerators.genAddend
import com.daml.lf.value.{Value => V}
import com.daml.platform.participant.util.LfEngineToApi.lfValueToApiValue
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{Matchers, WordSpec}
import scalaz.Equal
import scalaz.syntax.bifunctor._
import scalaz.std.option._
import scalaz.std.tuple._

class ApiValueToLfValueConverterTest
    extends WordSpec
    with Matchers
    with GeneratorDrivenPropertyChecks {
  import ApiValueToLfValueConverterTest._

  private[this] implicit val arbCid: Arbitrary[CidSrc] = Arbitrary(
    Gen.alphaStr map (t => V.ContractId.V0 assertFromString ('#' +: t)))

  "apiValueToLfValue" should {
    import ApiValueToLfValueConverter.apiValueToLfValue

    "retract lfValueToApiValue" in forAll(genAddend, minSuccessful(100)) { va =>
      import va.injshrink
      implicit val arbInj: Arbitrary[va.Inj[CidSrc]] = va.injarb
      forAll(minSuccessful(20)) { v: va.Inj[CidSrc] =>
        val vv = va.inj(v)
        val roundTrip = lfValueToApiValue(true, vv).right.toOption flatMap (x =>
          apiValueToLfValue(x).toMaybe.toOption)
        assert(Equal[Option[V[Cid]]].equal(roundTrip, Some(vv)))
      }
    }
  }
}

object ApiValueToLfValueConverterTest {

  type Cid = V.ContractId
  type CidSrc = V.ContractId.V0

  // Numeric are normalized when converting from api to lf,
  // them we have to relax numeric equality
  private implicit def eqValue: Equal[V[Cid]] = { (l, r) =>
    V.`Value Equal instance`[Cid]
      .contramap[V[Cid]](
        mapNumeric(_, n => LfNumeric assertFromUnscaledBigDecimal n.stripTrailingZeros))
      .equal(l, r)
  }

  private[this] def mapNumeric[C](fa: V[C], f: LfNumeric => LfNumeric): V[C] = {
    def go(fa: V[C]): V[C] = fa match {
      case V.ValueNumeric(m) => V.ValueNumeric(f(m))
      case _: V.ValueCidlessLeaf | V.ValueContractId(_) => fa
      case r @ V.ValueRecord(_, fields) => r copy (fields = fields map (_ rightMap go))
      case v @ V.ValueVariant(_, _, value) => v copy (value = go(value))
      case s @ V.ValueStruct(fields) => s copy (fields = fields map (_ rightMap go))
      case V.ValueList(fs) => V.ValueList(fs map go)
      case V.ValueOptional(o) => V.ValueOptional(o map go)
      case V.ValueTextMap(m) => V.ValueTextMap(m mapValue go)
      case V.ValueGenMap(m) => V.ValueGenMap(m map (_ bimap (go, go)))
    }
    go(fa)
  }
} 
Example 7
Source File: DarSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.archive

import com.daml.scalatest.FlatSpecCheckLaws
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.{FlatSpec, Matchers}
import scalaz.std.anyVal._
import scalaz.scalacheck.ScalazProperties

class DarSpec extends FlatSpec with Matchers with FlatSpecCheckLaws {
  behavior of s"${Dar.getClass.getSimpleName} Equal"
  checkLaws(ScalazProperties.equal.laws[Dar[Int]])

  behavior of s"${Dar.getClass.getSimpleName} Traverse"
  checkLaws(ScalazProperties.traverse.laws[Dar])

  behavior of s"${Dar.getClass.getSimpleName} Functor"
  checkLaws(ScalazProperties.functor.laws[Dar])

  private def darGen[A: Arbitrary]: Gen[Dar[A]] =
    for {
      main <- Arbitrary.arbitrary[A]
      dependencies <- Arbitrary.arbitrary[List[A]]
    } yield Dar[A](main, dependencies)

  private implicit def darArb[A: Arbitrary]: Arbitrary[Dar[A]] = Arbitrary(darGen)
} 
Example 8
Source File: RelationTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.data

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen
import org.scalatest.prop.PropertyChecks
import org.scalatest.{Matchers, PropSpec}

final class RelationTest extends PropSpec with Matchers with PropertyChecks {

  import Relation.Relation._

  // an empty map and a map with exclusively empty values represent
  // the same relationship but the underlying structure is different
  private val nonEmptyRelations: Gen[Map[Int, Set[Char]]] =
    arbitrary[Map[Int, Set[Char]]].suchThat(_.values.forall(_.nonEmpty))

  property("invert andThen invert == identity for non empty relations") {
    forAll(nonEmptyRelations) { nonEmpty: Map[Int, Set[Char]] =>
      nonEmpty shouldEqual invert(invert(nonEmpty))
    }
  }

  property("union commutative") {
    forAll { (m1: Map[Int, Set[Char]], m2: Map[Int, Set[Char]]) =>
      union(m1, m2) shouldEqual union(m2, m1)
    }
  }

  property("union associative") {
    forAll { (m1: Map[Int, Set[Char]], m2: Map[Int, Set[Char]], m3: Map[Int, Set[Char]]) =>
      union(union(m1, m2), m3) shouldEqual union(m1, union(m2, m3))
    }
  }

  property("union has unit") {
    forAll { m: Map[Int, Set[Char]] =>
      union(m, Map.empty[Int, Set[Char]]) shouldEqual m
      union(Map.empty[Int, Set[Char]], m) shouldEqual m
    }
  }

  property("flattening is the inverse of grouping for non empty relations") {
    forAll(nonEmptyRelations) { nonEmpty =>
      flatten(nonEmpty).toSeq.groupBy(_._1).mapValues(_.map(_._2).toSet) shouldEqual nonEmpty
    }
  }

  property("diff is idempotent") {
    forAll { (m1: Map[Int, Set[Char]], m2: Map[Int, Set[Char]]) =>
      diff(m1, m2) shouldEqual diff(diff(m1, m2), m2)
    }
  }

  property("diff by empty doesn't affect non-empty relations") {
    forAll(nonEmptyRelations) { m =>
      diff(m, Map.empty[Int, Set[Char]]) shouldEqual m
    }
  }

  property("diff: no item in the right operand appears in the result") {
    forAll { (m1: Map[Int, Set[Char]], m2: Map[Int, Set[Char]]) =>
      val result = flatten(diff(m1, m2)).toList
      val right = flatten(m2).toList
      result should contain noElementsOf right
    }
  }

  property("diff: items in the result should be a subset of the ones in the left operand") {
    forAll { (m1: Map[Int, Set[Char]], m2: Map[Int, Set[Char]]) =>
      val result = flatten(diff(m1, m2)).toSet
      val left = flatten(m1).toSet
      assert(result.subsetOf(left))
    }
  }

  property("diff is equivalent to flatten-and-diff") {
    forAll { (m1: Map[Int, Set[Char]], m2: Map[Int, Set[Char]]) =>
      flatten(diff(m1, m2)).toSet shouldEqual flatten(m1).toSet.diff(flatten(m2).toSet)
    }
  }
} 
Example 9
Source File: LfVersionsSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{Matchers, WordSpec}
import scalaz.NonEmptyList
import scalaz.scalacheck.ScalazArbitrary._

class LfVersionsSpec extends WordSpec with Matchers with GeneratorDrivenPropertyChecks {

  case class DummyVersion(value: Int) {
    def protoValue: String = value.toString
  }

  class DummyVersions(versions: NonEmptyList[DummyVersion])
      extends LfVersions[DummyVersion](versions)(_.protoValue)

  case class DummyError(msg: String)

  private def dummyVersionGen: Gen[DummyVersion] = arbitrary[Int].map(DummyVersion)

  implicit private val dummyVersionArb: Arbitrary[DummyVersion] = Arbitrary(dummyVersionGen)

  "LfVersions.acceptedVersions" should {
    "be otherVersions + defaultVersion" in forAll { vs: NonEmptyList[DummyVersion] =>
      val versions = new DummyVersions(vs)
      versions.acceptedVersions should ===(vs.list.toList)
      vs.list.toList.forall(v => versions.acceptedVersions.contains(v)) shouldBe true
    }
  }

  "LfVersions.decodeVersion" should {
    "return failure if passed version value is null, don't throw exception" in {
      val versions = new DummyVersions(NonEmptyList(DummyVersion(1)))
      versions.isAcceptedVersion(null) shouldBe None
    }

    "return failure if passed version value is an empty string, don't throw exception" in {
      val versions = new DummyVersions(NonEmptyList(DummyVersion(1)))
      versions.isAcceptedVersion("") shouldBe None
    }

    "return failure if passed version is not default and not supported" in forAll {
      (vs: NonEmptyList[DummyVersion], version: DummyVersion) =>
        whenever(!vs.list.toList.contains(version)) {
          val versions = new DummyVersions(vs)
          versions.acceptedVersions.contains(version) shouldBe false
          versions.isAcceptedVersion(version.protoValue) shouldBe None
        }
    }

    "return success if passed version is default" in forAll { default: DummyVersion =>
      val versions = new DummyVersions(NonEmptyList(default))
      versions.isAcceptedVersion(default.protoValue) shouldBe Some(default)
    }

    "return success if passed version is one of other versions" in forAll {
      (vs: NonEmptyList[DummyVersion], version: DummyVersion) =>
        val versions = new DummyVersions(version <:: vs)
        versions.acceptedVersions.contains(version) shouldBe true
        versions.isAcceptedVersion(version.protoValue) shouldBe Some(version)
    }
  }
} 
Example 10
Source File: DataArbitrary.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.data

import ImmArray.ImmArraySeq
import org.scalacheck.{Arbitrary, Gen}
import Arbitrary.arbitrary
import org.scalacheck.util.Buildable
import scalaz.{@@, Tag}

object DataArbitrary {
  implicit def `arb FrontStack`[A: Arbitrary]: Arbitrary[FrontStack[A]] =
    Arbitrary(
      arbitrary[Vector[(A, Option[ImmArray[A]])]]
        .map(_.foldRight(FrontStack.empty[A]) {
          case ((a, oia), acc) => oia.fold(a +: acc)(ia => (ia slowCons a) ++: acc)
        }))

  implicit def `arb ImmArray`[A: Arbitrary]: Arbitrary[ImmArray[A]] =
    Arbitrary {
      for {
        raw <- arbitrary[Seq[A]]
        min <- Gen.choose(0, 0 max (raw.size - 1))
        max <- Gen.choose(min, raw.size)
      } yield if (min >= max) ImmArray(Seq()) else ImmArray(raw).strictSlice(min, max)
    }

  implicit def `arb ImmArraySeq`[A: Arbitrary]: Arbitrary[ImmArraySeq[A]] =
    Arbitrary(arbitrary[ImmArray[A]] map (_.toSeq))

  private[this] sealed trait APS
  private[this] implicit val aaps: Arbitrary[String @@ APS] =
    Tag.subst(Arbitrary(Gen.asciiPrintableStr))
  implicit def `arb SortedLookupList`[A: Arbitrary]: Arbitrary[SortedLookupList[A]] =
    Arbitrary(
      Tag
        .unsubst[String, Lambda[k => Gen[Map[k, A]]], APS](arbitrary[Map[String @@ APS, A]])
        .map(SortedLookupList(_)))

  // The default collection instances don't make smaller-sized elements.
  sealed trait Div3 // XXX in scala 2.13 consider a Nat tparam
  private[this] def div3[T](g: Gen[T]): Gen[T] =
    Gen sized (n => Gen resize (n / 3, g))

  implicit def `arb container1 Div3`[C, T](
      implicit t: C => Traversable[T],
      b: Buildable[T, C],
      a: Arbitrary[T]): Arbitrary[C @@ Div3] =
    Tag subst Arbitrary(Gen buildableOf div3(a.arbitrary))

  implicit def `arb SortedLookupList Div3`[A: Arbitrary]: Arbitrary[SortedLookupList[A] @@ Div3] =
    Tag subst `arb SortedLookupList`(Arbitrary(div3(arbitrary[A])))
} 
Example 11
Source File: SomeArrayEqualsTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.speedy

import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{WordSpec, Matchers}

@SuppressWarnings(Array("org.wartremover.warts.Any"))
class SomeArrayEqualsTest extends WordSpec with Matchers with GeneratorDrivenPropertyChecks {
  import com.daml.lf.speedy.{SomeArrayEquals => SAE}
  import SomeArrayEqualsTest._

  "equals" should {
    "distinguish same-arity but different classes" in {
      case class A() extends SAE
      case class B() extends SAE
      case class C(i: Int) extends SAE
      case class D(i: Int) extends SAE
      val a = A()
      a shouldBe a
      a shouldBe A()
      a should not be B()
      C(42) shouldBe C(42)
      C(42) should not be D(42)
    }

    "distinguish different arity" in {
      case class A() extends SAE
      case class B(i: Int) extends SAE
      A() should not be B(0)
    }

    "case different element data types properly" in forAll { tb: TestBlob =>
      import java.util.Arrays.copyOf
      tb shouldBe tb
      tb.copy() shouldBe tb
      if (tb.ai ne null)
        tb.copy(ai = copyOf(tb.ai, tb.ai.length)) shouldBe tb
      if (tb.as ne null)
        tb.copy(as = copyOf(tb.as, tb.as.length)) shouldBe tb
      if (tb.s ne null)
        tb.copy(s = new String(tb.s)) shouldBe tb
    }

    "detect varying Ints" in forAll { (tb: TestBlob, i: Int) =>
      whenever(i != tb.i) {
        tb.copy(i = i) should not be tb
      }
    }

    "detect varying Strings" in forAll { (tb: TestBlob, s: Option[String]) =>
      whenever(s != Option(tb.s)) {
        tb.copy(s = s.orNull) should not be tb
      }
    }

    "detect varying Int arrays" in forAll { (tb: TestBlob, oai: Option[Array[Int]]) =>
      whenever(oai.fold(tb.ai ne null)(ai => (tb.ai eq null) || !(ai sameElements tb.ai))) {
        tb.copy(ai = oai.orNull) should not be tb
      }
    }

    "detect varying String arrays" in forAll { (tb: TestBlob, oas: Option[Array[String]]) =>
      whenever(oas.fold(tb.as ne null)(as => (tb.as eq null) || !(as sameElements tb.as))) {
        tb.copy(as = oas.orNull) should not be tb
      }
    }
  }
}

object SomeArrayEqualsTest {
  import org.scalacheck.{Gen, Arbitrary}
  import Arbitrary.{arbitrary => arb}

  final case class TestBlob(i: Int, ai: Array[Int], as: Array[String], s: String)
      extends SomeArrayEquals

  val testBlobGen: Gen[TestBlob] =
    arb[(Int, Option[Array[Int]], Option[Array[String]], Option[String])]
      .map { case (i, ai, as, s) => TestBlob(i, ai.orNull, as.orNull, s.orNull) }

  implicit val testBlobArb: Arbitrary[TestBlob] = Arbitrary(testBlobGen)
} 
Example 12
Source File: TimestampSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.javaapi.data

import java.time.Instant

import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FlatSpec, Matchers}

class TimestampSpec extends FlatSpec with Matchers with GeneratorDrivenPropertyChecks {

  behavior of "Timestamp"

  it should "be built from a java.time.Instant" in forAll(
    Gen.oneOf(0L, 1L, 10L, 100L, 1000L, Instant.now().toEpochMilli)) { millis =>
    val instant = java.time.Instant.ofEpochMilli(millis)
    withClue(
      s"input: ${millis}ms instant.getEpochSeconds: ${instant.getEpochSecond} instant.getNanos: ${instant.getNano} issue: ") {
      Timestamp
        .fromInstant(instant)
        .getMicroseconds shouldBe (millis * 1000) // getValue gives back microseconds
    }
  }

  it should "lose nanoseconds when doing TimeStamp.fromInstant(_).toInstant()" in {
    val instant = java.time.Instant.ofEpochSecond(1, 42)
    val timestamp = Timestamp.fromInstant(instant)
    timestamp.toInstant shouldBe Instant.ofEpochSecond(1, 0)
  }
} 
Example 13
Source File: NameClashRecordVariantUT.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.codegen

import com.daml.sample.MyMain.NameClashRecordVariant
import NameClashRecordVariant.{NameClashRecordVariantA, NameClashRecordVariantB}
import com.daml.ledger.client.binding.{Primitive => P, Value}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{Matchers, WordSpec}

class NameClashRecordVariantUT extends WordSpec with Matchers with GeneratorDrivenPropertyChecks {

  "generated variants have compatible read and write methods" in forAll(nameClashRecordVariantGen) {
    a1 =>
      val b = Value.encode(a1)
      val a2 = Value.decode[NameClashRecordVariant](b)
      Some(a1) shouldBe a2
  }

  def nameClashRecordVariantGen: Gen[NameClashRecordVariant] =
    Gen.oneOf(nameClashRecordVariantAGen, nameClashRecordVariantBGen)

  def nameClashRecordVariantAGen: Gen[NameClashRecordVariantA] =
    for {
      x <- arbitrary[P.Int64]
      y <- arbitrary[P.Int64]
      z <- arbitrary[P.Int64]
    } yield NameClashRecordVariantA(x, y, z)

  def nameClashRecordVariantBGen: Gen[NameClashRecordVariantB] =
    for {
      x <- arbitrary[P.Int64]
      y <- arbitrary[P.Int64]
      z <- arbitrary[P.Int64]
    } yield NameClashRecordVariantB(x, y, z)
} 
Example 14
Source File: DamlTimestampGen.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding.encoding
import java.time.Instant

import com.daml.ledger.client.binding.{Primitive => P}
import org.scalacheck.Gen

object DamlTimestampGen {

  private lazy val genRandomDamlTimestamp: Gen[P.Timestamp] = P.Timestamp.subst(
    Gen.zip(
      Gen.choose(P.Timestamp.MIN.getEpochSecond, P.Timestamp.MAX.getEpochSecond),
      Gen.choose(0L, 999999)) map { case (s, n) => Instant.ofEpochSecond(s, n * 1000) })

  private lazy val genSpecificDamlTimestamp: Gen[P.Timestamp] =
    Gen.oneOf(
      ts("6813-11-03T05:41:04Z"),
      ts("4226-11-05T05:07:48Z"),
      ts("8202-11-07T05:51:35Z"),
      ts("2529-11-06T05:57:36.498937000Z"),
      ts("2529-11-06T05:57:36.498937Z")
    )

  private def ts(s: String): P.Timestamp =
    P.Timestamp
      .discardNanos(Instant.parse(s))
      .getOrElse(sys.error("expected `P.Timestamp` friendly `Instant`"))

  lazy val genDamlTimestamp: Gen[P.Timestamp] =
    Gen.frequency((5, genRandomDamlTimestamp), (2, genSpecificDamlTimestamp))
} 
Example 15
Source File: DamlDateGen.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding.encoding

import java.time.LocalDate

import com.daml.ledger.client.binding.encoding.DamlDates._
import com.daml.ledger.client.binding.{Primitive => P}
import org.scalacheck.Gen

object DamlDateGen {

  private def genSqlCompatibleLocalDate: Gen[LocalDate] = {
    // skip the range
    val upTo: Long = RangeOfLocalDatesWithoutInjectiveFunctionToSqlDate._1.toEpochDay - 1
    val upFrom: Long = RangeOfLocalDatesWithoutInjectiveFunctionToSqlDate._2.toEpochDay + 1
    Gen
      .oneOf(
        Gen.choose(Min.toEpochDay, upTo),
        Gen.choose(upFrom, Max.toEpochDay)
      )
      .map(LocalDate.ofEpochDay)
  }

  def genDamlDate: Gen[P.Date] = P.Date.subst(genSqlCompatibleLocalDate)
} 
Example 16
Source File: DamlDecimalGen.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding.encoding

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Gen}
import com.daml.ledger.client.binding.{Primitive => P}

// DAML Decimal is DECIMAL(38, 10)
object DamlDecimalGen {

  private val scale = 10

  val MaxDamlDecimal = BigDecimal("9" * 28 + "." + "9" * scale).setScale(scale)
  val MinDamlDecimal = -MaxDamlDecimal

  // this gives us: [-21474836480000000000.0000000000; 21474836470000000000.0000000000]
  // [BigDecimal(scala.Int.MinValue, -10).setScale(10), BigDecimal(scala.Int.MaxValue, -10).setScale(10)]
  private val genDamlDecimal: Gen[BigDecimal] =
    for {
      n <- arbitrary[Int]
      s <- Gen.choose(-scale, scale)
    } yield BigDecimal(n.toLong, s).setScale(scale)

  private val genSpecificDamlDecimal: Gen[BigDecimal] =
    Gen.oneOf(
      MaxDamlDecimal,
      MinDamlDecimal,
      BigDecimal(0).setScale(scale),
      BigDecimal(1).setScale(scale),
      BigDecimal(-1).setScale(scale))

  lazy val arbDamlDecimal: Arbitrary[P.Numeric] = Arbitrary(
    Gen.frequency((10, genDamlDecimal), (5, genSpecificDamlDecimal)))
} 
Example 17
Source File: PrimitiveSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding

import java.time.{Instant, LocalDate}

import org.scalacheck.Gen
import org.scalatest.{WordSpec, Matchers}
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import shapeless.test.illTyped

import com.daml.ledger.client.binding.{Primitive => P}

class PrimitiveSpec extends WordSpec with Matchers with GeneratorDrivenPropertyChecks {
  import PrimitiveSpec._

  "Primitive types" when {
    "defined concretely" should {
      "have nice companion aliases" in {
        P.List: collection.generic.TraversableFactory[P.List]
      }
    }
    "defined abstractly" should {
      "carry their phantoms" in {
        def check[A, B]() = {
          illTyped(
            "implicitly[P.ContractId[A] =:= P.ContractId[B]]",
            "Cannot prove that .*ContractId\\[A\\] =:= .*ContractId\\[B\\].")
          illTyped(
            "implicitly[P.TemplateId[A] =:= P.TemplateId[B]]",
            "Cannot prove that .*TemplateId\\[A\\] =:= .*TemplateId\\[B\\].")
          illTyped(
            "implicitly[P.Update[A] =:= P.Update[B]]",
            "Cannot prove that .*Update\\[A\\] =:= .*Update\\[B\\].")
        }
        check[Unit, Unit]()
      }
    }
  }

  "Date.fromLocalDate" should {
    import ValueSpec.dateArb

    "pass through existing dates" in forAll { d: P.Date =>
      P.Date.fromLocalDate(d: LocalDate) shouldBe Some(d)
    }

    "be idempotent" in forAll(anyLocalDateGen) { d =>
      val od2 = P.Date.fromLocalDate(d)
      od2 flatMap (P.Date.fromLocalDate(_: LocalDate)) shouldBe od2
    }

    "prove MIN, MAX are valid" in {
      import P.Date.{MIN, MAX}
      P.Date.fromLocalDate(MIN: LocalDate) shouldBe Some(MIN)
      P.Date.fromLocalDate(MAX: LocalDate) shouldBe Some(MAX)
    }
  }

  "Timestamp.discardNanos" should {
    import ValueSpec.timestampArb

    "pass through existing times" in forAll { t: P.Timestamp =>
      P.Timestamp.discardNanos(t: Instant) shouldBe Some(t)
    }

    "be idempotent" in forAll(anyInstantGen) { i =>
      val oi2 = P.Timestamp.discardNanos(i)
      oi2 flatMap (P.Timestamp.discardNanos(_: Instant)) shouldBe oi2
    }

    "prove MIN, MAX are valid" in {
      import P.Timestamp.{MIN, MAX}
      P.Timestamp.discardNanos(MIN: Instant) shouldBe Some(MIN)
      P.Timestamp.discardNanos(MAX: Instant) shouldBe Some(MAX)
    }

    "preapprove values for TimestampConversion.instantToMicros" in forAll(anyInstantGen) { i =>
      P.Timestamp.discardNanos(i) foreach { t =>
        noException should be thrownBy com.daml.api.util.TimestampConversion
          .instantToMicros(t)
      }
    }
  }
}

object PrimitiveSpec {
  private val anyLocalDateGen: Gen[LocalDate] =
    Gen.choose(LocalDate.MIN.toEpochDay, LocalDate.MAX.toEpochDay) map LocalDate.ofEpochDay

  private val anyInstantGen: Gen[Instant] =
    Gen
      .zip(
        Gen.choose(Instant.MIN.getEpochSecond, Instant.MAX.getEpochSecond),
        Gen.choose(0L, 999999999))
      .map { case (s, n) => Instant.ofEpochSecond(s, n) }
} 
Example 18
Source File: CustomMatcherSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.scalatest

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen
import org.scalatest.WordSpec
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import scalaz.{Equal, Show}

class CustomMatcherSpec extends WordSpec with GeneratorDrivenPropertyChecks {

  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 10000)

  "make sure it works comparing ints" in {
    import com.daml.scalatest.CustomMatcher._
    import scalaz.std.anyVal._

    CustomMatcherOps(10) should_=== 10
    CustomMatcherOps(10) should_=/= 11

    10 should_=== 10
    10 should_=/= 11
  }

  case class Dummy(a: String, b: Int, c: BigDecimal)

  lazy val genDummy: Gen[Dummy] = for {
    a <- arbitrary[String]
    b <- arbitrary[Int]
    c <- arbitrary[BigDecimal]
  } yield Dummy(a, b, c)

  lazy val genPairOfNonEqualDummies: Gen[(Dummy, Dummy)] = {
    def genSetOf2: Gen[Set[Dummy]] =
      Gen.buildableOfN[Set[Dummy], Dummy](2, genDummy).filter(_.size == 2)

    genSetOf2.map(_.toSeq).map {
      case Seq(a, b) => (a, b)
      case a @ _ => sys.error(s"Should never happen: $a")
    }
  }

  implicit val dummyEqual: Equal[Dummy] = Equal.equalA

  implicit val dummyShow: Show[Dummy] = Show.showA

  "make sure it works comparing case classes with custom Show and Equal" in forAll(
    genPairOfNonEqualDummies) {
    case (a, b) =>
      import com.daml.scalatest.CustomMatcher._

      a should_=== a
      a should_=== a.copy()

      a should_=/= b
  }
} 
Example 19
Source File: CodeGenSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml
package codegen

import com.daml.lf.data.ImmArray.ImmArraySeq
import com.daml.lf.data.Ref.Identifier
import com.daml.lf.iface._
import com.daml.lf.value.test.ValueGenerators.idGen

import org.scalatest.{WordSpec, Matchers}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

class CodeGenSpec extends WordSpec with Matchers with GeneratorDrivenPropertyChecks {
  import CodeGen.filterTemplatesBy
  import CodeGenSpec._

  "filterTemplatesBy" should {
    "be identity given empty regexes" in forAll(trivialEnvInterfaceGen) { ei =>
      filterTemplatesBy(Seq.empty)(ei) should ===(ei)
    }

    "delete all templates given impossible regex" in forAll(trivialEnvInterfaceGen) { ei =>
      val noTemplates = ei copy (ei.typeDecls transform {
        case (_, tmpl @ InterfaceType.Template(_, _)) => InterfaceType.Normal(tmpl.`type`)
        case (_, v) => v
      })
      filterTemplatesBy(Seq("(?!a)a".r))(ei) should ===(noTemplates)
    }

    "match the union of regexes, not intersection" in forAll(trivialEnvInterfaceGen) { ei =>
      filterTemplatesBy(Seq("(?s).*".r, "(?!a)a".r))(ei) should ===(ei)
    }
  }
}

object CodeGenSpec {
  import org.scalacheck.{Arbitrary, Gen}
  import Arbitrary.arbitrary

  val trivialEnvInterfaceGen: Gen[EnvironmentInterface] = {
    val fooRec = Record(ImmArraySeq.empty)
    val fooTmpl = InterfaceType.Template(fooRec, DefTemplate(Map.empty, None))
    val fooNorm = InterfaceType.Normal(DefDataType(ImmArraySeq.empty, fooRec))
    implicit val idArb: Arbitrary[Identifier] = Arbitrary(idGen)
    arbitrary[Map[Identifier, Boolean]] map { ids =>
      EnvironmentInterface(ids transform { (_, isTemplate) =>
        if (isTemplate) fooTmpl else fooNorm
      })
    }
  }
} 
Example 20
Source File: KVStoreBenchmark.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.benchmark

import cats.effect.IO
import org.openjdk.jmh.annotations.{Benchmark, OperationsPerInvocation, TearDown}
import org.scalacheck.Gen
import cats.implicits._
import jbok.common.{gen, FileUtil}
import jbok.core.StatelessGen
import jbok.persistent.{ColumnFamily, MemoryKVStore}
import jbok.persistent.rocksdb.RocksKVStore

class KVStoreBenchmark extends JbokBenchmark {
  val size = 10000

  val blockHeaders = Gen.listOfN(size, StatelessGen.blockHeader).sample.get.toArray

  var i = 0

  val keyGen   = gen.sizedByteArray(16)
  val valueGen = gen.sizedByteArray(100)

  val keys   = Gen.listOfN(size, keyGen).sample.get
  val values = Gen.listOfN(size, valueGen).sample.get
  val kvs    = keys.zip(values).toArray

  val dirRocks         = FileUtil[IO].temporaryDir().allocated.unsafeRunSync()._1
  val (dbRocks, close) = RocksKVStore.resource[IO](dirRocks.path, List(ColumnFamily.default)).allocated.unsafeRunSync()
  var dbMem            = MemoryKVStore[IO].unsafeRunSync()

  @Benchmark
  def putRocks() = {
    val (k, v) = kvs(i)
    i = (i + 1) % kvs.length
    dbRocks.put(ColumnFamily.default, k, v).unsafeRunSync()
  }

  @Benchmark
  @OperationsPerInvocation(100)
  def putBatchRocks() = {
    i = (i + 1) % (kvs.length / 100)
    val put = (i * 100 until (i + 1) * 100)
      .map(i => kvs(i))
      .toList
    dbRocks.writeBatch(ColumnFamily.default, put, Nil).unsafeRunSync()
  }

  @Benchmark
  @OperationsPerInvocation(100)
  def putBatchRocksPar() = {
    i = (i + 1) % (kvs.length / 100)
    val put = (i * 100 until (i + 1) * 100)
      .map(i => kvs(i))
      .toList
    put.parTraverse { case (k, v) => dbRocks.put(ColumnFamily.default, k, v) }.unsafeRunSync()
  }

  @TearDown
  def tearDown(): Unit = {
    close.unsafeRunSync()
    dbMem = MemoryKVStore[IO].unsafeRunSync()
    RocksKVStore.destroy[IO](dirRocks.path).unsafeRunSync()
  }
} 
Example 21
Source File: TrieBenchmark.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.benchmark

import cats.effect.IO
import jbok.codec.HexPrefix
import jbok.codec.rlp.implicits._
import jbok.common.gen
import jbok.core.store.ColumnFamilies
import jbok.persistent.mpt.MptNode.LeafNode
import jbok.persistent.mpt.{MerklePatriciaTrie, MptNode}
import jbok.persistent.{MemoryKVStore, StageKVStore}
import org.openjdk.jmh.annotations._
import org.scalacheck.Gen

class TrieBenchmark extends JbokBenchmark {

  val store = MemoryKVStore[IO].unsafeRunSync()
  val mpt   = MerklePatriciaTrie[IO, Array[Byte], Array[Byte]](ColumnFamilies.Node, store).unsafeRunSync()
  var stage = StageKVStore(mpt)

  val size = 100000

  var i = 0

  val (keys, values) =
    (for {
      keys   <- Gen.listOfN(size, gen.boundedByteArray(0, 100))
      values <- Gen.listOfN(size, gen.boundedByteArray(0, 100))
    } yield (keys, values)).sample.get

//  @Benchmark
//  @OperationsPerInvocation(100)
//  def randomWrite() = {
//    for(_ <- 0 until 100) {
//      val key = keys(i)
//      val value = values(i)
//      mpt.putRaw(key, value).unsafeRunSync()
//      i = (i + 1) % size
//    }
//  }

  @Benchmark
  @OperationsPerInvocation(100)
  def roundtripNode() =
    for (_ <- 0 until 100) {
      val key   = keys(i)
      val value = values(i)
      val node  = LeafNode(HexPrefix.encodedToNibbles(key.encoded), value.encoded)
      val bytes = node.bytes
      bytes.decoded[MptNode]
      i = (i + 1) % size
    }

  @Benchmark
  @OperationsPerInvocation(100)
  def randomWriteState() = {
    for (_ <- 0 until 100) {
      val key   = keys(i)
      val value = values(i)
      stage = stage.put(key, value)
      i = (i + 1) % size
    }
    stage = stage.commit.unsafeRunSync()
  }
} 
Example 22
Source File: CodecBenchmark.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.benchmark

import jbok.codec.rlp.RlpCodec
import jbok.codec.rlp.implicits._
import jbok.core.StatelessGen
import jbok.core.models.BlockHeader
import org.openjdk.jmh.annotations._
import org.scalacheck.Gen

class CodecBenchmark extends JbokBenchmark {
  val size = 10000

  val xs = Gen.listOfN(size, StatelessGen.blockHeader).sample.get.toArray

  var i = 0

  @Benchmark
  @OperationsPerInvocation(1000)
  def derive_1k() =
    (0 until 1000).foreach { _ =>
      xs(i).encoded
      i = (i + 1) % size
    }

  val codec = RlpCodec[BlockHeader]
  @Benchmark
  @OperationsPerInvocation(1000)
  def derive_cached_1k() =
    (0 until 1000).foreach { _ =>
      xs(i).encoded(codec)
      i = (i + 1) % size
    }
} 
Example 23
Source File: HexPrefixSpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.codec

import jbok.codec.HexPrefix.Nibbles
import jbok.common.CommonSpec
import org.scalacheck.Gen
import scodec.bits._

class HexPrefixSpec extends CommonSpec {
  "HexPrefix" should {
    val charGen: Gen[Char] = Gen.oneOf("0123456789abcdef")
    val hexGen: Gen[String] = for {
      size  <- Gen.chooseNum(0, 100)
      chars <- Gen.listOfN(size, charGen)
    } yield chars.mkString

    val boolGen: Gen[Boolean] = Gen.oneOf(true, false)

    "encode and decode nibbles" in {
      HexPrefix.encode(Nibbles.coerce("12345"), isLeaf = false) shouldBe hex"112345"
      HexPrefix.encode(Nibbles.coerce("012345"), isLeaf = false) shouldBe hex"00012345"
      HexPrefix.encode(Nibbles.coerce("f1cb8"), isLeaf = true) shouldBe hex"3f1cb8"
      HexPrefix.encode(Nibbles.coerce("0f1cb8"), isLeaf = true) shouldBe hex"200f1cb8"

      HexPrefix.decode(hex"00abcd").require shouldBe ((false, Nibbles.coerce("abcd")))
      HexPrefix.decode(hex"20abcd").require shouldBe ((true, Nibbles.coerce("abcd")))
      HexPrefix.decode(hex"19abcd").require shouldBe ((false, Nibbles.coerce("9abcd")))
      HexPrefix.decode(hex"39abcd").require shouldBe ((true, Nibbles.coerce("9abcd")))

      forAll(hexGen, boolGen) {
        case (hex, isLeaf) =>
          val nibbles = Nibbles.coerce(hex)
          val bytes   = HexPrefix.encode(nibbles, isLeaf = isLeaf)
          val decoded = HexPrefix.decode(bytes).require
          decoded shouldBe ((isLeaf, nibbles))
      }
    }
  }
} 
Example 24
Source File: CommonSpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.common

import cats.effect.{IO, Resource}
import cats.implicits._
import jbok.common.log.{Level, Logger}
import jbok.common.thread.ThreadUtil
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest._
import org.scalatest.concurrent.TimeLimitedTests
import org.scalatest.prop.PropertyChecks
import org.scalatest.time.Span

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

trait CommonSpec
    extends WordSpecLike
    with Matchers
    with PropertyChecks
    with BeforeAndAfterAll
    with BeforeAndAfterEach
    with TimeLimitedTests
    with CancelAfterFailure
    with CommonArb {

  implicit val cs = IO.contextShift(ExecutionContext.global)

  implicit val timer = IO.timer(ExecutionContext.global)

  implicit val ce = IO.ioConcurrentEffect(cs)

  implicit val acg = ThreadUtil.acgGlobal

  override def timeLimit: Span = 60.seconds

  Logger.setRootHandlers[IO](Logger.consoleHandler(minimumLevel = Some(Level.Info))).unsafeRunSync()

  def withResource[A](res: Resource[IO, A])(f: A => IO[Unit]): Unit =
    res.use(a => f(a)).unsafeRunSync()

  def withIO[A](ioa: IO[A]): Unit =
    ioa.void.unsafeRunSync()

  def random[A](implicit arb: Arbitrary[A]): A =
    arb.arbitrary.sample.get

  def random[A](gen: Gen[A]): A =
    gen.sample.get
}

object CommonSpec extends CommonSpec 
Example 25
Source File: gen.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.common

import jbok.common.math.N
import org.scalacheck.Arbitrary._
import org.scalacheck.Gen
import org.scalacheck.Gen.Choose
import scodec.bits.ByteVector
import spire.laws.{gen => SpireGen}
import spire.math.{Natural, SafeLong}

object gen {
  def int(min: Int = Int.MinValue, max: Int = Int.MaxValue): Gen[Int] =
    Gen.choose(min, max)

  val hexChar: Gen[Char] = Gen.oneOf("0123456789abcdef")

  def hex(min: Int, max: Int): Gen[String] =
    for {
      size  <- Gen.chooseNum(min, max)
      chars <- Gen.listOfN(size, hexChar)
    } yield chars.mkString

  val natural: Gen[Natural] =
    SpireGen.natural

  val safeLong: Gen[SafeLong] =
    SpireGen.safeLong

  val N: Gen[N] =
    safeLong.map(_.abs)

  val bigInt: Gen[BigInt] =
    arbitrary[BigInt].map(_.abs)

  val byteArray: Gen[Array[Byte]] =
    Gen.listOf(arbitrary[Byte]).map(_.toArray)

  val byteVector: Gen[ByteVector] =
    byteArray.map(ByteVector.apply)

  def boundedByteArray(l: Int, u: Int): Gen[Array[Byte]] =
    Gen.choose(l, u).flatMap(size => sizedByteArray(size))

  def boundedByteVector(l: Int, u: Int): Gen[ByteVector] =
    Gen.choose(l, u).flatMap(size => sizedByteVector(size))

  def sizedByteArray(size: Int): Gen[Array[Byte]] =
    Gen.listOfN(size, arbitrary[Byte]).map(_.toArray)

  def sizedByteVector(size: Int): Gen[ByteVector] =
    Gen.listOfN(size, arbitrary[Byte]).map(ByteVector.apply)

  def posNum[T](implicit num: Numeric[T], c: Choose[T]): Gen[T] = Gen.posNum[T]

  def boundedList[T](minSize: Int, maxSize: Int, gen: Gen[T]): Gen[List[T]] =
    Gen.choose(minSize, maxSize).flatMap(size => Gen.listOfN(size, gen))
} 
Example 26
Source File: testkit.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.persistent

import cats.effect.{IO, Resource}
import jbok.codec.HexPrefix
import jbok.common.{gen, FileUtil}
import jbok.persistent.rocksdb.RocksKVStore
import org.scalacheck.{Arbitrary, Gen}
import scodec.bits.ByteVector
import jbok.codec.rlp.implicits._
import jbok.persistent.mpt.MptNode
import jbok.persistent.mpt.MptNode._
import cats.implicits._

object testkit {
  implicit def arbColumnFamily: Arbitrary[ColumnFamily] = Arbitrary {
    Gen.alphaNumStr.map(ColumnFamily.apply)
  }

  def testRocksKVStore(cfs: List[ColumnFamily] = List(ColumnFamily.default)): Resource[IO, KVStore[IO]] =
    FileUtil[IO].temporaryDir().flatMap { dir =>
      RocksKVStore.resource[IO](dir.path, cfs)
    }

  val testMemoryKVStore: Resource[IO, KVStore[IO]] =
    Resource.liftF(MemoryKVStore[IO])

  def testRocksStageStore(cfs: List[ColumnFamily] = List(ColumnFamily.default)): Resource[IO, StageKVStore[IO, ByteVector, ByteVector]] =
    testRocksKVStore(cfs).map(inner => StageKVStore(SingleColumnKVStore[IO, ByteVector, ByteVector](ColumnFamily.default, inner)))

  val testMemoryStageStore: Resource[IO, StageKVStore[IO, ByteVector, ByteVector]] =
    testMemoryKVStore.map(inner => StageKVStore(SingleColumnKVStore[IO, ByteVector, ByteVector](ColumnFamily.default, inner)))

  implicit lazy val arbLeafNode: Arbitrary[LeafNode] = Arbitrary {
    for {
      key   <- gen.boundedByteVector(0, 1024)
      value <- gen.boundedByteVector(0, 1024)
    } yield LeafNode(HexPrefix.encodedToNibbles(key.encoded), value.encoded)
  }

  implicit lazy val arbBranchNode: Arbitrary[BranchNode] = Arbitrary {
    for {
      children <- Gen
        .listOfN(16, Gen.oneOf(gen.sizedByteVector(32).map(_.asLeft), arbMptNode.arbitrary.map(_.asRight)))
        .map(childrenList => childrenList.map(child => Some(child)))
      value <- gen.byteVector
    } yield BranchNode(children, Some(value.encoded))
  }

  implicit lazy val arbExtensionNode: Arbitrary[ExtensionNode] = Arbitrary {
    for {
      key   <- gen.boundedByteVector(0, 1024)
      value <- gen.boundedByteVector(0, 1024)
    } yield ExtensionNode(HexPrefix.encodedToNibbles(key.encoded), Left(value))
  }

  implicit lazy val arbMptNode: Arbitrary[MptNode] = Arbitrary {
    Gen.oneOf[MptNode](arbLeafNode.arbitrary, arbExtensionNode.arbitrary, arbBranchNode.arbitrary)
  }
} 
Example 27
Source File: StackSpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.evm

import jbok.common.gen
import jbok.core.{CoreSpec, StatelessGen}
import jbok.core.models.UInt256
import org.scalacheck.{Arbitrary, Gen}

class StackSpec extends CoreSpec {
  val maxStackSize            = 32
  implicit val arbStack       = Arbitrary(StatelessGen.stack(maxStackSize, StatelessGen.uint256()))
  implicit val arbInt         = Arbitrary(Gen.choose(0, maxStackSize))
  implicit val arbUint256List = Arbitrary(gen.boundedList(0, 16, StatelessGen.uint256()))

  "Stack" should {
    "pop single element" in {
      forAll { stack: Stack =>
        val (v, stack1) = stack.pop
        if (stack.size > 0) {
          v shouldBe stack.toList.head
          stack1.toList shouldBe stack.toList.tail
        } else {
          v shouldBe 0
          stack1 shouldBe stack
        }
      }
    }

    "pop multiple elements" in {
      forAll { (stack: Stack, i: Int) =>
        val (vs, stack1) = stack.pop(i)
        if (stack.size >= i) {
          vs shouldBe stack.toList.take(i)
          stack1.toList shouldBe stack.toList.drop(i)
        } else {
          vs shouldBe Seq.fill(i)(UInt256.zero)
          stack1 shouldBe stack
        }
      }
    }

    "push single element" in {
      forAll { (stack: Stack, v: UInt256) =>
        val stack1 = stack.push(v)

        if (stack.size < stack.maxSize) {
          stack1.toList shouldBe (v +: stack.toList)
        } else {
          stack1 shouldBe stack
        }
      }
    }

    "push multiple elements" in {
      forAll { (stack: Stack, vs: List[UInt256]) =>
        val stack1 = stack.push(vs)

        if (stack.size + vs.size <= stack.maxSize) {
          stack1.toList shouldBe (vs.reverse ++ stack.toList)
        } else {
          stack1 shouldBe stack
        }
      }
    }

    "duplicate element" in {
      forAll { (stack: Stack, i: Int) =>
        val stack1 = stack.dup(i)

        if (i < stack.size && stack.size < stack.maxSize) {
          val x = stack.toList(i)
          stack1.toList shouldBe (x +: stack.toList)
        } else {
          stack1 shouldBe stack
        }
      }
    }

    "swap elements" in {
      forAll { (stack: Stack, i: Int) =>
        val stack1 = stack.swap(i)

        if (i < stack.size) {
          val x = stack.toList.head
          val y = stack.toList(i)
          stack1.toList shouldBe stack.toList.updated(0, y).updated(i, x)
        } else {
          stack1 shouldBe stack
        }
      }
    }
  }
} 
Example 28
Source File: StatefulGen.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.core

import cats.effect.IO
import jbok.core.ledger.History
import jbok.core.ledger.TypedBlock.MinedBlock
import jbok.core.mining.{BlockMiner, TxGen}
import jbok.core.models.{Block, SignedTransaction}
import org.scalacheck.Gen

object StatefulGen {
  import CoreSpec._

  def transactions(min: Int = 0, max: Int = 32, history: History[IO] = locator.unsafeRunSync().get[History[IO]]): Gen[List[SignedTransaction]] =
    for {
      size <- Gen.chooseNum(min, max)
      txGen = TxGen[IO](testKeyPair :: Nil, history).unsafeRunSync()
      txs   = txGen.genValidExternalTxN(size).unsafeRunSync()
    } yield txs

  def blocks(min: Int = 1, max: Int = 1): Gen[List[Block]] = {
    val objects = locator.unsafeRunSync()
    val miner   = objects.get[BlockMiner[IO]]
    for {
      size <- Gen.chooseNum(min, max)
      blocks = miner.mineN(size).unsafeRunSync()
    } yield blocks.map(_.block)
  }

  def block(parent: Option[Block] = None, stxs: Option[List[SignedTransaction]] = None): Gen[Block] =
    minedBlock(parent, stxs).map(_.block)

  def minedBlock(parent: Option[Block] = None, stxs: Option[List[SignedTransaction]] = None): Gen[MinedBlock] = {
    val objects = locator.unsafeRunSync()
    val miner   = objects.get[BlockMiner[IO]]
    miner.mine(parent, stxs).unsafeRunSync()
  }
} 
Example 29
Source File: PeerStoreSpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.core.peer

import cats.effect.IO
import cats.implicits._
import jbok.core.CoreSpec
import org.scalacheck.Gen

class PeerStoreSpec extends CoreSpec {
  "PeerStore" should {

    "put and get PeerUri" in check { objects =>
      val store = objects.get[PeerStore[IO]]
      val uris  = random[List[PeerUri]](Gen.listOfN(100, arbPeerUri.arbitrary))
      for {
        _  <- uris.traverse(store.put)
        xs <- store.getAll
        _ = xs should contain theSameElementsAs uris.toSet
      } yield ()
    }
  }
} 
Example 30
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 31
Source File: ExampleGeneration.scala    From circe-golden   with Apache License 2.0 5 votes vote down vote up
package io.circe.testing.golden

import org.scalacheck.Gen
import org.scalacheck.rng.Seed
import scala.util.Try

trait ExampleGeneration[A] { self: GoldenCodecLaws[A] =>
  def size: Int
  def gen: Gen[A]

  protected lazy val params: Gen.Parameters = Gen.Parameters.default.withSize(size)

  final def getValue(seed: Seed): A = gen.pureApply(params, seed)
  final def getValueFromBase64Seed(seed: String): Try[A] = Seed.fromBase64(seed).map(getValue)

  final def generateRandomGoldenExamples(count: Int): List[(Seed, A, String)] =
    (0 until count).map { _ =>
      val seed = Seed.random()
      val value = getValue(seed)

      (seed, value, printJson(encode(value)))
    }.toList
} 
Example 32
Source File: ResourceFileGoldenCodecLaws.scala    From circe-golden   with Apache License 2.0 5 votes vote down vote up
package io.circe.testing.golden

import cats.instances.list._, cats.instances.try_._
import cats.syntax.apply._, cats.syntax.traverse._
import io.circe.{ Decoder, Encoder, Printer }
import java.io.{ File, PrintWriter }
import org.scalacheck.{ Arbitrary, Gen }
import scala.reflect.runtime.universe.TypeTag
import scala.util.{ Failure, Try }
import scala.util.matching.Regex

abstract class ResourceFileGoldenCodecLaws[A](
  name: String,
  resourceRootDir: File,
  resourcePackage: List[String],
  val size: Int,
  count: Int,
  override protected val printer: Printer
) extends GoldenCodecLaws[A]
    with ExampleGeneration[A] {

  private[this] val resourceRootPath: String = "/" + resourcePackage.mkString("/") + "/"
  private[this] val resourceDir: File = resourcePackage.foldLeft(resourceRootDir) {
    case (acc, p) => new File(acc, p)
  }
  private[this] val GoldenFilePattern: Regex = "^-(.{44})\\.json$".r

  private[this] lazy val loadGoldenFiles: Try[List[(A, String)]] =
    Resources.open(resourceRootPath).flatMap { dirSource =>
      val files = dirSource.getLines.flatMap {
        case fileName if fileName.startsWith(name) =>
          fileName.drop(name.length) match {
            case GoldenFilePattern(seed) => Some((seed, fileName))
            case _                       => None
          }
        case _ => None
      }.toList.traverse[Try, (A, String)] {
        case (seed, name) =>
          val contents = Resources.open(resourceRootPath + name).map { source =>
            val lines = source.getLines.mkString("\n")
            source.close()
            lines
          }
          (getValueFromBase64Seed(seed), contents).tupled
      }

      dirSource.close()

      // Fail if we don't have either zero golden files or the required number.
      files.flatMap { values =>
        if (values.size == 0 || values.size == count) files
        else Failure(new IllegalStateException(s"Expected 0 or $count golden files, got ${values.size}"))
      }
    }

  private[this] def generateGoldenFiles: Try[List[(A, String)]] =
    generateRandomGoldenExamples(count).traverse {
      case (seed, value, encoded) =>
        Try {
          resourceDir.mkdirs()
          val file = new File(resourceDir, s"$name-${seed.toBase64}.json")

          val writer = new PrintWriter(file)
          writer.print(encoded)
          writer.close()

          (value, encoded)
        }
    }

  protected lazy val goldenExamples: Try[List[(A, String)]] =
    loadGoldenFiles.flatMap(fs => if (fs.isEmpty) generateGoldenFiles else loadGoldenFiles)
}

object ResourceFileGoldenCodecLaws {
  def apply[A](
    name: String,
    resourceRootDir: File,
    resourcePackage: List[String],
    size: Int,
    count: Int,
   printer: Printer
  )(implicit decodeA: Decoder[A], encodeA: Encoder[A], arbitraryA: Arbitrary[A]): GoldenCodecLaws[A] =
    new ResourceFileGoldenCodecLaws[A](name, resourceRootDir, resourcePackage, size, count, printer) {
      val decode: Decoder[A] = decodeA
      val encode: Encoder[A] = encodeA
      val gen: Gen[A] = arbitraryA.arbitrary
    }

  def apply[A](
    size: Int = 100,
    count: Int = 1,
    printer: Printer = Printer.spaces2
  )(
    implicit decodeA: Decoder[A],
    encodeA: Encoder[A],
    arbitraryA: Arbitrary[A],
    typeTagA: TypeTag[A]
  ): GoldenCodecLaws[A] =
    apply[A](Resources.inferName[A], Resources.inferRootDir, Resources.inferPackage[A], size, count, printer)
} 
Example 33
Source File: LiteralGenerator.scala    From drizzle-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.catalyst.expressions

import java.sql.{Date, Timestamp}

import org.scalacheck.{Arbitrary, Gen}

import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.CalendarInterval


object LiteralGenerator {

  lazy val byteLiteralGen: Gen[Literal] =
    for { b <- Arbitrary.arbByte.arbitrary } yield Literal.create(b, ByteType)

  lazy val shortLiteralGen: Gen[Literal] =
    for { s <- Arbitrary.arbShort.arbitrary } yield Literal.create(s, ShortType)

  lazy val integerLiteralGen: Gen[Literal] =
    for { i <- Arbitrary.arbInt.arbitrary } yield Literal.create(i, IntegerType)

  lazy val longLiteralGen: Gen[Literal] =
    for { l <- Arbitrary.arbLong.arbitrary } yield Literal.create(l, LongType)

  lazy val floatLiteralGen: Gen[Literal] =
    for {
      f <- Gen.chooseNum(Float.MinValue / 2, Float.MaxValue / 2,
        Float.NaN, Float.PositiveInfinity, Float.NegativeInfinity)
    } yield Literal.create(f, FloatType)

  lazy val doubleLiteralGen: Gen[Literal] =
    for {
      f <- Gen.chooseNum(Double.MinValue / 2, Double.MaxValue / 2,
        Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity)
    } yield Literal.create(f, DoubleType)

  // TODO cache the generated data
  def decimalLiteralGen(precision: Int, scale: Int): Gen[Literal] = {
    assert(scale >= 0)
    assert(precision >= scale)
    Arbitrary.arbBigInt.arbitrary.map { s =>
      val a = (s % BigInt(10).pow(precision - scale)).toString()
      val b = (s % BigInt(10).pow(scale)).abs.toString()
      Literal.create(
        Decimal(BigDecimal(s"$a.$b"), precision, scale),
        DecimalType(precision, scale))
    }
  }

  lazy val stringLiteralGen: Gen[Literal] =
    for { s <- Arbitrary.arbString.arbitrary } yield Literal.create(s, StringType)

  lazy val binaryLiteralGen: Gen[Literal] =
    for { ab <- Gen.listOf[Byte](Arbitrary.arbByte.arbitrary) }
      yield Literal.create(ab.toArray, BinaryType)

  lazy val booleanLiteralGen: Gen[Literal] =
    for { b <- Arbitrary.arbBool.arbitrary } yield Literal.create(b, BooleanType)

  lazy val dateLiteralGen: Gen[Literal] =
    for { d <- Arbitrary.arbInt.arbitrary } yield Literal.create(new Date(d), DateType)

  lazy val timestampLiteralGen: Gen[Literal] =
    for { t <- Arbitrary.arbLong.arbitrary } yield Literal.create(new Timestamp(t), TimestampType)

  lazy val calendarIntervalLiterGen: Gen[Literal] =
    for { m <- Arbitrary.arbInt.arbitrary; s <- Arbitrary.arbLong.arbitrary}
      yield Literal.create(new CalendarInterval(m, s), CalendarIntervalType)


  // Sometimes, it would be quite expensive when unlimited value is used,
  // for example, the `times` arguments for StringRepeat would hang the test 'forever'
  // if it's tested against Int.MaxValue by ScalaCheck, therefore, use values from a limited
  // range is more reasonable
  lazy val limitedIntegerLiteralGen: Gen[Literal] =
    for { i <- Gen.choose(-100, 100) } yield Literal.create(i, IntegerType)

  def randomGen(dt: DataType): Gen[Literal] = {
    dt match {
      case ByteType => byteLiteralGen
      case ShortType => shortLiteralGen
      case IntegerType => integerLiteralGen
      case LongType => longLiteralGen
      case DoubleType => doubleLiteralGen
      case FloatType => floatLiteralGen
      case DateType => dateLiteralGen
      case TimestampType => timestampLiteralGen
      case BooleanType => booleanLiteralGen
      case StringType => stringLiteralGen
      case BinaryType => binaryLiteralGen
      case CalendarIntervalType => calendarIntervalLiterGen
      case DecimalType.Fixed(precision, scale) => decimalLiteralGen(precision, scale)
      case dt => throw new IllegalArgumentException(s"not supported type $dt")
    }
  }
} 
Example 34
Source File: HillClimbingSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.search.local

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


class HillClimbingSpec extends Specification with ScalaCheck {
  import HillClimbingSpec._

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

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

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

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

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

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

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

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

import scala.concurrent.duration._


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

  import GeneticAlgorithm.StringIndividual._

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

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

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

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

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

} 
Example 36
Source File: Gens.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import java.time._
import java.util.TimeZone
import org.scalacheck.Gen

trait Gens {
  def instantGen: Gen[Instant] = Gen.chooseNum(0L, Long.MaxValue).map(Instant.ofEpochMilli)

  def localDateGen: Gen[LocalDate] = for {
    year <- Gen.chooseNum(Year.MIN_VALUE, Year.MAX_VALUE)
    month <- Gen.chooseNum(1, 12)
    dayOfMonth <- Gen.chooseNum(1, Month.of(month).length(Year.isLeap(year)))
  } yield LocalDate.of(year, month, dayOfMonth)

  def localDateTimeGen: Gen[LocalDateTime] = for {
    instant <- instantGen
    zoneId <- Gen.oneOf(TimeZone.getAvailableIDs.map(TimeZone.getTimeZone(_).toZoneId).toSeq)
  } yield LocalDateTime.ofInstant(instant, zoneId)

  def localTimeGen: Gen[LocalTime] = for {
    hour <- Gen.chooseNum(0, 23)
    minute <- Gen.chooseNum(0, 59)
    second <- Gen.chooseNum(0, 59)
  } yield LocalTime.of(hour, minute, second)

  def zonedDateTimeGen: Gen[ZonedDateTime] = for {
    instant <- instantGen
    zoneId <- Gen.oneOf(TimeZone.getAvailableIDs.map(TimeZone.getTimeZone(_).toZoneId).toSeq)
  } yield ZonedDateTime.ofInstant(instant, zoneId)

  def offsetDateTimeGen: Gen[OffsetDateTime] = for {
    instant <- instantGen.map(_.atZone(ZoneOffset.UTC).toLocalDateTime)
    offset <- Gen.chooseNum(ZoneOffset.MIN.getTotalSeconds, ZoneOffset.MAX.getTotalSeconds)
      .map(ZoneOffset.ofTotalSeconds)
  } yield OffsetDateTime.of(instant, offset)

  def durationGen: Gen[Duration] = for {
    start <- instantGen
    end <- instantGen
  } yield Duration.between(start, end)
} 
Example 37
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 38
Source File: RLPSpeedSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.rlp

import akka.util.ByteString
import io.iohk.ethereum.ObjectGenerators
import io.iohk.ethereum.domain.Block._
import io.iohk.ethereum.domain._
import io.iohk.ethereum.network.p2p.messages.CommonMessages.SignedTransactions._
import io.iohk.ethereum.network.p2p.messages.PV62.BlockBody
import io.iohk.ethereum.utils.Logger
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.{GeneratorDrivenPropertyChecks, PropertyChecks}
import org.spongycastle.util.encoders.Hex


class RLPSpeedSuite extends FunSuite
    with PropertyChecks
    with GeneratorDrivenPropertyChecks
    with ObjectGenerators
    with Logger {

  val rounds = 10000

  test("Main") {
    val startBlockSerialization: Long = System.currentTimeMillis
    val block = blockGen.sample.get
    val serializedBlock = doTestSerialize[Block](block, (b: Block) => b.toBytes, rounds)
    val elapsedBlockSerialization = (System.currentTimeMillis() - startBlockSerialization) / 1000f
    log.info(s"Block serializations / sec: (${rounds.toFloat / elapsedBlockSerialization})")

    val blockDeserializationStart: Long = System.currentTimeMillis
    val deserializedBlock: Block = doTestDeserialize(serializedBlock, (b: Array[Byte]) => b.toBlock, rounds)
    val elapsedBlockDeserialization = (System.currentTimeMillis() - blockDeserializationStart) / 1000f
    log.info(s"Block deserializations / sec: (${rounds.toFloat / elapsedBlockDeserialization})")

    val serializationTxStart: Long = System.currentTimeMillis
    val tx = validTransaction
    val serializedTx = doTestSerialize(tx, (stx: SignedTransaction) => stx.toBytes, rounds)
    val elapsedTxSerialization = (System.currentTimeMillis() - serializationTxStart) / 1000f
    log.info(s"TX serializations / sec: (${rounds.toFloat / elapsedTxSerialization})")

    val txDeserializationStart: Long = System.currentTimeMillis
    val deserializedTx: SignedTransaction = doTestDeserialize(serializedTx, (b: Array[Byte]) => b.toSignedTransaction, rounds)
    val elapsedTxDeserialization = (System.currentTimeMillis() - txDeserializationStart) / 1000f
    log.info(s"TX deserializations / sec: (${rounds.toFloat / elapsedTxDeserialization})")
  }

  test("Performance decode") {
    val blockRaw: String = "f8cbf8c7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a02f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817da00000000000000000000000000000000000000000000000000000000000000000834000008080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0"
    val payload: Array[Byte] = Hex.decode(blockRaw)
    val ITERATIONS: Int = 10000000
    log.info("Starting " + ITERATIONS + " decoding iterations...")
    val start1: Long = System.currentTimeMillis
    (1 to ITERATIONS).foreach { _ => RLP.rawDecode(payload); Unit }
    val end1: Long = System.currentTimeMillis
    log.info("Result decode()\t: " + (end1 - start1) + "ms")
  }

  def doTestSerialize[T](toSerialize: T, encode: T => Array[Byte], rounds: Int): Array[Byte] = {
    (1 until rounds).foreach(_ => {
      encode(toSerialize)
    })
    encode(toSerialize)
  }

  def doTestDeserialize[T](serialized: Array[Byte], decode: Array[Byte] => T, rounds: Int): T = {
    (1 until rounds).foreach(_ => {
      decode(serialized)
    })
    decode(serialized)
  }

  val validTransaction = SignedTransaction(
    Transaction(
      nonce = 172320,
      gasPrice = BigInt("50000000000"),
      gasLimit = 90000,
      receivingAddress = Address(Hex.decode("1c51bf013add0857c5d9cf2f71a7f15ca93d4816")),
      value = BigInt("1049756850000000000"),
      payload = ByteString.empty),
    pointSign = 28,
    signatureRandom = ByteString(Hex.decode("cfe3ad31d6612f8d787c45f115cc5b43fb22bcc210b62ae71dc7cbf0a6bea8df")),
    signature = ByteString(Hex.decode("57db8998114fae3c337e99dbd8573d4085691880f4576c6c1f6c5bbfe67d6cf0")),
    chainId = 0x3d.toByte
  ).get

  lazy val blockGen: Gen[Block] = for {
    header <- blockHeaderGen
    uncles <- blockHeaderGen
  } yield Block(header = header, BlockBody(transactionList = List.fill(10)(validTransaction), uncleNodesList = Seq(uncles)))
} 
Example 39
Source File: IodbDataSourceIntegrationSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.db

import akka.util.ByteString
import io.iohk.ethereum.db.dataSource.IodbDataSource
import org.scalacheck.Gen
import org.scalatest.FlatSpec

import scala.util.Try

class IodbDataSourceIntegrationSuite extends FlatSpec with DataSourceIntegrationTestBehavior {

  private def createDataSource(path: String) = IodbDataSource(path, KeySize)

  it should behave like dataSource(createDataSource)

  it should "error when insert/update with invalid length" in {
    forAll(seqByteStringOfNItemsGen(KeySizeWithoutPrefix)) { unFilteredKeyList: Seq[ByteString] =>
      withDir { path =>
        val keyList = unFilteredKeyList.take(KeyNumberLimit)
        val keysToInsert = keyList.take(keyList.size/2)
        val db = createDataSource(path).update(OtherNamespace, Seq(), keysToInsert.zip(keysToInsert))

        val invalidKeyList = keyList.map{ key =>
          val suffixOfRandomLength = (0 until Gen.choose(1, MaxIncreaseInLength).sample.get).map(_ => 1.toByte )
          suffixOfRandomLength ++ key
        }

        invalidKeyList.foreach { key => assert( Try{db.update(OtherNamespace, Seq(), Seq(key->key))}.isFailure) }

        db.destroy()
      }
    }
  }

  it should "error get with invalid length" in {
    forAll(seqByteStringOfNItemsGen(KeySizeWithoutPrefix)) { unFilteredKeyList: Seq[ByteString] =>
      withDir { path =>
        val keyList = unFilteredKeyList.take(KeyNumberLimit)
        val db = createDataSource(path).update(OtherNamespace, Seq(), keyList.zip(keyList))

        val invalidKeyList = keyList.map { key =>
          val suffixOfRandomLength = (0 until Gen.choose(1, MaxIncreaseInLength).sample.get).map(_ => 1.toByte)
          suffixOfRandomLength ++ key
        }

        invalidKeyList.foreach { key => assert( Try{db.get(OtherNamespace, key)}.isFailure) }

        db.destroy()
      }
    }
  }
} 
Example 40
Source File: ProgramSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.vm

import org.scalatest.prop.PropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import Generators._
import akka.util.ByteString
import org.scalacheck.Gen

class ProgramSpec extends FlatSpec with Matchers with PropertyChecks {

  val CodeSize = Byte.MaxValue
  val PositionsSize = 10

  val nonPushOp: Byte = JUMP.code
  val invalidOpCode: Byte = 0xef.toByte

  def positionsSetGen: Gen[Set[Int]] = getListGen(minSize = 0, maxSize = PositionsSize, genT = intGen(0, CodeSize)).map(_.toSet)

  it should "detect all jump destinations if there are no push op" in {
    forAll(positionsSetGen) { jumpDestLocations =>
      val code = ByteString((0 to CodeSize).map{ i =>
        if(jumpDestLocations.contains(i)) JUMPDEST.code
        else nonPushOp
      }.toArray)
      val program = Program(code)
      program.validJumpDestinations shouldBe jumpDestLocations
    }
  }

  it should "detect all jump destinations if there are push op" in {
    forAll(positionsSetGen, positionsSetGen) { (jumpDestLocations, pushOpLocations) =>
      val code = ByteString((0 to CodeSize).map{ i =>
        if(jumpDestLocations.contains(i)) JUMPDEST.code
        else if (pushOpLocations.contains(i)) PUSH1.code
        else nonPushOp
      }.toArray)
      val program = Program(code)

      //Removing the PUSH1 that would be used as a parameter of another PUSH1
      //  Example: In "PUSH1 PUSH1 JUMPDEST", the JUMPDEST is a valid jump destination
      val pushOpLocationsNotParameters = (pushOpLocations diff jumpDestLocations).toList.sorted
        .foldLeft(List.empty[Int]){case (recPushOpLocations, i) =>
          if(recPushOpLocations.lastOption.contains(i - 1)) recPushOpLocations else recPushOpLocations :+ i
        }

      val jumpDestLocationsWithoutPushBefore = jumpDestLocations
        .filterNot(i => pushOpLocationsNotParameters.contains(i - 1))
        .filter(i => 0 <= i && i <= CodeSize)
      program.validJumpDestinations shouldBe jumpDestLocationsWithoutPushBefore
    }
  }

  it should "detect all jump destinations if there are invalid ops" in {
    forAll(positionsSetGen, positionsSetGen) { (jumpDestLocations, invalidOpLocations) =>
      val code = ByteString((0 to CodeSize).map{ i =>
        if(jumpDestLocations.contains(i)) JUMPDEST.code
        else if (invalidOpLocations.contains(i)) invalidOpCode
        else nonPushOp
      }.toArray)
      val program = Program(code)
      program.validJumpDestinations shouldBe jumpDestLocations
    }
  }

  it should "detect all instructions as jump destinations if they are" in {
    val code = ByteString((0 to CodeSize).map(_ => JUMPDEST.code).toArray)
    val program = Program(code)
    program.validJumpDestinations shouldBe (0 to CodeSize).toSet
  }
} 
Example 41
Source File: StackSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.vm

import org.scalacheck.Gen
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FunSuite, Matchers}
import io.iohk.ethereum.domain.UInt256

class StackSpec extends FunSuite with Matchers with PropertyChecks {

  val maxStackSize = 32
  val stackGen = Generators.getStackGen(maxSize = maxStackSize)
  val intGen = Gen.choose(0, maxStackSize).filter(_ >= 0)
  val uint256Gen = Generators.getUInt256Gen()
  val uint256ListGen = Generators.getListGen(0, 16, uint256Gen)

  test("pop single element") {
    forAll(stackGen) { stack =>
      val (v, stack1) = stack.pop
      if (stack.size > 0) {
        v shouldEqual stack.toSeq.head
        stack1.toSeq shouldEqual stack.toSeq.tail
      } else {
        v shouldEqual 0
        stack1 shouldEqual stack
      }
    }
  }

  test("pop multiple elements") {
    forAll(stackGen, intGen) { (stack, i) =>
      val (vs, stack1) = stack.pop(i)
      if (stack.size >= i) {
        vs shouldEqual stack.toSeq.take(i)
        stack1.toSeq shouldEqual stack.toSeq.drop(i)
      } else {
        vs shouldEqual Seq.fill(i)(UInt256.Zero)
        stack1 shouldEqual stack
      }
    }
  }

  test("push single element") {
    forAll(stackGen, uint256Gen) { (stack, v) =>
      val stack1 = stack.push(v)

      if (stack.size < stack.maxSize) {
        stack1.toSeq shouldEqual (v +: stack.toSeq)
      } else {
        stack1 shouldEqual stack
      }
    }
  }

  test("push multiple elements") {
    forAll(stackGen, uint256ListGen) { (stack, vs) =>
      val stack1 = stack.push(vs)

      if (stack.size + vs.size <= stack.maxSize) {
        stack1.toSeq shouldEqual (vs.reverse ++ stack.toSeq)
      } else {
        stack1 shouldEqual stack
      }
    }
  }

  test("duplicate element") {
    forAll(stackGen, intGen) { (stack, i) =>
      val stack1 = stack.dup(i)

      if (i < stack.size && stack.size < stack.maxSize) {
        val x = stack.toSeq(i)
        stack1.toSeq shouldEqual (x +: stack.toSeq)
      } else {
        stack1 shouldEqual stack
      }
    }
  }

  test("swap elements") {
    forAll(stackGen, intGen) { (stack, i) =>
      val stack1 = stack.swap(i)

      if (i < stack.size) {
        val x = stack.toSeq.head
        val y = stack.toSeq(i)
        stack1.toSeq shouldEqual stack.toSeq.updated(0, y).updated(i, x)
      } else {
        stack1 shouldEqual stack
      }
    }
  }

} 
Example 42
Source File: EphemDataSourceSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.db.dataSource

import akka.util.ByteString
import io.iohk.ethereum.ObjectGenerators
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class EphemDataSourceSuite extends FunSuite
  with PropertyChecks
  with ObjectGenerators {

  val KeySize: Int = 32
  val KeyNumberLimit: Int = 40
  val OtherNamespace: IndexedSeq[Byte] = IndexedSeq[Byte]('e'.toByte)
  def putMultiple(dataSource: DataSource, toInsert: Seq[(ByteString, ByteString)]): DataSource = {
    toInsert.foldLeft(dataSource){ case (recDB, keyValuePair) =>
      recDB.update(OtherNamespace, Seq(), Seq(keyValuePair))
    }
  }

  def removeMultiple(dataSource: DataSource, toDelete: Seq[ByteString]): DataSource = {
    toDelete.foldLeft(dataSource){ case (recDB, key) =>
      recDB.update(OtherNamespace, Seq(key), Seq())
    }
  }

  test("EphemDataSource insert"){
    forAll(seqByteStringOfNItemsGen(KeySize)) { unFilteredKeyList: Seq[ByteString] =>
      val keyList = unFilteredKeyList.filter(_.length == KeySize)
      val db = putMultiple(dataSource = EphemDataSource(), toInsert = keyList.zip(keyList))
      keyList.foreach { key =>
        val obtained = db.get(OtherNamespace, key)
        assert(obtained.isDefined)
        assert(obtained.get sameElements key)
      }
    }
  }

  test("EphemDataSource delete"){
    forAll(seqByteStringOfNItemsGen(KeySize)) { keyList: Seq[ByteString] =>
      val (keysToDelete, keyValueLeft) = keyList.splitAt(Gen.choose(0, keyList.size).sample.get)

      val dbAfterInsert = putMultiple(dataSource = EphemDataSource(), toInsert = keyList.zip(keyList))
      val db = removeMultiple(dataSource = dbAfterInsert, toDelete = keysToDelete)
      keyValueLeft.foreach { key =>
        val obtained = db.get(OtherNamespace, key)
        assert(obtained.isDefined)
        assert(obtained.get sameElements key)
      }
      keysToDelete.foreach { key => assert(db.get(OtherNamespace, key).isEmpty) }
    }
  }

  test("EphemDataSource clear") {
    forAll(seqByteStringOfNItemsGen(KeySize)) { keyList: Seq[ByteString] =>
      val db = EphemDataSource()
        .update(OtherNamespace, toRemove = Seq(), toUpsert = keyList.zip(keyList))
        .clear

      keyList.foreach { key => assert(db.get(OtherNamespace, key).isEmpty) }
    }
  }
} 
Example 43
Source File: TotalDifficultyStorageSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.db.storage

import io.iohk.ethereum.ObjectGenerators
import io.iohk.ethereum.db.dataSource.EphemDataSource
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class TotalDifficultyStorageSuite extends FunSuite with PropertyChecks with ObjectGenerators {
  test("TotalDifficultyStorage insert") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ blockByteArrayHashes =>
      val blockHashes = blockByteArrayHashes.distinct
      val tdList = Gen.listOf(bigIntGen).sample.get
      val blockHashesTdPair = tdList.zip(blockHashes)

      val initialTotalDifficultyStorage = new TotalDifficultyStorage(EphemDataSource())
      val totalDifficultyStorage = blockHashesTdPair.foldLeft(initialTotalDifficultyStorage){
        case (recTotalDifficultyStorage, (td, blockHash)) =>
          recTotalDifficultyStorage.put(blockHash, td)
      }

      blockHashesTdPair.foreach{case (td, blockHash) => assert(totalDifficultyStorage.get(blockHash).contains(td)) }
    }
  }

  test("TotalDifficultyStorage delete") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ blockByteArrayHashes =>
      val blockHashes = blockByteArrayHashes.distinct
      val tdList = Gen.listOf(bigIntGen).sample.get
      val blockHashesTdPair = tdList.zip(blockHashes)

      //Total difficulty of blocks is inserted
      val initialTotalDifficultyStorage = new TotalDifficultyStorage(EphemDataSource())
      val totalDifficultyStorage = blockHashesTdPair.foldLeft(initialTotalDifficultyStorage){
        case (recTotalDifficultyStorage, (td, blockHash)) =>
          recTotalDifficultyStorage.put(blockHash, td)
      }

      //Total difficulty of blocks is deleted
      val (toDelete, toLeave) = blockHashesTdPair.splitAt(Gen.choose(0, blockHashesTdPair.size).sample.get)
      val totalDifficultyStorageAfterDelete = toDelete.foldLeft(totalDifficultyStorage){
        case (recTotalDifficultyStorage, (_, blockHash)) =>
          recTotalDifficultyStorage.remove(blockHash)
      }

      toLeave.foreach{case (td, blockHeader) => assert(totalDifficultyStorageAfterDelete.get(blockHeader).contains(td)) }
      toDelete.foreach{ case (_, bh) => assert(totalDifficultyStorageAfterDelete.get(bh).isEmpty) }
    }
  }
} 
Example 44
Source File: TransactionMappingStorageSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.db.storage

import io.iohk.ethereum.ObjectGenerators
import io.iohk.ethereum.db.dataSource.EphemDataSource
import io.iohk.ethereum.db.storage.TransactionMappingStorage.TransactionLocation
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class TransactionMappingStorageSuite extends FunSuite with PropertyChecks with ObjectGenerators {
  test("TransactionMappingStorage insert") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ txByteArrayHashes =>
      val txHashes = txByteArrayHashes.distinct
      val blockHashesList = Gen.listOfN(txByteArrayHashes.length, byteStringOfLengthNGen(32)).sample.get
      val txIndexList = Gen.listOfN(txByteArrayHashes.length, intGen).sample.get
      val txLocationList = blockHashesList.zip(txIndexList).map{ case (blockHash, txIndex) =>
        TransactionLocation(blockHash, txIndex) }

      val initialTxMappingStorage = new TransactionMappingStorage(EphemDataSource())
      val txMappingStorage = txHashes.zip(txLocationList).foldLeft(initialTxMappingStorage){
        case (recTxMappingStorage, (txHash, txLocation)) =>
          recTxMappingStorage.put(txHash, txLocation)
      }

      txHashes.zip(txLocationList).foreach{case (txHash, txLocation) => assert(txMappingStorage.get(txHash).contains(txLocation)) }
    }
  }

  test("TransactionMappingStorage delete") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ txByteArrayHashes =>
      val txHashes = txByteArrayHashes.distinct
      val blockHashesList = Gen.listOfN(txByteArrayHashes.length, byteStringOfLengthNGen(32)).sample.get
      val txIndexList = Gen.listOfN(txByteArrayHashes.length, intGen).sample.get
      val txLocationList = blockHashesList.zip(txIndexList).map{ case (blockHash, txIndex) =>
        TransactionLocation(blockHash, txIndex) }
      val txHashAndLocationPair = txHashes.zip(txLocationList)

      //Mapping of tx to blocks is inserted
      val initialTxMappingStorage = new TransactionMappingStorage(EphemDataSource())
      val txMappingStorage = txHashAndLocationPair.foldLeft(initialTxMappingStorage){
        case (recTxMappingStorage, (txHash, txLocation)) =>
          recTxMappingStorage.put(txHash, txLocation)
      }

      //Mapping of tx to blocks is deleted
      val (toDelete, toLeave) = txHashAndLocationPair.splitAt(Gen.choose(0, txHashAndLocationPair.size).sample.get)
      val txMappingStorageAfterDelete = toDelete.foldLeft(txMappingStorage){
        case (recTxMappingStorage, (txHash, _)) =>
          recTxMappingStorage.remove(txHash)
      }

      toLeave.foreach{case (txHash, txLocation) => assert(txMappingStorageAfterDelete.get(txHash).contains(txLocation)) }
      toDelete.foreach{ case (txHash, _) => assert(txMappingStorageAfterDelete.get(txHash).isEmpty) }
    }
  }
} 
Example 45
Source File: CodeStorageSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.db.storage

import akka.util.ByteString
import io.iohk.ethereum.ObjectGenerators
import io.iohk.ethereum.db.dataSource.EphemDataSource
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class CodeStorageSuite extends FunSuite with PropertyChecks with ObjectGenerators {
  val LimitCodeSize = 100

  test("CodeStorage insert") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ unfilteredCodeHashes =>
      val codeHashes = unfilteredCodeHashes.distinct
      val codes = Gen.listOfN(codeHashes.length, randomSizeByteArrayGen(0, LimitCodeSize)).sample.get.map(ByteString(_))
      val initialCodeStorage = new EvmCodeStorage(EphemDataSource())
      val codeStorage = codeHashes.zip(codes).foldLeft(initialCodeStorage){
        case (recCodeStorage, (codeHash, code)) =>
          recCodeStorage.put(codeHash, code)
      }

      codeHashes.zip(codes).foreach{ case (codeHash, code) =>
        assert(codeStorage.get(codeHash).contains(code))
      }
    }
  }

  test("CodeStorage delete") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ unfilteredCodeHashes =>
      val codeHashes = unfilteredCodeHashes.distinct
      val codes = Gen.listOfN(codeHashes.length, randomSizeByteArrayGen(0, LimitCodeSize)).sample.get.map(ByteString(_))

      //EVM codes are inserted
      val initialCodeStorage = new EvmCodeStorage(EphemDataSource())
      val codeStorage = codeHashes.zip(codes).foldLeft(initialCodeStorage){
        case (recCodeStorage, (codeHash, code)) =>
          recCodeStorage.put(codeHash, code)
      }

      //EVM codes are deleted
      val (toDelete, toLeave) = codeHashes.zip(codes)
        .splitAt(Gen.choose(0, codeHashes.size).sample.get)
      val codeStorageAfterDelete = toDelete.foldLeft(codeStorage){
        case (recCodeStorage, (codeHash, _)) =>
          recCodeStorage.remove(codeHash)
      }

      toLeave.foreach{ case (codeHash, code) => assert(codeStorageAfterDelete.get(codeHash).contains(code)) }
      toDelete.foreach{ case (codeHash, _) => assert(codeStorageAfterDelete.get(codeHash).isEmpty) }
    }
  }
} 
Example 46
Source File: NodeStorageSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.db.storage

import akka.util.ByteString
import io.iohk.ethereum.ObjectGenerators
import io.iohk.ethereum.db.dataSource.EphemDataSource
import io.iohk.ethereum.network.p2p.messages.PV63.MptNodeEncoders._
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class NodeStorageSuite extends FunSuite with PropertyChecks with ObjectGenerators {
  test("NodeStorage insert") {
    forAll(Gen.listOf(nodeGen)){ unfilteredMptNodes =>
      val mptNodes = unfilteredMptNodes.distinct
      val initialNodeStorage: NodeStorage = new NodeStorage(EphemDataSource())
      val nodeStorage = mptNodes.foldLeft(initialNodeStorage){
        case (recNodeStorage, node) =>
          recNodeStorage.update(Nil, Seq(ByteString(node.hash) -> node.toBytes))
      }

      mptNodes.foreach{ node =>
        val obtainedNode = nodeStorage.get(ByteString(node.hash)).map(_.toMptNode)
        assert(obtainedNode.contains(node))
      }
    }
  }

  test("NodeStorage delete") {
    forAll(Gen.listOf(nodeGen)){ unfilteredMptNodes =>
      val mptNodes = unfilteredMptNodes.distinct

      //Nodes are inserted
      val initialNodeStorage: NodeStorage = new NodeStorage(EphemDataSource())
      val nodeStorage = mptNodes.foldLeft(initialNodeStorage){
        case (recNodeStorage, node) =>
          recNodeStorage.update(Nil, Seq(ByteString(node.hash) -> node.toBytes))
      }

      //Nodes are deleted
      val (toDelete, toLeave) = mptNodes.splitAt(Gen.choose(0, mptNodes.size).sample.get)
      val nodeStorageAfterDelete = toDelete.foldLeft(nodeStorage){
        case (recNodeStorage, node) =>
          recNodeStorage.update(Seq(ByteString(node.hash)), Nil)
      }

      toLeave.foreach{ node =>
        val obtainedNode = nodeStorageAfterDelete.get(ByteString(node.hash)).map(_.toMptNode)
        assert(obtainedNode.contains(node)) }
      toDelete.foreach{ node => assert(nodeStorageAfterDelete.get(ByteString(node.hash)).isEmpty) }
    }
  }
} 
Example 47
Source File: ReceiptStorageSuite.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.db.storage

import io.iohk.ethereum.ObjectGenerators
import io.iohk.ethereum.db.dataSource.EphemDataSource
import io.iohk.ethereum.domain.Receipt
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class ReceiptStorageSuite extends FunSuite with PropertyChecks with ObjectGenerators {

  test("ReceiptStorage insert") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ blockByteArrayHashes =>
      val blockHashes = blockByteArrayHashes.distinct
      val receipts = receiptsGen(blockHashes.length).sample.get
      val blockHashesReceiptsPair = receipts.zip(blockHashes)

      val initialReceiptStorage = new ReceiptStorage(EphemDataSource())
      val receiptStorage = blockHashesReceiptsPair.foldLeft(initialReceiptStorage){
        case (recReceiptStorage, (receiptList, blockHash)) =>
          recReceiptStorage.put(blockHash, receiptList)
      }

      blockHashesReceiptsPair.foreach{case (rs, bh) =>
        val obtainedReceipts: Option[Seq[Receipt]] = receiptStorage.get(bh)
        assert(obtainedReceipts.contains(rs))
      }
    }
  }

  test("ReceiptStorage delete") {
    forAll(Gen.listOf(byteStringOfLengthNGen(32))){ blockByteArrayHashes =>
      val blockHashes = blockByteArrayHashes.distinct
      val receipts = receiptsGen(blockHashes.length).sample.get
      val blockHashesReceiptsPair = receipts.zip(blockHashes)

      //Receipts are inserted
      val initialReceiptStorage = new ReceiptStorage(EphemDataSource())
      val receiptStorage = blockHashesReceiptsPair.foldLeft(initialReceiptStorage){
        case (recReceiptStorage, (receiptList, blockHash)) =>
          recReceiptStorage.put(blockHash, receiptList)
      }

      //Receipts are deleted
      val (toDelete, toLeave) = blockHashesReceiptsPair.splitAt(Gen.choose(0, blockHashesReceiptsPair.size).sample.get)
      val receiptStorageAfterDelete = toDelete.foldLeft(receiptStorage){
        case (recReceiptStorage, (_, blockHash)) =>
          recReceiptStorage.remove(blockHash)
      }

      toLeave.foreach{case (rs, bh) =>
        val obtainedReceipts = receiptStorageAfterDelete.get(bh)
        assert(obtainedReceipts.contains(rs))
      }
      toDelete.foreach{ case (_, bh) => assert(receiptStorageAfterDelete.get(bh).isEmpty) }
    }
  }
} 
Example 48
Source File: OrderGenerator.scala    From akka-serialization-test   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.generator

import com.github.dnvriend.domain.OrderDomain._
import org.scalacheck.Gen

object OrderGenerator {

  val genItemType = Gen.oneOf(ItemType.CD, ItemType.DVD, ItemType.BluRay, ItemType.Game)

  val genItem = for {
    itemType ← genItemType
    title ← Gen.alphaStr
    price ← Gen.choose(2.50, 60.0)
    id ← Gen.option(Gen.uuid)
  } yield Item(itemType, title, price, id.map(_.toString))

  val genItems = Gen.listOf(genItem)

  val genAddress = for {
    zipcode ← Gen.alphaStr
    houseNumber ← Gen.choose(1, 200)
  } yield Address(zipcode, houseNumber)

  val dateGen = Gen.const(System.currentTimeMillis())

  val genOrder = for {
    name ← Gen.alphaStr
    address ← genAddress
    items ← genItems
    date ← dateGen
  } yield Order(name, address, items, date, None)

  def orders: List[Order] = Gen.listOf(genOrder).sample.getOrElse(Nil)
} 
Example 49
Source File: ContactsArbitrary.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.daos.arbitraries

import com.dataengi.crm.contacts.controllers.data._
import com.dataengi.crm.contacts.models.{ContactFieldTypes, ContactTypes, Group}
import com.dataengi.crm.common.arbitraries.CommonArbitrary
import com.dataengi.crm.contacts.models.ContactFieldTypes.ContactFieldType
import com.dataengi.crm.contacts.models.ContactTypes.ContactType
import org.scalacheck.{Arbitrary, Gen}

trait ContactsArbitrary extends CommonArbitrary {

  val groupArbitrary: Arbitrary[Group]                              = Arbitrary(Gen.resultOf(Group))
  implicit val createGroupDataArbitrary: Arbitrary[CreateGroupData] = Arbitrary(Gen.resultOf(CreateGroupData))

  implicit val contactTypeArbitrary: Arbitrary[ContactType] = Arbitrary(Gen.oneOf(ContactTypes.values.toList))
  implicit val contactFieldTypeArbitrary: Arbitrary[ContactFieldType] = Arbitrary(
    Gen.oneOf(ContactFieldTypes.values.toList))
  implicit val addressDataArbitrary: Arbitrary[AddressData]         = Arbitrary(Gen.resultOf(AddressData))
  implicit val emailDataArbitrary: Arbitrary[EmailData]             = Arbitrary(Gen.resultOf(EmailData))
  implicit val phoneDataArbitrary: Arbitrary[PhoneData]             = Arbitrary(Gen.resultOf(PhoneData))
  implicit val createContactArbitrary: Arbitrary[CreateContactData] = Arbitrary(Gen.resultOf(CreateContactData))
  implicit val updateContactArbitrary: Arbitrary[UpdateContactData] = Arbitrary(Gen.resultOf(UpdateContactData))

} 
Example 50
Source File: GroupsServiceSpec.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.services

import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.extensions.awaits._
import com.dataengi.crm.contacts.controllers.data.{AddContactsToGroupData, CreateGroupData}
import com.dataengi.crm.contacts.models.Group
import com.dataengi.crm.contacts.services.errors.GroupsServiceErrors
import com.dataengi.crm.contacts.context.GroupsServiceContext
import org.scalacheck.Gen
import org.specs2.runner.SpecificationsFinder
import play.api.test.PlaySpecification

class GroupsServiceSpec extends PlaySpecification with GroupsServiceContext {

  sequential

  "GroupsService" should {

    "create group" in {
      val createContactsBook = contactsBooksService.create(rootUser.id.get).await()
      createContactsBook.isRight === true
      val contactsBook      = createContactsBook.value
      val createGroupData   = createGroupDataArbitrary.arbitrary.sample.get.copy(contactsBookId = contactsBook.id.get)
      val createGroupResult = groupsService.create(createGroupData).await()
      createGroupResult.isRight === true
      val getGroupResult = groupsService.get(createGroupResult.value.id.get).await()
      getGroupResult.isRight === true
      getGroupResult.value.name === createGroupData.name
    }

    "get all groups in contacts book" in {
      val createContactsBook = contactsBooksService.findByOwner(rootUser.id.get).await()
      createContactsBook.isRight === true
      val contactsBook       = createContactsBook.value
      val createContactsData = createGroupDataArbitrary.arbitrary.sample.get
      val createGroupInContactsBookResult =
        groupsService.create(createContactsData.copy(contactsBookId = contactsBook.id.get)).await()
      createGroupInContactsBookResult.isRight === true
      val allContactsInContactsBookResult = groupsService.findAllInContactsBook(contactsBook.id.get).await()
      allContactsInContactsBookResult.isRight === true
      allContactsInContactsBookResult.value.nonEmpty === true
    }

    "add contacts to group" in {
      val group              = createGroup(TestGroupName)
      val createContactsData = Gen.listOfN(5, createContactArbitrary.arbitrary.sample).sample.get.flatten
      val createContactsResult =
        createContactsData.traverseC(data => contactsService.create(data, rootUser.id.get)).await()
      createContactsResult.isRight === true
      val addToGropResult =
        contactsService
          .addGroup(AddContactsToGroupData(groupId = group.id.get, contactIds = createContactsResult.value.map(_.id.get)))
          .await()
      addToGropResult.isRight === true
    }

    "find group by name" in {
      val getTestGroup = groupsService.find(TestGroupName).toOrWithLeft(GroupsServiceErrors.GroupNotFoundError).await()
      getTestGroup.isRight === true
    }

    "get group members" in {
      val getTestGroup = groupsService.find(TestGroupName).toOrWithLeft(GroupsServiceErrors.GroupNotFoundError).await()
      getTestGroup.isRight === true
      val groupId            = getTestGroup.value.id.get
      val groupMembersResult = contactsService.getGroupMembers(groupId).await()
      groupMembersResult.isRight === true
      groupMembersResult.value.size === 5
    }

  }

  def createGroup(name: String): Group = {
    val createContactsBook = contactsBooksService.create(rootUser.id.get).await()
    createContactsBook.isRight === true
    val contactsBook      = createContactsBook.value
    val createGroupData   = CreateGroupData(name, contactsBookId = contactsBook.id.get)
    val createGroupResult = groupsService.create(createGroupData).await()
    createGroupResult.isRight === true
    createGroupResult.value
  }

} 
Example 51
Source File: AuthenticationContext.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.context

import com.dataengi.crm.common.context.CRMApplication
import com.dataengi.crm.configurations.{RolesConfiguration, RootConfiguration}
import com.dataengi.crm.identities.errors.UsersServiceErrors
import com.dataengi.crm.contacts.generators.EmailGen
import org.scalacheck.Gen
import play.api.mvc.AnyContentAsEmpty
import play.api.test.FakeRequest
import com.dataengi.crm.contacts.services._
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.extensions.awaits._
import com.dataengi.crm.identities.arbitraries.IdentitiesArbitrary
import com.dataengi.crm.identities.controllers.data._
import com.dataengi.crm.identities.models.User
import com.dataengi.crm.identities.services._

trait AuthenticationContext extends CRMApplication with IdentitiesArbitrary {

  lazy val authenticationService = application.injector.instanceOf[AuthenticationService]
  lazy val invitesService        = application.injector.instanceOf[InvitesService]
  lazy val rolesService          = application.injector.instanceOf[RolesService]
  lazy val companiesService      = application.injector.instanceOf[CompaniesService]
  lazy val usersService          = application.injector.instanceOf[UsersService]
  lazy val rootConfiguration     = application.injector.instanceOf[RootConfiguration]
  lazy val rolesConfiguration    = application.injector.instanceOf[RolesConfiguration]

  lazy val rootSignInData =
    SignInData(rootConfiguration.rootLoginInfo.providerKey, rootConfiguration.rootPassword)

  lazy val TestCompanyName = "TEST_COMPANY" + Gen.alphaStr.sample.get

  lazy val userEmail             = EmailGen.randomEmailsGenerator.sample.getOrElse("[email protected]")
  lazy val userPassword          = "test_password"
  lazy val userSignInData        = SignInData(userEmail, userPassword)
  lazy val userSignUpData        = SignUpData(userPassword)
  lazy val forgotPassword        = ForgotPassword(userEmail)
  lazy val userLocalhost         = "localhost"
  lazy val newPassword: String   = "new_password"
  lazy val recoverPassword       = RecoverPasswordData(newPassword)
  lazy val userChangedSignInData = SignInData(userEmail, newPassword)
  lazy val rootUser: User = {
    usersService
      .findByEmail(rootConfiguration.rootLoginInfo.providerKey)
      .toOrWithLeft(UsersServiceErrors.IdentityNotFound)
      .await()
      .value
  }

  implicit val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest()

  def inviteData(testCompanyId: Long, salesRepresentativeRoleId: Long): InviteData = InviteData(
    email = userEmail,
    companyId = testCompanyId,
    roleId = salesRepresentativeRoleId
  )

} 
Example 52
Source File: IdentitiesArbitrary.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.arbitraries

import java.util.UUID
import java.util.concurrent.TimeUnit

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.authenticators.JWTAuthenticator
import com.dataengi.crm.common.arbitraries.CommonArbitrary
import com.dataengi.crm.identities.models.Actions.Action
import com.dataengi.crm.identities.models.InviteStatuses.InviteStatus
import com.dataengi.crm.identities.models._
import com.dataengi.crm.identities.models.PermissionStates.PermissionState
import com.mohiva.play.silhouette.api.util.PasswordInfo
import org.joda.time.DateTime
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

import scala.concurrent.duration.FiniteDuration

trait IdentitiesArbitrary extends CommonArbitrary {

  lazy val companyArbitrary: Arbitrary[Company] = Arbitrary(Gen.resultOf(Company))

  implicit val actionArbitrary: Arbitrary[Action]                   = Arbitrary(Gen.oneOf(Actions.values.toList))
  implicit val permissionStateArbitrary: Arbitrary[PermissionState] = Arbitrary(Gen.oneOf(PermissionStates.values.toList))
  implicit val permissionArbitrary: Arbitrary[Permission]           = Arbitrary(Gen.resultOf(Permission))
  implicit val roleArbitrary: Arbitrary[Role]                       = Arbitrary(Gen.resultOf(Role))
  implicit val inviteStatusArbitrary: Arbitrary[InviteStatus]       = Arbitrary(Gen.oneOf(InviteStatuses.values.toList))
  implicit val uuidArbitrary: Arbitrary[UUID]                       = Arbitrary(Gen.uuid)
  implicit val inviteArbitrary: Arbitrary[Invite]                   = Arbitrary(Gen.resultOf(Invite))

  val dateTimeGen = for {
    value <- Gen.Choose.chooseLong.choose(0, Long.MaxValue)
  } yield new DateTime(value)

  val finiteDurationGen = for {
    value <- Gen.Choose.chooseLong.choose(0, Long.MaxValue)
  } yield new FiniteDuration(value, TimeUnit.NANOSECONDS)

  val jsObject = Gen.oneOf(List(Some(Json.obj("a" -> "b")), None))

  implicit val jsObjectArbitrary       = Arbitrary(jsObject)
  implicit val dateTimeArbitrary       = Arbitrary(dateTimeGen)
  implicit val finiteDurationArbitrary = Arbitrary(finiteDurationGen)
  implicit val loginInfoArbitrary      = Arbitrary(Gen.resultOf(LoginInfo))
  implicit val authenticatorArbitrary  = Arbitrary(Gen.resultOf(JWTAuthenticator.apply _))
  implicit val passwordInfoArbitrary   = Arbitrary(Gen.resultOf(PasswordInfo))
} 
Example 53
Source File: EnumModuleCompanionTest.scala    From jvm-toxcore-api   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.core.typesafe

import im.tox.core.ModuleCompanionTest
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen

@SuppressWarnings(Array("org.wartremover.warts.Equals"))
abstract class EnumModuleCompanionTest[T, S <: Security](module: EnumModuleCompanion[T, S]) extends ModuleCompanionTest(module) {

  test("non-empty enum values") {
    assert(module.values.nonEmpty)
  }

  test("distinct ordinals") {
    val ordinals = module.values.toSeq.map(module.ordinal)
    assert(ordinals == ordinals.distinct)
  }

} 
Example 54
Source File: BoundedIntCompanionTest.scala    From jvm-toxcore-api   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.core.typesafe

import org.scalacheck.Gen

abstract class BoundedIntCompanionTest[T <: AnyVal](module: BoundedIntCompanion[T]) extends IntCompanionTest(module) {

  override protected final def genValidInt = Gen.choose(module.MinValue, module.MaxValue)
  override protected final def genInvalidInt = {
    val tooSmallGen = if (module.MinValue > Int.MinValue) {
      Some(Gen.choose(Int.MinValue, module.MinValue - 1))
    } else {
      None
    }
    val tooLargeGen = if (module.MaxValue < Int.MaxValue) {
      Some(Gen.choose(module.MaxValue + 1, Int.MaxValue))
    } else {
      None
    }

    tooSmallGen.toList ++ tooLargeGen.toList match {
      case Nil                  => fail(s"$module is a bounded int companion but sets no bounds")
      case List(gen)            => gen
      case gen1 :: gen2 :: tail => Gen.oneOf(gen1, gen2, tail: _*)
    }
  }

} 
Example 55
Source File: IntCompanionTest.scala    From jvm-toxcore-api   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.core.typesafe

import im.tox.core.ModuleCompanionTest
import org.scalacheck.{ Arbitrary, Gen }

@SuppressWarnings(Array("org.wartremover.warts.Equals"))
abstract class IntCompanionTest[T <: AnyVal](module: IntCompanion[T]) extends ModuleCompanionTest(module) {

  protected def genValidInt: Gen[Int]
  protected def genInvalidInt: Gen[Int]

  test("fromInt (valid)") {
    forAll(genValidInt) { (int: Int) =>
      assert(module.fromInt(int).isDefined)
    }
  }

  test("fromInt (invalid)") {
    forAll(genInvalidInt) { (int: Int) =>
      assert(module.fromInt(int).isEmpty)
    }
  }

  test("toInt") {
    forAll(genValidInt) { (int: Int) =>
      assert(module.toInt(module.fromInt(int).get) == int)
    }
  }

} 
Example 56
Source File: KeyCompanionTest.scala    From jvm-toxcore-api   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.core.typesafe

import org.scalacheck.{ Arbitrary, Gen }

@SuppressWarnings(Array("org.wartremover.warts.Equals"))
abstract class KeyCompanionTest[T <: AnyVal, S <: Security](
    companion: KeyCompanion[T, S]
)(implicit final val arbT: Arbitrary[T]) extends FixedSizeByteArrayCompanionTest(companion) {

  test("fromHexString") {
    forAll(Gen.containerOfN[Array, Char](
      companion.Size * 2,
      Gen.oneOf(
        Gen.choose('0', '9'),
        Gen.choose('a', 'f'),
        Gen.choose('A', 'F')
      )
    ).map(new String(_))) { string =>
      companion.fromHexString(string).toOption.get
    }
  }

  test("toString") {
    forAll { (self: T) =>
      assert(companion.equals(companion.fromHexString(self.toString).toOption.get, self))
    }
  }

  test("toHexString") {
    forAll { (self: T) =>
      assert(companion.equals(companion.fromHexString(companion.toHexString(self)).toOption.get, self))
    }
  }

  test("optimised toHexString") {
    forAll { (self: T) =>
      assert(companion.toHexStringOpt(self) == companion.toHexStringRef(self))
    }
  }

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

import eu.timepit.refined.api.RefType
import eu.timepit.refined.boolean.Or
import org.scalacheck.{Arbitrary, Gen}


object boolean extends BooleanInstances

trait BooleanInstances {

  implicit def orArbitrary[F[_, _], T, A, B](
      implicit rt: RefType[F],
      arbA: Arbitrary[F[T, A]],
      arbB: Arbitrary[F[T, B]]
  ): Arbitrary[F[T, A Or B]] = {
    val genA = arbA.arbitrary.map(rt.unwrap)
    val genB = arbB.arbitrary.map(rt.unwrap)
    arbitraryRefType(Gen.oneOf(genA, genB))
  }
} 
Example 58
Source File: reftype.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

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

object reftype extends RefTypeInstances

trait RefTypeInstances {

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

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

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

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

import eu.timepit.refined.api.{Refined, RefType}
import eu.timepit.refined.collection.{NonEmpty, Size}
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.util.Buildable


object collection extends CollectionInstances with CollectionInstancesBinCompat1

trait CollectionInstances {

  implicit def listSizeArbitrary[F[_, _]: RefType, T: Arbitrary, P](
      implicit arbSize: Arbitrary[Int Refined P]
  ): Arbitrary[F[List[T], Size[P]]] =
    buildableSizeArbitrary[F, List[T], T, P]

  implicit def vectorSizeArbitrary[F[_, _]: RefType, T: Arbitrary, P](
      implicit arbSize: Arbitrary[Int Refined P]
  ): Arbitrary[F[Vector[T], Size[P]]] =
    buildableSizeArbitrary[F, Vector[T], T, P]

  // This is private and not implicit because it could produce invalid
  // values for some collections:
  //
  // scala> buildableSizeArbitrary[Refined, Set[Boolean], Boolean, Equal[3]].arbitrary.sample
  // res0: Option[Refined[Set[Boolean], Size[Equal[3]]]] = Some(Set(false, true))
  private[scalacheck] def buildableSizeArbitrary[F[_, _]: RefType, C, T, P](
      implicit
      arbT: Arbitrary[T],
      arbSize: Arbitrary[Int Refined P],
      ev1: Buildable[T, C],
      ev2: C => Traversable[T]
  ): Arbitrary[F[C, Size[P]]] =
    arbitraryRefType(arbSize.arbitrary.flatMap { n =>
      Gen.buildableOfN[C, T](n.value, arbT.arbitrary)
    })
}

trait CollectionInstancesBinCompat1 {

  implicit def listNonEmptyArbitrary[F[_, _]: RefType, T: Arbitrary]
      : Arbitrary[F[List[T], NonEmpty]] =
    buildableNonEmptyArbitrary[F, List[T], T]

  implicit def vectorNonEmptyArbitrary[F[_, _]: RefType, T: Arbitrary]
      : Arbitrary[F[Vector[T], NonEmpty]] =
    buildableNonEmptyArbitrary[F, Vector[T], T]

  private[scalacheck] def buildableNonEmptyArbitrary[F[_, _]: RefType, C, T](
      implicit
      arbT: Arbitrary[T],
      ev1: Buildable[T, C],
      ev2: C => Traversable[T]
  ): Arbitrary[F[C, NonEmpty]] =
    arbitraryRefType(Gen.nonEmptyBuildableOf(arbT.arbitrary))
} 
Example 60
Source File: ToGen.scala    From xenomorph   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package xenomorph.scalacheck

import org.scalacheck.Gen

import scalaz.~>
import scalaz.Applicative
import scalaz.FreeAp
import scalaz.syntax.std.option._

import xenomorph._
import xenomorph.Schema._
import xenomorph.HFunctor._

trait ToGen[S[_]] {
  def toGen: S ~> Gen
}

object ToGen {
  implicit class ToGenOps[S[_], A](s: S[A]) {
    def toGen(implicit TG: ToGen[S]): Gen[A] = TG.toGen(s)
  }

  implicit def schemaToGen[P[_]: ToGen]: ToGen[Schema[P, ?]] = new ToGen[Schema[P, ?]] {
    def toGen = new (Schema[P, ?] ~> Gen) {
      override def apply[I](schema: Schema[P, I]) = {
        HFix.cataNT[SchemaF[P, ?[_], ?], Gen](genAlg).apply(schema)
      }
    }
  }

  def genAlg[P[_]: ToGen]: HAlgebra[SchemaF[P, ?[_], ?], Gen] =
    new HAlgebra[SchemaF[P, ?[_], ?], Gen] {
      def apply[I](schema: SchemaF[P, Gen, I]): Gen[I] = schema match {
        case s: PrimSchema[P, Gen, I] => implicitly[ToGen[P]].toGen(s.prim)
        case s: OneOfSchema[P, Gen, I] =>
          val altGens = s.alts.map({ case Alt(_, b, p) => b.map(p.reverseGet) })
          altGens.tail.headOption.cata(
            th => Gen.oneOf(altGens.head, th, altGens.tail.toList.tail: _*),
            altGens.head
          )

        case s: RecordSchema[P, Gen, I] => recordGen[P,I](s.props)
        case s: IsoSchema[P, Gen, i0, I] => s.base.map(s.iso.get(_))
      }
    }

  def recordGen[P[_]: ToGen, I](rb: FreeAp[PropSchema[I, Gen, ?], I]): Gen[I] = {
    implicit val djap: Applicative[Gen] = new Applicative[Gen] {
      def point[T](a: => T) = Gen.const(a)
      def ap[T, U](fa: => Gen[T])(ff: => Gen[T => U]): Gen[U] = {
        fa.flatMap(a => ff.map(_(a)))
      }
    }

    rb.foldMap(
      new (PropSchema[I, Gen, ?] ~> Gen) {
        def apply[B](ps: PropSchema[I, Gen, B]): Gen[B] = ps match {
          case Required(_, base, _, _) => base
          case opt: Optional[I, Gen, i] => Gen.option(opt.base)
        }
      }
    )
  }
} 
Example 61
Source File: Implicits.scala    From xenomorph   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package xenomorph.scalacheck

import xenomorph.Schema.Schema
import xenomorph.json.JType.JSchema
import xenomorph.json._

import scalaz.~>

object Implicits {

  implicit val toGen: ToGen[JSchema] = new ToGen[JSchema] { self =>
    import org.scalacheck.Arbitrary._
    import org.scalacheck.Gen
    import org.scalacheck.Gen._
    def toGen = new (JSchema ~> Gen) {
      def apply[A](s: JSchema[A]): Gen[A] = s.unmutu match {
        case JNullT()   => arbitrary[Unit]
        case JBoolT()   => arbitrary[Boolean]
        case JByteT()   => arbitrary[Byte]
        case JShortT()  => arbitrary[Short]
        case JIntT()    => arbitrary[Int]
        case JLongT()   => Gen.chooseNum(Long.MinValue + 808L, Long.MaxValue) // Magic number to circumvent Instant#toEpochMillis throwing exceptions
        case JFloatT()  => arbitrary[Float]
        case JDoubleT() => arbitrary[Double]
        case JCharT()   => arbitrary[Char]
        case JStrT()    => arbitrary[String]
        case arr: JArrayT[Schema[JSchema, ?], i] =>
          val baseDecoder: Gen[i] = ToGen.schemaToGen[JSchema](self).toGen(arr.elem)
          containerOf[Vector, i](baseDecoder)
      }
    }
  }

} 
Example 62
Source File: SnapshotStateSpecification.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.actors

import com.wavesplatform.dex.NoShrink
import com.wavesplatform.dex.domain.asset.Asset.IssuedAsset
import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.domain.bytes.ByteStr
import org.scalacheck.Gen
import org.scalatest.matchers.should.Matchers
import org.scalatest.propspec.AnyPropSpecLike
import org.scalatestplus.scalacheck.{ScalaCheckDrivenPropertyChecks => DrivenPropertyChecks}

class SnapshotStateSpecification extends AnyPropSpecLike with DrivenPropertyChecks with Matchers with NoShrink {
  property("nextSnapshotOffset generates greater offsets than old and last processed") {
    val assetPair = AssetPair(
      IssuedAsset(ByteStr("asset1".getBytes())),
      IssuedAsset(ByteStr("asset2".getBytes()))
    )

    val g = for {
      interval            <- Gen.choose(1, 1000L).label("interval")
      currSnapshotOffset  <- Gen.choose(-1, 1000L).label("currSnapshotOffset")
      lastProcessedOffset <- Gen.choose(-1, 1000L).label("lastProcessedOffset")
    } yield (currSnapshotOffset, lastProcessedOffset, interval)

    forAll(g) {
      case (currSnapshotOffset, lastProcessedOffset, interval) =>
        val nextOffset = SnapshotsState.nextSnapshotOffset(assetPair, currSnapshotOffset, lastProcessedOffset, interval)
        nextOffset should be > currSnapshotOffset
        nextOffset should be > lastProcessedOffset
    }
  }
} 
Example 63
Source File: OrderInfoSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.model

import com.wavesplatform.dex.domain.order.Order
import com.wavesplatform.dex.model.OrderInfoSpec.OrderExt
import com.wavesplatform.dex.{MatcherSpecBase, NoShrink}
import org.scalacheck.Gen
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class OrderInfoSpec extends AnyFreeSpec with Matchers with MatcherSpecBase with PropertyChecks with NoShrink {

  private def finalizedOrderInfoGen(o: Order, orderInfoVersion: Byte): Gen[OrderInfo[OrderStatus.Final]] =
    for {
      filledAmount    <- Gen.choose(0, o.amount)
      filledFee       <- if (orderInfoVersion == 1) Gen.const((BigInt(filledAmount) * 300000 / o.amount).toLong) else Gen.choose(0, o.matcherFee)
      status          <- Gen.oneOf(OrderStatus.Filled(filledAmount, filledFee), OrderStatus.Cancelled(filledAmount, filledFee))
      aoType          <- if (orderInfoVersion <= 2) Gen.const(AcceptedOrderType.Limit) else Gen.oneOf(AcceptedOrderType.Limit, AcceptedOrderType.Market)
      avgWeighedPrice <- if (orderInfoVersion <= 3) Gen.const(o.price) else Gen.choose(0, o.price)
    } yield o.toInfo(orderInfoVersion, status, aoType, avgWeighedPrice)

  private val finalizedOrderInfoGen: Gen[OrderInfo[OrderStatus.Final]] = for {
    (o, _) <- orderGenerator
    v      <- Gen.choose[Byte](1, 4)
    result <- finalizedOrderInfoGen(o, v)
  } yield result

  "OrderInfo" - {
    "x == decode(encode(x))" in forAll(finalizedOrderInfoGen) { oi =>
      OrderInfo.decode(OrderInfo encode oi) == oi
    }
  }
}

object OrderInfoSpec {

  implicit class OrderExt(val o: Order) extends AnyVal {
    def toInfo[A <: OrderStatus](version: Byte, status: A, aoType: AcceptedOrderType, avgWeighedPrice: Long): OrderInfo[A] = version match {
      case 1 => OrderInfo.v1[A](o.orderType, o.amount, o.price, o.timestamp, status, o.assetPair)
      case 2 => OrderInfo.v2[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair)
      case 3 => OrderInfo.v3[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair, aoType)
      case 4 => OrderInfo.v4[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair, aoType, avgWeighedPrice)
      case 5 =>
        OrderInfo
          .v5[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair, aoType, avgWeighedPrice, o.version)
    }
  }
} 
Example 64
Source File: ExchangeTransactionCreatorSpecification.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.model

import com.wavesplatform.dex.domain.asset.Asset
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.crypto
import com.wavesplatform.dex.domain.crypto.Proofs
import com.wavesplatform.dex.domain.order.Order
import com.wavesplatform.dex.domain.order.OrderOps._
import com.wavesplatform.dex.domain.transaction.ExchangeTransactionV2
import com.wavesplatform.dex.domain.utils.EitherExt2
import com.wavesplatform.dex.{MatcherSpecBase, NoShrink}
import org.scalacheck.Gen
import org.scalamock.scalatest.PathMockFactory
import org.scalatest.matchers.should.Matchers
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.{Assertion, BeforeAndAfterAll}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

import scala.concurrent.ExecutionContext.Implicits.global

class ExchangeTransactionCreatorSpecification
    extends AnyWordSpec
    with Matchers
    with MatcherSpecBase
    with BeforeAndAfterAll
    with PathMockFactory
    with PropertyChecks
    with NoShrink
    with TableDrivenPropertyChecks {

  private def getExchangeTransactionCreator(hasMatcherScript: Boolean = false,
                                            hasAssetScripts: Asset => Boolean = _ => false): ExchangeTransactionCreator = {
    new ExchangeTransactionCreator(MatcherAccount, matcherSettings.exchangeTxBaseFee, hasMatcherScript, hasAssetScripts)
  }

  "ExchangeTransactionCreator" should {
    "create an ExchangeTransactionV2" when {
      (List(1, 2, 3) ++ List(1, 2, 3)).combinations(2).foreach {
        case List(counterVersion, submittedVersion) =>
          s"counterVersion=$counterVersion, submittedVersion=$submittedVersion" in {
            val counter   = buy(wavesBtcPair, 100000, 0.0008, matcherFee = Some(2000L), version = counterVersion.toByte)
            val submitted = sell(wavesBtcPair, 100000, 0.0007, matcherFee = Some(1000L), version = submittedVersion.toByte)

            val tc = getExchangeTransactionCreator()
            val oe = mkOrderExecutedRaw(submitted, counter)

            tc.createTransaction(oe).explicitGet() shouldBe a[ExchangeTransactionV2]
          }
      }
    }

    "take fee from order executed event" when {
      "orders are matched fully" in {
        val preconditions = for { ((_, buyOrder), (_, sellOrder)) <- orderV3MirrorPairGenerator } yield (buyOrder, sellOrder)
        test(preconditions)
      }

      "orders are matched partially" in {
        val preconditions = for { ((_, buyOrder), (senderSell, sellOrder)) <- orderV3MirrorPairGenerator } yield {
          val sellOrderWithUpdatedAmount = sellOrder.updateAmount(sellOrder.amount / 2)
          val newSignature               = crypto.sign(senderSell, sellOrderWithUpdatedAmount.bodyBytes())
          val correctedSellOrder         = sellOrderWithUpdatedAmount.updateProofs(Proofs(Seq(ByteStr(newSignature))))

          (buyOrder, correctedSellOrder)
        }

        test(preconditions)
      }

      def test(preconditions: Gen[(Order, Order)]): Assertion = forAll(preconditions) {
        case (buyOrder, sellOrder) =>
          val tc = getExchangeTransactionCreator()
          val oe = mkOrderExecutedRaw(buyOrder, sellOrder)
          val tx = tc.createTransaction(oe).explicitGet()

          tx.buyMatcherFee shouldBe oe.submittedExecutedFee
          tx.sellMatcherFee shouldBe oe.counterExecutedFee
      }
    }
  }
} 
Example 65
Source File: AssetPairsDBSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.db

import com.wavesplatform.dex.domain.asset.Asset.Waves
import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.{MatcherSpecBase, NoShrink}
import org.scalacheck.Gen
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class AssetPairsDBSpec extends AnyFreeSpec with Matchers with WithDB with MatcherSpecBase with PropertyChecks with NoShrink {

  private val fixedAssetPairGen = assetPairGen.filterNot(x => x.amountAsset == Waves && x.priceAsset == Waves)

  "Default AssetPairsDB implementation" - {
    "stores and reads all asset pairs" in {
      val g = Gen.containerOf[Set, AssetPair](fixedAssetPairGen)
      forAll(g) { assetPairs =>
        test { apdb =>
          assetPairs.foreach(apdb.add)
          apdb.all() shouldBe assetPairs
        }
      }
    }

    "removes asset pair" in {
      val g = for {
        xs <- Gen.nonEmptyContainerOf[Vector, AssetPair](fixedAssetPairGen)
        indexGen = Gen.choose(0, xs.size - 1)
        is <- Gen.nonEmptyListOf(indexGen)
      } yield (xs.toSet, is.toSet.map(xs.apply))

      forAll(g) {
        case (assetPairs, toRemove) =>
          test { apdb =>
            assetPairs.foreach(apdb.add)
            toRemove.foreach(apdb.remove)
            apdb.all() shouldBe (assetPairs -- toRemove)
          }
      }
    }

  }

  private def test(f: AssetPairsDB => Any): Any = tempDb(db => f(AssetPairsDB(db)))

} 
Example 66
Source File: RateDBSpecification.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.db

import com.wavesplatform.dex.{MatcherSpecBase, NoShrink}
import org.scalacheck.Gen
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class RateDBSpecification extends AnyWordSpecLike with Matchers with WithDB with MatcherSpecBase with PropertyChecks with NoShrink {

  private def test(f: RateDB => Unit): Unit = f { RateDB(db) }

  "RateDB" should {
    "add, get and delete rates" in test { rdb =>
      val preconditions =
        Gen
          .listOfN(
            100,
            for {
              asset     <- arbitraryAssetGen
              rateValue <- Gen.choose(1, 100).map(_.toDouble / 100)
            } yield asset -> rateValue
          )
          .map(_.toMap)

      forAll(preconditions) { map =>
        map.foreach { case (asset, rateValue) => rdb.upsertRate(asset, rateValue) }
        rdb.getAllRates shouldBe map
        map.foreach { case (asset, _) => rdb.deleteRate(asset) }
        rdb.getAllRates.size shouldBe 0
      }
    }

    "update rate if it already exists" in test { rdb =>
      forAll(arbitraryAssetGen) { asset =>
        rdb.upsertRate(asset, 1)
        rdb.getAllRates shouldBe Map(asset -> 1)

        rdb.upsertRate(asset, 2)
        rdb.getAllRates shouldBe Map(asset -> 2)

        rdb.deleteRate(asset)
      }
    }
  }
} 
Example 67
Source File: RateCacheSpecification.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.caches

import com.wavesplatform.dex.db.{RateDB, WithDB}
import com.wavesplatform.dex.domain.asset.Asset
import com.wavesplatform.dex.domain.asset.Asset.Waves
import com.wavesplatform.dex.{MatcherSpecBase, NoShrink}
import org.scalacheck.Gen
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class RateCacheSpecification extends AnyWordSpecLike with Matchers with WithDB with MatcherSpecBase with PropertyChecks with NoShrink {

  private def test(f: RateCache => Unit): Unit = {
    withClue("with DB") { f(RateCache(db)) }
    withClue("in mem") { f(RateCache.inMem) }
  }

  private val WavesRate: Map[Asset, Double] = Map(Waves -> 1d)

  "RateCache" should {

    "add, get and delete rates" in test { rc =>
      val preconditions =
        Gen
          .listOfN(
            100,
            for {
              asset     <- arbitraryAssetGen
              rateValue <- Gen.choose(1, 100).map(_.toDouble / 100)
            } yield asset -> rateValue
          )
          .map(_.toMap[Asset, Double])

      forAll(preconditions) { map =>
        map.foreach { case (asset, rateValue) => rc.upsertRate(asset, rateValue) shouldBe None }
        rc.getAllRates should matchTo(map ++ WavesRate)
        map.foreach { case (asset, rate) => rc.deleteRate(asset) shouldBe Some(rate) }
        rc.getAllRates should matchTo(WavesRate)
      }
    }

    "update rate if it already exists" in test { rc =>
      forAll(arbitraryAssetGen) { asset: Asset =>
        rc.upsertRate(asset, 1) shouldBe None
        rc.getAllRates should matchTo(Map(asset -> 1d) ++ WavesRate)

        rc.upsertRate(asset, 2) shouldBe Some(1d)
        rc.getAllRates should matchTo(Map(asset -> 2d) ++ WavesRate)

        rc.deleteRate(asset) shouldBe Some(2d)
      }
    }

    "correctly restore state from db" in {
      val rateDB = RateDB(db)

      val asset1 = mkAssetId("First")
      val asset2 = mkAssetId("Second")

      rateDB.upsertRate(asset1, 1.5)
      rateDB.upsertRate(asset2, 5.1)

      RateCache(db).getAllRates should matchTo(Map(asset1 -> 1.5, asset2 -> 5.1) ++ WavesRate)
    }
  }
} 
Example 68
Source File: it.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform

import com.wavesplatform.dex.domain.account.{KeyPair, PublicKey}
import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.domain.order.{Order, OrderType}
import com.wavesplatform.dex.waves.WavesFeeConstants._
import com.wavesplatform.it.api.MatcherCommand
import org.scalacheck.Gen

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.{DurationInt, FiniteDuration}
import scala.concurrent.{Await, Future}
import scala.util.Random
import scala.util.control.NonFatal

package object it {

  
  def executeCommands(xs: Seq[MatcherCommand], ignoreErrors: Boolean = true, timeout: FiniteDuration = 3.minutes): Int = {
    Await.result(Future.sequence(xs.map(executeCommand(_, ignoreErrors))), timeout).sum
  }

  private def executeCommand(x: MatcherCommand, ignoreErrors: Boolean): Future[Int] =
    try x match {
      case MatcherCommand.Place(api, order) => api.tryPlace(order).map(_.fold(_ => 0, _ => 1))
      case MatcherCommand.Cancel(api, owner, order) =>
        api.tryCancel(owner, order).map(_.fold(_ => 0, _ => 1))
    } catch {
      case NonFatal(e) =>
        if (ignoreErrors) Future.successful(0)
        else Future.failed(e)
    }

  def orderGen(matcher: PublicKey,
               trader: KeyPair,
               assetPairs: Seq[AssetPair],
               types: Seq[OrderType] = Seq(OrderType.BUY, OrderType.SELL)): Gen[Order] = {
    val ts = System.currentTimeMillis()
    for {
      assetPair      <- Gen.oneOf(assetPairs)
      tpe            <- Gen.oneOf(types)
      amount         <- Gen.choose(10, 100)
      price          <- Gen.choose(10, 100)
      orderVersion   <- Gen.choose[Byte](1, 3)
      expirationDiff <- Gen.choose(600000, 6000000)
    } yield {
      if (tpe == OrderType.BUY)
        Order.buy(
          trader,
          matcher,
          assetPair,
          amount,
          price * Order.PriceConstant,
          ts,
          ts + expirationDiff,
          matcherFee,
          orderVersion
        )
      else
        Order.sell(
          trader,
          matcher,
          assetPair,
          amount,
          price * Order.PriceConstant,
          ts,
          ts + expirationDiff,
          matcherFee,
          orderVersion
        )
    }
  }

  def choose[T](xs: IndexedSeq[T]): T = xs(Random.nextInt(xs.size))
} 
Example 69
Source File: OrderBookSnapshotsTestSuite.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.it.sync

import com.typesafe.config.{Config, ConfigFactory}
import com.wavesplatform.dex.api.http.entities.HttpOrderStatus
import com.wavesplatform.dex.domain.order.Order
import com.wavesplatform.it.{MatcherSuiteBase, orderGen}
import org.scalacheck.Gen

class OrderBookSnapshotsTestSuite extends MatcherSuiteBase {
  private val interval = 50L

  override protected val dexInitialSuiteConfig: Config = ConfigFactory.parseString(
    s"""waves.dex {
      |  price-assets = ["$UsdId", "WAVES"]
      |  snapshots-interval = $interval
      |}""".stripMargin
  )

  private val assetPair1 = ethUsdPair
  private val assetPair2 = ethWavesPair

  private val ordersPack1Size = 11
  private val ordersPack1 = Gen
    .containerOfN[Vector, Order](ordersPack1Size - 1, orderGen(matcher, alice, List(assetPair1)))
    .sample
    .get :+ orderGen(matcher, alice, List(assetPair2)).sample.get

  private val ordersPack2Size = interval.toInt
  private val ordersPack2 = Gen
    .containerOfN[Vector, Order](ordersPack2Size, orderGen(matcher, alice, List(assetPair2)))
    .sample
    .get

  override protected def beforeAll(): Unit = {
    wavesNode1.start()
    broadcastAndAwait(IssueEthTx, IssueUsdTx)
    dex1.start()
  }

  "Order books are created with right offsets" in {

    ordersPack1.foreach(dex1.api.place)
    dex1.api.waitForCurrentOffset(_ == ordersPack1Size - 1)

    val allSnapshotOffsets1 = dex1.api.allSnapshotOffsets

    withClue("We doesn't show pairs, those have snapshot's offset equal to -1") {
      if (allSnapshotOffsets1.contains(assetPair1)) allSnapshotOffsets1(assetPair1) should be < interval
      if (allSnapshotOffsets1.contains(assetPair2)) allSnapshotOffsets1(assetPair2) should be < interval
    }

    ordersPack2.foreach(dex1.api.place)
    dex1.api.waitForCurrentOffset(_ == ordersPack1Size + ordersPack2Size - 1)

    val allSnapshotOffsets2 = dex1.api.allSnapshotOffsets

    withClue("Asset pairs has right offsets") {
      allSnapshotOffsets2.foreach {
        case (pair, offset) =>
          withClue(pair) {
            offset should be < (interval * 2)
          }
      }
    }
  }

  "All events are processed after restart" in {
    dex1.restart()
    dex1.api.waitForCurrentOffset(_ == ordersPack1Size + ordersPack2Size - 1)
    ordersPack1.foreach { order =>
      dex1.api.orderStatus(order) should not be HttpOrderStatus.Status.NotFound.name
    }
  }
} 
Example 70
Source File: DatabaseBackwardCompatTestSuite.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.it.sync.compat

import com.wavesplatform.dex.api.http.entities.HttpOrderStatus.Status
import com.wavesplatform.dex.domain.order.Order
import com.wavesplatform.dex.it.docker.DexContainer
import com.wavesplatform.it.orderGen
import com.wavesplatform.it.tags.DexMultipleVersions
import org.scalacheck.Gen
import org.testcontainers.containers.BindMode

import scala.concurrent.duration.DurationInt

@DexMultipleVersions
class DatabaseBackwardCompatTestSuite extends BackwardCompatSuiteBase {
  "Database backward compatibility test" in {
    val assetPairs = List(ethWavesPair, wavesUsdPair)
    val twoAccountsOrdersGen = Gen.oneOf(
      orderGen(matcher, alice, assetPairs),
      orderGen(matcher, bob, assetPairs)
    )

    val orders = Gen.containerOfN[Vector, Order](200, twoAccountsOrdersGen).sample.get
    orders.foreach(dex2.api.place)

    dex2.api.waitForOrder(orders.last)(_.status != Status.NotFound)
    dex2.stopWithoutRemove()

    dex1.start()
    orders.groupBy(_.assetPair).valuesIterator.foreach { orders =>
      dex1.api.waitForOrder(orders.last)(_.status != Status.NotFound)
    }
    Thread.sleep(3.seconds.toMillis) // An additional time to wait the concurrent processing

    val state1 = state(dex1.api, orders)
    val state2 = state(dex2.api, orders)
    state1 should matchTo(state2)
  }

  override protected def beforeAll(): Unit = {
    super.beforeAll()

    val containerDataDir = DexContainer.containerPath("data")
    List(dex1, dex2).foreach {
      _.underlying.configure {
        _.withFileSystemBind(localLogsDir.resolve("db").toString, containerDataDir, BindMode.READ_WRITE)
      }
    }

    dex2.start()
  }
} 
Example 71
Source File: MatcherRecoveryTestSuite.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.it.sync

import com.typesafe.config.{Config, ConfigFactory}
import com.wavesplatform.dex.domain.order.Order
import com.wavesplatform.it._
import com.wavesplatform.it.api.{MatcherCommand, MatcherState}
import org.scalacheck.Gen

import scala.util.Random

class MatcherRecoveryTestSuite extends MatcherSuiteBase {

  override protected def dexInitialSuiteConfig: Config = {
    ConfigFactory.parseString(
      s"""waves.dex {
       |  snapshots-interval = 51
       |  price-assets = [ "$UsdId", "WAVES" ]
       |}""".stripMargin
    )
  }

  private val placesNumber  = 200
  private val cancelsNumber = placesNumber / 10

  private val assetPairs = List(ethUsdPair, wavesUsdPair, ethWavesPair)
  private val orders     = Gen.containerOfN[Vector, Order](placesNumber, orderGen(matcher, alice, assetPairs)).sample.get

  private var successfulCommandsNumber = 0

  "Place, fill and cancel a lot of orders" in {
    val cancels = (1 to cancelsNumber).map(_ => choose(orders))

    val placeCommands  = Random.shuffle(orders.map(MatcherCommand.Place(dex1.asyncApi, _)))
    val cancelCommands = cancels.map(MatcherCommand.Cancel(dex1.asyncApi, alice, _))

    successfulCommandsNumber += executeCommands(placeCommands)
    successfulCommandsNumber += executeCommands(cancelCommands)
  }

  "Wait until all requests are processed - 1" in {
    dex1.api.waitForCurrentOffset(_ == successfulCommandsNumber - 1) // Index starts from 0
  }

  private var stateBefore: MatcherState = _

  "Store the current state" in {
    stateBefore = state
    withClue("common offset") { stateBefore.offset should be > 0L }
    stateBefore.snapshots.foreach {
      case (assetPair, snapshotOffset) => withClue(assetPair) { snapshotOffset should be > 0L }
    }
  }

  "Restart the matcher" in dex1.restart()

  "Wait until all requests are processed - 2" in dex1.api.waitForCurrentOffset(_ == successfulCommandsNumber - 1)

  "Verify the state" in {
    val stateAfter = state
    stateBefore should matchTo(stateAfter)
  }

  private def state = cleanState(matcherState(assetPairs, orders, Seq(alice)))

  protected def cleanState(state: MatcherState): MatcherState = state

  override protected def beforeAll(): Unit = {
    wavesNode1.start()
    broadcastAndAwait(IssueEthTx, IssueUsdTx)
    dex1.start()
  }
} 
Example 72
Source File: OrderBookAddBenchmark.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.model.orderbook

import java.util.concurrent.TimeUnit

import com.wavesplatform.dex.domain.order.{Order, OrderType}
import com.wavesplatform.dex.model.orderbook.OrderBookAddBenchmark._
import com.wavesplatform.dex.model.state.OrderBookBenchmarkState
import com.wavesplatform.dex.model.{AcceptedOrder, OrderBook}
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole
import org.scalacheck.Gen

import scala.collection.JavaConverters._

@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Array(Mode.AverageTime))
@Threads(4)
@Fork(1)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
class OrderBookAddBenchmark {
  @Benchmark def add_0_plus_1250_test(st: Add_0_To_1250_State, bh: Blackhole): Unit       = bh.consume { st.run() }
  @Benchmark def add_1250_plus_1250_test(st: Add_1250_To_1250_State, bh: Blackhole): Unit = bh.consume { st.run() }
}

object OrderBookAddBenchmark {

  @State(Scope.Thread) class Add_0_To_1250_State    extends AddState(initOrderNumber = 0, orderNumberToAdd = 1250)
  @State(Scope.Thread) class Add_1250_To_1250_State extends AddState(initOrderNumber = 1250, orderNumberToAdd = 1250)

  sealed abstract class AddState(initOrderNumber: Int, orderNumberToAdd: Int) extends OrderBookBenchmarkState {
    val maxPrice = 1000L * Order.PriceConstant
    val minPrice = 1L * Order.PriceConstant
    val priceGen = Gen.chooseNum(minPrice, maxPrice)

    val askGen = orderGen(priceGen, OrderType.SELL)
    val bidGen = orderGen(priceGen, OrderType.BUY)

    val orderBook: OrderBook = ordersGen(initOrderNumber).sample.get.foldLeft(OrderBook.empty)(_.add(_, ts, getMakerTakerFee).orderBook)

    val orders: List[AcceptedOrder] = ordersGen(orderNumberToAdd).sample.get

    def run(): OrderBook = orders.foldLeft(OrderBook.empty) {
      case (r, o) => r.add(o, ts, getMakerTakerFee).orderBook
    }

    def ordersGen(orderNumber: Int): Gen[List[AcceptedOrder]] =
      for {
        orderSides <- Gen.listOfN(orderNumber, orderSideGen)
        orders <- Gen.sequence {
          orderSides.map { side =>
            val orderGen = if (side == OrderType.SELL) askGen else bidGen
            Gen.oneOf(limitOrderGen(orderGen), marketOrderGen(orderGen))
          }
        }
      } yield orders.asScala.toList
  }

} 
Example 73
Source File: OrderBookCancelBenchmark.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.model.orderbook

import java.util.concurrent.{ThreadLocalRandom, TimeUnit}

import com.wavesplatform.dex.domain.order.Order
import com.wavesplatform.dex.model.OrderBook
import com.wavesplatform.dex.model.orderbook.OrderBookCancelBenchmark._
import com.wavesplatform.dex.model.state.OrderBookBenchmarkState
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole
import org.scalacheck.Gen

import scala.util.Random

@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Array(Mode.AverageTime))
@Threads(4)
@Fork(1)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
class OrderBookCancelBenchmark {
//  @Benchmark def cancel_2500_to_1250_test(st: Cancel_2500_To_1250_State, bh: Blackhole): Unit = bh.consume { st.run() }
  @Benchmark def cancel_1250_to_0_test(st: Cancel_1250_To_0_State, bh: Blackhole): Unit       = bh.consume { st.run() }
}

object OrderBookCancelBenchmark {

  @State(Scope.Thread) class Cancel_2500_To_1250_State extends CancelState(initOrderNumber = 2500, orderNumberAfterCancel = 1250)
  @State(Scope.Thread) class Cancel_1250_To_0_State    extends CancelState(initOrderNumber = 1250, orderNumberAfterCancel = 0)

  sealed abstract class CancelState(initOrderNumber: Int, orderNumberAfterCancel: Int) extends OrderBookBenchmarkState {
    private val askPricesMin = 1000L * Order.PriceConstant
    private val askPricesMax = 2000L * Order.PriceConstant

    private val bidPricesMin = 1L * Order.PriceConstant
    private val bidPricesMax = 999L * Order.PriceConstant

    val orderBookGen: Gen[OrderBook] = fixedSidesOrdersGen(
      levelNumber = initOrderNumber / 2,
      orderNumberInLevel = 2,
      askPricesGen = Gen.choose(askPricesMin, askPricesMax),
      bidPricesGen = Gen.choose(bidPricesMin, bidPricesMax)
    ).map(Function.tupled(mkOrderBook))

    val orderBook: OrderBook = orderBookGen.sample.get
    val orders: Seq[Order.Id] = {
      val xs = orderBook.allOrders.map(_.order.id()).toVector
      new Random(ThreadLocalRandom.current()).shuffle(xs).take(initOrderNumber - orderNumberAfterCancel)
    }

    def run(): OrderBook = orders.foldLeft(orderBook) { case (r, id) => r.cancel(id, ts)._1 }
  }

} 
Example 74
Source File: OrderBookBenchmarkState.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.model.state

import com.wavesplatform.dex.domain.order.OrderType
import com.wavesplatform.dex.gen.OrderBookGen
import com.wavesplatform.dex.model.{AcceptedOrder, LimitOrder}
import org.scalacheck.Gen

import scala.collection.JavaConverters._

trait OrderBookBenchmarkState extends OrderBookGen {
  def getMakerTakerFee(a: AcceptedOrder, b: LimitOrder): (Long, Long) = (a.matcherFee, b.matcherFee)

  def fixedSidesOrdersGen(levelNumber: Int,
                          orderNumberInLevel: Int,
                          askPricesGen: Gen[Long],
                          bidPricesGen: Gen[Long]): Gen[(Seq[LimitOrder], Seq[LimitOrder])] =
    for {
      askOrders <- fixedSideOrdersGen(OrderType.SELL, levelNumber / 2, orderNumberInLevel, askPricesGen)
      bidOrders <- fixedSideOrdersGen(OrderType.BUY, levelNumber / 2, orderNumberInLevel, bidPricesGen)
    } yield (askOrders, bidOrders)

  def fixedSideOrdersGen(side: OrderType, levels: Int, ordersInLevel: Int, pricesGen: Gen[Long]): Gen[Seq[LimitOrder]] =
    for {
      prices <- Gen.listOfN(levels, pricesGen)
      orders <- Gen.sequence(prices.map { price =>
        Gen.listOfN(ordersInLevel, limitOrderGen(orderGen(Gen.const(price), side)))
      })
    } yield orders.asScala.flatten
} 
Example 75
Source File: CatsTaglessInstances.scala    From sup   with Apache License 2.0 5 votes vote down vote up
package sup

import cats.Eq
import cats.arrow.FunctionK
import org.scalacheck.{Arbitrary, Gen}

import scala.util.Try

object CatsTaglessInstances {

  implicit val catsDataArbitraryOptionList: Arbitrary[FunctionK[Option, List]] = Arbitrary(
    Gen.const(λ[FunctionK[Option, List]](_.toList))
  )

  implicit val catsDataArbitraryListOption: Arbitrary[FunctionK[List, Option]] = Arbitrary(
    Gen.const(λ[FunctionK[List, Option]](_.headOption))
  )

  implicit val catsDataArbitraryTryOption: Arbitrary[FunctionK[Try, Option]] = Arbitrary(
    Gen.const(λ[FunctionK[Try, Option]](_.toOption))
  )

  implicit val catsDataArbitraryOptionTry: Arbitrary[FunctionK[Option, Try]] = Arbitrary(
    Gen.const(λ[FunctionK[Option, Try]](o => Try(o.get)))
  )

  implicit val catsDataArbitraryListVector: Arbitrary[FunctionK[List, Vector]] = Arbitrary(
    Gen.const(λ[FunctionK[List, Vector]](_.toVector))
  )

  implicit val catsDataArbitraryVectorList: Arbitrary[FunctionK[Vector, List]] = Arbitrary(
    Gen.const(λ[FunctionK[Vector, List]](_.toList))
  )

  implicit val eqThrow: Eq[Throwable] = Eq.fromUniversalEquals
} 
Example 76
Source File: ArbitraryDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.scalacheck.semiauto

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

import scala.language.experimental.macros

object ArbitraryDerivation {
  type Typeclass[T] = Arbitrary[T]

  def combine[T: Fallback](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = Arbitrary {
    Gen.lzy(Gen.sized { size =>
      if (size >= 0) {
        Gen.resize(size - 1, caseClass.constructMonadic(_.typeclass.arbitrary)(monadicGen))
      } else {
        implicitly[Fallback[T]].get
      }
    })
  }

  def dispatch[T: Fallback](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = Arbitrary {
    Gen.sized { size =>
      if (size > 0) {
        Gen.resize(
          size - 1,
          Gen.oneOf(sealedTrait.subtypes.map(_.typeclass.arbitrary)).flatMap(identity)
        )
      } else {
        implicitly[Fallback[T]].get
      }
    }
  }

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]

  private val monadicGen: Monadic[Gen] = new Monadic[Gen] {
    override def point[A](value: A): Gen[A] = Gen.const(value)
    override def flatMapS[A, B](from: Gen[A])(fn: A => Gen[B]): Gen[B] = from.flatMap(fn)
    override def mapS[A, B](from: Gen[A])(fn: A => B): Gen[B] = from.map(fn)
  }

  sealed trait Fallback[+T] extends Serializable {
    def get: Gen[T]
  }

  object Fallback {
    def apply[T](g: Gen[T]): Fallback[T] = new Fallback[T] {
      override def get: Gen[T] = g
    }

    def apply[T](v: T): Fallback[T] = Fallback[T](Gen.const(v))
    def apply[T](implicit arb: Arbitrary[T]): Fallback[T] = Fallback[T](arb.arbitrary)

    implicit def defaultFallback[T]: Fallback[T] = Fallback[T](Gen.fail)
  }
} 
Example 77
Source File: BaseLawsSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package tests

import java.util.UUID

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

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.prop.Configuration
import org.scalacheck.{ Arbitrary, Gen }
import org.scalacheck.util.Buildable
import org.typelevel.discipline.scalatest.FunSuiteDiscipline

import laws.{ AnyLaws, AtomicLaws }

trait BaseLawsSpec
  extends AnyFunSuite
  with FunSuiteDiscipline
  with Configuration
  with laws.TestEqInstances
  with laws.TestArbInstances {

  implicit val eqForUuid: Eq[UUID] =
    Eq.fromUniversalEquals

  implicit def eqForJavaEnums[A <: java.lang.Enum[A]]: Eq[A] =
    referenceEq[A]

  def checkAtomicLaws[A](name: String)(implicit a: Arbitrary[A], e: Eq[A], at: Atomic[A]): Unit = {
    checkAll(s"Atomic[$name].AnyLaws.any", AnyLaws[Atomic[A]].any)
    checkAll(s"Atomic[$name].AnyLaws.equalitySerializability", AnyLaws[Atomic[A]].equalitySerializability)
    checkAll(s"Atomic[$name].AnyLaws.referenceEquality", AnyLaws[Atomic[A]].referenceEquality)
    checkAll(s"Atomic[$name].EqTests.eqv", EqTests[Atomic[A]].eqv)
    checkAll(s"Atomic[$name].AtomicLaws.roundtrip", AtomicLaws[A].roundtrip)
  }

  
  protected val maxContainerSize = 3

  object LimitedContainers {
    implicit def arbCont[F[_], A](
      implicit
      A: Arbitrary[A],
      B: Buildable[A, F[A]],
      T: F[A] => Traversable[A]
    ): Arbitrary[F[A]] = Arbitrary {
      for {
        n <- Gen.choose(0, maxContainerSize)
        v <- Gen.containerOfN[F, A](n, A.arbitrary)
      } yield v
    }
  }
} 
Example 78
Source File: LawsSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package circe

import cats.Eq
import cats.implicits._

import io.circe.Json
import io.circe.numbers.BiggerDecimal
import io.circe.testing.instances.{ arbitraryJson, cogenJson }

import org.scalacheck.{ Arbitrary, Gen }

import cats.kernel.laws.discipline.OrderTests

class LawsSpec extends tests.BaseLawsSpec {

  import Atoms._

  implicit val eqBiggerDecimal: Eq[BiggerDecimal] =
    Eq.fromUniversalEquals

  implicit def arbBiggerDecimal(
    implicit
    arbBd: Arbitrary[BigDecimal],
    arbBi: Arbitrary[BigInt],
    arbDbl: Arbitrary[Double]
  ): Arbitrary[BiggerDecimal] = Arbitrary {
    Gen.oneOf(
      // fits into a BigDecimal:
      arbBd.arbitrary.map { x =>
        BiggerDecimal.fromBigDecimal(x.underlying)
      },
      // doesn't fit into a BigDecimal:
      arbBi.arbitrary.map { n =>
        val str = s"${n}e${n max Int.MaxValue.toLong + 1L}"
        BiggerDecimal.parseBiggerDecimal(str).getOrElse {
          core.impossible(s"cannot parse BiggerDecimal from '${str}'")
        }
      },
      // can contain negative zero:
      arbDbl.arbitrary.map(d => BiggerDecimal.fromDoubleUnsafe(- d))
    )
  }

  checkAtomicLaws[BiggerDecimal]("BiggerDecimal")

  checkAll("Codecs.orderForJson.Order", OrderTests[Json](Codecs.orderForJson).order)
} 
Example 79
Source File: ZonedDateTimeLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws


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

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


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

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

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

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

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

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

    def D: Zoned[A] = ev

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

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

import dtc.{TimeZoneId, Zoned}
import org.scalacheck.{Arbitrary, Gen}
import org.typelevel.discipline.Laws

trait ZonedDateTimeTests[A] extends Laws {

  def generalLocalDateTimeLaws: GeneralLocalDateTimeLaws[A]
  def laws: ZonedDateTimeLaws[A]

  def zonedDateTime(implicit arbA: Arbitrary[A], arbD: Arbitrary[Duration]): RuleSet = {
    new DefaultRuleSet(
      name = "ZonedDateTime",
      parent = None,
      "[within same offset] seconds addition laws" -> generalLocalDateTimeLaws.secondsAddition,
      "[within same offset] minutes addition laws" -> generalLocalDateTimeLaws.minutesAddition,
      "[within same offset] hours addition laws" -> generalLocalDateTimeLaws.hoursAddition,
      "[within same offset] withYear laws" -> generalLocalDateTimeLaws.withYear,
      "[within same offset] withMonth laws" -> generalLocalDateTimeLaws.withMonth,
      "[within same offset] withDayOfMonth laws" -> generalLocalDateTimeLaws.withDayOfMonth,
      "[within same offset] withHour laws" -> generalLocalDateTimeLaws.withHour,
      "[within same offset] withMinute laws" -> generalLocalDateTimeLaws.withMinute,
      "[within same offset] withSecond laws" -> generalLocalDateTimeLaws.withSecond,
      "[within same offset] withMillisecond laws" -> generalLocalDateTimeLaws.withMillisecond,
      "[within same offset] withTime laws" -> generalLocalDateTimeLaws.withTime,
      "[within same offset] withDate laws" -> generalLocalDateTimeLaws.withDate,
      "[within same offset] daysUntil is consistent with addition" -> generalLocalDateTimeLaws.daysUntilIsConsistentWithPlus,
      "[within same offset] monthsUntil is consistent with addition" -> generalLocalDateTimeLaws.monthsUntilIsConsistentWithPlus,
      "[within same offset] yearsUntil counts only number of full years" -> generalLocalDateTimeLaws.yearsUntilCountsOnlyFullUnits,
      "cross-offset addition" -> laws.crossOffsetAddition,
      "withZoneSameInstant gives the same instant" -> laws.withZoneSameInstantGivesSameInstant,
      "local time difference is the offset" -> laws.localTimeAndOffsetCorrelation
    )
  }
}

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

    def generalLocalDateTimeLaws: GeneralLocalDateTimeLaws[A] = GeneralLocalDateTimeLaws[A](
      gDateAndDurationWithinSameDST, arbLocalTime.arbitrary, arbLocalDate.arbitrary, gValidYear
    )

    def laws: ZonedDateTimeLaws[A] = ZonedDateTimeLaws[A](
      gDateAndDurationWithinSameDST, gDataSuite,
      arbLocalTime.arbitrary, arbLocalDate.arbitrary, gValidYear, gTimeZone
    )
  }
} 
Example 81
Source File: LocalDateTimeLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws

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

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


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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

  }

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

}

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

import java.time.Duration

import cats.Order
import dtc.{Provider, TimeZoneId}
import org.scalacheck.{Arbitrary, Gen}
import org.typelevel.discipline.Laws

trait ProviderTests[A] extends Laws {

  def laws: ProviderLaws[A]

  def provider(implicit arbA: Arbitrary[A], arbD: Arbitrary[Duration]): RuleSet = {
    new DefaultRuleSet(
      name = "Provider",
      parent = None,
      "two consequent now calls preserve order" -> laws.twoConsequentNowCalls
    )
  }
}

object ProviderTests {
  def apply[A: Provider : Order](
    gTimeZone: Gen[TimeZoneId])(
    implicit arbA: Arbitrary[A]): ProviderTests[A] = new ProviderTests[A] {
    def laws: ProviderLaws[A] = ProviderLaws(gTimeZone)
  }
} 
Example 84
Source File: DateTimeTests.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws

import java.time.Duration

import dtc.TimePoint
import org.scalacheck.{Arbitrary, Gen}
import org.typelevel.discipline.Laws

trait DateTimeTests[A] extends Laws {
  def laws: DateTimeLaws[A]

  def dateTime(implicit arbA: Arbitrary[A]): RuleSet = {
    new DefaultRuleSet(
      name = "DateTime",
      parent = None,
      "add and substract the same duration gives original value" -> laws.additionAndSubtractionOfSameDuration,
      "add zero gives same value" -> laws.additionOfZero,
      "add non zero changes value" -> laws.additionOfNonZero,
      "millis addition laws" -> laws.millisAddition,
      "until self is always zero" -> laws.untilSelfIsAlwaysZero,
      "until methods are consistent with addition" -> laws.untilIsConsistentWithPlus,
      "date is always defined" -> laws.dateMustNotThrow,
      "time is always defined" -> laws.timeMustNotThrow,
      "date fields are consistent with toLocalDate" -> laws.dateFieldsAreConsistentWithToLocalDate,
      "time fields are consistent with toLocalTime" -> laws.timeFieldsAreConsistentWithToLocalTime
    )
  }
}

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


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

trait ProviderLaws[A] {

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

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

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

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

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

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

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

import dtc.Local
import org.scalacheck.{Arbitrary, Gen}
import org.typelevel.discipline.Laws

trait LocalDateTimeTests[A] extends Laws {

  def generalLaws: GeneralLocalDateTimeLaws[A]
  def laws: LocalDateTimeLaws[A]

  def localDateTime(implicit arbA: Arbitrary[A], arbD: Arbitrary[Duration]): RuleSet = {
    new DefaultRuleSet(
      name = "LocalDateTime",
      parent = None,
      "seconds addition laws" -> generalLaws.secondsAddition,
      "minutes addition laws" -> generalLaws.minutesAddition,
      "hours addition laws" -> generalLaws.hoursAddition,
      "constructor consistency" -> laws.constructorConsistency,
      "plain constructor consistency" -> laws.plainConstructorConsistency,
      "withYear laws" -> generalLaws.withYear,
      "withMonth laws" -> generalLaws.withMonth,
      "withDayOfMonth laws" -> generalLaws.withDayOfMonth,
      "withHour laws" -> generalLaws.withHour,
      "withMinute laws" -> generalLaws.withMinute,
      "withSecond laws" -> generalLaws.withSecond,
      "withMillisecond laws" -> generalLaws.withMillisecond,
      "withTime laws" -> generalLaws.withTime,
      "withDate laws" -> generalLaws.withDate,
      "daysUntil is consistent with addition" -> generalLaws.daysUntilIsConsistentWithPlus,
      "monthsUntil is consistent with addition" -> generalLaws.monthsUntilIsConsistentWithPlus,
      "yearsUntil counts only number of full years" -> generalLaws.yearsUntilCountsOnlyFullUnits
    )
  }

  // see: https://github.com/moment/moment/issues/3029
  def monthUntilFractionHandling(implicit arbA: Arbitrary[A], arbD: Arbitrary[Duration]): RuleSet = {
    new DefaultRuleSet(
      name = "LocalDateTime",
      parent = None,
      "monthsUntil counts only number of full months" -> generalLaws.monthsUntilCountsOnlyFullUnits
    )
  }
}

object LocalDateTimeTests {
  def apply[A: Local](
    gDateAndDuration: Gen[(A, Duration)],
    gValidYear: Gen[Int])(
    implicit
    arbA: Arbitrary[A],
    arbLocalTime: Arbitrary[LocalTime],
    arbLocalDate: Arbitrary[LocalDate]): LocalDateTimeTests[A] = new LocalDateTimeTests[A] {

    def laws: LocalDateTimeLaws[A] = LocalDateTimeLaws[A](
      arbLocalTime.arbitrary, arbLocalDate.arbitrary
    )

    def generalLaws: GeneralLocalDateTimeLaws[A] = GeneralLocalDateTimeLaws[A](
      gDateAndDuration, arbLocalTime.arbitrary, arbLocalDate.arbitrary, gValidYear
    )
  }
} 
Example 87
Source File: JVMZonedDateTimeTests.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

import java.time.temporal.ChronoUnit
import java.time.{Duration, ZonedDateTime}

import cats.instances.option._
import cats.kernel.laws.discipline.OrderTests
import com.fortysevendeg.scalacheck.datetime.jdk8.ArbitraryJdk8
import dtc.{Offset, Zoned}
import dtc.laws.{DateTimeTests, ProviderTests, ZonedDateTimeTestData, ZonedDateTimeTests}
import dtc.syntax.timeZone._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Cogen, Gen}
import dtc.instances.providers.realZonedDateTimeProvider

abstract class JVMZonedDateTimeTests(instance: Zoned[ZonedDateTime]) extends DTCSuiteJVM {

  implicit val zonedInstance: Zoned[ZonedDateTime] = instance

  implicit val arbT: Arbitrary[ZonedDateTime] = ArbitraryJdk8.arbZonedDateTimeJdk8
  implicit val cogenT: Cogen[ZonedDateTime] = Cogen(_.toEpochSecond)

  val overflowSafePairGen: Gen[(ZonedDateTime, Duration)] = for {
    dt <- arbitrary[ZonedDateTime]
    dur <- arbitrary[Duration]
  } yield (dt, dur)

  def genDateFromPeriod(period: SameZoneOffsetPeriod): Gen[ZonedDateTime] =
    genDateTimeFromSameOffsetPeriod(period).map(tpl => ZonedDateTime.of(tpl._1, tpl._2, tpl._3.zoneId))

  val overflowSafePairGenWithinSameOffset: Gen[(ZonedDateTime, Duration)] = for {
    period <- arbitrary[SameZoneOffsetPeriod]
    dateTime <- genDateFromPeriod(period)
    duration <- genDateFromPeriod(period)
      .map(other => dateTime.until(other, ChronoUnit.NANOS))
      .map(Duration.ofNanos)
  } yield (dateTime, duration)

  val genZonedTestDataSuite: Gen[ZonedDateTimeTestData[ZonedDateTime]] =
    overflowSafePairGen.map {
      case (date, duration) =>
        val target = date.plus(duration)
        ZonedDateTimeTestData(date, duration,
          Offset(date.plus(duration).getOffset.getTotalSeconds), target.toLocalTime, target.toLocalDate)
    }

  checkAll("java.time.ZonedDateTime", DateTimeTests[ZonedDateTime](overflowSafePairGen).dateTime)
  checkAll("java.time.ZonedDateTime", ZonedDateTimeTests[ZonedDateTime](
    overflowSafePairGenWithinSameOffset,
    genZonedTestDataSuite,
    genYear,
    genTimeZone
  ).zonedDateTime)
  checkAll("java.time.ZonedDateTime", OrderTests[ZonedDateTime].order)
  checkAll("java.time.ZonedDateTime", OrderTests[ZonedDateTime].partialOrder)
  checkAll("java.time.ZonedDateTime", OrderTests[ZonedDateTime].eqv)

  checkAll("java.time.ZonedDateTime", ProviderTests[ZonedDateTime](genTimeZone).provider)
}

class ZonedDateTimeWithStrictEqualityTests
  extends JVMZonedDateTimeTests(dtc.instances.zonedDateTime.zonedDateTimeWithStrictEquality)

class ZonedDateTimeWithCrossZoneEqualityTests
  extends JVMZonedDateTimeTests(dtc.instances.zonedDateTime.zonedDateTimeWithCrossZoneEquality) 
Example 88
Source File: DTCSuite.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

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

import dtc.TimeZoneId
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.funspec.AnyFunSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
import org.typelevel.discipline.scalatest.FunSpecDiscipline

trait DTCSuite extends AnyFunSpecLike
  with Matchers
  with ScalaCheckDrivenPropertyChecks
  with FunSpecDiscipline {

  override implicit val generatorDrivenConfig: PropertyCheckConfiguration = PropertyCheckConfiguration(
    minSuccessful = 100
  )
  private val nanoOfDayRange = ChronoField.NANO_OF_DAY.range()

  val genLocalTime: Gen[LocalTime] =
    Gen.choose(nanoOfDayRange.getMinimum, nanoOfDayRange.getMaximum).map(LocalTime.ofNanoOfDay)
  implicit val arbLocalTime: Arbitrary[LocalTime] = Arbitrary(genLocalTime)

  val genDuration: Gen[Duration] =
    Gen.choose(Long.MinValue / 1000, Long.MaxValue / 1000)
      .map(l => Duration.of(l, MILLIS))

  implicit val arbDuration = Arbitrary(genDuration)

  def genDateTimeFromSameOffsetPeriod(period: SameZoneOffsetPeriod): Gen[(LocalDate, LocalTime, TimeZoneId)] = for {
    date <- Gen.choose(period.startDate.toEpochDay + 1L, period.endDate.toEpochDay - 1L).map(LocalDate.ofEpochDay)
    timeBounds <- Gen.const(
      if (date == period.startDate && date == period.endDate) (period.startTime, period.endTime)
      else if (date == period.startDate) (period.startTime, LocalTime.MAX)
      else if (date == period.endDate) (LocalTime.MAX, period.endTime)
      else (LocalTime.MIN, LocalTime.MAX)
    )
    time <- Gen.choose(timeBounds._1.toNanoOfDay, timeBounds._2.toNanoOfDay).map(LocalTime.ofNanoOfDay)
  } yield (date, time, period.zone)
} 
Example 89
Source File: MomentZonedDateTimeTests.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

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

import cats.instances.option._
import cats.kernel.laws.discipline.OrderTests
import dtc.{TimeZoneId, Zoned}
import dtc.js.MomentZonedDateTime
import dtc.laws.{DateTimeTests, ProviderTests, ZonedDateTimeTestData, ZonedDateTimeTests}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Cogen, Gen}
import dtc.instances.moment.providers.realMomentZonedDateTimeProvider

abstract class MomentZonedDateTimeTests(instance: Zoned[MomentZonedDateTime]) extends DTCSuiteJS {

  implicit val zonedInstance: Zoned[MomentZonedDateTime] = instance

  implicit val arbT: Arbitrary[MomentZonedDateTime] = Arbitrary(for {
    date <- arbitrary[LocalDate]
    time <- arbitrary[LocalTime]
    zone <- arbitrary[TimeZoneId]
  } yield MomentZonedDateTime.of(date, time, zone))

  implicit val cogenT: Cogen[MomentZonedDateTime] = cogenMomentDateTime[MomentZonedDateTime]

  val pairGen: Gen[(MomentZonedDateTime, Duration)] = for {
    zone <- arbitrary[TimeZoneId]
    pair <- overflowSafePairGen
  } yield (MomentZonedDateTime.of(pair._1, pair._2, zone), pair._3)

  def genDateFromPeriod(period: SameZoneOffsetPeriod): Gen[MomentZonedDateTime] =
    genDateTimeFromSameOffsetPeriod(period).map(tpl => MomentZonedDateTime.of(tpl._1, tpl._2, tpl._3))

  val overflowSafePairGenWithinSameOffset: Gen[(MomentZonedDateTime, Duration)] = for {
    period <- arbitrary[SameZoneOffsetPeriod]
    dateTime <- genDateFromPeriod(period)
    duration <- genDateFromPeriod(period)
      .map(other => dateTime.millisecondsUntil(other))
      .map(Duration.ofMillis)
  } yield (dateTime, duration)


  val genZonedTestDataSuite: Gen[ZonedDateTimeTestData[MomentZonedDateTime]] =
    pairGen.map {
      case (date, duration) =>
        val target = date.plus(duration)
        ZonedDateTimeTestData(date, duration, target.offset, target.toLocalTime, target.toLocalDate)
    }

  checkAll("MomentZonedDateTime", DateTimeTests[MomentZonedDateTime](pairGen).dateTime)
  checkAll("MomentZonedDateTime", ZonedDateTimeTests[MomentZonedDateTime](
    overflowSafePairGenWithinSameOffset,
    genZonedTestDataSuite,
    genJSValidYear,
    genTimeZone
  ).zonedDateTime)
  checkAll("MomentZonedDateTime", OrderTests[MomentZonedDateTime].order)
  checkAll("MomentZonedDateTime", OrderTests[MomentZonedDateTime].partialOrder)
  checkAll("MomentZonedDateTime", OrderTests[MomentZonedDateTime].eqv)

  checkAll("MomentZonedDateTime", ProviderTests[MomentZonedDateTime](genTimeZone).provider)
}

class MomentZonedDateTimeWithStrictEqualityTests
  extends MomentZonedDateTimeTests(dtc.instances.moment.momentZonedWithStrictEquality)

class MomentZonedDateTimeWithCrossZoneEqualityTests
  extends MomentZonedDateTimeTests(dtc.instances.moment.momentZonedWithCrossZoneEquality) 
Example 90
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 91
Source File: JsonDecoderSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package types

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

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

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

                                                                               """

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

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

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

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

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

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

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

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

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

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


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

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

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

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

import cats.data.NonEmptyList
import org.scalacheck.Prop.forAll
import org.scalacheck.Gen
import org.specs2._
import roc.postgresql.failures._

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

  Failure
    ReadyForQueryDecodingFailure should have correct message         $readyForQueryDecodingFailure
    UnknownAuthenticationFailure should have correct message         $unknownAuthRequestFailure
    UnsupportedAuthenticationFailure should have correct message     $unsupportedAuthFailure
    PostgresqlStateMachineFailure should have correct message        $postgresqlStateMachineFailure
    UnknownPostgresqlMessageTypeFailure should have correct message  $unknownPostgresqlMessageTypeFailure
    PostgresqlMessageDecodingFailure must have a correct error message   $postgresqlMessageDecodingFailure
                                                                         """

  val readyForQueryDecodingFailure = forAll { c: Char =>
    val msg = s"Received unexpected Char $c from Postgres Server."
    val error = new ReadyForQueryDecodingFailure(c)
    error.getMessage must_== msg
  }

  val unknownAuthRequestFailure = forAll { n: Int =>
    val expectedMessage = s"Unknown Authentication Request Type: $n"
    val error           = new UnknownAuthenticationRequestFailure(n)
    error.getMessage must_== expectedMessage
  }

  val unsupportedAuthFailure = forAll { s: String =>
    val expectedMessage =
      s"Unsupported Authentication Failure. $s authentication is not supported."
    val error           = new UnsupportedAuthenticationFailure(s)
    error.getMessage must_== expectedMessage
  }
  
  val postgresqlStateMachineFailure = forAll { (s1: String, s2: String) =>
    val expectedMessage = s"State Transition from $s1 -> $s2 is undefined."
    val error           = new PostgresqlStateMachineFailure(s1, s2)
    error.getMessage must_== expectedMessage
  }
  
  val unknownPostgresqlMessageTypeFailure = forAll { c: Char =>
    val expectedMessage = s"Unknown Postgresql MessageType '$c'."
    val error           = new UnknownPostgresqlMessageTypeFailure(c)
    error.getMessage must_== expectedMessage
  }

  val postgresqlMessageDecodingFailure = forAll(genNELErrorResponse) { nel: NonEmptyList[String] =>
    val error = new PostgresqlMessageDecodingFailure(nel)
    val expectedMessage = nel.foldLeft("")(_ + _)
    expectedMessage must_== error.getMessage
  }

  private lazy val genErrorResponseString: Gen[String] = Gen.oneOf(
    "Required Severity Level was not present.",
    "Required SQLSTATE Code was not present.",
    "Required Message was not present."
  )
  private lazy val genNELErrorResponse: Gen[NonEmptyList[String]] = for {
    string  <-  genErrorResponseString
  } yield NonEmptyList.of(string)

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

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._

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

  PasswordMessage
    should MD5 encrypt a password with given salt           $pmEncrypt
                                                                            """

  val pmEncrypt = forAll { (user: String, pm: PasswordMessage, salt: Array[Byte]) =>
    val md = MessageDigest.getInstance("MD5")
    md.update((pm.password+ user).getBytes(StandardCharsets.UTF_8))
    val unsaltedHexStr = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("")(_ + _)
    val saltedBytes = unsaltedHexStr.getBytes ++ salt
    md.reset()
    md.update(saltedBytes)
    val passwd = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("md5")(_ + _)
    passwd must_== PasswordMessage.encryptMD5Passwd(user, pm.password, salt)
  }
  
  lazy val genByte: Gen[Byte] = arbitrary[Byte]
  lazy val genSalt: Gen[Array[Byte]] = Gen.containerOfN[Array, Byte](4, genByte)
  lazy val genPasswordMessage: Gen[PasswordMessage] = for {
    password    <-  arbitrary[String]
  } yield new PasswordMessage(password)
  implicit lazy val implicitPasswordMessage: Arbitrary[PasswordMessage] = 
    Arbitrary(genPasswordMessage)
} 
Example 95
Source File: StartupSpecs.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql

import com.twitter.finagle.client.StackClient
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._
import roc.postgresql.Startup.{Database, Credentials}

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

  Database
    must have correct database name $testDatabase

  Credentials
    must have correct username and password $testUserAndPasswd

  Startup
    must have correct database, username, and password              $testStartupClass
    must have correct defaults for username, password, and database $testStartupDefaults
                                                                            """

  val testDatabase = forAll { dbContainer: DbContainer =>
    val database = dbContainer.db
    database.db must_== dbContainer.dbName
  }

  val testUserAndPasswd = forAll { credentialsContainer: CredentialsContainer =>
    val expectedCredentials = Credentials(credentialsContainer.username, 
      credentialsContainer.passwd) 
    credentialsContainer.credentials must_== expectedCredentials
  }

  val testStartupClass = forAll { startupContainer: StartupContainer =>
    val expectedStartup = Startup(startupContainer.username, startupContainer.passwd,
      startupContainer.database)
    startupContainer.startup must_== expectedStartup
  }

  val testStartupDefaults= {
    val expectedStartup = Startup("postgres", "postgres", "postgres")
    Startup(StackClient.defaultParams) must_== expectedStartup
  }

  case class DbContainer(db: Database, dbName: String)
  private lazy val databaseGen: Gen[DbContainer] = for {
    db  <-  arbitrary[String]
  } yield DbContainer(Database(db), db)
  implicit lazy val arbitraryDatabase: Arbitrary[DbContainer] =
    Arbitrary(databaseGen)

  case class CredentialsContainer(credentials: Credentials, username: String, passwd: String)
  private lazy val credentialsContainerGen: Gen[CredentialsContainer] = for {
    username    <-  arbitrary[String]
    password    <-  arbitrary[String]
  } yield CredentialsContainer(Credentials(username, password), username, password)
  implicit lazy val arbitraryCredentialsContainer: Arbitrary[CredentialsContainer] =
    Arbitrary(credentialsContainerGen)

  case class StartupContainer(startup: Startup, username: String, passwd: String, database: String)
  private lazy val startupContainerGen: Gen[StartupContainer] = for {
    username    <-  arbitrary[String]
    passwd      <-  arbitrary[String]
    database    <-  arbitrary[String]
  } yield StartupContainer(Startup(username, passwd, database), username, passwd, database)
  implicit lazy val arbitraryStartupContainer: Arbitrary[StartupContainer] =
    Arbitrary(startupContainerGen)
} 
Example 96
Source File: ResultsSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._
import org.specs2.mock.Mockito
import roc.postgresql.failures.ElementNotFoundFailure

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

  Row
    get(column) must throw ElementNotFound failure for unknown column name  $columnNotFound
                                                                           """

  val columnNotFound = forAll { sym: Symbol =>
    val row = new Row(List.empty[Element])
    row.get(sym) must throwA[ElementNotFoundFailure]
  }

  lazy val genSymbol: Gen[Symbol] = for {
    str <-  arbitrary[String]
  } yield Symbol(str)
  implicit lazy val arbitrarySymbol: Arbitrary[Symbol] =
    Arbitrary(genSymbol)
} 
Example 97
Source File: modelArbitratries.scala    From sbt-org-policies   with Apache License 2.0 5 votes vote down vote up
package sbtorgpolicies.arbitraries

import org.scalacheck.{Arbitrary, Gen}
import sbtorgpolicies.model.{ApacheLicense, CustomLicense, License, MITLicense}
import java.net.URL

trait modelArbitratries {

  implicit val URLArbitratry: Arbitrary[URL] =
    Arbitrary {
      for {
        protocol <- Gen.oneOf("http", "https", "ftp", "file")
        domain   <- Gen.alphaNumStr
        tld      <- Gen.oneOf("com", "io", "net")
        path     <- Arbitrary.arbitrary[String]
      } yield new URL(s"$protocol://$domain.$tld/$path")
    }

  val customLicenseArbitrary: Arbitrary[License] =
    Arbitrary {
      for {
        name <- Arbitrary.arbitrary[String]
        url  <- Arbitrary.arbitrary[URL]
      } yield CustomLicense(name, url)
    }

  implicit val licenseArbitrary: Arbitrary[License] =
    Arbitrary {
      Gen.oneOf[License](
        Gen.oneOf[License](MITLicense, ApacheLicense),
        customLicenseArbitrary.arbitrary
      )
    }
} 
Example 98
Source File: TemplateArbitraries.scala    From sbt-org-policies   with Apache License 2.0 5 votes vote down vote up
package sbtorgpolicies.arbitraries

import org.scalacheck.{Arbitrary, Gen}
import sbtorgpolicies.templates._

trait TemplateArbitraries {

  implicit val replaceableArbitrary: Arbitrary[ReplaceableT[String]] =
    Arbitrary(Gen.alphaStr map (ReplaceableT(_)))

  implicit val replacementsTupleArbitrary: Arbitrary[(String, Replaceable)] =
    Arbitrary {
      for {
        key         <- Gen.identifier
        replaceable <- replaceableArbitrary.arbitrary
      } yield (key, replaceable)
    }

  implicit val replacementsArbitrary: Arbitrary[Replacements] =
    Arbitrary(Gen.mapOf(replacementsTupleArbitrary.arbitrary))
}

object TemplateArbitraries extends TemplateArbitraries 
Example 99
Source File: ExceptionArbitraries.scala    From sbt-org-policies   with Apache License 2.0 5 votes vote down vote up
package sbtorgpolicies.arbitraries

import org.scalacheck.{Arbitrary, Gen}
import sbtorgpolicies.exceptions.{IOException, ValidationException}

trait ExceptionArbitraries {

  val exceptionMessage: String = "Generated Exception"

  implicit val ioExceptionArbitrary: Arbitrary[IOException] = Arbitrary {
    for {
      msg            <- Gen.alphaStr
      maybeException <- Gen.option(new RuntimeException(exceptionMessage))
    } yield IOException(msg, maybeException)
  }

  implicit val validationExceptionArbitrary: Arbitrary[ValidationException] = Arbitrary {
    for {
      msg            <- Gen.alphaStr
      maybeException <- Gen.option(new RuntimeException(exceptionMessage))
    } yield ValidationException(msg, maybeException)
  }

}

object ExceptionArbitraries extends ExceptionArbitraries 
Example 100
Source File: badgeArbitraries.scala    From sbt-org-policies   with Apache License 2.0 5 votes vote down vote up
package sbtorgpolicies.arbitraries

import org.scalacheck.{Arbitrary, Gen}
import sbtorgpolicies.model.License
import sbtorgpolicies.templates.badges.{BadgeInformation, ScalaJSBadge}

trait badgeArbitraries extends modelArbitratries {

  implicit val badgeInformationArbitrary: Arbitrary[BadgeInformation] =
    Arbitrary {
      for {
        owner              <- Arbitrary.arbitrary[String]
        repo               <- Arbitrary.arbitrary[String]
        branch             <- Arbitrary.arbitrary[String]
        sbtPlugin          <- Arbitrary.arbitrary[Boolean]
        libOrg             <- Arbitrary.arbitrary[String]
        libName            <- Arbitrary.arbitrary[String]
        libVersion         <- Arbitrary.arbitrary[String]
        scalaBinaryVersion <- Arbitrary.arbitrary[String]
        sbtBinaryVersion   <- Arbitrary.arbitrary[String]
        scalaJSV           <- Gen.option(scalaJSVArbitrary.arbitrary)
        license            <- Arbitrary.arbitrary[Option[License]]
      } yield BadgeInformation(
        owner,
        repo,
        branch,
        sbtPlugin,
        libOrg,
        libName,
        libVersion,
        scalaBinaryVersion,
        sbtBinaryVersion,
        scalaJSV,
        license
      )
    }

  val scalaJSVArbitrary: Arbitrary[String] = {
    val controlledArbitrary: Arbitrary[String] = Arbitrary {
      for {
        major <- Gen.oneOf(Seq(0))
        minor <- Gen.oneOf(Seq(6))
        patch <- Gen.chooseNum(0, 100)
      } yield s"$major.$minor.$patch"
    }

    val randomArbitrary: Arbitrary[String] = Arbitrary {
      for {
        major <- Gen.posNum[Int]
        minor <- Gen.posNum[Int]
        patch <- Gen.posNum[Int]
      } yield s"$major.$minor.$patch"
    }

    Arbitrary {
      Gen.oneOf[String](controlledArbitrary.arbitrary, randomArbitrary.arbitrary)
    }
  }

  implicit val scalaJSBadgeArbitrary: Arbitrary[ScalaJSBadge] =
    Arbitrary {
      for {
        info <- Arbitrary.arbitrary[BadgeInformation]
      } yield ScalaJSBadge(info)
    }

} 
Example 101
Source File: DCollectionGen.scala    From kontextfrei   with Apache License 2.0 5 votes vote down vote up
package com.danielwestheide.kontextfrei.scalatest

import com.danielwestheide.kontextfrei.DCollectionOps
import org.scalacheck.{Arbitrary, Gen}

import scala.reflect.ClassTag

trait DCollectionGen {

  def dcollectionOf[A: ClassTag, DCollection[_]](gen: => Gen[A])(
      implicit ops: DCollectionOps[DCollection]): Gen[DCollection[A]] = {
    Gen.nonEmptyListOf(gen).map(ops.unit(_))
  }

  implicit def arbDCollection[A: ClassTag, DCollection[_]](
      implicit ops: DCollectionOps[DCollection],
      arbA: Arbitrary[A]): Arbitrary[DCollection[A]] =
    Arbitrary(dcollectionOf(arbA.arbitrary))
}

object DCollectionGen extends DCollectionGen 
Example 102
Source File: CookieSignerTests.scala    From tsec   with MIT License 5 votes vote down vote up
package tsec

import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import tsec.cookies.CookieSigner
import tsec.mac.jca._
import cats.instances.either._
import cats.syntax.either._
import tsec.mac.MessageAuth

class CookieSignerTests extends TestSpec {

  implicit val arbitraryUUID: Arbitrary[UUID] = Arbitrary.apply(Gen.uuid)

  def signerTests[A](implicit M: MessageAuth[MacErrorM, A, MacSigningKey], keyGen: MacKeyGen[MacErrorM, A]) = {
    behavior of "CookieSigner for algo " + M.algorithm

    it should "Sign and verify any cookie properly with coercion" in {
      forAll { (s: String) =>
        val verified = for {
          key    <- keyGen.generateKey
          signed <- CookieSigner.sign(s, System.currentTimeMillis().toString, key)
          verify <- CookieSigner.verify(signed, key)
        } yield verify

        if (s.isEmpty)
          verified mustBe Left(MacSigningError("Cannot sign an empty string"))
        else
          verified mustBe Right(true)
      }
    }

    it should "Sign and retrieve properly for any properly signed message" in {
      forAll { (s: String) =>
        val verified = for {
          key    <- keyGen.generateKey
          signed <- CookieSigner.sign(s, System.currentTimeMillis().toString, key)
          verify <- CookieSigner.verifyAndRetrieve(signed, key)
        } yield verify

        if (s.isEmpty)
          verified mustBe Left(MacSigningError("Cannot sign an empty string"))
        else
          verified mustBe Right(s)
      }
    }

    it should "Not return true for verifying an incorrect key" in {
      forAll { (s: String) =>
        val verified = for {
          key    <- keyGen.generateKey
          key2   <- keyGen.generateKey
          signed <- CookieSigner.sign(s, System.currentTimeMillis().toString, key)
          verify <- CookieSigner.verify(signed, key2)
        } yield verify

        if (s.isEmpty)
          verified mustBe Left(MacSigningError("Cannot sign an empty string"))
        else
          verified mustBe Right(false)
      }
    }

    it should "verify UUIDs properly" in {
      forAll { (s: UUID) =>
        val verified = for {
          key    <- keyGen.generateKey
          signed <- CookieSigner.sign(s.toString, System.currentTimeMillis().toString, key)
          verify <- CookieSigner.verifyAndRetrieve(signed, key)
        } yield UUID.fromString(verify)
        verified mustBe Right(s)
      }
    }
  }

  signerTests[HMACSHA1]
  signerTests[HMACSHA256]
  signerTests[HMACSHA384]
  signerTests[HMACSHA512]

} 
Example 103
Source File: SodiumPWHashTest.scala    From tsec   with MIT License 5 votes vote down vote up
package tsec.libsodium

import cats.effect.IO
import org.scalacheck.{Arbitrary, Gen}
import tsec.passwordhashers._
import tsec.passwordhashers.libsodium._
import tsec.passwordhashers.libsodium.internal.SodiumPasswordHasher

class SodiumPWHashTest extends SodiumSpec {

  implicit val genStringAscii: Gen[String] = {
    val choose = Gen.choose(33.toChar, 126.toChar)
    Gen.listOf(choose).map(_.mkString)
  }
  implicit val arbStr = Arbitrary(genStringAscii)

  def testPasswordHash[P, S](hasher: SodiumPasswordHasher[P], stren: S)(
      implicit p: PWStrengthParam[P, S],
      P: PasswordHasher[IO, P]
  ) = {
    behavior of s"${hasher.hashingAlgorithm} with strength $stren"

    it should "hash and verify properly" in {
      forAll { (s: String) =>
        val program = for {
          hashed   <- hasher.hashpwWithStrength[IO, S](s, stren)
          verified <- hasher.checkpwBool[IO](s, hashed)
        } yield verified

        if (!s.isEmpty) {
          program.unsafeRunSync() mustBe true
        } else
          program.attempt.unsafeRunSync() mustBe a[Left[SodiumPasswordError, _]]
      }
    }

    it should "hash and verify properly (short circuit)" in {
      forAll { (s: String) =>
        val program = for {
          hashed <- hasher.hashpwWithStrength[IO, S](s, stren)
          _      <- hasher.checkPassShortCircuit[IO](s, hashed)
        } yield ()

        if (!s.isEmpty) {
          program.unsafeRunSync() mustBe (())
        } else
          program.attempt.unsafeRunSync() mustBe a[Left[SodiumPasswordError, _]]
      }
    }

    it should "not verify for an incorrect password" in {
      forAll { (s: String, s2: String) =>
        val program = for {
          hashed   <- hasher.hashpwWithStrength[IO, S](s, stren)
          verified <- hasher.checkpwBool[IO](s2, hashed)
        } yield verified
        if (!s.isEmpty)
          program.unsafeRunSync() mustBe s == s2
        else
          program.attempt.unsafeRunSync() mustBe a[Left[SodiumPasswordError, _]]
      }
    }

    it should "not verify for an incorrect password(short circuit)" in {
      forAll { (s: String, s2: String) =>
        val program = for {
          hashed   <- hasher.hashpwWithStrength[IO, S](s, stren)
          verified <- hasher.checkPassShortCircuit[IO](s2, hashed)
        } yield verified
        if (!s.isEmpty && s == s2)
          program.unsafeRunSync() mustBe (())
        else
          program.attempt.unsafeRunSync() mustBe a[Left[SodiumPasswordError, _]]
      }
    }

  }

  testPasswordHash(Argon2, PasswordStrength.MinStrength)
  testPasswordHash(Argon2, PasswordStrength.InteractiveStrength)
  testPasswordHash(Argon2, PasswordStrength.ModerateStrength)
//  testPasswordHash(Argon2, PasswordStrength.SensitiveStrength) //This takes _forever_

  testPasswordHash(SodiumSCrypt, PasswordStrength.MinStrength)
  testPasswordHash(SodiumSCrypt, PasswordStrength.InteractiveStrength)
//  testPasswordHash(SodiumSCrypt, PasswordStrength.SensitiveStrength) //This takes _forever_

} 
Example 104
Source File: KeyDerivationTest.scala    From tsec   with MIT License 5 votes vote down vote up
package tsec.libsodium

import cats.effect.IO
import org.scalacheck.Gen
import tsec.common._
import tsec.kdf.libsodium.KeyDerivation

class KeyDerivationTest extends SodiumSpec {

  behavior of "Key derivation"

  it should "generate different keys for different id's & context" in {
    val keyLengthGen = Gen.choose(ScalaSodium.crypto_kdf_BYTES_MIN, ScalaSodium.crypto_kdf_BYTES_MAX)
    val contextGen   = Gen.listOfN(ScalaSodium.crypto_kdf_CONTEXTBYTES, Gen.alphaChar).map(_.mkString)
    val master       = KeyDerivation.generateKey[IO].unsafeRunSync()

    forAll(keyLengthGen, contextGen) { (n: Int, context: String) =>
      val program = for {
        k1 <- KeyDerivation.deriveKey[IO](master, n, 1, context)
        k2 <- KeyDerivation.deriveKey[IO](master, n, 2, context)
        k3 <- KeyDerivation.deriveKey[IO](master, n, 3, context)
      } yield (k1, k2, k3)

      val result = program.unsafeRunSync()
      result._1 must not be (result._2)
      result._2 must not be (result._3)
    }
  }

  it should "fail generating derived key for invalid context length" in {
    forAll { (context: String) =>
      val ctx = context.utf8Bytes

      val program = for {
        master <- KeyDerivation.generateKey[IO]
        _      <- KeyDerivation.deriveKey[IO](master, 16, 1, context)
      } yield ()

      val result = program.attempt.unsafeRunSync()

      if (ctx.length != ScalaSodium.crypto_kdf_CONTEXTBYTES)
        result mustBe a[Left[Exception, _]]
      else
        result mustBe a[Right[_, Unit]]
    }
  }

  it should "fail generating derived key for invalid key length" in {
    forAll { (l: Int) =>
      val program = for {
        master <- KeyDerivation.generateKey[IO]
        context = "Examples"
        _ <- KeyDerivation.deriveKey[IO](master, l, 1, context)
      } yield ()

      val result = program.attempt.unsafeRunSync()

      if (ScalaSodium.crypto_kdf_BYTES_MIN <= l && ScalaSodium.crypto_kdf_BYTES_MAX >= l)
        result mustBe a[Right[_, Unit]]
      else
        result mustBe a[Left[Exception, _]]
    }
  }

} 
Example 105
Source File: LiteralGenerator.scala    From XSQL   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.catalyst.expressions

import java.sql.{Date, Timestamp}

import org.scalacheck.{Arbitrary, Gen}

import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.CalendarInterval


object LiteralGenerator {

  lazy val byteLiteralGen: Gen[Literal] =
    for { b <- Arbitrary.arbByte.arbitrary } yield Literal.create(b, ByteType)

  lazy val shortLiteralGen: Gen[Literal] =
    for { s <- Arbitrary.arbShort.arbitrary } yield Literal.create(s, ShortType)

  lazy val integerLiteralGen: Gen[Literal] =
    for { i <- Arbitrary.arbInt.arbitrary } yield Literal.create(i, IntegerType)

  lazy val longLiteralGen: Gen[Literal] =
    for { l <- Arbitrary.arbLong.arbitrary } yield Literal.create(l, LongType)

  lazy val floatLiteralGen: Gen[Literal] =
    for {
      f <- Gen.chooseNum(Float.MinValue / 2, Float.MaxValue / 2,
        Float.NaN, Float.PositiveInfinity, Float.NegativeInfinity)
    } yield Literal.create(f, FloatType)

  lazy val doubleLiteralGen: Gen[Literal] =
    for {
      f <- Gen.chooseNum(Double.MinValue / 2, Double.MaxValue / 2,
        Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity)
    } yield Literal.create(f, DoubleType)

  // TODO cache the generated data
  def decimalLiteralGen(precision: Int, scale: Int): Gen[Literal] = {
    assert(scale >= 0)
    assert(precision >= scale)
    Arbitrary.arbBigInt.arbitrary.map { s =>
      val a = (s % BigInt(10).pow(precision - scale)).toString()
      val b = (s % BigInt(10).pow(scale)).abs.toString()
      Literal.create(
        Decimal(BigDecimal(s"$a.$b"), precision, scale),
        DecimalType(precision, scale))
    }
  }

  lazy val stringLiteralGen: Gen[Literal] =
    for { s <- Arbitrary.arbString.arbitrary } yield Literal.create(s, StringType)

  lazy val binaryLiteralGen: Gen[Literal] =
    for { ab <- Gen.listOf[Byte](Arbitrary.arbByte.arbitrary) }
      yield Literal.create(ab.toArray, BinaryType)

  lazy val booleanLiteralGen: Gen[Literal] =
    for { b <- Arbitrary.arbBool.arbitrary } yield Literal.create(b, BooleanType)

  lazy val dateLiteralGen: Gen[Literal] =
    for { d <- Arbitrary.arbInt.arbitrary } yield Literal.create(new Date(d), DateType)

  lazy val timestampLiteralGen: Gen[Literal] =
    for { t <- Arbitrary.arbLong.arbitrary } yield Literal.create(new Timestamp(t), TimestampType)

  lazy val calendarIntervalLiterGen: Gen[Literal] =
    for { m <- Arbitrary.arbInt.arbitrary; s <- Arbitrary.arbLong.arbitrary}
      yield Literal.create(new CalendarInterval(m, s), CalendarIntervalType)


  // Sometimes, it would be quite expensive when unlimited value is used,
  // for example, the `times` arguments for StringRepeat would hang the test 'forever'
  // if it's tested against Int.MaxValue by ScalaCheck, therefore, use values from a limited
  // range is more reasonable
  lazy val limitedIntegerLiteralGen: Gen[Literal] =
    for { i <- Gen.choose(-100, 100) } yield Literal.create(i, IntegerType)

  def randomGen(dt: DataType): Gen[Literal] = {
    dt match {
      case ByteType => byteLiteralGen
      case ShortType => shortLiteralGen
      case IntegerType => integerLiteralGen
      case LongType => longLiteralGen
      case DoubleType => doubleLiteralGen
      case FloatType => floatLiteralGen
      case DateType => dateLiteralGen
      case TimestampType => timestampLiteralGen
      case BooleanType => booleanLiteralGen
      case StringType => stringLiteralGen
      case BinaryType => binaryLiteralGen
      case CalendarIntervalType => calendarIntervalLiterGen
      case DecimalType.Fixed(precision, scale) => decimalLiteralGen(precision, scale)
      case dt => throw new IllegalArgumentException(s"not supported type $dt")
    }
  }
} 
Example 106
Source File: hierarchyGen.scala    From HANAVora-Extensions   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.test

import org.apache.spark.sql.types.{LongType, Node}
import org.scalacheck.{Arbitrary, Gen}

import scala.util.Random
import scalaz._
import Scalaz._
import scalaz.scalacheck.ScalazArbitrary._

// scalastyle:off file.size.limit

object HierarchyGen {

  val MIN_SIZE_TREE = 6
  val MAX_SIZE_TREE = 100

  
  def next(): Long = {
    synchronized {
      if (currentSeq == Long.MaxValue) {
        currentSeq = Long.MinValue
      }
      val result = currentSeq
      currentSeq += 1
      result
    }
  }

  def arb: Arbitrary[Long] = Arbitrary {
    gen
  }

  def gen: Gen[Long] = Gen.resultOf[Int,Long] { x => next() }
} 
Example 107
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 108
Source File: Generators.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres

import java.nio.charset.StandardCharsets
import java.time.{ZonedDateTime, _}
import java.time.temporal.JulianFields
import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import Arbitrary.arbitrary
import com.twitter.finagle.postgres.values.Interval

object Generators {
  //need a more sensible BigDecimal generator, because ScalaCheck goes crazy with it and we can't even stringify them
  //this will be sufficient to test the decoder
  implicit val arbBD: Arbitrary[BigDecimal] = Arbitrary(for {
    precision <- Gen.choose(1, 32)
    scale <- Gen.choose(-precision, precision)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)))

  implicit val arbDate = Arbitrary[LocalDate](for {
    julian <- Gen.choose(1721060, 5373484)  //Postgres date parser doesn't like dates outside year range 0000-9999
  } yield LocalDate.now().`with`(JulianFields.JULIAN_DAY, julian))

  implicit val arbTime: Arbitrary[LocalTime] = Arbitrary[LocalTime](for {
    usec <- Gen.choose(0L, 24L * 60 * 60 * 1000000 - 1)
  } yield LocalTime.ofNanoOfDay(usec * 1000))

  implicit val arbInstant = Arbitrary[Instant](for {
    milli <- Gen.posNum[Long]
  } yield Instant.ofEpochMilli(milli))

  implicit val arbTimestamp = Arbitrary[LocalDateTime](for {
    milli <- Gen.posNum[Long]
  } yield LocalDateTime.ofInstant(Instant.ofEpochMilli(milli), ZoneId.systemDefault()))

  implicit val arbTimestampTz = Arbitrary[ZonedDateTime](for {
    milli <- Gen.posNum[Long]
  } yield ZonedDateTime.ofInstant(Instant.ofEpochMilli(milli), ZoneId.systemDefault()))

  implicit val arbZoneOffset = Arbitrary(Gen.choose(-12, 12).map(ZoneOffset.ofHours))

  implicit val arbInterval = Arbitrary(for {
    months <- Gen.choose(-120, 120)
    years <- Gen.choose(-10, 10)
    days <- Gen.choose(-50, 50)
    hours <- Gen.choose(-50, 50)
    minutes <- Gen.choose(0, 59)
    seconds <- Gen.choose(0, 59)
  } yield Interval(
    Duration.ofSeconds(seconds).plusMinutes(minutes).plusHours(hours),
    Period.ofMonths(months).plusYears(years).plusDays(days)
  ))

  implicit val arbTimeTz = Arbitrary[OffsetTime](for {
    time <- arbitrary[LocalTime]
    offs <- arbitrary[ZoneOffset]
  } yield time.atOffset(offs))

  implicit val arbUUID = Arbitrary[UUID](Gen.uuid)

  // arbitrary string that only contains valid UTF-8 characters
  val utf8 = StandardCharsets.UTF_8.newEncoder()
  implicit val arbUTF8String = Arbitrary(arbitrary[String].filter {
    str => utf8.canEncode(str) && !str.contains('\u0000')
  })

  // TODO: can empty maps be supported?
  implicit val arbHStore: Arbitrary[Map[String, Option[String]]] = Arbitrary(
    Gen.mapOf(for {
      k <- Gen.identifier
      v <- Gen.oneOf(Gen.alphaStr.map(Some(_)), Gen.const(None))
    } yield (k, v)).suchThat(_.nonEmpty)
  )

  // postgres has slightly different precision rules, but that doesn't mean the decoder isn't working
  implicit val arbFloat = Arbitrary[Float](for {
    precision <- Gen.choose(1, 6)
    scale <- Gen.choose(-10, 10)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)).toFloat)

  implicit val arbDouble = Arbitrary[Double](for {
    precision <- Gen.choose(1, 15)
    scale <- Gen.choose(-20, 20)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)).toDouble)
} 
Example 109
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.freespec.AnyFreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends AnyFreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 110
Source File: PlayJsonFormatSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalatest

import org.scalacheck.ops._
import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalatest.FlatSpecLike
import play.api.libs.json.Format
import play.api.libs.json.scalacheck.PlayJsonFormatTests

import scala.reflect.ClassTag
import scala.testing.scalatest.ScalaTestBridge


class PlayJsonFormatSpec[T](examples: Seq[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T])
  extends PlayJsonFormatTests[T](examples, playFormat, clsTag, shrink)
  with FlatSpecLike
  with ScalaTestBridge {

  def this(gen: Gen[T], samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) =
    this(gen.toIterator.take(samples).toSeq)

  def this(gen: Gen[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) = this(gen, 100)

  def this(samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary, samples)

  def this()(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary)
} 
Example 111
Source File: DurationGenerators.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalacheck

import org.scalacheck.{Arbitrary, Gen}

import scala.concurrent.duration._
import scala.concurrent.duration.ops.v4._
import scala.language.implicitConversions

trait DurationGenerators {

  implicit val arbTimeUnit: Arbitrary[TimeUnit] = Arbitrary {
    Gen.oneOf(
      DAYS,
      HOURS,
      MICROSECONDS,
      MILLISECONDS,
      MINUTES,
      NANOSECONDS,
      SECONDS
    )
  }

  
  private val minNanos = Long.MinValue + 1
  private val maxNanos = Long.MaxValue

  implicit def arbFiniteDuration(implicit timeUnitArb: Arbitrary[TimeUnit]): Arbitrary[FiniteDuration] = Arbitrary {
    for {
      length <- Gen.chooseNum(minNanos, maxNanos)
      unit <- timeUnitArb.arbitrary
    } yield Duration(length, NANOSECONDS).toUnitPrecise(unit)
  }

  implicit def arbDuration(implicit timeUnitArb: Arbitrary[TimeUnit]): Arbitrary[Duration] = Arbitrary {
    for {
      length <- Gen.oneOf(
        Gen.chooseNum(minNanos, maxNanos),
        Gen.oneOf(Double.NegativeInfinity, Double.MinPositiveValue, Double.PositiveInfinity, Double.NaN)
      )
      unit <- timeUnitArb.arbitrary
    } yield length match {
      case nanos: Long =>
        Duration(nanos, NANOSECONDS).toUnitPrecise(unit)
      case inf: Double =>
        Duration(inf, NANOSECONDS)
    }
  }

}

object DurationGenerators extends DurationGenerators 
Example 112
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.FreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatest.prop.GeneratorDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends FreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 113
Source File: JsValueOpsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.FlatSpec
import org.scalatest.prop.GeneratorDrivenPropertyChecks._
import play.api.libs.json._
import play.api.libs.json.scalacheck.JsValueGenerators

case class Troll(value: String)

object Troll {
  implicit val format: OFormat[Troll] = Json.format[Troll]
}

class JsValueOpsSpec extends FlatSpec
  with CompatibilityImplicits
  with JsValueGenerators {

  implicit val arbTroll: Arbitrary[Troll] = Arbitrary(Gen.identifier.map(Troll(_)))

  "transformAs" should "use the implicit JsonTransform" in {
    val troll = JsString("trolled :)")
    implicit val transform: JsonTransform[Troll] = JsonTransform(_ => troll)
    forAll() { json: JsValue =>
      assertResult(troll) {
        json.transformAs[Troll]
      }
    }
  }

  behavior of "asOrThrow"

  it should "convert the json as normal" in {
    implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value"))
    forAll() { troll: Troll =>
      assertResult(troll) {
        Json.toJson(troll).asOrThrow[Troll]
      }
    }
  }

  it should "transform the json when throwing an exception" in {
    implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value"))
    forAll() { json: JsObject =>
      val ex = intercept[InvalidJsonException] {
        json.asOrThrow[Troll]
      }
      assertResult(JsonTransform.RedactedValue) {
        (ex.json \ "value").get
      }
    }
  }
} 
Example 114
Source File: PlayJsonFormatSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalatest

import org.scalacheck.ops._
import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalatest.flatspec.AnyFlatSpecLike
import play.api.libs.json.Format
import play.api.libs.json.scalacheck.PlayJsonFormatTests

import scala.reflect.ClassTag
import scala.testing.scalatest.ScalaTestBridge


class PlayJsonFormatSpec[T](examples: Seq[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T])
  extends PlayJsonFormatTests[T](examples, playFormat, clsTag, shrink)
  with AnyFlatSpecLike
  with ScalaTestBridge {

  def this(gen: Gen[T], samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) =
    this(gen.toIterator.take(samples).toSeq)

  def this(gen: Gen[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) = this(gen, 100)

  def this(samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary, samples)

  def this()(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary)
} 
Example 115
Source File: DurationGenerators.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalacheck

import org.scalacheck.{Arbitrary, Gen}

import scala.concurrent.duration._
import scala.concurrent.duration.ops.v4._
import scala.language.implicitConversions

trait DurationGenerators {

  implicit val arbTimeUnit: Arbitrary[TimeUnit] = Arbitrary {
    Gen.oneOf(
      DAYS,
      HOURS,
      MICROSECONDS,
      MILLISECONDS,
      MINUTES,
      NANOSECONDS,
      SECONDS
    )
  }

  
  private val minNanos = Long.MinValue + 1
  private val maxNanos = Long.MaxValue

  implicit def arbFiniteDuration(implicit timeUnitArb: Arbitrary[TimeUnit]): Arbitrary[FiniteDuration] = Arbitrary {
    for {
      length <- Gen.chooseNum(minNanos, maxNanos)
      unit <- timeUnitArb.arbitrary
    } yield Duration(length, NANOSECONDS).toUnitPrecise(unit)
  }

  implicit def arbDuration(implicit timeUnitArb: Arbitrary[TimeUnit]): Arbitrary[Duration] = Arbitrary {
    for {
      length <- Gen.oneOf(
        Gen.chooseNum(minNanos, maxNanos),
        Gen.oneOf(Double.NegativeInfinity, Double.MinPositiveValue, Double.PositiveInfinity, Double.NaN)
      )
      unit <- timeUnitArb.arbitrary
    } yield length match {
      case nanos: Long =>
        Duration(nanos, NANOSECONDS).toUnitPrecise(unit)
      case inf: Double =>
        Duration(inf, NANOSECONDS)
    }
  }

}

object DurationGenerators extends DurationGenerators 
Example 116
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.freespec.AnyFreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends AnyFreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 117
Source File: JsValueOpsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._
import play.api.libs.json._
import play.api.libs.json.scalacheck.JsValueGenerators

case class Troll(value: String)

object Troll {
  implicit val format: OFormat[Troll] = Json.format[Troll]
}

class JsValueOpsSpec extends AnyFlatSpec
  with CompatibilityImplicits
  with JsValueGenerators {

  implicit val arbTroll: Arbitrary[Troll] = Arbitrary(Gen.identifier.map(Troll(_)))

  "transformAs" should "use the implicit JsonTransform" in {
    val troll = JsString("trolled :)")
    implicit val transform: JsonTransform[Troll] = JsonTransform(_ => troll)
    forAll() { json: JsValue =>
      assertResult(troll) {
        json.transformAs[Troll]
      }
    }
  }

  behavior of "asOrThrow"

  it should "convert the json as normal" in {
    implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value"))
    forAll() { troll: Troll =>
      assertResult(troll) {
        Json.toJson(troll).asOrThrow[Troll]
      }
    }
  }

  it should "transform the json when throwing an exception" in {
    implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value"))
    forAll() { json: JsObject =>
      val ex = intercept[InvalidJsonException] {
        json.asOrThrow[Troll]
      }
      assertResult(JsonTransform.RedactedValue) {
        (ex.json \ "value").get
      }
    }
  }
} 
Example 118
Source File: PlayJsonFormatSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalatest

import org.scalacheck.ops._
import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalatest.Tag
import org.scalatest.flatspec.AnyFlatSpecLike
import play.api.libs.json.Format
import play.api.libs.json.scalacheck.PlayJsonFormatTests

import scala.reflect.ClassTag
import scala.testing.scalatest.ScalaTestBridge


class PlayJsonFormatSpec[T](examples: Seq[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T])
  extends PlayJsonFormatTests[T](examples, playFormat, clsTag, shrink)
  with AnyFlatSpecLike
  with ScalaTestBridge {

  override def registerTest(testText: String, testTags: Tag*)(testFun: => Unit): Unit = {
    super[AnyFlatSpecLike].registerTest(testText, testTags: _*)(testFun)
  }

  def this(gen: Gen[T], samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) =
    this(gen.toIterator.take(samples).toSeq)

  def this(gen: Gen[T])(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T]) = this(gen, 100)

  def this(samples: Int)(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary, samples)

  def this()(implicit playFormat: Format[T], clsTag: ClassTag[T], shrink: Shrink[T], arb: Arbitrary[T]) =
    this(arb.arbitrary)
} 
Example 119
Source File: DurationGenerators.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.scalacheck

import org.scalacheck.{Arbitrary, Gen}

import scala.concurrent.duration._
import scala.concurrent.duration.ops.v4._
import scala.language.implicitConversions

trait DurationGenerators {

  implicit val arbTimeUnit: Arbitrary[TimeUnit] = Arbitrary {
    Gen.oneOf(
      DAYS,
      HOURS,
      MICROSECONDS,
      MILLISECONDS,
      MINUTES,
      NANOSECONDS,
      SECONDS
    )
  }

  
  private val minNanos = Long.MinValue + 1
  private val maxNanos = Long.MaxValue

  implicit def arbFiniteDuration(implicit timeUnitArb: Arbitrary[TimeUnit]): Arbitrary[FiniteDuration] = Arbitrary {
    for {
      length <- Gen.chooseNum(minNanos, maxNanos)
      unit <- timeUnitArb.arbitrary
    } yield Duration(length, NANOSECONDS).toUnitPrecise(unit)
  }

  implicit def arbDuration(implicit timeUnitArb: Arbitrary[TimeUnit]): Arbitrary[Duration] = Arbitrary {
    for {
      length <- Gen.oneOf(
        Gen.chooseNum(minNanos, maxNanos),
        Gen.oneOf(Double.NegativeInfinity, Double.MinPositiveValue, Double.PositiveInfinity, Double.NaN)
      )
      unit <- timeUnitArb.arbitrary
    } yield length match {
      case nanos: Long =>
        Duration(nanos, NANOSECONDS).toUnitPrecise(unit)
      case inf: Double =>
        Duration(inf, NANOSECONDS)
    }
  }

}

object DurationGenerators extends DurationGenerators 
Example 120
Source File: JsValueOpsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._
import play.api.libs.json._
import play.api.libs.json.scalacheck.JsValueGenerators

case class Troll(value: String)

object Troll {
  implicit val format: OFormat[Troll] = Json.format[Troll]
}

class JsValueOpsSpec extends AnyFlatSpec
  with CompatibilityImplicits
  with JsValueGenerators {

  implicit val arbTroll: Arbitrary[Troll] = Arbitrary(Gen.identifier.map(Troll(_)))

  "transformAs" should "use the implicit JsonTransform" in {
    val troll = JsString("trolled :)")
    implicit val transform: JsonTransform[Troll] = JsonTransform(_ => troll)
    forAll() { json: JsValue =>
      assertResult(troll) {
        json.transformAs[Troll]
      }
    }
  }

  behavior of "asOrThrow"

  it should "convert the json as normal" in {
    implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value"))
    forAll() { troll: Troll =>
      assertResult(troll) {
        Json.toJson(troll).asOrThrow[Troll]
      }
    }
  }

  it should "transform the json when throwing an exception" in {
    implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value"))
    forAll() { json: JsObject =>
      val ex = intercept[InvalidJsonException] {
        json.asOrThrow[Troll]
      }
      assertResult(JsonTransform.RedactedValue) {
        (ex.json \ "value").get
      }
    }
  }
} 
Example 121
Source File: FeaturePropSpec.scala    From spark-tda   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.ml.feature

import org.apache.spark.ml.linalg.{Vector, Vectors, DenseVector}
import org.apache.spark.ml.linalg.SQLDataTypes.VectorType
import org.apache.spark.sql.{SparkSession, DataFrame}
import org.apache.spark.sql.types.{
  StructField,
  IntegerType,
  DoubleType,
  BooleanType,
  StructType,
  StringType,
  ArrayType
}
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.PropSpec
import com.holdenkarau.spark.testing.{
  SharedSparkContext,
  DataframeGenerator,
  Column
}


abstract class FeaturePropSpec
    extends PropSpec
    with SharedSparkContext
    with DefaultReadWriteTest {
  implicit def arbitraryDenseVector: Arbitrary[DenseVector] =
    Arbitrary {
      for (arr <- arbitrary[Array[Double]]) yield new DenseVector(arr)
    }

  implicit def arbitraryVector: Arbitrary[Vector] =
    Arbitrary(
      Gen.frequency(
        1 -> arbitrary[DenseVector]
      ))

  lazy val spark = SparkSession.builder().getOrCreate()

  def schema =
    StructType(
      List(
        StructField("integer", IntegerType),
        StructField("double", DoubleType),
        StructField("boolean", BooleanType),
        StructField("string", StringType)
      ))

  def integerGen = new Column("integer", Gen.choose(-100, 100))

  def doubleGen = new Column("double", Gen.choose(-100.0, 100.0))

  def stringGen =
    new Column("string", Gen.oneOf("A", "BC", "DEF", "GHIJ", "KLMNO"))

  def dataframeGen =
    DataframeGenerator.arbitraryDataFrameWithCustomFields(
      spark.sqlContext,
      schema)(integerGen, doubleGen, stringGen)

  def hasDistinctValues(df: DataFrame, columns: String*): Boolean = {
    columns.foldLeft(true) { (acc, col) =>
      acc && df.select(col).distinct.count() > 1
    }
  }
} 
Example 122
Source File: catzSpec.scala    From interop-cats   with Apache License 2.0 5 votes vote down vote up
package zio.stream.interop

import cats.implicits._
import cats.laws.discipline._
import org.scalacheck.{ Arbitrary, Cogen, Gen }
import zio.stream.interop.catz._
import zio.stream._

class catzSpec extends catzSpecZStreamBase with GenStreamInteropCats {

  def genUStream[A: Arbitrary]: Gen[Stream[Nothing, A]] =
    Gen.oneOf(genSuccess[Nothing, A], genIdentityTrans(genSuccess[Nothing, A]))

  checkAllAsync(
    "MonadError[Stream[Int, ?]]",
    implicit tc => MonadErrorTests[Stream[Int, ?], Int].monadError[Int, Int, Int]
  )
  checkAllAsync(
    "Parallel[Stream[Throwable, ?]]",
    implicit tc => ParallelTests[Stream[Throwable, ?], ParStream[Any, Throwable, ?]].parallel[Int, Int]
  )
  checkAllAsync("MonoidK[Stream[Int, ?]]", implicit tc => MonoidKTests[Stream[Int, ?]].monoidK[Int])
  checkAllAsync(
    "SemigroupK[Stream[Option[Unit], ?]]",
    implicit tc => SemigroupKTests[Stream[Option[Unit], ?]].semigroupK[Int]
  )
  checkAllAsync(
    "SemigroupK[Stream[Throwable, ?]]",
    implicit tc => SemigroupKTests[Stream[Throwable, ?]].semigroupK[Int]
  )
  checkAllAsync("Bifunctor[Stream]", implicit tc => BifunctorTests[Stream].bifunctor[Int, Int, Int, Int, Int, Int])
  checkAllAsync(
    "Monad[Stream[Nothing, ?]]", { implicit tc =>
      implicit def streamArbitrary[A: Arbitrary: Cogen]: Arbitrary[Stream[Nothing, A]] = Arbitrary(genUStream[A])
      MonadTests[Stream[Nothing, ?]].apply[Int, Int, Int]
    }
  )
  checkAllAsync(
    "ArrowChoice[ZStream]",
    implicit tc => ArrowChoiceTests[ZStream[*, Int, *]].arrowChoice[Int, Int, Int, Int, Int, Int]
  )

  object summoningInstancesTest {
    import cats._

    Alternative[ZStream[String, Throwable, ?]]
    MonadError[ZStream[String, Throwable, ?], Throwable]
    Monad[ZStream[String, Throwable, ?]]
    Applicative[ZStream[String, Throwable, ?]]
    Functor[ZStream[String, Throwable, ?]]
    SemigroupK[ZStream[String, Throwable, ?]]
    Apply[ZStream[Any, Nothing, ?]]
  }
} 
Example 123
Source File: MagnoliaArbitrary.scala    From scalacheck-magnolia   with Apache License 2.0 5 votes vote down vote up
package scalacheckmagnolia

import magnolia.{CaseClass, Magnolia, SealedTrait}
import org.scalacheck.Gen.choose
import org.scalacheck.{Arbitrary, Gen, GenHack}

object MagnoliaArbitrary {
  type Typeclass[T] = Arbitrary[T]

  def combine[T](caseClass: CaseClass[Arbitrary, T]): Arbitrary[T] = Arbitrary[T] {
    GenHack.gen[T] { (params, seed) =>

      try {
        var acc = seed

        // todo use rawConstruct in next Magnolia version ?
        val a = caseClass.construct { p =>
          val r = p.typeclass.arbitrary.doPureApply(params, acc)
          acc = r.seed
          r.retrieve.get
        }
        GenHack.r(Some(a), acc)

      } catch {
        case _: StackOverflowError =>
          GenHack.r(None, seed.next)
      }
    }
  }

  def dispatch[T](sealedTrait: SealedTrait[Arbitrary, T])(): Arbitrary[T] = Arbitrary[T] {
    val gs: Seq[Gen[T]] = sealedTrait.subtypes.map(_.typeclass.arbitrary.asInstanceOf[Gen[T]])
    choose(0, gs.size - 1).flatMap(gs(_)).suchThat(x => gs.exists(GenHack.sieveCopy(_, x)))
  }


  implicit def gen[T]: Arbitrary[T] = macro Magnolia.gen[T]
} 
Example 124
Source File: ArbitraryStrategy.scala    From lithium   with Apache License 2.0 5 votes vote down vote up
package com.swissborg.lithium

import akka.cluster.swissborg.EitherValues
import cats.effect.Sync
import cats.{Applicative, ApplicativeError, Functor, Semigroupal}
import com.swissborg.lithium.instances.ArbitraryTestInstances._
import com.swissborg.lithium.strategy._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen.chooseNum
import org.scalacheck.{Arbitrary, Gen}

trait ArbitraryStrategy[F] {
  def fromScenario(scenario: Scenario): Arbitrary[F]
}

object ArbitraryStrategy extends EitherValues {
  implicit def keepRefereeArbitraryStrategy[F[_]: Applicative]: ArbitraryStrategy[KeepReferee[F]] =
    new ArbitraryStrategy[KeepReferee[F]] {
      override def fromScenario(scenario: Scenario): Arbitrary[KeepReferee[F]] = Arbitrary {
        val maybeNodes = scenario.worldViews.headOption.map(_.nodes)

        for {
          referee <- Gen.oneOf(maybeNodes.fold(Arbitrary.arbitrary[Node]) { nodes =>
            chooseNum(0, nodes.length - 1).map(nodes.toNonEmptyList.toList.apply)
          }, Arbitrary.arbitrary[Node])

          downIfLessThan <- chooseNum(1, maybeNodes.fold(1)(_.length))
        } yield new strategy.KeepReferee[F](
          KeepRefereeConfig(referee.member.address.toString, downIfLessThan)
        )
      }
    }

  implicit def staticQuorumArbitraryStrategy[F[_]: Sync]: ArbitraryStrategy[StaticQuorum[F]] =
    new ArbitraryStrategy[StaticQuorum[F]] {
      override def fromScenario(scenario: Scenario): Arbitrary[StaticQuorum[F]] = Arbitrary {
        val clusterSize = scenario.clusterSize

        val minQuorumSize = clusterSize / 2 + 1
        for {
          quorumSize <- chooseNum(minQuorumSize, clusterSize)
          role       <- arbitrary[String]
        } yield new strategy.StaticQuorum(StaticQuorumConfig(role, quorumSize))
      }
    }

  implicit def keepMajorityArbitraryStrategy[F[_]: ApplicativeError[*[_], Throwable]]
    : ArbitraryStrategy[KeepMajority[F]] =
    new ArbitraryStrategy[KeepMajority[F]] {
      override def fromScenario(scenario: Scenario): Arbitrary[KeepMajority[F]] =
        Arbitrary {
          for {
            role                  <- arbitrary[String]
            weaklUpMembersAllowed <- arbitrary[Boolean]
          } yield new strategy.KeepMajority(KeepMajorityConfig(role), weaklUpMembersAllowed)
        }
    }

  implicit def keepOldestArbitraryStrategy[F[_]: ApplicativeError[*[_], Throwable]]: ArbitraryStrategy[KeepOldest[F]] =
    new ArbitraryStrategy[KeepOldest[F]] {
      override def fromScenario(scenario: Scenario): Arbitrary[KeepOldest[F]] = Arbitrary {
        for {
          downIfAlone <- arbitrary[Boolean]
          role        <- arbitrary[String]
        } yield new strategy.KeepOldest(KeepOldestConfig(downIfAlone, role))
      }

    }

  implicit def downAllArbitraryStrategy[F[_]: Applicative]: ArbitraryStrategy[DownAll[F]] =
    new ArbitraryStrategy[DownAll[F]] {
      override def fromScenario(scenario: Scenario): Arbitrary[DownAll[F]] =
        Arbitrary(Gen.const(new strategy.DownAll[F]()))
    }

  implicit def downIndirectlyConnectedArbitraryStrategy[F[_]: Applicative]: ArbitraryStrategy[IndirectlyConnected[F]] =
    new ArbitraryStrategy[IndirectlyConnected[F]] {
      override def fromScenario(scenario: Scenario): Arbitrary[IndirectlyConnected[F]] =
        Arbitrary(Gen.const(new strategy.IndirectlyConnected[F]()))
    }

  implicit def unionArbitraryStrategy[F[_]: Functor: Semigroupal, Strat1[_[_]], Strat2[_[_]]](
    implicit ev1: Strat1[F] <:< Strategy[F],
    ev2: Strat2[F] <:< Strategy[F],
    arbStrat1: ArbitraryStrategy[Strat1[F]],
    arbStrat2: ArbitraryStrategy[Strat2[F]]
  ): ArbitraryStrategy[Union[F, Strat1, Strat2]] =
    new ArbitraryStrategy[Union[F, Strat1, Strat2]] {
      override def fromScenario(scenario: Scenario): Arbitrary[Union[F, Strat1, Strat2]] =
        Arbitrary {
          for {
            strat1 <- arbStrat1.fromScenario(scenario).arbitrary
            strat2 <- arbStrat2.fromScenario(scenario).arbitrary
          } yield new Union[F, Strat1, Strat2](strat1, strat2)
        }
    }
} 
Example 125
Source File: MonadTestInstances.scala    From lithium   with Apache License 2.0 5 votes vote down vote up
package com.swissborg.lithium

package instances

import cats.Monad
import org.scalacheck.{Arbitrary, Gen}

trait MonadTestInstances {
  implicit val arbitraryMonad: Monad[Arbitrary] = new Monad[Arbitrary] {
    override def pure[A](x: A): Arbitrary[A] = Arbitrary(Gen.const(x))

    override def flatMap[A, B](fa: Arbitrary[A])(f: A => Arbitrary[B]): Arbitrary[B] =
      Arbitrary(fa.arbitrary.flatMap(f.andThen(_.arbitrary)))

    override def tailRecM[A, B](a: A)(f: A => Arbitrary[Either[A, B]]): Arbitrary[B] =
      Arbitrary(Gen.tailRecM(a)(f.andThen(_.arbitrary)))
  }
} 
Example 126
Source File: ApplicativeTestInstances.scala    From lithium   with Apache License 2.0 5 votes vote down vote up
package com.swissborg.lithium

package instances

import cats.Applicative
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Gen.const

trait ApplicativeTestInstances {
  implicit val genApplicative: Applicative[Gen] = new Applicative[Gen] {
    override def pure[A](x: A): Gen[A] = const(x)
    override def ap[A, B](ff: Gen[A => B])(fa: Gen[A]): Gen[B] =
      for {
        ff <- ff
        a  <- fa
      } yield ff(a)
  }

  implicit val arbitraryApplicative: Applicative[Arbitrary] = new Applicative[Arbitrary] {
    override def pure[A](x: A): Arbitrary[A] = Arbitrary(Applicative[Gen].pure(x))
    override def ap[A, B](ff: Arbitrary[A => B])(fa: Arbitrary[A]): Arbitrary[B] =
      Arbitrary(Applicative[Gen].ap(ff.arbitrary)(fa.arbitrary))
  }
} 
Example 127
Source File: AkkaArbitraryInstances.scala    From lithium   with Apache License 2.0 5 votes vote down vote up
package akka.cluster.swissborg

import akka.actor.{ActorPath, Address, ChildActorPath, RootActorPath}
import akka.cluster.{Member, UniqueAddress, Reachability => _}
import com.swissborg.lithium.instances.ArbitraryTestInstances._
import org.scalacheck.Arbitrary._
import org.scalacheck.{Arbitrary, Gen}
import shapeless.tag
import shapeless.tag.@@


object AkkaArbitraryInstances {
  sealed trait JoiningTag
  type JoiningMember = Member @@ JoiningTag

  implicit val arbJoiningMember: Arbitrary[JoiningMember] = Arbitrary {
    for {
      uniqueAddress <- arbitrary[UniqueAddress]
    } yield tag[JoiningTag][Member](Member(uniqueAddress, Set("dc-datacenter")))
  }

  implicit val arbRootActorPath: Arbitrary[RootActorPath] = Arbitrary(arbitrary[Address].map(RootActorPath(_)))

  def arbChildActorPath(parent: ActorPath): Arbitrary[ChildActorPath] =
    Arbitrary(for {
      c   <- Gen.alphaChar
      cs  <- Gen.alphaStr
      uid <- Gen.chooseNum(0, Int.MaxValue)
      name = s"$c$cs"
    } yield new ChildActorPath(parent, name, uid))

  def arbActorPath(depth: Int, parent: ActorPath): Arbitrary[ActorPath] =
    Arbitrary(
      if (depth <= 0) Gen.const(parent)
      else arbChildActorPath(parent).arbitrary.flatMap(arbActorPath(depth - 1, _).arbitrary)
    )

  implicit val arbActorPath0: Arbitrary[ActorPath] = Arbitrary(for {
    depth  <- Gen.chooseNum(0, 10)
    parent <- arbitrary[RootActorPath]
    path   <- arbActorPath(depth, parent).arbitrary
  } yield path)
} 
Example 128
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 129
Source File: MergeByCommitCallbackTest.scala    From monix-kafka   with Apache License 2.0 5 votes vote down vote up
package monix.kafka

import monix.eval.Task
import monix.kafka.config.AutoOffsetReset
import monix.reactive.Observable
import org.apache.kafka.clients.producer.ProducerRecord
import org.scalatest.{FunSuite, Matchers}

import scala.concurrent.duration._
import scala.concurrent.Await
import monix.execution.Scheduler.Implicits.global
import org.apache.kafka.clients.consumer.OffsetCommitCallback
import org.apache.kafka.common.TopicPartition
import org.scalacheck.Gen
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

class MergeByCommitCallbackTest extends FunSuite with KafkaTestKit with ScalaCheckDrivenPropertyChecks with Matchers {

  val commitCallbacks: List[Commit] = List.fill(4)(new Commit {
    override def commitBatchSync(batch: Map[TopicPartition, Long]): Task[Unit] = Task.unit

    override def commitBatchAsync(batch: Map[TopicPartition, Long], callback: OffsetCommitCallback): Task[Unit] =
      Task.unit
  })

  val committableOffsetsGen: Gen[CommittableOffset] = for {
    partition <- Gen.posNum[Int]
    offset <- Gen.posNum[Long]
    commit <- Gen.oneOf(commitCallbacks)
  } yield CommittableOffset(new TopicPartition("topic", partition), offset, commit)

  test("merge by commit callback works") {
    forAll(Gen.nonEmptyListOf(committableOffsetsGen)) { offsets =>
      val partitions = offsets.map(_.topicPartition)
      val received: List[CommittableOffsetBatch] = CommittableOffsetBatch.mergeByCommitCallback(offsets)

      received.foreach { batch => partitions should contain allElementsOf batch.offsets.keys }

      received.size should be <= 4
    }
  }

  test("merge by commit callback for multiple consumers") {
    withRunningKafka {
      val count = 10000
      val topicName = "monix-kafka-merge-by-commit"

      val producerCfg = KafkaProducerConfig.default.copy(
        bootstrapServers = List("127.0.0.1:6001"),
        clientId = "monix-kafka-1-0-producer-test"
      )

      val producer = KafkaProducerSink[String, String](producerCfg, io)

      val pushT = Observable
        .range(0, count)
        .map(msg => new ProducerRecord(topicName, "obs", msg.toString))
        .bufferIntrospective(1024)
        .consumeWith(producer)

      val listT = Observable
        .range(0, 4)
        .mergeMap(i => createConsumer(i.toInt, topicName).take(500))
        .bufferTumbling(2000)
        .map(CommittableOffsetBatch.mergeByCommitCallback)
        .map { offsetBatches => assert(offsetBatches.length == 4) }
        .completedL

      Await.result(Task.parZip2(listT, pushT).runToFuture, 60.seconds)
    }
  }

  private def createConsumer(i: Int, topicName: String): Observable[CommittableOffset] = {
    val cfg = KafkaConsumerConfig.default.copy(
      bootstrapServers = List("127.0.0.1:6001"),
      groupId = s"kafka-tests-$i",
      autoOffsetReset = AutoOffsetReset.Earliest
    )

    KafkaConsumerObservable
      .manualCommit[String, String](cfg, List(topicName))
      .executeOn(io)
      .map(_.committableOffset)
  }
} 
Example 130
Source File: MergeByCommitCallbackTest.scala    From monix-kafka   with Apache License 2.0 5 votes vote down vote up
package monix.kafka

import monix.eval.Task
import monix.kafka.config.AutoOffsetReset
import monix.reactive.Observable
import org.apache.kafka.clients.producer.ProducerRecord
import org.scalatest.{FunSuite, Matchers}

import scala.concurrent.duration._
import scala.concurrent.Await
import monix.execution.Scheduler.Implicits.global
import org.apache.kafka.clients.consumer.OffsetCommitCallback
import org.apache.kafka.common.TopicPartition
import org.scalacheck.Gen
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

class MergeByCommitCallbackTest extends FunSuite with KafkaTestKit with ScalaCheckDrivenPropertyChecks with Matchers {

  val commitCallbacks: List[Commit] = List.fill(4)(new Commit {
    override def commitBatchSync(batch: Map[TopicPartition, Long]): Task[Unit] = Task.unit

    override def commitBatchAsync(batch: Map[TopicPartition, Long], callback: OffsetCommitCallback): Task[Unit] =
      Task.unit
  })

  val committableOffsetsGen: Gen[CommittableOffset] = for {
    partition <- Gen.posNum[Int]
    offset <- Gen.posNum[Long]
    commit <- Gen.oneOf(commitCallbacks)
  } yield CommittableOffset(new TopicPartition("topic", partition), offset, commit)

  test("merge by commit callback works") {
    forAll(Gen.nonEmptyListOf(committableOffsetsGen)) { offsets =>
      val partitions = offsets.map(_.topicPartition)
      val received: List[CommittableOffsetBatch] = CommittableOffsetBatch.mergeByCommitCallback(offsets)

      received.foreach { batch => partitions should contain allElementsOf batch.offsets.keys }

      received.size should be <= 4
    }
  }

  test("merge by commit callback for multiple consumers") {
    withRunningKafka {
      val count = 10000
      val topicName = "monix-kafka-merge-by-commit"

      val producerCfg = KafkaProducerConfig.default.copy(
        bootstrapServers = List("127.0.0.1:6001"),
        clientId = "monix-kafka-1-0-producer-test"
      )

      val producer = KafkaProducerSink[String, String](producerCfg, io)

      val pushT = Observable
        .range(0, count)
        .map(msg => new ProducerRecord(topicName, "obs", msg.toString))
        .bufferIntrospective(1024)
        .consumeWith(producer)

      val listT = Observable
        .range(0, 4)
        .mergeMap(i => createConsumer(i.toInt, topicName).take(500))
        .bufferTumbling(2000)
        .map(CommittableOffsetBatch.mergeByCommitCallback)
        .map { offsetBatches => assert(offsetBatches.length == 4) }
        .completedL

      Await.result(Task.parZip2(listT, pushT).runToFuture, 60.seconds)
    }
  }

  private def createConsumer(i: Int, topicName: String): Observable[CommittableOffset] = {
    val cfg = KafkaConsumerConfig.default.copy(
      bootstrapServers = List("127.0.0.1:6001"),
      groupId = s"kafka-tests-$i",
      autoOffsetReset = AutoOffsetReset.Earliest
    )

    KafkaConsumerObservable
      .manualCommit[String, String](cfg, List(topicName))
      .executeOn(io)
      .map(_.committableOffset)
  }
} 
Example 131
Source File: MergeByCommitCallbackTest.scala    From monix-kafka   with Apache License 2.0 5 votes vote down vote up
package monix.kafka

import monix.eval.Task
import monix.kafka.config.AutoOffsetReset
import monix.reactive.Observable
import org.apache.kafka.clients.producer.ProducerRecord
import org.scalatest.{FunSuite, Matchers}

import scala.concurrent.duration._
import scala.concurrent.Await
import monix.execution.Scheduler.Implicits.global
import org.apache.kafka.clients.consumer.OffsetCommitCallback
import org.apache.kafka.common.TopicPartition
import org.scalacheck.Gen
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

class MergeByCommitCallbackTest extends FunSuite with KafkaTestKit with ScalaCheckDrivenPropertyChecks with Matchers {

  val commitCallbacks: List[Commit] = List.fill(4)(new Commit {
    override def commitBatchSync(batch: Map[TopicPartition, Long]): Task[Unit] = Task.unit

    override def commitBatchAsync(batch: Map[TopicPartition, Long], callback: OffsetCommitCallback): Task[Unit] =
      Task.unit
  })

  val committableOffsetsGen: Gen[CommittableOffset] = for {
    partition <- Gen.posNum[Int]
    offset <- Gen.posNum[Long]
    commit <- Gen.oneOf(commitCallbacks)
  } yield CommittableOffset(new TopicPartition("topic", partition), offset, commit)

  test("merge by commit callback works") {
    forAll(Gen.nonEmptyListOf(committableOffsetsGen)) { offsets =>
      val partitions = offsets.map(_.topicPartition)
      val received: List[CommittableOffsetBatch] = CommittableOffsetBatch.mergeByCommitCallback(offsets)

      received.foreach { batch => partitions should contain allElementsOf batch.offsets.keys }

      received.size should be <= 4
    }
  }

  test("merge by commit callback for multiple consumers") {
    withRunningKafka {
      val count = 10000
      val topicName = "monix-kafka-merge-by-commit"

      val producerCfg = KafkaProducerConfig.default.copy(
        bootstrapServers = List("127.0.0.1:6001"),
        clientId = "monix-kafka-1-0-producer-test"
      )

      val producer = KafkaProducerSink[String, String](producerCfg, io)

      val pushT = Observable
        .range(0, count)
        .map(msg => new ProducerRecord(topicName, "obs", msg.toString))
        .bufferIntrospective(1024)
        .consumeWith(producer)

      val listT = Observable
        .range(0, 4)
        .mergeMap(i => createConsumer(i.toInt, topicName).take(500))
        .bufferTumbling(2000)
        .map(CommittableOffsetBatch.mergeByCommitCallback)
        .map { offsetBatches => assert(offsetBatches.length == 4) }
        .completedL

      Await.result(Task.parZip2(listT, pushT).runToFuture, 60.seconds)
    }
  }

  private def createConsumer(i: Int, topicName: String): Observable[CommittableOffset] = {
    val cfg = KafkaConsumerConfig.default.copy(
      bootstrapServers = List("127.0.0.1:6001"),
      groupId = s"kafka-tests-$i",
      autoOffsetReset = AutoOffsetReset.Earliest
    )

    KafkaConsumerObservable
      .manualCommit[String, String](cfg, List(topicName))
      .executeOn(io)
      .map(_.committableOffset)
  }
} 
Example 132
Source File: model.scala    From Scala-High-Performance-Programming   with MIT License 5 votes vote down vote up
package highperfscala.orderbook

import org.joda.time.Instant
import org.scalacheck.Gen

// Model taken from chapter 2

case class Price(value: BigDecimal) extends AnyVal
object Price {
  implicit val genPrice: Gen[Price] = Gen.posNum[Double].map(d =>
    Price(BigDecimal(d)))
  implicit val ordering: Ordering[Price] = new Ordering[Price] {
    def compare(x: Price, y: Price): Int =
      Ordering.BigDecimal.compare(x.value, y.value)
  }
}

case class OrderId(value: Long)
object OrderId {
  implicit val genOrderId: Gen[OrderId] = Gen.posNum[Long].map(OrderId.apply)
}

sealed trait LimitOrder {
  def id: OrderId
  def price: Price
}
object LimitOrder {
  implicit val genLimitOrder: Gen[LimitOrder] = Gen.oneOf(
    BuyLimitOrder.genBuyLimitOrder, SellLimitOrder.genSellLimitOrder)
}
case class BuyLimitOrder(id: OrderId, price: Price) extends LimitOrder
object BuyLimitOrder {
  implicit val genBuyLimitOrder: Gen[BuyLimitOrder] = Gen.zip(
    OrderId.genOrderId, Price.genPrice).map(Function.tupled(BuyLimitOrder.apply))
}
case class SellLimitOrder(id: OrderId, price: Price) extends LimitOrder
object SellLimitOrder {
  implicit val genSellLimitOrder: Gen[SellLimitOrder] = Gen.zip(
    OrderId.genOrderId, Price.genPrice).map(Function.tupled(
    SellLimitOrder.apply))
}

case class Execution(orderId: OrderId, price: Price)

case class CommandInstant(value: Instant) extends AnyVal
object CommandInstant {
  def now(): CommandInstant =
    CommandInstant(new Instant(System.currentTimeMillis()))
  implicit val genCommandInstant: Gen[CommandInstant] =
    Gen.posNum[Long].map(l => CommandInstant(new Instant(l)))
}

case class EventInstant(value: Instant) extends AnyVal
object EventInstant {
  def now(): EventInstant =
    EventInstant(new Instant(System.currentTimeMillis()))
  implicit val genEventInstant: Gen[EventInstant] =
    Gen.posNum[Long].map(l => EventInstant(new Instant(l)))
} 
Example 133
Source File: model.scala    From Scala-High-Performance-Programming   with MIT License 5 votes vote down vote up
package highperfscala
package orderbook

import org.scalacheck.Gen

case class Price(value: BigDecimal)
object Price {
  implicit val genPrice: Gen[Price] = Gen.posNum[Double].map(d =>
    Price(BigDecimal(d)))
  implicit val ordering: Ordering[Price] = new Ordering[Price] {
    def compare(x: Price, y: Price): Int =
      Ordering.BigDecimal.compare(x.value, y.value)
  }
}

case class OrderId(value: Long)
object OrderId {
  implicit val genOrderId: Gen[OrderId] = Gen.posNum[Long].map(OrderId.apply)
}

sealed trait LimitOrder {
  def id: OrderId
  def price: Price
}
object LimitOrder {
  implicit val genLimitOrder: Gen[LimitOrder] = Gen.oneOf(
    BuyLimitOrder.genBuyLimitOrder, SellLimitOrder.genSellLimitOrder)
}
case class BuyLimitOrder(id: OrderId, price: Price) extends LimitOrder
object BuyLimitOrder {
  implicit val genBuyLimitOrder: Gen[BuyLimitOrder] = Gen.zip(
    OrderId.genOrderId, Price.genPrice).map(Function.tupled(BuyLimitOrder.apply))
}
case class SellLimitOrder(id: OrderId, price: Price) extends LimitOrder
object SellLimitOrder {
  implicit val genSellLimitOrder: Gen[SellLimitOrder] = Gen.zip(
    OrderId.genOrderId, Price.genPrice).map(Function.tupled(
    SellLimitOrder.apply))
}

case class Execution(orderId: OrderId, price: Price) 
Example 134
Source File: DistributionTest.scala    From csb   with GNU General Public License v3.0 5 votes vote down vote up
package edu.msstate.dasi.csb.data.distributions

import com.holdenkarau.spark.testing.RDDGenerator
import edu.msstate.dasi.csb.test.PropertySpec
import org.scalacheck.{Arbitrary, Gen}
import org.scalactic.anyvals.PosZInt

import scala.collection.mutable

class DistributionTest extends PropertySpec {

  private val samples = 1000000
  private val tolerance = 0.01

  private val inputMinSize = PosZInt(10)
  private val inputSizeRange = PosZInt(20)

  override implicit val generatorDrivenConfig =
    PropertyCheckConfiguration(minSize = inputMinSize, sizeRange = inputSizeRange)

  private def testProbability[T](input: Map[T, Double], distribution: Distribution[T]) = {
    val counts = mutable.Map() ++ input.mapValues(_ => 0)

    for (_ <- 0 until samples) {
      counts(distribution.sample) += 1
    }

    for ((value, prob) <- input) {
      assert((counts(value).toDouble / samples - prob).abs < tolerance)
    }
  }

  test("a Distribution from an array should return samples according to the array probabilities") {
    val pairGen = for {
      value <- Gen.alphaChar
      prob <- Gen.posNum[Long]
    } yield (value, prob)

    val elementsGen = for (elements <- Gen.nonEmptyMap(pairGen)) yield elements

    forAll(elementsGen) { elements =>
      val sum = elements.values.sum
      val input = elements.mapValues(_ / sum.toDouble)
      val distribution = new Distribution(input.toArray)

      testProbability(input, distribution)
    }
  }

  test("a Distribution from an RDD should return samples according to the probability of the input occurrences") {
    forAll(RDDGenerator.genRDD[Char](sc)(Arbitrary.arbitrary[Char])) { rdd =>
      val sequence = rdd.collect
      val input = sequence.groupBy(identity).mapValues(_.length.toDouble / sequence.length)
      val distribution = Distribution(rdd)

      testProbability(input, distribution)
    }
  }
} 
Example 135
Source File: SigmaTestingData.scala    From sigmastate-interpreter   with MIT License 5 votes vote down vote up
package special.sigma

import org.ergoplatform.SigmaConstants.ScriptCostLimit
import org.ergoplatform.validation.ValidationRules
import sigmastate.interpreter.ContextExtension
import org.scalacheck.Gen.containerOfN
import sigmastate.{AvlTreeFlags, TrivialProp}
import sigmastate.Values.{BooleanConstant, IntConstant}
import org.scalacheck.{Arbitrary, Gen}
import sigmastate.helpers.SigmaTestingCommons
import sigmastate.eval._
import sigmastate.eval.Extensions._
import org.ergoplatform.{DataInput, ErgoBox, ErgoLikeContext, ErgoLikeTransaction}
import scorex.crypto.hash.{Blake2b256, Digest32}
import scorex.crypto.authds.{ADKey, ADValue}

trait SigmaTestingData extends SigmaTestingCommons with SigmaTypeGens {
  val bytesGen: Gen[Array[Byte]] = containerOfN[Array, Byte](100, Arbitrary.arbByte.arbitrary)
  val bytesCollGen = bytesGen.map(Colls.fromArray(_))
  implicit val arbBytes = Arbitrary(bytesCollGen)
  val keyCollGen = bytesCollGen.map(_.slice(0, 32))
  import org.ergoplatform.dsl.AvlTreeHelpers._

  protected def sampleAvlProver = {
    val key = keyCollGen.sample.get
    val value = bytesCollGen.sample.get
    val (_, avlProver) = createAvlTree(AvlTreeFlags.AllOperationsAllowed, ADKey @@ key.toArray -> ADValue @@ value.toArray)
    (key, value, avlProver)
  }

  protected def sampleAvlTree: AvlTree = {
    val (key, _, avlProver) = sampleAvlProver
    val digest = avlProver.digest.toColl
    val tree = SigmaDsl.avlTree(AvlTreeFlags.ReadOnly.serializeToByte, digest, 32, None)
    tree
  }

  val tokenId1: Digest32 = Blake2b256("id1")
  val tokenId2: Digest32 = Blake2b256("id2")
  val inBox = createBox(10, TrivialProp.TrueProp,
    Seq(tokenId1 -> 10L, tokenId2 -> 20L),
    Map(ErgoBox.R4 -> IntConstant(100), ErgoBox.R5 -> BooleanConstant(true)))

  val dataBox = createBox(1000, TrivialProp.TrueProp,
    Seq(tokenId1 -> 10L, tokenId2 -> 20L),
    Map(ErgoBox.R4 -> IntConstant(100), ErgoBox.R5 -> BooleanConstant(true)))

  val outBox = createBox(10, TrivialProp.TrueProp,
    Seq(tokenId1 -> 10L, tokenId2 -> 20L),
    Map(ErgoBox.R4 -> IntConstant(100), ErgoBox.R5 -> BooleanConstant(true)))

  val header1: Header = CHeader(Blake2b256("Header.id").toColl,
    0,
    Blake2b256("Header.parentId").toColl,
    Blake2b256("ADProofsRoot").toColl,
    sampleAvlTree,
    Blake2b256("transactionsRoot").toColl,
    timestamp = 0,
    nBits = 0,
    height = 0,
    extensionRoot = Blake2b256("transactionsRoot").toColl,
    minerPk = SigmaDsl.groupGenerator,
    powOnetimePk = SigmaDsl.groupGenerator,
    powNonce = Colls.fromArray(Array[Byte](0, 1, 2, 3, 4, 5, 6, 7)),
    powDistance = SigmaDsl.BigInt(BigInt("1405498250268750867257727119510201256371618473728619086008183115260323").bigInteger),
    votes = Colls.fromArray(Array[Byte](0, 1, 2))
  )
  val header2: Header = CHeader(Blake2b256("Header2.id").toColl,
    0,
    header1.id,
    Blake2b256("ADProofsRoot2").toColl,
    sampleAvlTree,
    Blake2b256("transactionsRoot2").toColl,
    timestamp = 2,
    nBits = 0,
    height = 1,
    extensionRoot = Blake2b256("transactionsRoot2").toColl,
    minerPk = SigmaDsl.groupGenerator,
    powOnetimePk = SigmaDsl.groupGenerator,
    powNonce = Colls.fromArray(Array.fill(0.toByte)(8)),
    powDistance = SigmaDsl.BigInt(BigInt("19306206489815517413186395405558417825367537880571815686937307203793939").bigInteger),
    votes =  Colls.fromArray(Array[Byte](0, 1, 0))
  )
  val headers = Colls.fromItems(header2, header1)
  val preHeader: PreHeader = CPreHeader(0,
    header2.id,
    timestamp = 3,
    nBits = 0,
    height = 2,
    minerPk = SigmaDsl.groupGenerator,
    votes = Colls.emptyColl[Byte]
  )
  val ergoCtx = new ErgoLikeContext(
    lastBlockUtxoRoot = header2.stateRoot.asInstanceOf[CAvlTree].treeData,
    boxesToSpend = IndexedSeq(inBox),
    spendingTransaction = new ErgoLikeTransaction(IndexedSeq(), IndexedSeq(DataInput(dataBox.id)), IndexedSeq(outBox)),
    selfIndex = 0, headers = headers, preHeader = preHeader, dataBoxes = IndexedSeq(dataBox),
    extension = ContextExtension.empty,
    validationSettings = ValidationRules.currentSettings,
    costLimit = ScriptCostLimit.value, initCost = 0L)
} 
Example 136
Source File: ResponseSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.converter

import com.mesosphere.cosmos.converter.Response._
import com.mesosphere.cosmos.error.ServiceMarathonTemplateNotFound
import com.mesosphere.cosmos.rpc
import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import com.mesosphere.universe
import com.mesosphere.universe.bijection.UniverseConversions._
import com.mesosphere.universe.v3.model.Cli
import com.twitter.bijection.Conversion.asMethod
import com.twitter.util.Return
import com.twitter.util.Throw
import com.twitter.util.Try
import org.scalacheck.Gen
import org.scalatest.FreeSpec
import org.scalatest.Matchers
import org.scalatest.prop.GeneratorDrivenPropertyChecks.forAll

final class ResponseSpec extends FreeSpec with Matchers {
  "Conversion[rpc.v2.model.InstallResponse,Try[rpc.v1.model.InstallResponse]]" - {
    val vstring = "9.87.654.3210"
    val ver = universe.v3.model.Version(vstring)
    val name = "ResponseSpec"
    val appid = AppId("foobar")
    val clis = List(None, Some("post install notes"))
    val notes = List(None, Some(Cli(None)))
    val validV2s = for {
      n <- Gen.oneOf(clis)
      c <- Gen.oneOf(notes)
    } yield (rpc.v2.model.InstallResponse(name, ver, Some(appid), n, c))
    val invalidV2s = for {
      n <- Gen.oneOf(clis)
      c <- Gen.oneOf(notes)
    } yield (rpc.v2.model.InstallResponse(name, ver, None, n, c))


    "success" in {
      val v1 = rpc.v1.model.InstallResponse(name, ver.as[universe.v2.model.PackageDetailsVersion], appid)

      forAll(validV2s) { x =>
        x.as[Try[rpc.v1.model.InstallResponse]] shouldBe Return(v1)
      }
    }
    "failure" in {
      //expecting failure due to missing marathon mustache
      forAll(invalidV2s) { x =>
        x.as[Try[rpc.v1.model.InstallResponse]] shouldBe Throw(
          ServiceMarathonTemplateNotFound(name, ver).exception
        )
      }
    }
  }

} 
Example 137
Source File: ResourceProxyHandlerSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.handler

import com.mesosphere.Generators.Implicits._
import com.mesosphere.cosmos.error.CosmosException
import com.mesosphere.cosmos.error.GenericHttpError
import io.lemonlabs.uri.Uri
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen
import org.scalatest.FreeSpec
import org.scalatest.Matchers
import org.scalatest.prop.PropertyChecks

final class ResourceProxyHandlerSpec extends FreeSpec with PropertyChecks with Matchers {

  type TestData = (Long, Uri)

  "When Content-Length is provided by the upstream server" - {

    "When Content-Length matches the actual content stream length" - {
      // scalastyle:off magic.number
      val genTestData: Gen[TestData] = for {
        actualLength <- Gen.chooseNum(2, 10)
        uri <- arbitrary[Uri]
      } yield {
        (actualLength.toLong, uri)
      }

      "Succeeds if Content-Length is below the limit" in {
        forAll(genTestData) { case (actualLength, uri) =>
          ResourceProxyHandler.validateContentLength(uri, Some(actualLength))
        }
      }

      "Fails if Content-Length is zero" in {
        forAll (genTestData) { case (_, uri) =>
          val exception = intercept[CosmosException](ResourceProxyHandler.validateContentLength(uri, Some(0)))
          assert(exception.error.isInstanceOf[GenericHttpError])
        }
      }
    }

  }

  "Fails when Content-Length is not provided by the upstream server" in {
    val exception = intercept[CosmosException](ResourceProxyHandler.validateContentLength(Uri.parse("/random"), None))
    assert(exception.error.isInstanceOf[GenericHttpError])
  }

  "Parses the filename correctly" in {

    ResourceProxyHandler.getFileNameFromUrl(
      Uri.parse("http://doesntreallymatter.com/c.d")
    ) shouldEqual Some("c.d")

    ResourceProxyHandler.getFileNameFromUrl(
      Uri.parse("http://doesntreallymatter.com/a/b/c.d")
    ) shouldEqual Some("c.d")

    ResourceProxyHandler.getFileNameFromUrl(
      Uri.parse("http://doesntreallymatter.com/a/b/c")
    ) shouldEqual Some("c")

    ResourceProxyHandler.getFileNameFromUrl(
      Uri.parse("http://doesntreallymatter.com/a/b/c/")
    ) shouldEqual Some("c")

    // These should never happen, but just in case.

    ResourceProxyHandler.getFileNameFromUrl(
      Uri.parse("http://doesntreallymatter.com/")
    ) shouldEqual None

    ResourceProxyHandler.getFileNameFromUrl(
      Uri.parse("https://doesntreallymatter.com")
    ) shouldEqual None

  }
} 
Example 138
Source File: PackageDefinitionSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.universe.v3.model

import com.mesosphere.Generators.nonNegNum
import org.scalacheck.Gen
import org.scalatest.FreeSpec
import org.scalatest.prop.PropertyChecks

final class PackageDefinitionSpec extends FreeSpec with PropertyChecks {

  "PackageDefinition$.ReleaseVersion" - {

    "ReleaseVersion$.validate should" - {

      "succeed on non-negative numbers" in {
        forAll (nonNegNum[Long]) { n =>
          whenever (n >= 0) {
            assert(ReleaseVersion.validate(n).isReturn)
          }
        }
      }

      "fail on negative numbers" in {
        forAll (Gen.negNum[Long]) { n =>
          whenever (n < 0) {
            assert(ReleaseVersion.validate(n).isThrow)
          }
        }
      }

    }

    "ReleaseVersion.value" in {
      forAll (nonNegNum[Long]) { n =>
        assertResult(n)(ReleaseVersion(n).value)
      }
    }

    "ReleaseVersion$.ordering orders by value" in {
      forAll (nonNegNum[Long], nonNegNum[Long]) { (a, b) =>
        whenever (a >= 0 && b >= 0) {
          val aVersion = ReleaseVersion(a)
          val bVersion = ReleaseVersion(b)

          assertResult(Ordering[Long].compare(a, b)) {
            Ordering[ReleaseVersion].compare(aVersion, bVersion)
          }
        }
      }
    }

  }

} 
Example 139
Source File: ArbitraryInstances.scala    From tutorial-cat   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.tutorial.cat

import org.scalacheck.{Arbitrary, Gen}

object ArbitraryIntInstances extends ArbitraryInstances[Int]

trait ArbitraryInstances[T] {

  implicit def arbitraryMaybe(implicit arbitrary: Arbitrary[T]): Arbitrary[Maybe[T]] = Arbitrary {
    Gen.option(arbitrary.arbitrary).map {
      case Some(t) => Just(t)
      case None => Empty
    }
  }

  implicit def arbitraryZeroOrMore(implicit arbitrary: Arbitrary[T]): Arbitrary[ZeroOrMore[T]] =
    Arbitrary {
      def toZeroOrMore(l: List[T]): ZeroOrMore[T] = l match {
        case head :: tail => OneOrMore(head, toZeroOrMore(tail))
        case Nil => Zero
      }

      Gen.listOf(arbitrary.arbitrary).map(toZeroOrMore)
    }

} 
Example 140
Source File: MonixInstancesLawsSuite.scala    From meow-mtl   with MIT License 5 votes vote down vote up
package com.olegpy.meow.monix


import cats.implicits._
import cats.effect.laws.discipline.arbitrary.genIO
import cats.mtl.laws.discipline._
import minitest.SimpleTestSuite
import minitest.laws.Checkers
import org.typelevel.discipline.Laws
import scala.concurrent.duration._

import cats.Eq
import _root_.monix.eval.{Task, TaskLike, TaskLocal}
import _root_.monix.execution.schedulers.TestScheduler
import org.scalacheck.{Arbitrary, Cogen, Gen}

object MonixInstancesLawsSuite extends SimpleTestSuite with Checkers {
  private def checkAll(name: String)(ruleSet: TestScheduler => Laws#RuleSet) = {
    implicit val ctx = TestScheduler()

    for ((id, prop) <- ruleSet(ctx).all.properties)
      test(name + "." + id) {
        ctx.tick(1.day)
        check(prop)
      }
  }

  implicit val options: Task.Options = Task.Options(
    autoCancelableRunLoops = true,
    localContextPropagation = true
  )

  implicit val eqThrowable: Eq[Throwable] = Eq.allEqual

  implicit def eqTask[A](implicit
    eqA: Eq[A],
    ts: TestScheduler,
    options: Task.Options
  ): Eq[Task[A]] = Eq.instance { (lhs, rhs) =>
    val lf = lhs.runToFutureOpt
    val rf = rhs.runToFutureOpt
    ts.tick(1.day)
    lf.value === rf.value
  }

  implicit def arbitraryTask[A: Arbitrary: Cogen] =
    Arbitrary(Gen.delay(genIO[A].map(TaskLike.fromIO(_))))

  private def unsafeTaskLocal()(implicit ctx: TestScheduler) = {
    val f = TaskLocal(0).runToFutureOpt
    ctx.tick()
    f.value.get.get
  }

  checkAll("TaskLocal.runLocal") { implicit ctx =>
    unsafeTaskLocal().runLocal(ev =>
      ApplicativeLocalTests(ev).applicativeLocal[Int, String])
  }

  checkAll("TaskLocal.runState") { implicit ctx =>
    unsafeTaskLocal().runState(ev =>
      MonadStateTests(ev).monadState[Int]
    )
  }

  checkAll("TaskLocal.runTell") { implicit ctx =>
    unsafeTaskLocal().runTell(ev =>
      FunctorTellTests(ev).functorTell[Int]
    )
  }
} 
Example 141
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 142
Source File: IQROutlierRejectorSpec.scala    From featran   with Apache License 2.0 5 votes vote down vote up
package com.spotify.featran.transformers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    val oob = List(
      (List(WeightedLabel("s1", 0.2), WeightedLabel("s2", 0.1)), missingBase.map(v => v * 0.3))
    )
    test(
      NHotWeightedEncoder("n_hot", encodeMissingValue = true),
      xs,
      names,
      expected,
      missingBase,
      oob
    )
  }
} 
Example 145
Source File: JodaLocalDateGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time.joda

import org.joda.time.chrono.ISOChronology
import org.joda.time.{Chronology, LocalDate, Period, ReadablePeriod}
import org.scalacheck.Gen
import org.scalacheck.ops.time.AbstractTimeGenerators

sealed trait JodaLocalDateGenerators extends AbstractTimeGenerators {
  override type InstantType = LocalDate
  override type DurationType = ReadablePeriod
  override type ParamsType = Chronology

  override def defaultParams: Chronology = ISOChronology.getInstanceUTC

  override val defaultRange: ReadablePeriod = Period.years(1)

  override protected[time] def now(implicit params: Chronology): LocalDate = LocalDate.now(params)

  override protected[time] def addToCeil(
    instant: LocalDate,
    duration: ReadablePeriod
  )(implicit params: Chronology): LocalDate = {
    instant plus duration
  }

  override protected[time] def subtractToFloor(
    instant: LocalDate,
    duration: ReadablePeriod
  )(implicit params: Chronology): LocalDate = {
    instant minus duration
  }

  override def between(start: LocalDate, end: LocalDate)(implicit params: Chronology): Gen[LocalDate] = {
    val startYear = start.getYear
    val startMonthOfYear = start.getMonthOfYear
    for {
      year <- Gen.choose(startYear, end.getYear)
      monthOfYear <- {
        if (year == startYear) Gen.choose(start.getMonthOfYear, end.getMonthOfYear)
        else Gen.choose(params.monthOfYear.getMinimumValue, params.monthOfYear.getMaximumValue)
      }
      dayOfMonth <- {
        if (year == startYear && monthOfYear == startMonthOfYear) Gen.choose(startMonthOfYear, end.getDayOfMonth)
        else Gen.choose(params.dayOfMonth.getMinimumValue, params.dayOfMonth.getMaximumValue)
      }
    } yield new LocalDate(year, monthOfYear, dayOfMonth, params)
  }
}

object JodaLocalDateGenerators extends JodaLocalDateGenerators 
Example 146
Source File: JavaLocalDateGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time

import java.time.temporal.TemporalAmount
import java.time._

import org.scalacheck.Gen

sealed trait JavaLocalDateGenerators extends AbstractTimeGenerators {
  override type InstantType = LocalDate
  override type DurationType = TemporalAmount
  override type ParamsType = Clock

  override def defaultParams: Clock = Clock.systemUTC()

  override val defaultRange: TemporalAmount = Period.ofYears(1)

  override protected[time] def now(implicit params: Clock): LocalDate = LocalDate.now()

  override def between(start: LocalDate, end: LocalDate)
    (implicit params: Clock): Gen[LocalDate] = {
    for {
      epochDay <- Gen.choose(start.toEpochDay, end.toEpochDay)
    } yield LocalDate.ofEpochDay(epochDay)
  }

  override protected[time] def addToCeil(instant: LocalDate, duration: TemporalAmount)
    (implicit params: Clock): LocalDate = {
    try instant plus duration
    catch {
      case dte: DateTimeException if dte.getMessage startsWith "Invalid value for Year" => LocalDate.MAX
    }
  }

  override protected[time] def subtractToFloor(instant: LocalDate, duration: TemporalAmount)
    (implicit params: Clock): LocalDate = {
    try instant minus duration
    catch {
      case dte: DateTimeException if dte.getMessage startsWith "Invalid value for Year" => LocalDate.MIN
    }
  }
}

object JavaLocalDateGenerators extends JavaLocalDateGenerators 
Example 147
Source File: JavaLocalDateTimeGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time

import java.time._
import java.time.temporal.TemporalAmount

import org.scalacheck.Gen

sealed trait JavaLocalDateTimeGenerators extends AbstractTimeGenerators {
  override type InstantType = LocalDateTime
  override type DurationType = TemporalAmount
  override type ParamsType = Clock

  override val defaultParams: Clock = Clock.systemUTC()

  lazy val defaultZoneOffset: ZoneOffset = defaultParams.getZone.getRules.getOffset(defaultParams.instant())

  override val defaultRange: TemporalAmount = Period.ofYears(1)

  override protected[time] def now(implicit params: Clock): LocalDateTime = LocalDateTime.now(params)

  import JavaLocalTimeGenerators.MAX_NANOS

  override def between(start: LocalDateTime, end: LocalDateTime)(implicit params: Clock): Gen[LocalDateTime] = {
    @inline def secondsOf(instant: LocalDateTime): Long = instant.toEpochSecond(params.getZone.getRules.getOffset(instant))
    val startSeconds = secondsOf(start)
    val endSeconds = secondsOf(end)
    if (startSeconds == endSeconds) {
      for {
        nanos <- Gen.chooseNum(start.getNano, end.getNano)
      } yield LocalDateTime.ofEpochSecond(startSeconds, nanos, defaultZoneOffset)
    } else {
      for {
        seconds <- Gen.chooseNum(startSeconds, endSeconds)
        nanos <- seconds match {
          case `startSeconds` =>
            Gen.chooseNum(start.getNano, MAX_NANOS)
          case `endSeconds` =>
            Gen.chooseNum(0, end.getNano)
          case _ =>
            Gen.chooseNum(0, MAX_NANOS)
        }
      } yield {
        LocalDateTime.ofEpochSecond(seconds, nanos, defaultZoneOffset)
      }
    }
  }

  override protected[time] def addToCeil(
    instant: LocalDateTime,
    duration: TemporalAmount
  )(implicit params: Clock): LocalDateTime = {
    try instant plus duration
    catch {
      case dte: DateTimeException if dte.getMessage startsWith "Invalid value for Year" => LocalDateTime.MAX
    }
  }

  override protected[time] def subtractToFloor(
    instant: LocalDateTime,
    duration: TemporalAmount
  )(implicit params: Clock): LocalDateTime = {
    try instant minus duration
    catch {
      case dte: DateTimeException if dte.getMessage startsWith "Invalid value for Year" => LocalDateTime.MIN
    }
  }
}

object JavaLocalDateTimeGenerators extends JavaLocalDateTimeGenerators 
Example 148
Source File: AbstractTimeGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time

import org.scalacheck.Gen

private[time] trait AbstractTimeGenerators extends GenericTimeGenerators {

  protected[time] def now(implicit params: ParamsType): InstantType

  protected[time] def addToCeil(instant: InstantType, duration: DurationType)(implicit params: ParamsType): InstantType

  protected[time] def subtractToFloor(instant: InstantType, duration: DurationType)(implicit params: ParamsType): InstantType

  override def before(when: InstantType, maxRange: DurationType = defaultRange)
    (implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    between(subtractToFloor(when, maxRange), when)
  }

  override def beforeNow(implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    before(now)
  }

  override def beforeNowWithin(maxRange: DurationType)
    (implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    before(now, maxRange)
  }

  override def after(when: InstantType, maxRange: DurationType = defaultRange)
    (implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    between(when, addToCeil(when, maxRange))
  }

  override def afterNow(implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    after(now)
  }

  override def afterNowWithin(maxRange: DurationType)
    (implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    after(now, maxRange)
  }

  override def around(when: InstantType, plusOrMinus: DurationType)
    (implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    between(subtractToFloor(when, plusOrMinus), addToCeil(when, plusOrMinus))
  }

  override def aroundNow(implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    around(now, defaultRange)
  }

  override def aroundNowWithin(plusOrMinus: DurationType)
    (implicit params: ParamsType = defaultParams): Gen[InstantType] = {
    around(now, plusOrMinus)
  }

} 
Example 149
Source File: JavaInstantGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time

import java.time.{Clock, Duration, Instant}

import org.scalacheck.Gen

object JavaInstantGenerators extends JavaInstantGenerators
trait JavaInstantGenerators extends AbstractTimeGenerators {
  override type InstantType = Instant
  override type DurationType = Duration
  override type ParamsType = Clock

  override val defaultRange: Duration = Duration.ofDays(365)

  override val defaultParams: Clock = Clock.systemUTC()

  override protected[time] def now(implicit clock: Clock): Instant = Instant.now(clock)

  import JavaLocalTimeGenerators.MAX_NANOS

  override def between(start: Instant, end: Instant)(implicit params: Clock): Gen[Instant] = {
    val startSeconds = start.getEpochSecond
    val endSeconds = end.getEpochSecond
    if (startSeconds == endSeconds) {
      for {
        nanos <- Gen.choose(start.getNano, end.getNano)
      } yield Instant.ofEpochSecond(startSeconds, nanos)
    }
    else {
      for {
        seconds <- Gen.choose(startSeconds, endSeconds)
        nanos <- seconds match {
          case `startSeconds` =>
            Gen.choose(start.getNano, MAX_NANOS)
          case `endSeconds` =>
            Gen.choose(0, end.getNano)
          case _ =>
            Gen.choose(0, MAX_NANOS)
        }
      } yield Instant.ofEpochSecond(seconds, nanos)
    }
  }

  override protected[time] def addToCeil(
    instant: Instant,
    duration: Duration
  )(implicit params: Clock): Instant = {
    try instant plus duration
    catch {
      case ex: ArithmeticException => Instant.MAX
    }
  }

  override protected[time] def subtractToFloor(
    instant: Instant,
    duration: Duration
  )(implicit params: Clock): Instant = {
    try instant minus duration
    catch {
      case ex: ArithmeticException => Instant.MIN
    }
  }
} 
Example 150
Source File: JavaLocalTimeGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time

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

import org.scalacheck.Gen

trait JavaLocalTimeGenerators extends AbstractTimeGenerators {
  override type InstantType = LocalTime
  override type DurationType = Duration
  override type ParamsType = Clock

  override val defaultParams: Clock = Clock.systemUTC()

  override val defaultRange: Duration = Duration.ofHours(24)

  override protected[time] def now(implicit params: Clock): LocalTime = LocalTime.now(params)

  override def between(start: LocalTime, end: LocalTime)(implicit params: Clock): Gen[LocalTime] = {
    for {
      nanoOfDay <- Gen.choose(start.toNanoOfDay, end.toNanoOfDay)
    } yield LocalTime.ofNanoOfDay(nanoOfDay)
  }

  override protected[time] def addToCeil(instant: LocalTime, duration: Duration)
    (implicit params: Clock): LocalTime = {
    instant plus duration
  }

  override protected[time] def subtractToFloor(instant: LocalTime, duration: Duration)
    (implicit params: Clock): LocalTime = {
    instant minus duration
  }
}

object JavaLocalTimeGenerators extends JavaLocalTimeGenerators {

  final val MAX_NANOS = 999999999
} 
Example 151
Source File: ImplicitJavaTimeGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time

import java.time._
import java.time.chrono._

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

import scala.collection.JavaConverters._

object ImplicitJavaTimeGenerators extends ImplicitJavaTimeGenerators
trait ImplicitJavaTimeGenerators {

  implicit val arbChronology: Arbitrary[Chronology] = {
    Arbitrary(oneOf(Seq(
      HijrahChronology.INSTANCE,
      IsoChronology.INSTANCE,
      JapaneseChronology.INSTANCE,
      MinguoChronology.INSTANCE,
      ThaiBuddhistChronology.INSTANCE
    )))
  }

  implicit val arbZoneId: Arbitrary[ZoneId] = {
    Arbitrary {
      Gen.oneOf(ZoneId.getAvailableZoneIds.asScala.toSeq.map(ZoneId.of))
    }
  }

  implicit val arbInstant: Arbitrary[Instant] = {
    Arbitrary {
      for {
        millis <- chooseNum(Instant.MIN.getEpochSecond, Instant.MAX.getEpochSecond)
        nanos <- chooseNum(Instant.MIN.getNano, Instant.MAX.getNano)
      } yield {
        Instant.ofEpochMilli(millis).plusNanos(nanos)
      }
    }
  }

  implicit val arbLocalDate: Arbitrary[LocalDate] = {
    Arbitrary {
      for {
        epochDay <- chooseNum(LocalDate.MIN.toEpochDay, LocalDate.MAX.toEpochDay)
      } yield LocalDate.ofEpochDay(epochDay)
    }
  }

  implicit val arbLocalTime: Arbitrary[LocalTime] = {
    Arbitrary {
      for {
        nanoOfDay <- chooseNum(LocalTime.MIN.toNanoOfDay, LocalTime.MAX.toNanoOfDay)
      } yield LocalTime.ofNanoOfDay(nanoOfDay)
    }
  }

  implicit lazy val arbLocalDateTime: Arbitrary[LocalDateTime] = {
    import ZoneOffset.UTC
    Arbitrary {
      for {
        seconds <- chooseNum(LocalDateTime.MIN.toEpochSecond(UTC), LocalDateTime.MAX.toEpochSecond(UTC))
        nanos <- chooseNum(LocalDateTime.MIN.getNano, LocalDateTime.MAX.getNano)
      } yield LocalDateTime.ofEpochSecond(seconds, nanos, UTC)
    }
  }

  implicit lazy val arbZonedDateTime: Arbitrary[ZonedDateTime] = {
    Arbitrary {
      for {
        zoneId <- arbZoneId.arbitrary
        instant <- arbInstant.arbitrary
      } yield ZonedDateTime.ofInstant(instant, zoneId)
    }
  }

} 
Example 152
Source File: FanOutSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.impl.stages

import org.scalacheck.Gen
import org.scalatest.Inspectors
import swave.core.StreamEnv
import swave.core.internal.testkit.TestFixture

final class FanOutSpec extends SyncPipeSpec with Inspectors {

  implicit val env    = StreamEnv()
  implicit val config = PropertyCheckConfiguration(minSuccessful = 1000)

  implicit val integerInput = Gen.chooseNum(0, 999)

  "Broadcast" in check {
    testSetup
      .input[Int]
      .fixtures(Gen.chooseNum(1, 3), _.output[Int])
      .prop
      .from { (in, outs) ⇒
        import TestFixture.State._

        in.spout
          .fanOutBroadcast()
          .subDrains(outs.tail.map(_.drain.dropResult))
          .subContinue
          .drainTo(outs.head.drain)

        in.terminalState match {
          case Cancelled ⇒ forAll(outs) { _.terminalState shouldBe Cancelled }
          case Completed ⇒ forAll(outs) { _.terminalState should (be(Cancelled) or be(Completed)) }
          case error     ⇒ forAll(outs) { _.terminalState should (be(error) or be(Cancelled)) }
        }

        forAll(outs) { out ⇒
          out.received shouldEqual in.produced.take(out.scriptedSize)
        }
      }
  }

  "BroadcastBuffered" in check {
    testSetup
      .input[Int]
      .fixtures(Gen.chooseNum(1, 3), _.output[Int])
      .param(Gen.chooseNum(1, 16))
      .prop
      .from { (in, outs, bufferSize) ⇒
        import TestFixture.State._

        in.spout
          .fanOutBroadcast(bufferSize)
          .subDrains(outs.tail.map(_.drain.dropResult))
          .subContinue
          .drainTo(outs.head.drain)

        in.terminalState match {
          case Cancelled ⇒ forAll(outs) { _.terminalState shouldBe Cancelled }
          case Completed ⇒ forAll(outs) { _.terminalState should (be(Cancelled) or be(Completed)) }
          case error     ⇒ forAll(outs) { _.terminalState should (be(error) or be(Cancelled)) }
        }

        forAll(outs) { out ⇒
          out.received shouldEqual in.produced.take(out.size)
        }
      }
  }
} 
Example 153
Source File: FlattenSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.impl.stages

import org.scalacheck.Gen
import org.scalatest.Inspectors
import swave.core.internal.testkit.{TestError, TestFixture}
import swave.core._

final class FlattenSpec extends SyncPipeSpec with Inspectors {

  implicit val env    = StreamEnv()
  implicit val config = PropertyCheckConfiguration(minSuccessful = 1000)

  implicit val integerInput = Gen.chooseNum(0, 999)

  "FlattenConcat" in check {
    testSetup
      .fixture(fd ⇒ fd.inputFromIterables(Gen.chooseNum(0, 3).flatMap(Gen.listOfN(_, fd.input[Int]))))
      .output[Int]
      .param(Gen.chooseNum(1, 3))
      .prop
      .from { (in, out, parallelism) ⇒
        import TestFixture.State._

        val allInputs          = in :: in.elements.toList
        var expectedResultSize = out.scriptedSize

        in.spout
          .map(_.spout)
          .flattenConcat(parallelism)
          .drainTo(out.drain) shouldTerminate likeThis {
          case Cancelled ⇒ // inputs can be in any state
          case Completed ⇒ forAll(allInputs) { _.terminalState shouldBe Completed }
          case error @ Error(TestError) ⇒
            forAtLeast(1, allInputs) { _.terminalState shouldBe error }
            expectedResultSize = out.size
        }

        out.received shouldEqual in.elements.flatMap(_.produced).take(expectedResultSize)
      }
  }

  "FlattenMerge" in check {
    testSetup
      .fixture(fd ⇒ fd.inputFromIterables(nonOverlappingIntTestInputs(fd, 0, 3)))
      .output[Int]
      .param(Gen.chooseNum(1, 3))
      .prop
      .from { (in, out, parallelism) ⇒
        import TestFixture.State._

        val allInputs          = in :: in.elements.toList
        var expectedResultSize = out.scriptedSize

        in.spout
          .map(_.spout)
          .flattenMerge(parallelism)
          .drainTo(out.drain) shouldTerminate likeThis {
          case Cancelled ⇒ // inputs can be in any state
          case Completed ⇒ forAll(allInputs) { _.terminalState shouldBe Completed }
          case error @ Error(TestError) ⇒
            forAtLeast(1, allInputs) { _.terminalState shouldBe error }
            expectedResultSize = out.size
        }

        // verify that we received the elements in the right order
        val received = out.received
        for (sub ← in.elements) {
          val produced = sub.produced.filter(received.contains).distinct
          received.filter(produced.contains).distinct shouldEqual produced
        }
      }
  }
} 
Example 154
Source File: LazyStartSpoutSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.impl.stages

import org.scalacheck.Gen
import org.scalatest.Inspectors
import swave.core._

final class LazyStartSpoutSpec extends SyncPipeSpec with Inspectors {

  implicit val env    = StreamEnv()
  implicit val config = PropertyCheckConfiguration(minSuccessful = 100)

  implicit val integerInput = Gen.chooseNum(0, 999)

  "Spout.lazy" in check {
    testSetup
      .input[Int]
      .output[String]
      .prop
      .from { (in, out) ⇒
        Spout
          .lazyStart(() ⇒ in.spout)
          .map(_.toString)
          .drainTo(out.drain) shouldTerminate asScripted(in)

        out.received shouldEqual in.produced.take(out.scriptedSize).map(_.toString)
      }
  }
} 
Example 155
Source File: SplitSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.impl.stages

import scala.collection.mutable.ListBuffer
import scala.util.Failure
import org.scalacheck.Gen
import org.scalatest.Inspectors
import swave.core._
import swave.core.internal.testkit._

final class SplitSpec extends SyncPipeSpec with Inspectors {

  implicit val env    = StreamEnv()
  implicit val config = PropertyCheckConfiguration(minSuccessful = 1000)

  implicit val integerInput = Gen.chooseNum(0, 999)
  implicit val booleanInput = Gen.oneOf(true, false)

  "SplitWhen" - {

    "state space verification" in stateSpaceVerification(Pipe[Int].splitWhen(_ < 100, _))

    "Example 1" in {
      Spout(1 to 9)
        .splitWhen(_ % 4 == 0)
        .map(_.map(_.toString).reduce(_ + _))
        .flattenConcat()
        .drainToMkString(100, ",")
        .value
        .get
        .get shouldEqual "123,4567,89"
    }
  }

  "SplitAfter" - {

    "state space verification" in stateSpaceVerification(Pipe[Int].splitAfter(_ < 100, _))

    "Example 1" in {
      Spout(1 to 9)
        .splitAfter(_ % 4 == 0)
        .map(_.map(_.toString).reduce(_ + _))
        .flattenConcat()
        .drainToMkString(100, ",")
        .value
        .get
        .get shouldEqual "1234,5678,9"
    }
  }

  def stateSpaceVerification(pipe: Boolean => Pipe[Int, Spout[Int]]): Unit = check {
    testSetup
      .input[Int]
      .output[Spout[Int]]
      .fixture(fd ⇒ Gen.listOfN(10, fd.output[Int]))
      .param[Boolean]
      .prop
      .from { (in, out, allSubOuts, eagerCancel) ⇒
        import TestFixture.State._

        val iter    = allSubOuts.iterator
        val subOuts = ListBuffer.empty[TestOutput[Int]]
        out.appendElemHandler { sub ⇒
          if (iter.hasNext) {
            val subOut = iter.next()
            subOuts += subOut
            inside(sub.drainTo(subOut.drain).value) {
              case Some(Failure(e)) ⇒ e shouldEqual TestError
              case _                ⇒ // ok here
            }
          } else sub.drainTo(Drain.ignore)
        }

        in.spout.via(pipe(eagerCancel)).drainTo(out.drain) shouldTerminate likeThis {
          case Cancelled ⇒ // input can be in any state

          case Completed if subOuts.nonEmpty ⇒
            forAll(subOuts) {
              _.terminalState should (be(Cancelled) or be(Completed))
            }

          case Completed ⇒ in.scriptedSize shouldBe 0

          case error @ Error(TestError) ⇒
            if (subOuts.nonEmpty) {
              forAll(subOuts.init) {
                _.terminalState should (be(Cancelled) or be(Completed))
              }
            }
            in.terminalState should (be(Cancelled) or be(error))
        }
      }
  }
} 
Example 156
Source File: GroupBySpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.impl.stages

import scala.collection.mutable.ListBuffer
import scala.util.Failure
import org.scalacheck.Gen
import org.scalatest.Inspectors
import swave.core._
import swave.core.internal.testkit._

final class GroupBySpec extends SyncPipeSpec with Inspectors {

  implicit val env    = StreamEnv()
  implicit val config = PropertyCheckConfiguration(minSuccessful = 1000)

  implicit val integerInput = Gen.chooseNum(0, 999)

  "GroupBy" in check {
    testSetup
      .input[Int]
      .fixture(_.output[Spout[Int]](TestGeneration.Default.nonDroppingOutputScripts))
      .fixture(fd ⇒ Gen.listOfN(16, fd.output[Int](TestGeneration.Default.nonDroppingOutputScripts)))
      .param(Gen.oneOf(false, true))
      .param(Gen.oneOf(false, true))
      .prop
      .from { (in, out, allSubOuts, reopenCancelledSubs, eagerCancel) ⇒
        import TestFixture.State._

        val iter    = allSubOuts.iterator
        val subOuts = ListBuffer.empty[TestOutput[Int]]
        out.appendElemHandler { sub ⇒
          if (iter.hasNext) {
            val subOut = iter.next()
            subOuts += subOut
            inside(sub.drainTo(subOut.drain).value) {
              case Some(Failure(e)) ⇒
                if (e != TestError) e.printStackTrace()
                e shouldEqual TestError
              case _ ⇒ // ok here
            }
          } else sub.drainTo(Drain.ignore)
        }

        in.spout
          .groupBy(maxSubstreams = 256, reopenCancelledSubs, eagerCancel)(_ % 8)
          .drainTo(out.drain) shouldTerminate likeThis {
          case Cancelled ⇒ // input can be in any state
            forAll(subOuts) {
              _.terminalState should (be(Cancelled) or be(Completed) or be(Error(TestError)))
            }

          case Completed if subOuts.nonEmpty ⇒
            forAll(subOuts) {
              _.terminalState should (be(Cancelled) or be(Completed))
            }

          case Completed ⇒ in.scriptedSize shouldBe 0

          case error @ Error(TestError) ⇒
            forAll(subOuts) {
              _.terminalState should (be(Cancelled) or be(error))
            }
            in.terminalState should (be(Cancelled) or be(error))
        }

        val subResults = subOuts.map(_.received).filter(_.nonEmpty).groupBy(_.head % 8)
        val expected   = in.produced.groupBy(_                                     % 8)
        val received =
          if (reopenCancelledSubs) subResults.map { case (key, seqs) ⇒ key → seqs.flatten } else
            subResults.map { case (key, seqs)                        ⇒ key → seqs.head }
        forAll(received) {
          case (key, receivedValues) ⇒
            receivedValues shouldEqual expected(key).take(receivedValues.size)
        }
      }
  }
} 
Example 157
Source File: RingBufferSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.util

import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FreeSpec, Matchers}
import swave.core.impl.util.RingBuffer

class RingBufferSpec extends FreeSpec with Matchers with GeneratorDrivenPropertyChecks {

  "A RingBuffer should" - {

    val bufferGen = for {
      bit ← Gen.choose(0, 8)
    } yield new RingBuffer[String](cap = 1 << bit)

    "take in exactly `capacity` elements" in {
      forAll(bufferGen) { buf ⇒
        val a = Stream.continually("x").takeWhile(buf.write).toArray
        a.length shouldEqual buf.capacity
      }
    }

    "read back exactly the number of elems previously written" in {
      val gen = for {
        buf   ← bufferGen
        count ← Gen.choose(0, buf.capacity)
      } yield (buf, count)

      forAll(gen) {
        case (buf, count) ⇒
          val values = List.tabulate(count)(_.toString)
          values.foreach(s ⇒ buf.write(s) shouldBe true)
          List.fill(count)(buf.read()) shouldEqual values
          buf.isEmpty shouldBe true
          a[NoSuchElementException] should be thrownBy buf.read()
      }
    }

    "pass a simple stress-test" in {
      val gen = for {
        buf     ← bufferGen
        opCount ← Gen.choose(5, 20)
        ops     ← Gen.listOfN(opCount, Gen.choose(-10, 20))
      } yield (buf, ops)

      forAll(gen) {
        case (buf, ops) ⇒
          val queue = collection.mutable.Queue[String]()
          val ints  = Iterator.from(0)
          ops foreach {
            case readCount if readCount < 0 ⇒
              -readCount times {
                buf.isEmpty shouldEqual queue.isEmpty
                if (queue.nonEmpty) queue.dequeue() shouldEqual buf.read()
                else a[NoSuchElementException] should be thrownBy buf.read()
              }
            case writeCount if writeCount > 0 ⇒
              writeCount times {
                val next = ints.next().toString
                if (buf.write(next)) queue.enqueue(next)
              }
            case 0 ⇒ // ignore
          }
      }
    }
  }
} 
Example 158
Source File: ResizableRingBufferSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.util

import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FreeSpec, Matchers}
import swave.core.impl.util.ResizableRingBuffer

class ResizableRingBufferSpec extends FreeSpec with Matchers with GeneratorDrivenPropertyChecks {

  "A ResizableRingBuffer should" - {

    val bufferGen = for {
      bit ← Gen.choose(0, 8)
    } yield new ResizableRingBuffer[String](initialCap = 1, maxCap = 1 << bit)

    "take in exactly `maxAvailable` elements" in {
      forAll(bufferGen) { buf ⇒
        Stream.continually("x").takeWhile(buf.write).toArray.length shouldEqual buf.maxCapacity
      }
    }

    "read back exactly the number of elems previously written" in {
      val gen = for {
        buf   ← bufferGen
        count ← Gen.choose(0, buf.maxCapacity)
      } yield (buf, count)

      forAll(gen) {
        case (buf, count) ⇒
          val values = List.tabulate(count)(_.toString)
          values.foreach(s ⇒ buf.write(s) shouldBe true)
          List.fill(count)(buf.read()) shouldEqual values
          buf.isEmpty shouldBe true
          a[NoSuchElementException] should be thrownBy buf.read()
      }
    }

    "pass a simple stress-test" in {
      val gen = for {
        buf     ← bufferGen
        opCount ← Gen.choose(5, 50)
        ops     ← Gen.listOfN(opCount, Gen.choose(-20, 50))
      } yield (buf, ops)

      forAll(gen) {
        case (buf, ops) ⇒
          val queue = collection.mutable.Queue[String]()
          val ints  = Iterator.from(0)
          ops foreach {
            case readCount if readCount < 0 ⇒
              -readCount times {
                buf.isEmpty shouldEqual queue.isEmpty
                if (queue.nonEmpty) queue.dequeue() shouldEqual buf.read()
                else a[NoSuchElementException] should be thrownBy buf.read()
              }
            case writeCount if writeCount > 0 ⇒
              writeCount times {
                val next = ints.next().toString
                if (buf.write(next)) queue.enqueue(next)
              }
            case 0 ⇒ // ignore
          }
      }
    }
  }
} 
Example 159
Source File: RichListSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.util

import org.scalacheck.Gen
import org.scalatest.{FreeSpec, Matchers}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

class RichListSpec extends FreeSpec with Matchers with GeneratorDrivenPropertyChecks {

  "RichList" - {

    "fastReverse" in {
      forAll { (list: List[Int]) ⇒
        list.fastReverse shouldEqual list.reverse
      }
    }

    "remove" in {
      forAll(Gen.choose(0, 5), Gen.choose(0, 4)) { (n: Int, x: Int) ⇒
        val list = List.tabulate(n)(identity)
        list.remove(x) shouldEqual list.filterNot(_ == x)
      }
    }
  }
} 
Example 160
Source File: RichRefArraySpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.util

import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FreeSpec, Matchers}

class RichRefArraySpec extends FreeSpec with Matchers with GeneratorDrivenPropertyChecks {

  "RichRefArray" - {
    val stringArrays = Gen.containerOf[Array, String](Gen.alphaStr)

    "fastIndexOf" in {
      val arrayWithIndex =
        for {
          arr ← stringArrays
          ix  ← Gen.chooseNum(0, arr.length + 1)
        } yield arr.map(Symbol(_)) → ix

      forAll(arrayWithIndex) {
        case (array, ix) ⇒
          val specimen = if (ix < array.length) array(ix) else 'foo
          array.fastIndexOf(specimen) shouldEqual array.indexOf(specimen)
      }
    }

    "reverse_!" in {
      forAll(stringArrays) { array ⇒
        val array2 = array.drop(0)
        array2.reverse_!()
        array2 shouldEqual array.reverse
      }
    }
  }
} 
Example 161
Source File: XorShiftRandomSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core.util

import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FreeSpec, Matchers}

class XorShiftRandomSpec extends FreeSpec with Matchers with GeneratorDrivenPropertyChecks {

  "XorShiftRandom" - {

    "nextLong" in {
      val random = XorShiftRandom()
      forAll(Gen.posNum[Long]) { bound ⇒
        random.nextLong(bound) should (be >= 0L and be < bound)
      }
    }

    "nextInt" in {
      val random = XorShiftRandom()
      forAll(Gen.posNum[Int]) { bound ⇒
        random.nextInt(bound) should (be >= 0 and be < bound)
      }
    }

    "nextDouble" in {
      val random = XorShiftRandom()
      forAll { (_: Unit) ⇒
        random.nextDouble() should (be >= 0.0 and be < 1.0)
      }
    }

    "shuffle" in {
      val random = XorShiftRandom()
      val array  = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
      val array2 = java.util.Arrays.copyOf(array, array.length)
      random.shuffle_!(array2)
      array2 should not equal array // will fail once every approx. 10! = 3.628.800 test runs
      array2.sorted shouldEqual array
    }
  }
} 
Example 162
Source File: DataReprsTest.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.runtime
package test

import org.scalacheck.{Arbitrary, Gen}
import Arbitrary.arbitrary
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

import scala.reflect.runtime.universe.TypeTag


class DataReprsTest extends FreeSpec with Matchers with ScalaCheckDrivenPropertyChecks {

  implicit val arbString: Arbitrary[String] = Arbitrary(Gen.listOf(arbitrary[Char]).map(_.mkString))

  def test[T : Arbitrary](implicit typeTag: TypeTag[T], reprsOf: ReprsOf.DataReprsOf[T]): Unit = {
    s"${typeTag}" in {
      forAll {
        (value: T) => reprsOf.encode(value)
      }
    }
  }

  "DataReprsOf checks" - {
    "Maps" - {
      test[Map[String, String]]
      test[Map[String, Int]]
      test[Map[String, Map[String, Int]]]
      test[List[Map[Int, String]]]
    }

    "Sequences" - {
      test[List[String]]
      test[List[Int]]
    }

    "Structs" - {
      test[(String, Int, Map[Int, String])]
      test[List[(Int, Boolean, String, String, Option[Int], Option[String], List[String], Map[String, Int])]]
    }
  }

} 
Example 163
Source File: BankAccountSpecSupport.scala    From akka-ddd-cqrs-es-example   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.bank.adaptor.util

import akka.actor.ActorSystem
import com.github.j5ik2o.bank.adaptor.generator.IdGenerator
import com.github.j5ik2o.bank.domain.model.{ BankAccountId, BankAccountName }
import org.scalacheck.Gen
import org.sisioh.baseunits.scala.money.Money
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile

trait BankAccountSpecSupport {

  val system: ActorSystem

  lazy val dbConfig: DatabaseConfig[JdbcProfile] =
    DatabaseConfig.forConfig[JdbcProfile](path = "slick", system.settings.config)

  lazy val bankAccountIdGenerator: IdGenerator[BankAccountId] =
    IdGenerator.ofBankAccountId(dbConfig.profile, dbConfig.db)

  val bankAccountNameGen: Gen[BankAccountName] =
    Gen.alphaStr.suchThat(v => v.nonEmpty && v.length <= 256).map(BankAccountName)
  val depositMoneyGen: Gen[Money]  = Gen.choose(1L, 100L).map(v => Money.yens(BigDecimal(v)))
  val withdrawMoneyGen: Gen[Money] = Gen.choose(1L, 50L).map(v => Money.yens(BigDecimal(v)))

  val bankAccountOldNameAndNewNameGen: Gen[(BankAccountName, BankAccountName)] = for {
    oldName <- bankAccountNameGen
    newName <- bankAccountNameGen
  } yield (oldName, newName)

  val bankAccountNameAndDepositMoneyGen: Gen[(BankAccountName, Money)] = for {
    name    <- bankAccountNameGen
    deposit <- depositMoneyGen
  } yield (name, deposit)

  val bankAccountNameAndDepositMoneyAndWithDrawMoneyGen: Gen[(BankAccountName, Money, Money)] = (for {
    name     <- bankAccountNameGen
    deposit  <- depositMoneyGen
    withdraw <- withdrawMoneyGen
  } yield (name, deposit, withdraw)).suchThat { case (_, deposit, withdraw) => deposit > withdraw }

} 
Example 164
Source File: ORSetSuite.scala    From crdt   with Apache License 2.0 5 votes vote down vote up
package com.machinomy.crdt.op

import org.scalatest.{FunSuite, Matchers}
import org.scalatest.prop.PropertyChecks
import org.scalacheck.Gen
import com.github.nscala_time.time.Imports._
import com.machinomy.crdt.state.TombStone

class ORSetSuite extends FunSuite with PropertyChecks with Matchers {
  test("fresh is empty") {
    val set = ORSet[Int, DateTime]()
    assert(set.value.isEmpty)
  }

  test("add") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val set = ORSet[Int, DateTime]()
      val (nextSet, operation) = set.add(i)
      nextSet.value should be(Set(i))
      operation.isDefined should be(true)
      operation.get.isInstanceOf[ORSet.Add[_, _]] should be(true)
    }
  }

  test("remove if present") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val initial = ORSet[Int, DateTime]()
      val (set, _) = initial.add(i)
      val (finalSet, operation) = set.remove(i)
      finalSet.value should be(empty)
      operation.isDefined should be(true)
      operation.get.isInstanceOf[ORSet.Remove[_, _]] should be(true)
    }
  }

  test("remove if absent") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val initial = ORSet[Int, DateTime]()
      val (set, operation) = initial.remove(i)
      set.value should be(empty)
      operation shouldNot be(empty)
      operation.get.isInstanceOf[ORSet.Remove[_, _]] should be(true)
    }
  }

  test("add operation") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val set = ORSet[Int, DateTime]()
      val addOp = ORSet.Add(i, implicitly[TombStone[DateTime]].next)
      val (nextSet, operation) = set.run(addOp)
      nextSet.value should be(Set(i))
      operation shouldNot be(empty)
      operation.get.isInstanceOf[ORSet.Add[_, _]] should be(true)
    }
  }

  test("remove operation if present") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val initial = ORSet[Int, DateTime]()
      val (set, _) = initial.add(i)
      val removeOp = ORSet.Remove(i, set.state(i))
      val (finalSet, operation) = set.run(removeOp)
      finalSet.value should be(empty)
      operation.isDefined should be(true)
      operation.get.isInstanceOf[ORSet.Remove[_, _]] should be(true)
    }
  }

  test("remove operation if absent") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val initial = ORSet[Int, DateTime]()
      val removeOp = ORSet.Remove(i, Set(implicitly[TombStone[DateTime]].next))
      val (set, operation) = initial.run(removeOp)
      set.value should be(empty)
      operation should be(empty)
    }
  }
} 
Example 165
Source File: CounterSuite.scala    From crdt   with Apache License 2.0 5 votes vote down vote up
package com.machinomy.crdt.op

import org.scalatest.{FunSuite, Matchers}
import org.scalatest.prop.PropertyChecks
import org.scalacheck.Gen

class CounterSuite extends FunSuite with PropertyChecks with Matchers {
  test("fresh value is zero") {
    val counter = Counter[Int]()
    assert(counter.value == 0)
  }

  test("increment") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val increment = Counter.Increment(i)
      val counter = Counter.update(Counter[Int](), increment)
      counter.value should be(i)
    }
  }

  test("decrement") {
    forAll(Gen.posNum[Int]) { (i: Int) =>
      val decrement = Counter.Decrement(i)
      val counter = Counter.update(Counter[Int](), decrement)
      counter.value should be(-1 * i)
    }
  }
} 
Example 166
Source File: GCounterSuite.scala    From crdt   with Apache License 2.0 5 votes vote down vote up
package com.machinomy.crdt.state

import cats.kernel.{Eq, Monoid}
import cats.syntax.all._
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class GCounterSuite extends FunSuite with PropertyChecks {
  val replicaGen = Gen.posNum[Int]
  val valueGen = Gen.posNum[Int]
  val counterGen = for {
    id <- replicaGen
    value <- valueGen
  } yield GCounter[Int, Int]() + (id -> value)
  val eq = implicitly[Eq[GCounter[Int, Int]]]

  test("Fresh GCounter is empty") {
    val fresh = GCounter[Int, Int]()
    assert(Monoid[GCounter[Int, Int]].isEmpty(fresh))
    assert(fresh.value === 0)
  }

  test("could be calculated") {
    val counter = GCounter[Int, Int]().increment(1, 2).increment(2, 3)
    assert(counter.value === 5)
  }

  test("could be combined") {
    val a = GCounter[Int, Int]() + (1, 2) + (2, 3)
    val b = GCounter[Int, Int]() + (1, 2) + (3, 4)
    val c = a |+| b
    assert(c.value === 2 + 3 + 4)
  }

  test("could present replica value") {
    val a = GCounter[Int, Int]()
    assert(a.get(0) === 0)
    val b = a.increment(1, 2).increment(2, 3)
    assert(b.get(1) === 2)
    assert(b.get(2) === 3)
  }

  test("equality") {
    val a = GCounter[Int, Int]()
    val b = GCounter[Int, Int]()
    assert(eq.eqv(a, b))

    val a1 = a + (1 -> 1)
    assert(eq.neqv(a1, b))
    val b1 = b + (1 -> 2)
    assert(a1 !== b1)
    assert(eq.neqv(a1, b1))
    val a2 = a1 + (1 -> 1)
    assert(eq.eqv(a2, b1))
  }

  test("associativity") {
    forAll(Gen.listOfN(3, counterGen)) {
      case x :: y :: z :: Nil =>
        val left = x |+| (y |+| z)
        val right = (x |+| y) |+| z
        assert(eq.eqv(left, right))
      case _ => throw new RuntimeException("This is unexpected, really")
    }
  }

  test("commutativity") {
    forAll(Gen.listOfN(2, counterGen)) {
      case x :: y :: Nil =>
        val left = x |+| y
        val right = y |+| x
        assert(eq.eqv(left, right))
      case _ => throw new RuntimeException("This is unexpected, really")
    }
  }

  test("idempotency") {
    forAll(Gen.listOf(counterGen)) { list =>
      whenever(list.nonEmpty) {
        val counter = list.reduce(_ |+| _)
        assert(eq.eqv(counter, counter |+| counter))
      }
    }
  }
} 
Example 167
Source File: TestObjects.scala    From elastic-indexer4s   with MIT License 5 votes vote down vote up
package com.yannick_cw.elastic_indexer4s.elasticsearch

import com.sksamuel.elastic4s.http.{ElasticClient, ElasticNodeEndpoint}
import com.sksamuel.elastic4s.mappings.{FieldDefinition, KeywordField, ObjectField, TextField}
import com.yannick_cw.elastic_indexer4s.elasticsearch.elasic_config.{
  ElasticWriteConfig,
  MappingSetting,
  TypedMappingSetting
}
import io.circe.Json
import io.circe.parser.parse
import org.scalacheck.Gen

import scala.concurrent.duration._

object TestObjects {
  case class Address(street: String, zip: Int)
  case class User(name: String, age: Int, address: Address)
  case class NotMatchingUser(name: Int)

  private val addressGen: Gen[Address] = for {
    street <- Gen.alphaStr
    zip    <- Gen.posNum[Int]
  } yield Address(street, zip)

  private val userGen = for {
    name    <- Gen.alphaStr
    age     <- Gen.posNum[Int]
    address <- addressGen
  } yield User(name, age, address)

  def randomUser: User = userGen.sample.get

  val userMappingDef: List[FieldDefinition] = List(
    TextField("name"),
    KeywordField("age"),
    ObjectField("address").fields(
      TextField("street"),
      KeywordField("zip")
    )
  )

  def jsonSettingMapping(docType: String, shards: Int, replicas: Int): Json =
    parse(
      s"""
      |{
      |  "settings": {
      |    "number_of_shards": $shards,
      |    "number_of_replicas": $replicas
      |  },
      |  "mappings": {
      |    "$docType": {
      |      "properties" : {
      |        "address" : {
      |          "properties" : {
      |            "street" : {
      |              "type" : "text"
      |            },
      |            "zip" : {
      |              "type" : "integer"
      |            }
      |          }
      |        },
      |        "age" : {
      |          "type" : "integer"
      |        },
      |        "name" : {
      |          "type" : "text"
      |        }
      |      }
      |    }
      |  }
      |}
      |
      |
    """.stripMargin
    ).fold(throw _, identity)

  def testConf(
      mappingSetting: MappingSetting = TypedMappingSetting(),
      waitForEs: FiniteDuration = 1 second
  )(implicit c: ElasticClient): ElasticWriteConfig =
    new ElasticWriteConfig(
      elasticNodeEndpoints = List(ElasticNodeEndpoint("http", "host", 0, None)),
      indexPrefix = "test_index",
      docType = "docType",
      mappingSetting = mappingSetting,
      waitForElasticTimeout = waitForEs
    ) { override lazy val client: ElasticClient = c }
} 
Example 168
Source File: PeopleGenerators.scala    From finch-template   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.redbubble.finchtemplate.util.spec

import com.redbubble.finchtemplate.model.Person
import com.redbubble.finchtemplate.model.people.{BirthYear, HairColour, Name}
import org.scalacheck.Gen

trait PeopleGenerators extends GenHelpers {
  val genName: Gen[Name] = genNonEmptyString.map(Name)
  val genHairColour: Gen[HairColour] = genNonEmptyString.map(HairColour)
  val genBirthYear: Gen[BirthYear] = genNonEmptyString.map(BirthYear)

  val genPerson: Gen[Person] = for {
    n <- genName
    c <- genHairColour
    y <- genBirthYear
  } yield Person(n, y, c)
} 
Example 169
Source File: StateSyntheticBenchmark.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state

import java.util.concurrent.TimeUnit

import com.wavesplatform.account.KeyPair
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.lang.directives.values._
import com.wavesplatform.lang.script.v1.ExprScript
import com.wavesplatform.lang.utils._
import com.wavesplatform.lang.v1.compiler.ExpressionCompiler
import com.wavesplatform.lang.v1.parser.Parser
import com.wavesplatform.settings.FunctionalitySettings
import com.wavesplatform.state.StateSyntheticBenchmark._
import com.wavesplatform.transaction.Asset.Waves
import com.wavesplatform.transaction.Transaction
import com.wavesplatform.transaction.smart.SetScriptTransaction
import com.wavesplatform.transaction.transfer._
import org.openjdk.jmh.annotations._
import org.scalacheck.Gen

@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Array(Mode.AverageTime))
@Threads(1)
@Fork(1)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
class StateSyntheticBenchmark {

  @Benchmark
  def appendBlock_test(db: St): Unit = db.genAndApplyNextBlock()

  @Benchmark
  def appendBlock_smart_test(db: SmartSt): Unit = db.genAndApplyNextBlock()

}

object StateSyntheticBenchmark {

  @State(Scope.Benchmark)
  class St extends BaseState {
    protected override def txGenP(sender: KeyPair, ts: Long): Gen[Transaction] =
      for {
        amount    <- Gen.choose(1, waves(1))
        recipient <- accountGen
      } yield TransferTransaction.selfSigned(1.toByte, sender, recipient.toAddress, Waves, amount, Waves, 100000, ByteStr.empty, ts).explicitGet()
  }

  @State(Scope.Benchmark)
  class SmartSt extends BaseState {

    override protected def updateFunctionalitySettings(base: FunctionalitySettings): FunctionalitySettings = {
      base.copy(preActivatedFeatures = Map(4.toShort -> 0))
    }

    protected override def txGenP(sender: KeyPair, ts: Long): Gen[Transaction] =
      for {
        recipient: KeyPair <- accountGen
        amount             <- Gen.choose(1, waves(1))
      } yield TransferTransaction
        .selfSigned(2.toByte, sender, recipient.toAddress, Waves, amount, Waves, 1000000, ByteStr.empty, ts)
        .explicitGet()

    @Setup
    override def init(): Unit = {
      super.init()

      val textScript    = "sigVerify(tx.bodyBytes,tx.proofs[0],tx.senderPublicKey)"
      val untypedScript = Parser.parseExpr(textScript).get.value
      val typedScript   = ExpressionCompiler(compilerContext(V1, Expression, isAssetScript = false), untypedScript).explicitGet()._1

      val setScriptBlock = nextBlock(
        Seq(
          SetScriptTransaction
            .selfSigned(1.toByte, richAccount, Some(ExprScript(typedScript).explicitGet()), 1000000, System.currentTimeMillis())
            .explicitGet()
        )
      )

      applyBlock(setScriptBlock)
    }
  }

} 
Example 170
Source File: Base64Test.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.utils

import com.wavesplatform.common.utils.Base64
import org.scalacheck.Gen
import org.scalatest.{Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class Base64Test extends PropSpec with PropertyChecks with Matchers {

  private val Base64Chars  = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
  private val IllegalChars = "!@#$%^&*()_-?/.,<>|\';:`~"

  val illegalGen: Gen[String] =
    for {
      length <- Gen.chooseNum(100, 1024)
      chars <- Gen
        .listOfN(length, Gen.oneOf(Base64Chars ++ IllegalChars))
        .filter(_.toSet.intersect(IllegalChars.toSet).nonEmpty)
    } yield chars.mkString

  property("handles empty sequences") {
    Base64.encode(Array.emptyByteArray) shouldBe ""
    Base64.tryDecode("").get.length shouldBe 0
    Base64.tryDecode("base64:").get.length shouldBe 0
  }

  property("decoding fails on illegal characters") {
    forAll(illegalGen) { s =>
      Base64.tryDecode(s).isSuccess shouldBe false
    }
  }

  property("decoding fails on null") {
    Base64.tryDecode(null).isSuccess shouldBe false
  }
} 
Example 171
Source File: Base58Test.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.utils

import com.wavesplatform.common.utils.{Base58, FastBase58, StdBase58}
import org.scalacheck.Gen
import org.scalatest.{Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}
import scorex.util.encode.{Base58 => ScorexBase58}

class Base58Test extends PropSpec with PropertyChecks with Matchers {
  import org.scalacheck.Shrink
  implicit val noShrink: Shrink[String] = Shrink.shrinkAny

  private val Base58Chars  = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
  private val IllegalChars = "+/=-_0lIO"

  val base58Gen: Gen[String] =
    for {
      length <- Gen.chooseNum(20, 100)
      chars  <- Gen.listOfN(length, Gen.oneOf(Base58Chars))
    } yield chars.mkString

  val nonBase58Gen: Gen[String] =
    for {
      length <- Gen.chooseNum(20, 100)
      chars <- Gen
        .listOfN(length, Gen.oneOf(Base58Chars ++ IllegalChars))
        .filter(_.toSet.intersect(IllegalChars.toSet).nonEmpty)
    } yield chars.mkString

  property("works the same as scorex implementation") {
    forAll(base58Gen) { s =>
      val bytes       = StdBase58.decode(s)
      val scorexBytes = ScorexBase58.decode(s).get
      bytes.sameElements(scorexBytes) shouldBe true

      val str       = StdBase58.encode(bytes)
      val scorexStr = ScorexBase58.encode(bytes)
      str shouldBe scorexStr
    }
  }

  property("decodes the same as fast implementation") {
    forAll(base58Gen) { s =>
      val bytes     = StdBase58.decode(s)
      val fastBytes = FastBase58.decode(s)
      bytes.sameElements(fastBytes) shouldBe true

      val str     = StdBase58.encode(bytes)
      val fastStr = FastBase58.encode(bytes)
      str shouldBe fastStr
    }
  }

  property("encodes the same as fast implementation") {
    forAll(base58Gen) { s =>
      val bytes   = StdBase58.decode(s)
      val str     = StdBase58.encode(bytes)
      val fastStr = FastBase58.encode(bytes)
      str shouldBe fastStr
    }
  }

  property("handles zeroes at start") {
    val encodedString = "11WH5tQgZH6Djm7RS2guC"
    val bytes         = ScorexBase58.decode(encodedString).get

    val stdStr  = StdBase58.encode(bytes)
    val fastStr = FastBase58.encode(bytes)

    stdStr shouldBe fastStr
  }

  property("handles empty sequences") {
    StdBase58.encode(Array.emptyByteArray) shouldBe ""
    FastBase58.encode(Array.emptyByteArray) shouldBe ""

    StdBase58.decode("").toSeq shouldBe Nil
    FastBase58.decode("").toSeq shouldBe Nil
  }

  property("decoding fails on illegal characters") {
    forAll(nonBase58Gen) { invalidStr =>
      intercept[IllegalArgumentException](StdBase58.decode(invalidStr))
      intercept[IllegalArgumentException](FastBase58.decode(invalidStr))
      intercept[IllegalArgumentException](Base58.decode(invalidStr))
    }
  }
} 
Example 172
Source File: BlockGen.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform

import com.wavesplatform.account.KeyPair
import com.wavesplatform.block.Block
import com.wavesplatform.block.Block.{GenerationSignatureLength, GenerationVRFSignatureLength, ProtoBlockVersion}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.transaction.{ProvenTransaction, Transaction}
import org.scalacheck.Gen
import org.scalatest.Suite

trait BlockGen extends TransactionGen { _: Suite =>

  import BlockGen._

  val blockParamGen: Gen[(Seq[ProvenTransaction], KeyPair)] = for {
    count        <- Gen.choose(minTransactionsInBlockCount, maxTransactionsInBlockCount)
    transactions <- randomTransactionsGen(count)
    signer       <- accountGen
  } yield (transactions, signer)

  def versionedBlockGen(txs: Seq[Transaction], signer: KeyPair, version: Byte): Gen[Block] =
    byteArrayGen(Block.BlockIdLength).flatMap(ref => versionedBlockGen(ByteStr(ref), txs, signer, version))

  def versionedBlockGen(reference: ByteStr, txs: Seq[Transaction], signer: KeyPair, version: Byte): Gen[Block] =
    for {
      baseTarget <- Gen.posNum[Long]
      genSig     <- if (version < ProtoBlockVersion) byteArrayGen(GenerationSignatureLength) else byteArrayGen(GenerationVRFSignatureLength)
      timestamp  <- timestampGen
    } yield Block
      .buildAndSign(
        version,
        if (txs.isEmpty) timestamp else txs.map(_.timestamp).max,
        reference,
        baseTarget,
        ByteStr(genSig),
        txs,
        signer,
        Seq.empty,
        -1L
      )
      .explicitGet()

  def blockGen(txs: Seq[Transaction], signer: KeyPair): Gen[Block] = versionedBlockGen(txs, signer, 1)

  val randomSignerBlockGen: Gen[Block] = for {
    (transactions, signer) <- blockParamGen
    block                  <- blockGen(transactions, signer)
  } yield block

  val predefinedSignerBlockGen: Gen[Block] = for {
    (transactions, _) <- blockParamGen
    signer            <- Gen.const(predefinedSignerPrivateKey)
    block             <- blockGen(transactions, signer)
  } yield block

  val mixedBlockGen: Gen[Block] = for {
    block <- Gen.oneOf(randomSignerBlockGen, predefinedSignerBlockGen)
  } yield block

  def blocksSeqGen(blockGen: Gen[Block]): Gen[(Int, Int, Seq[Block])] =
    for {
      start      <- Gen.posNum[Int].label("from")
      end        <- Gen.chooseNum(start, start + 20).label("to")
      blockCount <- Gen.choose(0, end - start + 1).label("actualBlockCount")
      blocks     <- Gen.listOfN(blockCount, blockGen).label("blocks")
    } yield (start, end, blocks)

  val randomBlocksSeqGen: Gen[(Int, Int, Seq[Block])] = blocksSeqGen(randomSignerBlockGen)

  val mixedBlocksSeqGen: Gen[(Int, Int, Seq[Block])] = blocksSeqGen(mixedBlockGen)

}

object BlockGen {
  val minTransactionsInBlockCount         = 1
  val maxTransactionsInBlockCount         = 100
  val predefinedSignerPrivateKey: KeyPair = KeyPair(ByteStr(Array.tabulate(10)(_.toByte)))
} 
Example 173
Source File: SetScriptTransactionSpecification.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.transaction

import com.wavesplatform.account.{KeyPair, PublicKey}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.{Base64, EitherExt2}
import com.wavesplatform.transaction.smart.SetScriptTransaction
import org.scalacheck.Gen
import play.api.libs.json._

class SetScriptTransactionSpecification extends GenericTransactionSpecification[SetScriptTransaction] {

  def transactionParser: TransactionParser = SetScriptTransaction

  def updateProofs(tx: SetScriptTransaction, p: Proofs): SetScriptTransaction = {
    tx.copy(1.toByte, proofs = p)
  }

  def assertTxs(f: Transaction, second: SetScriptTransaction): Unit = f match {
    case first: SetScriptTransaction =>
      first.sender shouldEqual second.sender
      first.timestamp shouldEqual second.timestamp
      first.fee shouldEqual second.fee
      first.version shouldEqual second.version
      first.proofs shouldEqual second.proofs
      first.bytes() shouldEqual second.bytes()
      first.script shouldEqual second.script
  }

  def generator: Gen[((Seq[com.wavesplatform.transaction.Transaction], SetScriptTransaction))] = setScriptTransactionGen.map(t => (Seq(), t))

  def jsonRepr: Seq[(JsValue, SetScriptTransaction)] =
    Seq(
      (
        Json.parse("""{
                       "type": 13,
                       "id": "Cst37pKJ19WnUZSD6mjqywosMJDbqatuYm2sFAbXrysE",
                       "sender": "3N5GRqzDBhjVXnCn44baHcz2GoZy5qLxtTh",
                       "senderPublicKey": "FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z",
                       "fee": 100000,
                       "feeAssetId": null,
                       "timestamp": 1526983936610,
                       "proofs": [
                       "tcTr672rQ5gXvcA9xCGtQpkHC8sAY1TDYqDcQG7hQZAeHcvvHFo565VEv1iD1gVa3ZuGjYS7hDpuTnQBfY2dUhY"
                       ],
                       "version": 1,
                       "chainId": 84,
                       "script": null
                       }
    """),
        SetScriptTransaction
          .create(
            1.toByte,
            PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet(),
            None,
            100000,
            1526983936610L,
            Proofs(Seq(ByteStr.decodeBase58("tcTr672rQ5gXvcA9xCGtQpkHC8sAY1TDYqDcQG7hQZAeHcvvHFo565VEv1iD1gVa3ZuGjYS7hDpuTnQBfY2dUhY").get))
          )
          .explicitGet()
      )
    )

  def transactionName: String = "SetScriptTransaction"

  property("SetScriptTransaction id doesn't depend on proof (spec)") {
    forAll(accountGen, proofsGen, proofsGen, contractOrExpr) {
      case (acc: KeyPair, proofs1, proofs2, script) =>
        val tx1 = SetScriptTransaction.create(1.toByte, acc.publicKey, Some(script), 1, 1, proofs1).explicitGet()
        val tx2 = SetScriptTransaction.create(1.toByte, acc.publicKey, Some(script), 1, 1, proofs2).explicitGet()
        tx1.id() shouldBe tx2.id()
    }
  }

  override def preserBytesJson: Option[(Array[TxVersion], JsValue)] =
    Some(
      Base64.decode(
        "AA0BVM0TkdpiFV5gEBKCPA/ywRDiYs057r7FRwiXfwlf5tB1AQAfAQkAAGQAAAACAAAAAAAAAAABAAAAAAAAAAAB/cLTbwAAAAACODUuPMqjnZaOKXYBAAEAQIluaI2QJaNachtUD0FI1RzgcY0NmElIyp/0V06TAljDP4NlAt2XUHme3asul95ah/3/5E7JE9a/NXjvxDx4iA8="
      ) -> Json.parse(
        """
          |{
          |  "senderPublicKey" : "EoXtNDWGV5XsjiEAZXufddF57a1FdWhypJnps92CAdp8",
          |  "sender" : "3NBy87bQasxRkFTfMM8sq6MDbVUiPGS95g8",
          |  "feeAssetId" : null,
          |  "chainId" : 84,
          |  "proofs" : [ "3kNEbDaUaCZudgk5V5iJtTEY5Tm6NPLjbE2Jh8cF3ruSRtyRcSdnKqCtUWC8qQnwfpVttio3CftsTC7mbNsBsLo8" ],
          |  "fee" : 37238062,
          |  "id" : "HkZwtM5u9H5FAV8ihaKJo5nBj3rj9yYL9mJoLcuecK29",
          |  "type" : 13,
          |  "version" : 1,
          |  "script" : "base64:AQkAAGQAAAACAAAAAAAAAAABAAAAAAAAAAAB/cLTbw==",
          |  "timestamp" : 4380493484802320758
          |}
          |""".stripMargin
      )
    )
} 
Example 174
Source File: GenericTransactionSpecification.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.transaction

import com.wavesplatform.{TransactionGen, crypto}
import org.scalacheck.Gen
import org.scalatest._
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}
import play.api.libs.json._

abstract class GenericTransactionSpecification[T <: com.wavesplatform.transaction.Transaction]
    extends PropSpec
    with PropertyChecks
    with Matchers
    with TransactionGen {

  def transactionParser: com.wavesplatform.transaction.TransactionParser
  def updateProofs(tx: T, p: Proofs): T
  def generator: Gen[(Seq[com.wavesplatform.transaction.Transaction], T)]
  def assertTxs(first: Transaction, second: T): Unit
  def jsonRepr: Seq[(JsValue, T)]
  def transactionName: String
  def preserBytesJson: Option[(Array[Byte], JsValue)] = None

  property(s"$transactionName serialization roundtrip") {
    forAll(generator) {
      case (_, tx) =>
        assertTxs(transactionParser.parseBytes(tx.bytes()).get, tx)
    }
  }

  preserBytesJson.foreach {
    case (bytes, json) =>
      property(s"$transactionName deserialize bytes") {
        val tx = transactionParser.parseBytes(bytes).get
        tx.json() shouldBe json
        tx match {
          case tx: ProvenTransaction =>
            assert(crypto.verify(tx.signature, tx.bodyBytes(), tx.sender), "signature should be valid")

          case _ => // Ignore
        }
      }
  }

  property(s"$transactionName serialization from TypedTransaction") {
    forAll(generator) { t =>
      val tx        = t._2
      val recovered = TransactionParsers.parseBytes(tx.bytes()).get
      assertTxs(recovered.asInstanceOf[T], tx)
    }
  }

  property(s"$transactionName id doesn't depend on proof") {
    forAll(generator, proofsGen) {
      case ((pref, tx), proofs1) =>
        val tx1 = updateProofs(tx, proofs1)
        tx1.id() shouldBe tx.id()
    }
  }

  property(s"$transactionName JSON format validation") {
    for ((js, tx) <- jsonRepr) {
      js shouldEqual tx.json()
    }
  }
} 
Example 175
Source File: GenesisTransactionSpecification.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.transaction

import com.wavesplatform.account.{KeyPair, PublicKey}
import com.wavesplatform.common.utils.{Base58, EitherExt2}
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest._
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class GenesisTransactionSpecification extends PropSpec with PropertyChecks with Matchers {

  private val defaultRecipient = PublicKey(Array.fill(32)(0: Byte))

  property("GenesisTransaction Signature should be the same") {
    val balance   = 457L
    val timestamp = 2398762345L
    val signature = GenesisTransaction.generateSignature(defaultRecipient.toAddress, balance, timestamp)

    val expected = "3L4zhpN1o6TysvM8FZFv1NmSEjpGSgV4V71e2iJwseFrrt65aZJiyXwqj5WpigLAn296sUrFb9yN8fdsY7GSdwwR"
    val actual   = Base58.encode(signature)

    assert(actual == expected)
  }

  property("GenesisTransaction parse from Bytes should work fine") {
    val bytes = Base58.tryDecodeWithLimit("5GoidXWjBfzuS9tZm4Fp6GAXUYFunVMsoWAew3eBnDbmaDi7WiP9yVpBD2").get

    val actualTransaction = GenesisTransaction.parseBytes(bytes).get

    val balance             = 12345L
    val timestamp           = 1234567890L
    val expectedTransaction = GenesisTransaction.create(defaultRecipient.toAddress, balance, timestamp).explicitGet()

    actualTransaction should equal(expectedTransaction)
  }

  property("GenesisTransaction serialize/deserialize roundtrip") {
    forAll(Gen.listOfN(32, Arbitrary.arbitrary[Byte]).map(_.toArray), Gen.posNum[Long], Gen.posNum[Long]) {
      (recipientSeed: Array[Byte], time: Long, amount: Long) =>
        val recipient = KeyPair(recipientSeed)
        val source    = GenesisTransaction.create(recipient.toAddress, amount, time).explicitGet()
        val bytes     = source.bytes()
        val dest      = GenesisTransaction.parseBytes(bytes).get

        source should equal(dest)
    }
  }

} 
Example 176
Source File: MicroBlockInvSpecSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.crypto._
import com.wavesplatform.{EitherMatchers, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.concurrent.Eventually
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class MicroBlockInvSpecSpec extends FreeSpec with Matchers with EitherMatchers with PropertyChecks with Eventually with TransactionGen {

  private val microBlockInvGen: Gen[MicroBlockInv] = for {
    acc          <- accountGen
    totalSig     <- byteArrayGen(SignatureLength)
    prevBlockSig <- byteArrayGen(SignatureLength)
  } yield MicroBlockInv(acc, ByteStr(totalSig), ByteStr(prevBlockSig))

  "MicroBlockInvMessageSpec" - {
    import MicroBlockInvSpec._

    "deserializeData(serializedData(data)) == data" in forAll(microBlockInvGen) { inv =>
      inv.signaturesValid() should beRight
      val restoredInv = deserializeData(serializeData(inv)).get
      restoredInv.signaturesValid() should beRight

      restoredInv shouldBe inv
    }
  }

} 
Example 177
Source File: HandshakeDecoderSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import java.nio.charset.StandardCharsets

import com.google.common.primitives.{Ints, Longs}
import com.wavesplatform.{NoShrink, TransactionGen}
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
import org.scalacheck.{Arbitrary, Gen}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class HandshakeDecoderSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen with NoShrink {

  "should read a handshake and remove itself from the pipeline" in {
    var mayBeDecodedHandshake: Option[Handshake] = None

    val channel = new EmbeddedChannel(
      new HandshakeDecoder(PeerDatabase.NoOp),
      new ChannelInboundHandlerAdapter {
        override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = msg match {
          case x: Handshake => mayBeDecodedHandshake = Some(x)
          case _            =>
        }
      }
    )

    val origHandshake = new Handshake(
      applicationName = "wavesI",
      applicationVersion = (1, 2, 3),
      nodeName = "test",
      nodeNonce = 4,
      declaredAddress = None
    )

    val buff = Unpooled.buffer
    origHandshake.encode(buff)
    buff.writeCharSequence("foo", StandardCharsets.UTF_8)

    channel.writeInbound(buff)

    mayBeDecodedHandshake should contain(origHandshake)
  }

  private val invalidHandshakeBytes: Gen[Array[Byte]] = {
    // To bypass situations where the appNameLength > whole buffer and HandshakeDecoder waits for next bytes
    val appName  = "x" * Byte.MaxValue
    val nodeName = "y" * Byte.MaxValue

    val appNameBytes   = appName.getBytes(StandardCharsets.UTF_8)
    val versionBytes   = Array(1, 2, 3).flatMap(Ints.toByteArray)
    val nodeNameBytes  = nodeName.getBytes(StandardCharsets.UTF_8)
    val nonceBytes     = Longs.toByteArray(1)
    val timestampBytes = Longs.toByteArray(System.currentTimeMillis() / 1000)

    val validDeclaredAddressLen = Set(0, 8, 20)
    val invalidBytesGen = Gen.listOfN(3, Arbitrary.arbByte.arbitrary).filter {
      case List(appNameLen, nodeNameLen, declaredAddressLen) =>
        !(appNameLen == appNameBytes.size || nodeNameLen == nodeNameBytes.size ||
          validDeclaredAddressLen.contains(declaredAddressLen))
      case _ =>
        false
    }

    invalidBytesGen.map {
      case List(appNameLen, nodeNameLen, declaredAddressLen) =>
        Array(appNameLen) ++
          appNameBytes ++
          versionBytes ++
          Array(nodeNameLen) ++
          nodeNameBytes ++
          nonceBytes ++
          Array(declaredAddressLen) ++
          timestampBytes
    }
  }

  "should blacklist a node sends an invalid handshake" in forAll(invalidHandshakeBytes) { bytes: Array[Byte] =>
    val decoder = new SpiedHandshakeDecoder
    val channel = new EmbeddedChannel(decoder)

    val buff = Unpooled.buffer
    buff.writeBytes(bytes)

    channel.writeInbound(buff)
    decoder.blockCalls shouldBe >(0)
  }

  private class SpiedHandshakeDecoder extends HandshakeDecoder(PeerDatabase.NoOp) {
    var blockCalls = 0

    override protected def block(ctx: ChannelHandlerContext, e: Throwable): Unit = {
      blockCalls += 1
    }
  }

} 
Example 178
Source File: RequestsSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.account.KeyPair
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.transaction.transfer.TransferTransaction
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.{FreeSpec, Matchers, OptionValues}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import play.api.libs.json._

class RequestsSpec extends FreeSpec with Matchers with OptionValues with ScalaCheckPropertyChecks with TransactionGen with NoShrink {
  private def transferRequestGen(version: Int): Gen[(KeyPair, JsObject)] =
    (for {
      sender    <- accountGen
      recipient <- accountGen
      proofs    <- proofsGen
    } yield (
      sender,
      Json.obj(
        "type"            -> 4,
        "version"         -> version,
        "senderPublicKey" -> sender.publicKey.toString,
        "assetId"         -> JsNull,
        "attachment"      -> "",
        "feeAssetId"      -> JsNull,
        "timestamp"       -> System.currentTimeMillis(),
        "fee"             -> 100000,
        "amount"          -> 10000,
        "recipient"       -> recipient.publicKey.toAddress.stringRepr,
        "proofs"          -> JsArray(proofs.proofs.map(p => JsString(p.toString)))
      )
    )).label(s"Transfer Request v$version")

  "TransferRequest" - {
    "accepts proofs for version >= 2" in {
      TransferTransaction.supportedVersions.filter(_ >= 2).foreach { version =>
        forAll(transferRequestGen(version)) {
          case (sender, json) =>
            val request = json.as[TransferRequest]
            val tx      = request.toTxFrom(sender.publicKey).explicitGet()

            request.proofs.value should be(tx.proofs)
        }
      }

    }
  }
} 
Example 179
Source File: FeatureProviderTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.features

import com.wavesplatform.block.Block
import com.wavesplatform.settings.{BlockchainSettings, FunctionalitySettings, GenesisSettings, RewardsSettings}
import com.wavesplatform.state.Blockchain
import org.scalacheck.Gen
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class FeatureProviderTest extends FlatSpec with Matchers with ScalaCheckPropertyChecks with MockFactory {
  "blockVersionAt" should "return valid version" in {
    val fs                 = FunctionalitySettings.MAINNET
    val v3ActivationHeight = fs.blockVersion3AfterHeight
    val v4ActivationHeight = 1740000
    val v5ActivationHeight = 2000000

    val genesisAt = 1
    val plainAt   = (2 to fs.blockVersion3AfterHeight + 1).toSet
    val ngAt      = (v3ActivationHeight + 2 to v4ActivationHeight).toSet
    val rewardAt  = (v4ActivationHeight + 1 until v5ActivationHeight).toSet

    val features = Map(
      BlockchainFeatures.BlockReward.id -> v4ActivationHeight,
      BlockchainFeatures.BlockV5.id     -> v5ActivationHeight
    )

    val blockchain = mock[Blockchain]
    (blockchain.activatedFeatures _).expects().anyNumberOfTimes().returning(features)
    (blockchain.settings _).expects().anyNumberOfTimes().returning(BlockchainSettings('W', fs, GenesisSettings.MAINNET, RewardsSettings.MAINNET))

    forAll(Gen.choose(1, v5ActivationHeight * 2)) { h =>
      if (h == genesisAt) blockchain.blockVersionAt(h) shouldBe Block.GenesisBlockVersion
      else if (plainAt contains h) blockchain.blockVersionAt(h) shouldBe Block.PlainBlockVersion
      else if (ngAt contains h) blockchain.blockVersionAt(h) shouldBe Block.NgBlockVersion
      else if (rewardAt contains h) blockchain.blockVersionAt(h) shouldBe Block.RewardBlockVersion
      else blockchain.blockVersionAt(h) shouldBe Block.ProtoBlockVersion
    }

    blockchain.blockVersionAt(v3ActivationHeight) shouldBe Block.PlainBlockVersion
    blockchain.blockVersionAt(v3ActivationHeight + 1) shouldBe Block.PlainBlockVersion
    blockchain.blockVersionAt(v3ActivationHeight + 2) shouldBe Block.NgBlockVersion

    blockchain.blockVersionAt(v4ActivationHeight) shouldBe Block.NgBlockVersion
    blockchain.blockVersionAt(v4ActivationHeight + 1) shouldBe Block.RewardBlockVersion

    blockchain.blockVersionAt(v5ActivationHeight) shouldBe Block.ProtoBlockVersion
  }
} 
Example 180
Source File: NgStateTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state

import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.history._
import com.wavesplatform.state.diffs._
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.{Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class NgStateTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink {

  def preconditionsAndPayments(amt: Int): Gen[(GenesisTransaction, Seq[TransferTransaction])] =
    for {
      master    <- accountGen
      recipient <- accountGen
      ts        <- positiveIntGen
      genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      payments: Seq[TransferTransaction] <- Gen.listOfN(amt, wavesTransferGeneratorP(master, recipient.toAddress))
    } yield (genesis, payments)

  property("can forge correctly signed blocks") {
    forAll(preconditionsAndPayments(10)) {
      case (genesis, payments) =>
        val (block, microBlocks) = chainBaseAndMicro(randomSig, genesis, payments.map(t => Seq(t)))

        val ng = new NgState(block, Diff.empty, 0L, 0L, Set.empty, None, block.header.generationSignature, Map.empty)
        microBlocks.foreach(m => ng.append(m, Diff.empty, 0L, 0L, 0L))

        ng.totalDiffOf(microBlocks.last.totalResBlockSig)
        microBlocks.foreach { m =>
          val (forged, _, _, _, _) = ng.totalDiffOf(m.totalResBlockSig).get
          forged.signatureValid() shouldBe true
        }
        Seq(microBlocks(4)).map(x => ng.totalDiffOf(x.totalResBlockSig))
    }
  }

  property("can resolve best liquid block") {
    forAll(preconditionsAndPayments(5)) {
      case (genesis, payments) =>
        val (block, microBlocks) = chainBaseAndMicro(randomSig, genesis, payments.map(t => Seq(t)))

        val ng = new NgState(block, Diff.empty, 0L, 0L, Set.empty, None, block.header.generationSignature, Map.empty)
        microBlocks.foreach(m => ng.append(m, Diff.empty, 0L, 0L, 0L))

        ng.bestLiquidBlock.id() shouldBe microBlocks.last.totalResBlockSig

        new NgState(block, Diff.empty, 0L, 0L, Set.empty, Some(0), block.header.generationSignature, Map.empty).bestLiquidBlock.id() shouldBe block.id()
    }
  }

  property("can resolve best last block") {
    forAll(preconditionsAndPayments(5)) {
      case (genesis, payments) =>
        val (block, microBlocks) = chainBaseAndMicro(randomSig, genesis, payments.map(t => Seq(t)))

        val ng = new NgState(block, Diff.empty, 0L, 0L, Set.empty, None, block.header.generationSignature, Map.empty)

        microBlocks.foldLeft(1000) {
          case (thisTime, m) =>
            ng.append(m, Diff.empty, 0L, 0L, thisTime)
            thisTime + 50
        }

        ng.bestLastBlockInfo(0).blockId shouldBe block.id()
        ng.bestLastBlockInfo(1001).blockId shouldBe microBlocks.head.totalResBlockSig
        ng.bestLastBlockInfo(1051).blockId shouldBe microBlocks.tail.head.totalResBlockSig
        ng.bestLastBlockInfo(2000).blockId shouldBe microBlocks.last.totalResBlockSig

        new NgState(block, Diff.empty, 0L, 0L, Set.empty, Some(0), block.header.generationSignature, Map.empty).bestLiquidBlock.id() shouldBe block.id()
    }
  }

  property("calculates carry fee correctly") {
    forAll(preconditionsAndPayments(5)) {
      case (genesis, payments) =>
        val (block, microBlocks) = chainBaseAndMicro(randomSig, genesis, payments.map(t => Seq(t)))

        val ng = new NgState(block, Diff.empty, 0L, 0L, Set.empty, None, block.header.generationSignature, Map.empty)
        microBlocks.foreach(m => ng.append(m, Diff.empty, 1L, 0L, 0L))

        ng.totalDiffOf(block.id()).map(_._3) shouldBe Some(0L)
        microBlocks.zipWithIndex.foreach {
          case (m, i) =>
            val u = ng.totalDiffOf(m.totalResBlockSig).map(_._3)
            u shouldBe Some(i + 1)
        }
        ng.carryFee shouldBe microBlocks.size
    }
  }
} 
Example 181
Source File: StateReaderEffectiveBalancePropertyTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.reader

import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.features.BlockchainFeatures._
import com.wavesplatform.lagonaki.mocks.TestBlock.{create => block}
import com.wavesplatform.settings.TestFunctionalitySettings.Enabled
import com.wavesplatform.state.LeaseBalance
import com.wavesplatform.state.diffs._
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.transaction.lease.LeaseTransaction
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class StateReaderEffectiveBalancePropertyTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {
  property("No-interactions genesis account's effectiveBalance doesn't depend on depths") {
    val setup: Gen[(GenesisTransaction, Int, Int, Int)] = for {
      master <- accountGen
      ts     <- positiveIntGen
      genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      emptyBlocksAmt <- Gen.choose(1, 10)
      atHeight       <- Gen.choose(1, 20)
      confirmations  <- Gen.choose(1, 20)
    } yield (genesis, emptyBlocksAmt, atHeight, confirmations)

    forAll(setup) {
      case (genesis: GenesisTransaction, emptyBlocksAmt, atHeight, confirmations) =>
        val genesisBlock = block(Seq(genesis))
        val nextBlocks   = List.fill(emptyBlocksAmt - 1)(block(Seq.empty))
        assertDiffAndState(genesisBlock +: nextBlocks, block(Seq.empty)) { (_, newState) =>
          newState.effectiveBalance(genesis.recipient, confirmations) shouldBe genesis.amount
        }
    }
  }

  property("Negative generating balance case") {
    val fs  = Enabled.copy(preActivatedFeatures = Map(SmartAccounts.id -> 0, SmartAccountTrading.id -> 0))
    val Fee = 100000
    val setup = for {
      master <- accountGen
      ts     <- positiveLongGen
      genesis = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      leaser <- accountGen
      xfer1  <- transferGeneratorPV2(ts + 1, master, leaser.toAddress, ENOUGH_AMT / 3)
      lease1 = LeaseTransaction.selfSigned(2.toByte, leaser, master.toAddress, xfer1.amount - Fee, Fee, ts + 2).explicitGet()
      xfer2 <- transferGeneratorPV2(ts + 3, master, leaser.toAddress, ENOUGH_AMT / 3)
      lease2 = LeaseTransaction.selfSigned(2.toByte, leaser, master.toAddress, xfer2.amount - Fee, Fee, ts + 4).explicitGet()
    } yield (leaser, genesis, xfer1, lease1, xfer2, lease2)

    forAll(setup) {
      case (leaser, genesis, xfer1, lease1, xfer2, lease2) =>
        assertDiffAndState(Seq(block(Seq(genesis)), block(Seq(xfer1, lease1))), block(Seq(xfer2, lease2)), fs) { (_, state) =>
          val portfolio       = state.wavesPortfolio(lease1.sender.toAddress)
          val expectedBalance = xfer1.amount + xfer2.amount - 2 * Fee
          portfolio.balance shouldBe expectedBalance
          state.generatingBalance(leaser.toAddress, state.lastBlockId) shouldBe 0
          portfolio.lease shouldBe LeaseBalance(0, expectedBalance)
          portfolio.effectiveBalance shouldBe 0
        }
    }
  }
} 
Example 182
Source File: BalanceDiffValidationTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.settings.TestFunctionalitySettings
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.transaction.lease.LeaseTransaction
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class BalanceDiffValidationTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {

  val ownLessThatLeaseOut: Gen[(GenesisTransaction, TransferTransaction, LeaseTransaction, LeaseTransaction, TransferTransaction)] = for {
    master <- accountGen
    alice  <- accountGen
    bob    <- accountGen
    cooper <- accountGen
    ts     <- positiveIntGen
    amt    <- positiveLongGen
    fee    <- smallFeeGen
    genesis: GenesisTransaction                 = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
    masterTransfersToAlice: TransferTransaction = createWavesTransfer(master, alice.toAddress, amt, fee, ts).explicitGet()
    (aliceLeasesToBob, _)    <- leaseAndCancelGeneratorP(alice, bob.toAddress) suchThat (_._1.amount < amt)
    (masterLeasesToAlice, _) <- leaseAndCancelGeneratorP(master, alice.toAddress) suchThat (_._1.amount > aliceLeasesToBob.amount)
    transferAmt              <- Gen.choose(amt - fee - aliceLeasesToBob.amount, amt - fee)
    aliceTransfersMoreThanOwnsMinusLeaseOut = createWavesTransfer(alice, cooper.toAddress, transferAmt, fee, ts).explicitGet()

  } yield (genesis, masterTransfersToAlice, aliceLeasesToBob, masterLeasesToAlice, aliceTransfersMoreThanOwnsMinusLeaseOut)

  property("can transfer more than own-leaseOut before allow-leased-balance-transfer-until") {
    val settings = TestFunctionalitySettings.Enabled.copy(blockVersion3AfterHeight = 4)

    forAll(ownLessThatLeaseOut) {
      case (genesis, masterTransfersToAlice, aliceLeasesToBob, masterLeasesToAlice, aliceTransfersMoreThanOwnsMinusLeaseOut) =>
        assertDiffEi(
          Seq(TestBlock.create(Seq(genesis, masterTransfersToAlice, aliceLeasesToBob, masterLeasesToAlice))),
          TestBlock.create(Seq(aliceTransfersMoreThanOwnsMinusLeaseOut)),
          settings
        ) { totalDiffEi =>
          totalDiffEi.explicitGet()
        }
    }
  }

  property("cannot transfer more than own-leaseOut after allow-leased-balance-transfer-until") {
    val settings = TestFunctionalitySettings.Enabled.copy(blockVersion3AfterHeight = 4)

    forAll(ownLessThatLeaseOut) {
      case (genesis, masterTransfersToAlice, aliceLeasesToBob, masterLeasesToAlice, aliceTransfersMoreThanOwnsMinusLeaseOut) =>
        assertDiffEi(
          Seq(
            TestBlock.create(Seq(genesis)),
            TestBlock.create(Seq()),
            TestBlock.create(Seq()),
            TestBlock.create(Seq()),
            TestBlock.create(Seq(masterTransfersToAlice, aliceLeasesToBob, masterLeasesToAlice))
          ),
          TestBlock.create(Seq(aliceTransfersMoreThanOwnsMinusLeaseOut)),
          settings
        ) { totalDiffEi =>
          totalDiffEi should produce("trying to spend leased money")
        }
    }
  }
} 
Example 183
Source File: PaymentTransactionDiffTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import cats.Monoid
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.settings.TestFunctionalitySettings
import com.wavesplatform.state._
import com.wavesplatform.transaction.{GenesisTransaction, PaymentTransaction}
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class PaymentTransactionDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {

  val preconditionsAndPayments: Gen[(GenesisTransaction, PaymentTransaction, PaymentTransaction)] = for {
    master    <- accountGen
    recipient <- otherAccountGen(candidate = master)
    ts        <- positiveIntGen
    genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
    paymentV2: PaymentTransaction <- paymentGeneratorP(master, recipient.toAddress)
    paymentV3: PaymentTransaction <- paymentGeneratorP(master, recipient.toAddress)
  } yield (genesis, paymentV2, paymentV3)

  val settings = TestFunctionalitySettings.Enabled.copy(blockVersion3AfterHeight = 2)

  property("Diff doesn't break invariant before block version 3") {
    forAll(preconditionsAndPayments) {
      case ((genesis, paymentV2, _)) =>
        assertDiffAndState(Seq(TestBlock.create(Seq(genesis))), TestBlock.create(Seq(paymentV2)), settings) { (blockDiff, newState) =>
          val totalPortfolioDiff: Portfolio = Monoid.combineAll(blockDiff.portfolios.values)
          totalPortfolioDiff.balance shouldBe 0
          totalPortfolioDiff.effectiveBalance shouldBe 0
        }
    }
  }

  property("Validation fails with block version 3") {
    forAll(preconditionsAndPayments) {
      case ((genesis, paymentV2, paymentV3)) =>
        assertDiffEi(Seq(TestBlock.create(Seq(genesis)), TestBlock.create(Seq(paymentV2))), TestBlock.create(Seq(paymentV3)), settings) {
          blockDiffEi =>
            blockDiffEi should produce(s"Payment transaction is deprecated after h=${settings.blockVersion3AfterHeight}")
        }
    }
  }

} 
Example 184
Source File: TransactionFieldAccessTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart.scenarios

import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.lang.directives.values._
import com.wavesplatform.lang.utils._
import com.wavesplatform.lang.v1.compiler.ExpressionCompiler
import com.wavesplatform.lang.v1.parser.Parser
import com.wavesplatform.state.diffs.produce
import com.wavesplatform.state.diffs.smart._
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.transaction.lease.LeaseTransaction
import com.wavesplatform.transaction.smart.SetScriptTransaction
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class TransactionFieldAccessTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {

  private def preconditionsTransferAndLease(
      code: String): Gen[(GenesisTransaction, SetScriptTransaction, LeaseTransaction, TransferTransaction)] = {
    val untyped = Parser.parseExpr(code).get.value
    val typed   = ExpressionCompiler(compilerContext(V1, Expression, isAssetScript = false), untyped).explicitGet()._1
    preconditionsTransferAndLease(typed)
  }

  private val script =
    """
      |
      | match tx {
      | case ttx: TransferTransaction =>
      |       isDefined(ttx.assetId)==false
      | case _ =>
      |       false
      | }
      """.stripMargin

  property("accessing field of transaction without checking its type first results on exception") {
    forAll(preconditionsTransferAndLease(script)) {
      case ((genesis, script, lease, transfer)) =>
        assertDiffAndState(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(transfer)), smartEnabledFS) { case _ => () }
        assertDiffEi(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(lease)), smartEnabledFS)(totalDiffEi =>
          totalDiffEi should produce("TransactionNotAllowedByScript"))
    }
  }
} 
Example 185
Source File: TransferByIdTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart.scenarios

import com.wavesplatform.common.utils._
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.lang.directives.values.{Expression, V3}
import com.wavesplatform.lang.script.v1.ExprScript
import com.wavesplatform.lang.utils.compilerContext
import com.wavesplatform.lang.v1.compiler.ExpressionCompiler
import com.wavesplatform.lang.v1.parser.Parser
import com.wavesplatform.state.BinaryDataEntry
import com.wavesplatform.state.diffs.ENOUGH_AMT
import com.wavesplatform.state.diffs.smart.smartEnabledFS
import com.wavesplatform.transaction.smart.SetScriptTransaction
import com.wavesplatform.transaction.transfer.TransferTransaction
import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction}
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class TransferByIdTest extends PropSpec with ScalaCheckPropertyChecks with WithState with TransactionGen with NoShrink {

  val scriptSrc =
    s"""
       |match tx {
       |  case dtx: DataTransaction =>
       |    let txId    = extract(getBinary(dtx.data, "transfer_id"))
       |    let maybeTx = transferTransactionById(txId)
       |
       |    isDefined(maybeTx)
       |
       |  case _ => false
       |}
     """.stripMargin

  val expr = {
    val parsed = Parser.parseExpr(scriptSrc).get.value
    ExpressionCompiler(compilerContext(V3, Expression, isAssetScript = false), parsed).explicitGet()._1
  }

  def preconditions: Gen[(GenesisTransaction, TransferTransaction, SetScriptTransaction, DataTransaction)] =
    for {
      master    <- accountGen
      recipient <- accountGen
      ts        <- positiveIntGen
      genesis = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      setScript <- selfSignedSetScriptTransactionGenP(master, ExprScript(V3, expr).explicitGet())
      transfer <- Gen.oneOf[TransferTransaction](
        transferGeneratorP(ts, master, recipient.toAddress, ENOUGH_AMT / 2),
        transferGeneratorPV2(ts, master, recipient.toAddress, ENOUGH_AMT / 2)
      )
      data <- dataTransactionGenP(master, List(BinaryDataEntry("transfer_id", transfer.id())))
    } yield (genesis, transfer, setScript, data)

  property("Transfer by id works fine") {
    forAll(preconditions) {
      case (genesis, transfer, setScript, data) =>
        assertDiffEi(
          Seq(TestBlock.create(Seq(genesis, transfer))),
          TestBlock.create(Seq(setScript, data)),
          smartEnabledFS
        )(_ shouldBe an[Right[_, _]])
    }
  }
} 
Example 186
Source File: OracleDataTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart.scenarios

import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.lang.Global.MaxBase58Bytes
import com.wavesplatform.lang.directives.values._
import com.wavesplatform.lang.script.v1.ExprScript
import com.wavesplatform.lang.utils._
import com.wavesplatform.lang.v1.compiler.ExpressionCompiler
import com.wavesplatform.lang.v1.parser.Parser
import com.wavesplatform.state.diffs.TransactionDiffer.TransactionValidationError
import com.wavesplatform.state.diffs._
import com.wavesplatform.state.diffs.smart.smartEnabledFS
import com.wavesplatform.transaction.TxValidationError.ScriptExecutionError
import com.wavesplatform.transaction.smart.SetScriptTransaction
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.transaction.{CreateAliasTransaction, DataTransaction, GenesisTransaction, Proofs}
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.{Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class OracleDataTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink with Matchers {
  val preconditions
      : Gen[(GenesisTransaction, GenesisTransaction, CreateAliasTransaction, SetScriptTransaction, DataTransaction, TransferTransaction)] =
    for {
      master <- accountGen
      oracle <- accountGen
      alice  <- accountGen
      ts     <- positiveIntGen
      genesis  = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      genesis2 = GenesisTransaction.create(oracle.toAddress, ENOUGH_AMT, ts).explicitGet()
      alias           <- aliasGen
      createAlias     <- createAliasGen(oracle, alias, 400000, System.currentTimeMillis())
      long            <- longEntryGen(dataAsciiKeyGen)
      bool            <- booleanEntryGen(dataAsciiKeyGen).filter(_.key != long.key)
      bin             <- binaryEntryGen(MaxBase58Bytes, dataAsciiKeyGen).filter(e => e.key != long.key && e.key != bool.key)
      str             <- stringEntryGen(500, dataAsciiKeyGen).filter(e => e.key != long.key && e.key != bool.key && e.key != bin.key)
      dataTransaction <- dataTransactionGenP(oracle, List(long, bool, bin, str))
      allFieldsRequiredScript = s"""
                                   | match tx {
                                   | case t : DataTransaction =>
                                   |   let txId = match extract(transactionById(t.id)) {
                                   |     case d: DataTransaction => d.bodyBytes == base64'${ByteStr(dataTransaction.bodyBytes.apply()).base64}'
                                   |     case _ => false
                                   |   }
                                   |   let txHeightId = extract(transactionHeightById(t.id)) > 0
                                   |   txId && txHeightId
                                   | case _ : CreateAliasTransaction => true
                                   | case _ =>
                                   |   let oracle = Alias("${alias.name}")
                                   |   let long = extract(getInteger(oracle,"${long.key}")) == ${long.value}
                                   |   let bool = extract(getBoolean(oracle,"${bool.key}")) == ${bool.value}
                                   |   let bin = extract(getBinary(oracle,"${bin.key}")) == base58'${bin.value.toString}'
                                   |   let str = extract(getString(oracle,"${str.key}")) == "${str.value}"
                                   |   long && bool && bin && str
                                   |}""".stripMargin
      setScript <- {
        val untypedAllFieldsRequiredScript = Parser.parseExpr(allFieldsRequiredScript).get.value
        val typedAllFieldsRequiredScript =
          ExpressionCompiler(compilerContext(V1, Expression, isAssetScript = false), untypedAllFieldsRequiredScript).explicitGet()._1
        selfSignedSetScriptTransactionGenP(master, ExprScript(typedAllFieldsRequiredScript).explicitGet())
      }
      transferFromScripted <- versionedTransferGenP(master.publicKey, alice.toAddress, Proofs.empty)

    } yield (genesis, genesis2, createAlias, setScript, dataTransaction, transferFromScripted)

  property("simple oracle value required to transfer") {
    forAll(preconditions) {
      case (genesis, genesis2, createAlias, setScript, dataTransaction, transferFromScripted) =>
        assertDiffAndState(
          Seq(TestBlock.create(Seq(genesis, genesis2, createAlias, setScript, dataTransaction))),
          TestBlock.create(Seq(transferFromScripted)),
          smartEnabledFS
        ) { case _ => () }
        assertDiffEi(
          Seq(TestBlock.create(Seq(genesis, genesis2, createAlias, setScript))),
          TestBlock.create(Seq(transferFromScripted)),
          smartEnabledFS
        )(_ should matchPattern { case Left(TransactionValidationError(_: ScriptExecutionError, _)) => })
    }
  }
} 
Example 187
Source File: AddressFromRecipientScenarioTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart.scenarios

import com.wavesplatform.account.{AddressOrAlias, KeyPair}
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CaseObj}
import com.wavesplatform.state.diffs._
import com.wavesplatform.state.diffs.smart.predef._
import com.wavesplatform.transaction.Asset.Waves
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.transaction.{CreateAliasTransaction, GenesisTransaction}
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class AddressFromRecipientScenarioTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {

  val preconditionsAndAliasCreations: Gen[(Seq[GenesisTransaction], CreateAliasTransaction, TransferTransaction, TransferTransaction)] = for {
    master                   <- accountGen
    ts                       <- timestampGen
    other: KeyPair <- accountGen
    genesis1: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
    genesis2: GenesisTransaction = GenesisTransaction.create(other.toAddress, ENOUGH_AMT, ts).explicitGet()
    alias              <- aliasGen
    fee                <- smallFeeGen
    aliasTx            <- createAliasGen(other, alias, fee, ts)
    transferViaAddress <- transferGeneratorP(master, other.toAddress, Waves, Waves)
    transferViaAlias   <- transferGeneratorP(master, AddressOrAlias.fromBytes(alias.bytes, 0).explicitGet()._1, Waves, Waves)
  } yield (Seq(genesis1, genesis2), aliasTx, transferViaAddress, transferViaAlias)

  val script = """
    | match tx {
    |  case t : TransferTransaction =>  addressFromRecipient(t.recipient)
    |  case _ => throw()
    |  }
    |  """.stripMargin

  property("Script can resolve AddressOrAlias") {
    forAll(preconditionsAndAliasCreations) {
      case (gen, aliasTx, transferViaAddress, transferViaAlias) =>
        assertDiffAndState(Seq(TestBlock.create(gen)), TestBlock.create(Seq(aliasTx))) {
          case (_, state) =>
            val addressBytes = runScript[CaseObj](script, transferViaAddress, state).explicitGet().fields("bytes").asInstanceOf[CONST_BYTESTR]
            addressBytes.bs.arr.sameElements(transferViaAddress.recipient.bytes) shouldBe true
            val resolvedAddressBytes =
              runScript[CaseObj](script, transferViaAlias, state).explicitGet().fields("bytes").asInstanceOf[CONST_BYTESTR]

            resolvedAddressBytes.bs.arr.sameElements(transferViaAddress.recipient.bytes) shouldBe true
        }
    }
  }

  property("Script can't resolve alias that doesn't exist") {
    forAll(preconditionsAndAliasCreations) {
      case (gen, _, _, transferViaAlias) =>
        assertDiffAndState(Seq(TestBlock.create(gen)), TestBlock.create(Seq())) {
          case (_, state) =>
            runScript(script, transferViaAlias, state) should produce(" does not exists")
        }
    }
  }
} 
Example 188
Source File: SigVerifyPerformanceTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart.performance

import com.wavesplatform.account.{KeyPair, PublicKey}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.lang.directives.values._
import com.wavesplatform.lang.script.v1.ExprScript
import com.wavesplatform.lang.utils._
import com.wavesplatform.lang.v1.compiler.ExpressionCompiler
import com.wavesplatform.lang.v1.compiler.Terms._
import com.wavesplatform.lang.v1.parser.Parser
import com.wavesplatform.metrics.Instrumented
import com.wavesplatform.state.diffs._
import com.wavesplatform.state.diffs.smart._
import com.wavesplatform.transaction.Asset.Waves
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class SigVerifyPerformanceTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {

  private val AmtOfTxs = 10000

  private def simpleSendGen(from: KeyPair, to: PublicKey, ts: Long): Gen[TransferTransaction] =
    for {
      amt <- smallFeeGen
      fee <- smallFeeGen
    } yield TransferTransaction.selfSigned(1.toByte, from, to.toAddress, Waves, amt, Waves, fee, ByteStr.empty,  ts).explicitGet()

  private def scriptedSendGen(from: KeyPair, to: PublicKey, ts: Long): Gen[TransferTransaction] =
    for {
      amt <- smallFeeGen
      fee <- smallFeeGen
    } yield TransferTransaction.selfSigned(2.toByte, from, to.toAddress, Waves, amt, Waves, fee, ByteStr.empty,  ts).explicitGet()

  private def differentTransfers(typed: EXPR) =
    for {
      master    <- accountGen
      recipient <- accountGen
      ts        <- positiveIntGen
      amt       <- smallFeeGen
      fee       <- smallFeeGen
      genesis = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      setScript <- selfSignedSetScriptTransactionGenP(master, ExprScript(typed).explicitGet())
      transfer       = simpleSendGen(master, recipient.publicKey, ts)
      scriptTransfer = scriptedSendGen(master, recipient.publicKey, ts)
      transfers       <- Gen.listOfN(AmtOfTxs, transfer)
      scriptTransfers <- Gen.listOfN(AmtOfTxs, scriptTransfer)
    } yield (genesis, setScript, transfers, scriptTransfers)

  ignore("parallel native signature verification vs sequential scripted signature verification") {
    val textScript    = "sigVerify(tx.bodyBytes,tx.proofs[0],tx.senderPk)"
    val untypedScript = Parser.parseExpr(textScript).get.value
    val typedScript   = ExpressionCompiler(compilerContext(V1, Expression, isAssetScript = false), untypedScript).explicitGet()._1

    forAll(differentTransfers(typedScript)) {
      case (gen, setScript, transfers, scriptTransfers) =>
        def simpleCheck(): Unit = assertDiffAndState(Seq(TestBlock.create(Seq(gen))), TestBlock.create(transfers), smartEnabledFS) { case _ => }
        def scriptedCheck(): Unit =
          assertDiffAndState(Seq(TestBlock.create(Seq(gen, setScript))), TestBlock.create(scriptTransfers), smartEnabledFS) {
            case _ =>
          }

        val simeplCheckTime   = Instrumented.withTimeMillis(simpleCheck())._2
        val scriptedCheckTime = Instrumented.withTimeMillis(scriptedCheck())._2
        println(s"[parallel] simple check time: $simeplCheckTime ms,\t [seqential] scripted check time: $scriptedCheckTime ms")
    }

  }
} 
Example 189
Source File: SmartAssetEvalTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart

import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.lang.directives.values.{Expression, V3}
import com.wavesplatform.lang.script.v1.ExprScript
import com.wavesplatform.lang.utils._
import com.wavesplatform.lang.v1.compiler.ExpressionCompiler
import com.wavesplatform.lang.v1.parser.Parser
import com.wavesplatform.state.diffs._
import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves}
import com.wavesplatform.transaction.assets.{IssueTransaction, SetAssetScriptTransaction}
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.transaction.{GenesisTransaction, TxVersion}
import com.wavesplatform.utils._
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class SmartAssetEvalTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {
  val preconditions: Gen[(GenesisTransaction, IssueTransaction, SetAssetScriptTransaction, TransferTransaction)] =
    for {
      firstAcc  <- accountGen
      secondAcc <- accountGen
      ts        <- timestampGen
      genesis = GenesisTransaction.create(firstAcc.toAddress, ENOUGH_AMT, ts).explicitGet()

      emptyScript = s"""
                       |{-# STDLIB_VERSION 3 #-}
                       |{-# CONTENT_TYPE EXPRESSION #-}
                       |{-# SCRIPT_TYPE ASSET #-}
                       |
                       |true
                       |
        """.stripMargin

      parsedEmptyScript = Parser.parseExpr(emptyScript).get.value

      emptyExprScript = ExprScript(V3, ExpressionCompiler(compilerContext(V3, Expression, isAssetScript = true), parsedEmptyScript).explicitGet()._1)
        .explicitGet()

      issueTransaction = IssueTransaction(
          TxVersion.V2,
          firstAcc.publicKey,
          "name".utf8Bytes,
          "description".utf8Bytes,
          100,
          0,
          false,
          Some(emptyExprScript),
          1000000,
          ts
        ).signWith(firstAcc.privateKey)

      asset = IssuedAsset(issueTransaction.id())

      assetScript = s"""
                       | {-# STDLIB_VERSION 3 #-}
                       | {-# CONTENT_TYPE EXPRESSION #-}
                       | {-# SCRIPT_TYPE ASSET #-}
                       |
                       | this.id         == base58'${asset.id.toString}' &&
                       | this.quantity   == 100                        &&
                       | this.decimals   == 0                          &&
                       | this.reissuable == false                      &&
                       | this.scripted   == true                       &&
                       | this.sponsored  == false
                       |
        """.stripMargin

      untypedScript = Parser.parseExpr(assetScript).get.value

      typedScript = ExprScript(V3, ExpressionCompiler(compilerContext(V3, Expression, isAssetScript = true), untypedScript).explicitGet()._1)
        .explicitGet()

      setAssetScriptTransaction = SetAssetScriptTransaction
        .signed(1.toByte, firstAcc.publicKey, asset, Some(typedScript), 1000, ts + 10, firstAcc.privateKey)
        .explicitGet()

      assetTransferTransaction = TransferTransaction.selfSigned(1.toByte, firstAcc, secondAcc.toAddress, asset, 1, Waves, 1000, ByteStr.empty,  ts + 20)
        .explicitGet()

    } yield (genesis, issueTransaction, setAssetScriptTransaction, assetTransferTransaction)

  property("Smart asset with scrtipt that contains 'this' link") {
    forAll(preconditions) {
      case (genesis, issueTransaction, setAssetScriptTransaction, assetTransferTransaction) =>
        assertDiffAndState(smartEnabledFS) { append =>
          append(Seq(genesis)).explicitGet()
          append(Seq(issueTransaction)).explicitGet()
          append(Seq(setAssetScriptTransaction)).explicitGet()
          append(Seq(assetTransferTransaction)).explicitGet()
        }
    }
  }
} 
Example 190
Source File: AddressTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart.predef

import com.wavesplatform.account.{Address, AddressScheme}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.lang.Testing._
import com.wavesplatform.lang.directives.DirectiveDictionary
import com.wavesplatform.lang.directives.values.{StdLibVersion, V4}
import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CaseObj}
import com.wavesplatform.lang.v1.evaluator.ctx.impl.unit
import com.wavesplatform.state.diffs._
import com.wavesplatform.state.diffs.smart.predef
import com.wavesplatform.transaction.TxValidationError.InvalidAddress
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.{Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class AddressTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink {
  property("should calculate address from public key") {
    forAll(accountGen) { acc =>
      val script =
        s"""
           | let pk = base58'${acc.publicKey}'
           | let address = addressFromPublicKey(pk)
           | address.bytes
        """.stripMargin
      runScript(script) shouldBe evaluated(ByteStr(Address.fromPublicKey(acc.publicKey, chainId).bytes))
    }
  }

  property("should calculate address from bytes") {
    AddressScheme.current = new AddressScheme { override  val chainId: Byte = predef.chainId }

    forAll(for {
      account <- accountGen
      version <- Gen.oneOf(DirectiveDictionary[StdLibVersion].all)
    } yield (account, version)) {
      case (account, version) =>
        val address = Address.fromPublicKey(account.publicKey)
        val script =
          s"""
           | let addressString = "$address"
           | let maybeAddress = addressFromString(addressString)
           | let address = extract(maybeAddress)
           | address.bytes
        """.stripMargin
        runScript(script, ctxV = version) shouldBe evaluated(ByteStr(Address.fromBytes(address.bytes).explicitGet().bytes))
    }
  }

  property("should calculate address and return bytes without intermediate ref") {
    AddressScheme.current = new AddressScheme { override  val chainId: Byte = predef.chainId }

    forAll(for {
      account <- accountGen
      version <- Gen.oneOf(DirectiveDictionary[StdLibVersion].all)
    } yield (account, version)) {
      case (account, version) =>
        val address = Address.fromPublicKey(account.publicKey)
        val script =
          s"""
           | let addressString = "$address"
           | let maybeAddress = addressFromString(addressString)
           | extract(maybeAddress).bytes
        """.stripMargin
        runScript(script, ctxV = version) shouldBe evaluated(ByteStr(Address.fromBytes(address.bytes).explicitGet().bytes))
    }
  }

  property("should fails on illegal bytes length") {
    val correctLength = Address.AddressLength
    Address.fromBytes(Array.emptyByteArray) should produce("Wrong addressBytes length")
    Address.fromBytes(Array(1)) should produce("Wrong addressBytes length")
    Address.fromBytes(Array.fill(correctLength - 1)(1)) should produce("Wrong addressBytes length")
    Address.fromBytes(Array.fill(correctLength + 1)(1)) should produce("Wrong addressBytes length")
  }

  property("Address.fromString errors") {
    Address.fromString("a" * 37) shouldBe Left(InvalidAddress("Wrong address string length: max=36, actual: 37"))
    Address.fromString("a" * 36) shouldBe Left(InvalidAddress("Wrong addressBytes length: expected: 26, actual: 27"))
    Address.fromString("a" * 35) shouldBe Left(InvalidAddress("Unknown address version: 18"))
  }

  property("RIDE addressFromString V4 limit exceeding result") {
    runScript(s""" addressFromString("${"a" * 37}") """, ctxV = V4) shouldBe Right(unit)
    runScript(s""" addressFromString("${"a" * 36}") """, ctxV = V4) shouldBe Right(unit)
    runScript(s""" addressFromString("${"a" * 35}") """, ctxV = V4) shouldBe Right(unit)
  }

  property("RIDE addressFromString V4 success") {
    AddressScheme.current = new AddressScheme { override  val chainId: Byte = 'T' }

    val base58 = """3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU"""
    val result = runScript(s""" addressFromString("$base58") """, ctxV = V4)
      .explicitGet()
      .asInstanceOf[CaseObj]
    result.caseType.name shouldBe "Address"
    result.fields shouldBe Map("bytes" -> CONST_BYTESTR(ByteStr.decodeBase58(base58).get).explicitGet())
  }
} 
Example 191
Source File: package.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import cats.implicits._
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.lang.Global
import com.wavesplatform.lang.contract.DApp
import com.wavesplatform.lang.directives.DirectiveSet
import com.wavesplatform.lang.directives.values.{Account, Expression, ScriptType, StdLibVersion, V3, DApp => DAppType}
import com.wavesplatform.lang.v1.compiler.{ContractCompiler, ExpressionCompiler, Terms}
import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext
import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext}
import com.wavesplatform.lang.v1.parser.Expressions.{DAPP, EXPR}
import com.wavesplatform.lang.v1.traits.Environment
import com.wavesplatform.state.diffs.FeeValidation._
import com.wavesplatform.transaction.assets.IssueTransaction
import com.wavesplatform.transaction.smart.InvokeScriptTransaction
import org.scalacheck.Gen

package object ci {
  def ciFee(sc: Int = 0, nonNftIssue: Int = 0): Gen[Long] =
    Gen.choose(
      FeeUnit * FeeConstants(InvokeScriptTransaction.typeId) + sc * ScriptExtraFee + nonNftIssue * FeeConstants(IssueTransaction.typeId) * FeeUnit,
      FeeUnit * FeeConstants(InvokeScriptTransaction.typeId) + (sc + 1) * ScriptExtraFee - 1 + nonNftIssue * FeeConstants(IssueTransaction.typeId) * FeeUnit
    )

  def compileContractFromExpr(expr: DAPP, version: StdLibVersion = V3): DApp = {
    val ctx =
      PureContext.build(Global, version).withEnvironment[Environment] |+|
        CryptoContext.build(Global, version).withEnvironment[Environment] |+|
        WavesContext.build(
          DirectiveSet(version, Account, DAppType).explicitGet()
        )
    ContractCompiler(ctx.compilerContext, expr, version).explicitGet()
  }

  def compileExpr(expr: EXPR, version: StdLibVersion, scriptType: ScriptType): Terms.EXPR = {
    val ctx =
      PureContext.build(Global, version).withEnvironment[Environment] |+|
        CryptoContext.build(Global, version).withEnvironment[Environment] |+|
        WavesContext.build(
          DirectiveSet(version, scriptType, Expression).explicitGet()
        )
    ExpressionCompiler(ctx.compilerContext, expr).explicitGet()._1
  }
} 
Example 192
Source File: CommonValidationTimeTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.db.WithState
import com.wavesplatform.settings.TestFunctionalitySettings.Enabled
import com.wavesplatform.state._
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.{Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class CommonValidationTimeTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink with WithState {

  property("disallows too old transacions") {
    forAll(for {
      prevBlockTs <- timestampGen
      blockTs     <- Gen.choose(prevBlockTs, prevBlockTs + 7 * 24 * 3600 * 1000)
      master      <- accountGen
      height      <- positiveIntGen
      recipient   <- accountGen
      amount      <- positiveLongGen
      fee         <- smallFeeGen
      transfer1 = createWavesTransfer(master, recipient.toAddress, amount, fee, prevBlockTs - Enabled.maxTransactionTimeBackOffset.toMillis - 1)
        .explicitGet()
    } yield (prevBlockTs, blockTs, height, transfer1)) {
      case (prevBlockTs, blockTs, height, transfer1) =>
        withLevelDBWriter(Enabled) { blockchain: Blockchain =>
          val result = TransactionDiffer(Some(prevBlockTs), blockTs)(blockchain, transfer1).resultE
          result should produce("in the past relative to previous block timestamp")
        }
    }
  }

  property("disallows transactions from far future") {
    forAll(for {
      prevBlockTs <- timestampGen
      blockTs     <- Gen.choose(prevBlockTs, prevBlockTs + 7 * 24 * 3600 * 1000)
      master      <- accountGen
      height      <- positiveIntGen
      recipient   <- accountGen
      amount      <- positiveLongGen
      fee         <- smallFeeGen
      transfer1 = createWavesTransfer(master, recipient.toAddress, amount, fee, blockTs + Enabled.maxTransactionTimeForwardOffset.toMillis + 1)
        .explicitGet()
    } yield (prevBlockTs, blockTs, height, transfer1)) {
      case (prevBlockTs, blockTs, height, transfer1) =>
        val functionalitySettings = Enabled.copy(lastTimeBasedForkParameter = blockTs - 1)
        withLevelDBWriter(functionalitySettings) { blockchain: Blockchain =>
          TransactionDiffer(Some(prevBlockTs), blockTs)(blockchain, transfer1).resultE should
            produce("in the future relative to block timestamp")
        }
    }
  }
} 
Example 193
Source File: GenesisTransactionDiffTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import cats._
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.state._
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class GenesisTransactionDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink {
  def nelMax[T](g: Gen[T], max: Int = 10): Gen[List[T]] = Gen.choose(1, max).flatMap(Gen.listOfN(_, g))

  property("fails if height != 1") {
    forAll(genesisGen, positiveIntGen suchThat (_ > 1)) { (gtx, h) =>
      GenesisTransactionDiff(h)(gtx) should produce("GenesisTransaction cannot appear in non-initial block")
    }
  }

  property("Diff establishes Waves invariant") {
    forAll(nelMax(genesisGen)) { gtxs =>
      assertDiffAndState(Seq.empty, TestBlock.create(gtxs)) { (blockDiff, _) =>
        val totalPortfolioDiff: Portfolio = Monoid.combineAll(blockDiff.portfolios.values)
        totalPortfolioDiff.balance shouldBe gtxs.map(_.amount).sum
        totalPortfolioDiff.effectiveBalance shouldBe gtxs.map(_.amount).sum
        totalPortfolioDiff.assets shouldBe Map.empty

        gtxs.foreach { gtx =>
          blockDiff.portfolios(gtx.recipient).balance shouldBe gtx.amount
        }
      }
    }
  }
} 
Example 194
Source File: OneDimensionalMiningConstraintSuite.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.mining

import com.wavesplatform.state.{Blockchain, Diff}
import com.wavesplatform.transaction.Transaction
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalamock.scalatest.PathMockFactory
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class OneDimensionalMiningConstraintSuite extends FreeSpec with Matchers with PropertyChecks with PathMockFactory with TransactionGen with NoShrink {
  "OneDimensionalMiningConstraint" - {
    "should be full if the limit is 0, but not overfilled" in {
      val tank = createConstConstraint(0, 1, "const")
      tank.isFull shouldBe true
      tank.isOverfilled shouldBe false
    }

    "put(transaction)" - tests { (maxTxs, txs) =>
      val constraint = createConstConstraint(maxTxs, transactionSize = 1, "txSize")
      txs.foldLeft(constraint)(_.put(stub[Blockchain], _, Diff.empty))
    }
  }

  private def tests(toConstraint: (Int, List[Transaction]) => MiningConstraint): Unit = {
    val dontReachLimitGen: Gen[MiningConstraint] = for {
      maxTxs   <- Gen.chooseNum(1, Int.MaxValue)
      txNumber <- Gen.chooseNum(0, maxTxs - 1)
      txs      <- Gen.listOfN(math.min(txNumber, 15), randomTransactionGen)
    } yield toConstraint(maxTxs, txs)

    "multiple items don't reach the limit" in forAll(dontReachLimitGen) { updatedConstraint =>
      updatedConstraint.isFull shouldBe false
      updatedConstraint.isOverfilled shouldBe false
    }

    val reachSoftLimitGen: Gen[MiningConstraint] = for {
      maxTxs <- Gen.chooseNum(1, 10)
      txs    <- Gen.listOfN(maxTxs, randomTransactionGen)
    } yield toConstraint(maxTxs, txs)

    "multiple items reach the limit softly" in forAll(reachSoftLimitGen) { updatedConstraint =>
      updatedConstraint.isFull shouldBe true
      updatedConstraint.isOverfilled shouldBe false
    }

    val reachHardLimitGen: Gen[MiningConstraint] = for {
      maxTxs   <- Gen.chooseNum(1, 10)
      txNumber <- Gen.chooseNum(maxTxs + 1, maxTxs + 10)
      txs      <- Gen.listOfN(txNumber, randomTransactionGen)
    } yield toConstraint(maxTxs, txs)

    "multiple items reach the limit with gap" in forAll(reachHardLimitGen) { updatedConstraint =>
      updatedConstraint.isFull shouldBe true
      updatedConstraint.isOverfilled shouldBe true
    }
  }
} 
Example 195
Source File: ScriptComplexityMiningConstraintSuite.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.mining

import com.typesafe.config.ConfigFactory
import com.wavesplatform.account.KeyPair
import com.wavesplatform.common.utils._
import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3
import com.wavesplatform.settings.WavesSettings
import com.wavesplatform.state.diffs.TransactionDiffer
import com.wavesplatform.state.{AccountScriptInfo, Blockchain, LeaseBalance}
import com.wavesplatform.transaction.smart.script.ScriptCompiler
import com.wavesplatform.transaction.{DataTransaction, Transaction, TxVersion}
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalamock.scalatest.PathMockFactory
import org.scalatest.{FlatSpec, Matchers}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

class ScriptComplexityMiningConstraintSuite
    extends FlatSpec
    with Matchers
    with ScalaCheckDrivenPropertyChecks
    with PathMockFactory
    with TransactionGen
    with NoShrink {
  private val settings = WavesSettings.fromRootConfig(ConfigFactory.load())

  private val complexity = OneDimensionalMiningConstraint(1000, TxEstimators.scriptsComplexity, "MaxScriptsComplexityInBlock")
  private val maxTxs     = OneDimensionalMiningConstraint(3, TxEstimators.one, "MaxTxsInMicroBlock")
  private val constraint = MultiDimensionalMiningConstraint(complexity, maxTxs)

  val (script, _) = ScriptCompiler.compile("true", ScriptEstimatorV3).explicitGet()

  "ScriptComplexityMiningConstraint" should "accept non-scripted txs after limit" in {
    forAll(preconditions) {
      case (acc1, tx1, tx2, tx3) =>
        val blockchain = stub[Blockchain]
        (blockchain.settings _).when().returning(settings.blockchainSettings)
        (blockchain.height _).when().returning(1)
        (blockchain.activatedFeatures _).when().returning(Map(BlockchainFeatures.DataTransaction.id -> 0))

        val txDiffer =
          TransactionDiffer(Some(System.currentTimeMillis() - 1000), System.currentTimeMillis())(blockchain, _: Transaction).resultE.explicitGet()
        (blockchain.balance _).when(*, *).returning(10000000)
        (blockchain.leaseBalance _).when(*).returning(LeaseBalance(0, 0))
        (blockchain.accountScript _).when(tx1.sender.toAddress).returning(Some(AccountScriptInfo(acc1.publicKey, script, 1000, Map.empty)))
        (blockchain.accountScript _).when(*).returning(None)

        val c1          = constraint.put(blockchain, tx1, txDiffer(tx1))
        val cOverfilled = c1.put(blockchain, tx1, txDiffer(tx1))
        cOverfilled.isOverfilled shouldBe true

        val c2 = c1.put(blockchain, tx2, txDiffer(tx2))
        c2.isFull shouldBe false

        val c3 = c2.put(blockchain, tx3, txDiffer(tx3))
        c3.isFull shouldBe true
        c3.isOverfilled shouldBe false
    }

  }

  private[this] def preconditions: Gen[(KeyPair, DataTransaction, DataTransaction, DataTransaction)] =
    for {
      acc1 <- accountGen
      acc2 <- accountGen
      tx1 = DataTransaction.selfSigned(TxVersion.V1, acc1, Nil, 1000000, System.currentTimeMillis()).explicitGet()
      tx2 = DataTransaction.selfSigned(TxVersion.V1, acc2, Nil, 1000000, System.currentTimeMillis()).explicitGet()
      tx3 = DataTransaction.selfSigned(TxVersion.V1, acc2, Nil, 1000000, System.currentTimeMillis()).explicitGet()
    } yield (acc1, tx1, tx2, tx3)
} 
Example 196
Source File: GenesisBlockUpdateSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.events

import com.wavesplatform.settings.WavesSettings
import com.wavesplatform.state.diffs.ENOUGH_AMT
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.{BlockGen, TestHelpers}
import org.scalacheck.Gen
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import com.wavesplatform.common.utils.EitherExt2

class GenesisBlockUpdateSpec extends FreeSpec with Matchers with BlockGen with ScalaCheckPropertyChecks with EventsHelpers {
  override protected def settings: WavesSettings = TestHelpers.enableNG(super.settings)

  val genesisAppendWithWavesAmountGen: Gen[(BlockAppended, Long)] = for {
    master      <- accountGen
    wavesAmount <- Gen.choose(1L, ENOUGH_AMT)
    gt = GenesisTransaction.create(master.toAddress, wavesAmount, 0).explicitGet()
    b <- blockGen(Seq(gt), master)
    ba = appendBlock(b)
  } yield (ba, wavesAmount)

  "on genesis block append" - {
    "master address balance gets correctly updated" in forAll(genesisAppendWithWavesAmountGen) {
      case (BlockAppended(_, _, _, _, _, upds), wavesAmount) =>
        upds.head.balances.head._3 shouldBe wavesAmount
    }

    "updated Waves amount is calculated correctly" in forAll(genesisAppendWithWavesAmountGen) {
      case (BlockAppended(_, _, _, updatedWavesAmount, _, _), wavesAmount) =>
        updatedWavesAmount shouldBe wavesAmount
    }
  }

} 
Example 197
Source File: BlockchainUpdaterMicroblockBadSignaturesTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.history

import com.wavesplatform.{EitherMatchers, TransactionGen}
import com.wavesplatform.account.KeyPair
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.crypto._
import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.state.diffs._
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.history.Domain.BlockchainUpdaterExt
import org.scalacheck.Gen
import org.scalatest._
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class BlockchainUpdaterMicroblockBadSignaturesTest
    extends PropSpec
    with PropertyChecks
    with DomainScenarioDrivenPropertyCheck
    with Matchers
    with EitherMatchers
    with TransactionGen {

  val preconditionsAndPayments: Gen[(GenesisTransaction, TransferTransaction, TransferTransaction)] = for {
    master    <- accountGen
    recipient <- accountGen
    ts        <- positiveIntGen
    genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
    payment: TransferTransaction  <- wavesTransferGeneratorP(master, recipient.toAddress)
    payment2: TransferTransaction <- wavesTransferGeneratorP(master, recipient.toAddress)
  } yield (genesis, payment, payment2)

  property("bad total resulting block signature") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments) {
      case (domain, (genesis, payment, payment2)) =>
        val block0                 = buildBlockOfTxs(randomSig, Seq(genesis))
        val (block1, microblocks1) = chainBaseAndMicro(block0.id(), payment, Seq(payment2).map(Seq(_)))
        val badSigMicro            = microblocks1.head.copy(totalResBlockSig = randomSig)
        domain.blockchainUpdater.processBlock(block0) should beRight
        domain.blockchainUpdater.processBlock(block1) should beRight
        domain.blockchainUpdater.processMicroBlock(badSigMicro) should produce("InvalidSignature")
    }
  }

  property("bad microBlock signature") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments) {
      case (domain, (genesis, payment, payment2)) =>
        val block0                 = buildBlockOfTxs(randomSig, Seq(genesis))
        val (block1, microblocks1) = chainBaseAndMicro(block0.id(), payment, Seq(payment2).map(Seq(_)))
        val badSigMicro            = microblocks1.head.copy(signature = randomSig)
        domain.blockchainUpdater.processBlock(block0) should beRight
        domain.blockchainUpdater.processBlock(block1) should beRight
        domain.blockchainUpdater.processMicroBlock(badSigMicro) should produce("InvalidSignature")
    }
  }

  property("other sender") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments) {
      case (domain, (genesis, payment, payment2)) =>
        val otherSigner = KeyPair(TestBlock.randomOfLength(KeyLength))
        val block0      = buildBlockOfTxs(randomSig, Seq(genesis))
        val block1      = buildBlockOfTxs(block0.id(), Seq(payment))
        val badSigMicro = buildMicroBlockOfTxs(block0.id(), block1, Seq(payment2), otherSigner)._2
        domain.blockchainUpdater.processBlock(block0) should beRight
        domain.blockchainUpdater.processBlock(block1) should beRight
        domain.blockchainUpdater.processMicroBlock(badSigMicro) should produce("another account")
    }
  }
} 
Example 198
Source File: BlockchainUpdaterGeneratorFeeSameBlockTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.history

import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.history.Domain.BlockchainUpdaterExt
import com.wavesplatform.state.diffs._
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.{EitherMatchers, TransactionGen}
import org.scalacheck.Gen
import org.scalatest._
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class BlockchainUpdaterGeneratorFeeSameBlockTest
    extends PropSpec
    with PropertyChecks
    with DomainScenarioDrivenPropertyCheck
    with Matchers
    with EitherMatchers
    with TransactionGen {

  type Setup = (GenesisTransaction, TransferTransaction, TransferTransaction)

  val preconditionsAndPayments: Gen[Setup] = for {
    sender    <- accountGen
    recipient <- accountGen
    fee       <- smallFeeGen
    ts        <- positiveIntGen
    genesis: GenesisTransaction = GenesisTransaction.create(sender.toAddress, ENOUGH_AMT, ts).explicitGet()
    payment: TransferTransaction <- wavesTransferGeneratorP(ts, sender, recipient.toAddress)
    generatorPaymentOnFee: TransferTransaction = createWavesTransfer(defaultSigner, recipient.toAddress, payment.fee, fee, ts + 1).explicitGet()
  } yield (genesis, payment, generatorPaymentOnFee)

  property("block generator can spend fee after transaction before applyMinerFeeWithTransactionAfter") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments, DefaultWavesSettings) {
      case (domain, (genesis, somePayment, generatorPaymentOnFee)) =>
        val blocks = chainBlocks(Seq(Seq(genesis), Seq(generatorPaymentOnFee, somePayment)))
        blocks.foreach(block => domain.blockchainUpdater.processBlock(block) should beRight)
    }
  }

  property("block generator can't spend fee after transaction after applyMinerFeeWithTransactionAfter") {
    scenario(preconditionsAndPayments, MicroblocksActivatedAt0WavesSettings) {
      case (domain, (genesis, somePayment, generatorPaymentOnFee)) =>
        val blocks = chainBlocks(Seq(Seq(genesis), Seq(generatorPaymentOnFee, somePayment)))
        blocks.init.foreach(block => domain.blockchainUpdater.processBlock(block) should beRight)
        domain.blockchainUpdater.processBlock(blocks.last) should produce("unavailable funds")
    }
  }
} 
Example 199
Source File: BlockchainUpdaterBlockOnlyTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.history

import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.history.Domain.BlockchainUpdaterExt
import com.wavesplatform.state.diffs._
import com.wavesplatform.transaction._
import com.wavesplatform.transaction.transfer._
import com.wavesplatform.{EitherMatchers, TransactionGen}
import org.scalacheck.Gen
import org.scalatest._
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class BlockchainUpdaterBlockOnlyTest
    extends PropSpec
    with PropertyChecks
    with DomainScenarioDrivenPropertyCheck
    with Matchers
    with EitherMatchers
    with TransactionGen {

  def preconditionsAndPayments(paymentsAmt: Int): Gen[(GenesisTransaction, Seq[TransferTransaction])] =
    for {
      master    <- accountGen
      recipient <- accountGen
      ts        <- positiveIntGen
      genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      payments <- Gen.listOfN(paymentsAmt, wavesTransferGeneratorP(ts, master, recipient.toAddress))
    } yield (genesis, payments)

  property("can apply valid blocks") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments(1)) {
      case (domain, (genesis, payments)) =>
        val blocks = chainBlocks(Seq(Seq(genesis), Seq(payments.head)))
        blocks.map(block => domain.blockchainUpdater.processBlock(block) should beRight)
    }
  }

  property("can apply, rollback and reprocess valid blocks") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments(2)) {
      case (domain, (genesis, payments)) =>
        val blocks = chainBlocks(Seq(Seq(genesis), Seq(payments.head), Seq(payments(1))))
        domain.blockchainUpdater.processBlock(blocks.head) should beRight
        domain.blockchainUpdater.height shouldBe 1
        domain.blockchainUpdater.processBlock(blocks(1)) should beRight
        domain.blockchainUpdater.height shouldBe 2
        domain.blockchainUpdater.removeAfter(blocks.head.id()) should beRight
        domain.blockchainUpdater.height shouldBe 1
        domain.blockchainUpdater.processBlock(blocks(1)) should beRight
        domain.blockchainUpdater.processBlock(blocks(2)) should beRight
    }
  }

  property("can't apply block with invalid signature") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments(1)) {
      case (domain, (genesis, payment)) =>
        val blocks = chainBlocks(Seq(Seq(genesis), payment))
        domain.blockchainUpdater.processBlock(blocks.head) should beRight
        domain.blockchainUpdater.processBlock(spoilSignature(blocks.last)) should produce("invalid signature")
    }
  }

  property("can't apply block with invalid signature after rollback") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments(1)) {
      case (domain, (genesis, payment)) =>
        val blocks = chainBlocks(Seq(Seq(genesis), payment))
        domain.blockchainUpdater.processBlock(blocks.head) should beRight
        domain.blockchainUpdater.processBlock(blocks(1)) should beRight
        domain.blockchainUpdater.removeAfter(blocks.head.id()) should beRight
        domain.blockchainUpdater.processBlock(spoilSignature(blocks(1))) should produce("invalid signature")
    }
  }

  property("can process 11 blocks and then rollback to genesis") {
    assume(BlockchainFeatures.implemented.contains(BlockchainFeatures.SmartAccounts.id))
    scenario(preconditionsAndPayments(10)) {
      case (domain, (genesis, payments)) =>
        val blocks = chainBlocks(Seq(genesis) +: payments.map(Seq(_)))
        blocks.foreach { b =>
          domain.blockchainUpdater.processBlock(b) should beRight
        }
        domain.blockchainUpdater.removeAfter(blocks.head.id()) should beRight
    }
  }
} 
Example 200
Source File: BlockchainUpdaterBurnTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.history

import com.wavesplatform.TransactionGen
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.history.Domain.BlockchainUpdaterExt
import com.wavesplatform.settings.{BlockchainSettings, WavesSettings}
import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce}
import com.wavesplatform.transaction.Asset.IssuedAsset
import com.wavesplatform.transaction.assets.{BurnTransaction, IssueTransaction, ReissueTransaction}
import com.wavesplatform.transaction.transfer.TransferTransaction
import com.wavesplatform.transaction.{Asset, GenesisTransaction, TxVersion}
import org.scalacheck.Gen
import org.scalatest.{Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class BlockchainUpdaterBurnTest extends PropSpec with PropertyChecks with DomainScenarioDrivenPropertyCheck with Matchers with TransactionGen {
  val Waves: Long = 100000000

  type Setup =
    (Long, GenesisTransaction, TransferTransaction, IssueTransaction, BurnTransaction, ReissueTransaction)

  val preconditions: Gen[Setup] = for {
    master                                                   <- accountGen
    ts                                                       <- timestampGen
    transferAssetWavesFee                                    <- smallFeeGen
    alice                                                    <- accountGen
    (_, assetName, description, quantity, decimals, _, _, _) <- issueParamGen
    genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
    masterToAlice: TransferTransaction = TransferTransaction.selfSigned(1.toByte, master, alice.toAddress, Asset.Waves, 3 * Waves, Asset.Waves, transferAssetWavesFee, ByteStr.empty,  ts + 1)
      .explicitGet()
    issue: IssueTransaction = IssueTransaction(TxVersion.V1, alice.publicKey, assetName, description, quantity, decimals, false, script = None, Waves, ts + 100)
      .signWith(alice.privateKey)
    burn: BurnTransaction = BurnTransaction.selfSigned(1.toByte, alice, IssuedAsset(issue.assetId), quantity / 2, Waves, ts + 200).explicitGet()
    reissue: ReissueTransaction = ReissueTransaction
      .selfSigned(1.toByte, alice, IssuedAsset(issue.assetId), burn.quantity, true, Waves, ts + 300)
      .explicitGet()
  } yield (ts, genesis, masterToAlice, issue, burn, reissue)

  val localBlockchainSettings: BlockchainSettings = DefaultBlockchainSettings.copy(
    functionalitySettings = DefaultBlockchainSettings.functionalitySettings
      .copy(
        featureCheckBlocksPeriod = 1,
        blocksForFeatureActivation = 1,
        preActivatedFeatures = Map(BlockchainFeatures.NG.id -> 0, BlockchainFeatures.DataTransaction.id -> 0)
      )
  )
  val localWavesSettings: WavesSettings = settings.copy(blockchainSettings = localBlockchainSettings)

  property("issue -> burn -> reissue in sequential blocks works correctly") {
    scenario(preconditions, localWavesSettings) {
      case (domain, (ts, genesis, masterToAlice, issue, burn, reissue)) =>
        val block0 = customBuildBlockOfTxs(randomSig, Seq(genesis), defaultSigner, 1.toByte, ts)
        val block1 = customBuildBlockOfTxs(block0.id(), Seq(masterToAlice), defaultSigner, TxVersion.V1, ts + 150)
        val block2 = customBuildBlockOfTxs(block1.id(), Seq(issue), defaultSigner, TxVersion.V1, ts + 250)
        val block3 = customBuildBlockOfTxs(block2.id(), Seq(burn), defaultSigner, TxVersion.V1, ts + 350)
        val block4 = customBuildBlockOfTxs(block3.id(), Seq(reissue), defaultSigner, TxVersion.V1, ts + 450)

        domain.appendBlock(block0)
        domain.appendBlock(block1)

        domain.appendBlock(block2)
        val assetDescription1 = domain.blockchainUpdater.assetDescription(IssuedAsset(issue.assetId)).get
        assetDescription1.reissuable should be(false)
        assetDescription1.totalVolume should be(issue.quantity)

        domain.appendBlock(block3)
        val assetDescription2 = domain.blockchainUpdater.assetDescription(IssuedAsset(issue.assetId)).get
        assetDescription2.reissuable should be(false)
        assetDescription2.totalVolume should be(issue.quantity - burn.quantity)

        domain.blockchainUpdater.processBlock(block4) should produce("Asset is not reissuable")
    }
  }

  property("issue -> burn -> reissue in micro blocks works correctly") {
    scenario(preconditions, localWavesSettings) {
      case (domain, (ts, genesis, masterToAlice, issue, burn, reissue)) =>
        val block0 = customBuildBlockOfTxs(randomSig, Seq(genesis), defaultSigner, TxVersion.V1, ts)
        val block1 = customBuildBlockOfTxs(block0.id(), Seq(masterToAlice), defaultSigner, TxVersion.V1, ts + 150)
        val block2 = customBuildBlockOfTxs(block1.id(), Seq(issue), defaultSigner, TxVersion.V1, ts + 250)
        val block3 = customBuildBlockOfTxs(block2.id(), Seq(burn, reissue), defaultSigner, TxVersion.V1, ts + 350)

        domain.appendBlock(block0)
        domain.appendBlock(block1)

        domain.appendBlock(block2)
        val assetDescription1 = domain.blockchainUpdater.assetDescription(IssuedAsset(issue.assetId)).get
        assetDescription1.reissuable should be(false)
        assetDescription1.totalVolume should be(issue.quantity)

        domain.blockchainUpdater.processBlock(block3) should produce("Asset is not reissuable")
    }
  }
}