org.scalacheck.Arbitrary Scala Examples

The following examples show how to use org.scalacheck.Arbitrary. 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: 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 3
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 4
Source File: LedgerOffsetUtilTest.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 com.daml.http.Generators
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import scalaz.scalacheck.ScalazProperties

class LedgerOffsetUtilTest
    extends FlatSpec
    with Matchers
    with FlatSpecCheckLaws
    with GeneratorDrivenPropertyChecks {

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

  import LedgerOffsetUtilTest._

  behavior of LedgerOffsetUtil.AbsoluteOffsetOrdering.getClass.getSimpleName

  checkLaws(ScalazProperties.order.laws[LedgerOffset.Value.Absolute])
}

object LedgerOffsetUtilTest {
  import org.scalacheck.Arbitrary

  implicit val arbAbsoluteOffset: Arbitrary[LedgerOffset.Value.Absolute] = Arbitrary(
    Generators.absoluteLedgerOffsetVal)

  implicit val scalazOrder: scalaz.Order[LedgerOffset.Value.Absolute] =
    scalaz.Order.fromScalaOrdering(LedgerOffsetUtil.AbsoluteOffsetOrdering)
} 
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: 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 9
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 10
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 11
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 12
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 13
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 14
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 15
Source File: ProgramSpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.evm

import jbok.common.{gen, CommonSpec}
import org.scalacheck.Arbitrary
import scodec.bits.ByteVector

class ProgramSpec extends CommonSpec {

  val CodeSize: Int = Byte.MaxValue
  val PositionsSize = 10

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

  implicit val arbPositionSet: Arbitrary[Set[Int]] =
    Arbitrary(gen.boundedList(0, PositionsSize, gen.int(0, CodeSize)).map(_.toSet))

  "program" should {

    "detect all jump destinations if there are no push op" in {
      forAll { jumpDestLocations: Set[Int] =>
        val code = ByteVector((0 to CodeSize).map { i =>
          if (jumpDestLocations.contains(i)) JUMPDEST.code
          else nonPushOp
        }.toArray)
        val program = Program(code)
        program.validJumpDestinations shouldBe jumpDestLocations
      }
    }

    "detect all jump destinations if there are push op" in {
      forAll { (jumpDestLocations: Set[Int], pushOpLocations: Set[Int]) =>
        val code = ByteVector((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
      }
    }

    "detect all jump destinations if there are invalid ops" in {
      forAll { (jumpDestLocations: Set[Int], invalidOpLocations: Set[Int]) =>
        val code = ByteVector((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
      }
    }

    "detect all instructions as jump destinations if they are" in {
      val code    = ByteVector((0 to CodeSize).map(_ => JUMPDEST.code).toArray)
      val program = Program(code)
      program.validJumpDestinations shouldBe (0 to CodeSize).toSet
    }
  }
} 
Example 16
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 17
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 18
Source File: GoldenCodecTests.scala    From circe-golden   with Apache License 2.0 5 votes vote down vote up
package io.circe.testing.golden

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

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

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

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

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

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

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

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

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

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

import io.circe.Codec
import io.circe.generic.semiauto.deriveCodec
import java.time.Instant

case class Visit(id: Long, page: String, ts: Instant)

object Visit {
  implicit val codecForVisit: Codec[Visit] = deriveCodec
}

import cats.kernel.Eq
import io.circe.testing.{ ArbitraryInstances, CodecTests }
import org.scalacheck.Arbitrary
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.prop.Configuration
import org.typelevel.discipline.scalatest.FlatSpecDiscipline

trait VisitTestInstances extends ArbitraryInstances {
  implicit val eqVisit: Eq[Visit] = Eq.fromUniversalEquals
  implicit val arbitraryVisit: Arbitrary[Visit] = Arbitrary(
    for {
      id <- Arbitrary.arbitrary[Long]
      page <- Arbitrary.arbitrary[String]
      ts <- Arbitrary.arbitrary[Long].map(Instant.ofEpochMilli)
    } yield Visit(id, page, ts)
  )
}

class OldVisitSuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitTestInstances {
  checkAll("Codec[Visit]", CodecTests[Visit].codec)

  val good = """{"id":12345,"page":"/index.html","ts":"2019-10-22T14:54:13Z"}"""
  val value = Visit(12345L, "/index.html", Instant.parse("2019-10-22T14:54:13Z"))

  "codecForVisit" should "decode JSON that's known to be good" in {
    assert(io.circe.jawn.decode[Visit](good) === Right(value))
  }

  it should "produce the expected results" in {
    import io.circe.syntax._
    assert(value.asJson.noSpaces === good)
  }
}

import io.circe.testing.golden.GoldenCodecTests

class VisitSuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitTestInstances {
  checkAll("GoldenCodec[Visit]", GoldenCodecTests[Visit].goldenCodec)
} 
Example 20
Source File: VisitRepositorySuite.scala    From circe-golden   with Apache License 2.0 5 votes vote down vote up
package io.circe.testing.golden.example

import io.circe.{ Codec, Printer }
import io.circe.generic.semiauto.deriveCodec
import java.time.Instant

case class VisitRepository(visits: Map[String, Visit])

object VisitRepository {
  implicit val codecForVisitRepository: Codec[VisitRepository] = deriveCodec
}

import cats.kernel.Eq
import io.circe.testing.{ ArbitraryInstances, CodecTests }
import org.scalacheck.Arbitrary
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.prop.Configuration
import org.typelevel.discipline.scalatest.FlatSpecDiscipline

trait VisitRepositoryTestInstances extends VisitTestInstances with ArbitraryInstances {
  implicit val eqVisitRepository: Eq[VisitRepository] = Eq.fromUniversalEquals
  implicit val arbitraryVisitRepository: Arbitrary[VisitRepository] = Arbitrary(
    for {
      visits <- Arbitrary.arbitrary[Map[String, Visit]]
    } yield VisitRepository(visits)
  )
}

class OldVisitRepositorySuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitRepositoryTestInstances {
  checkAll("Codec[VisitRepository]", CodecTests[VisitRepository].codec)

  val good = """{"visits":{"1":{"id":12345,"page":"/index.html","ts":"2019-10-22T14:54:13Z"}}}"""
  val value = VisitRepository(Map("1" -> Visit(12345L, "/index.html", Instant.parse("2019-10-22T14:54:13Z"))))

  "codecForVisitRepository" should "decode JSON that's known to be good" in {
    assert(io.circe.jawn.decode[VisitRepository](good) === Right(value))
  }

  it should "produce the expected results" in {
    import io.circe.syntax._
    assert(value.asJson.noSpaces === good)
  }
}

import io.circe.testing.golden.GoldenCodecTests

class VisitRepositorySuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitRepositoryTestInstances {
  checkAll("GoldenCodec[VisitRepository]", GoldenCodecTests[VisitRepository](Printer.spaces2SortKeys).goldenCodec)
} 
Example 21
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 22
Source File: SymmetricSerializationLaws.scala    From circe-yaml   with Apache License 2.0 5 votes vote down vote up
package io.circe.yaml

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

trait SymmetricSerializationLaws {

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

}

object SymmetricSerializationLaws {

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

trait SymmetricSerializationTests extends Laws {
  def laws: SymmetricSerializationLaws

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

object SymmetricSerializationTests {
  def apply[A: Eq: Arbitrary: Decoder: Encoder](
    print: Json => String,
    parse: String => Either[ParsingFailure, Json]
  ): SymmetricSerializationTests =
    new SymmetricSerializationTests {
      val laws: SymmetricSerializationLaws = SymmetricSerializationLaws()
      symmetricPrinter[A](print, parse)
    }
} 
Example 23
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 24
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 25
Source File: ReflexVacuumAgentProgramSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.environment.vacuum

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

import scala.annotation.tailrec


class ReflexVacuumAgentProgramSpec extends Specification with ScalaCheck {

  implicit val arbVacuumEnvironment = Arbitrary(VacuumEnvironment())

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

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

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

} 
Example 26
Source File: ECDSASignatureSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.crypto

import akka.util.ByteString
import io.iohk.ethereum.nodebuilder.SecureRandomBuilder
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import org.spongycastle.crypto.params.ECPublicKeyParameters
import org.spongycastle.util.encoders.Hex

class ECDSASignatureSpec extends FlatSpec with Matchers with PropertyChecks with SecureRandomBuilder {
  "ECDSASignature" should "recover public key correctly for go ethereum transaction" in {
    val bytesToSign = Hex.decode("5a1465f4683bf2c18fc72c0789239c0f52b3ceac666ca9551cf265a11abe912c")
    val signatureRandom = ByteString(Hex.decode("f3af65a23fbf207b933d3c962381aa50e0ac19649c59c1af1655e592a8d95401"))
    val signature = ByteString(Hex.decode("53629a403579f5ce57bcbefba2616b1c6156d308ddcd37372c94943fdabeda97"))
    val pointSign = 28

    val sig = ECDSASignature(BigInt(1, signatureRandom.toArray[Byte]), BigInt(1, signature.toArray[Byte]), pointSign.toByte)

    sig.publicKey(bytesToSign).isEmpty shouldBe false
  }

  it should "fail on case from transaction 74c45d0cf2332cc021bebdfee6b1c1da0b58e8f4154537adb79b025f722920a4" in {
    val bytesToSign = Hex.decode("2bb3925f178aa22c11435c61899e134fb7b1227016274b5f7b9d85c4469130ba")
    val signatureRandom = ByteString(Hex.decode("fbe3df0cf030655d817a89936850d1cc00c07c35d3b21be73cfe9a730ea8b753"))
    val signature = ByteString(Hex.decode("62d73b6a92ac23ff514315fad795bbac6d485481d356329d71467e93c87dfa42"))
    val pointSign = 0x1f

    val sig = ECDSASignature(BigInt(1, signatureRandom.toArray[Byte]), BigInt(1, signature.toArray[Byte]), pointSign.toByte)

    sig.publicKey(bytesToSign).isEmpty shouldBe true
  }

  it should "sign message and recover public key" in {
    forAll(arbitrary[Array[Byte]], Arbitrary.arbitrary[Unit].map(_ => generateKeyPair(secureRandom))) {
      (message, keys) =>

        val pubKey = keys.getPublic.asInstanceOf[ECPublicKeyParameters].getQ
        val msg = kec256(message)

        val signature = ECDSASignature.sign(msg, keys)
        val recPubKey = signature.publicKey(msg)

        val result = recPubKey.map(a => ECDSASignature.uncompressedIndicator +: a).map(curve.getCurve.decodePoint).map(_.getEncoded(true)).map(ByteString(_))
        val expected = Some(pubKey.getEncoded(true)).map(ByteString(_))

        result shouldBe expected
    }
  }
} 
Example 27
Source File: EthashSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.consensus

import akka.util.ByteString
import io.iohk.ethereum.crypto.kec256
import org.scalacheck.Arbitrary
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import org.spongycastle.util.encoders.Hex

class EthashSpec extends FlatSpec with Matchers with PropertyChecks {

  import Ethash._

  "Ethash" should "generate correct hash" in {
    forAll(Arbitrary.arbitrary[Long].filter(_ < 15000000)) { blockNumber =>
      seed(epoch(blockNumber)) shouldBe seedForBlockReference(blockNumber)
    }
  }

  it should "calculate cache size" in {
    val cacheSizes = Seq(16776896, 16907456, 17039296, 17170112, 17301056, 17432512, 17563072)
    cacheSizes.zipWithIndex.foreach { case (referenceSize, epoch) =>
      cacheSize(epoch) shouldBe referenceSize
    }
  }

  it should "compute proof of work using cache" in {
    val hash = Array(0xf5, 0x7e, 0x6f, 0x3a, 0xcf, 0xc0, 0xdd, 0x4b, 0x5b, 0xf2, 0xbe, 0xe4, 0x0a, 0xb3, 0x35, 0x8a, 0xa6, 0x87, 0x73, 0xa8, 0xd0, 0x9f, 0x5e, 0x59, 0x5e, 0xab, 0x55, 0x94, 0x05, 0x52, 0x7d, 0x72).map(_.toByte)
    val nonce = Array(0xd7, 0xb3, 0xac, 0x70, 0xa3, 0x01, 0xa2, 0x49).map(_.toByte)

    val mixHash = Array(0x1f, 0xff, 0x04, 0xce, 0xc9, 0x41, 0x73, 0xfd, 0x59, 0x1e, 0x3d, 0x89, 0x60, 0xce, 0x6b, 0xdf, 0x8b, 0x19, 0x71, 0x04, 0x8c, 0x71, 0xff, 0x93, 0x7b, 0xb2, 0xd3, 0x2a, 0x64, 0x31, 0xab, 0x6d).map(_.toByte)
    val boundary = Array(0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x3e, 0x9b, 0x6c, 0x69, 0xbc, 0x2c, 0xe2, 0xa2, 0x4a, 0x8e, 0x95, 0x69, 0xef, 0xc7, 0xd7, 0x1b, 0x33, 0x35, 0xdf, 0x36, 0x8c, 0x9a, 0xe9, 0x7e, 0x53, 0x84).map(_.toByte)

    val blockNumber = 486382
    val cache = makeCache(epoch(blockNumber))
    val proofOfWork = hashimotoLight(hash, nonce, dagSize(epoch(blockNumber)), cache)

    proofOfWork.mixHash shouldBe ByteString(mixHash)
    proofOfWork.difficultyBoundary shouldBe ByteString(boundary)

    val table = Table(
      ("blockNumber", "hashWithoutNonce", "nonce", "mixHash"),
      (3521,"269d13f7ca546dced28ee26071dcb61085b7c54dfc5f93808b94885e136cd616","534ab630b9aa1f68","c6913517d1dc7544febde9f17e65d6ae4fa380d4a2a2d31305b0043caf95e717"),
      (5021,"7bd6c3c49a0627712c51f1abf0a7828bb25ebb8679d2584385a191db955667da","413dc4ec1a0df7c4","35890608f8867402052b2ce55a694b86a44ce87e7fb5412a77a025b184f25883"),
      (5091,"5b27820bfa3a059274ce17db0beea90ba0b6fbe6b49d2a23cbf972e8cde79319","59225875d18ad606","46f72f8b269461078e9d1cf4edf1b608f9d101e0f335ea59568c3436f291d01b"),
      (3091,"c37d980124cf83a4de4d9600f5bb6d3883797b84b7ec472feff6ca855c01d245","745609efa9c4eef3","c647fec06481b9f3f74cd771968d6d630aa11bf75ebd9e3c55ccfbae0fbad4da"),
      (1091,"c1c1efb8fdd4241a55db39e092fedae3df6d4abc13133778810027ade6557bc6","4d9ddadaea6c20b2","53624a7faac2ec82208348f7a11e3b38c880a2fec76dd8b47e434fe641eeacde"),
      (109,"aa234d4bcee14e93d127275dcc83504b6e730a14e9110bd09b68e1964f0daad3","388e6b37c22147b7","df14701b1ad6d3d5639956e463250960de3189a726cb38d71a6f6042f45dea72"),
      (1009,"3259779f9d2c477d29e18ead0ccc829bf2146723563c3e81e5e4886673d93bfb","5faa044b70ccdf6b","a1f1af0c2ca3e1d8e69da59fefbfeb4d0d172ec96bdbdac71b2cde49ddb3a828"),
      (1001,"028cc9a70d6db52c2a2606f04392e9a323d0370291d6c6d78bc8ce54acf1d761","a54b5b31ce3de766","819c26573f1a9cd6c4b9a399b72fbfb0084a104b25b62083533e114ee98a4831"),
      (1000,"15c5729eb017a703c13d00752338f6b55e2d2551b380706f0486f2ccca57ae1e","eb610e766452a801","a369e2fd5c4e357cf9f60ba063ae0baf32075b0d7ed80cd78134bc401db8f1bf"),
      (100,"41944a94a42695180b1ca231720a87825f17d36475112b659c23dea1542e0977","37129c7f29a9364b","5bb43c0772e58084b221c8e0c859a45950c103c712c5b8f11d9566ee078a4501"))

    forAll(table) { (blockNumber, hashWithoutNonce, nonce, mixHash) =>
      val cache = makeCache(epoch(blockNumber))
      val proofOfWork = hashimotoLight(Hex.decode(hashWithoutNonce), Hex.decode(nonce), dagSize(epoch(blockNumber)), cache)
      proofOfWork.mixHash shouldBe ByteString(Hex.decode(mixHash))
    }
  }

  def seedForBlockReference(blockNumber: BigInt): ByteString = {
    if (blockNumber < EPOCH_LENGTH) {
      //wrong version from YP:
      //ByteString(kec256(Hex.decode("00" * 32)))
      //working version:
      ByteString(Hex.decode("00" * 32))
    } else {
      kec256(seedForBlockReference(blockNumber - EPOCH_LENGTH))
    }
  }

} 
Example 28
Source File: SignedTransactionSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.domain

import io.iohk.ethereum.crypto
import io.iohk.ethereum.crypto.generateKeyPair
import io.iohk.ethereum.domain.SignedTransaction.FirstByteOfAddress
import io.iohk.ethereum.nodebuilder.SecureRandomBuilder
import io.iohk.ethereum.vm.Generators
import org.scalacheck.Arbitrary
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import org.spongycastle.crypto.params.ECPublicKeyParameters

class SignedTransactionSpec extends FlatSpec with Matchers with PropertyChecks with SecureRandomBuilder {
  "SignedTransaction" should "correctly set pointSign for chainId with chain specific signing schema" in {
    forAll(Generators.transactionGen(), Arbitrary.arbitrary[Unit].map(_ => generateKeyPair(secureRandom))) {
      (tx, key) =>
        val chainId: Byte = 0x3d
        val allowedPointSigns = Set((chainId * 2 + 35).toByte, (chainId * 2 + 36).toByte)
        //byte 0 of encoded ECC point indicates that it is uncompressed point, it is part of spongycastle encoding
        val address = Address(crypto.kec256(key.getPublic.asInstanceOf[ECPublicKeyParameters].getQ.getEncoded(false).tail).drop(FirstByteOfAddress))
        val result = SignedTransaction.sign(tx, key, Some(chainId))

        allowedPointSigns should contain(result.signature.v)
        address shouldEqual result.senderAddress
    }
  }
} 
Example 29
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 30
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 31
Source File: PortTest.scala    From jvm-toxcore-api   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.core.network

import im.tox.core.typesafe.Equals._
import im.tox.core.ModuleCompanionTest
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary.arbitrary

object PortTest {

  implicit val arbPort: Arbitrary[Port] =
    Arbitrary(arbitrary[Char].filter(_ =/= 0).map(x => new Port(x)))

}

@SuppressWarnings(Array("org.wartremover.warts.Equals"))
final class PortTest extends ModuleCompanionTest(Port) {

  test("creation") {
    for (portNumber <- Port.MinValue to Port.MaxValue) {
      Port.fromInt(portNumber) match {
        case None       => fail(s"out of range: $portNumber")
        case Some(port) => assert(port.value == portNumber)
      }
    }
  }

  test("creation from invalid values") {
    for (portNumber <- Seq(-1, Int.MinValue, Int.MaxValue, 0x10000)) {
      assert(Port.fromInt(portNumber).isEmpty)
    }
  }

} 
Example 32
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 33
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 34
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 35
Source File: string.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 eu.timepit.refined.string.{EndsWith, StartsWith, Trimmed, Uuid}
import eu.timepit.refined.types.string.TrimmedString
import org.scalacheck.Arbitrary
import shapeless.Witness


object string extends StringInstances with StringInstancesBinCompat1

trait StringInstances {

  implicit def endsWithArbitrary[F[_, _], S <: String](
      implicit rt: RefType[F],
      ws: Witness.Aux[S]
  ): Arbitrary[F[String, EndsWith[S]]] =
    arbitraryRefType(Arbitrary.arbString.arbitrary.map(_ + ws.value))

  implicit def startsWithArbitrary[F[_, _], S <: String](
      implicit rt: RefType[F],
      ws: Witness.Aux[S]
  ): Arbitrary[F[String, StartsWith[S]]] =
    arbitraryRefType(Arbitrary.arbString.arbitrary.map(ws.value + _))

  implicit def nonEmptyStringArbitrary[F[_, _]](
      implicit rt: RefType[F]
  ): Arbitrary[F[String, NonEmpty]] =
    collection.buildableNonEmptyArbitrary[F, String, Char]

  implicit def stringSizeArbitrary[F[_, _]: RefType, P](
      implicit
      arbChar: Arbitrary[Char],
      arbSize: Arbitrary[Int Refined P]
  ): Arbitrary[F[String, Size[P]]] =
    collection.buildableSizeArbitrary[F, String, Char, P]

  implicit def uuidStringArbitrary[F[_, _]](
      implicit rt: RefType[F]
  ): Arbitrary[F[String, Uuid]] =
    arbitraryRefType(Arbitrary.arbUuid.arbitrary.map(_.toString))
}

trait StringInstancesBinCompat1 {
  implicit def trimmedStringArbitrary[F[_, _]](
      implicit rt: RefType[F]
  ): Arbitrary[F[String, Trimmed]] =
    arbitraryRefType(Arbitrary.arbString.arbitrary.map(TrimmedString.trim(_).value))
} 
Example 36
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 37
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 38
Source File: ShiftSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

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

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

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

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

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

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

  property("shift Byte") = createProperty[Byte]
  property("shift Short") = createProperty[Short]
  property("shift Int") = createProperty[Int]
  property("shift Long") = createProperty[Long]
} 
Example 39
Source File: ScodecSpec.scala    From xenomorph   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package xenomorph.scodec

import _root_.scodec.Attempt
import _root_.scodec.bits.BitVector
import org.scalacheck.Arbitrary
import org.scalatest.FunSuite
import org.scalatest.prop.Checkers
import xenomorph.Schema.Schema
import xenomorph.json.JType.JSchema
import xenomorph.samples.Person

class ScodecSpec extends FunSuite with Checkers {

  import xenomorph.scalacheck.ToGen._
  import xenomorph.scalacheck.Implicits._
  import xenomorph.scodec.ToEncoder._
  import xenomorph.scodec.ToDecoder._
  import xenomorph.scodec.Implicits._

  test("Serialization of values to binary should round-trip values produced by a generator"){

    val schema: Schema[JSchema, Person] = Person.schema
    implicit val arbPerson : Arbitrary[Person] = Arbitrary(schema.toGen)

    check(
      (p: Person) => {
        val res = for {
          enc <- schema.toEncoder.encode(p)
          dec <- schema.toDecoder.decode(enc)
        } yield dec

        (res.map(_.value) == Attempt.successful(p)) &&
          (res.map(_.remainder) == Attempt.successful(BitVector.empty))
      }
    )
  }

} 
Example 40
Source File: ScalacheckInstances.scala    From sup   with Apache License 2.0 5 votes vote down vote up
package sup

import org.scalacheck.Cogen
import org.scalacheck.Arbitrary
import sup.data.Tagged

object ScalacheckInstances {

  implicit def arbitraryTagged[Tag: Arbitrary, E: Arbitrary]: Arbitrary[Tagged[Tag, E]] = Arbitrary {
    for {
      tag <- Arbitrary.arbitrary[Tag]
      elem <- Arbitrary.arbitrary[E]
    } yield Tagged(tag, elem)
  }

  implicit def arbitraryHealthResult[H[_]](implicit F: Arbitrary[H[Health]]): Arbitrary[HealthResult[H]] = Arbitrary {
    F.arbitrary.map(HealthResult(_))
  }

  implicit val arbitraryHealth: Arbitrary[Health] = Arbitrary(Arbitrary.arbitrary[Boolean].map(Health.fromBoolean))
  implicit val cogenHealth: Cogen[Health] = Cogen.cogenBoolean.contramap(_.isHealthy)

  implicit def arbitraryHealthCheck[F[_], H[_]](
    implicit A: Arbitrary[F[HealthResult[H]]]
  ): Arbitrary[HealthCheck[F, H]] =
    Arbitrary(A.arbitrary.map(HealthCheck.liftF))

  implicit def cogenHealthResult[H[_]](implicit C: Cogen[H[Health]]): Cogen[HealthResult[H]] = C.contramap(_.value)

  implicit def cogenHealthCheck[F[_], H[_]](implicit C: Cogen[F[HealthResult[H]]]): Cogen[HealthCheck[F, H]] =
    C.contramap(_.check)

  implicit def cogenTagged[Tag: Cogen, H: Cogen]: Cogen[Tagged[Tag, H]] = Cogen[(Tag, H)].contramap { tagged =>
    (tagged.tag, tagged.health)
  }
} 
Example 41
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 42
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 43
Source File: Types.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.test

import cats.Eq
import cats.instances.all._
import org.scalacheck.Arbitrary

object Types {
  class MiniInt(val i: Int)

  object MiniInt {
    def apply(i: Int): MiniInt = new MiniInt(i)

    implicit val arbMiniInt: Arbitrary[MiniInt] = Arbitrary(
      Arbitrary.arbInt.arbitrary.map(MiniInt(_))
    )
    implicit val eqMiniInt: Eq[MiniInt] = Eq.by(_.i)
  }

  class MiniSet(val s: Set[Int])

  object MiniSet {
    def apply(s: Set[Int]): MiniSet = new MiniSet(s)

    implicit val arbMiniSet: Arbitrary[MiniSet] = Arbitrary(
      Arbitrary.arbContainer[Set, Int].arbitrary.map(MiniSet(_))
    )
    implicit val eqMiniSet: Eq[MiniSet] = Eq.by(_.s)
  }

} 
Example 44
Source File: Rules.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package laws

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

object Rules extends Serialization {

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

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

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

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

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

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

import core.EnumLike

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

trait EnumLikeLaws[A] extends Laws {

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

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

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

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

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

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

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

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

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

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

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

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

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

object AnyLaws {

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

  final class Dummy()
}

trait AnyLaws[A] extends Laws {

  import AnyLaws._

  implicit def Arb: Arbitrary[A]

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

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

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

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

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

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

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

import cats.Eq

import shapeless._
import shapeless.syntax.singleton._
import shapeless.record._

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalacheck.Arbitrary

class ReifiedEqSpec extends AnyFlatSpec with Matchers {

  def reifiedEq[A: Arbitrary]: Eq[Reified[A]] =
    ReifiedEqSpec.Helper.testEqForReified

  type XY = Record.`'x -> Int, 'y -> String`.T
  type XYZ1 = Record.`'a -> XY, 'z -> Float`.T
  type YZ = Record.`'y -> String, 'z -> Float`.T
  type XYZ2 = Record.`'x -> Int, 'a -> YZ`.T
  implicitly[XYZ1 =:!= XYZ2]

  "The test Eq[Reified] instance" should "allow tuple nesting differences" in {
    implicit def arbXyz1(implicit arbTup: Arbitrary[(Int, String, Float)]): Arbitrary[XYZ1] = Arbitrary {
      for {
        t <- arbTup.arbitrary
      } yield {
        'a ->> ('x ->> t._1 :: 'y ->> t._2 :: HNil) ::
        'z ->> t._3 ::
        HNil
      }
    }

    val r1: Reified[XYZ1] = Reified[XYZ1]
    val r2: Reified[XYZ1] = Reified[XYZ2].imap[XYZ1] { xyz2 =>
      'a ->> ('x ->> xyz2.head :: 'y ->> xyz2.tail.head('y) :: HNil) ::
      'z ->> xyz2.tail.head('z) ::
      HNil
    } { xyz1 =>
      'x ->> xyz1.head('x) ::
      'a ->> ('y ->> xyz1.head('y) :: 'z ->> xyz1.tail.head :: HNil) ::
      HNil
    }

    reifiedEq[XYZ1].eqv(r1, r2) should be (true)
  }

  it should "not allow additional fields" in {
    val r1 = Reified[(Int, String)]
    val r2 = Reified[(Int, String, Float)].imap[(Int, String)] {
      case (i, s, _) => (i, s)
    } {
      case (i, s) => (i, s, 0.0f)
    }

    reifiedEq[(Int, String)].eqv(r1, r2) should be (false)
  }

  it should "not allow field reordering" in {
    val r1 = Reified[(Int, String)]
    val r2 = Reified[(String, Int)].imap[(Int, String)] {
      case (s, i) => (i, s)
    } {
      case (i, s) => (s, i)
    }

    reifiedEq[(Int, String)].eqv(r1, r2) should be (false)
  }
}

object ReifiedEqSpec {
  object Helper extends TestEqInstances
} 
Example 49
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 50
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 51
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 52
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 53
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 54
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 55
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 56
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 57
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 58
Source File: LocalDateTimeTests.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

import java.time.{Duration, LocalDateTime, ZoneOffset}

import cats.instances.option._
import cats.kernel.laws.discipline.OrderTests
import com.fortysevendeg.scalacheck.datetime.jdk8.ArbitraryJdk8.genZonedDateTime
import dtc.instances.localDateTime._
import dtc.laws.{DateTimeTests, LocalDateTimeTests, ProviderTests}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Cogen}
import dtc.instances.providers.realLocalDateTimeProvider

class JVMLocalDateTimeTests extends DTCSuiteJVM {

  implicit val arbT: Arbitrary[LocalDateTime] = Arbitrary(genZonedDateTime.map(_.toLocalDateTime))
  implicit val cogenT: Cogen[LocalDateTime] = Cogen(_.toEpochSecond(ZoneOffset.UTC))

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

  val ldtTests = LocalDateTimeTests[LocalDateTime](overflowSafePairGen, genYear)
  checkAll("java.time.LocalDateTime", DateTimeTests[LocalDateTime](overflowSafePairGen).dateTime)
  checkAll("java.time.LocalDateTime", ldtTests.localDateTime)
  checkAll("java.time.LocalDateTime", ldtTests.monthUntilFractionHandling)
  checkAll("java.time.LocalDateTime", OrderTests[LocalDateTime].order)
  checkAll("java.time.LocalDateTime", OrderTests[LocalDateTime].partialOrder)
  checkAll("java.time.LocalDateTime", OrderTests[LocalDateTime].eqv)

  checkAll("java.time.LocalDateTime", ProviderTests[LocalDateTime](genTimeZone).provider)
} 
Example 59
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 60
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 61
Source File: MomentLocalDateTimeTests.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

import java.time.{LocalDate, LocalTime}

import cats.instances.option._
import cats.kernel.laws.discipline.OrderTests
import dtc.instances.moment._
import dtc.js.MomentLocalDateTime
import dtc.laws.{DateTimeTests, LocalDateTimeTests, ProviderTests}
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary.arbitrary
import dtc.instances.moment.providers.realMomentLocalDateTimeProvider

class MomentLocalDateTimeTests extends DTCSuiteJS {

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

  implicit val cogenT = cogenMomentDateTime[MomentLocalDateTime]

  val pairGen = overflowSafePairGen.map(t => (MomentLocalDateTime.of(t._1, t._2), t._3))
  val ldtTests = LocalDateTimeTests[MomentLocalDateTime](
    pairGen,
    genJSValidYear
  )
  checkAll("MomentLocalDateTimeTests", DateTimeTests[MomentLocalDateTime](pairGen).dateTime)
  checkAll("MomentLocalDateTimeTests", ldtTests.localDateTime)
  // see: https://github.com/moment/moment/issues/3029
  // checkAll("MomentLocalDateTimeTests", ldtTests.localDateTime)
  checkAll("MomentLocalDateTimeTests", OrderTests[MomentLocalDateTime].order)
  checkAll("MomentLocalDateTimeTests", OrderTests[MomentLocalDateTime].partialOrder)
  checkAll("MomentLocalDateTimeTests", OrderTests[MomentLocalDateTime].eqv)

  checkAll("MomentLocalDateTimeTests", ProviderTests[MomentLocalDateTime](genTimeZone).provider)
} 
Example 62
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 63
Source File: JSDateTests.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

import java.time.{LocalDate, LocalTime}

import cats.instances.option._
import cats.kernel.laws.discipline.OrderTests
import dtc.instances.jsDate._
import dtc.js.JSDate
import dtc.laws.{DateTimeTests, LocalDateTimeTests, ProviderTests}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Cogen}
import dtc.instances.providers.realJSDateProvider

class JSDateTests extends DTCSuiteJS {

  implicit val cogenT: Cogen[JSDate] = Cogen(_.jsGetTime.toLong)

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

  val pairGen = overflowSafePairGen.map(t => (JSDate.of(t._1, t._2), t._3))
  val ldtTests = LocalDateTimeTests[JSDate](
    pairGen, genJSValidYear
  )

  checkAll("JSDate", DateTimeTests[JSDate](pairGen).dateTime)
  checkAll("JSDate", ldtTests.localDateTime)
  checkAll("JSDate", ldtTests.monthUntilFractionHandling)
  checkAll("JSDate", OrderTests[JSDate].order)
  checkAll("JSDate", OrderTests[JSDate].partialOrder)
  checkAll("JSDate", OrderTests[JSDate].eqv)

  checkAll("JSDate", ProviderTests[JSDate](genTimeZone).provider)
} 
Example 64
Source File: arb.scala    From abc   with Apache License 2.0 5 votes vote down vote up
package com.rklaehn.abc

import algebra.{Eq, Order}
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary._

object arb {

  implicit def arbArraySeq[T: Arbitrary: ClassTag] = Arbitrary {
    for {
      xs ← arbitrary[IndexedSeq[T]]
    } yield
      ArraySeq(xs: _*)
  }

  implicit def arbTotalArraySeq[K: Arbitrary: Eq: ClassTag] = Arbitrary {
    for {
      m ← arbitrary[ArraySeq[K]]
      default ← arbitrary[K]
    } yield
      m.withDefault(default)
  }

  implicit def arbArraySet[T: Arbitrary: Order: ClassTag] = Arbitrary {
    for {
      xs ← arbitrary[IndexedSeq[T]]
    } yield
      ArraySet(xs: _*)
  }

  implicit def arbNegatableArraySet[T: Arbitrary: Order: ClassTag] = Arbitrary {
    for {
      xs ← arbitrary[Vector[T]]
      n ← arbitrary[Boolean]
    } yield
      NegatableArraySet(xs :_*) xor NegatableArraySet.fromBoolean(n)
  }

  implicit def arbArrayMap[K: Arbitrary: Order: ClassTag, V: Arbitrary: ClassTag] = Arbitrary {
    for {
      xs ← arbitrary[IndexedSeq[(K, V)]]
    } yield
      ArrayMap(xs: _*)
  }

  implicit def arbTotalArrayMap[K: Arbitrary: Order: ClassTag, V: Arbitrary: ClassTag: Eq] = Arbitrary {
    for {
      m ← arbitrary[ArrayMap[K, V]]
      default ← arbitrary[V]
    } yield
      m.withDefault(default)
  }

//
//  implicit def arbArrayMultiMap[K: Arbitrary: Order: ClassTag, V: Arbitrary: Order: ClassTag] = Arbitrary {
//    for {
//      xs ← arbitrary[IndexedSeq[(K, ArraySet[V])]]
//    } yield
//      ArrayMultiMap(xs: _*)
//  }
} 
Example 65
Source File: ArraySetCheck.scala    From abc   with Apache License 2.0 5 votes vote down vote up
package com.rklaehn.abc

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  property("flatMap") = forAll { as: ArraySeq[Int] ⇒
    as.flatMap(x ⇒ ArraySeq(x, x + 1)).length == as.length * 2
  }
} 
Example 67
Source File: ArraySetHashCheck.scala    From abc   with Apache License 2.0 5 votes vote down vote up
package com.rklaehn.abc

import algebra.{Eq, Order}
import cats.implicits._
import org.scalacheck.Arbitrary
import org.scalatest.FunSuite
import org.scalatest.prop.Checkers

class ArraySetHashCheck extends FunSuite with Checkers with Helpers {

  def checkHashing[T: Order: Hash: ClassTag: Arbitrary](): Unit = {
    val name = typeName[T]
    test(s"hashConsistency $name") {
      check { xs: Vector[T] ⇒
        Eq.eqv(ArraySet(xs: _*), ArraySet(xs.reverse: _*)) &&
        Hash.hash(ArraySet(xs: _*)) == Hash.hash(ArraySet(xs.reverse: _*))
      }
    }
  }
  checkHashing[Byte]()
  checkHashing[Short]()
  checkHashing[Int]()
  checkHashing[Long]()
  checkHashing[Float]()
  checkHashing[Double]()
  checkHashing[Boolean]()
  checkHashing[Char]()
  checkHashing[String]()
} 
Example 68
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 69
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 70
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 71
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 72
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 73
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 74
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 75
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 76
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 77
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 78
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 79
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 80
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 81
Source File: LawTests.scala    From paiges   with Apache License 2.0 5 votes vote down vote up
package org.typelevel.paiges

import cats.Semigroupal
import cats.Contravariant
import cats.kernel.{Eq, Monoid}
import cats.laws.discipline.{ContravariantTests, DeferTests, ExhaustiveCheck, SemigroupalTests, SerializableTests}
import cats.kernel.laws.discipline.MonoidTests
import cats.laws.discipline.eq.catsLawsEqForFn1Exhaustive

import org.typelevel.discipline.scalatest.FunSuiteDiscipline
import org.scalacheck.Arbitrary
import org.scalactic.anyvals.{PosInt, PosZDouble, PosZInt}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.prop.Configuration

class LawTests extends LawChecking with CatsDocument {
  import org.typelevel.paiges.Generators._
  import org.typelevel.paiges.instances._

  implicit val docEq: Eq[Doc] =
    Eq.instance((x: Doc, y: Doc) => PaigesTest.docEquiv.equiv(x, y))

  implicit def monoidTests[A: Eq: Arbitrary: Monoid] = MonoidTests[A]

  implicit def arbitraryForDocument[A]: Arbitrary[Document[A]] =
    Arbitrary(Document.useToString[A])

  implicit def eqForDocument[A: ExhaustiveCheck]: Eq[Document[A]] =
    Eq.by[Document[A], A => Doc](inst => (a: A) => inst.document(a))

  implicit val eqBool: Eq[Boolean] =
    Eq.instance[Boolean](_ == _)

  checkAll("Monoid[Doc]", MonoidTests[Doc].monoid)
  checkAll("Monoid[Style]", MonoidTests[Style].monoid)

  checkAll("Contravariant[Document]", ContravariantTests[Document].contravariant[Boolean, Boolean, Boolean])
  checkAll("Contravariant[Document]", SerializableTests.serializable(Contravariant[Document]))
  checkAll("Defer[Document]", DeferTests[Document].defer[Boolean])

  {
    implicit val semigroupalDocument: Semigroupal[Document] =
      CatsDocument.semigroupalDocument(Doc.char(','))
    checkAll("Semigroupal[Document]", SemigroupalTests[Document].semigroupal[Boolean, Boolean, Boolean])
    checkAll("Semigroupal[Document]", SerializableTests.serializable(Semigroupal[Document]))
  }
}

abstract class LawChecking extends AnyFunSuite with Configuration with FunSuiteDiscipline {

  lazy val checkConfiguration: PropertyCheckConfiguration =
    PropertyCheckConfiguration(
      minSuccessful = if (Platform.isJvm) PosInt(50) else PosInt(5),
      maxDiscardedFactor = if (Platform.isJvm) PosZDouble(5.0) else PosZDouble(50.0),
      minSize = PosZInt(0),
      sizeRange = if (Platform.isJvm) PosZInt(10) else PosZInt(5),
      workers = PosInt(1)
    )

  // The scalacheck defaults 'sizeRange' (100) is too high for Scala-js, so we reduce to 10.
  // We also set `minSuccessful` to 100 unconditionally.
  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    if (Platform.isJvm) PropertyCheckConfiguration(sizeRange = 100, minSuccessful = 100)
    else PropertyCheckConfiguration(sizeRange = 10, minSuccessful = 100)
} 
Example 82
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 83
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 84
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 85
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 86
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 87
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 88
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 89
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 90
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 91
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 92
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 93
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 94
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 95
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 96
Source File: KNNPropSpec.scala    From spark-tda   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.ml.util.knn

import scala.reflect.ClassTag
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen.{choose, oneOf}
import org.scalatest.PropSpec
import org.apache.spark.ml.linalg.{
  CosineDistance,
  EuclideanDistance,
  ManhattanDistance,
  JaccardDistance,
  HammingDistance
}
import org.apache.spark.ml.linalg.{Vector, SparseVector, DenseVector, Vectors}
import com.holdenkarau.spark.testing.SharedSparkContext


abstract class KNNPropSpec extends PropSpec with SharedSparkContext {
  implicit def arbitraryDenseVector: Arbitrary[DenseVector] =
    Arbitrary {
      for (arr <- arbitrary[Array[Double]]) yield new DenseVector(arr)
    }

  implicit def arbitrarySparseVector: Arbitrary[SparseVector] =
    Arbitrary {
      for (vec <- arbitrary[DenseVector]) yield vec.toSparse
    }

  implicit def arbitraryVector: Arbitrary[Vector] =
    Arbitrary(
      Gen.frequency(
        1 -> arbitrary[DenseVector],
        1 -> arbitrary[SparseVector]
      ))

  private def arraysOfNM[T: ClassTag](numRows: Int,
                                      numCols: Int,
                                      gen: Gen[T]): Gen[Array[Array[T]]] =
    Gen.listOfN(numRows * numCols, gen).map { square =>
      square.toArray.grouped(numCols).toArray
    }

  private def vectorsOfNM(numRows: Int,
                          numCols: Int,
                          gen: Gen[Double]): Gen[Array[DenseVector]] =
    for {
      arrays <- arraysOfNM(numRows, numCols, gen)
    } yield arrays.map(arr => new DenseVector(arr))

  val treeGen = for {
    measure <- oneOf(CosineDistance,
                     EuclideanDistance,
                     ManhattanDistance,
                     HammingDistance,
                     JaccardDistance)
    numVectors <- choose(1, 100)
    vectors <- vectorsOfNM(numVectors, 2, choose(-10.0, 10.0))
  } yield
    vectors
      .scanLeft(Seq[Vector]())(_ :+ _)
      .tail
      .map(
        vs =>
          VPTree(vs.map(v => VectorEntry(0L, v)).toIndexedSeq,
                 measure,
                 10,
                 10,
                 10))
} 
Example 97
Source File: IntervalPropSpec.scala    From spark-tda   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.ml.util.interval

import scala.reflect.ClassTag
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.PropSpec


abstract class IntervalPropSpec extends PropSpec {
  implicit def arbitraryOpenEndpoint: Arbitrary[Open] =
    Arbitrary { for (at <- arbitrary[Double]) yield Open(at) }

  implicit def arbitraryClosedEndpoint: Arbitrary[Closed] =
    Arbitrary { for (at <- arbitrary[Double]) yield Closed(at) }

  implicit def arbitraryUnboundedEndpoint: Arbitrary[Unbounded] =
    Arbitrary(Unbounded())

  implicit def arbitraryEndpoint: Arbitrary[Endpoint] =
    Arbitrary(
      Gen.frequency(
        4 -> arbitrary[Open],
        4 -> arbitrary[Closed],
        2 -> arbitrary[Unbounded]
      ))

  implicit def arbitraryLowerBound: Arbitrary[LowerBound] =
    Arbitrary(for (endpoint <- arbitrary[Endpoint]) yield LowerBound(endpoint))

  implicit def arbitraryUpperBound: Arbitrary[UpperBound] =
    Arbitrary(for (endpoint <- arbitrary[Endpoint]) yield UpperBound(endpoint))

  implicit def arbitraryBound: Arbitrary[Bound] =
    Arbitrary(Gen.oneOf(arbitrary[LowerBound], arbitrary[UpperBound]))

  implicit def arbitraryInterval: Arbitrary[Interval] = Arbitrary {
    def validate(lhs: Endpoint, rhs: Endpoint) =
      Interval.validate(LowerBound(lhs), UpperBound(rhs)) || Interval
        .validate(LowerBound(rhs), UpperBound(lhs))
    def interval(lhs: Endpoint, rhs: Endpoint) =
      if (Interval.validate(LowerBound(lhs), UpperBound(rhs)))
        new Interval(LowerBound(lhs), UpperBound(rhs))
      else new Interval(LowerBound(rhs), UpperBound(lhs))
    for {
      x <- arbitrary[Endpoint]
      y <- arbitrary[Endpoint] if validate(x, y)
    } yield interval(x, y)
  }

  implicit def arbitrary2DimensionalCube: Arbitrary[Cube] = Arbitrary {
    for {
      x <- arbitrary[Interval]
      y <- arbitrary[Interval]
    } yield Cube(x, y)
  }
} 
Example 98
Source File: VecMapSpec.scala    From chinese-restaurant-process   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.monsanto.stats.tables.clustering

import com.monsanto.stats.tables.UnitSpec
import org.scalatest._
import enablers.Collecting
import scala.collection.GenTraversable
import prop.GeneratorDrivenPropertyChecks
import org.scalactic.Equality
import org.scalactic.anyvals.{ PosZInt, PosZDouble }
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Gen._
import scala.collection.mutable
import com.monsanto.stats.tables._

class VecMapSpec extends UnitSpec {

  val allTopicVectorResults: Vector[TopicVectorInput] = MnMGen.getData()
  val p5 = ModelParams(5, 1, 1)
  val crp = new CRP(p5, allTopicVectorResults)

  "A VecMap" should {
    "offer a toMap method that returns a Map equal to the Map passed to its factory method" in {
      crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9)).toMap shouldEqual Map(1 -> 1, 2 -> 4, 3 -> 9)
    }
    "be equal to another VecMap created with an equal Map" in {
      crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9)) shouldEqual crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9))
    }
    "offer a size method that returns the size of the initializing Map" in {
      crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9, 5 -> 25)).size shouldEqual 4
      crp.VecMap(Map.empty).size shouldEqual 0
      crp.VecMap(Map(10 -> 9)).size shouldEqual 1
    }
    "offer a + method that combines sums (does Matrix addition on this one-row matrix)" in {
      val vecMap = crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9, 5 -> 25))
      vecMap + crp.VecMap(Map.empty) shouldEqual vecMap
      crp.VecMap(Map.empty) + vecMap shouldEqual vecMap
      vecMap + vecMap shouldEqual crp.VecMap(Map(1 -> 2, 2 -> 8, 3 -> 18, 5 -> 50))
      crp.VecMap(Map.empty) + crp.VecMap(Map.empty) shouldEqual crp.VecMap(Map.empty)
      vecMap + crp.VecMap(Map(77 -> 77, 88 -> 88, 99 -> 99)) shouldEqual crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9, 5 -> 25, 77 -> 77, 88 -> 88, 99 -> 99))
      vecMap + crp.VecMap(Map(77 -> 77, 88 -> 88, 99 -> 99)) shouldEqual crp.VecMap(Map(2 -> 4, 3 -> 9, 5 -> 25, 77 -> 77, 88 -> 88, 99 -> 99, 1 -> 1))
    }
  }
} 
Example 99
Source File: HCacheTests.scala    From dagon   with Apache License 2.0 5 votes vote down vote up
package com.stripe.dagon

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object CacheTestsSL extends CacheTests[String, Long]("CacheTests[String, Long]") 
Example 101
Source File: MTLSpecs.scala    From shims   with Apache License 2.0 5 votes vote down vote up
package shims.effect

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

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

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

import org.scalacheck.{Arbitrary, Prop}

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

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

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

import java.io.{ByteArrayOutputStream, PrintStream}

object MTLSpecs extends Specification with Discipline {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object CodecEquivalenceLaws {

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

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

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

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

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

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

  def useTagged[A](
    implicit
    circeDecode: TaggedDecoder[tags.Circe, A],
    magnoliaDecode: TaggedDecoder[tags.Magnolia, A],
    circeEncode: TaggedEncoder[tags.Circe, A],
    magnoliaEncode: TaggedEncoder[tags.Magnolia, A]): CodecEquivalenceTests[A] = new CodecEquivalenceTests[A] {
    val laws: CodecEquivalenceLaws[A] = CodecEquivalenceLaws[A](
      circeDecode.toTagged, magnoliaDecode.toTagged, circeEncode.toTagged, magnoliaEncode.toTagged)
  }
} 
Example 103
Source File: CardinalDirection.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.tests.examples

import cats.kernel.Eq
import org.scalacheck.{ Arbitrary, Gen }

sealed trait CardinalDirection
case object North extends CardinalDirection
case object South extends CardinalDirection
case object East extends CardinalDirection
case object West extends CardinalDirection

object CardinalDirection {
  implicit val eqCardinalDirection: Eq[CardinalDirection] = Eq.fromUniversalEquals
  implicit val arbitraryCardinalDirection: Arbitrary[CardinalDirection] = Arbitrary(
    Gen.oneOf(North, South, East, West)
  )
}

sealed trait ExtendedCardinalDirection
case object North2 extends ExtendedCardinalDirection
case object South2 extends ExtendedCardinalDirection
case object East2 extends ExtendedCardinalDirection
case object West2 extends ExtendedCardinalDirection
case class NotACardinalDirectionAtAll(x: String) extends ExtendedCardinalDirection

object ExtendedCardinalDirection {
  implicit val eqExtendedCardinalDirection: Eq[ExtendedCardinalDirection] = Eq.fromUniversalEquals
  implicit val arbitraryExtendedCardinalDirection: Arbitrary[ExtendedCardinalDirection] = Arbitrary(
    Gen.oneOf(
      Gen.const(North2),
      Gen.const(South2),
      Gen.const(East2),
      Gen.const(West2),
      Arbitrary.arbitrary[String].map(NotACardinalDirectionAtAll(_))
    )
  )
} 
Example 104
Source File: WrappedOptionalString.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.tests.examples

import cats.kernel.Eq
import io.circe.{ Decoder, Encoder }
import org.scalacheck.Arbitrary

case class OptionalString(value: String) {
  def toOption: Option[String] = value match {
    case "" => None
    case other => Some(other)
  }
}

object OptionalString {
  def fromOption(o: Option[String]): OptionalString =
    OptionalString(o.getOrElse(""))

  implicit val decodeOptionalString: Decoder[OptionalString] =
    Decoder[Option[String]].map(fromOption)

  implicit val encodeOptionalString: Encoder[OptionalString] =
    Encoder[Option[String]].contramap(_.toOption)

  implicit val eqOptionalString: Eq[OptionalString] = Eq.fromUniversalEquals

  implicit val arbitraryOptionalString: Arbitrary[OptionalString] =
    Arbitrary(Arbitrary.arbitrary[Option[String]].map(fromOption))
}

case class WrappedOptionalField(f: OptionalString)

object WrappedOptionalField {
  implicit val decodeWrappedOptionalField: Decoder[WrappedOptionalField] =
    Decoder.forProduct1("f")(WrappedOptionalField.apply)

  implicit val encodeWrappedOptionalField: Encoder[WrappedOptionalField] =
    Encoder.forProduct1("f")(_.f)

  implicit val eqWrappedOptionalField: Eq[WrappedOptionalField] =
    Eq.fromUniversalEquals

  implicit val arbitraryWrappedOptionalField: Arbitrary[WrappedOptionalField] =
    Arbitrary(Arbitrary.arbitrary[OptionalString].map(WrappedOptionalField(_)))
} 
Example 105
Source File: SemiautoDerivedSuiteInputs.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.magnolia

import cats.kernel.Eq
import io.circe.generic.semiauto._
import io.circe.{Decoder, Encoder}
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Arbitrary.arbitrary

object SemiautoDerivedSuiteInputs {

  sealed trait RecursiveAdtExample
  case class BaseAdtExample(a: String) extends RecursiveAdtExample
  case class NestedAdtExample(r: RecursiveAdtExample)
      extends RecursiveAdtExample

  object RecursiveAdtExample {
    implicit val eqRecursiveAdtExample: Eq[RecursiveAdtExample] =
      Eq.fromUniversalEquals

    private def atDepth(depth: Int): Gen[RecursiveAdtExample] =
      if (depth < 3)
        Gen.oneOf(
          Arbitrary.arbitrary[String].map(BaseAdtExample(_)),
          atDepth(depth + 1).map(NestedAdtExample(_))
        )
      else Arbitrary.arbitrary[String].map(BaseAdtExample(_))

    implicit val arbitraryRecursiveAdtExample: Arbitrary[RecursiveAdtExample] =
      Arbitrary(atDepth(0))
  }

  case class RecursiveWithOptionExample(o: Option[RecursiveWithOptionExample])

  object RecursiveWithOptionExample {
    implicit val eqRecursiveWithOptionExample: Eq[RecursiveWithOptionExample] =
      Eq.fromUniversalEquals

    private def atDepth(depth: Int): Gen[RecursiveWithOptionExample] =
      if (depth < 3)
        Gen.option(atDepth(depth + 1)).map(RecursiveWithOptionExample(_))
      else Gen.const(RecursiveWithOptionExample(None))

    implicit val arbitraryRecursiveWithOptionExample
      : Arbitrary[RecursiveWithOptionExample] =
      Arbitrary(atDepth(0))
  }

  case class AnyInt(value: Int) extends AnyVal

  object AnyInt {
    implicit val encodeAnyInt: Encoder[AnyInt] = deriveEncoder
    implicit val decodeAnyInt: Decoder[AnyInt] = deriveDecoder
  }

  case class AnyValInside(v: AnyInt)

  object AnyValInside {
    implicit val eqAnyValInside: Eq[AnyValInside] = Eq.fromUniversalEquals

    implicit val arbitraryAnyValInside: Arbitrary[AnyValInside] =
      Arbitrary(arbitrary[Int].map(i => AnyValInside(AnyInt(i))))
  }

  case class OvergenerationExampleInner(i: Int)
  case class OvergenerationExampleOuter0(i: OvergenerationExampleInner)
  case class OvergenerationExampleOuter1(oi: Option[OvergenerationExampleInner])
} 
Example 106
Source File: GeneratableNumberFormats.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen.formats

import de.leanovate.swaggercheck.schema.model.formats.NumberFormats
import de.leanovate.swaggercheck.schema.model.{JsonPath, ValidationResult}
import org.scalacheck.{Arbitrary, Gen}

object GeneratableNumberFormats {

  object FloatNumber extends GeneratableFormat[BigDecimal] {
    override def generate: Gen[BigDecimal] = Arbitrary.arbitrary[Float].map(_.toDouble).map(BigDecimal.decimal)

    override def validate(path: JsonPath, value: BigDecimal): ValidationResult =
      NumberFormats.FloatNumber.validate(path, value)
  }

  object DoubleNumber extends GeneratableFormat[BigDecimal] {
    override def generate: Gen[BigDecimal] = Arbitrary.arbitrary[Double].map(BigDecimal.decimal)

    override def validate(path: JsonPath, value: BigDecimal): ValidationResult =
      NumberFormats.DoubleNumber.validate(path, value)
  }

  val defaultFormats = Map(
    "float" -> FloatNumber,
    "double" -> DoubleNumber
  )
} 
Example 107
Source File: GeneratableIntegerFormats.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen.formats

import de.leanovate.swaggercheck.schema.model.formats.IntegerFormats
import de.leanovate.swaggercheck.schema.model.{JsonPath, ValidationResult}
import org.scalacheck.{Arbitrary, Gen}

object GeneratableIntegerFormats {

  object Int32 extends GeneratableFormat[BigInt] {
    override def generate: Gen[BigInt] = Arbitrary.arbitrary[Int].map(BigInt.apply)

    override def validate(path: JsonPath, value: BigInt): ValidationResult =
      IntegerFormats.Int32.validate(path, value)
  }

  object Int64 extends GeneratableFormat[BigInt] {
    override def generate: Gen[BigInt] = Arbitrary.arbitrary[Long].map(BigInt.apply)

    override def validate(path: JsonPath, value: BigInt): ValidationResult =
      IntegerFormats.Int64.validate(path, value)
  }

  val defaultFormats = Map(
    "int32" -> Int32,
    "int64" -> Int64
  )
} 
Example 108
Source File: GeneratableInteger.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen

import de.leanovate.swaggercheck.schema.adapter.NodeAdapter
import de.leanovate.swaggercheck.schema.model.{IntegerDefinition, JsonPath, Schema, ValidationResult}
import de.leanovate.swaggercheck.shrinkable.{CheckJsInteger, CheckJsValue}
import org.scalacheck.{Arbitrary, Gen}

case class GeneratableInteger(
                               definition: IntegerDefinition
                             ) extends GeneratableDefinition {
  override def validate[T](schema: Schema, path: JsonPath, node: T)
                          (implicit nodeAdapter: NodeAdapter[T]): ValidationResult =
    definition.validate(schema, path, node)

  override def generate(schema: GeneratableSchema): Gen[CheckJsValue] = {
    val generator: Gen[BigInt] =
      definition.format
        .flatMap(schema.findGeneratableIntegerFormat)
        .map(_.generate)
        .getOrElse(Arbitrary.arbitrary[BigInt])
        .retryUntil {
          value: BigInt =>
            !definition.minimum.exists(_ > value) && !definition.maximum.exists(_ < value)
        }
    generator.map(value => CheckJsInteger(definition.minimum, definition.maximum, value))
  }
} 
Example 109
Source File: GeneratableNumber.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen

import de.leanovate.swaggercheck.schema.adapter.NodeAdapter
import de.leanovate.swaggercheck.schema.model.{JsonPath, NumberDefinition, Schema, ValidationResult}
import de.leanovate.swaggercheck.shrinkable.{CheckJsNumber, CheckJsValue}
import org.scalacheck.{Arbitrary, Gen}

import scala.util.Try

case class GeneratableNumber(
                              definition: NumberDefinition
                            ) extends GeneratableDefinition {
  override def validate[T](schema: Schema, path: JsonPath, node: T)
                          (implicit nodeAdapter: NodeAdapter[T]): ValidationResult =
    definition.validate(schema, path, node)

  override def generate(schema: GeneratableSchema): Gen[CheckJsValue] = {
    val generator: Gen[BigDecimal] =
      definition.format
        .flatMap(schema.findGeneratableNumberFormat)
        .map(_.generate)
        .getOrElse(Arbitrary.arbitrary[BigDecimal])
        .retryUntil {
          value: BigDecimal =>
            Try(BigDecimal(value.toString())).isSuccess &&
              !definition.minimum.exists(_ > value) && !definition.maximum.exists(_ < value)
        }
    generator.map(value => CheckJsNumber(definition.minimum, definition.maximum, value))
  }
} 
Example 110
Source File: CheckJsIntegerSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.shrinkable

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

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

      val shrink = Shrink.shrink(original)

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

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

      val shrink = Shrink.shrink(original)

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

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

      val shrink = Shrink.shrink(original)

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


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

      val shrink = Shrink.shrink(original)

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

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

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

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

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

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

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

import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import models._
import org.scalacheck.{Arbitrary, Gen}

trait Arbitraries {
  implicit val arbitraryUUID = Arbitrary[UUID](Gen.uuid)

  implicit val arbitraryThingType = Arbitrary[ThingType.Value](Gen.oneOf(ThingType.Primary, ThingType.Secondary, ThingType.Other))

  implicit val arbitraryThing = Arbitrary[Thing](for {
    id <- Arbitrary.arbitrary[UUID]
    name <- Gen.choose(1, 100).flatMap(Gen.listOfN(_, Gen.alphaNumChar).map(_.mkString))
    thingType <- Arbitrary.arbitrary[ThingType.Value]
  } yield Thing(id, name, thingType))

  implicit val arbitraryLink = Arbitrary[Link](for {
    href <- Generators.url
  } yield Link(href))

  implicit val arbitraryThingPageLinks = Arbitrary[ThingsPageLinks](for {
    self <- Arbitrary.arbitrary[Link]
    first <- Arbitrary.arbitrary[Option[Link]]
    last <- Arbitrary.arbitrary[Option[Link]]
  } yield ThingsPageLinks(self, first, last))

  implicit val arbitraryThingPage = Arbitrary[ThingsPage](for {
    size <- Gen.choose(0, 20)
    things <- Gen.listOfN(size, Arbitrary.arbitrary[Thing])
    _links <- Arbitrary.arbitrary[ThingsPageLinks]
  } yield ThingsPage(things, _links))

  implicit val arbitraryError = Arbitrary[Error](for {
    code <- Gen.choose(100, 599)
    message <- Arbitrary.arbitrary[String]
  } yield Error(code, message))
} 
Example 113
Source File: ThingsControllerSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

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

import scala.concurrent.Future

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

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

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

        status(result) must between(200, 300)

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

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

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

    new GuiceApplicationBuilder()
      .overrides(bind[ThingsRepository].toInstance(mockThingsRepository))
      .build()
  }
} 
Example 114
Source File: Thing.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class Thing(
                  id: Long,
                  name: String,
                  description: Option[String]
                  )

object Thing {
  implicit val jsonFormat = Json.format[Thing]

  implicit val arbitrary = Arbitrary(for {
    id <- Gen.posNum[Long]
    name <- Gen.identifier
    description <- Gen.option(Gen.identifier)
  } yield Thing(id, name, description))
} 
Example 115
Source File: AnyThing.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.net.{URI, URL}
import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDate}
import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.{Json, OFormat}

import scala.util.Try

case class AnyThing(
                     anUUID: String,
                     anURL: String,
                     anURI: String,
                     anEmail: String,
                     aDate: LocalDate,
                     aDateTime: Instant,
                     anInt32: Int,
                     anInt64: Long,
                     aFloat: Float,
                     aDouble: Double,
                     aBoolean: Boolean,
                     anEnum: String,
                     aMap: Map[String, String]
                   ) {
  def isValid: Boolean = {
    Try {
      UUID.fromString(anUUID)
      new URL(anURL)
      new URI(anURI)
    }.isSuccess && Set("V1", "V2", "V3").contains(anEnum)
  }
}

object AnyThing {
  implicit val jsonFormat: OFormat[AnyThing] = Json.format[AnyThing]

  implicit val arbitrary = Arbitrary(for {
    anUUID <- Gen.uuid.map(_.toString)
    anURL <- Generators.url
    anURI <- Generators.uri
    anEmail <- Generators.email
    aDate <- Arbitrary.arbitrary[Int].map(diff => LocalDate.now().plus(diff, ChronoUnit.DAYS))
    aDateTime <- Arbitrary.arbitrary[Long].map(diff => Instant.now().plus(diff, ChronoUnit.NANOS))
    anInt32 <- Arbitrary.arbitrary[Int]
    anInt64 <- Arbitrary.arbitrary[Long]
    aFloat <- Arbitrary.arbitrary[Float]
    aDouble <- Arbitrary.arbitrary[Double]
    aBoolean <- Arbitrary.arbitrary[Boolean]
    anEnum <- Gen.oneOf("V1", "V2", "V3")
    aMap <- Arbitrary.arbitrary[Map[String, String]]
  } yield AnyThing(anUUID, anURL, anURI, anEmail, aDate, aDateTime, anInt32, anInt64, aFloat, aDouble, aBoolean, anEnum, aMap))
} 
Example 116
Source File: ServiceDocument.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import org.scalacheck.Arbitrary
import play.api.libs.json.Json

case class ServiceDocumentLinks(
                                 self: Link,
                                 things: Link
                                 )

object ServiceDocumentLinks {
  implicit val jsonFormat = Json.format[ServiceDocumentLinks]

  implicit val arbitrary = Arbitrary(for {
    self <- Arbitrary.arbitrary[Link]
    things <- Arbitrary.arbitrary[Link]
  } yield ServiceDocumentLinks(self, things))
}

case class ServiceDocument(
                            _links: ServiceDocumentLinks
                            )

object ServiceDocument {
  implicit val jsonFormat = Json.format[ServiceDocument]

  implicit val arbitrary = Arbitrary(for {
    _links <- Arbitrary.arbitrary[ServiceDocumentLinks]
  } yield ServiceDocument(_links))
} 
Example 117
Source File: OtherBase.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class OtherBase(
                      id: UUID,
                      firstName: Option[String],
                      lastName: String
                      )

object OtherBase {
  implicit val jsonFormat = Json.format[OtherBase]

  implicit val arbitrary = Arbitrary(for {
    id <- Gen.uuid
    firstName <- Arbitrary.arbitrary[Option[String]]
    lastName <- Arbitrary.arbitrary[String]
  } yield OtherBase(id, firstName, lastName))
} 
Example 118
Source File: SubBase.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class SubBase(
                    id: UUID,
                    email: Option[String]
                    )

object SubBase {
  implicit val jsonFormat = Json.format[SubBase]

  implicit val arbitrary = Arbitrary(for {
    id <- Gen.uuid
    email <- Gen.option(Generators.email)
  } yield SubBase(id, email))
} 
Example 119
Source File: Author.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.bookdb

import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class Author(
                   id: Option[UUID],
                   name: String
                 )

object Author {
  implicit val jsonFormat = Json.format[Author]

  implicit val arbitrary = Arbitrary(for {
    id <- Gen.option(Gen.uuid)
    name <- Arbitrary.arbitrary[String]
  } yield Author(id, name))
} 
Example 120
Source File: UberProduct.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.uber

import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class UberProduct(
                        product_id: Option[String],
                        description: Option[String],
                        display_name: Option[String],
                        capacity: Option[String],
                        image: Option[String]
                        )

object UberProduct {
  implicit val jsonFormat = Json.format[UberProduct]

  implicit val arbitrary = Arbitrary(for {
    product_id <- Gen.option(Gen.identifier)
    description <- Gen.option(Gen.alphaStr)
    display_name <- Gen.option(Gen.alphaStr)
    capacity <- Gen.option(Gen.alphaStr)
    image <- Gen.option(Gen.identifier)
  } yield UberProduct(product_id, description, display_name, capacity, image))
} 
Example 121
Source File: UberError.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.uber

import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class UberError(
                  code: Option[Int],
                  message: Option[String],
                  fields: Option[String]
                  )

object UberError {
  implicit val jsonFormat = Json.format[UberError]

  implicit val arbitrary = Arbitrary(for {
    code <- Gen.option(Gen.choose(400, 599))
    message <- Gen.option(Gen.alphaStr)
    fields <- Gen.option(Gen.identifier)
  } yield UberError(code, message, fields))
} 
Example 122
Source File: UberApiSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck

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

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

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

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

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

        verifier.verify(json)
    }
  }

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

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

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

        verifier.verify(json)
    }
  }

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

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

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

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

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

import java.util.UUID

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

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

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

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

        verifier.verify(json)
    }
  }

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

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

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

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

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

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

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

      (operationVerifier.request.path == "/v1/authors") :| "Path" &&
        (operationVerifier.request.method == "POST") :| "Method" &&
        operationVerifier.responseVerifier.verify(response).isSuccess :| "Response verifier"
      true :| "Just ok"
  }
} 
Example 124
Source File: PropertyCheck.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airspec.spi

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


trait PropertyCheck extends Asserts { this: AirSpecSpi =>

  protected def scalaCheckConfig: Parameters = Test.Parameters.default

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

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

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

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

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

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

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

  protected def forAll[A1, A2, A3, U](checker: (A1, A2, A3) => U)(implicit
      a1: Arbitrary[A1],
      s1: Shrink[A1],
      pp1: A1 => Pretty,
      a2: Arbitrary[A2],
      s2: Shrink[A2],
      pp2: A2 => Pretty,
      a3: Arbitrary[A3],
      s3: Shrink[A3],
      pp3: A3 => Pretty
  ): Unit = {
    val prop = Prop.forAll { (a1: A1, a2: A2, a3: A3) =>
      checker(a1, a2, a3)
      true
    }(booleanProp, a1, s1, pp1, a2, s2, pp2, a3, s3, pp3)
    checkProperty(prop)
  }
} 
Example 125
Source File: ArbitraryProtoUtils.scala    From sparksql-scalapb   with Apache License 2.0 5 votes vote down vote up
package scalapb.spark

import com.google.protobuf.ByteString
import org.scalacheck.Arbitrary
import org.scalacheck.derive.MkArbitrary
import scalapb.spark.test.{all_types2 => AT2}
import scalapb.spark.test3.{all_types3 => AT3}
import scalapb.{GeneratedEnum, GeneratedEnumCompanion, GeneratedMessage, Message}
import shapeless.Strict
import org.scalacheck.Gen
import scalapb.UnknownFieldSet

object ArbitraryProtoUtils {
  import org.scalacheck.ScalacheckShapeless._

  implicit val arbitraryBS = Arbitrary(
    implicitly[Arbitrary[Array[Byte]]].arbitrary
      .map(t => ByteString.copyFrom(t))
  )

  // Default scalacheck-shapeless would chose Unrecognized instances with recognized values.
  private def fixEnum[A <: GeneratedEnum](
      e: A
  )(implicit cmp: GeneratedEnumCompanion[A]): A = {
    if (e.isUnrecognized) cmp.values.find(_.value == e.value).getOrElse(e)
    else e
  }

  def arbitraryEnum[A <: GeneratedEnum: Arbitrary: GeneratedEnumCompanion] = {
    Arbitrary(implicitly[Arbitrary[A]].arbitrary.map(fixEnum(_)))
  }

  implicit val arbitraryUnknownFields = Arbitrary(
    Gen.const(UnknownFieldSet.empty)
  )

  implicit val nestedEnum2 = arbitraryEnum[AT2.EnumTest.NestedEnum]

  implicit val nestedEnum3 = arbitraryEnum[AT3.EnumTest.NestedEnum]

  implicit val topLevelEnum2 = arbitraryEnum[AT2.TopLevelEnum]

  implicit val topLevelEnum3 = arbitraryEnum[AT3.TopLevelEnum]

  implicit def arbitraryMessage[A <: GeneratedMessage](implicit
      ev: Strict[MkArbitrary[A]]
  ) = {
    implicitly[Arbitrary[A]]
  }
} 
Example 126
Source File: EpisodeCheckInstances.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.api.matching

import canoe.TestIO._
import cats.Eq
import cats.effect.IO
import cats.syntax.applicativeError._
import fs2.Stream
import org.scalacheck.{Arbitrary, Gen}

object EpisodeCheckInstances {

  implicit def eqEpisode[I: Arbitrary, O]: Eq[Episode[IO, I, O]] = {

    val inputGen =
      Gen.listOf(
        Gen.frequency(
          1 -> Arbitrary.arbException.arbitrary.map(Left(_)),
          10 -> Arbitrary.arbitrary[I].map(Right(_))
        )
      )

    val input = Stream.emits(inputGen.sample.get).evalMap {
      case Right(i) => IO.pure(i)
      case Left(e)  => IO.raiseError(e)
    }

    def result(ep: Episode[IO, I, O]): List[Either[Throwable, O]] =
      input.through(ep.attempt.matching).toList()

    (x: Episode[IO, I, O], y: Episode[IO, I, O]) =>
      result(x) == result(y)
  }

  implicit val eqThrowable: Eq[Throwable] = Eq.fromUniversalEquals[Throwable]

  implicit def arbEpisode[F[_], I, O: Arbitrary]: Arbitrary[Episode[F, I, O]] =
    Arbitrary(
      Gen.oneOf(
        Arbitrary.arbitrary[O].map(o => Episode.Pure[F, O](o)),
        for {
          b <- Arbitrary.arbBool.arbitrary
          o <- Arbitrary.arbitrary[O]
        } yield Episode.Next[F, I](_ => b).map(_ => o)
      )
    )

} 
Example 127
Source File: ScenarioCheckInstances.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.api

import canoe.TestIO._
import canoe.models.PrivateChat
import canoe.models.messages.{TelegramMessage, TextMessage}
import cats.Eq
import cats.effect.IO
import fs2.Stream
import org.scalacheck.{Arbitrary, Gen}

object ScenarioCheckInstances {
  // Basically the same instances as in EpisodeCheckInstances

  private def message(s: String): TextMessage =
    TextMessage(-1, PrivateChat(-1, None, None, None), -1, s)

  implicit def arbMessage: Arbitrary[TelegramMessage] =
    Arbitrary(Arbitrary.arbString.arbitrary.map(message))

  implicit def eqScenario[A]: Eq[Scenario[IO, A]] = {

    val inputGen =
      Gen.listOf(
        Gen.frequency(
          1 -> Arbitrary.arbException.arbitrary.map(Left(_)),
          10 -> Arbitrary.arbitrary[TelegramMessage].map(Right(_))
        )
      )

    val input = Stream.emits(inputGen.sample.get).evalMap {
      case Right(i) => IO.pure(i)
      case Left(e)  => IO.raiseError(e)
    }

    def result(sc: Scenario[IO, A]): List[Either[Throwable, A]] =
      input.through(sc.attempt.pipe).toList()

    (x: Scenario[IO, A], y: Scenario[IO, A]) =>
      result(x) == result(y)
  }

  implicit val eqThrowable: Eq[Throwable] = Eq.fromUniversalEquals[Throwable]

  implicit def arbScenario[F[_], A: Arbitrary]: Arbitrary[Scenario[F, A]] =
    Arbitrary(
      Gen.oneOf(
        Arbitrary.arbitrary[A].map(a => Scenario.pure[F](a)),
        for {
          b <- Arbitrary.arbBool.arbitrary
          a <- Arbitrary.arbitrary[A]
        } yield Scenario.expect[F, A] { case _ if b => a }
      )
    )

} 
Example 128
Source File: Assesments.scala    From Learn-Scala-Programming   with MIT License 5 votes vote down vote up
import org.scalacheck.{Arbitrary, Gen, Prop}
import org.scalacheck.Prop.forAll

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

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

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

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

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

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


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

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

  val mapGen = Gen.mapOf(pairGen)
} 
Example 129
Source File: LawChecking.scala    From curryhoward   with Apache License 2.0 5 votes vote down vote up
package io.chymyst.ch.unit

import io.chymyst.ch.implement
import org.scalacheck.Arbitrary
import org.scalatest.{Assertion, FlatSpec, Matchers}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

trait FMap[F[_]] {
  def f[A, B]: (A ⇒ B) ⇒ F[A] ⇒ F[B]
}

trait FPoint[F[_]] {
  def f[A]: A ⇒ F[A]
}

trait FFlatMap[F[_]] {
  def f[A, B]: (A ⇒ F[B]) ⇒ F[A] ⇒ F[B]
}

trait LawChecking extends FlatSpec with Matchers with GeneratorDrivenPropertyChecks {

  def fEqual[A: Arbitrary, B](f1: A ⇒ B, f2: A ⇒ B): Assertion = {
    forAll { (x: A) ⇒ f1(x) shouldEqual f2(x) }
  }

  private def checkFunctionEquality[A: Arbitrary, B](f1: A ⇒ B, f2: A ⇒ B)(implicit resultsEqual: (B, B) ⇒ Assertion): Assertion = {
    forAll { (x: A) ⇒ resultsEqual(f1(x), f2(x)) }
  }

  // Check equality for higher-order functions of type A ⇒ B ⇒ C.
  def hofEqual[A: Arbitrary, B: Arbitrary, C: Arbitrary](f1: A ⇒ B ⇒ C, f2: A ⇒ B ⇒ C): Assertion =
    checkFunctionEquality[A, B ⇒ C](f1, f2)(implicitly[Arbitrary[A]], (x: B ⇒ C, y: B ⇒ C) ⇒ fEqual(x, y))


  def fmapLawIdentity[A: Arbitrary, F[_]](fmap: FMap[F])(implicit fResultsEqual: (F[A], F[A]) ⇒ Assertion, ev: Arbitrary[F[A]]): Assertion = {
    checkFunctionEquality[F[A], F[A]](fmap.f(identity[A]), identity[F[A]])
  }

  def fmapLawComposition[A: Arbitrary, B: Arbitrary, C: Arbitrary, F[_]](fmap: FMap[F])(implicit fResultsEqual: (F[C], F[C]) ⇒ Assertion, evA: Arbitrary[F[A]], evAB: Arbitrary[A ⇒ B], evBC: Arbitrary[B ⇒ C]): Assertion = {
    forAll { (f: A ⇒ B, g: B ⇒ C) ⇒
      checkFunctionEquality[F[A], F[C]](fmap.f(f) andThen fmap.f(g), fmap.f(f andThen g))
    }
  }

  def fmapPointLaw[A: Arbitrary, B: Arbitrary, F[_]](point: FPoint[F], fmap: FMap[F])(implicit fResultsEqual: (F[B], F[B]) ⇒ Assertion, evAB: Arbitrary[A ⇒ B]): Assertion = forAll { (f: A ⇒ B) ⇒
    val point_dot_map = point.f andThen fmap.f(f)
    val f_dot_point = f andThen point.f
    checkFunctionEquality[A, F[B]](point_dot_map, f_dot_point)
  }

  def flatmapPointLaw[A: Arbitrary, B: Arbitrary, F[_]](point: FPoint[F], flatmap: FFlatMap[F])(implicit fResultsEqual: (F[B], F[B]) ⇒ Assertion, evAB: Arbitrary[A ⇒ F[B]], evFB: Arbitrary[F[B]]): Assertion = forAll { (f: A ⇒ F[B]) ⇒
    checkFunctionEquality[F[B], F[B]](flatmap.f(point.f), identity)
    checkFunctionEquality(point.f andThen flatmap.f(f), f)
  }

  def flatmapAssocLaw[A: Arbitrary, B: Arbitrary, C: Arbitrary, F[_]](fflatMap: FFlatMap[F])(implicit fResultsEqual: (F[C], F[C]) ⇒ Assertion, evFA: Arbitrary[F[A]], evAB: Arbitrary[A ⇒ F[B]], evBC: Arbitrary[B ⇒ F[C]]): Assertion = forAll { (f: A ⇒ F[B], g: B ⇒ F[C]) ⇒
    val x = fflatMap.f(f) andThen fflatMap.f(g)
    val y = fflatMap.f((x: A) ⇒ fflatMap.f(g)(f(x)))
    checkFunctionEquality[F[A], F[C]](x, y)
  }

  def flip[A, B, C]: (A ⇒ B ⇒ C) ⇒ (B ⇒ A ⇒ C) = implement
} 
Example 130
Source File: P23Check.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

    Await.result(fServer.close())
  }
} 
Example 138
Source File: ScodecIntegrationTest.scala    From finagle-serial   with Apache License 2.0 5 votes vote down vote up
package io.github.finagle.serial.scodec

import _root_.scodec._
import _root_.scodec.codecs._
import com.twitter.util.Await
import io.github.finagle.serial.{ApplicationError, CodecError}
import io.github.finagle.serial.tests.SerialIntegrationTest
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.FunSuite

class ScodecIntegrationTest extends FunSuite with ScodecSerial with SerialIntegrationTest {
  implicit val intCodec: Codec[Int] = int32
  implicit val stringCodec: Codec[String] = variableSizeBits(uint24, utf8)

  case class Foo(i: Int, s: String)

  implicit val fooCodec: Codec[Foo] = (uint8 :: stringCodec).as[Foo]

  implicit val fooArbitrary: Arbitrary[Foo] = Arbitrary(
    for {
      i <- Gen.choose(0, 255)
      s <- Gen.alphaStr
    } yield Foo(i, s)
  )

  test("A service that doubles an integer should work on all integers") {
    testFunctionService[Int, Int](_ * 2)
  }

  test("A service that returns the length of a string should work on all strings") {
    testFunctionService[String, Int](s => s.length)
  }

  test("A service that changes a case class should work on all instances") {
    testFunctionService[Foo, Foo] {
      case Foo(i, s) => Foo(i % 128, s * 2)
    }
  }

  test("A service should correctly throw encoding errors on the client side") {
    val (server, client) = createServerAndClient[Foo, Int](_.i)

    an[CodecError] should be thrownBy Await.result(client(Foo(Int.MaxValue, "foo")))

    server.close()
  }

  test("A service should correctly throw encoding errors on the server side") {
    val (server, client) = createServerAndClient[Foo, Foo] {
      case Foo(i, s) => Foo(Int.MaxValue, s)
    }

    an[CodecError] should be thrownBy Await.result(client(Foo(1, "foo")))

    server.close()
  }

  test("A service should correctly throw handled application errors") {
    val (server, client) = createServerAndClient[String, Int](_.toInt)

    an[NumberFormatException] should be thrownBy Await.result(client("not an integer"))

    server.close()
  }

  case class UnknownError(message: String) extends Throwable

  test("A service should correctly wrap unhandled application errors") {
    val (server, client) = createServerAndClient[String, Int] { s =>
      throw UnknownError("something happened")
    }

    an[ApplicationError] should be thrownBy Await.result(client("not an integer"))

    server.close()
  }
} 
Example 139
Source File: RerunnableSuite.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util

import cats.instances.either._
import cats.instances.int._
import cats.instances.tuple._
import cats.instances.unit._
import cats.kernel.laws.discipline.MonoidTests
import cats.laws.discipline._
import cats.laws.discipline.arbitrary._
import cats.{ Comonad, Eq }
import com.twitter.conversions.DurationOps._
import org.scalacheck.Arbitrary

class RerunnableSuite extends CatbirdSuite with ArbitraryInstances with EqInstances {
  implicit def rerunnableEq[A](implicit A: Eq[A]): Eq[Rerunnable[A]] =
    Rerunnable.rerunnableEqWithFailure[A](1.second)
  implicit val rerunnableComonad: Comonad[Rerunnable] =
    Rerunnable.rerunnableComonad(1.second)
  implicit val rerunnableParEqInt: Eq[Rerunnable.Par[Int]] =
    Rerunnable.rerunnableParEqWithFailure(1.second)
  implicit val rerunnableParEqInt3: Eq[Rerunnable.Par[(Int, Int, Int)]] =
    Rerunnable.rerunnableParEqWithFailure(1.second)
  implicit def rerunnableParArbitrary[A](implicit A: Arbitrary[A]): Arbitrary[Rerunnable.Par[A]] =
    Arbitrary(A.arbitrary.map(value => Rerunnable.Par(Rerunnable.const(value))))

  checkAll("Rerunnable[Int]", MonadErrorTests[Rerunnable, Throwable].monadError[Int, Int, Int])
  checkAll("Rerunnable[Int]", ComonadTests[Rerunnable].comonad[Int, Int, Int])
  checkAll("Rerunnable[Int]", FunctorTests[Rerunnable](rerunnableComonad).functor[Int, Int, Int])
  checkAll("Rerunnable[Int]", MonoidTests[Rerunnable[Int]].monoid)
  checkAll("Rerunnable[Int]", ParallelTests[Rerunnable, Rerunnable.Par].parallel[Int, Int])
  checkAll("Rerunnable.Par[Int]", CommutativeApplicativeTests[Rerunnable.Par].commutativeApplicative[Int, Int, Int])
} 
Example 140
Source File: arbitrary.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util

import com.twitter.concurrent.AsyncStream
import com.twitter.conversions.DurationOps._
import com.twitter.util.{ Future, Return, Try, Var }
import org.scalacheck.{ Arbitrary, Cogen }

trait ArbitraryInstances {
  implicit def futureArbitrary[A](implicit A: Arbitrary[A]): Arbitrary[Future[A]] =
    Arbitrary(A.arbitrary.map(Future.value))

  implicit def tryArbitrary[A](implicit A: Arbitrary[A]): Arbitrary[Try[A]] =
    Arbitrary(A.arbitrary.map(Return(_)))

  implicit def varArbitrary[A](implicit A: Arbitrary[A]): Arbitrary[Var[A]] =
    Arbitrary(A.arbitrary.map(Var.value))

  implicit def asyncStreamArbitrary[A](implicit A: Arbitrary[A]): Arbitrary[AsyncStream[A]] =
    Arbitrary(A.arbitrary.map(AsyncStream.of))

  implicit def rerunnableArbitrary[A](implicit A: Arbitrary[A]): Arbitrary[Rerunnable[A]] =
    Arbitrary(futureArbitrary[A].arbitrary.map(Rerunnable.fromFuture[A](_)))

  implicit def cogenFuture[A](implicit A: Cogen[A]): Cogen[Future[A]] =
    A.contramap(futureComonad(1.second).extract)

  implicit def cogenVar[A](implicit A: Cogen[A]): Cogen[Var[A]] =
    A.contramap(varComonad.extract)

  implicit def cogenRerunnable[A](implicit A: Cogen[A]): Cogen[Rerunnable[A]] =
    A.contramap(Rerunnable.rerunnableComonad(1.second).extract)
} 
Example 141
Source File: future.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util

import cats.instances.either._
import cats.instances.int._
import cats.instances.tuple._
import cats.instances.unit._
import cats.kernel.laws.discipline.{ MonoidTests, SemigroupTests }
import cats.laws.discipline._
import cats.laws.discipline.arbitrary._
import cats.{ Comonad, Eq }
import com.twitter.conversions.DurationOps._
import com.twitter.util.Future
import org.scalacheck.Arbitrary

class FutureSuite extends CatbirdSuite with FutureInstances with ArbitraryInstances with EqInstances {
  implicit val eqFutureInt: Eq[Future[Int]] = futureEqWithFailure(1.second)
  implicit val eqFutureFutureInt: Eq[Future[Future[Int]]] = futureEqWithFailure(1.second)
  implicit val eqFutureFutureFutureInt: Eq[Future[Future[Future[Int]]]] = futureEqWithFailure(1.second)
  implicit val eqFutureInt3: Eq[Future[(Int, Int, Int)]] = futureEqWithFailure(1.second)
  implicit val eqFutureEitherUnit: Eq[Future[Either[Throwable, Unit]]] = futureEqWithFailure(1.second)
  implicit val eqFutureEitherInt: Eq[Future[Either[Throwable, Int]]] = futureEqWithFailure(1.second)
  implicit val comonad: Comonad[Future] = futureComonad(1.second)
  implicit val eqFutureParInt: Eq[FuturePar[Int]] = futureParEqWithFailure(1.second)
  implicit val eqFutureParInt3: Eq[FuturePar[(Int, Int, Int)]] = futureParEqWithFailure(1.second)
  implicit def arbFuturePar[A](implicit A: Arbitrary[A]): Arbitrary[FuturePar[A]] =
    Arbitrary(A.arbitrary.map(value => FuturePar(Future.value(value))))

  checkAll("Future[Int]", MonadErrorTests[Future, Throwable].monadError[Int, Int, Int])
  checkAll("Future[Int]", ComonadTests[Future].comonad[Int, Int, Int])
  checkAll("Future[Int]", FunctorTests[Future](comonad).functor[Int, Int, Int])
  checkAll("Future[Int]", SemigroupTests[Future[Int]](twitterFutureSemigroup[Int]).semigroup)
  checkAll("Future[Int]", MonoidTests[Future[Int]].monoid)
  checkAll("Future[Int]", ParallelTests[Future, FuturePar].parallel[Int, Int])
  checkAll("FuturePar[Int]", CommutativeApplicativeTests[FuturePar].commutativeApplicative[Int, Int, Int])
} 
Example 142
Source File: TraceGenerators.scala    From money   with Apache License 2.0 5 votes vote down vote up
package com.comcast.money.core

import java.time.Instant
import java.util.UUID

import org.scalacheck.{ Arbitrary, Gen }

import scala.concurrent.duration._
import scala.language.higherKinds
import Arbitrary.arbitrary
import com.comcast.money.api.{ Note, Span, SpanId }
import org.scalacheck.Gen.{ alphaLowerChar, alphaUpperChar, choose, frequency }

trait TraceGenerators {

  def genOption[A](g: Gen[A]): Gen[Option[A]] = Gen.oneOf(Gen.const(Option.empty[A]), g map Option.apply)

  def genUUID: Gen[UUID] = for {
    hi <- arbitrary[Long]
    lo <- arbitrary[Long]
  } yield new UUID(hi, lo)

  def genStr: Gen[String] = Gen.listOf(Gen.alphaNumChar) map {
    _.mkString
  }

  def genHexStrFromLong: Gen[String] = for {
    l <- arbitrary[Long]
  } yield l.toHexString

  def genTraceSystemMetadataPair: Gen[(String, String)] = for {
    name <- genStr
    value <- genStr
  } yield name -> value

  def genTraceSystemMetadata: Gen[Map[String, String]] = Gen.nonEmptyMap(genTraceSystemMetadataPair)

  def genSpanId: Gen[SpanId] = for {
    traceId <- genUUID
    parentId <- arbitrary[Long]
    childId <- arbitrary[Long]
  } yield new SpanId(traceId.toString, parentId, childId)

} 
Example 143
Source File: EmrConfigurationSpec.scala    From hyperion   with Apache License 2.0 5 votes vote down vote up
package com.krux.hyperion.resource

import com.krux.hyperion.adt.HType
import com.krux.hyperion.aws.AdpEmrConfiguration
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary._
import org.scalacheck.Gen._
import org.scalatest.Inside._
import org.scalatest.prop.PropertyChecks._
import org.scalatest.{FlatSpec, Matchers}

class EmrConfigurationSpec extends FlatSpec with Matchers {

  it should "not emit empty lists" in {
    implicit lazy val genEmrConfig = Arbitrary(EmrConfiguration("hadoop-env"))

    implicit lazy val genProperty = Arbitrary(for {key <- alphaStr; value <- alphaStr}
      yield Property(HType.string2HString(key), HType.string2HString(value)))

    forAll { (config: List[EmrConfiguration], props: List[Property], classification: String) =>
      val emrConfig = EmrConfiguration(classification)
        .withConfiguration(config: _*)
        .withProperty(props: _*)

      val ser = emrConfig.serialize

      inside(ser) { case AdpEmrConfiguration(_, _, _, prop, conf) =>
        conf shouldNot be(Some(Seq()))
        prop shouldNot be(Some(Seq()))
      }
    }
  }
} 
Example 144
Source File: CodecSpec.scala    From hammock   with MIT License 5 votes vote down vote up
package hammock

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

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

import scala.util._

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

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

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

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

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

object CodecTests {

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

}

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

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

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

  test("syntax should exist for types for which a Codec exist") {
    1.encode shouldEqual Entity.StringEntity("1")
  }
} 
Example 145
Source File: DeltaByteArrayEncoderSuite.scala    From OAP   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.execution.datasources.oap.io

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

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

class DeltaByteArrayEncoderCheck extends Properties("DeltaByteArrayEncoder") {

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

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

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

class DeltaByteArrayEncoderSuite extends SparkFunSuite with Checkers {

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

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

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

class CodecFactoryCheck extends Properties("CodecFactory") {

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

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

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

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

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

class CodecFactorySuite extends SparkFunSuite with Checkers {

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

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

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

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

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

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

class DictionaryBasedEncoderSuite extends SparkFunSuite with Checkers {

  test("Check Encoding/Decoding") {
    check(PropertiesAdapter.getProp(new DictionaryBasedEncoderCheck()))
  }
} 
Example 148
Source File: TermTests.scala    From liberator   with MIT License 5 votes vote down vote up
package io.aecor.liberator.tests

import cats.kernel.laws.discipline.GroupTests
import cats.laws.discipline.{ MonadTests, SerializableTests }
import cats.tests.CatsSuite
import cats.{ Eq, Id, Monad }
import io.aecor.liberator.Term
import org.scalacheck.{ Arbitrary, Cogen, Gen }

class TermTests extends CatsSuite with TermInstances {
  trait M[F[_]]
  implicit def mf: M[Id] = new M[Id] {}
  checkAll("Term[M, Int]", GroupTests[Term[M, Int]].group)
  checkAll("Term[M, ?]", MonadTests[Term[M, ?]].monad[Int, Int, Int])
  checkAll("Monad[Term[M, ?]]", SerializableTests.serializable(Monad[Term[M, ?]]))
}

sealed trait TermInstances {
  private def termGen[M[_[_]], A](maxDepth: Int)(implicit A: Arbitrary[A]): Gen[Term[M, A]] = {
    val noFlatMapped =
      Gen.oneOf(A.arbitrary.map(Term.pure[M, A]), A.arbitrary.map(Term.pure[M, A]))

    val nextDepth = Gen.chooseNum(1, math.max(1, maxDepth - 1))

    def withFlatMapped =
      for {
        fDepth <- nextDepth
        freeDepth <- nextDepth
        f <- Arbitrary
              .arbFunction1[A, Term[M, A]](
                Arbitrary(termGen[M, A](fDepth)),
                Cogen[Unit].contramap(_ => ())
              )
              .arbitrary
        freeFA <- termGen[M, A](freeDepth)
      } yield freeFA.flatMap(f)

    if (maxDepth <= 1) noFlatMapped
    else Gen.oneOf(noFlatMapped, withFlatMapped)
  }

  implicit def termArbitrary[M[_[_]], A](implicit A: Arbitrary[A]): Arbitrary[Term[M, A]] =
    Arbitrary(termGen[M, A](4))

  implicit def termEq[M[_[_]], A, F[_]](implicit mf: M[F],
                                        eqA: Eq[F[A]],
                                        F: Monad[F]): Eq[Term[M, A]] =
    new Eq[Term[M, A]] {
      override def eqv(x: Term[M, A], y: Term[M, A]): Boolean =
        eqA.eqv(x(mf), y(mf))
    }
} 
Example 149
Source File: AccountMergeOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers, KeyPair}

class AccountMergeOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[AccountMergeOperation]] = Arbitrary(genTransacted(genAccountMergeOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "account merge operation" should {
    "serde via xdr string" >> prop { actual: AccountMergeOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: AccountMergeOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[AccountMergeOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account":"${op.operation.sourceAccount.get.accountId}",
           |  "type_i": 8,
           |  "type": "account_merge"
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "account": "${op.operation.sourceAccount.get.accountId}",
           |  "into": "${KeyPair.fromPublicKey(op.operation.destination.hash).accountId}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[AccountMergeOperation]] mustEqual op
    }.setGen(genTransacted(genAccountMergeOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 150
Source File: SetOptionsOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class SetOptionsOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[SetOptionsOperation]] = Arbitrary(genTransacted(genSetOptionsOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "set options operation" should {
    "serde via xdr string" >> prop { actual: SetOptionsOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: SetOptionsOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded must beEquivalentTo(actual)
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[SetOptionsOperation] =>
      val doc =
        s"""
           |{
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659137"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659137"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${opt("inflation_dest", op.operation.inflationDestination.map(_.accountId))}
           |  ${opt("home_domain", op.operation.homeDomain)}
           |  ${opt("master_key_weight", op.operation.masterKeyWeight)}
           |  ${opt("signer_key", op.operation.signer.map(_.key.encodeToChars.mkString))}
           |  ${opt("signer_weight", op.operation.signer.map(_.weight))}
           |  ${opt("set_flags", op.operation.setFlags.map(_.map(_.i)))}
           |  ${opt("set_flags_s", op.operation.setFlags.map(_.map(_.s)))}
           |  ${opt("clear_flags", op.operation.clearFlags.map(_.map(_.i)))}
           |  ${opt("clear_flags_s", op.operation.clearFlags.map(_.map(_.s)))}
           |  ${opt("low_threshold", op.operation.lowThreshold)}
           |  ${opt("med_threshold", op.operation.mediumThreshold)}
           |  ${opt("high_threshold", op.operation.highThreshold)}
           |  "type": "set_options",
           |  "type_i": 5,
           |}
         """.stripMargin

      parse(doc).extract[Transacted[SetOptionsOperation]] must beEquivalentTo(op)
    }.setGen(genTransacted(genSetOptionsOperation.suchThat(_.sourceAccount.nonEmpty)))
  }
} 
Example 151
Source File: PathPaymentStrictReceiveOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class PathPaymentStrictReceiveOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[PathPaymentStrictReceiveOperation]] = Arbitrary(genTransacted(genPathPaymentStrictReceiveOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "path payment operation" should {
    "serde via xdr string" >> prop { actual: PathPaymentStrictReceiveOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: PathPaymentStrictReceiveOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[PathPaymentStrictReceiveOperation] =>
      val doc =
        s"""
           |{
           |  "_links":{
           |    "self":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713"},
           |    "transaction":{"href":"https://horizon-testnet.stellar.org/transactions/a995af17837d1b53fb5782269250a36e9dbe74170260b46f2708e5f23f7c864a"},
           |    "effects":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713/effects"},
           |    "succeeds":{"href":"https://horizon-testnet.stellar.org/effects?order=desc&cursor=940258535411713"},
           |    "precedes":{"href":"https://horizon-testnet.stellar.org/effects?order=asc&cursor=940258535411713"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type":"path_payment",
           |  "type_i":2,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.destinationAmount)}
           |  ${amountDocPortion(op.operation.sendMax, "source_max", "source_")}
           |  "from":"${op.operation.sourceAccount.get.accountId}",
           |  "to":"${op.operation.destinationAccount.publicKey.accountId}",
           |  "path":[${if (op.operation.path.isEmpty) "" else op.operation.path.map(asset(_)).mkString("{", "},{", "}")}]
           |}
         """.stripMargin

      parse(doc).extract[Transacted[Operation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genPathPaymentStrictReceiveOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[PathPaymentStrictReceiveOperation]): Transacted[PathPaymentStrictReceiveOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 152
Source File: CreateAccountOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class CreateAccountOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[CreateAccountOperation]] = Arbitrary(genTransacted(genCreateAccountOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer + OperationDeserializer

  "create account operation" should {
    "serde via xdr string" >> prop { actual: CreateAccountOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: CreateAccountOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "be parsed from json " >> prop { op: Transacted[CreateAccountOperation] =>
      val doc =
        s"""
           |{
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659137"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659137"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "create_account",
           |  "type_i": 0,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "starting_balance": "${amountString(op.operation.startingBalance)}",
           |  "funder": "${op.operation.sourceAccount.get.accountId}",
           |  "account": "${op.operation.destinationAccount.publicKey.accountId}"
           |}
         """.stripMargin

      parse(doc).extract[Transacted[CreateAccountOperation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genCreateAccountOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[CreateAccountOperation]): Transacted[CreateAccountOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 153
Source File: InflationOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class InflationOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[InflationOperation]] = Arbitrary(genTransacted(genInflationOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "the inflation operation" should {
    "serde via xdr string" >> prop { actual: InflationOperation =>
      Operation.decodeXDR(base64(actual.encode)) mustEqual actual
    }

    "serde via xdr bytes" >> prop { actual: InflationOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[InflationOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "inflation",
           |  "type_i": 9,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[InflationOperation]] mustEqual op
    }.setGen(genTransacted(genInflationOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 154
Source File: BumpSequenceOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class BumpSequenceOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[BumpSequenceOperation]] = Arbitrary(genTransacted(genBumpSequenceOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "bump sequence operation" should {
    "serde via xdr bytes" >> prop { actual: BumpSequenceOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "serde via xdr string" >> prop { actual: BumpSequenceOperation =>
      Operation.decodeXDR(ByteArrays.base64(actual.encode)) mustEqual actual
    }

    "parse from json" >> prop { op: Transacted[BumpSequenceOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "bump_sequence",
           |  "type_i": 11,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "bump_to": ${op.operation.bumpTo}
           |}
         """.stripMargin

      parse(doc).extract[Transacted[BumpSequenceOperation]] mustEqual op
    }.setGen(genTransacted(genBumpSequenceOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 155
Source File: CreatePassiveSellOfferOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class CreatePassiveSellOfferOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[CreatePassiveSellOfferOperation]] = Arbitrary(genTransacted(genCreatePassiveSellOfferOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer + OperationDeserializer

  "create passive offer operation" should {
    "serde via xdr string" >> prop { actual: CreatePassiveSellOfferOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: CreatePassiveSellOfferOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[CreatePassiveSellOfferOperation] =>
      val doc =
        s"""
           |{
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659137"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659137"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "create_passive_sell_offer",
           |  "type_i": 4,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.selling, assetPrefix = "selling_")},
           |  ${asset(op.operation.buying, "buying_")},
           |  "offer_id": 0,
           |  "price": "1.0",
           |  "price_r": {
           |    "d": ${op.operation.price.d},
           |    "n": ${op.operation.price.n}
           |  }
           |}
         """.stripMargin

      parse(doc).extract[Transacted[CreatePassiveSellOfferOperation]] mustEqual op
    }.setGen(genTransacted(genCreatePassiveSellOfferOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 156
Source File: PathPaymentStrictSendOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class PathPaymentStrictSendOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[PathPaymentStrictSendOperation]] = Arbitrary(genTransacted(genPathPaymentStrictSendOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "path payment operation" should {
    "serde via xdr string" >> prop { actual: PathPaymentStrictSendOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: PathPaymentStrictSendOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[PathPaymentStrictSendOperation] =>
      val doc =
        s"""
           |{
           |  "_links":{
           |    "self":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713"},
           |    "transaction":{"href":"https://horizon-testnet.stellar.org/transactions/a995af17837d1b53fb5782269250a36e9dbe74170260b46f2708e5f23f7c864a"},
           |    "effects":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713/effects"},
           |    "succeeds":{"href":"https://horizon-testnet.stellar.org/effects?order=desc&cursor=940258535411713"},
           |    "precedes":{"href":"https://horizon-testnet.stellar.org/effects?order=asc&cursor=940258535411713"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type":"path_payment_strict_send",
           |  "type_i":13,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.sendAmount, assetPrefix = "source_")}
           |  ${amountDocPortion(op.operation.destinationMin, "destination_min")}
           |  "from":"${op.operation.sourceAccount.get.accountId}",
           |  "to":"${op.operation.destinationAccount.publicKey.accountId}",
           |  "path":[${if (op.operation.path.isEmpty) "" else op.operation.path.map(asset(_)).mkString("{", "},{", "}")}]
           |}
         """.stripMargin

      parse(doc).extract[Transacted[Operation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genPathPaymentStrictSendOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[PathPaymentStrictSendOperation]): Transacted[PathPaymentStrictSendOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 157
Source File: AllowTrustOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers, KeyPair}

class AllowTrustOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[AllowTrustOperation]] = Arbitrary(genTransacted(genAllowTrustOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "allow trust operation" should {
    "serde via xdr string" >> prop { actual: AllowTrustOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: AllowTrustOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[AllowTrustOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "allow_trust",
           |  "type_i": 7,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "asset_type": "${if (op.operation.assetCode.length <= 4) "credit_alphanum4" else "credit_alphanum12"}",
           |  "asset_code": "${op.operation.assetCode}",
           |  "asset_issuer": "${op.operation.sourceAccount.get.accountId}"
           |  "trustor": "${op.operation.trustor.accountId}",
           |  "trustee": "${op.operation.sourceAccount.get.accountId}",
           |  "authorize": ${op.operation.trustLineFlags.contains(TrustLineAuthorized)}
           |  "authorize_to_maintain_liabilities": ${op.operation.trustLineFlags.contains(TrustLineCanMaintainLiabilities)}
           |}
         """.stripMargin

      val parsed = parse(doc).extract[Transacted[AllowTrustOperation]]
      parsed mustEqual op
      parsed.operation.authorize mustEqual op.operation.authorize
      parsed.operation.authorizeToMaintainLiabilities mustEqual op.operation.authorizeToMaintainLiabilities
    }.setGen(genTransacted(genAllowTrustOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 158
Source File: ChangeTrustOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class ChangeTrustOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[ChangeTrustOperation]] = Arbitrary(genTransacted(genChangeTrustOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "change trust operation" should {
    "serde via xdr string" >> prop { actual: ChangeTrustOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: ChangeTrustOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[ChangeTrustOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "change_trust",
           |  "type_i": 6,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.limit, "limit")},
           |  "trustee": "${op.operation.limit.asset.issuer.accountId}",
           |  "trustor": "${op.operation.sourceAccount.get.accountId}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[ChangeTrustOperation]] mustEqual op
    }.setGen(genTransacted(genChangeTrustOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 159
Source File: ManageDataOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.apache.commons.codec.binary.Base64
import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers, PublicKey}

class ManageDataOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arbDelete: Arbitrary[Transacted[DeleteDataOperation]] = Arbitrary(genTransacted(genDeleteDataOperation))
  implicit val arbWrite: Arbitrary[Transacted[WriteDataOperation]] = Arbitrary(genTransacted(genWriteDataOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  def doc[O <: ManageDataOperation](op: Transacted[O]) = {
    val dataValue = op.operation match {
      case WriteDataOperation(_, value, _) => Base64.encodeBase64String(value.toArray)
      case _ => ""
    }

    s"""
      |{
      |  "_links": {
      |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
      |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
      |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
      |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
      |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
      |  },
      |  "id": "${op.id}",
      |  "paging_token": "10157597659137",
      |  "source_account": "${op.operation.sourceAccount.get.accountId}",
      |  "type": "manage_data",
      |  "type_i": 1,
      |  "created_at": "${formatter.format(op.createdAt)}",
      |  "transaction_hash": "${op.txnHash}",
      |  "name": "${op.operation.name}",
      |  "value": "$dataValue"
      |}""".stripMargin
  }

  "a write data operation" should {
    "serde via xdr string" >> prop { actual: WriteDataOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: WriteDataOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded must beEquivalentTo(actual)
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[WriteDataOperation] =>
      parse(doc(op)).extract[Transacted[ManageDataOperation]] must beEquivalentTo(op)
    }.setGen(genTransacted(genWriteDataOperation.suchThat(_.sourceAccount.nonEmpty)))

    "encode a string payload as UTF-8 in base64" >> prop { (s: String, source: PublicKey) =>
      val value = new String(s.take(64).getBytes("UTF-8").take(60), "UTF-8")
      WriteDataOperation("name", value).value.toSeq mustEqual value.getBytes("UTF-8").toSeq
      WriteDataOperation("name", value, None).value.toSeq mustEqual value.getBytes("UTF-8").toSeq
      WriteDataOperation("name", value, Some(source)).value.toSeq mustEqual value.getBytes("UTF-8").toSeq
    }.setGen1(Arbitrary.arbString.arbitrary.suchThat(_.nonEmpty))

    "fail if the key is greater than 64 bytes" >> prop { s: String =>
      WriteDataOperation(s, "value") must throwAn[IllegalArgumentException]
    }.setGen(Gen.identifier.suchThat(_.getBytes("UTF-8").length > 64))

    "fail if the value is greater than 64 bytes" >> prop { s: String =>
      WriteDataOperation("name", s) must throwAn[IllegalArgumentException]
    }.setGen(Gen.identifier.suchThat(_.getBytes("UTF-8").length > 64))
  }

  "a delete data operation" should {
    "serde via xdr string" >> prop { actual: DeleteDataOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: DeleteDataOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[DeleteDataOperation] =>
      parse(doc(op)).extract[Transacted[ManageDataOperation]] mustEqual op
    }.setGen(genTransacted(genDeleteDataOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 160
Source File: PaymentOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class PaymentOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[PaymentOperation]] = Arbitrary(genTransacted(genPaymentOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "payment operation" should {
    "serde via xdr string" >> prop { actual: PaymentOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: PaymentOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[PaymentOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "payment",
           |  "type_i": 1,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.amount)},
           |  "from": "${op.operation.sourceAccount.get.accountId}",
           |  "to": "${op.operation.destinationAccount.publicKey.accountId}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[PaymentOperation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genPaymentOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[PaymentOperation]): Transacted[PaymentOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 161
Source File: TransactionResultSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.result

import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.model.ledger.OfferEntry
import stellar.sdk.model.{Amount, Asset, NativeAmount, Price}
import stellar.sdk.model.result.TransactionResult._
import stellar.sdk.{ArbitraryInput, DomainMatchers, KeyPair}

import scala.util.Try

class TransactionResultSpec extends Specification with ArbitraryInput with DomainMatchers {

  "a transaction result" should {
    "serde via xdr bytes" >> prop { r: TransactionResult =>
      r must serdeUsing(TransactionResult.decode)
    }
  }

  "a transaction result code" should {
    "not be constructed with an invalid id" >> {
      Code(-12) must throwA[RuntimeException]
    }
  }

  "An XDR transaction success" should {
    "be decodable" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGQAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAB////+wAAAAA=") mustEqual
        TransactionSuccess(NativeAmount(100), Seq(CreateAccountSuccess, PaymentNoDestination))
    }
  }

  "a transaction success" should {
    "always mark sequenceUpdates as true" >> prop { t: TransactionSuccess =>
      t.sequenceUpdated must beTrue
    }
  }

  "An XDR transaction failure" should {
    "be decodable for failure due to bad operation" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT/////AAAAAQAAAAAAAAAB/////AAAAAA=") mustEqual
        TransactionFailure(NativeAmount(100), Seq(PaymentSourceNotAuthorised))
    }
    "be decodable for txn too early" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////+AAAAAA==") mustEqual
        TransactionNotAttempted(SubmittedTooEarly, NativeAmount(100))
    }
    "be decodable for txn too late" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////9AAAAAA==") mustEqual
        TransactionNotAttempted(SubmittedTooLate, NativeAmount(100))
    }
    "be decodable for bad auth" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////6AAAAAA==") mustEqual
        TransactionNotAttempted(BadAuthorisation, NativeAmount(100))
    }
    "be decodable for missing operations" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////8AAAAAA==") mustEqual
        TransactionNotAttempted(NoOperations, NativeAmount(100))
    }
    "be decodable for bad sequence numbers" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////7AAAAAA==") mustEqual
        TransactionNotAttempted(BadSequenceNumber, NativeAmount(100))
    }
    "be decodable for insufficient balance" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////5AAAAAA==") mustEqual
        TransactionNotAttempted(InsufficientBalance, NativeAmount(100))
    }
    "be decodable for missing source account" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////4AAAAAA==") mustEqual
        TransactionNotAttempted(SourceAccountNotFound, NativeAmount(100))
    }
    "be decodable for insufficient fee" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////3AAAAAA==") mustEqual
        TransactionNotAttempted(InsufficientFee, NativeAmount(100))
    }
    "be decodable for extraneous signatures" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////2AAAAAA==") mustEqual
        TransactionNotAttempted(UnusedSignatures, NativeAmount(100))
    }
    "be decodable for other reasons" >> {
      TransactionResult.decodeXDR("AAAAAAAAAGT////1AAAAAA==") mustEqual
        TransactionNotAttempted(UnspecifiedInternalError, NativeAmount(100))
    }
    "return failure when not decodable" >> {
      Try(TransactionResult.decodeXDR("foo")) must beFailedTry[TransactionResult]
    }
  }

  "a transaction not successful" should {
    "mark sequenceUpdates as true only when fee is not zero" >> prop { t: TransactionNotSuccessful =>
      t.sequenceUpdated mustEqual t.feeCharged.units != 0
    }
  }
} 
Example 162
Source File: TwitterSourceSpec.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.streaming.twitter

import java.time.Instant

import org.apache.gearpump.streaming.MockUtil
import org.apache.gearpump.streaming.twitter.TwitterSource.{Factory, MessageListener}
import org.mockito.Mockito._
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, PropSpec}
import org.scalatest.prop.PropertyChecks
import twitter4j.{FilterQuery, TwitterStream}

class TwitterSourceSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {

  implicit val arbQuery: Arbitrary[Option[FilterQuery]] = Arbitrary {
    Gen.oneOf(None, Some(new FilterQuery()))
  }

  property("TwitterSource should properly setup, poll message and teardown") {
    forAll {
      (query: Option[FilterQuery], startTime: Long) =>
        val factory = mock[Factory]
        val stream = mock[TwitterStream]
        val listener = mock[MessageListener]

        when(factory.getTwitterStream).thenReturn(stream)
        val twitterSource = new TwitterSource(factory, query, listener)

        twitterSource.open(MockUtil.mockTaskContext, Instant.ofEpochMilli(startTime))

        verify(stream).addListener(listener)
        query match {
          case Some(q) =>
            verify(stream).filter(q)
          case None =>
            verify(stream).sample()
        }

        twitterSource.read()
        verify(listener).poll()

        twitterSource.close()
        verify(stream).shutdown()
    }
  }
} 
Example 163
Source File: editTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.edit

import cats.implicits._
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class editTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  private val lineGen = Gen.frequency(
    3 -> Arbitrary.arbString.arbitrary,
    1 -> Gen.oneOf("scala-steward:off", "scala-steward:on"),
    1 -> Gen.alphaNumStr.map(_ + " // scala-steward:off")
  )

  private val contentGen = Gen.listOf(lineGen).map(_.mkString("\n"))

  test("splitByOffOnMarker") {
    forAll(contentGen) { s: String =>
      splitByOffOnMarker(s).foldMap { case (part, _) => part } shouldBe s
    }
  }
} 
Example 164
Source File: gitTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.git

import org.scalacheck.{Arbitrary, Gen}
import org.scalasteward.core.TestSyntax._
import org.scalasteward.core.data.Update
import org.scalasteward.core.data.Update.Single
import org.scalasteward.core.repoconfig.CommitsConfig
import org.scalasteward.core.update.show
import org.scalasteward.core.util.Nel
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class gitTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  implicit val updateArbitrary: Arbitrary[Update] = Arbitrary(for {
    groupId <- Gen.alphaStr
    artifactId <- Gen.alphaStr
    currentVersion <- Gen.alphaStr
    newerVersion <- Gen.alphaStr
  } yield Single(groupId % artifactId % currentVersion, Nel.one(newerVersion)))

  test("commitMsgFor should work with static message") {
    val commitsConfig = CommitsConfig(Some("Static message"))
    forAll { update: Update => commitMsgFor(update, commitsConfig) shouldBe "Static message" }
  }

  test("commitMsgFor should work with default message") {
    val commitsConfig = CommitsConfig(Some("${default}"))
    forAll { update: Update =>
      commitMsgFor(update, commitsConfig) shouldBe s"Update ${show.oneLiner(update)} to ${update.nextVersion}"
    }
  }

  test("commitMsgFor should work with templated message") {
    val commitsConfig =
      CommitsConfig(Some("Update ${artifactName} from ${currentVersion} to ${nextVersion}"))
    forAll { update: Update =>
      commitMsgFor(update, commitsConfig) shouldBe s"Update ${show.oneLiner(update)} from ${update.currentVersion} to ${update.nextVersion}"
    }
  }

} 
Example 165
Source File: TestInstances.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core

import _root_.io.chrisdavenport.log4cats.Logger
import _root_.io.chrisdavenport.log4cats.slf4j.Slf4jLogger
import cats.effect.{ContextShift, IO, Timer}
import org.scalacheck.{Arbitrary, Cogen, Gen}
import org.scalasteward.core.data.Version
import org.scalasteward.core.util.Change
import org.scalasteward.core.util.Change.{Changed, Unchanged}
import scala.concurrent.ExecutionContext

object TestInstances {
  implicit def changeArbitrary[T](implicit arbT: Arbitrary[T]): Arbitrary[Change[T]] =
    Arbitrary(arbT.arbitrary.flatMap(t => Gen.oneOf(Changed(t), Unchanged(t))))

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

  implicit val ioLogger: Logger[IO] =
    Slf4jLogger.getLogger[IO]

  implicit val ioTimer: Timer[IO] =
    IO.timer(ExecutionContext.global)

  implicit val versionArbitrary: Arbitrary[Version] = {
    val versionChar = Gen.frequency(
      (8, Gen.numChar),
      (5, Gen.const('.')),
      (3, Gen.alphaChar),
      (2, Gen.const('-'))
    )
    Arbitrary(Gen.listOf(versionChar).map(_.mkString).map(Version.apply))
  }

  implicit val versionCogen: Cogen[Version] =
    Cogen(_.alnumComponents.map {
      case Version.Component.Numeric(value) => BigInt(value).toLong
      case a @ Version.Component.Alpha(_)   => a.order.toLong
      case _                                => 0L
    }.sum)
} 
Example 166
Source File: NurtureAlgTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.nurture

import cats.data.StateT
import cats.effect.IO
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.{Arbitrary, Gen}
import org.scalasteward.core.TestSyntax._
import org.scalasteward.core.data.ProcessResult.{Ignored, Updated}
import org.scalasteward.core.data.Update.Single
import org.scalasteward.core.data.{ProcessResult, Update}
import org.scalasteward.core.util.Nel
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class NurtureAlgTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  implicit val updateArbitrary: Arbitrary[Update] = Arbitrary(for {
    groupId <- Gen.alphaStr
    artifactId <- Gen.alphaStr
    currentVersion <- Gen.alphaStr
    newerVersion <- Gen.alphaStr
  } yield Single(groupId % artifactId % currentVersion, Nel.one(newerVersion)))

  test("processUpdates with No Limiting") {
    forAll { updates: List[Update] =>
      NurtureAlg
        .processUpdates(
          updates,
          _ => StateT[IO, Int, ProcessResult](actionAcc => IO.pure(actionAcc + 1 -> Ignored)),
          None
        )
        .runS(0)
        .unsafeRunSync() shouldBe updates.size
    }
  }

  test("processUpdates with Limiting should process all updates up to the limit") {
    forAll { updates: Set[Update] =>
      val (ignorableUpdates, appliableUpdates) = updates.toList.splitAt(updates.size / 2)
      val f: Update => StateT[IO, Int, ProcessResult] = update =>
        StateT[IO, Int, ProcessResult](actionAcc =>
          IO.pure(actionAcc + 1 -> (if (ignorableUpdates.contains(update)) Ignored else Updated))
        )
      NurtureAlg
        .processUpdates(
          ignorableUpdates ++ appliableUpdates,
          f,
          PosInt.unapply(appliableUpdates.size)
        )
        .runS(0)
        .unsafeRunSync() shouldBe updates.size
    }
  }
} 
Example 167
Source File: DatasetGenerator.scala    From spark-testing-base   with Apache License 2.0 5 votes vote down vote up
package com.holdenkarau.spark.testing

import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{Dataset, Encoder, SQLContext}
import org.scalacheck.{Arbitrary, Gen}

import scala.reflect.ClassTag

object DatasetGenerator {

  
  def arbitrarySizedDataset[T: ClassTag : Encoder]
    (sqlCtx: SQLContext, minPartitions: Int = 1)
    (generator: Int => Gen[T]): Arbitrary[Dataset[T]] = {

    val rddGen: Gen[RDD[T]] =
      RDDGenerator.genSizedRDD[T](sqlCtx.sparkContext, minPartitions)(generator)
    val datasetGen: Gen[Dataset[T]] =
      rddGen.map(rdd => sqlCtx.createDataset(rdd))

    Arbitrary {
      datasetGen
    }
  }
} 
Example 168
Source File: MLUserDefinedType.scala    From spark-testing-base   with Apache License 2.0 5 votes vote down vote up
package com.holdenkarau.spark.testing

import org.apache.spark.sql.types.DataType
import org.apache.spark.ml.linalg.SQLDataTypes.{MatrixType, VectorType}
import org.apache.spark.ml.linalg.{DenseMatrix, Vectors}
import org.scalacheck.{Arbitrary, Gen}


object MLUserDefinedType {
  def unapply(dataType: DataType): Option[Gen[Any]] =
    dataType match {
      case MatrixType => {
        val dense = for {
          rows <- Gen.choose(0, 20)
          cols <- Gen.choose(0, 20)
          values <- Gen.containerOfN[Array, Double](rows * cols, Arbitrary.arbitrary[Double])
        } yield new DenseMatrix(rows, cols, values)
        val sparse = dense.map(_.toSparse)
        Some(Gen.oneOf(dense, sparse))
      }
      case VectorType => {
        val dense = Arbitrary.arbitrary[Array[Double]].map(Vectors.dense)
        val sparse = for {
          indices <- Gen.nonEmptyContainerOf[Set, Int](Gen.choose(0, Int.MaxValue - 1))
          values <- Gen.listOfN(indices.size, Arbitrary.arbitrary[Double])
        } yield Vectors.sparse(indices.max + 1, indices.toSeq.zip(values))
        Some(Gen.oneOf(dense, sparse))
      }
      case _ => None
    }
} 
Example 169
Source File: SampleDatasetGeneratorTest.scala    From spark-testing-base   with Apache License 2.0 5 votes vote down vote up
package com.holdenkarau.spark.testing

import org.apache.spark.sql.{Dataset, SQLContext}
import org.scalacheck.{Gen, Arbitrary}
import org.scalacheck.Prop.forAll
import org.scalatest.FunSuite
import org.scalatest.prop.Checkers

class SampleDatasetGeneratorTest extends FunSuite
    with SharedSparkContext with Checkers {

  test("test generating Datasets[String]") {
    val sqlContext = new SQLContext(sc)
    import sqlContext.implicits._

    val property =
      forAll(
        DatasetGenerator.genDataset[String](sqlContext)(
          Arbitrary.arbitrary[String])) {
        dataset => dataset.map(_.length).count() == dataset.count()
      }

    check(property)
  }

  test("test generating sized Datasets[String]") {
    val sqlContext = new SQLContext(sc)
    import sqlContext.implicits._

    val property =
      forAll {
        DatasetGenerator.genSizedDataset[(Int, String)](sqlContext) { size =>
          Gen.listOfN(size, Arbitrary.arbitrary[Char]).map(l => (size, l.mkString))
        }
      }{
        dataset =>
          val tuples = dataset.collect()
          val value = dataset.map{ case (_, str) => str.length}
          tuples.forall{ case (size, str) => size == str.length} &&
          value.count() == dataset.count
      }

    check(property)
  }

  test("test generating Datasets[Custom Class]") {
    val sqlContext = new SQLContext(sc)
    import sqlContext.implicits._

    val carGen: Gen[Dataset[Car]] =
      DatasetGenerator.genDataset[Car](sqlContext) {
        val generator: Gen[Car] = for {
          name <- Arbitrary.arbitrary[String]
          speed <- Arbitrary.arbitrary[Int]
        } yield (Car(name, speed))

        generator
    }

    val property =
      forAll(carGen) {
        dataset => dataset.map(_.speed).count() == dataset.count()
      }

    check(property)
  }
}

case class Car(name: String, speed: Int) 
Example 170
Source File: DatasetGeneratorSizeSpecial.scala    From spark-testing-base   with Apache License 2.0 5 votes vote down vote up
package com.holdenkarau.spark.testing

import org.apache.spark.sql.{Dataset, SQLContext}
import org.scalacheck.{Gen, Arbitrary}
import org.scalacheck.Prop.forAll
import org.scalatest.FunSuite
import org.scalatest.prop.Checkers

class DatasetGeneratorSizeSpecial extends FunSuite
    with SharedSparkContext with Checkers {

  test("test generating sized Datasets[Custom Class]") {
    val sqlContext = new SQLContext(sc)
    import sqlContext.implicits._

    // In 2.3 List is fine, however prior to 2.1 the generator returns
    // a concrete sub type which isn't handled well.
    // This works in 1.6.1+ but we only test in 2.0+ because that's easier
    val carGen: Gen[Dataset[Seq[Car]]] =
      DatasetGenerator.genSizedDataset[Seq[Car]](sqlContext) { size =>
        val slowCarsTopNumber = math.ceil(size * 0.1).toInt
        def carGenerator(speed: Gen[Int]): Gen[Car] = for {
          name <- Arbitrary.arbitrary[String]
          speed <- speed
        } yield Car(name, speed)

        val cars: Gen[List[Car]] = for {
          slowCarsNumber: Int <- Gen.choose(0, slowCarsTopNumber)
          slowCars: List[Car] <- Gen.listOfN(slowCarsNumber, carGenerator(Gen.choose(0, 20)))
          normalSpeedCars: List[Car] <- Gen.listOfN(
            size - slowCarsNumber,
            carGenerator(Gen.choose(21, 150))
          )
        } yield {
          slowCars ++ normalSpeedCars
        }
        cars
      }

    val property =
      forAll(carGen.map(_.flatMap(identity))) {
        dataset =>
          val cars = dataset.collect()
          val dataSetSize  = cars.length
          val slowCars = cars.filter(_.speed < 21)
          slowCars.length <= dataSetSize * 0.1 &&
            cars.map(_.speed).length == dataSetSize
      }

    check(property)
  }
} 
Example 171
Source File: SplitEpiTests.scala    From redis4cats   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.redis4cats.codecs

import cats.Eq
import cats.laws.discipline._
import dev.profunktor.redis4cats.codecs.laws.SplitEpiLaws
import dev.profunktor.redis4cats.codecs.splits.SplitEpi
import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import org.typelevel.discipline.Laws

// Credits to Rob Norris (@tpolecat) -> https://skillsmatter.com/skillscasts/11626-keynote-pushing-types-and-gazing-at-the-stars
trait SplitEpiTests[A, B] extends Laws {
  def laws: SplitEpiLaws[A, B]

  def splitEpi(implicit a: Arbitrary[A], b: Arbitrary[B], eqA: Eq[A], eqB: Eq[B]): RuleSet =
    new DefaultRuleSet(
      name = "splitEpimorphism",
      parent = None,
      "identity" -> forAll(laws.identity _),
      "idempotence" -> forAll(laws.idempotence _)
    )
}

object SplitEpiTests {
  def apply[A, B](epi: SplitEpi[A, B]): SplitEpiTests[A, B] =
    new SplitEpiTests[A, B] {
      val laws = SplitEpiLaws[A, B](epi)
    }
} 
Example 172
Source File: SplitMonoTests.scala    From redis4cats   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.redis4cats.codecs

import cats.Eq
import cats.laws.discipline._
import dev.profunktor.redis4cats.codecs.laws.SplitMonoLaws
import dev.profunktor.redis4cats.codecs.splits.SplitMono
import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import org.typelevel.discipline.Laws

// Credits to Rob Norris (@tpolecat) -> https://skillsmatter.com/skillscasts/11626-keynote-pushing-types-and-gazing-at-the-stars
trait SplitMonoTests[A, B] extends Laws {
  def laws: SplitMonoLaws[A, B]

  def splitMono(implicit a: Arbitrary[A], b: Arbitrary[B], eqA: Eq[A], eqB: Eq[B]): RuleSet =
    new DefaultRuleSet(
      name = "splitMonomorphism",
      parent = None,
      "identity" -> forAll(laws.identity _),
      "idempotence" -> forAll(laws.idempotence _)
    )
}

object SplitMonoTests {
  def apply[A, B](mono: SplitMono[A, B]): SplitMonoTests[A, B] =
    new SplitMonoTests[A, B] {
      val laws = SplitMonoLaws[A, B](mono)
    }
} 
Example 173
Source File: ApplyKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package laws
package discipline

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

trait ApplyKTests[F[_[_]]] extends FunctorKTests[F] with SemigroupalKTests[F] {
  def laws: ApplyKLaws[F]

  def applyK[A[_], B[_], C[_], T: Arbitrary](implicit
                                               ArbFA: Arbitrary[F[A]],
                                               ArbCG: Arbitrary[F[B]],
                                               ArbCH: Arbitrary[F[C]],
                                               iso: IsomorphismsK[F],
                                               ArbitraryFK: Arbitrary[A ~> B],
                                               ArbitraryFK2: Arbitrary[B ~> C],
                                               ArbitraryFK3: Arbitrary[B ~> A],
                                               ArbitraryFK4: Arbitrary[C ~> B],
                                               EqFA: Eq[F[A]],
                                               EqFC: Eq[F[C]],
                                               EqFG: Eq[F[Tuple2K[A, Tuple2K[B, C, *], *]]],
                                               EqFGH: Eq[F[Tuple3K[A, B, C]#λ]]
                                              ): RuleSet =
    new RuleSet {
      val name = "applyK"
      val parents = List(functorK[A, B, C, T], semigroupalK[A, B, C])
      val bases = List.empty
      val props = List(
        "applyK associativity" -> forAll(laws.applyKAssociativity[A, B, C] _))
    }
}

object ApplyKTests {
  def apply[F[_[_]]: ApplyK]: ApplyKTests[F] =
    new ApplyKTests[F] { def laws: ApplyKLaws[F] = ApplyKLaws[F] }
} 
Example 174
Source File: SemigroupalKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package laws
package discipline


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

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

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


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

  import IsomorphismsK._

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

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

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

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

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

      }
  }
} 
Example 175
Source File: FunctorKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package laws
package discipline

import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import cats.{Eq, ~>}
import cats.laws.discipline._

trait FunctorKTests[F[_[_]]] extends InvariantKTests[F] {
  def laws: FunctorKLaws[F]

  def functorK[A[_], B[_], C[_], T: Arbitrary](implicit
                                               ArbFA: Arbitrary[F[A]],
                                               ArbitraryFK: Arbitrary[A ~> B],
                                               ArbitraryFK2: Arbitrary[B ~> C],
                                               ArbitraryFK3: Arbitrary[B ~> A],
                                               ArbitraryFK4: Arbitrary[C ~> B],
                                               EqFA: Eq[F[A]],
                                               EqFC: Eq[F[C]]
                                              ): RuleSet = {
    new DefaultRuleSet(
      name = "functorK",
      parent = Some(invariantK[A, B, C]),
      "covariant identity" -> forAll(laws.covariantIdentity[A] _),
      "covariant composition" -> forAll(laws.covariantComposition[A, B, C] _))
  }
}

object FunctorKTests {
  def apply[F[_[_]]: FunctorK]: FunctorKTests[F] =
    new FunctorKTests[F] { def laws: FunctorKLaws[F] = FunctorKLaws[F] }
} 
Example 176
Source File: InvariantKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package laws
package discipline

import cats.{Eq, ~>}
import org.scalacheck.Prop._
import org.scalacheck.Arbitrary
import org.typelevel.discipline.Laws
import cats.laws.discipline._

trait InvariantKTests[F[_[_]]] extends Laws {
  def laws: InvariantKLaws[F]

  def invariantK[A[_], B[_], C[_]](implicit
                                                          ArbFA: Arbitrary[F[A]],
                                                          ArbAB: Arbitrary[A ~> B],
                                                          ArbBA: Arbitrary[B ~> A],
                                                          ArbBC: Arbitrary[B ~> C],
                                                          ArbCB: Arbitrary[C ~> B],
                                                          EqFA: Eq[F[A]],
                                                          EqFC: Eq[F[C]]
                                                         ): RuleSet = {
    new DefaultRuleSet(
      name = "invariantK",
      parent = None,
      "invariant identity" -> forAll(laws.invariantIdentity[A] _),
      "invariant composition" -> forAll(laws.invariantComposition[A, B, C] _))
  }
}

object InvariantKTests {
  def apply[F[_[_]]: InvariantK]: InvariantKTests[F] =
    new InvariantKTests[F] { def laws: InvariantKLaws[F] = InvariantKLaws[F] }
} 
Example 177
Source File: ContravariantKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless.laws.discipline

import cats.laws.discipline._
import cats.tagless.ContravariantK
import cats.tagless.laws.ContravariantKLaws
import cats.{Eq, ~>}
import org.scalacheck.Arbitrary
import org.scalacheck.Prop._

trait ContravariantKTests[F[_[_]]] extends InvariantKTests[F] {
  def laws: ContravariantKLaws[F]

  def contravariantK[A[_], B[_], C[_], T: Arbitrary](
    implicit
    arbFa: Arbitrary[F[A]],
    arbFkAB: Arbitrary[A ~> B],
    arbFkBC: Arbitrary[B ~> C],
    arbFkBA: Arbitrary[B ~> A],
    arbFkCB: Arbitrary[C ~> B],
    eqFa: Eq[F[A]],
    eqFc: Eq[F[C]]
  ): RuleSet = new DefaultRuleSet(
    name = "contravariantK",
    parent = Some(invariantK[A, B, C]),
    "contravariant identity" -> forAll(laws.contravariantIdentity[A] _),
    "contravariant composition" -> forAll(laws.contravariantComposition[A, B, C] _)
  )
}

object ContravariantKTests {
  def apply[F[_[_]]: ContravariantK]: ContravariantKTests[F] =
    new ContravariantKTests[F] { val laws = ContravariantKLaws[F] }
} 
Example 178
Source File: autoApplyKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package tests

import cats.Eq
import cats.data.EitherT
import cats.instances.all._
import cats.laws.discipline.SerializableTests
import cats.laws.discipline.arbitrary._
import cats.laws.discipline.eq._
import cats.tagless.instances.all._
import cats.tagless.laws.discipline.ApplyKTests
import cats.tagless.tests.autoApplyKTests.AutoApplyKTestAlg
import org.scalacheck.Arbitrary

import scala.util.Try

class autoApplyKTests extends CatsTaglessTestSuite {
  // Type inference limitation.
  implicit val eqTuple3K = AutoApplyKTestAlg.eqForAutoApplyKTestAlg[Tuple3K[Try, Option, List]#λ]
  checkAll("ApplyK[AutoApplyKTestAlg]", ApplyKTests[AutoApplyKTestAlg].applyK[Try, Option, List, Int])
  checkAll("ApplyK is Serializable", SerializableTests.serializable(ApplyK[AutoApplyKTestAlg]))
}

object autoApplyKTests {

  @autoApplyK(autoDerivation = false)
  trait AutoApplyKTestAlg[F[_]] {
    def parseInt(str: String): F[Int]
    def parseDouble(str: String): EitherT[F, String, Double]
    def divide(dividend: Float, divisor: Float): F[Float]
  }

  object AutoApplyKTestAlg {
    import TestInstances._

    implicit def eqForAutoApplyKTestAlg[F[_]](
      implicit eqFi: Eq[F[Int]], eqFf: Eq[F[Float]], eqEfd: Eq[EitherT[F, String, Double]]
    ): Eq[AutoApplyKTestAlg[F]] = Eq.by {
      algebra => (algebra.parseInt _, algebra.parseDouble _, algebra.divide _)
    }

    implicit def arbitraryAutoApplyKTestAlg[F[_]](
      implicit arbFi: Arbitrary[F[Int]], arbFf: Arbitrary[F[Float]], arbEfd: Arbitrary[EitherT[F, String, Double]]
    ): Arbitrary[AutoApplyKTestAlg[F]] = Arbitrary {
      for {
        pInt <- Arbitrary.arbitrary[String => F[Int]]
        pDouble <- Arbitrary.arbitrary[String => EitherT[F, String, Double]]
        div <- Arbitrary.arbitrary[(Float, Float) => F[Float]]
      } yield new AutoApplyKTestAlg[F] {
        def parseInt(str: String) = pInt(str)
        def parseDouble(str: String) = pDouble(str)
        def divide(dividend: Float, divisor: Float) = div(dividend, divisor)
      }
    }
  }

  @autoApplyK
  trait AlgWithVarArgsParameter[F[_]] {
    def sum(xs: Int*): Int
    def fSum(xs: Int*): F[Int]
  }
} 
Example 179
Source File: autoApplyTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless.tests

import cats.instances.all._
import cats.laws.discipline.eq._
import cats.laws.discipline.{ApplyTests, SerializableTests}
import cats.tagless.autoApply
import cats.{Apply, Eq}
import org.scalacheck.Arbitrary

class autoApplyTests extends CatsTaglessTestSuite {
  import autoApplyTests._

  checkAll("Apply[TestAlgebra]", ApplyTests[TestAlgebra].apply[Long, String, Int])
  checkAll("Serializable Apply[TestAlgebra]", SerializableTests.serializable(Apply[TestAlgebra]))
}

object autoApplyTests {
  import TestInstances._

  @autoApply
  trait TestAlgebra[T] {
    def abstractEffect(a: String): T
    def concreteEffect(a: String): T = abstractEffect(a + " concreteEffect")
    def abstractOther(a: String): String
    def concreteOther(a: String): String = a + " concreteOther"
    def withoutParams: T
    def curried(a: String)(b: Int): T
  }

  @autoApply
  trait AlgWithExtraTypeParam[T1, T] {
    def foo(a: T1): T
  }

  @autoApply
  trait AlgWithGenericMethod[T] {
    def plusOne[A](i: A): T
  }

  @autoApply
  trait AlgWithVarArgsParameter[T] {
    def sum(xs: Int*): Int
    def product(xs: Int*): T
  }

  implicit def eqForTestAlgebra[T: Eq]: Eq[TestAlgebra[T]] =
    Eq.by { algebra =>
      (
        algebra.abstractEffect _,
        algebra.concreteEffect _,
        algebra.abstractOther _,
        algebra.concreteOther _,
        algebra.withoutParams,
        Function.uncurried(algebra.curried _).tupled
      )
    }

  implicit def arbitraryTestAlgebra[T: Arbitrary]: Arbitrary[TestAlgebra[T]] =
    Arbitrary {
      for {
        absEff <- Arbitrary.arbitrary[String => T]
        conEff <- Arbitrary.arbitrary[Option[String => T]]
        absOther <- Arbitrary.arbitrary[String => String]
        conOther <- Arbitrary.arbitrary[Option[String => String]]
        withoutParameters <- Arbitrary.arbitrary[T]
        curry <- Arbitrary.arbitrary[String => Int => T]
      } yield new TestAlgebra[T] {
        override def abstractEffect(i: String) = absEff(i)
        override def concreteEffect(a: String) = conEff.getOrElse(super.concreteEffect(_))(a)
        override def abstractOther(a: String) = absOther(a)
        override def concreteOther(a: String) = conOther.getOrElse(super.concreteOther(_))(a)
        override def withoutParams = withoutParameters
        override def curried(a: String)(b: Int) = curry(a)(b)
      }
    }
} 
Example 180
Source File: autoBifunctorTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless.tests

import cats.{Bifunctor, Eq}
import cats.instances.AllInstances
import cats.laws.discipline.{BifunctorTests, SerializableTests}
import cats.laws.discipline.eq._
import cats.tagless.autoBifunctor
import org.scalacheck.{Arbitrary, Cogen}

class autoBifunctorTests extends CatsTaglessTestSuite {
  import autoBifunctorTests._

  checkAll("Bifunctor[TestAlgebra]", BifunctorTests[TestAlgebra].bifunctor[String, Boolean, Option[String], Int, String, List[Int]])
  checkAll("Serializable Bifunctor[TestAlgebra]", SerializableTests.serializable(Bifunctor[TestAlgebra]))

  test("extra type param correctly handled") {
    val transformedAlg = AlgWithExtraTypeParamString.bimap(i => if (i > 0) Some(i) else None, new String(_))
    transformedAlg.foo("") should be(None)
    transformedAlg.foo("1") should be(Some(1))
    transformedAlg.boo("adsfdsd") should be("adsfdsd")
  }
}

object autoBifunctorTests extends TestInstances with AllInstances {

  @autoBifunctor
  trait TestAlgebra[A, B] {
    def left: A
    def right: B
    def toTuple: (A, B) = (left, right)
    def mapLeft[C](f: A => C): C = f(left)
    def mapRight[C](f: B => C): C = f(right)
    def concreteMethod: Int = 0
    def fromInt(i: Int): A
    def fromString(s: String): B
  }

  object TestAlgebra {
    implicit def eqv[A: Eq: Cogen, B: Eq: Cogen]: Eq[TestAlgebra[A, B]] =
      Eq.by { algebra =>
        (
          algebra.left,
          algebra.right,
          algebra.fromInt _,
          algebra.fromString _,
          algebra.concreteMethod,
          algebra.toTuple,
          algebra.mapLeft[Int] _,
          algebra.mapRight[Int] _
        )
      }
  }

  implicit def arbitrary[A: Arbitrary, B: Arbitrary]: Arbitrary[TestAlgebra[A, B]] =
    Arbitrary(for {
      a1 <- Arbitrary.arbitrary[A]
      a2 <- Arbitrary.arbitrary[A]
      b <- Arbitrary.arbitrary[B]
      int <- Arbitrary.arbitrary[Int]
      tuple <- Arbitrary.arbitrary[Option[(A, B)]]
    } yield new TestAlgebra[A, B] {
      override def left = a1
      override def right = b
      override def concreteMethod = int
      override def fromInt(i: Int) = if (i > 0) left else a2
      override def fromString(s: String) = b
      override def toTuple = tuple.getOrElse(super.toTuple)
    })

  @autoBifunctor
  trait AlgWithExtraTypeParam[T, A, B] {
    def foo(t: T): A
    def boo(t: T): B
  }

  object AlgWithExtraTypeParamString extends AlgWithExtraTypeParam[String, Int, Array[Char]] {
    override def foo(t: String) = t.length
    override def boo(t: String) = t.toCharArray
  }
} 
Example 181
Source File: autoSemigroupalTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless.tests

import cats.instances.all._
import cats.laws.discipline.eq._
import cats.laws.discipline.{SemigroupalTests, SerializableTests}
import cats.tagless.{autoInvariant, autoSemigroupal}
import cats.{Eq, Semigroupal}
import org.scalacheck.Arbitrary

class autoSemigroupalTests extends CatsTaglessTestSuite {
  import autoSemigroupalTests._

  checkAll("Semigroupal[TestAlgebra]", SemigroupalTests[TestAlgebra].semigroupal[Long, String, Int])
  checkAll("Serializable Semigroupal[TestAlgebra]", SerializableTests.serializable(Semigroupal[TestAlgebra]))
}

object autoSemigroupalTests {
  import TestInstances._

  @autoSemigroupal
  @autoInvariant // Needed for Isomorphisms
  trait TestAlgebra[T] {
    def abstractEffect(a: String): T
    def concreteEffect(a: String): T = abstractEffect(a + " concreteEffect")
    def abstractOther(a: String): String
    def concreteOther(a: String): String = a + " concreteOther"
    def withoutParams: T
    def curried(a: String)(b: Int): T
  }

  @autoSemigroupal
  trait AlgWithExtraTypeParam[T1, T] {
    def foo(a: T1): T
  }

  @autoSemigroupal
  trait AlgWithGenericMethod[T] {
    def plusOne[A](i: A): T
  }

  @autoSemigroupal
  trait AlgWithVarArgsParameter[T] {
    def sum(xs: Int*): Int
    def product(xs: Int*): T
  }

  implicit def eqForTestAlgebra[T: Eq]: Eq[TestAlgebra[T]] =
    Eq.by { algebra =>
      (
        algebra.abstractEffect _,
        algebra.concreteEffect _,
        algebra.abstractOther _,
        algebra.concreteOther _,
        algebra.withoutParams,
        Function.uncurried(algebra.curried _).tupled
      )
    }

  implicit def arbitraryTestAlgebra[T: Arbitrary]: Arbitrary[TestAlgebra[T]] =
    Arbitrary {
      for {
        absEff <- Arbitrary.arbitrary[String => T]
        conEff <- Arbitrary.arbitrary[Option[String => T]]
        absOther <- Arbitrary.arbitrary[String => String]
        conOther <- Arbitrary.arbitrary[Option[String => String]]
        withoutParameters <- Arbitrary.arbitrary[T]
        curry <- Arbitrary.arbitrary[String => Int => T]
      } yield new TestAlgebra[T] {
        override def abstractEffect(i: String) = absEff(i)
        override def concreteEffect(a: String) = conEff.getOrElse(super.concreteEffect(_))(a)
        override def abstractOther(a: String) = absOther(a)
        override def concreteOther(a: String) = conOther.getOrElse(super.concreteOther(_))(a)
        override def withoutParams = withoutParameters
        override def curried(a: String)(b: Int) = curry(a)(b)
      }
    }
} 
Example 182
Source File: autoProfunctorTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package tests

import cats.Eq
import cats.arrow.Profunctor
import cats.instances.all._
import cats.laws.discipline.{ProfunctorTests, SerializableTests}
import cats.laws.discipline.eq._
import org.scalacheck.{Arbitrary, Cogen}

class autoProfunctorTests extends CatsTaglessTestSuite {
  import autoProfunctorTests._

  checkAll("Profunctor[TestAlgebra]", ProfunctorTests[TestAlgebra].profunctor[Long, String, Int, Long, String, Int])
  checkAll("Serializable Profunctor[TestAlgebra]", SerializableTests.serializable(Profunctor[TestAlgebra]))

  test("extra type param correctly handled") {
    val asStringAlg = AlgWithExtraTypeParamString.dimap((s: String) => s.length)(_ + 1)
    asStringAlg.foo("base", "x2") should be(9d)
  }
}

object autoProfunctorTests {
   import TestInstances._

  @autoProfunctor
  trait TestAlgebra[A, B] {
    def abstractCovariant(str: String): B
    def concreteCovariant(str: String): B = abstractCovariant(str + " concreteCovariant")
    def abstractContravariant(a: A): String
    def concreteContravariant(a: A): String = abstractContravariant(a) + " concreteContravariant"
    def abstractMixed(a: A): B
    def concreteMixed(a: A): B = abstractMixed(a)
    def abstractOther(str: String): String
    def concreteOther(str: String): String = str + " concreteOther"
    def withoutParams: B
    def fromList(as: List[A]): List[B]
  }

  object TestAlgebra {
    implicit def eqv[A: Arbitrary, B: Eq]: Eq[TestAlgebra[A, B]] =
      Eq.by { algebra =>
        (
          algebra.abstractCovariant _,
          algebra.concreteCovariant _,
          algebra.abstractContravariant _,
          algebra.concreteContravariant _,
          algebra.abstractMixed _,
          algebra.concreteMixed _,
          algebra.abstractOther _,
          algebra.concreteOther _,
          algebra.withoutParams,
          algebra.fromList _
        )
      }
  }

  implicit def arbitrary[A: Cogen, B: Arbitrary]: Arbitrary[TestAlgebra[A, B]] =
    Arbitrary(for {
      absCovariant <- Arbitrary.arbitrary[String => B]
      conCovariant <- Arbitrary.arbitrary[Option[String => B]]
      absContravariant <- Arbitrary.arbitrary[A => String]
      conContravariant <- Arbitrary.arbitrary[Option[A => String]]
      absMixed <- Arbitrary.arbitrary[A => B]
      conMixed <- Arbitrary.arbitrary[Option[A => B]]
      absOther <- Arbitrary.arbitrary[String => String]
      conOther <- Arbitrary.arbitrary[Option[String => String]]
      noParams <- Arbitrary.arbitrary[B]
      list <- Arbitrary.arbitrary[List[A] => List[B]]
    } yield new TestAlgebra[A, B] {
      override def abstractCovariant(str: String) = absCovariant(str)
      override def concreteCovariant(str: String) = conCovariant.getOrElse(super.concreteCovariant(_))(str)
      override def abstractContravariant(a: A) = absContravariant(a)
      override def concreteContravariant(a: A) = conContravariant.getOrElse(super.concreteContravariant(_))(a)
      override def abstractMixed(a: A) = absMixed(a)
      override def concreteMixed(a: A) = conMixed.getOrElse(super.concreteMixed(_))(a)
      override def abstractOther(str: String) = absOther(str)
      override def concreteOther(str: String) = conOther.getOrElse(super.concreteOther(_))(str)
      override def withoutParams = noParams
      override def fromList(as: List[A]) = list(as)
    })

  @autoProfunctor
  trait AlgWithExtraTypeParam[T, A, B] {
    def foo(t: T, a: A): B
  }

  object AlgWithExtraTypeParamString extends AlgWithExtraTypeParam[String, Int, Double] {
    override def foo(t: String, a: Int) = t.length * a.toDouble
  }
} 
Example 183
Source File: autoContravariantKTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless.tests

import cats.Eq
import cats.data.Cokleisli
import cats.instances.all._
import cats.laws.discipline.SerializableTests
import cats.laws.discipline.arbitrary._
import cats.laws.discipline.eq._
import cats.tagless.{ContravariantK, autoContravariantK}
import cats.tagless.instances.all._
import cats.tagless.laws.discipline.ContravariantKTests
import org.scalacheck.{Arbitrary, Cogen}

import scala.util.Try

class autoContravariantKTests extends CatsTaglessTestSuite {
  import autoContravariantKTests._

  checkAll("ContravariantK[TestAlgebra]", ContravariantKTests[TestAlgebra].contravariantK[Try, Option, List, Int])
  checkAll("Serializable ContravariantK[TestAlgebra]", SerializableTests.serializable(ContravariantK[TestAlgebra]))
}

object autoContravariantKTests {
  import TestInstances._

  @autoContravariantK
  trait TestAlgebra[F[_]] {
    def sum(xs: F[Int]): Int
    def sumAll(xss: F[Int]*): Int
    def foldSpecialized(init: String)(f: (Int, String) => Int): Cokleisli[F, String, Int]
  }

  object TestAlgebra {
    implicit def eqv[F[_]](implicit arbFi: Arbitrary[F[Int]], arbFs: Arbitrary[F[String]]): Eq[TestAlgebra[F]] =
      Eq.by { algebra => (algebra.sum _, algebra.sumAll _, algebra.foldSpecialized _) }
  }

  implicit def arbitrary[F[_]](
    implicit arbFs: Arbitrary[F[String]], coFi: Cogen[F[Int]], coFs: Cogen[F[String]]
  ): Arbitrary[TestAlgebra[F]] = Arbitrary(for {
    s <- Arbitrary.arbitrary[F[Int] => Int]
    sa <- Arbitrary.arbitrary[Seq[F[Int]] => Int]
    fs <- Arbitrary.arbitrary[(String, (Int, String) => Int) => Cokleisli[F, String, Int]]
  } yield new TestAlgebra[F] {
    def sum(xs: F[Int]) = s(xs)
    def sumAll(xss: F[Int]*) = sa(xss)
    def foldSpecialized(init: String)(f: (Int, String) => Int) = fs(init, f)
  })

  @autoContravariantK
  trait TestAlgebraWithExtraTypeParam[F[_], A] extends TestAlgebra[F] {
    def fold[B](init: B)(f: (B, A) => B): Cokleisli[F, A, B]
  }
} 
Example 184
Source File: autoFunctorTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package tests


import cats.{Eq, Functor}
import cats.instances.all._
import cats.laws.discipline.{FunctorTests, SerializableTests}
import cats.laws.discipline.eq._
import org.scalacheck.{Arbitrary, Cogen}

class autoFunctorTests extends CatsTaglessTestSuite {
  import autoFunctorTests._

  checkAll("Functor[TestAlgebra]", FunctorTests[TestAlgebra].functor[Long, String, Int])
  checkAll("Serializable Functor[TestAlgebra]", SerializableTests.serializable(Functor[TestAlgebra]))

  test("extra type param correctly handled") {
    val doubleAlg = AlgWithExtraTypeParamFloat.map(_.toDouble)
    doubleAlg.foo("big") should be(3d)
  }
}

object autoFunctorTests {
  import TestInstances._

  @autoFunctor
  trait TestAlgebra[T] {
    def abstractEffect(a: String): T
    def concreteEffect(a: String): T = abstractEffect(a + " concreteEffect")
    def abstractOther(a: String): String
    def concreteOther(a: String): String = a + " concreteOther"
    def withoutParams: T
    def toList(xs: List[Int]): List[T]
    def fromFunction(f: T => String): T
  }

  @autoFunctor
  trait AlgWithCurry[T] {
    def foo(a: String)(b: Int): T
  }

  @autoFunctor
  trait AlgWithExtraTypeParam[T1, T] {
    def foo(a: T1): T
  }

  object AlgWithExtraTypeParamFloat extends AlgWithExtraTypeParam[String, Float] {
    def foo(a: String): Float = a.length.toFloat
  }

  @autoFunctor
  trait AlgWithGenericMethod[T] {
    def plusOne[A](i: A): T
  }

  @autoFunctor
  trait AlgWithVarArgsParameter[T] {
    def sum(xs: Int*): Int
    def product(xs: Int*): T
  }

  implicit def eqForTestAlgebra[T: Eq: Cogen]: Eq[TestAlgebra[T]] =
    Eq.by { algebra =>
      (
        algebra.abstractEffect _,
        algebra.concreteEffect _,
        algebra.abstractOther _,
        algebra.concreteOther _,
        algebra.withoutParams,
        algebra.toList _,
        algebra.fromFunction _
      )
    }

  implicit def arbitraryTestAlgebra[T: Arbitrary: Cogen]: Arbitrary[TestAlgebra[T]] =
    Arbitrary {
      for {
        absEff <- Arbitrary.arbitrary[String => T]
        conEff <- Arbitrary.arbitrary[Option[String => T]]
        absOther <- Arbitrary.arbitrary[String => String]
        conOther <- Arbitrary.arbitrary[Option[String => String]]
        withoutParameters <- Arbitrary.arbitrary[T]
        list <- Arbitrary.arbitrary[List[Int] => List[T]]
        fromFn <- Arbitrary.arbitrary[(T => String) => T]
      } yield new TestAlgebra[T] {
        override def abstractEffect(i: String) = absEff(i)
        override def concreteEffect(a: String) = conEff.getOrElse(super.concreteEffect(_))(a)
        override def abstractOther(a: String) = absOther(a)
        override def concreteOther(a: String) = conOther.getOrElse(super.concreteOther(_))(a)
        override def withoutParams = withoutParameters
        override def toList(xs: List[Int]) = list(xs)
        override def fromFunction(f: T => String) = fromFn(f)
      }
    }
} 
Example 185
Source File: autoFlatMapTests.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless.tests

import cats.{Eq, FlatMap}
import cats.instances.all._
import cats.laws.discipline.{FlatMapTests, SerializableTests}
import cats.laws.discipline.eq._
import cats.tagless.autoFlatMap
import org.scalacheck.{Arbitrary, Cogen}

class autoFlatMapTests extends CatsTaglessTestSuite {
  import autoFlatMapTests._

  checkAll("FlatMap[TestAlgebra]", FlatMapTests[TestAlgebra].flatMap[Float, String, Int])
  checkAll("serializable FlatMap[TestAlgebra]", SerializableTests.serializable(FlatMap[TestAlgebra]))

  test("extra type param correctly handled") {
    val doubleAlg: AlgWithExtraTypeParam[String, Double] = AlgWithExtraTypeParamFloat.map(_.toDouble)
    doubleAlg.foo("big") should be(3d)
  }
}

object autoFlatMapTests {
  import TestInstances._

  @autoFlatMap
  trait TestAlgebra[T] {
    def abstractEffect(a: String): T
    def concreteEffect(a: String): T = abstractEffect(a + " concreteEffect")
    def abstractOther(a: String): String
    def concreteOther(a: String): String = a + " concreteOther"
    def withoutParams: T
  }

  @autoFlatMap
  trait AlgWithExtraTypeParam[T1, T] {
    def foo(a: T1): T
  }

  object AlgWithExtraTypeParamFloat extends AlgWithExtraTypeParam[String, Float] {
    def foo(a: String): Float = a.length.toFloat
  }

  @autoFlatMap
  trait AlgWithGenericMethod[T] {
    def plusOne[A](i: A): T
  }

  @autoFlatMap
  trait AlgWithVarArgsParameter[T] {
    def sum(xs: Int*): Int
    def generic[A](as: A*): T
  }

  implicit def eqForTestAlgebra[T: Eq]: Eq[TestAlgebra[T]] = Eq.by { algebra =>
    (
      algebra.abstractEffect _,
      algebra.concreteEffect _,
      algebra.abstractOther _,
      algebra.concreteOther _,
      algebra.withoutParams
    )
  }

  implicit def arbitraryTestAlgebra[T: Arbitrary](implicit cS: Cogen[String]): Arbitrary[TestAlgebra[T]] =
    Arbitrary {
      for {
        absEff <- Arbitrary.arbitrary[String => T]
        conEff <- Arbitrary.arbitrary[Option[String => T]]
        absOther <- Arbitrary.arbitrary[String => String]
        conOther <- Arbitrary.arbitrary[Option[String => String]]
        noParams <- Arbitrary.arbitrary[T]
      } yield new TestAlgebra[T] {
        override def abstractEffect(i: String): T = absEff(i)
        override def concreteEffect(a: String): T = conEff.getOrElse(super.concreteEffect(_))(a)
        override def abstractOther(a: String): String = absOther(a)
        override def concreteOther(a: String): String = conOther.getOrElse(super.concreteOther(_))(a)
        override def withoutParams: T = noParams
      }
    }
} 
Example 186
Source File: PointProp.scala    From chronicler   with Apache License 2.0 5 votes vote down vote up
package com.github.fsanaulla.chronicler.core.shared

import com.github.fsanaulla.chronicler.core.model._
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.FlatSpec
import org.scalatestplus.scalacheck.Checkers

class PointProp extends FlatSpec with Checkers {

  implicit val nonEmptyStringArb: Arbitrary[String] =
    Arbitrary(Gen.nonEmptyListOf[Char](Gen.alphaChar).map(_.mkString))

  implicit val arb: Arbitrary[Point] = Arbitrary {
    for {
      city   <- implicitly[Arbitrary[String]].arbitrary
      name   <- implicitly[Arbitrary[String]].arbitrary
      age    <- implicitly[Arbitrary[Int]].arbitrary
      adult  <- implicitly[Arbitrary[Boolean]].arbitrary
      weight <- implicitly[Arbitrary[Double]].arbitrary
      ts     <- implicitly[Arbitrary[Long]].arbitrary.filter(_ > 0)
    } yield {
      Point("test")
        .addTag("city", city)
        .addField("name", name)
        .addField("age", age)
        .addField("adult", adult)
        .addField("weight", weight)
        .addTimestamp(ts)
    }
  }

  private val sb = new StringBuilder()

  "Point" should "be correctly serialized" in check { p: Point =>
    val fields = p.fields
    val city   = p.tags.collectFirst { case InfluxTag(key, value) if key == "city" => value }
    val name   = fields.collectFirst { case StringField(key, value) if key == "name" => value }
    val age    = fields.collectFirst { case IntField(key, value) if key == "age" => value }
    val adult  = fields.collectFirst { case BooleanField(key, value) if key == "adult" => value }
    val weight = fields.collectFirst { case DoubleField(key, value) if key == "weight" => value }

    val result = sb
      .append("test,city=")
      .append(city.get)
      .append(" name=")
      .append("\"")
      .append(name.get)
      .append("\",")
      .append("age=")
      .append(age.get)
      .append("i,")
      .append("adult=")
      .append(adult.get)
      .append(",weight=")
      .append(weight.get)
      .append(" ")
      .append(p.time)
      .result()
    sb.clear()

    p.serialize == result
  }
} 
Example 187
Source File: uber_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package uber.api.yaml

import org.scalacheck.Gen
import org.scalacheck.Arbitrary
import play.api.libs.json.scalacheck.JsValueGenerators
import Arbitrary._
import java.util.UUID
import scala.math.BigDecimal
import de.zalando.play.controllers.ArrayWrapper

object Generators extends JsValueGenerators {
    

    
    def createDoubleGenerator = _generate(DoubleGenerator)
    def createActivitiesHistoryGenerator = _generate(ActivitiesHistoryGenerator)
    def createProfilePictureGenerator = _generate(ProfilePictureGenerator)
    def createErrorCodeGenerator = _generate(ErrorCodeGenerator)
    def createEstimatesTimeGetCustomer_uuidGenerator = _generate(EstimatesTimeGetCustomer_uuidGenerator)
    def createProductsGetResponses200Generator = _generate(ProductsGetResponses200Generator)
    def createPriceEstimateHigh_estimateGenerator = _generate(PriceEstimateHigh_estimateGenerator)
    def createEstimatesPriceGetResponses200Generator = _generate(EstimatesPriceGetResponses200Generator)
    def createActivitiesHistoryOptGenerator = _generate(ActivitiesHistoryOptGenerator)
    

    
    def DoubleGenerator = arbitrary[Double]
    def ActivitiesHistoryGenerator = Gen.option(ActivitiesHistoryOptGenerator)
    def ProfilePictureGenerator = Gen.option(arbitrary[String])
    def ErrorCodeGenerator = Gen.option(arbitrary[Int])
    def EstimatesTimeGetCustomer_uuidGenerator = Gen.option(arbitrary[UUID])
    def ProductsGetResponses200Generator = Gen.containerOf[List,Product](ProductGenerator)
    def PriceEstimateHigh_estimateGenerator = Gen.option(arbitrary[BigDecimal])
    def EstimatesPriceGetResponses200Generator = Gen.containerOf[List,PriceEstimate](PriceEstimateGenerator)
    def ActivitiesHistoryOptGenerator = _genList(ActivityGenerator, "csv")
    

    def createActivityGenerator = _generate(ActivityGenerator)
    def createPriceEstimateGenerator = _generate(PriceEstimateGenerator)
    def createProductGenerator = _generate(ProductGenerator)
    def createProfileGenerator = _generate(ProfileGenerator)
    def createActivitiesGenerator = _generate(ActivitiesGenerator)
    def createErrorGenerator = _generate(ErrorGenerator)


    def ActivityGenerator = for {
        uuid <- ProfilePictureGenerator
    } yield Activity(uuid)
    def PriceEstimateGenerator = for {
        low_estimate <- PriceEstimateHigh_estimateGenerator
        display_name <- ProfilePictureGenerator
        estimate <- ProfilePictureGenerator
        high_estimate <- PriceEstimateHigh_estimateGenerator
        product_id <- ProfilePictureGenerator
        currency_code <- ProfilePictureGenerator
        surge_multiplier <- PriceEstimateHigh_estimateGenerator
    } yield PriceEstimate(low_estimate, display_name, estimate, high_estimate, product_id, currency_code, surge_multiplier)
    def ProductGenerator = for {
        image <- ProfilePictureGenerator
        description <- ProfilePictureGenerator
        display_name <- ProfilePictureGenerator
        product_id <- ProfilePictureGenerator
        capacity <- ProfilePictureGenerator
    } yield Product(image, description, display_name, product_id, capacity)
    def ProfileGenerator = for {
        first_name <- ProfilePictureGenerator
        email <- ProfilePictureGenerator
        promo_code <- ProfilePictureGenerator
        last_name <- ProfilePictureGenerator
        picture <- ProfilePictureGenerator
    } yield Profile(first_name, email, promo_code, last_name, picture)
    def ActivitiesGenerator = for {
        offset <- ErrorCodeGenerator
        limit <- ErrorCodeGenerator
        count <- ErrorCodeGenerator
        history <- ActivitiesHistoryGenerator
    } yield Activities(offset, limit, count, history)
    def ErrorGenerator = for {
        code <- ErrorCodeGenerator
        message <- ProfilePictureGenerator
        fields <- ProfilePictureGenerator
    } yield Error(code, message, fields)

    def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample

    def _genList[T](gen: Gen[T], format: String): Gen[ArrayWrapper[T]] = for {
        items <- Gen.containerOf[List,T](gen)
    } yield ArrayWrapper(format)(items)
    
    
    
    
    implicit lazy val arbUUID: Arbitrary[UUID] = Arbitrary(Gen.uuid)
    

} 
Example 188
Source File: expanded_polymorphism_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package expanded

import org.scalacheck.Gen
import org.scalacheck.Arbitrary
import play.api.libs.json.scalacheck.JsValueGenerators
import Arbitrary._
import de.zalando.play.controllers.ArrayWrapper

object Generators extends JsValueGenerators {
    

    
    def createNullGenerator = _generate(NullGenerator)
    def createLongGenerator = _generate(LongGenerator)
    def createPetsGetLimitGenerator = _generate(PetsGetLimitGenerator)
    def createPetsGetTagsOptGenerator = _generate(PetsGetTagsOptGenerator)
    def createNewPetTagGenerator = _generate(NewPetTagGenerator)
    def createPetsGetResponses200Generator = _generate(PetsGetResponses200Generator)
    def createPetsGetTagsGenerator = _generate(PetsGetTagsGenerator)
    

    
    def NullGenerator = arbitrary[Null]
    def LongGenerator = arbitrary[Long]
    def PetsGetLimitGenerator = Gen.option(arbitrary[Int])
    def PetsGetTagsOptGenerator = _genList(arbitrary[String], "csv")
    def NewPetTagGenerator = Gen.option(arbitrary[String])
    def PetsGetResponses200Generator = Gen.containerOf[List,Pet](PetGenerator)
    def PetsGetTagsGenerator = Gen.option(PetsGetTagsOptGenerator)
    

    def createNewPetGenerator = _generate(NewPetGenerator)
    def createPetGenerator = _generate(PetGenerator)
    def createErrorGenerator = _generate(ErrorGenerator)


    def NewPetGenerator = for {
        name <- arbitrary[String]
        tag <- NewPetTagGenerator
    } yield NewPet(name, tag)
    def PetGenerator = for {
        name <- arbitrary[String]
        tag <- NewPetTagGenerator
        id <- arbitrary[Long]
    } yield Pet(name, tag, id)
    def ErrorGenerator = for {
        code <- arbitrary[Int]
        message <- arbitrary[String]
    } yield Error(code, message)

    def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample

    def _genList[T](gen: Gen[T], format: String): Gen[ArrayWrapper[T]] = for {
        items <- Gen.containerOf[List,T](gen)
    } yield ArrayWrapper(format)(items)
    
    
    
} 
Example 189
Source File: simple_petstore_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package simple_petstore_api_yaml

import org.scalacheck.Gen
import org.scalacheck.Arbitrary
import play.api.libs.json.scalacheck.JsValueGenerators
import Arbitrary._
import de.zalando.play.controllers.ArrayWrapper

object Generators extends JsValueGenerators {
    

    
    def createNullGenerator = _generate(NullGenerator)
    def createNewPetTagGenerator = _generate(NewPetTagGenerator)
    def createLongGenerator = _generate(LongGenerator)
    def createPetsGetLimitGenerator = _generate(PetsGetLimitGenerator)
    def createNewPetIdGenerator = _generate(NewPetIdGenerator)
    def createPetsGetTagsOptGenerator = _generate(PetsGetTagsOptGenerator)
    def createPetsGetResponses200Generator = _generate(PetsGetResponses200Generator)
    def createPetsGetTagsGenerator = _generate(PetsGetTagsGenerator)
    

    
    def NullGenerator = arbitrary[Null]
    def NewPetTagGenerator = Gen.option(arbitrary[String])
    def LongGenerator = arbitrary[Long]
    def PetsGetLimitGenerator = Gen.option(arbitrary[Int])
    def NewPetIdGenerator = Gen.option(arbitrary[Long])
    def PetsGetTagsOptGenerator = _genList(arbitrary[String], "csv")
    def PetsGetResponses200Generator = Gen.containerOf[List,Pet](PetGenerator)
    def PetsGetTagsGenerator = Gen.option(PetsGetTagsOptGenerator)
    

    def createErrorModelGenerator = _generate(ErrorModelGenerator)
    def createPetGenerator = _generate(PetGenerator)
    def createNewPetGenerator = _generate(NewPetGenerator)


    def ErrorModelGenerator = for {
        code <- arbitrary[Int]
        message <- arbitrary[String]
    } yield ErrorModel(code, message)
    def PetGenerator = for {
        id <- arbitrary[Long]
        name <- arbitrary[String]
        tag <- NewPetTagGenerator
    } yield Pet(id, name, tag)
    def NewPetGenerator = for {
        name <- arbitrary[String]
        id <- NewPetIdGenerator
        tag <- NewPetTagGenerator
    } yield NewPet(name, id, tag)

    def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample

    def _genList[T](gen: Gen[T], format: String): Gen[ArrayWrapper[T]] = for {
        items <- Gen.containerOf[List,T](gen)
    } yield ArrayWrapper(format)(items)
    
    
    
} 
Example 190
Source File: basic_polymorphism_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package basic_polymorphism_yaml

import org.scalacheck.Gen
import org.scalacheck.Arbitrary
import play.api.libs.json.scalacheck.JsValueGenerators
import Arbitrary._

object Generators extends JsValueGenerators {
    

    
    def createCatHuntingSkillGenerator = _generate(CatHuntingSkillGenerator)
    

    
    def CatHuntingSkillGenerator = Gen.oneOf(Seq(Clueless, Lazy, Adventurous, Aggressive))
    

    def createCatGenerator = _generate(CatGenerator)
    def createDogGenerator = _generate(DogGenerator)
    def createCatNDogGenerator = _generate(CatNDogGenerator)
    def createPetGenerator = _generate(PetGenerator)
    def createLabradorGenerator = _generate(LabradorGenerator)


    def CatGenerator = for {
        name <- arbitrary[String]
        petType <- arbitrary[String]
        huntingSkill <- CatHuntingSkillGenerator
    } yield Cat(name, petType, huntingSkill)
    def DogGenerator = for {
        name <- arbitrary[String]
        petType <- arbitrary[String]
        packSize <- arbitrary[Int]
    } yield Dog(name, petType, packSize)
    def CatNDogGenerator = for {
        name <- arbitrary[String]
        petType <- arbitrary[String]
        packSize <- arbitrary[Int]
        huntingSkill <- CatHuntingSkillGenerator
    } yield CatNDog(name, petType, packSize, huntingSkill)
    def PetGenerator = for {
        name <- arbitrary[String]
        petType <- arbitrary[String]
    } yield Pet(name, petType)
    def LabradorGenerator = for {
        name <- arbitrary[String]
        petType <- arbitrary[String]
        packSize <- arbitrary[Int]
        cuteness <- arbitrary[Int]
    } yield Labrador(name, petType, packSize, cuteness)

    def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample

    
    
    
} 
Example 191
Source File: KubernetesComponents.scala    From sbt-kubeyml   with MIT License 5 votes vote down vote up
package kubeyml.deployment

import kubeyml.protocol.NonEmptyString
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.ScalacheckShapeless._

trait KubernetesComponents {

  private def strOrEmpty: Gen[String] = Gen.oneOf(Gen.const(""), Gen.alphaNumStr)

  def nonEmptyParts(deploymentTestParts: DeploymentTestParts) = {
    import deploymentTestParts._
    Seq(namespace, dockerImage, serviceName, envName, metadataKey, metadataValue).forall(_.nonEmpty)
  }

  val highEmptyChance: Gen[DeploymentTestParts] =
    for {
      serviceName <- strOrEmpty
      namespace <- strOrEmpty
      metaKey <- strOrEmpty
      metaValue <- strOrEmpty
      dockerImage <- strOrEmpty
      envName <- strOrEmpty
      envValue <- strOrEmpty
      deploymentTestParts = DeploymentTestParts(serviceName, namespace, metaKey, metaValue, dockerImage, envName, envValue)
      if !nonEmptyParts(deploymentTestParts)
    } yield deploymentTestParts

  val lowEmptyChance: Gen[DeploymentTestParts] = for {
      serviceName <- Gen.alphaNumStr
      namespace <- Gen.alphaNumStr
      metaKey <- Gen.alphaNumStr
      metaValue <- Gen.alphaNumStr
      dockerImage <- Gen.alphaNumStr
      envName <- Gen.alphaNumStr
      envValue <- Gen.alphaNumStr
    } yield DeploymentTestParts(serviceName, namespace, metaKey, metaValue, dockerImage, envName, envValue)


  implicit val nonEmptyStringGen: Arbitrary[NonEmptyString] =
    Arbitrary(Gen.alphaStr.filterNot(_.isEmpty).map(NonEmptyString))

  val environmentVariableTestPartsGen: Gen[EnvironmentVariableTestParts] ={ for {
    envTestParts <- implicitly[Arbitrary[EnvironmentVariableTestParts]].arbitrary
    alphaNumRawValue <- Gen.alphaNumStr
  } yield (envTestParts.copy(rawValue = alphaNumRawValue))
  }.filterNot {
    case EnvironmentVariableTestParts(fieldPathName, _, secretEnvName, _, _, rawName, _) =>
      Seq(fieldPathName == secretEnvName, fieldPathName == rawName, secretEnvName == rawName)
        .fold(false)(_ || _)
  }

}


object KubernetesComponents extends KubernetesComponents

case class DeploymentTestParts(
      serviceName: String,
      namespace: String,
      metadataKey: String,
      metadataValue: String,
      dockerImage: String,
      envName: String,
      envValue: String
)

case class EnvironmentVariableTestParts(
   fieldPathName: NonEmptyString,
   fieldPathValue: NonEmptyString,
   secretEnvName: NonEmptyString,
   secretKey: NonEmptyString,
   secretName: NonEmptyString,
   rawName: NonEmptyString,
   rawValue: String
) 
Example 192
Source File: JsonLogEncodingTest.scala    From cedi-dtrace   with Apache License 2.0 5 votes vote down vote up
package com.ccadllc.cedi.dtrace
package logging

import cats.effect.{ IO, Effect }

import io.circe._
import io.circe.syntax._

import org.scalacheck.Arbitrary

import org.scalatest.wordspec.AnyWordSpec

import json.encoding._

class JsonLogEncodingTests extends AnyWordSpec with TestSupport {

  // format: OFF
  val calculateQuarterlySalesTraceContextJson = Json.obj(
    "where"           -> calculateQuarterlySalesTraceContext.system.data.allValues.asJson,
    "root"            -> calculateQuarterlySalesTraceContext.currentSpan.root.asJson,
    "trace-id"        -> calculateQuarterlySalesTraceContext.currentSpan.spanId.traceId.asJson,
    "span-id"         -> calculateQuarterlySalesTraceContext.currentSpan.spanId.spanId.asJson,
    "parent-id"       -> calculateQuarterlySalesTraceContext.currentSpan.spanId.parentSpanId.asJson,
    "span-name"       -> calculateQuarterlySalesTraceContext.currentSpan.spanName.value.asJson,
    "start-time"      -> calculateQuarterlySalesTraceContext.currentSpan.startTime.asJson,
    "span-success"    -> calculateQuarterlySalesTraceContext.currentSpan.failure.isEmpty.asJson,
    "failure-detail"  -> calculateQuarterlySalesTraceContext.currentSpan.failure.map(_.render).asJson,
    "span-duration"   -> calculateQuarterlySalesTraceContext.currentSpan.duration.toMicros.asJson,
    "notes"           -> Map(
      quarterlySalesUnitsNote.name.value        ->  quarterlySalesUnitsNoteValue.value.toString,
      quarterlySalesGoalReachedNote.name.value  ->  quarterlySalesGoalReachedNoteValue.value.toString,
      salesRegionNote.name.value                ->  salesRegionNoteValue.value,
      quarterlySalesTotalNote.name.value        ->  quarterlySalesTotalNoteValue.value.toString
    ).asJson
  )
  // format: ON

  implicit def traceArb[F[_]: Effect]: Arbitrary[TraceContext[F]] = Arbitrary(genTraceContext[F])

  "Trace" should { encodeGeneratedJson[TraceContext[IO]] }
  "Trace" should { encodeSpecificJson(calculateQuarterlySalesTraceContext, calculateQuarterlySalesTraceContextJson) }
} 
Example 193
Source File: TestSupport.scala    From cedi-dtrace   with Apache License 2.0 5 votes vote down vote up
package com.ccadllc.cedi.dtrace
package logging

import cats.effect.{ IO, Sync }

import io.circe._
import io.circe.syntax._

import org.scalacheck.Arbitrary

import org.scalatest.Suite
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

import shapeless.Lazy

trait TestSupport extends AnyWordSpecLike with Matchers with ScalaCheckPropertyChecks with TraceGenerators with TestData {
  self: Suite =>

  override def testEmitter[F[_]: Sync]: F[TraceSystem.Emitter[F]] = Sync[F].pure(LogEmitter.apply)

  val salesManagementSystem = TraceSystem(testSystemData, testEmitter[IO].unsafeRunSync, TraceSystem.realTimeTimer[IO])
  val calculateQuarterlySalesTraceContext = TraceContext(quarterlySalesCalculationSpan, true, salesManagementSystem)

  def encodeGeneratedJson[A: Arbitrary](implicit encoder: Lazy[Encoder[A]]): Unit = {
    implicit val e = encoder.value
    "encode arbitrary instances to JSON" in {
      forAll { (msg: A) => msg.asJson.noSpaces should not be (None) }
    }
  }
  def encodeSpecificJson[A](a: A, json: Json)(implicit encoder: Lazy[Encoder[A]]): Unit = {
    implicit val e = encoder.value
    "encode specific instance to JSON and ensure it matches expected" in { a.asJson shouldBe json }
  }
} 
Example 194
Source File: MoneyHeaderCodecTest.scala    From cedi-dtrace   with Apache License 2.0 5 votes vote down vote up
package com.ccadllc.cedi.dtrace
package interop
package money

import java.util.UUID

import org.scalacheck.Arbitrary
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

import MoneyHeaderCodec._

class MoneyHeaderCodecTest extends AnyWordSpec with Matchers with ScalaCheckPropertyChecks with TraceGenerators {

  implicit val arbitraryUUID: Arbitrary[UUID] = Arbitrary(genUUID)

  "the Money Header Codec" should {
    "decode correctly given any valid UUID for trace-Id and any valid long integers for parent and span ID" in {
      forAll { (traceIdValue: UUID, parentSpanIdValue: Long, spanIdValue: Long) =>
        val expectedSpanId = SpanId(traceIdValue, parentSpanIdValue, spanIdValue)
        val header = Header(
          HeaderName,
          Header.Value(s"$TraceIdHeader=$traceIdValue;$ParentIdHeader=$parentSpanIdValue;$SpanIdHeader=$spanIdValue"))
        val errorOrSpanId = headerCodec.decode(List(header))
        errorOrSpanId shouldBe Right(Header.Decoded(Some(expectedSpanId), true))
      }
    }
    "encode correctly for any valid UUID for trace-Id and any valid long integers for parent and span ID" in {
      forAll { (traceIdValue: UUID, parentSpanIdValue: Long, spanIdValue: Long) =>
        val expectedHeader = Header(
          HeaderName,
          Header.Value(s"$TraceIdHeader=$traceIdValue;$ParentIdHeader=$parentSpanIdValue;$SpanIdHeader=$spanIdValue"))
        val spanId = SpanId(traceIdValue, parentSpanIdValue, spanIdValue)
        val headers = headerCodec.encode(spanId)
        headers shouldBe List(expectedHeader)
      }
    }
    "round-trip correctly given any valid UUID for trace-Id and any valid long integers for parent and span ID" in {
      forAll { (traceIdValue: UUID, parentSpanIdValue: Long, spanIdValue: Long) =>
        val expectedSpanId = SpanId(traceIdValue, parentSpanIdValue, spanIdValue)
        val headers = headerCodec.encode(expectedSpanId)
        val errorOrSpanId = headerCodec.decode(headers)
        errorOrSpanId shouldBe Right(Header.Decoded(Some(expectedSpanId), true))
      }
    }
  }
} 
Example 195
Source File: GenValue.scala    From bosatsu   with Apache License 2.0 5 votes vote down vote up
package org.bykn.bosatsu

import org.scalacheck.{Arbitrary, Cogen, Gen}
import Value._

object GenValue {

  val cogenValue: Cogen[Value] =
    Cogen[Int].contramap { v: Value => v.hashCode }

  lazy val genProd: Gen[ProductValue] =
    Gen.lzy(Gen.oneOf(Gen.const(UnitValue),
      genValue.flatMap { v => genProd.map(ConsValue(v, _)) }))

  lazy val genValue: Gen[Value] = {
    val recur = Gen.lzy(genValue)
    val genEnumLike = Gen.choose(0, 1024).map(SumValue(_, UnitValue))

    val genSum =
      for {
        i <- Gen.choose(0, 1024)
        v <- genProd
      } yield SumValue(i, v)

    val genExt: Gen[Value] =
      Gen.oneOf(
        Gen.choose(Int.MinValue, Int.MaxValue).map(VInt(_)),
        Arbitrary.arbitrary[String].map(Str(_)))

    val genFn: Gen[FnValue] = {
      val fn: Gen[Value => Value] = Gen.function1(recur)(cogenValue)

      fn.map(FnValue(_))
    }

    Gen.oneOf(genEnumLike, genProd, genSum, genExt, genFn)
  }
} 
Example 196
Source File: GenJson.scala    From bosatsu   with Apache License 2.0 5 votes vote down vote up
package org.bykn.bosatsu

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

object GenJson {

  val genJsonNumber: Gen[Json.JNumberStr] = {
    def cat(gs: List[Gen[String]]): Gen[String] =
      gs match {
        case Nil => Gen.const("")
        case h :: tail => Gen.zip(h, cat(tail)).map { case (a, b) => a + b }
      }

    val digit09 = Gen.oneOf('0' to '9').map(_.toString)
    val digit19 = Gen.oneOf('1' to '9').map(_.toString)
    val digits = Gen.listOf(digit09).map(_.mkString)
    val digits1 = Gen.zip(digit09, Gen.listOf(digit09)).map { case (h, t) => (h :: t).mkString }
    val int = Gen.frequency(
      (1, Gen.const("0")),
      (20, Gen.zip(digit19, digits).map { case (h, t) => h + t }))
    val frac = digits1.map("." + _)

    def opt(g: Gen[String]): Gen[String] =
      Gen.oneOf(true, false).flatMap {
        case true => g
        case false => Gen.const("")
      }
    val exp = cat(List(Gen.oneOf("e", "E"), opt(Gen.oneOf("+", "-")), digits1))
    cat(List(opt(Gen.const("-")), int, opt(frac), opt(exp))).map(Json.JNumberStr(_))
  }

  def genJson(depth: Int): Gen[Json] = {
    val genString = Gen.listOf(Gen.choose(1.toChar, 127.toChar)).map(_.mkString)
    val str = genString.map(Json.JString(_))
    val nd1 = Arbitrary.arbitrary[Long].map { i => Json.JNumberStr(i.toString) }
    val nd2 = Arbitrary.arbitrary[Double].map { d => Json.JNumberStr(d.toString) }
    val nd3 = Arbitrary.arbitrary[Int].map { i => Json.JNumberStr(i.toString) }
    val b = Gen.oneOf(Json.JBool(true), Json.JBool(false))

    val d0 = Gen.oneOf(str, nd1, nd2, nd3, b, Gen.const(Json.JNull))
    if (depth <= 0) d0
    else {
      val recurse = Gen.lzy(genJson(depth - 1))
      val collectionSize = Gen.choose(0, depth * depth)
      val ary = collectionSize.flatMap(Gen.listOfN(_, recurse).map { l => Json.JArray(l.toVector) })
      val map = collectionSize.flatMap { sz =>
        Gen.listOfN(sz, Gen.zip(genString, recurse))
          .map { m => Json.JObject(m).normalize }
      }
      Gen.frequency((10, d0), (1, ary), (1, map))
    }
  }

  implicit val arbJson: Arbitrary[Json] =
    Arbitrary(Gen.choose(0, 4).flatMap(genJson(_)))

  implicit def shrinkJson(
    implicit ss: Shrink[String],
    sd: Shrink[Double]): Shrink[Json] =
    Shrink[Json](new Function1[Json, Stream[Json]] {
      def apply(j: Json): Stream[Json] = {
        import Json._
        j match {
          case JString(str) => ss.shrink(str).map(JString(_))
          case JNumberStr(nstr) => Stream.empty
          case JNull => Stream.empty
          case JBool(_) => Stream.empty
          case JArray(js) =>
            (0 until js.size).toStream.map { sz =>
              JArray(js.take(sz))
            }
          case JObject(mapList) =>
            (0 until mapList.size).toStream.map { sz =>
              JObject(mapList.take(sz))
            }
        }
      }
    })
} 
Example 197
Source File: GettingStartedWithFPSpec.scala    From exercises-fpinscala   with Apache License 2.0 5 votes vote down vote up
package fpinscalalib

import org.scalacheck.ScalacheckShapeless._
import org.scalacheck.{Arbitrary, Gen}
import org.scalaexercises.Test
import org.scalatest.refspec.RefSpec
import org.scalatestplus.scalacheck.Checkers
import shapeless._

class GettingStartedWithFPSpec extends RefSpec with Checkers {

  def `fibonacci asserts`() = {
    implicit val arb = Arbitrary {
      for {
        res0 <- Gen.choose(2, 10)
        res1 <- Gen.choose(2, 10)
      } yield res0 :: res1 :: HNil
    }

    check(Test.testSuccess(GettingStartedWithFPSection.fibAssert _, 0 :: HNil))
  }

  def `isSorted asserts`() =
    check(
      Test
        .testSuccess(GettingStartedWithFPSection.isSortedAssert _, true :: false :: true :: HNil)
    )

  def `currying asserts`() =
    check(Test.testSuccess(GettingStartedWithFPSection.curryAssert _, true :: true :: HNil))

  def `uncurrying asserts`() =
    check(Test.testSuccess(GettingStartedWithFPSection.uncurryAssert _, true :: true :: HNil))

  def `composing asserts`() =
    check(Test.testSuccess(GettingStartedWithFPSection.composeAssert _, false :: 2 :: 3 :: HNil))
} 
Example 198
Source File: StrictnessAndLazinessSpec.scala    From exercises-fpinscala   with Apache License 2.0 5 votes vote down vote up
package fpinscalalib

import fpinscalalib.customlib.laziness.Stream
import org.scalacheck.ScalacheckShapeless._
import org.scalacheck.{Arbitrary, Gen}
import org.scalaexercises.Test
import org.scalatest.refspec.RefSpec
import org.scalatestplus.scalacheck.Checkers
import shapeless.HNil

class StrictnessAndLazinessSpec extends RefSpec with Checkers {
  import Gen.{const, frequency, resize, sized}
  import Arbitrary._

  implicit def arbStreamAlternative[T](implicit a: Arbitrary[T]): Arbitrary[Stream[T]] =
    Arbitrary(
      sized(n =>
        frequency((n, resize(n / 2, arbitrary[T]).map(Stream(_))), (1, const(Stream.empty)))
      )
    )

  def `stream toList asserts`() =
    check(
      Test.testSuccess(StrictnessAndLazinessSection.streamToListAssert _, List(1, 2, 3) :: HNil)
    )

  def `stream take asserts`() =
    check(Test.testSuccess(StrictnessAndLazinessSection.streamTakeAssert _, 1 :: HNil))

  def `stream drop asserts`() =
    check(Test.testSuccess(StrictnessAndLazinessSection.streamDropAssert _, 1 :: HNil))

  def `stream takeWhile asserts`() =
    check(
      Test.testSuccess(
        StrictnessAndLazinessSection.streamTakeWhileAssert _,
        List(1, 2) :: List[Int]() :: HNil
      )
    )

  def `stream forAll asserts`() =
    check(Test.testSuccess(StrictnessAndLazinessSection.streamForAllAssert _, true :: HNil))

  def `stream trace asserts`() = {
    check(
      Test.testSuccess(
        StrictnessAndLazinessSection.streamTraceAssert _,
        11 :: Stream(2, 3, 4) :: Stream(3, 4) :: 13 :: Stream(4) :: 14 :: HNil
      )
    )
  }

  def `stream ones asserts`() = {
    check(
      Test.testSuccess(
        StrictnessAndLazinessSection.streamOnesAssert _,
        List(1, 1, 1, 1, 1) :: true :: true :: false :: HNil
      )
    )
  }

  def `stream integers asserts`() =
    check(Test.testSuccess(StrictnessAndLazinessSection.streamIntegersAssert _, 1 :: HNil))

  def `stream fibs asserts`() =
    check(Test.testSuccess(StrictnessAndLazinessSection.streamFibsAssert _, 0 :: 1 :: HNil))

  def `stream fibs via unfold asserts`() =
    check(
      Test.testSuccess(StrictnessAndLazinessSection.streamFibsViaUnfoldAssert _, 0 :: 1 :: HNil)
    )

  def `stream integers via unfold asserts`() =
    check(Test.testSuccess(StrictnessAndLazinessSection.streamIntegersAssert _, 1 :: HNil))

  def `stream ones via unfold asserts`() =
    StrictnessAndLazinessSection.streamOnesViaUnfoldAssert(Some((1, 1)))

  def `stream take via unfold asserts`() =
    StrictnessAndLazinessSection.streamTakeViaUnfold(0, 1)

  def `stream tails asserts`() =
    StrictnessAndLazinessSection.streamTailsAssert(1)

  def `stream scanRight asserts`() =
    check(
      Test
        .testSuccess(StrictnessAndLazinessSection.streamScanRightAssert _, List(6, 5, 3, 0) :: HNil)
    )
} 
Example 199
Source File: RadixTreeLawsCheck.scala    From radixtree   with Apache License 2.0 5 votes vote down vote up
package com.rklaehn.radixtree

import algebra.instances.all._
import org.scalacheck.Arbitrary
import org.scalatest.FunSuite
import org.typelevel.discipline.scalatest.Discipline
import Instances._
import algebra.laws.RingLaws
import cats.kernel.laws.discipline.MonoidTests

class RadixTreeLawsCheck extends FunSuite with Discipline {

  implicit def arbRadixTree[K: Arbitrary : RadixTree.Key, V: Arbitrary]: Arbitrary[RadixTree[K, V]] = Arbitrary {
    for {
      kvs ← Arbitrary.arbitrary[List[(K, V)]]
    } yield
    RadixTree(kvs: _*)
  }

  checkAll("MonoidTests[RadixTree[String, String]].monoid", MonoidTests[RadixTree[String, String]].monoid)
  checkAll("MonoidTests[RadixTree[Array[Byte], Array[Byte]]].monoid", MonoidTests[RadixTree[Array[Byte], Array[Byte]]].monoid)
  checkAll("RingLaws[RadixTree[String, Byte]].additiveMonoid", RingLaws[RadixTree[String, Short]].additiveMonoid)
  checkAll("RingLaws[RadixTree[Array[Byte], Int]].additiveMonoid", RingLaws[RadixTree[String, Int]].additiveMonoid)
} 
Example 200
Source File: RowCodecTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv
package scalaz

import _root_.scalaz._, Scalaz._
import _root_.scalaz.scalacheck.ScalazProperties._
import arbitrary._, equality._
import kantan.codecs.scalaz.laws.discipline.ScalazDisciplineSuite
import org.scalacheck.{Arbitrary, Gen}

class RowCodecTests extends ScalazDisciplineSuite {

  // Limits the size of rows to 10 - using the default size makes these tests prohibitively long in some contexts
  // (in particular, travis will timeout on the scala.js execution of these tests).
  implicit def arbSeq[A: Arbitrary]: Arbitrary[Seq[A]] = Arbitrary(Gen.listOfN(10, implicitly[Arbitrary[A]].arbitrary))

  // scalaz doesn't provide an Eq[Seq] instance, mostly because Seq isn't a very meaningfull type.
  implicit def seqEq[A: Equal]: Equal[Seq[A]] = Equal[List[A]].contramap(_.toList)

  checkAll("RowDecoder", monadError.laws[RowDecoder, DecodeError])
  checkAll("RowDecoder", plus.laws[RowDecoder])
  checkAll("RowEncoder", contravariant.laws[RowEncoder])

}