org.scalacheck.Cogen Scala Examples
The following examples show how to use org.scalacheck.Cogen.
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: FoldedTests.scala From aecor with MIT License | 5 votes |
package aecor.tests import aecor.data.Folded import cats.{ CoflatMap, Eval, Later, Monad, MonadError, Semigroupal } import cats.laws.{ ApplicativeLaws, CoflatMapLaws, FlatMapLaws, MonadLaws } import cats.laws.discipline._ import Folded.syntax._ import org.scalacheck.{ Arbitrary, Cogen } import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuiteLike import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.typelevel.discipline.scalatest.Discipline import cats.implicits._ class FoldedTests extends AnyFunSuiteLike with Matchers with ScalaCheckDrivenPropertyChecks with Discipline with StrictCatsEquality { implicit def arbitraryFolded[A](implicit A: Arbitrary[Option[A]]): Arbitrary[Folded[A]] = Arbitrary(A.arbitrary.map(_.map(_.next).getOrElse(impossible))) implicit def cogenFolded[A](implicit A: Cogen[Option[A]]): Cogen[Folded[A]] = A.contramap(_.toOption) checkAll("Folded[Int]", SemigroupalTests[Folded].semigroupal[Int, Int, Int]) checkAll("Cartesian[Folded]", SerializableTests.serializable(Semigroupal[Folded])) checkAll("Folded[Int]", CoflatMapTests[Folded].coflatMap[Int, Int, Int]) checkAll("CoflatMap[Folded]", SerializableTests.serializable(CoflatMap[Folded])) checkAll("Folded[Int]", MonadTests[Folded].monad[Int, Int, Int]) checkAll("Monad[Folded]", SerializableTests.serializable(Monad[Folded])) checkAll("Folded with Unit", MonadErrorTests[Folded, Unit].monadError[Int, Int, Int]) checkAll("MonadError[Folded, Unit]", SerializableTests.serializable(MonadError[Folded, Unit])) test("show") { impossible[Int].show should ===("Impossible") 1.next.show should ===("Next(1)") forAll { fs: Folded[String] => fs.show should ===(fs.toString) } } // The following tests check laws which are a different formulation of // laws that are checked. Since these laws are more or less duplicates of // existing laws, we don't check them for all types that have the relevant // instances. test("Kleisli associativity") { forAll { (l: Long, f: Long => Folded[Int], g: Int => Folded[Char], h: Char => Folded[String]) => val isEq = FlatMapLaws[Folded].kleisliAssociativity(f, g, h, l) isEq.lhs should ===(isEq.rhs) } } test("Cokleisli associativity") { forAll { (l: Folded[Long], f: Folded[Long] => Int, g: Folded[Int] => Char, h: Folded[Char] => String) => val isEq = CoflatMapLaws[Folded].cokleisliAssociativity(f, g, h, l) isEq.lhs should ===(isEq.rhs) } } test("applicative composition") { forAll { (fa: Folded[Int], fab: Folded[Int => Long], fbc: Folded[Long => Char]) => val isEq = ApplicativeLaws[Folded].applicativeComposition(fa, fab, fbc) isEq.lhs should ===(isEq.rhs) } } val monadLaws = MonadLaws[Folded] test("Kleisli left identity") { forAll { (a: Int, f: Int => Folded[Long]) => val isEq = monadLaws.kleisliLeftIdentity(a, f) isEq.lhs should ===(isEq.rhs) } } test("Kleisli right identity") { forAll { (a: Int, f: Int => Folded[Long]) => val isEq = monadLaws.kleisliRightIdentity(a, f) isEq.lhs should ===(isEq.rhs) } } test("map2Eval is lazy") { val bomb: Eval[Folded[Int]] = Later(sys.error("boom")) impossible[Int].map2Eval(bomb)(_ + _).value should ===(impossible[Int]) } }
Example 2
Source File: Cell.scala From kantan.csv with Apache License 2.0 | 5 votes |
package kantan.csv package laws import org.scalacheck.{Arbitrary, Cogen, Gen, Shrink} sealed trait Cell extends Product with Serializable { def value: String def encoded: String def map(f: String => String): Cell = Cell(f(value)) } object Cell { final case class Escaped private[Cell] (override val value: String) extends Cell { override def encoded = "\"" + value.replaceAll("\"", "\"\"") + "\"" } final case class NonEscaped private[Cell] (override val value: String) extends Cell { override def encoded = value } case object Empty extends Cell { override val value: String = "" override def encoded: String = "" } implicit val cellEncoder: CellEncoder[Cell] = CellEncoder.from(_.value) implicit val cellDecoder: CellDecoder[Cell] = CellDecoder.from(s => DecodeResult(Cell(s))) implicit val nonEscapedCellEncoder: CellEncoder[Cell.NonEscaped] = CellEncoder.from(_.value) private def containsEscapable(value: String): Boolean = value.exists(c => c == '"' || c == ',' || c == '\n' || c == '\r') def apply(value: String): Cell = if(value == "") Empty else if(containsEscapable(value)) Escaped(value) else NonEscaped(value) // - CSV character generators ---------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- val nonEscapedChar: Gen[Char] = Gen.oneOf((0x20 to 0x21) ++ (0x23 to 0x2B) ++ (0x2D to 0x7E)).map(_.toChar) val escapedChar: Gen[Char] = Gen.oneOf(',', '"', '\r', '\n') // - CSV cell generators --------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- val escaped: Gen[Escaped] = for { esc <- escapedChar str <- Gen.listOf(Gen.oneOf(nonEscapedChar, escapedChar)) i <- Gen.choose(0, str.size) } yield { val (h, t) = str.splitAt(i) Escaped((h ++ (esc :: t)).mkString) } val nonEscaped: Gen[NonEscaped] = Gen.nonEmptyListOf(nonEscapedChar).map(v => NonEscaped(v.mkString)) val cell: Gen[Cell] = Gen.oneOf(escaped, nonEscaped, Gen.const(Empty)) val nonEmptyCell: Gen[Cell] = Gen.oneOf(escaped, nonEscaped) implicit val arbEscaped: Arbitrary[Escaped] = Arbitrary(escaped) implicit val arbNonEscaped: Arbitrary[NonEscaped] = Arbitrary(nonEscaped) implicit val arbCell: Arbitrary[Cell] = Arbitrary(cell) implicit val cogenCell: Cogen[Cell] = Cogen[String].contramap(_.value) implicit val cellShrink: Shrink[Cell] = Shrink { case Empty => Shrink.shrinkAny.shrink(Empty) case Escaped(s) => Shrink.shrinkString.shrink(s).filter(containsEscapable).map(Escaped) case NonEscaped(s) => Shrink.shrinkString.shrink(s).filter(_.nonEmpty).map(NonEscaped) } // - CSV row generators ---------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- def rowOf[C <: Cell](gen: Gen[C]): Gen[List[C]] = Gen.nonEmptyListOf(gen) val row: Gen[List[Cell]] = for { // Makes sure we don't end up with the non-empty list of the empty cell, which is the empty list. head <- Gen.oneOf(escaped, nonEscaped) tail <- Gen.listOf(cell) } yield head :: tail implicit val arbEscapedRow: Arbitrary[List[Escaped]] = Arbitrary(rowOf(escaped)) implicit val arbNonEscapedRow: Arbitrary[List[NonEscaped]] = Arbitrary(rowOf(nonEscaped)) implicit val arbRow: Arbitrary[List[Cell]] = Arbitrary(row) implicit val rowShrink: Shrink[List[Cell]] = Shrink { case Nil => Shrink.shrinkAny.shrink(Nil) case (head :: Nil) => cellShrink.shrink(head).map(_ :: Nil) case (head :: tail) => Shrink.shrinkContainer[List, Cell].shrink(tail).map(t => head :: t) ++ cellShrink.shrink(head).map(_ :: tail) } // - CSV generators -------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- def csvOf[C <: Cell](gen: Gen[C]): Gen[List[List[C]]] = Gen.nonEmptyListOf(rowOf(gen)) implicit val arbEscapedCsv: Arbitrary[List[List[Escaped]]] = Arbitrary(csvOf(escaped)) implicit val arbNonEscapedCsv: Arbitrary[List[List[NonEscaped]]] = Arbitrary(csvOf(nonEscaped)) implicit val arbCsv: Arbitrary[List[List[Cell]]] = Arbitrary(Gen.nonEmptyListOf(row)) }
Example 3
Source File: package.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.scalaz import com.typesafe.config.{ ConfigValue, ConfigValueFactory } import org.scalacheck.{ Arbitrary, Cogen, Gen } import org.scalacheck.Arbitrary.{ arbitrary => arb } import pureconfig.{ ConfigConvert, ConfigReader, ConfigWriter, Derivation } import pureconfig.error._ import scala.collection.JavaConverters._ import scalaz.scalacheck.ScalaCheckBinding.GenMonad import scalaz.syntax.applicative._ package object arbitrary { private[this] val MaxConfigDepth = 3 private[this] val MaxCollectionLength = 3 private[this] def genAny(depth: Int): Gen[Any] = { val genScalar: Gen[Any] = Gen.oneOf( Gen.oneOf(true, false), Gen.choose(Double.MinValue, Double.MaxValue), Gen.alphaStr) def genList(depth: Int): Gen[List[Any]] = Gen.choose(0, MaxCollectionLength).flatMap(n => Gen.listOfN(n, Gen.lzy(genAny(depth - 1)))) def genMap(depth: Int): Gen[Map[String, Any]] = Gen.choose(0, MaxCollectionLength).flatMap(n => Gen.mapOfN(n, for { k <- Gen.alphaStr; v <- Gen.lzy(genAny(depth - 1)) } yield (k, v))) if (depth == 0) genScalar else Gen.frequency( 3 -> genScalar, 1 -> genList(depth).map(_.asJava), 1 -> genMap(depth).map(_.asJava)) } implicit val arbConfigValue: Arbitrary[ConfigValue] = Arbitrary(genAny(MaxConfigDepth).map(ConfigValueFactory.fromAnyRef)) implicit val cogenConfigValue: Cogen[ConfigValue] = Cogen[String].contramap[ConfigValue](_.render) private[this] val genFailureReason: Gen[FailureReason] = Gen.oneOf( ^^(Gen.alphaStr, Gen.alphaStr, Gen.alphaStr)(CannotConvert.apply), ^(Gen.posNum[Int], Gen.posNum[Int])(WrongSizeString.apply), ^(Gen.posNum[Int], Gen.posNum[Int])(WrongSizeList.apply), Gen.alphaStr.map(k => KeyNotFound.apply(k)), Gen.alphaStr.map(UnknownKey.apply)) implicit val arbConfigReaderFailures: Arbitrary[ConfigReaderFailures] = Arbitrary { for { n <- Gen.choose(1, MaxCollectionLength) l <- Gen.listOfN(n, genFailureReason).map(_.map(r => ConvertFailure(r, None, ""))) } yield ConfigReaderFailures(l.head, l.tail: _*) } implicit val cogenConfigReaderFailures: Cogen[ConfigReaderFailures] = Cogen[String].contramap[ConfigReaderFailures](_.toString) implicit def arbConfigReader[A: Arbitrary]: Arbitrary[ConfigReader[A]] = Arbitrary(arb[ConfigValue => Either[ConfigReaderFailures, A]].map(ConfigReader.fromFunction)) implicit def arbConfigWriter[A: Cogen]: Arbitrary[ConfigWriter[A]] = Arbitrary(arb[A => ConfigValue].map(ConfigWriter.fromFunction)) implicit def arbConfigConvert[A: Arbitrary: Cogen]: Arbitrary[ConfigConvert[A]] = Arbitrary { for { reader <- arb[ConfigReader[A]] writer <- arb[ConfigWriter[A]] } yield ConfigConvert.fromReaderAndWriter(Derivation.Successful(reader), Derivation.Successful(writer)) } }
Example 4
Source File: package.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.cats import scala.collection.JavaConverters._ import com.typesafe.config.{ Config, ConfigValue, ConfigValueFactory } import org.scalacheck.Arbitrary.{ arbitrary => arb } import org.scalacheck.{ Arbitrary, Cogen, Gen } import pureconfig._ import pureconfig.error.{ ConfigReaderFailures, ConvertFailure } package object arbitrary { private[this] val MaxConfigDepth = 3 private[this] val MaxCollSize = 3 private[this] def genAnyMapForConfig(maxDepth: Int): Gen[Map[String, Any]] = { Gen.choose(0, MaxCollSize).flatMap { sz => Gen.mapOfN(sz, for { k <- Gen.alphaStr; v <- Gen.lzy(genAnyForConfig(maxDepth - 1)) } yield (k, v)) } } private[this] def genAnyForConfig(maxDepth: Int): Gen[Any] = { val genScalar: Gen[Any] = Gen.oneOf( Gen.oneOf(true, false), Gen.choose(Int.MinValue, Int.MaxValue), Gen.choose(Double.MinValue, Double.MaxValue), Gen.alphaStr) def genList(maxDepth: Int): Gen[List[Any]] = Gen.choose(0, MaxCollSize).flatMap { sz => Gen.listOfN(sz, Gen.lzy(genAnyForConfig(maxDepth - 1))) } if (maxDepth == 0) genScalar else Gen.frequency( 3 -> genScalar, 1 -> genList(maxDepth).map(_.asJava), 1 -> genAnyMapForConfig(maxDepth).map(_.asJava)) } implicit val arbConfigValue: Arbitrary[ConfigValue] = Arbitrary { genAnyForConfig(MaxConfigDepth).map(ConfigValueFactory.fromAnyRef) } implicit val arbConfig: Arbitrary[Config] = Arbitrary { genAnyMapForConfig(MaxConfigDepth).map(_.asJava).map(ConfigValueFactory.fromMap(_).toConfig) } implicit val cogenConfigValue: Cogen[ConfigValue] = Cogen[String].contramap[ConfigValue](_.render) implicit val arbConfigReaderFailures: Arbitrary[ConfigReaderFailures] = Arbitrary { Gen.const(ConfigReaderFailures(ConvertFailure(EmptyTraversableFound("List"), None, ""))) } implicit val cogenConfigReaderFailures: Cogen[ConfigReaderFailures] = Cogen[String].contramap[ConfigReaderFailures](_.toString) implicit val arbConfigObjectSource: Arbitrary[ConfigObjectSource] = Arbitrary { Gen.either(arb[ConfigReaderFailures], arb[Config]).map(ConfigObjectSource(_)) } implicit def arbConfigReader[A: Arbitrary]: Arbitrary[ConfigReader[A]] = Arbitrary { arb[ConfigValue => ConfigReader.Result[A]].map(ConfigReader.fromFunction) } implicit def arbConfigWriter[A: Cogen]: Arbitrary[ConfigWriter[A]] = Arbitrary { arb[A => ConfigValue].map(ConfigWriter.fromFunction) } implicit def arbConfigConvert[A: Arbitrary: Cogen]: Arbitrary[ConfigConvert[A]] = Arbitrary { for { reader <- arb[ConfigReader[A]]; writer <- arb[ConfigWriter[A]] } yield ConfigConvert.fromReaderAndWriter(Derivation.Successful(reader), Derivation.Successful(writer)) } }
Example 5
Source File: TestAlgebras.scala From mainecoon with Apache License 2.0 | 5 votes |
package mainecoon package tests import cats.Eval import cats.kernel.Eq import org.scalacheck.{Arbitrary, Cogen} import scala.util.Try import cats.laws.discipline.eq._ import cats.implicits._ @finalAlg @autoFunctorK @autoSemigroupalK @autoProductNK trait SafeAlg[F[_]] { def parseInt(i: String): F[Int] def divide(dividend: Float, divisor: Float): F[Float] } object SafeAlg { implicit def eqForSafeAlg[F[_]](implicit eqFInt: Eq[F[Int]], eqFFloat: Eq[F[Float]]): Eq[SafeAlg[F]] = Eq.by[SafeAlg[F], (String => F[Int], (((Float, Float)) => F[Float]))] { p => ( (s: String) => p.parseInt(s), (pair: (Float, Float)) => p.divide(pair._1, pair._2)) } implicit def arbitrarySafeAlg[F[_]](implicit cS: Cogen[String], gF: Cogen[Float], FI: Arbitrary[F[Int]], FB: Arbitrary[F[Float]]): Arbitrary[SafeAlg[F]] = Arbitrary { for { f1 <- Arbitrary.arbitrary[String => F[Int]] f2 <- Arbitrary.arbitrary[(Float, Float) => F[Float]] } yield new SafeAlg[F] { def parseInt(i: String): F[Int] = f1(i) def divide(dividend: Float, divisor: Float): F[Float] = f2(dividend, divisor) } } } @finalAlg @autoInvariantK trait SafeInvAlg[F[_]] { def parseInt(i: F[String]): F[Int] } object SafeInvAlg { implicit def eqForSafeInvAlg[F[_]](implicit eqFInt: Eq[F[Int]], eqFString: Eq[F[String]], A: Arbitrary[F[String]]): Eq[SafeInvAlg[F]] = Eq.by[SafeInvAlg[F], F[String] => F[Int]] { p => (s: F[String]) => p.parseInt(s) } implicit def arbitrarySafeInvAlg[F[_]](implicit gF: Cogen[F[String]], FI: Arbitrary[F[Int]]): Arbitrary[SafeInvAlg[F]] = Arbitrary { for { f <- Arbitrary.arbitrary[F[String] => F[Int]] } yield new SafeInvAlg[F] { def parseInt(i: F[String]): F[Int] = f(i) } } } object Interpreters { implicit object tryInterpreter extends SafeAlg[Try] { def parseInt(s: String) = Try(s.toInt) def divide(dividend: Float, divisor: Float): Try[Float] = Try(dividend / divisor) } implicit object lazyInterpreter extends SafeAlg[Eval] { def parseInt(s: String): Eval[Int] = Eval.later(s.toInt) def divide(dividend: Float, divisor: Float): Eval[Float] = Eval.later(dividend / divisor) } }
Example 6
Source File: autoApplyKTests.scala From mainecoon with Apache License 2.0 | 5 votes |
package mainecoon package tests import cats.kernel.Eq import cats.laws.discipline.SerializableTests import mainecoon.laws.discipline.ApplyKTests import mainecoon.tests.autoApplyKTests.AutoApplyKTestAlg import util.Try class autoApplyKTests extends MainecoonTestSuite { implicit def eqT32 = AutoApplyKTestAlg.eqForAutoApplyKTestAlg[Tuple3K[Try, Option, List]#λ] //have to help scalac here checkAll("AutoApplyKTestAlg[Option]", ApplyKTests[AutoApplyKTestAlg].applyK[Try, Option, List, Int]) checkAll("ApplyK[ParseAlg]", SerializableTests.serializable(ApplyK[AutoApplyKTestAlg])) } object autoApplyKTests { import org.scalacheck.{Arbitrary, Cogen} import cats.laws.discipline.eq._ import cats.implicits._ @autoApplyK(autoDerivation = false) trait AutoApplyKTestAlg[F[_]] { def parseInt(i: String): F[Int] def divide(dividend: Float, divisor: Float): F[Float] } object AutoApplyKTestAlg { implicit def eqForAutoApplyKTestAlg[F[_]](implicit eqFInt: Eq[F[Int]], eqFFloat: Eq[F[Float]]): Eq[AutoApplyKTestAlg[F]] = Eq.by[AutoApplyKTestAlg[F], (String => F[Int], (((Float, Float)) => F[Float]))] { p => ( (s: String) => p.parseInt(s), (pair: (Float, Float)) => p.divide(pair._1, pair._2)) } implicit def arbitraryAutoApplyKTestAlg[F[_]](implicit cS: Cogen[String], gF: Cogen[Float], FI: Arbitrary[F[Int]], FB: Arbitrary[F[Float]]): Arbitrary[AutoApplyKTestAlg[F]] = Arbitrary { for { f1 <- Arbitrary.arbitrary[String => F[Int]] f2 <- Arbitrary.arbitrary[(Float, Float) => F[Float]] } yield new AutoApplyKTestAlg[F] { def parseInt(i: String): F[Int] = f1(i) def divide(dividend: Float, divisor: Float): F[Float] = f2(dividend, divisor) } } } }
Example 7
Source File: autoFunctorTests.scala From mainecoon with Apache License 2.0 | 5 votes |
package mainecoon package tests import cats.Functor import cats.kernel.Eq import cats.kernel.instances.string._ import cats.kernel.instances.tuple._ import cats.laws.discipline.eq._ import cats.laws.discipline.{FunctorTests, SerializableTests} import mainecoon.tests.autoFunctorTests._ import org.scalacheck.{Arbitrary, Cogen} class autoFunctorTests extends MainecoonTestSuite { 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 { @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 } @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 } implicit def eqForTestAlgebra[T](implicit eqT: Eq[T]): Eq[TestAlgebra[T]] = Eq.by { p => (p.abstractEffect: String => T) -> (p.concreteEffect: String => T) -> (p.abstractOther: String => String) -> (p.concreteOther: String => String) -> p.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]] withoutParameters <- 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 = withoutParameters } } }
Example 8
Source File: autoFlatMapTests.scala From mainecoon with Apache License 2.0 | 5 votes |
package mainecoon.tests import cats.FlatMap import cats.kernel.Eq import cats.kernel.instances.string._ import cats.kernel.instances.tuple._ import cats.laws.discipline.eq._ import cats.laws.discipline.{FlatMapTests, SerializableTests} import mainecoon.autoFlatMap import mainecoon.tests.autoFlatMapTests._ import org.scalacheck.{Arbitrary, Cogen} class autoFlatMapTests extends MainecoonTestSuite { 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 = AlgWithExtraTypeParamFloat.map(_.toDouble) doubleAlg.foo("big") should be(3d) } } object autoFlatMapTests { @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 } implicit def eqForTestAlgebra[T](implicit eqT: Eq[T]): Eq[TestAlgebra[T]] = Eq.by { p => (p.abstractEffect: String => T) -> (p.concreteEffect: String => T) -> (p.abstractOther: String => String) -> (p.concreteOther: String => String) -> p.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]] withoutParameters <- 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 = withoutParameters } } }
Example 9
Source File: OdinSpec.scala From odin with Apache License 2.0 | 5 votes |
package io.odin import java.time.LocalDateTime import cats.effect.{Clock, Timer} import cats.{Applicative, Eval} import io.odin.formatter.Formatter import io.odin.meta.Position import org.scalacheck.{Arbitrary, Cogen, Gen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.{Checkers, ScalaCheckDrivenPropertyChecks} import org.typelevel.discipline.Laws import scala.concurrent.duration.{FiniteDuration, TimeUnit} trait OdinSpec extends AnyFlatSpec with Matchers with Checkers with ScalaCheckDrivenPropertyChecks with EqInstances { def checkAll(name: String, ruleSet: Laws#RuleSet): Unit = { for ((id, prop) <- ruleSet.all.properties) it should (name + "." + id) in { check(prop) } } def zeroTimer[F[_]](implicit F: Applicative[F]): Timer[F] = new Timer[F] { def clock: Clock[F] = new Clock[F] { def realTime(unit: TimeUnit): F[Long] = F.pure(0L) def monotonic(unit: TimeUnit): F[Long] = F.pure(0L) } def sleep(duration: FiniteDuration): F[Unit] = ??? } val lineSeparator: String = System.lineSeparator() val nonEmptyStringGen: Gen[String] = Gen.nonEmptyListOf(Gen.alphaNumChar).map(_.mkString) val levelGen: Gen[Level] = Gen.oneOf(Level.Trace, Level.Debug, Level.Info, Level.Warn, Level.Error) implicit val levelArbitrary: Arbitrary[Level] = Arbitrary(levelGen) val positionGen: Gen[Position] = for { fileName <- nonEmptyStringGen enclosureName <- Gen.uuid.map(_.toString) packageName <- nonEmptyStringGen line <- Gen.posNum[Int] } yield { Position(fileName, enclosureName, packageName, line) } implicit val positionArbitrary: Arbitrary[Position] = Arbitrary(positionGen) val loggerMessageGen: Gen[LoggerMessage] = { val startTime = System.currentTimeMillis() for { level <- levelGen msg <- Gen.alphaNumStr context <- Gen.mapOfN(20, nonEmptyStringGen.flatMap(key => nonEmptyStringGen.map(key -> _))) exception <- Gen.option(Arbitrary.arbitrary[Throwable]) position <- positionGen threadName <- nonEmptyStringGen timestamp <- Gen.choose(0, startTime) } yield { LoggerMessage( level = level, message = Eval.now(msg), context = context, exception = exception, position = position, threadName = threadName, timestamp = timestamp ) } } implicit val loggerMessageArbitrary: Arbitrary[LoggerMessage] = Arbitrary(loggerMessageGen) implicit val cogenLoggerMessage: Cogen[LoggerMessage] = Cogen[LoggerMessage]((msg: LoggerMessage) => msg.level.hashCode().toLong + msg.message.value.hashCode().toLong) val formatterGen: Gen[Formatter] = Gen.oneOf(Formatter.default, Formatter.colorful) implicit val formatterArbitrary: Arbitrary[Formatter] = Arbitrary(formatterGen) val localDateTimeGen: Gen[LocalDateTime] = for { year <- Gen.choose(0, LocalDateTime.now().getYear) month <- Gen.choose(1, 12) day <- Gen.choose(1, 28) hour <- Gen.choose(0, 23) minute <- Gen.choose(0, 59) second <- Gen.choose(0, 59) } yield { LocalDateTime.of(year, month, day, hour, minute, second) } implicit val localDateTimeArbitrary: Arbitrary[LocalDateTime] = Arbitrary(localDateTimeGen) }
Example 10
Source File: partialOrder.scala From kittens with Apache License 2.0 | 5 votes |
package cats package derived import cats.instances.all._ import cats.kernel.laws.discipline.{PartialOrderTests, SerializableTests} import org.scalacheck.{Arbitrary, Cogen} class PartialOrderSuite extends KittensSuite { import PartialOrderSuite._ import TestDefns._ def testPartialOrder(context: String)( implicit iList: PartialOrder[IList[Int]], inner: PartialOrder[Inner], outer: PartialOrder[Outer], interleaved: PartialOrder[Interleaved[Int]], tree: PartialOrder[Tree[Int]], recursive: PartialOrder[Recursive], boxKeyValue: PartialOrder[Box[KeyValue]] ): Unit = { checkAll(s"$context.PartialOrder[IList[Int]]", PartialOrderTests[IList[Int]].partialOrder) checkAll(s"$context.PartialOrder[Inner]", PartialOrderTests[Inner].partialOrder) checkAll(s"$context.PartialOrder[Outer]", PartialOrderTests[Outer].partialOrder) checkAll(s"$context.PartialOrder[Interleaved[Int]]", PartialOrderTests[Interleaved[Int]].partialOrder) checkAll(s"$context.PartialOrder[Tree[Int]]", PartialOrderTests[Tree[Int]].partialOrder) checkAll(s"$context.PartialOrder[Recursive]", PartialOrderTests[Recursive].partialOrder) checkAll(s"$context.PartialOrder[Box[KeyValue]]", PartialOrderTests[Box[KeyValue]].partialOrder) checkAll(s"$context.PartialOrder is Serialiable", SerializableTests.serializable(PartialOrder[Tree[Int]])) test(s"$context.PartialOrder respects existing instances") { val x = Box(KeyValue("red", 1)) val y = Box(KeyValue("red", 2)) val z = Box(KeyValue("blue", 1)) assert(boxKeyValue.partialCompare(x, y) < 0) assert(boxKeyValue.partialCompare(y, z).isNaN) } } { import auto.partialOrder._ testPartialOrder("auto") } { import cached.partialOrder._ testPartialOrder("cached") } { import semiInstances._ testPartialOrder("semiauto") } } object PartialOrderSuite { import TestDefns._ object semiInstances { implicit val iList: PartialOrder[IList[Int]] = semiauto.partialOrder implicit val inner: PartialOrder[Inner] = semiauto.partialOrder implicit val outer: PartialOrder[Outer] = semiauto.partialOrder implicit val interleaved: PartialOrder[Interleaved[Int]] = semiauto.partialOrder implicit val tree: PartialOrder[Tree[Int]] = semiauto.partialOrder implicit val recursive: PartialOrder[Recursive] = semiauto.partialOrder implicit val boxKeyValue: PartialOrder[Box[KeyValue]] = semiauto.partialOrder } final case class KeyValue(key: String, value: Int) object KeyValue extends ((String, Int) => KeyValue) { implicit val arbitrary: Arbitrary[KeyValue] = Arbitrary(Arbitrary.arbitrary[(String, Int)].map(tupled)) implicit val cogen: Cogen[KeyValue] = Cogen[(String, Int)].contramap(unapply(_).get) implicit val partialOrder: PartialOrder[KeyValue] = PartialOrder.from((x, y) => if (x.key == y.key) x.value.toDouble - y.value.toDouble else Double.NaN) } }
Example 11
Source File: GenValue.scala From bosatsu with Apache License 2.0 | 5 votes |
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 12
Source File: package.scala From kafka4s with Apache License 2.0 | 5 votes |
package com.banno.kafka import org.scalacheck.{Arbitrary, Cogen, Gen} import org.apache.kafka.clients.producer.ProducerRecord import org.apache.kafka.clients.consumer.ConsumerRecord package object test { implicit def arbitraryProducerRecord[K: Arbitrary, V: Arbitrary] : Arbitrary[ProducerRecord[K, V]] = Arbitrary { for { t <- Gen.identifier k <- Arbitrary.arbitrary[K] v <- Arbitrary.arbitrary[V] } yield new ProducerRecord(t, k, v) } implicit def arbitraryConsumerRecord[K: Arbitrary, V: Arbitrary] : Arbitrary[ConsumerRecord[K, V]] = Arbitrary { for { t <- Gen.identifier p <- Gen.posNum[Int] o <- Gen.posNum[Long] k <- Arbitrary.arbitrary[K] v <- Arbitrary.arbitrary[V] } yield new ConsumerRecord(t, p, o, k, v) } //these things are necessary for EqSpec implicit def producerRecordCogen[K, V]: Cogen[ProducerRecord[K, V]] = Cogen(pr => pr.key.toString.length.toLong + pr.value.toString.length.toLong) // ¯\_(ツ)_/¯ implicit def consumerRecordCogen[K, V]: Cogen[ConsumerRecord[K, V]] = Cogen(cr => cr.key.toString.length.toLong + cr.value.toString.length.toLong) // ¯\_(ツ)_/¯ }
Example 13
Source File: MonixInstancesLawsSuite.scala From meow-mtl with MIT License | 5 votes |
package com.olegpy.meow.monix import cats.implicits._ import cats.effect.laws.discipline.arbitrary.genIO import cats.mtl.laws.discipline._ import minitest.SimpleTestSuite import minitest.laws.Checkers import org.typelevel.discipline.Laws import scala.concurrent.duration._ import cats.Eq import _root_.monix.eval.{Task, TaskLike, TaskLocal} import _root_.monix.execution.schedulers.TestScheduler import org.scalacheck.{Arbitrary, Cogen, Gen} object MonixInstancesLawsSuite extends SimpleTestSuite with Checkers { private def checkAll(name: String)(ruleSet: TestScheduler => Laws#RuleSet) = { implicit val ctx = TestScheduler() for ((id, prop) <- ruleSet(ctx).all.properties) test(name + "." + id) { ctx.tick(1.day) check(prop) } } implicit val options: Task.Options = Task.Options( autoCancelableRunLoops = true, localContextPropagation = true ) implicit val eqThrowable: Eq[Throwable] = Eq.allEqual implicit def eqTask[A](implicit eqA: Eq[A], ts: TestScheduler, options: Task.Options ): Eq[Task[A]] = Eq.instance { (lhs, rhs) => val lf = lhs.runToFutureOpt val rf = rhs.runToFutureOpt ts.tick(1.day) lf.value === rf.value } implicit def arbitraryTask[A: Arbitrary: Cogen] = Arbitrary(Gen.delay(genIO[A].map(TaskLike.fromIO(_)))) private def unsafeTaskLocal()(implicit ctx: TestScheduler) = { val f = TaskLocal(0).runToFutureOpt ctx.tick() f.value.get.get } checkAll("TaskLocal.runLocal") { implicit ctx => unsafeTaskLocal().runLocal(ev => ApplicativeLocalTests(ev).applicativeLocal[Int, String]) } checkAll("TaskLocal.runState") { implicit ctx => unsafeTaskLocal().runState(ev => MonadStateTests(ev).monadState[Int] ) } checkAll("TaskLocal.runTell") { implicit ctx => unsafeTaskLocal().runTell(ev => FunctorTellTests(ev).functorTell[Int] ) } }
Example 14
Source File: LTask.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect import cats.Eq import cats.effect.internals.Conversions import cats.effect.laws.util.TestContext import org.scalacheck.{Arbitrary, Cogen} import cats.syntax.flatMap._ import cats.syntax.functor._ import scala.concurrent.{ExecutionContext, ExecutionException, Future, Promise} import scala.util.{Either, Left, Right} implicit def effectInstance(implicit ec: ExecutionContext): Effect[LTask] = new Effect[LTask] { def pure[A](x: A): LTask[A] = LTask(_ => Future.successful(x)) def raiseError[A](e: Throwable): LTask[A] = LTask(_ => Future.failed(e)) def suspend[A](thunk: => LTask[A]): LTask[A] = LTask { implicit ec => Future.successful(()).flatMap(_ => thunk.run(ec)) } def async[A](k: (Either[Throwable, A] => Unit) => Unit): LTask[A] = LTask { _ => val p = Promise[A]() k(r => p.tryComplete(Conversions.toTry(r))) p.future } def asyncF[A](k: (Either[Throwable, A] => Unit) => LTask[Unit]): LTask[A] = LTask { implicit ec => val p = Promise[A]() k(r => p.tryComplete(Conversions.toTry(r))).run(ec) p.future } def runAsync[A](fa: LTask[A])(cb: Either[Throwable, A] => IO[Unit]): SyncIO[Unit] = SyncIO(fa.run(ec).onComplete { r => cb(Conversions.toEither(r)).unsafeRunAsyncAndForget() }) def flatMap[A, B](fa: LTask[A])(f: A => LTask[B]): LTask[B] = LTask { implicit ec => Future.successful(()).flatMap { _ => fa.run(ec).flatMap { a => f(a).run(ec) } } } def tailRecM[A, B](a: A)(f: A => LTask[Either[A, B]]): LTask[B] = flatMap(f(a)) { case Left(a) => tailRecM(a)(f) case Right(b) => pure(b) } def handleErrorWith[A](fa: LTask[A])(f: Throwable => LTask[A]): LTask[A] = LTask { implicit ec => Future.successful(()).flatMap { _ => fa.run(ec).recoverWith { case err: ExecutionException if err.getCause ne null => f(err.getCause).run(ec) case err => f(err).run(ec) } } } def bracketCase[A, B]( acquire: LTask[A] )(use: A => LTask[B])(release: (A, ExitCase[Throwable]) => LTask[Unit]): LTask[B] = for { a <- acquire etb <- attempt(use(a)) _ <- release(a, etb match { case Left(e) => ExitCase.error[Throwable](e) case Right(_) => ExitCase.complete }) b <- rethrow(pure(etb)) } yield b } }
Example 15
Source File: ReadLawsCheck.scala From laserdisc with MIT License | 5 votes |
package laserdisc package protocol import cats.laws.discipline.{ContravariantTests, MonadTests, SerializableTests} import cats.{Contravariant, Eq, Monad} import munit.DisciplineSuite import org.scalacheck.Gen.chooseNum import org.scalacheck.{Arbitrary, Cogen, Gen} final class ReadLawsCheck extends DisciplineSuite with LawsCheckSettings with Implicits { import ReadInstances._ checkAll("Read[Num, *]", MonadTests[Read[Num, *]].stackUnsafeMonad[Long, String, Long]) checkAll("Monad[Read[Num, *]]", SerializableTests.serializable(Monad[Read[Num, *]])) checkAll("Read[*, Long]", ContravariantTests[Read[*, Long]].contravariant[Str, Num, Str]) checkAll("Contravariant[Read[*, Long]]", SerializableTests.serializable(Contravariant[Read[*, Long]])) } private[protocol] sealed trait Implicits { implicit val genNum: Gen[Num] = chooseNum(0L, Long.MaxValue) map Num.apply implicit val genStr: Gen[Str] = Gen.alphaNumStr map Str.apply implicit val genListOfNum: Gen[List[Num]] = Gen.listOfN(500, genNum) map (_.distinct) implicit val genListOfStr: Gen[List[Str]] = Gen.listOfN(500, genStr) map (_.distinct) implicit def arbNum(implicit ev: Gen[Num]): Arbitrary[Num] = Arbitrary(ev) implicit def arbStr(implicit ev: Gen[Str]): Arbitrary[Str] = Arbitrary(ev) implicit val cogenNum: Cogen[Num] = Cogen(_.value) implicit val cogenStr: Cogen[Str] = Cogen(_.value.length.toLong) implicit def arbReadNum(implicit ev: Arbitrary[Long]): Arbitrary[Read[Num, Long]] = Arbitrary(ev.arbitrary map Read.const) implicit def arbReadStr(implicit ev: Arbitrary[Long]): Arbitrary[Read[Str, Long]] = Arbitrary(ev.arbitrary map Read.const) implicit def arbReadNumString(implicit ev: Arbitrary[Num]): Arbitrary[Read[Num, String]] = Arbitrary(ev.arbitrary map (n => Read.const(n.value.toString))) implicit def arbReadNumStringFun(implicit ev: Arbitrary[Num]): Arbitrary[Read[Num, Long => String]] = Arbitrary(ev.arbitrary map (l => Read.const(_ => l.value.toString))) implicit def arbReadNumNumFun(implicit ev: Arbitrary[String]): Arbitrary[Read[Num, String => Long]] = Arbitrary(ev.arbitrary map (s => Read.const(_ => s.length.toLong))) implicit def eqReadTup[A, B, C, D](implicit ga: Gen[List[A]], eb: Eq[B], ec: Eq[C], ed: Eq[D]): Eq[Read[A, (B, C, D)]] = (x: ==>[A, (B, C, D)], y: ==>[A, (B, C, D)]) => { val as = ga.sample.get as.forall { a => (x.read(a), y.read(a)) match { case (Right((b1, c1, d1)), Right((b2, c2, d2))) => eb.eqv(b1, b2) && ec.eqv(c1, c2) && ed.eqv(d1, d2) case (Left(e1), Left(e2)) => e1.message == e2.message case _ => false } } } implicit def eqRead[A, B](implicit ga: Gen[List[A]], eb: Eq[B]): Eq[Read[A, B]] = (x: A ==> B, y: A ==> B) => { val as = ga.sample.get as.forall { a => (x.read(a), y.read(a)) match { case (Right(b1), Right(b2)) => eb.eqv(b1, b2) case (Left(e1), Left(e2)) => e1.message == e2.message case _ => false } } } }
Example 16
Source File: NewtsSuite.scala From newts with Apache License 2.0 | 5 votes |
package newts import cats.instances.AllInstances import newts.syntax.AllSyntax import org.scalacheck.{Arbitrary, Cogen} import org.scalacheck.Arbitrary.arbitrary import org.scalatest.prop.GeneratorDrivenPropertyChecks import org.scalatest.{FunSuite, Matchers} import org.typelevel.discipline.scalatest.Discipline trait NewtsSuite extends FunSuite with Matchers with GeneratorDrivenPropertyChecks with Discipline with AllSyntax with AllInstances with cats.syntax.AllSyntax with ArbitraryInstances trait ArbitraryInstances { def arbNewtype[S, A: Arbitrary](implicit newtype: Newtype.Aux[S, A]): Arbitrary[S] = Arbitrary(arbitrary[A].map(newtype.wrap)) def cogenNewtype[S, A: Cogen](implicit newtype: Newtype.Aux[S, A]): Cogen[S] = Cogen[A].contramap(newtype.unwrap) implicit val allArbitrary: Arbitrary[All] = arbNewtype[All, Boolean] implicit val anyArbitrary: Arbitrary[Any] = arbNewtype[Any, Boolean] implicit def multArbitrary[A:Arbitrary]: Arbitrary[Mult[A]] = arbNewtype[Mult[A], A] implicit def dualArbitrary[A: Arbitrary]: Arbitrary[Dual[A]] = arbNewtype[Dual[A], A] implicit def firstArbitrary[A: Arbitrary]: Arbitrary[First[A]] = arbNewtype[First[A], A] implicit def lastArbitrary[A: Arbitrary]: Arbitrary[Last[A]] = arbNewtype[Last[A], A] implicit def firstOptionArbitrary[A: Arbitrary]: Arbitrary[FirstOption[A]] = arbNewtype[FirstOption[A], Option[A]] implicit def lastOptionArbitrary[A: Arbitrary]: Arbitrary[LastOption[A]] = arbNewtype[LastOption[A], Option[A]] implicit def minArbitrary[A: Arbitrary]: Arbitrary[Min[A]] = arbNewtype[Min[A], A] implicit def maxArbitrary[A: Arbitrary]: Arbitrary[Max[A]] = arbNewtype[Max[A], A] implicit def zipListArbitrary[A: Arbitrary]: Arbitrary[ZipList[A]] = arbNewtype[ZipList[A], List[A]] implicit def backwardsArbitrary[F[_], A](implicit ev: Arbitrary[F[A]]): Arbitrary[Backwards[F, A]] = arbNewtype[Backwards[F, A], F[A]] implicit def reverseArbitrary[F[_], A](implicit ev: Arbitrary[F[A]]): Arbitrary[Reverse[F, A]] = arbNewtype[Reverse[F, A], F[A]] implicit val allCogen: Cogen[All] = cogenNewtype[All, Boolean] implicit val anyCogen: Cogen[Any] = cogenNewtype[Any, Boolean] implicit def multCogen[A: Cogen]: Cogen[Mult[A]] = cogenNewtype[Mult[A], A] implicit def dualCogen[A: Cogen]: Cogen[Dual[A]] = cogenNewtype[Dual[A], A] implicit def firstCogen[A: Cogen]: Cogen[First[A]] = cogenNewtype[First[A], A] implicit def lastCogen[A: Cogen]: Cogen[Last[A]] = cogenNewtype[Last[A], A] implicit def firstOptionCogen[A: Cogen]: Cogen[FirstOption[A]] = cogenNewtype[FirstOption[A], Option[A]] implicit def lastOptionCogen[A: Cogen] : Cogen[LastOption[A]] = cogenNewtype[LastOption[A], Option[A]] implicit def minOptionCogen[A: Cogen] : Cogen[Min[A]] = cogenNewtype[Min[A], A] implicit def maxOptionCogen[A: Cogen] : Cogen[Max[A]] = cogenNewtype[Max[A], A] implicit def zipListCogen[A: Cogen]: Cogen[ZipList[A]] = cogenNewtype[ZipList[A], List[A]] implicit def backwardsCogen[F[_], A](implicit ev: Cogen[F[A]]): Cogen[Backwards[F, A]] = cogenNewtype[Backwards[F, A], F[A]] implicit def reverseCogen[F[_], A](implicit ev: Cogen[F[A]]): Cogen[Reverse[F, A]] = cogenNewtype[Reverse[F, A], F[A]] }
Example 17
Source File: laws.scala From newts with Apache License 2.0 | 5 votes |
package newts.internal import cats.kernel.Eq import cats.kernel.laws.OrderLaws import cats.kernel.laws.discipline.OrderTests import cats.laws._ import cats.laws.discipline._ import cats.syntax.order._ import org.scalacheck.{Arbitrary, Cogen} import org.scalacheck.Prop.forAll object laws { trait MaxBoundedLaws[A] extends OrderLaws[A] { override implicit def E: MaxBounded[A] def maxValue(a: A): IsEq[A] = (E.maxValue max a) <-> E.maxValue } object MaxBoundedLaws { def apply[A](implicit ev: MaxBounded[A]): MaxBoundedLaws[A] = new MaxBoundedLaws[A] { def E: MaxBounded[A] = ev } } trait MinBoundedLaws[A] extends OrderLaws[A] { override implicit def E: MinBounded[A] def maxValue(a: A): IsEq[A] = (E.minValue min a) <-> E.minValue } object MinBoundedLaws { def apply[A](implicit ev: MinBounded[A]): MinBoundedLaws[A] = new MinBoundedLaws[A] { def E: MinBounded[A] = ev } } object discipline { trait MaxBoundedTests[A] extends OrderTests[A] { override def laws: MaxBoundedLaws[A] def maxBounded(implicit arbA: Arbitrary[A], arbF: Arbitrary[A => A], eqOA: Eq[Option[A]], eqA: Eq[A]): RuleSet = new DefaultRuleSet( "maxBounded", Some(order), "maxValue" -> forAll(laws.maxValue _) ) } object MaxBoundedTests { def apply[A: MaxBounded]: MaxBoundedTests[A] = new MaxBoundedTests[A] { def laws: MaxBoundedLaws[A] = MaxBoundedLaws[A] } } trait MinBoundedTests[A] extends OrderTests[A] { override def laws: MinBoundedLaws[A] def minBounded(implicit arbA: Arbitrary[A], arbF: Arbitrary[A => A], eqOA: Eq[Option[A]], eqA: Eq[A]): RuleSet = new DefaultRuleSet( "minBounded", Some(order), "minValue" -> forAll(laws.maxValue _) ) } object MinBoundedTests { def apply[A: MinBounded]: MinBoundedTests[A] = new MinBoundedTests[A] { def laws: MinBoundedLaws[A] = MinBoundedLaws[A] } } } }
Example 18
Source File: catzSpecZStreamBase.scala From interop-cats with Apache License 2.0 | 5 votes |
package zio.stream.interop import cats.Eq import cats.effect.laws.util.TestContext import cats.implicits._ import org.scalacheck.{ Arbitrary, Cogen, Gen } import zio.interop.catz.taskEffectInstance import zio.interop.catzSpecBase import zio.stream._ import zio.{ Chunk, ZIO } private[interop] trait catzSpecZStreamBase extends catzSpecBase with catzSpecZStreamBaseLowPriority with GenStreamInteropCats { implicit def chunkEq[A](implicit ev: Eq[A]): Eq[Chunk[A]] = (x: Chunk[A], y: Chunk[A]) => x.corresponds(y)(ev.eqv) implicit def zstreamEqStream[E: Eq, A: Eq](implicit tc: TestContext): Eq[Stream[E, A]] = Eq.by(_.either) implicit def zstreamEqUStream[A: Eq](implicit tc: TestContext): Eq[Stream[Nothing, A]] = Eq.by(ustream => taskEffectInstance.toIO(ustream.runCollect.sandbox.either)) implicit def zstreamEqParIO[E: Eq, A: Eq](implicit tc: TestContext): Eq[ParStream[Any, E, A]] = Eq.by(Par.unwrap(_)) implicit def zstreamArbitrary[R: Cogen, E: Arbitrary: Cogen, A: Arbitrary: Cogen]: Arbitrary[ZStream[R, E, A]] = Arbitrary(Arbitrary.arbitrary[R => Stream[E, A]].map(ZStream.fromEffect(ZIO.environment[R]).flatMap(_))) implicit def streamArbitrary[E: Arbitrary: Cogen, A: Arbitrary: Cogen]: Arbitrary[Stream[E, A]] = Arbitrary(Gen.oneOf(genStream[E, A], genLikeTrans(genStream[E, A]), genIdentityTrans(genStream[E, A]))) implicit def zstreamParArbitrary[R, E: Arbitrary: Cogen, A: Arbitrary: Cogen]: Arbitrary[ParStream[R, E, A]] = Arbitrary(Arbitrary.arbitrary[Stream[E, A]].map(Par.apply)) } private[interop] trait catzSpecZStreamBaseLowPriority { self: catzSpecZStreamBase => implicit def zstreamEq[R: Arbitrary, E: Eq, A: Eq](implicit tc: TestContext): Eq[ZStream[R, E, A]] = { def run(r: R, zstream: ZStream[R, E, A]) = taskEffectInstance.toIO(zstream.runCollect.provide(r).either) Eq.instance( (stream1, stream2) => Arbitrary.arbitrary[R].sample.fold(false)(r => catsSyntaxEq(run(r, stream1)) eqv run(r, stream2)) ) } }
Example 19
Source File: catzSpec.scala From interop-cats with Apache License 2.0 | 5 votes |
package zio.stream.interop import cats.implicits._ import cats.laws.discipline._ import org.scalacheck.{ Arbitrary, Cogen, Gen } import zio.stream.interop.catz._ import zio.stream._ class catzSpec extends catzSpecZStreamBase with GenStreamInteropCats { def genUStream[A: Arbitrary]: Gen[Stream[Nothing, A]] = Gen.oneOf(genSuccess[Nothing, A], genIdentityTrans(genSuccess[Nothing, A])) checkAllAsync( "MonadError[Stream[Int, ?]]", implicit tc => MonadErrorTests[Stream[Int, ?], Int].monadError[Int, Int, Int] ) checkAllAsync( "Parallel[Stream[Throwable, ?]]", implicit tc => ParallelTests[Stream[Throwable, ?], ParStream[Any, Throwable, ?]].parallel[Int, Int] ) checkAllAsync("MonoidK[Stream[Int, ?]]", implicit tc => MonoidKTests[Stream[Int, ?]].monoidK[Int]) checkAllAsync( "SemigroupK[Stream[Option[Unit], ?]]", implicit tc => SemigroupKTests[Stream[Option[Unit], ?]].semigroupK[Int] ) checkAllAsync( "SemigroupK[Stream[Throwable, ?]]", implicit tc => SemigroupKTests[Stream[Throwable, ?]].semigroupK[Int] ) checkAllAsync("Bifunctor[Stream]", implicit tc => BifunctorTests[Stream].bifunctor[Int, Int, Int, Int, Int, Int]) checkAllAsync( "Monad[Stream[Nothing, ?]]", { implicit tc => implicit def streamArbitrary[A: Arbitrary: Cogen]: Arbitrary[Stream[Nothing, A]] = Arbitrary(genUStream[A]) MonadTests[Stream[Nothing, ?]].apply[Int, Int, Int] } ) checkAllAsync( "ArrowChoice[ZStream]", implicit tc => ArrowChoiceTests[ZStream[*, Int, *]].arrowChoice[Int, Int, Int, Int, Int, Int] ) object summoningInstancesTest { import cats._ Alternative[ZStream[String, Throwable, ?]] MonadError[ZStream[String, Throwable, ?], Throwable] Monad[ZStream[String, Throwable, ?]] Applicative[ZStream[String, Throwable, ?]] Functor[ZStream[String, Throwable, ?]] SemigroupK[ZStream[String, Throwable, ?]] Apply[ZStream[Any, Nothing, ?]] } }
Example 20
Source File: CacheTests.scala From dagon with Apache License 2.0 | 5 votes |
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 21
Source File: PackageSpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.scalacheck import eu.timepit.refined.api.Refined import eu.timepit.refined.numeric.Positive import eu.timepit.refined.types.all._ import org.scalacheck.{Cogen, Prop, Properties} class PackageSpec extends Properties("Package") { // this is just copied from core since core’s test configuration is built for scalacheck 1.14 only def wellTyped[A](body: => A): Prop = Prop.secure { body true } property("Cogen[Short Refined Positive]") = wellTyped(Cogen[Short Refined Positive]) property("Cogen[LowerCaseChar]") = wellTyped(Cogen[LowerCaseChar]) property("Cogen[NonEmptyString]") = wellTyped(Cogen[NonEmptyString]) property("Cogen[PosInt]") = wellTyped(Cogen[PosInt]) }
Example 22
Source File: ScalacheckInstances.scala From sup with Apache License 2.0 | 5 votes |
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 23
Source File: CogenDerivation.scala From magnolify with Apache License 2.0 | 5 votes |
package magnolify.scalacheck.semiauto import magnolia._ import org.scalacheck.Cogen import scala.language.experimental.macros object CogenDerivation { type Typeclass[T] = Cogen[T] def combine[T](caseClass: ReadOnlyCaseClass[Typeclass, T]): Typeclass[T] = Cogen { (seed, t) => caseClass.parameters.foldLeft(seed) { (seed, p) => // inject index to distinguish cases like `(Some(false), None)` and `(None, Some(0))` val s = Cogen.cogenInt.perturb(seed, p.index) p.typeclass.perturb(s, p.dereference(t)) } } def dispatch[T](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = Cogen { (seed, t: T) => sealedTrait.dispatch(t) { sub => // inject index to distinguish case objects instances val s = Cogen.cogenInt.perturb(seed, sub.index) sub.typeclass.perturb(s, sub.cast(t)) } } implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T] }
Example 24
Source File: LocalDateTimeTests.scala From dtc with Apache License 2.0 | 5 votes |
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 25
Source File: JVMZonedDateTimeTests.scala From dtc with Apache License 2.0 | 5 votes |
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 26
Source File: MomentZonedDateTimeTests.scala From dtc with Apache License 2.0 | 5 votes |
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 27
Source File: JSDateTests.scala From dtc with Apache License 2.0 | 5 votes |
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 28
Source File: HCacheTests.scala From dagon with Apache License 2.0 | 5 votes |
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 29
Source File: reftype.scala From refined with MIT License | 5 votes |
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 30
Source File: arbitrary.scala From catbird with Apache License 2.0 | 5 votes |
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 31
Source File: TermTests.scala From liberator with MIT License | 5 votes |
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 32
Source File: TestInstances.scala From scala-steward with Apache License 2.0 | 5 votes |
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 33
Source File: autoBifunctorTests.scala From cats-tagless with Apache License 2.0 | 5 votes |
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 34
Source File: autoProfunctorTests.scala From cats-tagless with Apache License 2.0 | 5 votes |
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 35
Source File: autoContravariantKTests.scala From cats-tagless with Apache License 2.0 | 5 votes |
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 36
Source File: autoFunctorTests.scala From cats-tagless with Apache License 2.0 | 5 votes |
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 37
Source File: autoFlatMapTests.scala From cats-tagless with Apache License 2.0 | 5 votes |
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 } } }