cats.kernel.Eq Scala Examples

The following examples show how to use cats.kernel.Eq. 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: ConfiguredJsonCodecWithKeySuite.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras

import cats.kernel.Eq
import io.circe.{ Decoder, Encoder }
import io.circe.literal._
import io.circe.testing.CodecTests
import org.scalacheck.{ Arbitrary, Gen }
import org.scalacheck.Arbitrary.arbitrary

object ConfiguredJsonCodecWithKeySuite {
  implicit val customConfig: Configuration =
    Configuration.default.withSnakeCaseMemberNames.withDefaults.withDiscriminator("type").withSnakeCaseConstructorNames

  @ConfiguredJsonCodec
  sealed trait ConfigExampleBase
  case class ConfigExampleFoo(thisIsAField: String, a: Int = 0, @JsonKey("myField") b: Double) extends ConfigExampleBase

  object ConfigExampleFoo {
    implicit val eqConfigExampleFoo: Eq[ConfigExampleFoo] = Eq.fromUniversalEquals
    val genConfigExampleFoo: Gen[ConfigExampleFoo] = for {
      thisIsAField <- arbitrary[String]
      a <- arbitrary[Int]
      b <- arbitrary[Double]
    } yield ConfigExampleFoo(thisIsAField, a, b)
    implicit val arbitraryConfigExampleFoo: Arbitrary[ConfigExampleFoo] = Arbitrary(genConfigExampleFoo)
  }

  object ConfigExampleBase {
    implicit val eqConfigExampleBase: Eq[ConfigExampleBase] = Eq.fromUniversalEquals
    val genConfigExampleBase: Gen[ConfigExampleBase] =
      ConfigExampleFoo.genConfigExampleFoo
    implicit val arbitraryConfigExampleBase: Arbitrary[ConfigExampleBase] = Arbitrary(genConfigExampleBase)
  }
}

class ConfiguredJsonCodecWithKeySuite extends CirceSuite {
  import ConfiguredJsonCodecWithKeySuite._

  checkLaws("Codec[ConfigExampleBase]", CodecTests[ConfigExampleBase].codec)

  "ConfiguredJsonCodec" should "support key annotation and configuration" in forAll { (f: String, b: Double) =>
    val foo: ConfigExampleBase = ConfigExampleFoo(f, 0, b)
    val json = json"""{ "type": "config_example_foo", "this_is_a_field": $f, "myField": $b}"""
    val expected = json"""{ "type": "config_example_foo", "this_is_a_field": $f, "a": 0, "myField": $b}"""

    assert(Encoder[ConfigExampleBase].apply(foo) === expected)
    assert(Decoder[ConfigExampleBase].decodeJson(json) === Right(foo))
  }
} 
Example 2
Source File: FragmentSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

class FragmentSpec extends RdfSpec {

  "A Fragment" should {
    val pct    =
      "%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%C3%86"
    val ucs    = "£¤¥¦§¨©ª«¬\u00AD®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆ"
    val delims = "!$&'()*+,;=:"
    val rest   = "?/:@"

    "be parsed correctly from a string" in {
      Fragment(pct + ucs + delims + rest).rightValue.value shouldEqual ucs + ucs + delims + rest
    }

    "succeed for empty" in {
      Fragment("").rightValue
    }

    "show" in {
      val encodedDelims = urlEncode("#[]")
      Fragment(
        pct + ucs + delims + rest + encodedDelims
      ).rightValue.show shouldEqual ucs + ucs + delims + rest + encodedDelims
    }

    "pct encoded representation" in {
      val encodedDelims = urlEncode("#[]")
      Fragment(
        pct + ucs + delims + rest + encodedDelims
      ).rightValue.pctEncoded shouldEqual pct + pct + delims + rest + encodedDelims
    }

    "eq" in {
      val lhs = Fragment(pct + ucs + delims + rest).rightValue
      val rhs = Fragment(ucs + ucs + delims + rest).rightValue
      Eq.eqv(lhs, rhs) shouldEqual true
    }
  }
} 
Example 3
Source File: QuerySpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

import scala.collection.immutable.{SortedMap, SortedSet}

class QuerySpec extends RdfSpec {

  "A Query" should {
    "be constructed successfully" in {
      // format: off
      val cases = List(
        "" -> SortedMap.empty[String, SortedSet[String]],
        "a=b&a=b&a=c&a&b&b&b=c&d/&e?" -> SortedMap(
          "a" -> SortedSet("", "b", "c"),
          "b" -> SortedSet("", "c"),
          "d/" -> SortedSet(""),
          "e?" -> SortedSet("")),
        "%3D%26=%3D%26&%3D&%26" -> SortedMap(
          "=&" -> SortedSet("=&"),
          "="  -> SortedSet(""),
          "&"  -> SortedSet("")),
        "%C2%A3=%C3%86" -> SortedMap("£" -> SortedSet("Æ"))
      )
      // format: on
      forAll(cases) {
        case (raw, map) =>
          Query(raw).rightValue.value shouldEqual map
      }
    }
    "fail to parse" in {
      val cases = List("a==b", "a=b&", "a#", "a&&", "a=&b")
      forAll(cases) { str => Query(str).leftValue }
    }
    "show" in {
      val encodedDelim = urlEncode("[]#")
      Query("a=b&a=b&a=c&a&b&b&b=c&d&e" + encodedDelim).rightValue.show shouldEqual "a&a=b&a=c&b&b=c&d&e" + encodedDelim
    }
    "pct encoded representation" in {
      val utf8         = "£Æ"
      val encodedUtf8  = urlEncode(utf8)
      val allowedDelim = "!:@!$()*,"
      val encodedDelim = urlEncode("[]#")
      Query(
        utf8 + encodedUtf8 + allowedDelim + encodedDelim
      ).rightValue.pctEncoded shouldEqual (encodedUtf8 + encodedUtf8 + allowedDelim + encodedDelim)
    }
    "eq" in {
      val lhs = Query("a=b&a=b&a=c&a&b&b&b=c&d&e").rightValue
      val rhs = Query("a=b&a=b&a=c&a&b&b=c&d&e").rightValue
      Eq.eqv(lhs, rhs) shouldEqual true
    }
  }
} 
Example 4
Source File: ComponentSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

class ComponentSpec extends RdfSpec {

  "A R or Q Component" should {
    "be constructed successfully" in {
      val cases = List(
        "a"                     -> "a",
        "a%C2%A3/?:@;&b%C3%86c" -> "a£/?:@;&bÆc",
        "a£/?:@;&bÆc"           -> "a£/?:@;&bÆc"
      )
      forAll(cases) {
        case (str, expected) =>
          Component(str).rightValue.value shouldEqual expected
      }
    }
    "fail to construct" in {
      val strings = List("", "asd?=", "asd?+", "asd?=a", "asd?+a")
      forAll(strings) { s => Component(s).leftValue }
    }
    "show" in {
      Component("a%C2%A3/?:@;&b%C3%86c").rightValue.show shouldEqual "a£/?:@;&bÆc"
    }
    "eq" in {
      val lhs = Component("a%C2%A3/?:@;&b%C3%86c").rightValue
      val rhs = Component("a£/?:@;&bÆc").rightValue
      Eq.eqv(lhs, rhs) shouldEqual true
    }
  }
} 
Example 5
Source File: NidSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

class NidSpec extends RdfSpec {

  "A Nid" should {
    "be constructed successfully" in {
      val strings = List("aa", "a-a", "1a", "11", "AA", s"a${List.fill(30)("1").mkString}a")
      forAll(strings) { s => Nid(s).rightValue }
    }
    "fail to construct" in {
      val strings = List("", "-a", "a-", "a", "%20a", "-", s"a${List.fill(31)("1").mkString}a")
      forAll(strings) { s => Nid(s).leftValue }
    }
    val normalized = Nid("IbAn")

    "normalize input during construction" in {
      normalized.rightValue.value shouldEqual "iban"
    }
    "show" in {
      normalized.rightValue.show shouldEqual "iban"
    }
    "eq" in {
      Eq.eqv(Nid("iban").rightValue, normalized.rightValue) shouldEqual true
    }
  }
} 
Example 6
Source File: TestAlgebras.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
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 7
Source File: autoApplyKTests.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
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 8
Source File: MainecoonTestSuite.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
package mainecoon.tests

import cats.arrow.FunctionK
import cats.instances.AllInstances
import cats.kernel.Eq
import mainecoon.syntax.AllSyntax
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.{FunSuite, Matchers}
import org.typelevel.discipline.scalatest.Discipline

import scala.util.Try

class MainecoonTestSuite extends FunSuite with Matchers with Discipline with TestInstances with AllInstances with AllSyntax with cats.syntax.AllSyntax


trait TestInstances {
  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.allEqual
} 
Example 9
Source File: autoFunctorTests.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
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 10
Source File: autoFlatMapTests.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
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 11
Source File: Models.scala    From ticket-booking-aecor   with Apache License 2.0 5 votes vote down vote up
package ru.pavkin.booking.common.models

import cats.Order
import cats.implicits._
import cats.kernel.{ Eq, Monoid }
import enumeratum._
import io.circe.{ Decoder, Encoder }
import io.circe.generic.semiauto._
import ru.pavkin.booking.common.json.AnyValCoders._

import scala.collection.immutable

case class Money(amount: BigDecimal) extends AnyVal

object Money {
  implicit val monoid: Monoid[Money] = new Monoid[Money] {
    def empty: Money = Money(0)
    def combine(x: Money, y: Money): Money = Money(x.amount + y.amount)
  }
}

case class BookingKey(value: String) extends AnyVal

case class ClientId(value: String) extends AnyVal
object ClientId {
  implicit val eqInstance: Eq[ClientId] = Eq.fromUniversalEquals
}

case class ConcertId(value: String) extends AnyVal

case class Row(num: Int) extends AnyVal
case class SeatNumber(num: Int) extends AnyVal

case class Seat(row: Row, number: SeatNumber)

object Seat {
  def seat(row: Int, number: Int): Seat = Seat(Row(row), SeatNumber(number))

  implicit val order: Order[Seat] = Order.by(s => (s.row.num, s.number.num))
  implicit val decoder: Decoder[Seat] = deriveDecoder
  implicit val encoder: Encoder[Seat] = deriveEncoder
}

case class Ticket(seat: Seat, price: Money)
object Ticket {
  implicit val decoder: Decoder[Ticket] = deriveDecoder
  implicit val encoder: Encoder[Ticket] = deriveEncoder
}
case class PaymentId(value: String) extends AnyVal

sealed trait BookingStatus extends EnumEntry

object BookingStatus extends Enum[BookingStatus] with CirceEnum[BookingStatus] {
  case object AwaitingConfirmation extends BookingStatus
  case object Confirmed extends BookingStatus
  case object Denied extends BookingStatus
  case object Canceled extends BookingStatus
  case object Settled extends BookingStatus

  def values: immutable.IndexedSeq[BookingStatus] = findValues
} 
Example 12
Source File: CardinalDirection.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.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 13
Source File: PortSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

class PortSpec extends RdfSpec {

  "A Port" should {
    "be constructed successfully" in {
      val strings = List("0", "1", "10", "65535", "60000")
      forAll(strings) { s => Port(s).rightValue }
    }
    "be range checked" in {
      val ints = List(-1, 65536)
      forAll(ints) { i => Port(i).leftValue }
    }
    "fail to construct" in {
      val strings = List("", "00", "01", "-1", "65536")
      forAll(strings) { s => Port(s).leftValue }
    }
    "show" in {
      Port(1).rightValue.show shouldEqual "1"
    }
    "eq" in {
      Eq.eqv(Port("1").rightValue, Port(1).rightValue) shouldEqual true
    }
  }
} 
Example 14
Source File: GSetSuite.scala    From crdt   with Apache License 2.0 5 votes vote down vote up
package com.machinomy.crdt.state

import cats.kernel.Eq
import org.scalatest.FunSuite
import cats.syntax.all._

class GSetSuite extends FunSuite {
  val eq = implicitly[Eq[GSet[Int]]]

  test("Just created GSet is empty") {
    val gSet = GSet[Int]()
    assert(gSet.value.isEmpty)
  }

  test("GSet calculates value") {
    val a = GSet[Int]()
    val b = a + 3
    val c = b + 1
    val d = c + 3
    assert(d.value === Set(1, 3))
  }

  test("GSets can be merged") {
    val a = GSet[Int](Set(1, 2, 3))
    val b = GSet[Int](Set(2, 3, 4))
    val result = a |+| b
    assert(result.value === Set(1, 2, 3, 4))
  }

  test("equality") {
    val a = GSet[Int]()
    val b = GSet[Int]()
    assert(eq.eqv(a, b))

    val a1 = a + 1
    assert(a1 !== b)

    val b1 = b + 1
    assert(eq.eqv(a1, b1))
  }
} 
Example 15
Source File: GCounterSuite.scala    From crdt   with Apache License 2.0 5 votes vote down vote up
package com.machinomy.crdt.state

import cats.kernel.{Eq, Monoid}
import cats.syntax.all._
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class GCounterSuite extends FunSuite with PropertyChecks {
  val replicaGen = Gen.posNum[Int]
  val valueGen = Gen.posNum[Int]
  val counterGen = for {
    id <- replicaGen
    value <- valueGen
  } yield GCounter[Int, Int]() + (id -> value)
  val eq = implicitly[Eq[GCounter[Int, Int]]]

  test("Fresh GCounter is empty") {
    val fresh = GCounter[Int, Int]()
    assert(Monoid[GCounter[Int, Int]].isEmpty(fresh))
    assert(fresh.value === 0)
  }

  test("could be calculated") {
    val counter = GCounter[Int, Int]().increment(1, 2).increment(2, 3)
    assert(counter.value === 5)
  }

  test("could be combined") {
    val a = GCounter[Int, Int]() + (1, 2) + (2, 3)
    val b = GCounter[Int, Int]() + (1, 2) + (3, 4)
    val c = a |+| b
    assert(c.value === 2 + 3 + 4)
  }

  test("could present replica value") {
    val a = GCounter[Int, Int]()
    assert(a.get(0) === 0)
    val b = a.increment(1, 2).increment(2, 3)
    assert(b.get(1) === 2)
    assert(b.get(2) === 3)
  }

  test("equality") {
    val a = GCounter[Int, Int]()
    val b = GCounter[Int, Int]()
    assert(eq.eqv(a, b))

    val a1 = a + (1 -> 1)
    assert(eq.neqv(a1, b))
    val b1 = b + (1 -> 2)
    assert(a1 !== b1)
    assert(eq.neqv(a1, b1))
    val a2 = a1 + (1 -> 1)
    assert(eq.eqv(a2, b1))
  }

  test("associativity") {
    forAll(Gen.listOfN(3, counterGen)) {
      case x :: y :: z :: Nil =>
        val left = x |+| (y |+| z)
        val right = (x |+| y) |+| z
        assert(eq.eqv(left, right))
      case _ => throw new RuntimeException("This is unexpected, really")
    }
  }

  test("commutativity") {
    forAll(Gen.listOfN(2, counterGen)) {
      case x :: y :: Nil =>
        val left = x |+| y
        val right = y |+| x
        assert(eq.eqv(left, right))
      case _ => throw new RuntimeException("This is unexpected, really")
    }
  }

  test("idempotency") {
    forAll(Gen.listOf(counterGen)) { list =>
      whenever(list.nonEmpty) {
        val counter = list.reduce(_ |+| _)
        assert(eq.eqv(counter, counter |+| counter))
      }
    }
  }
} 
Example 16
Source File: laws.scala    From newts   with Apache License 2.0 5 votes vote down vote up
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 17
Source File: Any.scala    From newts   with Apache License 2.0 5 votes vote down vote up
package newts

import cats.kernel.Eq
import cats.{Monoid, Show}

final case class Any(getAny: Boolean) extends AnyVal

object Any {
  implicit val newtypeInstance: Newtype.Aux[Any, Boolean] = Newtype.from(Any.apply)(_.getAny)

  implicit val monoidInstance: Monoid[Any] with Eq[Any] = new Monoid[Any] with Eq[Any]{
    def eqv(x: Any, y: Any): Boolean = x == y
    val empty: Any = Any(false)
    def combine(x: Any, y: Any): Any = Any(x.getAny || y.getAny)
  }

  implicit def showInstance: Show[Any] = Show.fromToString
} 
Example 18
Source File: Dual.scala    From newts   with Apache License 2.0 5 votes vote down vote up
package newts

import cats.kernel.Eq
import cats.syntax.functor._
import cats.{Applicative, Distributive, Eval, Functor, Monad, Monoid, Semigroup, Show, Traverse}

import scala.annotation.tailrec

final case class Dual[A](getDual: A) extends AnyVal

object Dual extends DualInstances0 {
  implicit def newtypeInstance[A]: Newtype.Aux[Dual[A], A] = Newtype.from[Dual[A], A](Dual.apply)(_.getDual)

  implicit val monadInstance: Monad[Dual] = new Monad[Dual] {
    def pure[A](x: A): Dual[A] = Dual(x)
    def flatMap[A, B](fa: Dual[A])(f: A => Dual[B]): Dual[B] = f(fa.getDual)
    @tailrec
    def tailRecM[A, B](a: A)(f: A => Dual[Either[A, B]]): Dual[B] = f(a) match {
      case Dual(Left(a1)) => tailRecM(a1)(f)
      case Dual(Right(b)) => Dual(b)
    }
  }
  
  implicit def semigroupInstance[A](implicit A: Semigroup[A]): Semigroup[Dual[A]] = new Semigroup[Dual[A]]{
    def combine(x: Dual[A], y: Dual[A]): Dual[A] = Dual(A.combine(y.getDual, x.getDual))
  }

  implicit def showInstance[A](implicit ev: Show[A]): Show[Dual[A]] = Show.show(a =>
    s"Dual(${Show[A].show(a.getDual)})"
  )

  implicit def dualEq[A: Eq]: Eq[Dual[A]] = Eq.by(_.getDual)
}

trait DualInstances0 {
  implicit def monoidInstances[A](implicit A: Monoid[A]): Monoid[Dual[A]] = new Monoid[Dual[A]]{
    def empty: Dual[A] = Dual(A.empty)
    def combine(x: Dual[A], y: Dual[A]): Dual[A] = Dual(A.combine(y.getDual, x.getDual))
  }

  implicit val traverseInstance: Traverse[Dual] = new Traverse[Dual] {
    def traverse[G[_], A, B](fa: Dual[A])(f: A => G[B])(implicit ev: Applicative[G]): G[Dual[B]] =
      f(fa.getDual).map(Dual(_))

    def foldLeft[A, B](fa: Dual[A], b: B)(f: (B, A) => B): B =
      f(b, fa.getDual)

    def foldRight[A, B](fa: Dual[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] =
      f(fa.getDual, lb)
  }

  implicit val distributiveInstance: Distributive[Dual] = new Distributive[Dual] {
    def distribute[G[_], A, B](ga: G[A])(f: A => Dual[B])(implicit ev: Functor[G]): Dual[G[B]] =
      Dual(ga.map(f(_).getDual))

    def map[A, B](fa: Dual[A])(f: A => B): Dual[B] = Dual(f(fa.getDual))
  }
} 
Example 19
Source File: Mult.scala    From newts   with Apache License 2.0 5 votes vote down vote up
package newts

import cats.kernel.{CommutativeMonoid, Eq}
import cats.syntax.functor._
import cats.{Applicative, CommutativeMonad, Distributive, Eval, Functor, Show, Traverse}

import scala.annotation.tailrec

final case class Mult[A](getMult: A) extends AnyVal

object Mult extends MultInstances0 {
  implicit def newtypeInstance[A]: Newtype.Aux[Mult[A], A] = Newtype.from[Mult[A], A](Mult.apply)(_.getMult)

  implicit val monadInstance: CommutativeMonad[Mult] = new CommutativeMonad[Mult] {
    def pure[A](x: A): Mult[A] = Mult(x)
    def flatMap[A, B](fa: Mult[A])(f: A => Mult[B]): Mult[B] = f(fa.getMult)
    @tailrec
    def tailRecM[A, B](a: A)(f: A => Mult[Either[A, B]]): Mult[B] = f(a) match {
      case Mult(Left(a1)) => tailRecM(a1)(f)
      case Mult(Right(b)) => Mult(b)
    }
  }

  implicit def monoidInstance[A](implicit num: Numeric[A]): CommutativeMonoid[Mult[A]] = new CommutativeMonoid[Mult[A]] {
    val empty: Mult[A] = Mult(num.one)
    def combine(x: Mult[A], y: Mult[A]): Mult[A] = Mult(num.times(x.getMult, y.getMult))
  }

  implicit def eqInstance[A: Eq]: Eq[Mult[A]] = Eq.by(_.getMult)

  implicit def showInstance[A](implicit ev: Show[A]): Show[Mult[A]] = Show.show(a =>
    s"Mult(${ev.show(a.getMult)})"
  )
}

trait MultInstances0 {
  implicit val traverseInstance: Traverse[Mult] = new Traverse[Mult] {
    def traverse[G[_], A, B](fa: Mult[A])(f: A => G[B])(implicit ev: Applicative[G]): G[Mult[B]] =
      f(fa.getMult).map(Mult(_))

    def foldLeft[A, B](fa: Mult[A], b: B)(f: (B, A) => B): B =
      f(b, fa.getMult)

    def foldRight[A, B](fa: Mult[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] =
      f(fa.getMult, lb)
  }

  implicit val distributiveInstance: Distributive[Mult] = new Distributive[Mult] {
    def distribute[G[_], A, B](ga: G[A])(f: A => Mult[B])(implicit ev: Functor[G]): Mult[G[B]] =
      Mult(ga.map(f(_).getMult))

    def map[A, B](fa: Mult[A])(f: A => B): Mult[B] = Mult(f(fa.getMult))
  }
} 
Example 20
Source File: FirstOption.scala    From newts   with Apache License 2.0 5 votes vote down vote up
package newts

import cats.{Alternative, Applicative, Eval, Monad, Monoid, MonoidK, Show, Traverse}
import cats.instances.option._
import cats.syntax.functor._
import cats.syntax.traverse._
import cats.kernel.Eq

import scala.annotation.tailrec

final case class FirstOption[A](getFirstOption: Option[A]) extends AnyVal

object FirstOption extends FirstOptionInstances0 {
  implicit def newtypeInstance[A]: Newtype.Aux[FirstOption[A], Option[A]] =
    Newtype.from[FirstOption[A], Option[A]](FirstOption.apply)(_.getFirstOption)

  implicit val monadAlternativeInstance: Monad[FirstOption] with Alternative[FirstOption] = new Monad[FirstOption] with Alternative[FirstOption] {
    def empty[A]: FirstOption[A] = FirstOption(None)
    def combineK[A](x: FirstOption[A], y: FirstOption[A]): FirstOption[A] = FirstOption(x.getFirstOption.orElse(y.getFirstOption))
    def pure[A](x: A): FirstOption[A] = FirstOption(Some(x))
    def flatMap[A, B](fa: FirstOption[A])(f: A => FirstOption[B]): FirstOption[B] =
      fa.getFirstOption.fold(empty[B])(f)

    @tailrec
    def tailRecM[A, B](a: A)(f: A => FirstOption[Either[A, B]]): FirstOption[B] =
      f(a).getFirstOption match {
        case None           => empty
        case Some(Left(a1)) => tailRecM(a1)(f)
        case Some(Right(b)) => pure(b)
      }
  }

  implicit def monoidInstance[A]: Monoid[FirstOption[A]] = MonoidK[FirstOption].algebra

  implicit def eqInstance[A: Eq]: Eq[FirstOption[A]] = Eq.by(_.getFirstOption)

  implicit def showInstance[A: Show]: Show[FirstOption[A]] = Show.show(a =>
    s"FirstOption(${Show[Option[A]].show(a.getFirstOption)})"
  )
}

trait FirstOptionInstances0 {
  implicit val traverseInstance: Traverse[FirstOption] = new Traverse[FirstOption] {
    def traverse[G[_], A, B](fa: FirstOption[A])(f: A => G[B])(implicit ev: Applicative[G]): G[FirstOption[B]] =
      fa.getFirstOption.traverse(f).map(FirstOption(_))

    def foldLeft[A, B](fa: FirstOption[A], b: B)(f: (B, A) => B): B =
      fa.getFirstOption.fold(b)(f(b, _))

    def foldRight[A, B](fa: FirstOption[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] =
      fa.getFirstOption.fold(lb)(f(_, lb))
  }
} 
Example 21
Source File: LastOption.scala    From newts   with Apache License 2.0 5 votes vote down vote up
package newts

import cats.instances.option._
import cats.kernel.Eq
import cats.syntax.functor._
import cats.syntax.traverse._
import cats.{Alternative, Applicative, Eval, Monad, Monoid, MonoidK, Show, Traverse}

final case class LastOption[A](getLastOption: Option[A]) extends AnyVal

object LastOption extends LastOptionInstances0 {
  implicit def newtypeInstance[A]: Newtype.Aux[LastOption[A], Option[A]] =
    Newtype.from[LastOption[A], Option[A]](LastOption.apply)(_.getLastOption)

  implicit val monadAlternativeInstance: Monad[LastOption] with Alternative[LastOption] = new Monad[LastOption] with Alternative[LastOption] {
    override def empty[A]: LastOption[A] = LastOption(None)
    override def combineK[A](x: LastOption[A], y: LastOption[A]): LastOption[A] = LastOption(y.getLastOption.orElse(x.getLastOption))
    override def pure[A](x: A): LastOption[A] = LastOption(Some(x))
    override def flatMap[A, B](fa: LastOption[A])(f: (A) => LastOption[B]): LastOption[B] =
      fa.getLastOption.fold(empty[B])(f)

    override def tailRecM[A, B](a: A)(f: (A) => LastOption[Either[A, B]]): LastOption[B] = {
      f(a).getLastOption match {
        case None => empty
        case Some(Left(a1)) => tailRecM(a1)(f)
        case Some(Right(b)) => pure(b)
      }
    }
  }

  implicit def monoidInstance[A]: Monoid[LastOption[A]] = MonoidK[LastOption].algebra

  implicit def eqInstance[A: Eq]: Eq[LastOption[A]] = Eq.by(_.getLastOption)

  implicit def showInstance[A: Show]: Show[LastOption[A]] = Show.show(a =>
    s"LastOption(${Show[Option[A]].show(a.getLastOption)})"
  )
}

trait LastOptionInstances0 {
  implicit val traverseInstance: Traverse[LastOption] = new Traverse[LastOption] {
    def traverse[G[_], A, B](fa: LastOption[A])(f: A => G[B])(implicit ev: Applicative[G]): G[LastOption[B]] =
      fa.getLastOption.traverse(f).map(LastOption(_))

    def foldLeft[A, B](fa: LastOption[A], b: B)(f: (B, A) => B): B =
      fa.getLastOption.fold(b)(f(b, _))

    def foldRight[A, B](fa: LastOption[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] =
      fa.getLastOption.fold(lb)(f(_, lb))
  }
} 
Example 22
Source File: All.scala    From newts   with Apache License 2.0 5 votes vote down vote up
package newts

import cats.kernel.Eq
import cats.{Monoid, Show}

final case class All(getAll: Boolean) extends AnyVal

object All {
  implicit val newtypeInstance: Newtype.Aux[All, Boolean] = Newtype.from(All.apply)(_.getAll)

  implicit val monoidInstance: Monoid[All] with Eq[All] = new Monoid[All] with Eq[All]{
    def eqv(x: All, y: All): Boolean = x == y
    val empty: All = All(true)
    def combine(x: All, y: All): All = All(x.getAll && y.getAll)
  }

  implicit def showInstance: Show[All] = Show.fromToString
} 
Example 23
Source File: ZipList.scala    From newts   with Apache License 2.0 5 votes vote down vote up
package newts

import cats.{Apply, Show}
import cats.instances.list._
import cats.kernel.Eq

final case class ZipList[A](getZipList: List[A]) extends AnyVal

object ZipList {
  implicit def newtypeInstance[A]: Newtype.Aux[ZipList[A], List[A]] =
    Newtype.from[ZipList[A], List[A]](ZipList.apply)(_.getZipList)

  implicit val instances: Apply[ZipList] = new Apply[ZipList] {
    def map[A, B](fa: ZipList[A])(f: A => B): ZipList[B] =
      ZipList(fa.getZipList.map(f))

    def ap[A, B](ff: ZipList[A => B])(fa: ZipList[A]): ZipList[B] =
      map(product(ff, fa)){case (f, a) => f(a)}

    override def product[A, B](fa: ZipList[A], fb: ZipList[B]): ZipList[(A, B)] =
      ZipList(fa.getZipList.zip(fb.getZipList))
  }

  implicit def eqInstances[A: Eq]: Eq[ZipList[A]] = Eq.by(_.getZipList)

  implicit def showInstance[A](implicit ev: Show[A]): Show[ZipList[A]] = Show.show(a =>
    s"ZipList(${Show[List[A]].show(a.getZipList)})"
  )
} 
Example 24
Source File: EqInstances.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.testing

import cats.kernel.Eq
import shapeless.LowPriority

sealed trait FallbackEqInstances {
  implicit def fallbackEq[A](implicit lp: LowPriority) = new Eq[A] {
    def eqv(x: A, y: A): Boolean =
      (x, y) match {
        case (x: Array[_], y: Array[_]) => x.sameElements(y)
        case _                          => Eq.fromUniversalEquals[A].eqv(x, y)
      }
  }
}

trait EqInstances extends FallbackEqInstances {
  // == does not compare arrays for value equality, but for reference equality.
  implicit def arrayEq[T](implicit eqT: Eq[T]): Eq[Array[T]] =
    new Eq[Array[T]] {
      def eqv(xs: Array[T], ys: Array[T]): Boolean =
        (xs.length == ys.length) &&
          (xs.zip(ys)).forall { case (x, y) => eqT.eqv(x, y) }
    }
}

object EqInstances extends EqInstances 
Example 25
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 26
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 27
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 28
Source File: Measures.scala    From sonar-scala   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.mwz.sonar.scala
package sensor

import scala.annotation.tailrec
import scala.util.matching.Regex

import cats.instances.char._
import cats.kernel.Eq
import cats.syntax.eq._
import scalariform.lexer.{Token, TokenType, Tokens}


object Measures {
  implicit val tokenTypeEq = Eq.fromUniversalEquals[TokenType]
  val NewLineRegex: Regex = "(\r\n)|\r|\n".r

  def countClasses(tokens: List[Token]): Int = {
    tokens.foldLeft(0) { // scalastyle:ignore org.scalastyle.scalariform.NamedArgumentChecker
      case (acc, token) =>
        val tokenType = token.tokenType
        if (tokenType === Tokens.CLASS || tokenType === Tokens.OBJECT) acc + 1
        else acc
    }
  }

  def countMethods(tokens: List[Token]): Int = {
    tokens.foldLeft(0) { // scalastyle:ignore org.scalastyle.scalariform.NamedArgumentChecker
      case (acc, token) =>
        if (token.tokenType === Tokens.DEF) acc + 1
        else acc
    }
  }

  @tailrec
  def countCommentLines(tokens: List[Token], i: Int = 0): Int = {
    tokens match {
      case Nil => i
      case token :: tail if token.tokenType.isComment =>
        token.tokenType match {
          case Tokens.LINE_COMMENT =>
            countCommentLines(tail, i + 1)
          case Tokens.MULTILINE_COMMENT =>
            countCommentLines(tail, i + token.rawText.count(_ === '\n') + 1)
          case Tokens.XML_COMMENT =>
            new scala.NotImplementedError("XML ?!"); i
          case _ => i // Not a comment!
        }
      case _ :: tail => countCommentLines(tail, i)
    }
  }

  @tailrec
  def countNonCommentLines(tokens: List[Token], i: Int = 0): Int = {
    @tailrec
    def getNextLine(tokens: List[Token]): List[Token] = {
      tokens match {
        case Nil =>
          Nil
        case token :: tail
            if token.tokenType === Tokens.WS &&
            NewLineRegex.findFirstIn(token.text).nonEmpty =>
          tail
        case token :: tail if token.tokenType === Tokens.LINE_COMMENT =>
          tail
        case _ :: tail =>
          getNextLine(tail)
      }
    }

    tokens match {
      case Nil => i
      case token :: tail if token.tokenType === Tokens.WS =>
        countNonCommentLines(tail, i)
      case token :: _ if token.tokenType === Tokens.EOF => i
      case token :: tail =>
        if (!token.tokenType.isNewline & !token.tokenType.isComment)
          countNonCommentLines(getNextLine(tail), i + 1)
        else countNonCommentLines(tail, i)
    }
  }
} 
Example 29
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 30
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 31
Source File: package.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc

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

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

package object laws {

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

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

  // eq instances
  implicit val eqLocalTime: Eq[LocalTime] = Eq.fromUniversalEquals
  implicit val eqLocalDate: Eq[LocalDate] = Eq.fromUniversalEquals
  implicit val eqDayOfWeek: Eq[DayOfWeek] = Eq.fromUniversalEquals
} 
Example 32
Source File: instances.scala    From paiges   with Apache License 2.0 5 votes vote down vote up
package org.typelevel.paiges

import cats.kernel.{Eq, Monoid}

package object instances {
  implicit val paigesDocMonoid: Monoid[Doc] =
    new Monoid[Doc] {
      def empty: Doc = Doc.empty
      def combine(x: Doc, y: Doc): Doc = x + y
    }

  implicit val paigesStyleMonoid: Monoid[Style] =
    new Monoid[Style] {
      def empty: Style = Style.Empty
      def combine(x: Style, y: Style): Style = x ++ y
    }

  implicit val paigesStyleEq: Eq[Style] =
    Eq.fromUniversalEquals
} 
Example 33
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 34
Source File: Printer.scala    From skeuomorph   with Apache License 2.0 5 votes vote down vote up
package higherkindness.skeuomorph

import catz.contrib.Decidable
import cats.{Contravariant, Show}
import cats.implicits._
import cats.kernel.Eq

trait Printer[T] extends Printer.ContravariantPrinter[T]

object Printer {

  def apply[A](implicit instance: Printer[A]): Printer[A] = instance

  
  def toValidIdentifier(string: String): String =
    if (string.isEmpty) string
    else scala.meta.Term.Name(string).syntax

  implicit val divisiblePrinter: Decidable[Printer] = new Decidable[Printer] {
    def unit: Printer[Unit] = Printer.unit
    def product[A, B](fa: Printer[A], fb: Printer[B]): Printer[(A, B)] =
      new Printer[(A, B)] {
        def print(ab: (A, B)): String = fa.print(ab._1) + fb.print(ab._2)
      }
    def contramap[A, B](fa: Printer[A])(f: B => A): Printer[B] =
      print[B]((fa.print _).compose(f))
    def choose[A, B, C](fa: Printer[A], fb: Printer[B])(cab: C => Either[A, B]): Printer[C] =
      Printer(cab(_).fold(fa.print, fb.print))
  }

  implicit val catsContravariantForPrinter: Contravariant[Printer] = new Contravariant[Printer] {
    def contramap[A, B](fa: Printer[A])(f: B => A): Printer[B] =
      print[B]((fa.print _).compose(f))
  }

  implicit def catsLawsEqForPrinter[A](implicit ev: Eq[A => String]): Eq[Printer[A]] =
    Eq.by[Printer[A], A => String](printA => a => printA.print(a))
} 
Example 35
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 36
Source File: CirceSuite.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.tests

import cats.instances.AllInstances
import cats.kernel.Eq
import cats.syntax.{AllSyntax, EitherOps}
import io.circe.testing.{ArbitraryInstances, EqInstances}
import org.scalatest.FlatSpec
import org.scalatestplus.scalacheck.{Checkers, ScalaCheckDrivenPropertyChecks}
import org.typelevel.discipline.Laws


trait CirceSuite
    extends FlatSpec
    with ScalaCheckDrivenPropertyChecks
    with AllInstances
    with AllSyntax
    with ArbitraryInstances
    with Checkers
    with EqInstances {

  override def convertToEqualizer[T](left: T): Equalizer[T] =
    sys.error("Intentionally ambiguous implicit for Equalizer")

  implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab)

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

  implicit def eqSeq[A: Eq]: Eq[Seq[A]] = Eq.by((_: Seq[A]).toVector)(
    cats.kernel.instances.vector.catsKernelStdEqForVector[A]
  )
} 
Example 37
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 38
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 39
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 40
Source File: service.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.finagle

import cats.instances.int._
import cats.kernel.Eq
import cats.laws.discipline._
import cats.laws.discipline.eq._
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.Service
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.prop.Configuration
import org.typelevel.discipline.scalatest.FunSuiteDiscipline

class ServiceSuite
    extends AnyFunSuite
    with FunSuiteDiscipline
    with Configuration
    with ServiceInstances
    with ArbitraryInstances
    with EqInstances {
  implicit val eq: Eq[Service[Boolean, Int]] = serviceEq(1.second)

  checkAll("Service", CategoryTests[Service].compose[Boolean, Int, Boolean, Int])
  checkAll("Service", CategoryTests[Service].category[Boolean, Int, Boolean, Int])
  checkAll("Service", ProfunctorTests[Service].profunctor[Boolean, Int, Boolean, Int, Boolean, Int])
} 
Example 41
Source File: RerunnableSuite.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util.effect

import cats.effect.laws.discipline.EffectTests
import cats.effect.laws.discipline.arbitrary.catsEffectLawsArbitraryForIO
import cats.effect.laws.util.{ TestContext, TestInstances }
import cats.effect.{ Bracket, IO }
import cats.instances.either._
import cats.instances.int._
import cats.instances.tuple._
import cats.instances.unit._
import cats.kernel.Eq
import cats.laws.discipline.arbitrary._
import com.twitter.util.{ Await, Monitor, Throw }
import io.catbird.util.{ ArbitraryInstances, Rerunnable }
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.prop.Configuration
import org.typelevel.discipline.scalatest.FunSuiteDiscipline

class RerunnableSuite
    extends AnyFunSuite
    with FunSuiteDiscipline
    with Configuration
    with ArbitraryInstances
    with TestInstances {
  implicit val context: TestContext = TestContext()
  implicit def rerunnableEq[A](implicit A: Eq[A]): Eq[Rerunnable[A]] =
    Eq.by[Rerunnable[A], IO[A]](rerunnableToIO)

  checkAll("Rerunnable[Int]", EffectTests[Rerunnable].effect[Int, Int, Int])

  test("Exceptions thrown by release are handled by Monitor") {
    val useException = new Exception("thrown by use")
    val releaseException = new Exception("thrown by release")

    var monitoredException: Throwable = null
    val monitor = Monitor.mk { case e => monitoredException = e; true; }

    val rerunnable = Bracket[Rerunnable, Throwable]
      .bracket(Rerunnable.Unit)(_ => Rerunnable.raiseError(useException))(_ => Rerunnable.raiseError(releaseException))
      .liftToTry

    val result = Await.result(Monitor.using(monitor)(rerunnable.run))

    assert(result == Throw(useException))
    assert(monitoredException == releaseException)
  }
} 
Example 42
Source File: Key.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal

import cats.implicits._
import cats.kernel.Eq
import cats.{Functor, Order, Show}
import com.datastax.driver.core.{GettableByNameData, SettableData}
import com.evolutiongaming.scassandra.syntax._
import com.evolutiongaming.scassandra.{DecodeRow, EncodeRow}
import com.evolutiongaming.skafka.Topic

final case class Key(id: String, topic: Topic) {

  override def toString = s"$topic:$id"
}

object Key {

  implicit val eqKey: Eq[Key] = Eq.fromUniversalEquals

  implicit val showKey: Show[Key] = Show.fromToString

  implicit val orderKey: Order[Key] = Order.whenEqual(
    Order.by { a: Key => a.topic },
    Order.by { a: Key => a.id })

  implicit val orderingKey: Ordering[Key] = orderKey.toOrdering


  implicit val encodeRowKey: EncodeRow[Key] = new EncodeRow[Key] {

    def apply[B <: SettableData[B]](data: B, value: Key) = {
      data
        .encode("id", value.id)
        .encode("topic", value.topic)
    }
  }

  implicit val decodeRowKey: DecodeRow[Key] = new DecodeRow[Key] {

    def apply(data: GettableByNameData) = {
      Key(
        id = data.decode[String]("id"),
        topic = data.decode[Topic]("topic"))
    }
  }


  def random[F[_] : Functor : RandomIdOf](topic: Topic): F[Key] = {
    for {
      randomId <- RandomIdOf[F].apply
    } yield {
      Key(id = randomId.value, topic = topic)
    }
  }
} 
Example 43
Source File: CirceSuite.scala    From circe-optics   with Apache License 2.0 5 votes vote down vote up
package io.circe.optics

import cats.kernel.Eq
import cats.instances.AllInstances
import cats.syntax.{ AllSyntax, EitherOps }
import io.circe.testing.{ ArbitraryInstances, EqInstances }
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.scalacheck.{ Checkers, ScalaCheckDrivenPropertyChecks }
import org.typelevel.discipline.Laws
import org.typelevel.discipline.scalatest.FlatSpecDiscipline
import scala.language.implicitConversions


trait CirceSuite
    extends AnyFlatSpec
    with FlatSpecDiscipline
    with ScalaCheckDrivenPropertyChecks
    with AllInstances
    with AllSyntax
    with ArbitraryInstances
    with EqInstances {
  override def convertToEqualizer[T](left: T): Equalizer[T] =
    sys.error("Intentionally ambiguous implicit for Equalizer")

  implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab)

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

  def assertEq[A: Eq](expected: A, actual: A): Unit =
    assert(
      expected === actual,
      s"""Expected did not match actual:
         |
         |Expected: $expected
         |Actual:   $actual"""
    )
} 
Example 44
Source File: JsonPathSuite.scala    From circe-optics   with Apache License 2.0 5 votes vote down vote up
package io.circe.optics

import cats.kernel.Eq
import io.circe._
import io.circe.generic.semiauto._
import io.circe.syntax._
import io.circe.optics.JsonPath.root

class JsonPathSuite extends CirceSuite {

  case class Car(model: String, maxSpeed: Int, automatic: Boolean)
  object Car {
    implicit val eq: Eq[Car] = Eq.fromUniversalEquals[Car]
    implicit val decoder: Decoder[Car] = deriveDecoder[Car]
    implicit val encoder: Encoder.AsObject[Car] = deriveEncoder[Car]
  }

  val john: Json = Json.obj(
    "first_name" -> "John".asJson,
    "last_name" -> "Doe".asJson,
    "age" -> 25.asJson,
    "address" -> Json.obj(
      "street_number" -> 12.asJson,
      "street_name" -> "High Street".asJson
    ),
    "cars" -> List(
      Car("fancy", 120, automatic = false),
      Car("suv", 80, automatic = true)
    ).asJson
  )

  "JsonPath" should "support traversal by field name" in {
    assert(root.address.street_number.int.getOption(john) === Some(12))
  }

  it should "support traversal by array index" in {
    assert(root.cars.index(1).model.string.getOption(john) === Some("suv"))
  }

  it should "support traversal by array index using apply" in {
    assert(root.cars(1).model.string.getOption(john) === Some("suv"))
  }

  it should "support traversal by array index using apply on the root" in {
    val jsonArray = List("first".asJson, "second".asJson).asJson
    assert(root(0).string.getOption(jsonArray) === Some("first"))
  }

  it should "support insertion and deletion" in {
    assert(root.at("first_name").setOption(None)(john) === john.asObject.map(_.remove("first_name").asJson))
    assert(root.at("foo").set(Some(true.asJson))(john).asObject.flatMap(_.apply("foo")) === Some(Json.True))
  }

  it should "support codec" in {
    assert(root.cars.index(0).as[Car].getOption(john) === Some(Car("fancy", 120, automatic = false)))
  }

  "JsonTraversalPath" should "support traversal over each values of a json object" in {
    assert(root.each.string.getAll(john) === List("John", "Doe"))
  }

  it should "support traversal over each values of a json array" in {
    assert(root.cars.each.maxSpeed.int.getAll(john) === List(120, 80))
  }

  it should "support filtering by field of json object" in {
    assert(root.filterByField(_.contains("first")).string.getAll(john) === List("John"))
  }

  it should "support filtering by index of json array" in {
    assert(root.cars.filterByIndex(_ % 2 == 1).as[Car].getAll(john) === List(Car("suv", 80, automatic = true)))
  }

  it should "support a safe filtering by value" in {
    assert(
      root.cars.each.filter(root.maxSpeed.int.exist(_ > 100)).model.string.getAll(john) === List("fancy")
    )
  }

  it should "support an unsafe filtering by value" in {
    assert(
      root.cars.each.filterUnsafe(root.maxSpeed.int.exist(_ > 100)).model.string.set("new")(john) ===
        Json.obj(
          "first_name" -> "John".asJson,
          "last_name" -> "Doe".asJson,
          "age" -> 25.asJson,
          "address" -> Json.obj(
            "street_number" -> 12.asJson,
            "street_name" -> "High Street".asJson
          ),
          "cars" -> List(
            Car("new", 120, automatic = false),
            Car("suv", 80, automatic = true)
          ).asJson
        )
    )
  }

} 
Example 45
Source File: UrnSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

class UrnSpec extends RdfSpec {

  "An Urn" should {
    "be parsed correctly" in {
      // format: off
      val cases = List(
        "urn:uUid:6e8bc430-9c3a-11d9-9669-0800200c9a66"           -> "urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66",
        "urn:example:a%C2%A3/b%C3%86c//:://?=a=b#"                -> "urn:example:a£/bÆc//:://?=a=b#",
        "urn:lex:eu:council:directive:2010-03-09;2010-19-UE"      -> "urn:lex:eu:council:directive:2010-03-09;2010-19-UE",
        "urn:Example:weather?=op=map&lat=39.56&lon=-104.85#test"  -> "urn:example:weather?=lat=39.56&lon=-104.85&op=map#test",
        "urn:examp-lE:foo-bar-baz-qux?+CCResolve:cc=uk"           -> "urn:examp-le:foo-bar-baz-qux?+CCResolve:cc=uk",
        "urn:examp-lE:foo-bar-baz-qux?=a=b?+CCResolve:cc=uk"      -> "urn:examp-le:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b",
        "urn:examp-lE:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b"      -> "urn:examp-le:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b",
        "urn:examp-lE:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b#hash" -> "urn:examp-le:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b#hash"
      )
      // format: on
      forAll(cases) {
        case (in, expected) =>
          Urn(in).rightValue.asString shouldEqual expected
      }
    }

    "fail to parse" in {
      val fail = List(
        "urn:example:some/path/?+",
        "urn:example:some/path/?="
      )
      forAll(fail) { str => Urn(str).leftValue }
    }

    val withHash = Iri.absolute("urn:examp-lE:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b#hash").rightValue

    "be absolute" in {
      withHash.isAbsolute shouldEqual true
    }

    "be a Urn" in {
      withHash.isUrn shouldEqual true
    }

    "as uri" in {
      val iri = Iri.absolute("urn:example:a£/bÆc//:://?=a=b#").rightValue
      iri.asUri shouldEqual "urn:example:a%C2%A3/b%C3%86c//:://?=a=b#"
    }

    "show" in {
      val iri = Iri.absolute("urn:example:a£/bÆc//:://?=a=b#").rightValue
      iri.show shouldEqual "urn:example:a£/bÆc//:://?=a=b#"
    }

    "return an optional self" in {
      withHash.asUrn shouldEqual Some(withHash)
    }

    "return an optional self from asAbsolute" in {
      withHash.asAbsolute shouldEqual Some(withHash)
    }

    "not be an Url" in {
      withHash.isUrl shouldEqual false
    }

    "not return a url" in {
      withHash.asUrl shouldEqual None
    }

    "not be a RelativeIri" in {
      withHash.isRelative shouldEqual false
    }

    "not return a RelativeIri" in {
      withHash.asRelative shouldEqual None
    }

    "eq" in {
      val lhs = Urn("urn:examp-lE:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b#hash").rightValue
      val rhs = Urn("urn:examp-le:foo-bar-baz-qux?+CCResolve:cc=uk?=a=b#hash").rightValue
      Eq.eqv(lhs, rhs) shouldEqual true
    }
  }
} 
Example 46
Source File: UserInfoSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

class UserInfoSpec extends RdfSpec {

  "An UserInfo" should {
    val pct    =
      "%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%C3%86"
    val ucsUp  = "£¤¥¦§¨©ª«¬\u00AD®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆ"
    val ucsLow = "£¤¥¦§¨©ª«¬\u00AD®¯°±²³´µ¶·¸¹º»¼½¾¿àáâãäåæ"
    val delims = "!$&'()*+,;=:"
    val up     = "ABCD"
    val low    = "abcd"

    "be parsed correctly from a string" in {
      UserInfo("aBcd:Efgh").rightValue.value shouldEqual "aBcd:Efgh"
    }

    "equal when compared with ignored casing" in {
      UserInfo("aBcd:Efgh").rightValue equalsIgnoreCase UserInfo("Abcd:efgH").rightValue shouldEqual true
    }

    "be parsed correctly from percent encoded string" in {
      UserInfo(pct).rightValue.value shouldEqual ucsUp
    }

    "be parsed correctly from ucs chars" in {
      UserInfo(ucsUp).rightValue.value shouldEqual ucsUp
    }

    "be parsed correctly from delimiters" in {
      UserInfo(delims).rightValue.value shouldEqual delims
    }

    "be parsed correctly from mixed characters" in {
      val in  = ucsUp + ucsLow + pct + delims + up
      val out = ucsUp + ucsLow + ucsUp + delims + up
      UserInfo(in).rightValue.value shouldEqual out
    }

    "fail for empty" in {
      UserInfo("").leftValue
    }

    "show" in {
      UserInfo(up + low).rightValue.show shouldEqual (up + low)
    }

    "eq" in {
      Eq.eqv(UserInfo(ucsUp + ucsLow).rightValue, UserInfo(ucsUp + ucsLow).rightValue) shouldEqual true
    }

    "not eq" in {
      Eq.eqv(UserInfo(ucsUp).rightValue, UserInfo(ucsLow).rightValue) shouldEqual false
    }
  }
} 
Example 47
Source File: SchemeSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.rdf

import cats.kernel.Eq
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.rdf.Iri._

class SchemeSpec extends RdfSpec {

  "A Scheme" should {
    "be constructed successfully" in {
      val strings = List("urn", "https", "http", "file", "ftp", "ssh", "a", "a0", "a-", "a+", "a.", "HTTPS", "A0-+.")
      forAll(strings) { s => Scheme(s).rightValue }
    }
    "fail to construct" in {
      val strings = List("", "0", "0a", "as_", "%20a", "0-+.")
      forAll(strings) { s => Scheme(s).leftValue }
    }
    "return the appropriate boolean flag" in {
      val cases = List(
        ("urn", true, false, false),
        ("URN", true, false, false),
        ("https", false, true, false),
        ("HTTPS", false, true, false),
        ("http", false, false, true),
        ("HTTP", false, false, true)
      )
      forAll(cases) {
        case (string, isUrn, isHttps, isHttp) =>
          val scheme = Scheme(string).rightValue
          scheme.isUrn shouldEqual isUrn
          scheme.isHttps shouldEqual isHttps
          scheme.isHttp shouldEqual isHttp
      }
    }

    val normalized = Scheme("HtTpS").rightValue

    "normalize input during construction" in {
      normalized.value shouldEqual "https"
    }
    "show" in {
      normalized.show shouldEqual "https"
    }
    "eq" in {
      Eq.eqv(Scheme("https").rightValue, normalized) shouldEqual true
    }
  }
}