eu.timepit.refined.collection.NonEmpty Scala Examples
The following examples show how to use eu.timepit.refined.collection.NonEmpty.
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: users.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.model import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.NonEmpty object users { final case class UserCredentials( email: String Refined NonEmpty, username: String Refined NonEmpty, password: String Refined NonEmpty, fullName: String Refined NonEmpty, useProvider: Boolean, register: Boolean ) { def userNamespace: String = { val un = username.value un.replace("+", "") } } }
Example 2
Source File: User.scala From whirlwind-tour-akka-typed with Apache License 2.0 | 5 votes |
package de.heikoseeberger.wtat import cats.data.{ NonEmptyList, Validated } import cats.syntax.apply._ import cats.syntax.either._ import eu.timepit.refined.api.Refined import eu.timepit.refined.boolean.And import eu.timepit.refined.char.LetterOrDigit import eu.timepit.refined.collection.{ Forall, NonEmpty } import eu.timepit.refined.refineV object User { type Username = Refined[String, UsernameRefinement] type UsernameRefinement = And[NonEmpty, Forall[LetterOrDigit]] type Nickname = Refined[String, NicknameRefinement] type NicknameRefinement = NonEmpty def apply(username: String, nickname: String): Validated[NonEmptyList[String], User] = (validateUsername(username), validateNickname(nickname)).mapN(new User(_, _)) def validateUsername(username: String): Validated[NonEmptyList[String], Username] = refineV[UsernameRefinement](username).toValidatedNel def validateNickname(nickname: String): Validated[NonEmptyList[String], Nickname] = refineV[NicknameRefinement](nickname).toValidatedNel } final case class User(username: User.Username, nickname: User.Nickname)
Example 3
Source File: TapirCodecRefinedTest.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.codec.refined import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.NonEmpty import eu.timepit.refined.numeric.{Greater, GreaterEqual, Less, LessEqual} import eu.timepit.refined.string.{IPv4, MatchesRegex} import eu.timepit.refined.types.string.NonEmptyString import eu.timepit.refined.{W, refineMV, refineV} import org.scalatest.{FlatSpec, Matchers} import sttp.tapir.Codec.PlainCodec import sttp.tapir.{DecodeResult, ValidationError, Validator} class TapirCodecRefinedTest extends FlatSpec with Matchers with TapirCodecRefined { val nonEmptyStringCodec: PlainCodec[NonEmptyString] = implicitly[PlainCodec[NonEmptyString]] "Generated codec" should "return DecodResult.Invalid if subtype can't be refined with correct tapir validator if available" in { val expectedValidator: Validator[String] = Validator.minLength(1) nonEmptyStringCodec.decode("") should matchPattern { case DecodeResult.InvalidValue(List(ValidationError(validator, "", _))) if validator == expectedValidator => } } it should "correctly delegate to raw parser and refine it" in { nonEmptyStringCodec.decode("vive le fromage") shouldBe DecodeResult.Value(refineMV[NonEmpty]("vive le fromage")) } it should "return DecodResult.Invalid if subtype can't be refined with derived tapir validator if non tapir validator available" in { type IPString = String Refined IPv4 val IPStringCodec = implicitly[PlainCodec[IPString]] val expectedMsg = refineV[IPv4]("192.168.0.1000").left.get IPStringCodec.decode("192.168.0.1000") should matchPattern { case DecodeResult.InvalidValue(List(ValidationError(Validator.Custom(_, `expectedMsg`), "192.168.0.1000", _))) => } } "Generated codec for MatchesRegex" should "use tapir Validator.Pattern" in { type VariableConstraint = MatchesRegex[W.`"[a-zA-Z][-a-zA-Z0-9_]*"`.T] type VariableString = String Refined VariableConstraint val identifierCodec = implicitly[PlainCodec[VariableString]] val expectedValidator: Validator[String] = Validator.pattern("[a-zA-Z][-a-zA-Z0-9_]*") identifierCodec.decode("-bad") should matchPattern { case DecodeResult.InvalidValue(List(ValidationError(validator, "-bad", _))) if validator == expectedValidator => } } "Generated codec for Less" should "use tapir Validator.max" in { type IntConstraint = Less[W.`3`.T] type LimitedInt = Int Refined IntConstraint val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] val expectedValidator: Validator[Int] = Validator.max(3, exclusive = true) limitedIntCodec.decode("3") should matchPattern { case DecodeResult.InvalidValue(List(ValidationError(validator, 3, _))) if validator == expectedValidator => } } "Generated codec for LessEqual" should "use tapir Validator.max" in { type IntConstraint = LessEqual[W.`3`.T] type LimitedInt = Int Refined IntConstraint val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] val expectedValidator: Validator[Int] = Validator.max(3) limitedIntCodec.decode("4") should matchPattern { case DecodeResult.InvalidValue(List(ValidationError(validator, 4, _))) if validator == expectedValidator => } } "Generated codec for Greater" should "use tapir Validator.min" in { type IntConstraint = Greater[W.`3`.T] type LimitedInt = Int Refined IntConstraint val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] val expectedValidator: Validator[Int] = Validator.min(3, exclusive = true) limitedIntCodec.decode("3") should matchPattern { case DecodeResult.InvalidValue(List(ValidationError(validator, 3, _))) if validator == expectedValidator => } } "Generated codec for GreaterEqual" should "use tapir Validator.min" in { type IntConstraint = GreaterEqual[W.`3`.T] type LimitedInt = Int Refined IntConstraint val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] val expectedValidator: Validator[Int] = Validator.min(3) limitedIntCodec.decode("2") should matchPattern { case DecodeResult.InvalidValue(List(ValidationError(validator, 2, _))) if validator == expectedValidator => } } "Generated validator for Greater" should "use tapir Validator.min" in { type IntConstraint = Greater[W.`3`.T] type LimitedInt = Int Refined IntConstraint implicitly[Validator[LimitedInt]] should matchPattern { case Validator.Mapped(Validator.Min(3, true), _) => } } }
Example 4
Source File: TapirCodecRefined.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.codec.refined import sttp.tapir._ import eu.timepit.refined.api.{Refined, Validate} import eu.timepit.refined.collection.NonEmpty import eu.timepit.refined.refineV import eu.timepit.refined.string.MatchesRegex import eu.timepit.refined.numeric.{Greater, GreaterEqual, Less, LessEqual} import shapeless.Witness import scala.reflect.ClassTag trait TapirCodecRefined extends LowPriorityValidatorForPredicate { implicit def codecForRefined[R, V, P, CF <: CodecFormat](implicit tm: Codec[R, V, CF], refinedValidator: Validate[V, P], refinedValidatorTranslation: ValidatorForPredicate[V, P] ): Codec[R, V Refined P, CF] = { implicitly[Codec[R, V, CF]] .validate( refinedValidatorTranslation.validator ) // in reality if this validator has to fail, it will fail before in mapDecode while trying to construct refined type .mapDecode { v: V => refineV[P](v) match { case Right(refined) => DecodeResult.Value(refined) case Left(errorMessage) => DecodeResult.InvalidValue(refinedValidatorTranslation.validationErrors(v, errorMessage)) } }(_.value) } // implicit def validatorFromPredicate[V, P](implicit vfp: ValidatorForPredicate[V, P]): Validator[V Refined P] = vfp.validator.contramap(_.value) // implicit val validatorForNonEmptyString: ValidatorForPredicate[String, NonEmpty] = ValidatorForPredicate.fromPrimitiveValidator[String, NonEmpty](Validator.minLength(1)) implicit def validatorForMatchesRegexp[S <: String](implicit ws: Witness.Aux[S] ): ValidatorForPredicate[String, MatchesRegex[S]] = ValidatorForPredicate.fromPrimitiveValidator(Validator.pattern(ws.value)) implicit def validatorForLess[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): ValidatorForPredicate[N, Less[NM]] = ValidatorForPredicate.fromPrimitiveValidator(Validator.max(ws.value, exclusive = true)) implicit def validatorForLessEqual[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM] ): ValidatorForPredicate[N, LessEqual[NM]] = ValidatorForPredicate.fromPrimitiveValidator(Validator.max(ws.value)) implicit def validatorForGreater[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): ValidatorForPredicate[N, Greater[NM]] = ValidatorForPredicate.fromPrimitiveValidator(Validator.min(ws.value, exclusive = true)) implicit def validatorForGreaterEqual[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM] ): ValidatorForPredicate[N, GreaterEqual[NM]] = ValidatorForPredicate.fromPrimitiveValidator(Validator.min(ws.value)) } trait ValidatorForPredicate[V, P] { def validator: Validator[V] def validationErrors(value: V, refinedErrorMessage: String): List[ValidationError[_]] } object ValidatorForPredicate { def fromPrimitiveValidator[V, P](v: Validator.Primitive[V]): ValidatorForPredicate[V, P] = new ValidatorForPredicate[V, P] { override def validator: Validator[V] = v override def validationErrors(value: V, refinedErrorMessage: String): List[ValidationError[_]] = List(ValidationError[V](v, value)) } } trait LowPriorityValidatorForPredicate { implicit def genericValidatorForPredicate[V, P: ClassTag](implicit refinedValidator: Validate[V, P] ): ValidatorForPredicate[V, P] = new ValidatorForPredicate[V, P] { override val validator: Validator.Custom[V] = Validator.Custom( refinedValidator.isValid, implicitly[ClassTag[P]].runtimeClass.toString ) //for the moment there is no way to get a human description of a predicate/validator without having a concrete value to run it override def validationErrors(value: V, refinedErrorMessage: String): List[ValidationError[_]] = List(ValidationError[V](validator.copy(message = refinedErrorMessage), value)) } }
Example 5
Source File: RefinedReadConfig.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config.examples.refined import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.{ NonEmpty, Size } import eu.timepit.refined.numeric.{ Greater, GreaterEqual } import zio.config.refined._ import zio.config._, ConfigDescriptor._ import zio.config.ConfigSource object RefinedReadConfig extends App { case class RefinedProd( ldap: Refined[String, NonEmpty], port: Refined[Int, GreaterEqual[W.`1024`.T]], dburl: Option[Refined[String, NonEmpty]], longs: Refined[List[Long], Size[Greater[W.`2`.T]]] ) def prodConfig = ( nonEmpty(string("LDAP")) |@| greaterEqual[W.`1024`.T](int("PORT")) |@| nonEmpty(string("DB_URL")).optional |@| size[Greater[W.`2`.T]](list("LONGVALS")(long)) )( RefinedProd.apply, RefinedProd.unapply ) val configMultiMap = Map( "LDAP" -> ::("ldap", Nil), "PORT" -> ::("1999", Nil), "DB_URL" -> ::("ddd", Nil), "LONGVALS" -> ::("1234", List("2345", "3456")) ) read(prodConfig.from(ConfigSource.fromMultiMap(configMultiMap))) // Right(RefinedProd(ldap,1999,Some(ddd),List(1234, 2345, 3456))) }
Example 6
Source File: RefinedTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.refined import com.sksamuel.avro4s._ import eu.timepit.refined.api.Refined import eu.timepit.refined.auto._ import eu.timepit.refined.collection.NonEmpty import org.apache.avro.Schema import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec case class Foo(nonEmptyStr: String Refined NonEmpty) class RefinedTest extends AnyWordSpec with Matchers { "refinedSchemaFor" should { "use the schema for the underlying type" in { AvroSchema[Foo] shouldBe new Schema.Parser().parse( """ |{ | "type": "record", | "name": "Foo", | "namespace": "com.sksamuel.avro4s.refined", | "fields": [{ | "name": "nonEmptyStr", | "type": "string" | }] |} """.stripMargin) } } "refinedEncoder" should { "use the encoder for the underlying type" in { val expected: String Refined NonEmpty = "foo" val record = ToRecord[Foo].to(Foo(expected)) record.get("nonEmptyStr").toString shouldBe expected.value } } "refinedDecoder" should { "use the decoder for the underlying type" in { val expected: String Refined NonEmpty = "foo" val record = ImmutableRecord(AvroSchema[Foo], Vector(expected.value)) FromRecord[Foo].from(record) shouldBe Foo(expected) } "throw when the value does not conform to the refined predicate" in { val record = ImmutableRecord(AvroSchema[Foo], Vector("")) assertThrows[IllegalArgumentException](FromRecord[Foo].from(record)) } } }
Example 7
Source File: AcceptanceSpecData.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.tooling import java.lang.System.getProperty import cats.implicits._ import ch.renku.acceptancetests.model.users.UserCredentials import ch.renku.acceptancetests.pages.GitLabPages.GitLabBaseUrl import ch.renku.acceptancetests.pages.RenkuPage.RenkuBaseUrl import ch.renku.acceptancetests.workflows.LoginType import ch.renku.acceptancetests.workflows.LoginType.{LoginWithProvider, LoginWithoutProvider} import eu.timepit.refined.api.{RefType, Refined} import eu.timepit.refined.auto._ import eu.timepit.refined.collection.NonEmpty import eu.timepit.refined.string.Url trait AcceptanceSpecData { private val testsDefaults = TestsDefaults() protected implicit lazy val renkuBaseUrl: RenkuBaseUrl = { val env = Option(getProperty("env")) orElse sys.env.get("RENKU_TEST_URL") orElse testsDefaults.env toBaseUrl(env.get) getOrElse showErrorAndStop( "-Denv argument or RENKU_TEST_URL environment variable is not a valid URL" ) } private lazy val toBaseUrl: String => Either[String, RenkuBaseUrl] = (url) => { val baseUrl = if (url.endsWith("/")) url.substring(0, url.length - 1) else url; RefType .applyRef[String Refined Url](baseUrl) .map(RenkuBaseUrl.apply) } protected implicit lazy val userCredentials: UserCredentials = { for { email <- Option(getProperty("email")) orElse sys.env.get("RENKU_TEST_EMAIL") orElse testsDefaults.email flatMap toNonEmpty username <- Option(getProperty("username")) orElse sys.env.get("RENKU_TEST_USERNAME") orElse testsDefaults.username flatMap toNonEmpty password <- Option(getProperty("password")) orElse sys.env.get("RENKU_TEST_PASSWORD") orElse testsDefaults.password flatMap toNonEmpty fullName <- Option(getProperty("fullname")) orElse sys.env.get("RENKU_TEST_FULL_NAME") orElse testsDefaults.fullname flatMap toNonEmpty useProvider = Option(getProperty("provider")) orElse sys.env.get("RENKU_TEST_PROVIDER") match { case Some(s) => s.nonEmpty case None => false } register = Option(getProperty("register")) orElse sys.env.get("RENKU_TEST_REGISTER") match { case Some(s) => s.nonEmpty case None => false } } yield UserCredentials(email, username, password, fullName, useProvider, register) } getOrElse showErrorAndStop( "You must provide either the arguments -Dusername -Dfullname, -Demail or/and -Dpassword args invalid or missing" + " or set the environment variables RENKU_TEST_EMAIL RENKU_TEST_USERNAME RENKU_TEST_PASSWORD and/or RENKU_TEST_FULL_NAME" ) private lazy val toNonEmpty: String => Option[String Refined NonEmpty] = RefType .applyRef[String Refined NonEmpty](_) .toOption private def showErrorAndStop[T](message: String Refined NonEmpty): T = { Console.err.println(message) System.exit(1) throw new IllegalArgumentException(message) } protected implicit def gitLabBaseUrlFrom(implicit loginType: LoginType, renkuBaseUrl: RenkuBaseUrl): GitLabBaseUrl = loginType match { case LoginWithProvider => gitLabProviderBaseUrl(renkuBaseUrl.value) case LoginWithoutProvider => GitLabBaseUrl(renkuBaseUrl.value) } private def gitLabProviderBaseUrl(baseUrl: String): GitLabBaseUrl = if (baseUrl.endsWith("dev.renku.ch")) GitLabBaseUrl("https://dev.renku.ch") else GitLabBaseUrl("https://renkulab.io") implicit lazy val renkuCliConfig: RenkuCliConfig = RenkuCliConfig( version = Option(getProperty("renkuVersion")) .orElse(sys.env.get("RENKU_TEST_CLI_VERSION")) .orElse(testsDefaults.renkuVersion.some) .map(RenkuVersion) .getOrElse(showErrorAndStop("No renku cli version found")), installCommand = RenkuInstallCommand(testsDefaults.renkuInstallCommand) ) }
Example 8
Source File: Command.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.tooling.console import Command._ final case class Command( command: String, userInputs: List[UserInput] = Nil, maybeFileName: Option[Filename] = None ) { assert(command.trim.nonEmpty, "Console command cannot be blank") def userInput(userInput: UserInput): Command = copy(userInputs = userInputs :+ userInput) def >>(filename: Filename): Command = copy(maybeFileName = Some(filename)) override lazy val toString: String = command } object Command { import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.NonEmpty type UserInput = String Refined NonEmpty type Filename = String Refined NonEmpty }
Example 9
Source File: projects.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.model import java.net.URL import java.time.LocalDateTime import java.time.format.DateTimeFormatter import ch.renku.acceptancetests.generators.Generators.Implicits._ import ch.renku.acceptancetests.generators.Generators._ import ch.renku.acceptancetests.model.users.UserCredentials import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.NonEmpty object projects { final case class ProjectIdentifier( namespace: String Refined NonEmpty, slug: String Refined NonEmpty ) final case class ProjectDetails( title: String Refined NonEmpty, description: String Refined NonEmpty, readmeTitle: String ) final case class ProjectUrl(value: String) { override lazy val toString: String = value } object ProjectUrl { implicit class ProjectUrlOps(projectUrl: ProjectUrl)(implicit userCredentials: UserCredentials) { import ch.renku.acceptancetests.tooling.UrlEncoder.urlEncode lazy val addGitCredentials: String = { val protocol = new URL(projectUrl.value).getProtocol projectUrl.value .replace( s"$protocol://", s"$protocol://${urlEncode(userCredentials.username.value)}:${urlEncode(userCredentials.password.value)}@" ) } } } object ProjectDetails { def generate: ProjectDetails = { val now = LocalDateTime.now() val desc = prefixParagraph("An automatically generated project for testing: ").generateOne val readmeTitle = s"test${now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm_ss"))}" ProjectDetails(Refined.unsafeApply(s"test_${now.format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HHmm_ss"))}"), desc, readmeTitle) } def generateHandsOnProject(captureScreenshots: Boolean): ProjectDetails = if (captureScreenshots) { val readmeTitle = "flights tutorial" ProjectDetails(Refined.unsafeApply(readmeTitle), Refined.unsafeApply("A renku tutorial project."), readmeTitle) } else generate implicit class TitleOps(title: String Refined NonEmpty) { lazy val toPathSegment: String = title.value.replace(" ", "-") } } }
Example 10
Source File: string.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.scalacheck import eu.timepit.refined.api.{Refined, RefType} import eu.timepit.refined.collection.{NonEmpty, Size} import eu.timepit.refined.string.{EndsWith, StartsWith, Trimmed, Uuid} import eu.timepit.refined.types.string.TrimmedString import org.scalacheck.Arbitrary import shapeless.Witness object string extends StringInstances with StringInstancesBinCompat1 trait StringInstances { implicit def endsWithArbitrary[F[_, _], S <: String]( implicit rt: RefType[F], ws: Witness.Aux[S] ): Arbitrary[F[String, EndsWith[S]]] = arbitraryRefType(Arbitrary.arbString.arbitrary.map(_ + ws.value)) implicit def startsWithArbitrary[F[_, _], S <: String]( implicit rt: RefType[F], ws: Witness.Aux[S] ): Arbitrary[F[String, StartsWith[S]]] = arbitraryRefType(Arbitrary.arbString.arbitrary.map(ws.value + _)) implicit def nonEmptyStringArbitrary[F[_, _]]( implicit rt: RefType[F] ): Arbitrary[F[String, NonEmpty]] = collection.buildableNonEmptyArbitrary[F, String, Char] implicit def stringSizeArbitrary[F[_, _]: RefType, P]( implicit arbChar: Arbitrary[Char], arbSize: Arbitrary[Int Refined P] ): Arbitrary[F[String, Size[P]]] = collection.buildableSizeArbitrary[F, String, Char, P] implicit def uuidStringArbitrary[F[_, _]]( implicit rt: RefType[F] ): Arbitrary[F[String, Uuid]] = arbitraryRefType(Arbitrary.arbUuid.arbitrary.map(_.toString)) } trait StringInstancesBinCompat1 { implicit def trimmedStringArbitrary[F[_, _]]( implicit rt: RefType[F] ): Arbitrary[F[String, Trimmed]] = arbitraryRefType(Arbitrary.arbString.arbitrary.map(TrimmedString.trim(_).value)) }
Example 11
Source File: Page.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.pages import ch.renku.acceptancetests.pages.Page._ import ch.renku.acceptancetests.pages.RenkuPage.RenkuBaseUrl import ch.renku.acceptancetests.tooling._ import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.NonEmpty import eu.timepit.refined.string._ import org.openqa.selenium.{By, WebDriver, WebElement} import org.scalatest.concurrent.Eventually import org.scalatest.time.{Seconds, Span} import org.scalatest.{Matchers => ScalatestMatchers} import org.scalatestplus.selenium.WebBrowser import scala.concurrent.duration._ import scala.language.{implicitConversions, postfixOps} abstract class Page[Url <: BaseUrl] extends ScalatestMatchers with Eventually with AcceptanceSpecPatience { val path: Path val title: Title def pageReadyElement(implicit webDriver: WebDriver): Option[WebElement] def url(implicit baseUrl: Url): String = s"$baseUrl$path" protected implicit def toWebElement(element: WebBrowser.Element): WebElement = element.underlying protected implicit def toMaybeWebElement(maybeElement: Option[WebBrowser.Element]): Option[WebElement] = maybeElement.map(_.underlying) protected implicit class ElementOps(element: WebBrowser.Element) { def parent: WebElement = element.findElement(By.xpath("./..")) def enterValue(value: String): Unit = value foreach { char => element.sendKeys(char.toString) sleep (100 millis) } } protected implicit class WebElementOps(element: WebElement) { def enterValue(value: String): Unit = value foreach { char => element.sendKeys(char.toString) sleep (100 millis) } } object sleep { def apply(duration: Duration): Unit = Page.SleepThread(duration) } protected implicit class OperationOps(unit: Unit) { def sleep(duration: Duration): Unit = Page.SleepThread(duration) } protected def waitUpTo(duration: Duration): PatienceConfig = PatienceConfig( // Wait up to 2 minutes for this operation timeout = scaled(Span(AcceptanceSpecPatience.WAIT_SCALE * duration.toSeconds, Seconds)), interval = scaled(Span(2, Seconds)) ) } object Page { type Path = String Refined StartsWith[W.`"/"`.T] type Title = String Refined NonEmpty // Use a unique name to avoid problems on case-insensitive and preserving file systems object SleepThread { def apply(duration: Duration): Unit = Thread sleep duration.toMillis } } abstract class RenkuPage extends Page[RenkuBaseUrl] object RenkuPage { case class RenkuBaseUrl(value: String Refined Url) extends BaseUrl(value) }
Example 12
Source File: RefinedSpec.scala From cormorant with MIT License | 5 votes |
package io.chrisdavenport.cormorant.refined import org.specs2._ class RefinedSpec extends mutable.Specification { "refined module" should { "be able to derive a put for a class" in { import _root_.io.chrisdavenport.cormorant._ import _root_.io.chrisdavenport.cormorant.implicits._ import eu.timepit.refined._ import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.NonEmpty // import eu.timepit.refined.auto._ // import eu.timepit.refined.numeric._ // import eu.timepit.refined.boolean._ // import eu.timepit.refined.char._ // import eu.timepit.refined.collection._ // import eu.timepit.refined.generic._ // import eu.timepit.refined.string._ // import shapeless.{ ::, HNil } val refinedValue : String Refined NonEmpty = refineMV[NonEmpty]("Hello") Put[String Refined NonEmpty].put(refinedValue) must_=== CSV.Field("Hello") } "be able to derive a get for a class" in { import _root_.io.chrisdavenport.cormorant._ import _root_.io.chrisdavenport.cormorant.implicits._ import eu.timepit.refined._ import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.NonEmpty val refinedValue : String Refined NonEmpty = refineMV[NonEmpty]("Hello") val csv = CSV.Field("Hello") Get[String Refined NonEmpty].get(csv) must_=== Right(refinedValue) } } }
Example 13
Source File: RefinedSpec.scala From refined with MIT License | 5 votes |
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 14
Source File: string.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.types import eu.timepit.refined.api.{Refined, RefinedType, RefinedTypeOps} import eu.timepit.refined.collection.{MaxSize, NonEmpty, Size} import eu.timepit.refined.numeric.Interval import eu.timepit.refined.string.{HexStringSpec, Trimmed} import shapeless.Nat._1 import shapeless.Witness type HexString = String Refined HexStringSpec object HexString extends RefinedTypeOps[HexString, String] } trait StringTypes { final type FiniteString[N] = string.FiniteString[N] final val FiniteString = string.FiniteString final type NonEmptyString = string.NonEmptyString final val NonEmptyString = string.NonEmptyString final type TrimmedString = string.TrimmedString final val TrimmedString = string.TrimmedString final type HexString = string.HexString final val HexString = string.HexString } trait StringTypesBinCompat1 { final type NonEmptyFiniteString[N] = string.NonEmptyFiniteString[N] final val NonEmptyFiniteString = string.NonEmptyFiniteString }
Example 15
Source File: RefineMacro.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.macros import eu.timepit.refined.api.{RefType, Validate} import eu.timepit.refined.char.{Digit, Letter, LowerCase, UpperCase, Whitespace} import eu.timepit.refined.collection.NonEmpty import eu.timepit.refined.internal.Resources import eu.timepit.refined.numeric.{Negative, NonNegative, NonPositive, Positive} import scala.reflect.macros.blackbox class RefineMacro(val c: blackbox.Context) extends MacroUtils with LiteralMatchers { import c.universe._ def impl[F[_, _], T: c.WeakTypeTag, P: c.WeakTypeTag](t: c.Expr[T])( rt: c.Expr[RefType[F]], v: c.Expr[Validate[T, P]] ): c.Expr[F[T, P]] = { val tValue: T = t.tree match { case Literal(Constant(value)) => value.asInstanceOf[T] case BigDecimalMatcher(value) => value.asInstanceOf[T] case BigIntMatcher(value) => value.asInstanceOf[T] case _ => abort(Resources.refineNonCompileTimeConstant) } val validate = validateInstance(v) val res = validate.validate(tValue) if (res.isFailed) { abort(validate.showResult(tValue, res)) } refTypeInstance(rt).unsafeWrapM(c)(t) } def implApplyRef[FTP, F[_, _], T: c.WeakTypeTag, P: c.WeakTypeTag](t: c.Expr[T])( ev: c.Expr[F[T, P] =:= FTP], rt: c.Expr[RefType[F]], v: c.Expr[Validate[T, P]] ): c.Expr[FTP] = c.Expr[FTP](impl(t)(rt, v).tree) private def validateInstance[T, P](v: c.Expr[Validate[T, P]])( implicit T: c.WeakTypeTag[T], P: c.WeakTypeTag[P] ): Validate[T, P] = validateInstances .collectFirst { case (tpeT, instancesForT) if tpeT =:= T.tpe => instancesForT.collectFirst { case (tpeP, validate) if tpeP =:= P.tpe => validate.asInstanceOf[Validate[T, P]] } } .flatten .getOrElse(eval(v)) private val validateInstances: List[(Type, List[(Type, Any)])] = { def instance[T, P](implicit P: c.WeakTypeTag[P], v: Validate[T, P]): (Type, Validate[T, P]) = P.tpe -> v List( weakTypeOf[Int] -> List( instance[Int, Positive], instance[Int, NonPositive], instance[Int, Negative], instance[Int, NonNegative] ), weakTypeOf[Long] -> List( instance[Long, Positive], instance[Long, NonPositive], instance[Long, Negative], instance[Long, NonNegative] ), weakTypeOf[Double] -> List( instance[Double, Positive], instance[Double, NonPositive], instance[Double, Negative], instance[Double, NonNegative] ), weakTypeOf[String] -> List( instance[String, NonEmpty] ), weakTypeOf[Char] -> List( instance[Char, Digit], instance[Char, Letter], instance[Char, LowerCase], instance[Char, UpperCase], instance[Char, Whitespace] ) ) } }
Example 16
Source File: CollectionArbitrarySpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.scalacheck import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.{MaxSize, NonEmpty, Size} import eu.timepit.refined.numeric.Interval import eu.timepit.refined.scalacheck.collection._ import eu.timepit.refined.scalacheck.numeric._ import org.scalacheck.Properties import shapeless.nat._ class CollectionArbitrarySpec extends Properties("CollectionArbitrary") { property("List[String] Refined MaxSize[42]") = checkArbitraryRefinedType[List[String] Refined MaxSize[W.`42`.T]] property("List[String] Refined MaxSize[_13]") = checkArbitraryRefinedType[List[String] Refined MaxSize[_13]] property("List[Int] Refined NonEmpty") = checkArbitraryRefinedType[List[Int] Refined NonEmpty] property("Vector[Int] Refined MaxSize[23]") = checkArbitraryRefinedType[Vector[Int] Refined MaxSize[W.`23`.T]] property("Vector[Double] Refined NonEmpty") = checkArbitraryRefinedType[Vector[Double] Refined NonEmpty] property("Size[Interval.Closed[23, 42]]") = checkArbitraryRefinedType[List[Char] Refined Size[Interval.Closed[W.`23`.T, W.`42`.T]]] }
Example 17
Source File: collection.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.scalacheck import eu.timepit.refined.api.{Refined, RefType} import eu.timepit.refined.collection.{NonEmpty, Size} import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.util.Buildable object collection extends CollectionInstances with CollectionInstancesBinCompat1 trait CollectionInstances { implicit def listSizeArbitrary[F[_, _]: RefType, T: Arbitrary, P]( implicit arbSize: Arbitrary[Int Refined P] ): Arbitrary[F[List[T], Size[P]]] = buildableSizeArbitrary[F, List[T], T, P] implicit def vectorSizeArbitrary[F[_, _]: RefType, T: Arbitrary, P]( implicit arbSize: Arbitrary[Int Refined P] ): Arbitrary[F[Vector[T], Size[P]]] = buildableSizeArbitrary[F, Vector[T], T, P] // This is private and not implicit because it could produce invalid // values for some collections: // // scala> buildableSizeArbitrary[Refined, Set[Boolean], Boolean, Equal[3]].arbitrary.sample // res0: Option[Refined[Set[Boolean], Size[Equal[3]]]] = Some(Set(false, true)) private[scalacheck] def buildableSizeArbitrary[F[_, _]: RefType, C, T, P]( implicit arbT: Arbitrary[T], arbSize: Arbitrary[Int Refined P], ev1: Buildable[T, C], ev2: C => Traversable[T] ): Arbitrary[F[C, Size[P]]] = arbitraryRefType(arbSize.arbitrary.flatMap { n => Gen.buildableOfN[C, T](n.value, arbT.arbitrary) }) } trait CollectionInstancesBinCompat1 { implicit def listNonEmptyArbitrary[F[_, _]: RefType, T: Arbitrary] : Arbitrary[F[List[T], NonEmpty]] = buildableNonEmptyArbitrary[F, List[T], T] implicit def vectorNonEmptyArbitrary[F[_, _]: RefType, T: Arbitrary] : Arbitrary[F[Vector[T], NonEmpty]] = buildableNonEmptyArbitrary[F, Vector[T], T] private[scalacheck] def buildableNonEmptyArbitrary[F[_, _]: RefType, C, T]( implicit arbT: Arbitrary[T], ev1: Buildable[T, C], ev2: C => Traversable[T] ): Arbitrary[F[C, NonEmpty]] = arbitraryRefType(Gen.nonEmptyBuildableOf(arbT.arbitrary)) }