shapeless.test.illTyped Scala Examples

The following examples show how to use shapeless.test.illTyped. 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: TypedVectorAssemblerTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package feature

import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import org.apache.spark.ml.linalg._
import shapeless.test.illTyped

class TypedVectorAssemblerTests extends FramelessMlSuite {

  test(".transform() returns a correct TypedTransformer") {
    def prop[A: TypedEncoder: Arbitrary] = forAll { x5: X5[Int, Long, Double, Boolean, A] =>
      val assembler = TypedVectorAssembler[X4[Int, Long, Double, Boolean]]
      val ds = TypedDataset.create(Seq(x5))
      val ds2 = assembler.transform(ds).as[X6[Int, Long, Double, Boolean, A, Vector]]

      ds2.collect.run() ==
        Seq(X6(x5.a, x5.b, x5.c, x5.d, x5.e, Vectors.dense(x5.a.toDouble, x5.b.toDouble, x5.c, if (x5.d) 1D else 0D)))
    }

    def prop2[A: TypedEncoder: Arbitrary] = forAll { x5: X5[Boolean, BigDecimal, Byte, Short, A] =>
      val assembler = TypedVectorAssembler[X4[Boolean, BigDecimal, Byte, Short]]
      val ds = TypedDataset.create(Seq(x5))
      val ds2 = assembler.transform(ds).as[X6[Boolean, BigDecimal, Byte, Short, A, Vector]]

      ds2.collect.run() ==
        Seq(X6(x5.a, x5.b, x5.c, x5.d, x5.e, Vectors.dense(if (x5.a) 1D else 0D, x5.b.toDouble, x5.c.toDouble, x5.d.toDouble)))
    }

    check(prop[String])
    check(prop[Double])
    check(prop2[Long])
    check(prop2[Boolean])
  }

  test("create() compiles only with correct inputs") {
    illTyped("TypedVectorAssembler.create[Double]()")
    illTyped("TypedVectorAssembler.create[X1[String]]()")
    illTyped("TypedVectorAssembler.create[X2[String, Double]]()")
    illTyped("TypedVectorAssembler.create[X3[Int, String, Double]]()")
  }

} 
Example 2
Source File: SemiautoDerivedSuite.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.magnolia

import io.circe.magnolia.derivation.decoder.semiauto._
import io.circe.magnolia.derivation.encoder.semiauto._
import io.circe.testing.CodecTests
import io.circe.tests.CirceSuite
import io.circe.tests.examples._
import io.circe.{Decoder, Encoder, Json}
import shapeless.test.illTyped

class SemiautoDerivedSuite extends CirceSuite {
  import SemiautoDerivedSuiteInputs._

  implicit def decodeBox[A: Decoder]: Decoder[Box[A]] = deriveMagnoliaDecoder
  implicit def encodeBox[A: Encoder]: Encoder[Box[A]] = deriveMagnoliaEncoder

  implicit def decodeQux[A: Decoder]: Decoder[Qux[A]] = deriveMagnoliaDecoder
  implicit def encodeQux[A: Encoder]: Encoder[Qux[A]] = deriveMagnoliaEncoder

  implicit val decodeWub: Decoder[Wub] = deriveMagnoliaDecoder
  implicit val encodeWub: Encoder[Wub] = deriveMagnoliaEncoder
  implicit val decodeFoo: Decoder[Foo] = deriveMagnoliaDecoder
  implicit val encodeFoo: Encoder[Foo] = deriveMagnoliaEncoder

  implicit val decodeAnyValInside: Decoder[AnyValInside] = deriveMagnoliaDecoder
  implicit val encodeAnyValInside: Encoder[AnyValInside] = deriveMagnoliaEncoder

  implicit val decodeRecursiveAdtExample: Decoder[RecursiveAdtExample] = deriveMagnoliaDecoder
  implicit val encodeRecursiveAdtExample: Encoder[RecursiveAdtExample] = deriveMagnoliaEncoder

  implicit val decodeRecursiveWithOptionExample: Decoder[RecursiveWithOptionExample] =
    deriveMagnoliaDecoder
  implicit val encodeRecursiveWithOptionExample: Encoder[RecursiveWithOptionExample] =
    deriveMagnoliaEncoder

  checkLaws("Codec[Tuple1[Int]]", CodecTests[Tuple1[Int]].unserializableCodec)
  checkLaws("Codec[(Int, Int, Foo)]", CodecTests[(Int, Int, Foo)].unserializableCodec)
  checkLaws("Codec[Box[Int]]", CodecTests[Box[Int]].unserializableCodec)
  checkLaws("Codec[Qux[Int]]", CodecTests[Qux[Int]].unserializableCodec)
  checkLaws("Codec[Seq[Foo]]", CodecTests[Seq[Foo]].unserializableCodec)
  checkLaws("Codec[Baz]", CodecTests[Baz].unserializableCodec)
  checkLaws("Codec[Foo]", CodecTests[Foo].unserializableCodec)
  checkLaws("Codec[RecursiveAdtExample]", CodecTests[RecursiveAdtExample].unserializableCodec)
  checkLaws("Codec[RecursiveWithOptionExample]", CodecTests[RecursiveWithOptionExample].unserializableCodec)
  checkLaws("Codec[AnyValInside]", CodecTests[AnyValInside].unserializableCodec)

  "A generically derived codec" should "not interfere with base instances" in forAll { (is: List[Int]) =>
    val json = Encoder[List[Int]].apply(is)

    assert(json === Json.fromValues(is.map(Json.fromInt)) && json.as[List[Int]] === Right(is))
  }

  it should "not come from nowhere" in {
    illTyped("Decoder[OvergenerationExampleInner]")
    illTyped("Encoder[OvergenerationExampleInner]")

    illTyped("Decoder[OvergenerationExampleOuter0]")
    illTyped("Encoder[OvergenerationExampleOuter0]")
    illTyped("Decoder[OvergenerationExampleOuter1]")
    illTyped("Encoder[OvergenerationExampleOuter1]")
  }

  it should "require instances for all parts" in {
    illTyped("deriveMagnoliaDecoder[OvergenerationExampleInner0]")
    illTyped("deriveMagnoliaDecoder[OvergenerationExampleInner1]")
    illTyped("deriveMagnoliaEncoder[OvergenerationExampleInner0]")
    illTyped("deriveMagnoliaEncoder[OvergenerationExampleInner1]")
  }
} 
Example 3
Source File: ValueClassSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.magnolia

import scala.language.higherKinds

import pureconfig._
import pureconfig.module.magnolia.auto.reader._
import pureconfig.module.magnolia.auto.writer._
import shapeless.test.illTyped

// NOTE: behavior differs from pureconfig.generic (value classes also need to be case classes)
final case class IntWrapper(inner: Int) extends AnyVal {
  override def toString: String = s"IntWrapper($inner)"
}

final case class PrivateFloatValue private (value: Float) extends AnyVal

final case class GenericValue[A] private (t: A) extends AnyVal {
  override def toString: String = "GenericValue(" + t.toString + ")"
}

object GenericValue {
  def from[A](t: A): GenericValue[A] = new GenericValue[A](t)
}

trait Read[A] {
  def read(str: String): A
}

object Read {
  def apply[A](implicit readT: Read[A]): Read[A] = readT

  implicit val badReadString = new Read[String] {
    override def read(str: String): String = ""
  }
}

class ValueClassSuite extends BaseSuite {

  behavior of "ConfigConvert for Value Classes"

  checkRead[IntWrapper](ConfigWriter.forPrimitive[Int].to(1) -> new IntWrapper(1))
  checkWrite[IntWrapper](new IntWrapper(1) -> ConfigWriter.forPrimitive[Int].to(1))

  "ConfigReader[PrivateFloatValue]" should "not be derivable because the constructor is private" in {
    illTyped("pureconfig.ConfigReader[PrivateFloatValue]")
  }

  {
    implicit def genericValueReader[A](implicit readT: Read[A]): ConfigReader[GenericValue[A]] =
      ConfigReader.fromString(s => Right(GenericValue.from(readT.read(s))))

    "ConfigReader" should " should be able to override value classes ConfigReader" in {
      val reader = ConfigReader[GenericValue[String]]
      val expected = Right(GenericValue.from(""))
      val configValue = ConfigWriter.forPrimitive[String].to("foobar")
      reader.from(configValue) shouldEqual expected
    }
  }
} 
Example 4
Source File: DerivationModesSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.magnolia

import scala.language.higherKinds

import com.typesafe.config.ConfigFactory
import pureconfig._
import shapeless.test.illTyped

class DerivationModesSuite extends BaseSuite {

  sealed trait Entity
  case class Person(name: String, surname: String) extends Entity
  case class Place(name: String, lat: Double, lon: Double) extends Entity

  val person = Person("John", "Doe")
  val conf = ConfigFactory.parseString("{ type: person, name: John, surname: Doe }")

  case class CustomCaseClass(customObject: CustomObject, mapCustomObject: Map[String, CustomObject], mapListCustomObject: Map[String, List[CustomObject]])
  case class CustomObject(value: Int)
  object CustomObject {
    implicit val pureconfigReader: ConfigReader[CustomObject] = ConfigReader.fromStringOpt {
      case "eaaxacaca" => Some(CustomObject(453))
      case "a" => Some(CustomObject(45))
      case _ => Some(CustomObject(1))
    }
    implicit val pureconfigWriter: ConfigWriter[CustomObject] = ConfigWriter.toString {
      case CustomObject(453) => "eaaxacaca"
      case CustomObject(45) => "a"
      case _ => "cvbc"
    }
  }

  val customCaseClass = CustomCaseClass(
    CustomObject(453),
    Map("a" -> CustomObject(453), "b" -> CustomObject(45)),
    Map("x" -> List(CustomObject(45), CustomObject(453), CustomObject(1))))
  val customConf = ConfigFactory.parseString(
    """{
      |  custom-object = "eaaxacaca"
      |  map-custom-object { a = "eaaxacaca", b = "a" }
      |  map-list-custom-object { x = ["a", "eaaxacaca", "cvbc"]}
      |}""".stripMargin)

  behavior of "default"

  it should "not provide instance derivation for products and coproducts out-of-the-box" in {
    illTyped("loadConfig[Entity](conf)")
    illTyped("ConfigWriter[Entity]")
  }

  behavior of "semiauto"

  it should "not provide instance derivation for products and coproducts out-of-the-box" in {
    illTyped("{ import pureconfig.module.magnolia.reader.semiauto._; loadConfig[Entity](conf) }")
    illTyped("{ import pureconfig.module.magnolia.reader.semiauto._; ConfigWriter[Entity] }")
  }

  it should "provide methods to derive readers on demand" in {
    import pureconfig.module.magnolia.semiauto.reader._

    implicit val personReader = deriveReader[Person]
    implicit val placeReader = deriveReader[Place]
    implicit val entityReader = deriveReader[Entity]

    ConfigReader[Entity].from(conf.root) shouldBe Right(person)
  }

  it should "provide methods to derive writers on demand" in {
    import pureconfig.module.magnolia.semiauto.writer._

    implicit val personWriter = deriveWriter[Person]
    implicit val placeWriter = deriveWriter[Place]
    implicit val entityWriter = deriveWriter[Entity]

    ConfigWriter[Entity].to(person) shouldBe conf.root()
  }

  behavior of "auto"

  it should "provide instance derivation for products and coproducts out-of-the-box" in {
    import pureconfig.module.magnolia.auto.reader._
    import pureconfig.module.magnolia.auto.writer._

    ConfigReader[Entity].from(conf.root) shouldBe Right(person)
    ConfigWriter[Entity].to(person) shouldBe conf.root()
  }

  it should "use existing reader and writer instances when they exist" in {
    import pureconfig.module.magnolia.auto.reader._
    import pureconfig.module.magnolia.auto.writer._

    ConfigReader[CustomCaseClass].from(customConf.root) shouldBe Right(customCaseClass)
    ConfigWriter[CustomCaseClass].to(customCaseClass) shouldBe customConf.root()
  }
} 
Example 5
Source File: EnumerationsSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig

import com.typesafe.config.{ ConfigFactory, ConfigValueFactory, ConfigValueType }
import pureconfig.error.WrongType
import pureconfig.generic.error.NoValidCoproductOptionFound
import pureconfig.generic.semiauto._
import shapeless.test.illTyped

class EnumerationsSuite extends BaseSuite {

  sealed trait Color
  case object RainyBlue extends Color
  case object SunnyYellow extends Color

  val conf = ConfigFactory.parseString("{ type: person, name: John, surname: Doe }")

  behavior of "deriveEnumeration"

  it should "provide methods to derive readers for enumerations encoded as sealed traits" in {
    implicit val colorReader = deriveEnumerationReader[Color]

    ConfigReader[Color].from(ConfigValueFactory.fromAnyRef("rainy-blue")) shouldBe Right(RainyBlue)
    ConfigReader[Color].from(ConfigValueFactory.fromAnyRef("sunny-yellow")) shouldBe Right(SunnyYellow)

    val unknownValue = ConfigValueFactory.fromAnyRef("blue")
    ConfigReader[Color].from(unknownValue) should failWith(NoValidCoproductOptionFound(unknownValue, Seq.empty), "", emptyConfigOrigin)
    ConfigReader[Color].from(conf.root()) should failWith(WrongType(ConfigValueType.OBJECT, Set(ConfigValueType.STRING)), "", stringConfigOrigin(1))
  }

  it should "provide methods to derive writers for enumerations encoded as sealed traits" in {
    implicit val colorWriter = deriveEnumerationWriter[Color]

    ConfigWriter[Color].to(RainyBlue) shouldEqual ConfigValueFactory.fromAnyRef("rainy-blue")
    ConfigWriter[Color].to(SunnyYellow) shouldEqual ConfigValueFactory.fromAnyRef("sunny-yellow")
  }

  it should "provide methods to derive full converters for enumerations encoded as sealed traits" in {
    implicit val colorConvert = deriveEnumerationConvert[Color]

    ConfigConvert[Color].from(ConfigValueFactory.fromAnyRef("rainy-blue")) shouldBe Right(RainyBlue)
    ConfigConvert[Color].from(ConfigValueFactory.fromAnyRef("sunny-yellow")) shouldBe Right(SunnyYellow)
    ConfigConvert[Color].to(RainyBlue) shouldEqual ConfigValueFactory.fromAnyRef("rainy-blue")
    ConfigConvert[Color].to(SunnyYellow) shouldEqual ConfigValueFactory.fromAnyRef("sunny-yellow")
  }

  it should "provide customizable methods to derive readers for enumerations encoded as sealed traits" in {
    implicit val colorReader = deriveEnumerationReader[Color](ConfigFieldMapping(PascalCase, SnakeCase))

    ConfigReader[Color].from(ConfigValueFactory.fromAnyRef("rainy_blue")) shouldBe Right(RainyBlue)
    ConfigReader[Color].from(ConfigValueFactory.fromAnyRef("sunny_yellow")) shouldBe Right(SunnyYellow)
  }

  it should "provide customizable methods to derive writers for enumerations encoded as sealed traits" in {
    implicit val colorWriter = deriveEnumerationWriter[Color](ConfigFieldMapping(PascalCase, SnakeCase))

    ConfigWriter[Color].to(RainyBlue) shouldEqual ConfigValueFactory.fromAnyRef("rainy_blue")
    ConfigWriter[Color].to(SunnyYellow) shouldEqual ConfigValueFactory.fromAnyRef("sunny_yellow")
  }

  it should "provide customizable methods to derive full converters for enumerations encoded as sealed traits" in {
    implicit val colorConvert = deriveEnumerationConvert[Color](ConfigFieldMapping(PascalCase, SnakeCase))

    ConfigConvert[Color].from(ConfigValueFactory.fromAnyRef("rainy_blue")) shouldBe Right(RainyBlue)
    ConfigConvert[Color].from(ConfigValueFactory.fromAnyRef("sunny_yellow")) shouldBe Right(SunnyYellow)
    ConfigConvert[Color].to(RainyBlue) shouldEqual ConfigValueFactory.fromAnyRef("rainy_blue")
    ConfigConvert[Color].to(SunnyYellow) shouldEqual ConfigValueFactory.fromAnyRef("sunny_yellow")
  }

  it should "not allow deriving readers, writers and full converters for enumerations encoded as sealed traits whose subclasses are not all case objects" in {

    illTyped("deriveEnumerationReader[Entity]")
    illTyped("deriveEnumerationWriter[Entity]")
    illTyped("deriveEnumerationConvert[Entity]")
  }
} 
Example 6
Source File: ValueClassSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig

import pureconfig.generic.auto._
import shapeless.test.illTyped

final class IntWrapper(val inner: Int) extends AnyVal {
  override def toString: String = s"IntWrapper($inner)"
}

final class PrivateFloatValue private (val value: Float) extends AnyVal

final class GenericValue[A] private (val t: A) extends AnyVal {
  override def toString: String = "GenericValue(" + t.toString + ")"
}

object GenericValue {
  def from[A](t: A): GenericValue[A] = new GenericValue[A](t)
}

trait Read[A] {
  def read(str: String): A
}

object Read {
  def apply[A](implicit readT: Read[A]): Read[A] = readT

  implicit val badReadString = new Read[String] {
    override def read(str: String): String = ""
  }
}

class ValueClassSuite extends BaseSuite {

  behavior of "ConfigConvert for Value Classes"

  checkRead[IntWrapper](ConfigWriter.forPrimitive[Int].to(1) -> new IntWrapper(1))
  checkWrite[IntWrapper](new IntWrapper(1) -> ConfigWriter.forPrimitive[Int].to(1))

  "ConfigReader[PrivateFloatValue]" should "not be derivable because the constructor is private" in {
    illTyped("pureconfig.ConfigReader[PrivateFloatValue]")
  }

  {
    implicit def genericValueReader[A](implicit readT: Read[A]): ConfigReader[GenericValue[A]] =
      ConfigReader.fromString(s => Right(GenericValue.from(readT.read(s))))

    "ConfigReader" should " should be able to override value classes ConfigReader" in {
      val reader = ConfigReader[GenericValue[String]]
      val expected = Right(GenericValue.from(""))
      val configValue = ConfigWriter.forPrimitive[String].to("foobar")
      reader.from(configValue) shouldEqual expected
    }
  }
} 
Example 7
Source File: DerivationModesSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig

import com.typesafe.config.ConfigFactory
import shapeless.test.illTyped

class DerivationModesSuite extends BaseSuite {

  sealed trait Entity
  case class Person(name: String, surname: String) extends Entity
  case class Place(name: String, lat: Double, lon: Double) extends Entity

  val person = Person("John", "Doe")
  val conf = ConfigFactory.parseString("{ type: person, name: John, surname: Doe }")

  case class CustomCaseClass(customObject: CustomObject, mapCustomObject: Map[String, CustomObject], mapListCustomObject: Map[String, List[CustomObject]])
  case class CustomObject(value: Int)
  object CustomObject {
    implicit val pureconfigReader: ConfigReader[CustomObject] = ConfigReader.fromStringOpt {
      case "eaaxacaca" => Some(CustomObject(453))
      case "a" => Some(CustomObject(45))
      case _ => Some(CustomObject(1))
    }
    implicit val pureconfigWriter: ConfigWriter[CustomObject] = ConfigWriter.toString {
      case CustomObject(453) => "eaaxacaca"
      case CustomObject(45) => "a"
      case _ => "cvbc"
    }
  }

  val customCaseClass = CustomCaseClass(
    CustomObject(453),
    Map("a" -> CustomObject(453), "b" -> CustomObject(45)),
    Map("x" -> List(CustomObject(45), CustomObject(453), CustomObject(1))))
  val customConf = ConfigFactory.parseString(
    """{
      |  custom-object = "eaaxacaca"
      |  map-custom-object { a = "eaaxacaca", b = "a" }
      |  map-list-custom-object { x = ["a", "eaaxacaca", "cvbc"]}
      |}""".stripMargin)

  behavior of "default"

  it should "not provide instance derivation for products and coproducts out-of-the-box" in {
    illTyped("loadConfig[Entity](conf)")
    illTyped("ConfigWriter[Entity]")
  }

  behavior of "semiauto"

  it should "not provide instance derivation for products and coproducts out-of-the-box" in {
    illTyped("{ import pureconfig.generic.semiauto._; loadConfig[Entity](conf) }")
    illTyped("{ import pureconfig.generic.semiauto._; ConfigWriter[Entity] }")
  }

  it should "provide methods to derive readers on demand" in {
    import pureconfig.generic.semiauto._

    implicit val personReader = deriveReader[Person]
    implicit val placeReader = deriveReader[Place]
    implicit val entityReader = deriveReader[Entity]

    ConfigReader[Entity].from(conf.root) shouldBe Right(person)
  }

  it should "provide methods to derive writers on demand" in {
    import pureconfig.generic.semiauto._

    implicit val personWriter = deriveWriter[Person]
    implicit val placeWriter = deriveWriter[Place]
    implicit val entityWriter = deriveWriter[Entity]

    ConfigWriter[Entity].to(person) shouldBe conf.root()
  }

  it should "provide methods to derive full converters on demand" in {
    import pureconfig.generic.semiauto._

    implicit val personConvert = deriveConvert[Person]
    implicit val placeConvert = deriveConvert[Place]
    implicit val entityConvert = deriveConvert[Entity]

    ConfigReader[Entity].from(conf.root) shouldBe Right(person)
    ConfigWriter[Entity].to(person) shouldBe conf.root()
  }

  behavior of "auto"

  it should "provide instance derivation for products and coproducts out-of-the-box" in {
    import pureconfig.generic.auto._

    ConfigReader[Entity].from(conf.root) shouldBe Right(person)
    ConfigWriter[Entity].to(person) shouldBe conf.root()
  }

  it should "use existing reader and writer instances when they exist" in {
    import pureconfig.generic.auto._

    ConfigReader[CustomCaseClass].from(customConf.root) shouldBe Right(customCaseClass)
    ConfigWriter[CustomCaseClass].to(customCaseClass) shouldBe customConf.root()
  }
} 
Example 8
Source File: DropTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped

class DropTest extends TypedDatasetSuite {
  import DropTest._

  test("fail to compile on missing value") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XMissing] = f.drop[XMissing]('j)"""
    }
  }

  test("fail to compile on different column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XDifferentColumnName] = f.drop[XDifferentColumnName]('j)"""
    }
  }

  test("fail to compile on added column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XAdded] = f.drop[XAdded]('j)"""
    }
  }

  test("remove column in the middle") {
    val f: TypedDataset[X] = TypedDataset.create(X(1, 1, false) :: X(1, 1, false) :: X(1, 10, false) :: Nil)
    val fNew: TypedDataset[XGood] = f.drop[XGood]

    fNew.collect().run().foreach(xg => assert(xg === XGood(1, false)))
  }

  test("drop four columns") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d5 = TypedDataset.create(X5(value, value, value, value, value) :: Nil)
      val d4 = d5.drop[X4[A, A, A, A]]
      val d3 = d4.drop[X3[A, A, A]]
      val d2 = d3.drop[X2[A, A]]
      val d1 = d2.drop[X1[A]]

      X1(value) ?= d1.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }
}

object DropTest {
  case class X(i: Int, j: Int, k: Boolean)
  case class XMissing(i: Int)
  case class XDifferentColumnName(ij: Int, k: Boolean)
  case class XAdded(i: Int, j: Int, k: Boolean, l: Int)
  case class XGood(i: Int, k: Boolean)
} 
Example 9
Source File: RecordEncoderTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.apache.spark.sql.Row
import org.apache.spark.sql.types.StructType
import shapeless.{HList, LabelledGeneric}
import shapeless.test.illTyped
import org.scalatest.matchers.should.Matchers

case class UnitsOnly(a: Unit, b: Unit)

case class TupleWithUnits(u0: Unit, _1: Int, u1: Unit, u2: Unit, _2: String, u3: Unit)

object TupleWithUnits {
  def apply(_1: Int, _2: String): TupleWithUnits = TupleWithUnits((), _1, (), (), _2, ())
}

case class OptionalNesting(o: Option[TupleWithUnits])

object RecordEncoderTests {
  case class A(x: Int)
  case class B(a: Seq[A])
  case class C(b: B)
}

class RecordEncoderTests extends TypedDatasetSuite with Matchers {
  test("Unable to encode products made from units only") {
    illTyped("""TypedEncoder[UnitsOnly]""")
  }

  test("Dropping fields") {
    def dropUnitValues[L <: HList](l: L)(implicit d: DropUnitValues[L]): d.Out = d(l)
    val fields = LabelledGeneric[TupleWithUnits].to(TupleWithUnits(42, "something"))
    dropUnitValues(fields) shouldEqual LabelledGeneric[(Int, String)].to((42, "something"))
  }

  test("Representation skips units") {
    assert(TypedEncoder[(Int, String)].catalystRepr == TypedEncoder[TupleWithUnits].catalystRepr)
  }

  test("Serialization skips units") {
    val df = session.createDataFrame(Seq((1, "one"), (2, "two")))
    val ds = df.as[TupleWithUnits](TypedExpressionEncoder[TupleWithUnits])
    val tds = TypedDataset.create(Seq(TupleWithUnits(1, "one"), TupleWithUnits(2, "two")))

    df.collect shouldEqual tds.toDF.collect
    ds.collect.toSeq shouldEqual tds.collect.run
  }

  test("Empty nested record value becomes null on serialization") {
    val ds = TypedDataset.create(Seq(OptionalNesting(Option.empty)))
    val df = ds.toDF
    df.na.drop.count shouldBe 0
  }

  test("Empty nested record value becomes none on deserialization") {
    val rdd = sc.parallelize(Seq(Row(null)))
    val schema = TypedEncoder[OptionalNesting].catalystRepr.asInstanceOf[StructType]
    val df = session.createDataFrame(rdd, schema)
    val ds = TypedDataset.createUnsafe(df)(TypedEncoder[OptionalNesting])
    ds.firstOption.run.get.o.isEmpty shouldBe true
  }

  test("Deeply nested optional values have correct deserialization") {
    val rdd = sc.parallelize(Seq(Row(true, Row(null, null))))
    type NestedOptionPair = X2[Boolean, Option[X2[Option[Int], Option[String]]]]
    val schema = TypedEncoder[NestedOptionPair].catalystRepr.asInstanceOf[StructType]
    val df = session.createDataFrame(rdd, schema)
    val ds = TypedDataset.createUnsafe(df)(TypedEncoder[NestedOptionPair])
    ds.firstOption.run.get shouldBe X2(true, Some(X2(None, None)))
  }

  test("Nesting with collection") {
    import RecordEncoderTests._
    val obj = C(B(Seq(A(1))))
    val rdd = sc.parallelize(Seq(obj))
    val ds = session.createDataset(rdd)(TypedExpressionEncoder[C])
    ds.collect.head shouldBe obj
  }
} 
Example 10
Source File: ColTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import shapeless.test.illTyped

import org.scalacheck.Prop
import org.scalacheck.Prop._

class ColTests extends TypedDatasetSuite {
  test("col") {
    val x4 = TypedDataset.create[X4[Int, String, Long, Boolean]](Nil)
    val t4 = TypedDataset.create[(Int, String, Long, Boolean)](Nil)

    x4.col('a)
    t4.col('_1)

    x4.col[Int]('a)
    t4.col[Int]('_1)

    illTyped("x4.col[String]('a)", "No column .* of type String in frameless.X4.*")

    x4.col('b)
    t4.col('_2)

    x4.col[String]('b)
    t4.col[String]('_2)

    illTyped("x4.col[Int]('b)", "No column .* of type Int in frameless.X4.*")

    ()
  }

  test("colMany") {
    type X2X2 = X2[X2[Int, String], X2[Long, Boolean]]
    val x2x2 = TypedDataset.create[X2X2](Nil)

    val aa: TypedColumn[X2X2, Int] = x2x2.colMany('a, 'a)
    val ab: TypedColumn[X2X2, String] = x2x2.colMany('a, 'b)
    val ba: TypedColumn[X2X2, Long] = x2x2.colMany('b, 'a)
    val bb: TypedColumn[X2X2, Boolean] = x2x2.colMany('b, 'b)

    illTyped("x2x2.colMany('a, 'c)")
    illTyped("x2x2.colMany('a, 'a, 'a)")
  }

  test("select colMany") {
    def prop[A: TypedEncoder](x: X2[X2[A, A], A]): Prop = {
      val df = TypedDataset.create(x :: Nil)
      val got = df.select(df.colMany('a, 'a)).collect().run()

      got ?= (x.a.a :: Nil)
    }

    check(prop[Int] _)
    check(prop[X2[Int, Int]] _)
    check(prop[X2[X2[Int, Int], Int]] _)
  }
} 
Example 11
Source File: RepeatTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops

import shapeless.test.illTyped
import shapeless.{::, HNil, Nat}

class RepeatTest extends TypedDatasetSuite {
  test("summoning with implicitly") {
    implicitly[Repeat.Aux[Int::Boolean::HNil, Nat._1, Int::Boolean::HNil]]
    implicitly[Repeat.Aux[Int::Boolean::HNil, Nat._2, Int::Boolean::Int::Boolean::HNil]]
    implicitly[Repeat.Aux[Int::Boolean::HNil, Nat._3, Int::Boolean::Int::Boolean::Int::Boolean::HNil]]
    implicitly[Repeat.Aux[String::HNil, Nat._5, String::String::String::String::String::HNil]]
  }

  test("ill typed") {
    illTyped("""implicitly[Repeat.Aux[String::HNil, Nat._5, String::String::String::String::HNil]]""")
  }
} 
Example 12
Source File: SmartProjectTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped


case class Foo(i: Int, j: Int, x: String)
case class Bar(i: Int, x: String)
case class InvalidFooProjectionType(i: Int, x: Boolean)
case class InvalidFooProjectionName(i: Int, xerr: String)

class SmartProjectTest extends TypedDatasetSuite {
  // Lazy needed to prevent initialization anterior to the `beforeAll` hook
  lazy val dataset = TypedDataset.create(Foo(1, 2, "hi") :: Foo(2, 3, "there") :: Nil)

  test("project Foo to Bar") {
    assert(dataset.project[Bar].count().run() === 2)
  }

  test("project to InvalidFooProjection should not type check") {
    illTyped("dataset.project[InvalidFooProjectionType]")
    illTyped("dataset.project[InvalidFooProjectionName]")
  }

  test("X4 to X1,X2,X3,X4 projections") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder, D: TypedEncoder](data: Vector[X4[A, B, C, D]]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.project[X4[A, B, C, D]].collect().run().toVector ?= data
      dataset.project[X3[A, B, C]].collect().run().toVector ?= data.map(x => X3(x.a, x.b, x.c))
      dataset.project[X2[A, B]].collect().run().toVector ?= data.map(x => X2(x.a, x.b))
      dataset.project[X1[A]].collect().run().toVector ?= data.map(x => X1(x.a))
    }

    check(forAll(prop[Int, String, X1[String], Boolean] _))
    check(forAll(prop[Short, Long, String, Boolean] _))
    check(forAll(prop[Short, (Boolean, Boolean), String, (Int, Int)] _))
    check(forAll(prop[X2[String, Boolean], (Boolean, Boolean), String, Boolean] _))
    check(forAll(prop[X2[String, Boolean], X3[Boolean, Boolean, Long], String, String] _))
  }

  test("X3U to X1,X2,X3 projections") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder](data: Vector[X3U[A, B, C]]): Prop = {
      val dataset = TypedDataset.create(data)

      dataset.project[X3[A, B, C]].collect().run().toVector ?= data.map(x => X3(x.a, x.b, x.c))
      dataset.project[X2[A, B]].collect().run().toVector ?= data.map(x => X2(x.a, x.b))
      dataset.project[X1[A]].collect().run().toVector ?= data.map(x => X1(x.a))
    }

    check(forAll(prop[Int, String, X1[String]] _))
    check(forAll(prop[Short, Long, String] _))
    check(forAll(prop[Short, (Boolean, Boolean), String] _))
    check(forAll(prop[X2[String, Boolean], (Boolean, Boolean), String] _))
    check(forAll(prop[X2[String, Boolean], X3[Boolean, Boolean, Long], String] _))
  }
} 
Example 13
Source File: WithColumnTest.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped

class WithColumnTest extends TypedDatasetSuite {
  import WithColumnTest._

  test("fail to compile on missing value") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XMissing] = f.withColumn[XMissing](f('j) === 10)"""
    }
  }

  test("fail to compile on different column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XDifferentColumnName] = f.withColumn[XDifferentColumnName](f('j) === 10)"""
    }
  }

  test("fail to compile on added column name") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XAdded] = f.withColumn[XAdded](f('j) === 10)"""
    }
  }

  test("fail to compile on wrong typed column") {
    val f: TypedDataset[X] = TypedDataset.create(X(1,1) :: X(1,1) :: X(1,10) :: Nil)
    illTyped {
      """val fNew: TypedDataset[XWrongType] = f.withColumn[XWrongType](f('j) === 10)"""
    }
  }

  test("append four columns") {
    def prop[A: TypedEncoder](value: A): Prop = {
      val d = TypedDataset.create(X1(value) :: Nil)
      val d1 = d.withColumn[X2[A, A]](d('a))
      val d2 = d1.withColumn[X3[A, A, A]](d1('b))
      val d3 = d2.withColumn[X4[A, A, A, A]](d2('c))
      val d4 = d3.withColumn[X5[A, A, A, A, A]](d3('d))

      X5(value, value, value, value, value) ?= d4.collect().run().head
    }

    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }

  test("update in place") {
    def prop[A : TypedEncoder](startValue: A, replaceValue: A): Prop = {
      val d = TypedDataset.create(X2(startValue, replaceValue) :: Nil)

      val X2(a, b) = d.withColumnReplaced('a, d('b))
        .collect()
        .run()
        .head

      a ?= b
    }
    check(prop[Int] _)
    check(prop[Long] _)
    check(prop[String] _)
    check(prop[SQLDate] _)
    check(prop[Option[X1[Boolean]]] _)
  }
}

object WithColumnTest {
  case class X(i: Int, j: Int)
  case class XMissing(i: Int, k: Boolean)
  case class XDifferentColumnName(i: Int, ji: Int, k: Boolean)
  case class XAdded(i: Int, j: Int, k: Boolean, l: Int)
  case class XWrongType(i: Int, j: Int, k: Int)
  case class XGood(i: Int, j: Int, k: Boolean)
} 
Example 14
Source File: UnionTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Prop
import org.scalacheck.Prop._
import shapeless.test.illTyped

class UnionTests extends TypedDatasetSuite {

  test("fail to compile on not aligned schema") {
    val dataset1 = TypedDataset.create(Foo(1, 1) :: Nil)
    val dataset2 = TypedDataset.create(Wrong(1, 1, 1) :: Nil)

    illTyped {
      """val fNew = dataset1 union dataset2 """
    }
  }

  test("Union for simple data types") {
    def prop[A: TypedEncoder](data1: Vector[A], data2: Vector[A]): Prop = {
      val dataset1 = TypedDataset.create(data1)
      val dataset2 = TypedDataset.create(data2)
      val datasetUnion = dataset1.union(dataset2).collect().run().toVector
      val dataUnion = data1.union(data2)

      datasetUnion ?= dataUnion
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[String] _))
  }

  test("Align fields for case classes") {
    def prop[A: TypedEncoder, B: TypedEncoder](data1: Vector[(A, B)], data2: Vector[(A, B)]): Prop = {

      val dataset1 = TypedDataset.create(data1.map((Foo.apply[A, B] _).tupled))
      val dataset2 = TypedDataset.create(data2.map { case (a, b) => Bar[A, B](b, a) })
      val datasetUnion = dataset1.union(dataset2).collect().run().map(foo => (foo.x, foo.y)).toVector
      val dataUnion = data1 union data2

      datasetUnion ?= dataUnion
    }

    check(forAll(prop[Int, String] _))
    check(forAll(prop[String, X1[Option[Long]]] _))
  }

  test("Align fields for different number of columns") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder](data1: Vector[(A, B, C)], data2: Vector[(A, B)]): Prop = {

      val dataset1 = TypedDataset.create(data2.map((Foo.apply[A, B] _).tupled))
      val dataset2 = TypedDataset.create(data1.map { case (a, b, c) => Baz[A, B, C](c, b, a) })
      val datasetUnion: Seq[(A, B)] = dataset1.union(dataset2).collect().run().map(foo => (foo.x, foo.y)).toVector
      val dataUnion = data2 union data1.map { case (a, b, _) => (a, b) }

      datasetUnion ?= dataUnion
    }

    check(forAll(prop[Option[Int], String, Array[Long]] _))
    check(forAll(prop[String, X1[Option[Int]], X2[String, Array[Int]]] _))
  }
}

final case class Foo[A, B](x: A, y: B)
final case class Bar[A, B](y: B, x: A)
final case class Baz[A, B, C](z: C, y: B, x: A)
final case class Wrong[A, B, C](a: A, b: B, c: C) 
Example 15
Source File: TypedIndexToStringTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package feature

import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Prop._
import shapeless.test.illTyped
import org.scalatest.matchers.must.Matchers

class TypedIndexToStringTests extends FramelessMlSuite with Matchers {

  test(".transform() correctly transform an input dataset") {
    implicit val arbDouble = Arbitrary(Gen.choose(0, 99).map(_.toDouble))

    def prop[A: TypedEncoder: Arbitrary] = forAll { x2: X2[Double, A] =>
      val transformer = TypedIndexToString[X1[Double]](Array.fill(100)("foo"))
      val ds = TypedDataset.create(Seq(x2))
      val ds2 = transformer.transform(ds)

      ds2.collect.run() == Seq((x2.a, x2.b, "foo"))
    }

    check(prop[Double])
    check(prop[String])
  }

  test("create() compiles only with correct inputs") {
    illTyped("TypedIndexToString.create[String](Array(\"foo\"))")
    illTyped("TypedIndexToString.create[X1[String]](Array(\"foo\"))")
    illTyped("TypedIndexToString.create[X1[Long]](Array(\"foo\"))")
    illTyped("TypedIndexToString.create[X2[String, Int]](Array(\"foo\"))")
  }

} 
Example 16
Source File: AutoDerivedSuite.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.magnolia

import io.circe.magnolia.derivation.decoder.auto._
import io.circe.magnolia.derivation.encoder.auto._
import io.circe.testing.CodecTests
import io.circe.tests.CirceSuite
import io.circe.tests.examples._
import io.circe.{Decoder, Encoder, Json}
import shapeless.tag
import shapeless.tag.@@
import shapeless.test.illTyped

class AutoDerivedSuite extends CirceSuite {
  import AutoDerivedSuiteInputs._

  // TODO: All these imports are temporary workaround for https://github.com/propensive/magnolia/issues/89
  import Encoder._
  import Decoder._

  private implicit val encodeStringTag: Encoder[String @@ Tag] = Encoder[String].narrow
  private implicit val decodeStringTag: Decoder[String @@ Tag] = Decoder[String].map(tag[Tag](_))

  checkLaws("Codec[Tuple1[Int]]", CodecTests[Tuple1[Int]].unserializableCodec)
  checkLaws("Codec[(Int, Int, Foo)]", CodecTests[(Int, Int, Foo)].unserializableCodec)
  checkLaws("Codec[Qux[Int]]", CodecTests[Qux[Int]].unserializableCodec)
  checkLaws("Codec[Seq[Foo]]", CodecTests[Seq[Foo]].unserializableCodec)
  checkLaws("Codec[Baz]", CodecTests[Baz].unserializableCodec)
  checkLaws("Codec[Foo]", CodecTests[Foo].unserializableCodec)
  checkLaws("Codec[OuterCaseClassExample]", CodecTests[OuterCaseClassExample].unserializableCodec)
  checkLaws("Codec[RecursiveAdtExample]", CodecTests[RecursiveAdtExample].unserializableCodec)
  checkLaws("Codec[RecursiveWithOptionExample]", CodecTests[RecursiveWithOptionExample].unserializableCodec)
  checkLaws("Codec[RecursiveWithListExample]", CodecTests[RecursiveWithListExample].unserializableCodec)
  checkLaws("Codec[AnyValInside]", CodecTests[AnyValInside].unserializableCodec)

  "A generically derived codec" should "not interfere with base instances" in forAll { (is: List[Int]) =>
    val json = Encoder[List[Int]].apply(is)

    assert(json === Json.fromValues(is.map(Json.fromInt)) && json.as[List[Int]] === Right(is))
  }

  it should "not be derived for Object" in {
    illTyped("Decoder[Object]")
    illTyped("Encoder[Object]")
  }

  it should "not be derived for AnyRef" in {
    illTyped("Decoder[AnyRef]")
    illTyped("Encoder[AnyRef]")
  }

  "Generic decoders" should "not interfere with defined decoders" in forAll { (xs: List[String]) =>
    val json = Json.obj("SubtypeWithExplicitInstance" -> Json.fromValues(xs.map(Json.fromString)))
    val ch = Decoder[Sealed].apply(json.hcursor)
    val res = ch === Right(SubtypeWithExplicitInstance(xs): Sealed)
    assert(res)
  }

  "Generic encoders" should "not interfere with defined encoders" in forAll { (xs: List[String]) =>
    val json = Json.obj("SubtypeWithExplicitInstance" -> Json.fromValues(xs.map(Json.fromString)))

    assert(Encoder[Sealed].apply(SubtypeWithExplicitInstance(xs): Sealed) === json)
  }

  // TODO: tagged types don't work ATM, might be related to https://github.com/propensive/magnolia/issues/89
  //  checkLaws("Codec[WithTaggedMembers]", CodecTests[WithTaggedMembers].unserializableCodec)
  checkLaws("Codec[Seq[WithSeqOfTagged]]", CodecTests[Seq[WithSeqOfTagged]].unserializableCodec)
} 
Example 17
Source File: TypedStringIndexerTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package feature

import frameless.ml.feature.TypedStringIndexer.HandleInvalid
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Prop._
import shapeless.test.illTyped
import org.scalatest.matchers.must.Matchers

class TypedStringIndexerTests extends FramelessMlSuite with Matchers {

  test(".fit() returns a correct TypedTransformer") {
    def prop[A: TypedEncoder : Arbitrary] = forAll { x2: X2[String, A] =>
      val indexer = TypedStringIndexer[X1[String]]
      val ds = TypedDataset.create(Seq(x2))
      val model = indexer.fit(ds).run()
      val resultDs = model.transform(ds).as[X3[String, A, Double]]

      resultDs.collect.run() == Seq(X3(x2.a, x2.b, 0D))
    }

    check(prop[Double])
    check(prop[String])
  }

  test("param setting is retained") {
    implicit val arbHandleInvalid: Arbitrary[HandleInvalid] = Arbitrary {
      Gen.oneOf(HandleInvalid.Keep, HandleInvalid.Error, HandleInvalid.Skip)
    }

    val prop = forAll { handleInvalid: HandleInvalid =>
      val indexer = TypedStringIndexer[X1[String]]
        .setHandleInvalid(handleInvalid)
      val ds = TypedDataset.create(Seq(X1("foo")))
      val model = indexer.fit(ds).run()

      model.transformer.getHandleInvalid == handleInvalid.sparkValue
    }

    check(prop)
  }

  test("create() compiles only with correct inputs") {
    illTyped("TypedStringIndexer.create[Double]()")
    illTyped("TypedStringIndexer.create[X1[Double]]()")
    illTyped("TypedStringIndexer.create[X2[String, Long]]()")
  }

} 
Example 18
Source File: TypedRandomForestClassifierTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package classification

import shapeless.test.illTyped
import org.apache.spark.ml.linalg._
import frameless.ml.params.trees.FeatureSubsetStrategy
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Prop._
import org.scalatest.matchers.must.Matchers

class TypedRandomForestClassifierTests extends FramelessMlSuite with Matchers {
  implicit val arbDouble: Arbitrary[Double] =
    Arbitrary(Gen.choose(1, 99).map(_.toDouble)) // num classes must be between 0 and 100 for the test
  implicit val arbVectorNonEmpty: Arbitrary[Vector] =
    Arbitrary(Generators.arbVector.arbitrary suchThat (_.size > 0)) // vector must not be empty for RandomForestClassifier
  import Generators.arbTreesFeaturesSubsetStrategy

  test("fit() returns a correct TypedTransformer") {
    val prop = forAll { x2: X2[Double, Vector] =>
      val rf = TypedRandomForestClassifier[X2[Double, Vector]]
      val ds = TypedDataset.create(Seq(x2))
      val model = rf.fit(ds).run()
      val pDs = model.transform(ds).as[X5[Double, Vector, Vector, Vector, Double]]

      pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b)
    }

    val prop2 = forAll { x2: X2[Vector, Double] =>
      val rf = TypedRandomForestClassifier[X2[Vector, Double]]
      val ds = TypedDataset.create(Seq(x2))
      val model = rf.fit(ds).run()
      val pDs = model.transform(ds).as[X5[Vector, Double, Vector, Vector, Double]]

      pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b)
    }

    def prop3[A: TypedEncoder: Arbitrary] = forAll { x3: X3[Vector, Double, A] =>
      val rf = TypedRandomForestClassifier[X2[Vector, Double]]
      val ds = TypedDataset.create(Seq(x3))
      val model = rf.fit(ds).run()
      val pDs = model.transform(ds).as[X6[Vector, Double, A, Vector, Vector, Double]]

      pDs.select(pDs.col('a), pDs.col('b), pDs.col('c)).collect.run() == Seq((x3.a, x3.b, x3.c))
    }

    check(prop)
    check(prop2)
    check(prop3[String])
    check(prop3[Double])
  }

  test("param setting is retained") {
    val prop = forAll { featureSubsetStrategy: FeatureSubsetStrategy =>
      val rf = TypedRandomForestClassifier[X2[Double, Vector]]
        .setNumTrees(10)
        .setMaxBins(100)
        .setFeatureSubsetStrategy(featureSubsetStrategy)
        .setMaxDepth(10)
        .setMaxMemoryInMB(100)
        .setMinInfoGain(0.1D)
        .setMinInstancesPerNode(2)
        .setSubsamplingRate(0.9D)

      val ds = TypedDataset.create(Seq(X2(0D, Vectors.dense(0D))))
      val model = rf.fit(ds).run()

      model.transformer.getNumTrees == 10 &&
        model.transformer.getMaxBins == 100 &&
        model.transformer.getFeatureSubsetStrategy == featureSubsetStrategy.sparkValue &&
        model.transformer.getMaxDepth == 10 &&
        model.transformer.getMaxMemoryInMB == 100 &&
        model.transformer.getMinInfoGain == 0.1D &&
        model.transformer.getMinInstancesPerNode == 2 &&
        model.transformer.getSubsamplingRate == 0.9D
    }

    check(prop)
  }

  test("create() compiles only with correct inputs") {
    illTyped("TypedRandomForestClassifier.create[Double]()")
    illTyped("TypedRandomForestClassifier.create[X1[Double]]()")
    illTyped("TypedRandomForestClassifier.create[X2[Double, Double]]()")
    illTyped("TypedRandomForestClassifier.create[X3[Vector, Double, Int]]()")
    illTyped("TypedRandomForestClassifier.create[X2[Vector, String]]()")
  }

} 
Example 19
Source File: TypedRandomForestRegressorTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package regression

import frameless.ml.params.trees.FeatureSubsetStrategy
import shapeless.test.illTyped
import org.apache.spark.ml.linalg._
import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import org.scalatest.matchers.must.Matchers

class TypedRandomForestRegressorTests extends FramelessMlSuite with Matchers {
  implicit val arbVectorNonEmpty: Arbitrary[Vector] =
    Arbitrary(Generators.arbVector.arbitrary suchThat (_.size > 0)) // vector must not be empty for RandomForestRegressor
  import Generators.arbTreesFeaturesSubsetStrategy

  test("fit() returns a correct TypedTransformer") {
    val prop = forAll { x2: X2[Double, Vector] =>
      val rf = TypedRandomForestRegressor[X2[Double, Vector]]
      val ds = TypedDataset.create(Seq(x2))
      val model = rf.fit(ds).run()
      val pDs = model.transform(ds).as[X3[Double, Vector, Double]]

      pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b)
    }

    val prop2 = forAll { x2: X2[Vector, Double] =>
      val rf = TypedRandomForestRegressor[X2[Vector, Double]]
      val ds = TypedDataset.create(Seq(x2))
      val model = rf.fit(ds).run()
      val pDs = model.transform(ds).as[X3[Vector, Double, Double]]

      pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b)
    }

    def prop3[A: TypedEncoder: Arbitrary] = forAll { x3: X3[Vector, Double, A] =>
      val rf = TypedRandomForestRegressor[X2[Vector, Double]]
      val ds = TypedDataset.create(Seq(x3))
      val model = rf.fit(ds).run()
      val pDs = model.transform(ds).as[X4[Vector, Double, A, Double]]

      pDs.select(pDs.col('a), pDs.col('b), pDs.col('c)).collect.run() == Seq((x3.a, x3.b, x3.c))
    }

    check(prop)
    check(prop2)
    check(prop3[String])
    check(prop3[Double])
  }

  test("param setting is retained") {
    val prop = forAll { featureSubsetStrategy: FeatureSubsetStrategy =>
      val rf = TypedRandomForestRegressor[X2[Double, Vector]]
        .setNumTrees(10)
        .setMaxBins(100)
        .setFeatureSubsetStrategy(featureSubsetStrategy)
        .setMaxDepth(10)
        .setMaxMemoryInMB(100)
        .setMinInfoGain(0.1D)
        .setMinInstancesPerNode(2)
        .setSubsamplingRate(0.9D)

      val ds = TypedDataset.create(Seq(X2(0D, Vectors.dense(0D))))
      val model = rf.fit(ds).run()

      model.transformer.getNumTrees == 10 &&
        model.transformer.getMaxBins == 100 &&
        model.transformer.getFeatureSubsetStrategy == featureSubsetStrategy.sparkValue &&
        model.transformer.getMaxDepth == 10 &&
        model.transformer.getMaxMemoryInMB == 100 &&
        model.transformer.getMinInfoGain == 0.1D &&
        model.transformer.getMinInstancesPerNode == 2 &&
        model.transformer.getSubsamplingRate == 0.9D
    }

    check(prop)
  }

  test("create() compiles only with correct inputs") {
    illTyped("TypedRandomForestRegressor.create[Double]()")
    illTyped("TypedRandomForestRegressor.create[X1[Double]]()")
    illTyped("TypedRandomForestRegressor.create[X2[Double, Double]]()")
    illTyped("TypedRandomForestRegressor.create[X3[Vector, Double, Int]]()")
    illTyped("TypedRandomForestRegressor.create[X2[Vector, String]]()")
  }

} 
Example 20
Source File: EnumerationSemiautoDerivedSuite.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras

import io.circe.{ Codec, Decoder, Encoder }
import io.circe.generic.extras.semiauto._
import io.circe.literal._
import io.circe.testing.CodecTests
import shapeless.test.illTyped

import examples._

class EnumerationSemiautoDerivedSuite extends CirceSuite {
  implicit val decodeCardinalDirection: Decoder[CardinalDirection] = deriveEnumerationDecoder
  implicit val encodeCardinalDirection: Encoder[CardinalDirection] = deriveEnumerationEncoder
  val codecForCardinalDirection: Codec[CardinalDirection] = deriveEnumerationCodec

  checkLaws("Codec[CardinalDirection]", CodecTests[CardinalDirection].codec)
  checkLaws(
    "Codec[CardinalDirection] via Codec",
    CodecTests[CardinalDirection](codecForCardinalDirection, codecForCardinalDirection).codec
  )
  checkLaws(
    "Codec[CardinalDirection] via Decoder and Codec",
    CodecTests[CardinalDirection](implicitly, codecForCardinalDirection).codec
  )
  checkLaws(
    "Codec[CardinalDirection] via Encoder and Codec",
    CodecTests[CardinalDirection](codecForCardinalDirection, implicitly).codec
  )

  "deriveEnumerationDecoder" should "not compile on an ADT with case classes" in {
    implicit val config: Configuration = Configuration.default
    illTyped("deriveEnumerationDecoder[ExtendedCardinalDirection]")
  }

  it should "respect Configuration" in {
    implicit val config: Configuration = Configuration.default.withSnakeCaseConstructorNames
    val decodeMary = deriveEnumerationDecoder[Mary]
    val expected = json""""little_lamb""""
    assert(decodeMary.decodeJson(expected) === Right(LittleLamb))
  }

  "deriveEnumerationEncoder" should "not compile on an ADT with case classes" in {
    implicit val config: Configuration = Configuration.default
    illTyped("deriveEnumerationEncoder[ExtendedCardinalDirection]")
  }

  it should "respect Configuration" in {
    implicit val config: Configuration = Configuration.default.withSnakeCaseConstructorNames
    val encodeMary = deriveEnumerationEncoder[Mary]
    val expected = json""""little_lamb""""
    assert(encodeMary(LittleLamb) === expected)
  }
} 
Example 21
Source File: pure.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import alleycats.Pure
import cats.data.NonEmptyList
import cats.instances.all._
import cats.laws.discipline.SerializableTests
import shapeless.test.illTyped

class PureSuite extends KittensSuite {
  import PureSuite._
  import TestDefns._

  def testPure(context: String)(
    implicit lOption: Pure[LOption],
    pList: Pure[PList],
    caseClassWOption: Pure[CaseClassWOption],
    nelOption: Pure[NelOption],
    interleaved: Pure[Interleaved],
    boxColor: Pure[BoxColor]
  ): Unit = {
    test(s"$context.Pure[LOption]")(assert(lOption.pure(42) == Some(42) :: Nil))
    test(s"$context.Pure[PList]")(assert(pList.pure("Scala") == ("Scala" :: Nil, "Scala" :: Nil)))
    test(s"$context.Pure[CaseClassWOption]")(assert(caseClassWOption.pure(3.14) == CaseClassWOption(Some(3.14))))
    test(s"$context.Pure[NelOption]")(assert(nelOption.pure(42) == NonEmptyList.of(Some(42))))
    test(s"$context.Pure[Interleaved]")(assert(interleaved.pure('x') == Interleaved(0, 'x', 0, 'x' :: Nil, "")))
    test(s"$context.Pure respects existing instances")(assert(boxColor.pure(()) == Box(Color(255, 255, 255))))
    checkAll(s"$context.Pure is Serializable", SerializableTests.serializable(Pure[Interleaved]))
  }

  {
    import auto.pure._
    testPure("auto")
    illTyped("Pure[IList]")
    illTyped("Pure[Snoc]")
  }

  {
    import cached.pure._
    testPure("cached")
    illTyped("Pure[IList]")
    illTyped("Pure[Snoc]")
  }

  {
    import semiInstances._
    testPure("semiauto")
    illTyped("semiauto.pure[IList]")
    illTyped("semiauto.pure[Snoc]")
  }
}

object PureSuite {
  import TestDefns._

  type LOption[A] = List[Option[A]]
  type PList[A] = (List[A], List[A])
  type NelOption[A] = NonEmptyList[Option[A]]
  type BoxColor[A] = Box[Color[A]]

  object semiInstances {
    implicit val lOption: Pure[LOption] = semiauto.pure
    implicit val pList: Pure[PList] = semiauto.pure
    implicit val caseClassWOption: Pure[CaseClassWOption] = semiauto.pure
    implicit val nelOption: Pure[NelOption] = semiauto.pure
    implicit val interleaved: Pure[Interleaved] = semiauto.pure
    implicit val boxColor: Pure[BoxColor] = semiauto.pure
  }

  final case class Color[A](r: Int, g: Int, b: Int)
  object Color {

    implicit val pure: Pure[Color] = new Pure[Color] {
      def pure[A](value: A) = Color(255, 255, 255)
    }
  }
} 
Example 22
Source File: emptyk.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import alleycats.{EmptyK, Pure}
import alleycats.std.all._
import cats.data.NonEmptyList
import cats.laws.discipline.SerializableTests
import cats.instances.all._
import shapeless.test.illTyped

class EmptyKSuite extends KittensSuite {
  import EmptyKSuite._
  import TestDefns._

  def testEmptyK(context: String)(
    implicit lOption: EmptyK[LOption],
    pList: EmptyK[PList],
    caseClassWOption: EmptyK[CaseClassWOption],
    nelOption: EmptyK[NelOption],
    boxColor: EmptyK[BoxColor]
  ): Unit = {
    test(s"$context.EmptyK[LOption]")(assert(lOption.empty == Nil))
    test(s"$context.EmptyK[PList]")(assert(pList.empty == (Nil, Nil)))
    test(s"$context.EmptyK[CaseClassWOption]")(assert(caseClassWOption.empty == CaseClassWOption(None)))
    test(s"$context.EmptyK[NelOption]")(assert(nelOption.empty == NonEmptyList.of(None)))
    test(s"$context.EmptyK respects existing instances")(assert(boxColor.empty == Box(Color(255, 255, 255))))
    checkAll(s"$context.EmptyK is Serializable", SerializableTests.serializable(EmptyK[PList]))
  }

  implicit val pureBox: Pure[Box] = new Pure[Box] {
    def pure[A](a: A) = Box(a)
  }

  {
    import auto.emptyK._
    testEmptyK("auto")
    illTyped("EmptyK[IList]")
    illTyped("EmptyK[Snoc]")
  }

  {
    import cached.emptyK._
    testEmptyK("cached")
    illTyped("EmptyK[IList]")
    illTyped("EmptyK[Snoc]")
  }

  {
    import semiInstances._
    testEmptyK("semiauto")
    illTyped("semiauto.emptyK[IList]")
    illTyped("semiauto.emptyK[Snoc]")
  }
}

object EmptyKSuite {
  import TestDefns._

  type LOption[A] = List[Option[A]]
  type PList[A] = (List[A], List[A])
  type NelOption[A] = NonEmptyList[Option[A]]
  type BoxColor[A] = Box[Color[A]]

  object semiInstances {
    implicit val lOption: EmptyK[LOption] = semiauto.emptyK
    implicit val pList: EmptyK[PList] = semiauto.emptyK
    implicit val caseClassWOption: EmptyK[CaseClassWOption] = semiauto.emptyK
    implicit val nelOption: EmptyK[NelOption] = semiauto.emptyK
    implicit val boxColor: EmptyK[BoxColor] = semiauto.emptyK
  }

  final case class Color[A](r: Int, g: Int, b: Int)
  object Color {

    implicit val emptyK: EmptyK[Color] = new EmptyK[Color] {
      def empty[A] = Color(255, 255, 255)
    }
  }
} 
Example 23
Source File: empty.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import alleycats.Empty
import cats.instances.all._
import cats.laws.discipline.SerializableTests
import shapeless.test.illTyped

class EmptySuite extends KittensSuite {
  import EmptySuite._
  import TestDefns._

  def testEmpty(context: String)(
    implicit foo: Empty[Foo],
    outer: Empty[Outer],
    interleaved: Empty[Interleaved[String]],
    recursive: Empty[Recursive],
    iList: Empty[IList[Dummy]],
    snoc: Empty[Snoc[Dummy]],
    box: Empty[Box[Mask]],
    chain: Empty[Chain]
  ): Unit = {
    test(s"$context.Empty[Foo]")(assert(foo.empty == Foo(0, None)))
    test(s"$context.Empty[Outer]")(assert(outer.empty == Outer(Inner(0))))
    test(s"$context.Empty[Interleaved[String]]")(assert(interleaved.empty == Interleaved(0, "", 0, Nil, "")))
    test(s"$context.Empty[Recursive]")(assert(recursive.empty == Recursive(0, None)))
    test(s"$context.Empty[IList[Dummy]]")(assert(iList.empty == INil()))
    test(s"$context.Empty[Snoc[Dummy]]")(assert(snoc.empty == SNil()))
    test(s"$context.Empty respects existing instances")(assert(box.empty == Box(Mask(0xffffffff))))
    // Known limitation of recursive typeclass derivation.
    test(s"$context.Empty[Chain] throws a StackOverflowError") {
      val throwable = intercept[Throwable](chain.empty)
      val jvm = throwable.isInstanceOf[StackOverflowError]
      val js = Option(throwable.getMessage).exists(_.contains("stack size exceeded"))
      assert(jvm || js)
    }
    checkAll(s"$context.Empty is Serializable", SerializableTests.serializable(Empty[Interleaved[String]]))
  }

  {
    import auto.empty._
    testEmpty("auto")
    illTyped("Empty[IList[Int]]")
    illTyped("Empty[Snoc[Int]]")
    illTyped("Empty[Rgb]")
  }

  {
    import cached.empty._
    testEmpty("cached")
    illTyped("Empty[IList[Int]]")
    illTyped("Empty[Snoc[Int]]")
    illTyped("Empty[Rgb]")
  }

  {
    import semiInstances._
    illTyped("semi.empty[IList[Int]]")
    illTyped("semi.empty[Snoc[Int]]")
    illTyped("semi.empty[Rgb]")
    testEmpty("semiauto")
  }
}

object EmptySuite {
  import TestDefns._

  // `Monoid[Option[A]]` gives us `Empty[Option[A]]` but it requires a `Semigroup[A]`.
  implicit def emptyOption[A]: Empty[Option[A]] = Empty(None)

  object semiInstances {
    implicit val foo: Empty[Foo] = semiauto.empty
    implicit val outer: Empty[Outer] = semiauto.empty
    implicit val interleaved: Empty[Interleaved[String]] = semiauto.empty
    implicit val recursive: Empty[Recursive] = semiauto.empty
    implicit val iList: Empty[IList[Dummy]] = semiauto.empty
    implicit val snoc: Empty[Snoc[Dummy]] = semiauto.empty
    implicit val box: Empty[Box[Mask]] = semiauto.empty
    implicit val chain: Empty[Chain] = semiauto.empty
  }

  trait Dummy
  final case class Chain(head: Int, tail: Chain)
  final case class Mask(bits: Int)
  object Mask {
    implicit val empty: Empty[Mask] = Empty(Mask(0xffffffff))
  }
} 
Example 24
Source File: IllegalConstructsSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core

import org.scalatest.FreeSpec
import shapeless.test.illTyped

class IllegalConstructsSpec extends FreeSpec {

  "Illegal DSL constructs shouldn't compile" - {

    "illegal switch fanout continue with too few substreams" in {
      illTyped(
        """Spout(1, 2, 3)
           .fanOutSwitch(2)(i => if (i > 0) 1 else 0)
           .sub.end
           .continue""",
        "Cannot `continue` here! You still have at least one unconsumed fan-out sub-stream.")
    }

    "illegal switch fanout subContinue with too few substreams" in {
      illTyped(
        """Spout(1, 2, 3)
           .fanOutSwitch(2)(i => if (i > 0) 1 else 0)
           .subContinue""",
        "`subContinue` is only possible with exactly one remaining fan-out sub-stream unconsumed!")
    }

    "illegal switch fanout sub with too many substreams" in {
      illTyped(
        """Spout(1, 2, 3)
           .fanOutSwitch(2)(i => if (i > 0) 1 else 0)
           .sub.end
           .sub.end
           .sub.end""",
        "Illegal substream definition! All available fan-out sub-streams have already been consumed.")
    }

    "illegal fanout continue with zero unterminated fanin sub-streams" in {
      illTyped(
        """Spout(1, 2, 3)
           .fanOutBroadcast()
           .continue""",
        "Continuation is only possible with exactly one open fan-in sub-stream!")
    }

    "illegal fanout continue with two unterminated fanin sub-streams" in {
      illTyped(
        """Spout(1, 2, 3)
           .fanOutBroadcast()
           .sub.end
           .sub.end
           .continue""",
        "Continuation is only possible with exactly one open fan-in sub-stream!")
    }

    "illegal zero sub fanin" in {
      illTyped(
        """Spout(1, 2, 3)
           .fanOutBroadcast()
           .fanInConcat()""",
        "Cannot fan-in here. You need to have at least two open fan-in sub-streams.")
    }
  }
} 
Example 25
Source File: NumericTaggingSuite.scala    From protoless   with Apache License 2.0 5 votes vote down vote up
package io.protoless.tag

import org.scalatest.FreeSpec
import shapeless.test.illTyped

class NumericTaggingSuite extends FreeSpec {

  "Numeric tagging must be allowed on" - {

    "Int" in {
      signed(1)
      unsigned(1)
      fixed(1)
      signedFixed(1)
    }

    "Long" in {
      signed(1L)
      unsigned(1L)
      fixed(1L)
      signedFixed(1L)
    }

    "no other numeric type" in {
      illTyped("""signed(1f)""")
      illTyped("""signed(1d)""")
      illTyped("""signed(1.toShort)""")
      illTyped("""signed(BigDecimal(1))""")
    }

    "no other exotic type" in {
      illTyped("""signed("1")""")
      illTyped("""signed(Seq(1, 2, 3))""")
      illTyped("""signed(true)""")
    }
  }
} 
Example 26
Source File: ValueClassSuite.scala    From protoless   with Apache License 2.0 5 votes vote down vote up
package io.protoless.fields

import io.protoless.tests.ProtolessSuite

import shapeless.test.illTyped

case class ValueClass(x: Int) extends AnyVal
case class NotValueClass(x: Int)

class ValueClassClassSuite extends ProtolessSuite {

  private val bytes = Seq(0x08, 0x96, 0x01).map(_.toByte).toArray // number 150 at field 1
  private val valueClass = ValueClass(150)

  "value class must be decoded" in {
    val dec: FieldDecoder[ValueClass] = FieldDecoder[ValueClass]
    dec.decode(bytes, 1) must ===(Right(valueClass))
  }

  "value class must be encoded" in {
    val enc: FieldEncoder[ValueClass] = FieldEncoder[ValueClass]
    enc.encodeAsBytes(1, valueClass) must ===(bytes)
  }

  "Class not inheriting AnyVal must not be decoded like ValueClass" in {
    illTyped("""FieldDecoder[NotValueClass]""")
    illTyped("""FieldDecoder.decodeValueClass.read(bytes, 1)""")
  }

  "Class not inheriting AnyVal must not be encoded like ValueClass" in {
    illTyped("""FieldEncoder[NotValueClass]""")
    illTyped("""FieldEncoder.encodeValueClass.encodeAsByte(1, NotValueClass(1))""")
  }

} 
Example 27
Source File: CodecForColumnSpec.scala    From troy   with Apache License 2.0 5 votes vote down vote up
package troy
package driver.schema

import org.scalatest.{FlatSpec, Matchers}
import shapeless.test.illTyped
import troy.driver.{CassandraDataType => CDT}
import troy.driver.codecs.TroyCodec
import troy.driver.codecs.PrimitivesCodecs.intAsInt
import troy.driver.schema.column.{CodecForColumn, ColumnType}
import troy.driver.schema.KeyspaceExists
import troy.driver.schema.TableExists
import troy.driver.schema.VersionExists

class CodecForColumnSpec extends FlatSpec with Matchers {
  implicit val v1Exists = VersionExists.instance[1]
  implicit val keyspaceTestExists = KeyspaceExists.instance[1, "my_keyspace"]
  implicit val tablePostsInKeyspaceTestExists = TableExists.instance[1, "my_keyspace", "my_table"]

  implicit val column1 = ColumnType.instance[1, "my_keyspace", "my_table", "my_column_1", CDT.Ascii]
  implicit val column2 = ColumnType.instance[1, "my_keyspace", "my_table", "my_column_2", CDT.Int]
  implicit val column3 = ColumnType.instance[1, "my_keyspace", "my_table", "my_column_3", CDT.List[CDT.Int]]
  implicit val column4 = ColumnType.instance[1, "my_keyspace", "my_table", "my_column_4", CDT.Map[CDT.Int, CDT.Ascii]]

  CodecForColumn[1, "my_keyspace", "my_table", "my_column_1"].codec: TroyCodec[CDT.Ascii, String]
  CodecForColumn[1, "my_keyspace", "my_table", "my_column_2"].codec: TroyCodec[CDT.Int, Int]
  CodecForColumn[1, "my_keyspace", "my_table", "my_column_3"].codec: TroyCodec[CDT.List[CDT.Int], Seq[Int]]
  CodecForColumn[1, "my_keyspace", "my_table", "my_column_4"].codec: TroyCodec[CDT.Map[CDT.Int, CDT.Ascii], Map[Int, String]]

  "Fetching codec for non existing column" should "fail" in {
    illTyped(
      """
        CodecForColumn[1, "my_keyspace", "my_table", "my_column_99"].codec
      """)
  }
} 
Example 28
Source File: DescrSpec.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.swagger

import ru.tinkoff.tschema.swagger.DescrSpec._
import shapeless.syntax.singleton._
import shapeless.test.illTyped
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import ru.tinkoff.tschema.swagger.Swagger

class DescrSpec extends AnyFlatSpec with Matchers {
  "descr" should "set description for existing field" in assert(
    Swagger
      .instance[Foo]
      .descr(Symbol("x") ->> xDescr)
      .typ
      .asInstanceOf[SwaggerRef]
      .typ
      .value
      .asInstanceOf[SwaggerObject]
      .properties
      .map(prop => (prop.name, prop.description, prop.typ.value)) ===
      Vector(("x", Some(xDescr), SwaggerPrimitive.string), ("y", None, SwaggerPrimitive.integer))
  )

  it should " not compile if for nonexisting field" in {
    illTyped("""SwaggerTypeable.deriveNamedTypeable[Foo].descr('z ->> "bar")""")
  }

  val barTyp = SwaggerTypeable.deriveNamedTypeable[Bar].typ

  "DescribeTypeable" should "set description for type" in assert(barTyp match {
    case ref: SwaggerRef => ref.descr.contains(barDescr)
    case _               => false
  })
  it should "set description for fields" in assert(barTyp.deref.value match {
    case obj: SwaggerObject =>
      obj.properties.forall {
        case SwaggerProperty("x", None, _)           => true
        case SwaggerProperty("y", Some(`yDescr`), _) => true
        case _                                       => false
      }
    case _                  => false
  })

}

object DescrSpec {
  final case class Foo(x: String, y: Int)
  final case class Bar(x: String, y: String)
  val barDescr = "Bar type"
  val xDescr   = "IPhone 10 version"
  val yDescr   = "Real men's chromosome"

  implicit val barDescription: DescribeTypeable[Bar] = DescribeTypeable.make[Bar](barDescr, "y" -> yDescr)
} 
Example 29
Source File: MagnoliaSpec.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.swagger
import io.circe.Printer
import ru.tinkoff.tschema.swagger.testDomain.{LotOfVariants, TopStuff, WeirdThing}
import shapeless.test.illTyped
import org.scalatest.flatspec.AnyFlatSpec

class MagnoliaSpec extends AnyFlatSpec {
  import MagnoliaSwagger.{derive => magnoliaDerive}

  "magnolia" should "derive known types" in {
    implicit lazy val weirdThingSwaggerTypeable: SwaggerTypeable[WeirdThing] =
      SwaggerTypeable.make(SwaggerPrimitive.boolean).as[WeirdThing]
    implicit lazy val lots: SwaggerTypeable[LotOfVariants]                   = MagnoliaSwagger.derivedInstance
    lazy val testSwagger: SwaggerTypeable[TopStuff]                          = magnoliaDerive
  }

  it should "not derive unknown types" in {
    illTyped("""lazy val testSwagger: SwaggerTypeable[TopStuff] = magnoliaDerive""")
  }
}

object MagnoliaSpec {

  implicit val cfg: SwaggerTypeable.Config =
    SwaggerTypeable.defaultConfig.snakeCaseProps.snakeCaseAlts.withDiscriminator("type")
  implicit val printer                     = Printer.spaces4.copy(dropNullValues = true)
} 
Example 30
Source File: GetLHSArgSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

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

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

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

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

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

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

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

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

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

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


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

package com.daml.ledger.client.binding

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

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

class TemplateSpec extends WordSpec with Matchers with GeneratorDrivenPropertyChecks {
  import TemplateSpec._
  // avoid importing CNA to test that implicit resolution is working properly

  "Template subclasses" when {
    "having colliding names" should {
      val cna = Tmpls.CNA("id", 1, 2, 3, 4)
      "resolve 'create' properly" in {
        val c = cna.create
        identity[P.Int64](c)
        illTyped("cna.create: Primitive.Update[Tmpls.CNA]", "(?s).*found[^\n]*Int64.*")
        val u = (cna: Template[Tmpls.CNA]).create
        identity[P.Update[P.ContractId[Tmpls.CNA]]](u)
      }
    }

    "a companion is defined" should {
      "resolve Value implicitly" in {
        implicitly[Value[Tmpls.CNA]]
      }

      "resolve the companion implicitly" in {
        implicitly[TemplateCompanion[Tmpls.CNA]]
      }
    }
  }
}

object TemplateSpec {
  object Tmpls {
    final case class CNA(
        id: P.Text,
        template: P.Int64,
        create: P.Int64,
        namedArguments: P.Int64,
        archive: P.Int64)
        extends Template[CNA] {
      protected[this] override def templateCompanion(implicit d: DummyImplicit) = CNA
    }
    // We've already passed the first test, by scalac checking that
    // these don't conflict with inherited names post-erasure.

    object CNA extends TemplateCompanion.Empty[CNA] {
      override protected val onlyInstance = CNA("", 0, 0, 0, 0)
      val id = P.TemplateId("hi", "there", "you")
      val consumingChoices = Set()
    }
  }
} 
Example 32
Source File: RefTypeSpecScalazTag.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalaz

import _root_.scalaz.@@
import _root_.scalaz.std.anyVal._
import _root_.scalaz.syntax.equal._
import _root_.scalaz.syntax.show._
import eu.timepit.refined.TestUtils._
import eu.timepit.refined.api.{RefType, RefTypeSpec}
import eu.timepit.refined.numeric._
import eu.timepit.refined.scalaz.auto._
import org.scalacheck.Prop._
import shapeless.test.illTyped

class RefTypeSpecScalazTag extends RefTypeSpec[@@]("scalaz.@@") {

  property("refineM with type alias") = secure {
    type PositiveInt = Int @@ Positive

    val x: PositiveInt = RefType[@@].refineM(5)
    val y: PositiveInt = 5
    val z = 5: PositiveInt
    illTyped("val a: PositiveInt = -5", "Predicate failed: \\(-5 > 0\\).*")
    x == y && y == z
  }

  property("(T @@ P) <!: T") = wellTyped {
    illTyped("implicitly[(Int @@ Positive) <:< Int]", "Cannot prove.*")
  }

  property("scalaz.Equal") = secure {
    type PosInt = Int @@ Positive
    val x: PosInt = 5
    val y: PosInt = 5
    x === y
  }

  property("scalaz.Show") = secure {
    type PosInt = Int @@ Positive
    val x: PosInt = 5
    x.shows ?= "5"
  }
} 
Example 33
Source File: EvalValidateSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

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

class EvalValidateSpec extends Properties("EvalValidate") {

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

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

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

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

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

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

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

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

class RefTypeCodecSpec extends Properties("RefTypeCodec") {

  type PosInt = Int Refined Positive
  implicit val intCodec = int8

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class AutoSpec extends Properties("auto") {

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

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

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

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

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

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

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

class RefineMSpec extends Properties("refineM") {

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

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

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

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

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

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

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

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

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

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

class BigLiteralsSpec extends Properties("BigLiterals") {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class RefineSyntaxSpec extends Properties("refine syntax") {

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

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

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

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

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

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

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

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

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

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

class RefinedSpec extends Properties("Refined") {

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

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

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

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

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

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

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

class CollectionInferenceSpec extends Properties("CollectionInference") {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

final case class CrashOnTypeTag[A]()

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

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

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

  property("CrashOnTypeTag[Int => String]") = wellTyped {
    illTyped(
      """ val crash: String @@ CrashOnTypeTag[Int => String] = "function" """,
      ".*java.lang.ClassNotFoundException.*"
    )
  }
} 
Example 44
Source File: NegateSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

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

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

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

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

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

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

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

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

  property("String argument") = {
    illTyped("""implicitly[Negate[W.`"Something"`.T]]""")
    true
  }
} 
Example 45
Source File: PrimitiveSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding

import java.time.{Instant, LocalDate}

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

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

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

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

  "Date.fromLocalDate" should {
    import ValueSpec.dateArb

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

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

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

  "Timestamp.discardNanos" should {
    import ValueSpec.timestampArb

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

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

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

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

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

  private val anyInstantGen: Gen[Instant] =
    Gen
      .zip(
        Gen.choose(Instant.MIN.getEpochSecond, Instant.MAX.getEpochSecond),
        Gen.choose(0L, 999999999))
      .map { case (s, n) => Instant.ofEpochSecond(s, n) }
} 
Example 46
Source File: StringOpsSpec.scala    From singleton-ops   with Apache License 2.0 5 votes vote down vote up
package singleton.ops

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import java.util.UUID

import shapeless.test.{ typed, illTyped }

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalactic.TypeCheckedTripleEquals

class UUIDMacroSpec extends AnyFlatSpec with Matchers with TypeCheckedTripleEquals {

  def uuid: Nothing = sys.error("this should never be invoked")

  "UUID literal macro" should "work" in {
    val x = uuid"3a108ce3-9284-4883-a72c-71ced1f30e4c"
    typed[UUID] { x }
    x.variant should === (2)
    x.version should === (4)
    x should === (UUID.fromString("3a108ce3-9284-4883-a72c-71ced1f30e4c"))
  }

  it should "reject non-RFC-4122 UUIDs" in {
    val str = "00000000-0000-0001-0000-000000000002"
    val u = UUID.fromString(str)
    u.variant should !== (2)
    illTyped(
      """uuid"00000000-0000-0001-0000-000000000002"""",
      ".*not an RFC-4122 UUID.*"
    )
  }

  it should "reject syntactically invalid strings" in {
    illTyped(
      """uuid"abcd"""",
      ".*not a valid UUID.*"
    )
  }

  it should "only accept string literals" in {
    illTyped(
      """
        val v: String = "3a108ce3-9284-4883-a72c-71ced1f30e4c"
        StringContext(v).uuid()
      """,
      ".*not a string literal.*"
    )
  }
}