eu.timepit.refined.api.Refined Scala Examples
The following examples show how to use eu.timepit.refined.api.Refined.
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: package.scala From pfhais with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package com.wegtam.books.pfhais import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.collection._ import eu.timepit.refined.numeric._ import eu.timepit.refined.string._ package object pure { // A string containing a database login which must be non empty. type DatabaseLogin = String Refined NonEmpty // A string containing a database password which must be non empty. type DatabasePassword = String Refined NonEmpty // A string containing a database url. type DatabaseUrl = String Refined Uri // A string that must not be empty. type NonEmptyString = String Refined NonEmpty // A TCP port number which is valid in the range of 1 to 65535. type PortNumber = Int Refined Interval.Closed[W.`1`.T, W.`65535`.T] }
Example 2
Source File: JupyterLabPage.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.pages import ch.renku.acceptancetests.model.projects.{ProjectDetails, ProjectIdentifier} import ch.renku.acceptancetests.model.projects.ProjectDetails._ import ch.renku.acceptancetests.model.users.UserCredentials import ch.renku.acceptancetests.pages.Page.{Path, Title} import eu.timepit.refined.api.Refined import eu.timepit.refined.auto._ import org.openqa.selenium.Keys.RETURN import org.openqa.selenium.interactions.Actions import org.openqa.selenium.{WebDriver, WebElement} import org.scalatestplus.selenium.WebBrowser.{cssSelector, find} object JupyterLabPage { def apply()(implicit projectDetails: ProjectDetails, userCredentials: UserCredentials): JupyterLabPage = new JupyterLabPage(projectDetails.title.toPathSegment, userCredentials.userNamespace) def apply(projectId: ProjectIdentifier): JupyterLabPage = new JupyterLabPage(projectId.slug, projectId.namespace) } class JupyterLabPage(projectSlug: String, namespace: String) extends RenkuPage { override val title: Title = "JupyterLab" override val path: Path = Refined.unsafeApply( s"/jupyterhub/user/${namespace}/${projectSlug}" ) override def pageReadyElement(implicit webDriver: WebDriver): Option[WebElement] = Some(terminalIcon) def terminalIcon(implicit webDriver: WebDriver): WebElement = eventually { find(cssSelector("div.jp-LauncherCard [data-icon='ui-components:terminal']")) getOrElse fail( "Terminal icon not found" ) } object terminal { def %>(command: String)(implicit webDriver: WebDriver): Unit = eventually { val terminalElement = find(cssSelector("#jp-Terminal-0 > div > div.xterm-screen > canvas.xterm-cursor-layer")) getOrElse fail( "Terminal not found" ) new Actions(webDriver) .moveToElement(terminalElement) .click() .sendKeys(s"$command$RETURN") .build() .perform() } } }
Example 3
Source File: GitLabPages.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.pages import ch.renku.acceptancetests.model.projects.ProjectDetails import ch.renku.acceptancetests.model.projects.ProjectDetails._ import ch.renku.acceptancetests.model.users.UserCredentials import ch.renku.acceptancetests.pages.Page.{Path, Title} import ch.renku.acceptancetests.tooling.BaseUrl import eu.timepit.refined.api.Refined import eu.timepit.refined.auto._ import eu.timepit.refined.string.Url import org.openqa.selenium.{WebDriver, WebElement} import org.scalatestplus.selenium.WebBrowser.{cssSelector, find} object GitLabPages { def apply()(implicit projectDetails: ProjectDetails, userCredentials: UserCredentials): GitLabPages = new GitLabPages(projectDetails, userCredentials) case class GitLabBaseUrl(value: String Refined Url) extends BaseUrl(value) sealed abstract class GitLabPage extends Page[GitLabBaseUrl] } class GitLabPages( projectDetails: ProjectDetails, userCredentials: UserCredentials ) { import GitLabPages._ case object ProjectPage extends GitLabPage { override val path: Path = Refined.unsafeApply( s"/gitlab/${userCredentials.userNamespace}/${projectDetails.title.toPathSegment}" ) override val title: Title = Refined.unsafeApply( s"${userCredentials.fullName} / ${projectDetails.title} · GitLab" ) override def pageReadyElement(implicit webDriver: WebDriver): Option[WebElement] = Some(settingsLink) def settingsLink(implicit webDriver: WebDriver): WebElement = eventually { find(cssSelector("span.nav-item-name.qa-settings-item")) getOrElse fail("Settings link not found") } } case object GitLabProjectsPage extends GitLabPage { override val path: Path = "/gitlab/dashboard/projects" override val title: Title = "Projects · Dashboard · GitLab" override def pageReadyElement(implicit webDriver: WebDriver): Option[WebElement] = Some(newProjectButton) private def newProjectButton(implicit webDriver: WebDriver): WebElement = eventually { find(cssSelector("a[href='/gitlab/projects/new']")) getOrElse fail("New Project button not found") } } case object SettingsPage extends GitLabPage { override val path: Path = Refined.unsafeApply( s"/gitlab/${userCredentials.userNamespace}/${projectDetails.title.toPathSegment}/edit" ) override val title: Title = Refined.unsafeApply( s"General · Settings · ${userCredentials.fullName} / ${projectDetails.title} · GitLab" ) override def pageReadyElement(implicit webDriver: WebDriver): Option[WebElement] = Some(Advanced.expandButton) object Advanced { def expandButton(implicit webDriver: WebDriver): WebElement = eventually { find(cssSelector("section.advanced-settings button.js-settings-toggle")) getOrElse fail( "Advanced -> Expand button not found" ) } def removeProject(implicit webDriver: WebDriver): WebElement = eventually { find(cssSelector("form > input[value='Remove project'")) getOrElse fail( "Advanced -> Remove project button not found" ) } def confirmRemoval(project: ProjectDetails)(implicit webDriver: WebDriver): Unit = eventually { find(cssSelector("input#confirm_name_input")) .getOrElse(fail("Advanced -> Project removal name confirmation input not found")) .enterValue(project.title.toPathSegment) find(cssSelector("input[value='Confirm'")) .getOrElse(fail("Advanced -> Project removal Confirm button not found")) .click() } } } }
Example 4
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 5
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 6
Source File: AnonEnv.scala From renku with Apache License 2.0 | 5 votes |
package ch.renku.acceptancetests.tooling import java.lang.System.getProperty import ch.renku.acceptancetests.model.projects.ProjectIdentifier import eu.timepit.refined.api.Refined case class AnonEnvConfig(projectId: ProjectIdentifier, isAvailable: Boolean = false) trait AnonEnv extends AcceptanceSpecData { protected implicit lazy val anonEnvConfig: AnonEnvConfig = { AnonEnvConfig(anonProjectIdentifier, isAnonEnvAvailable) } protected lazy val anonProjectIdentifier: ProjectIdentifier = { Option(getProperty("anon")) orElse sys.env.get("RENKU_TEST_ANON_PROJECT") match { case Some(s) => { val projectId = s.split("/").map(_.trim) ProjectIdentifier(Refined.unsafeApply(projectId(0)), Refined.unsafeApply(projectId(1))) } case None => ProjectIdentifier(Refined.unsafeApply("cramakri"), Refined.unsafeApply("covid-19-dashboard")) } } protected lazy val isAnonEnvAvailable: Boolean = { val baseUrl = renkuBaseUrl Option(getProperty("anonAvail")) orElse sys.env.get("RENKU_TEST_ANON_AVAILABLE") match { case Some(s) => { s.toLowerCase == "true" } case None => baseUrl.value.value.equals("https://dev.renku.ch") } } }
Example 7
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 8
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 9
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 10
Source File: NumericCodecs.scala From skunk with MIT License | 5 votes |
// Copyright (c) 2018-2020 by Rob Norris // This software is licensed under the MIT License (MIT). // For more information see LICENSE or https://opensource.org/licenses/MIT package skunk.refined.codec import eu.timepit.refined.boolean.And import eu.timepit.refined.api.Validate import skunk.Codec import skunk.data.Type import eu.timepit.refined._ import eu.timepit.refined.api.Refined trait Scale[N] trait Precision[N] trait NumericCodecs { def validateScale[N <: Int](n: Int): Validate.Plain[BigDecimal, Scale[N]] = Validate.fromPredicate[BigDecimal, Scale[N]]( _.scale <= n, d => s"($d has scale ≤ $n)", new Scale[N] {}) def validatePrecision[N <: Int](n: Int): Validate.Plain[BigDecimal, Precision[N]] = Validate.fromPredicate[BigDecimal, Precision[N]]( _.precision <= n, d => s"($d has precision ≤ $n)", new Precision[N] {}) implicit class NumericOps(num: Codec[BigDecimal]) { def apply[S <: Int, P <: Int](precision: P, scale: S): Codec[BigDecimal Refined (Precision[P] And Scale[S])] = { implicit val __s: Validate.Plain[BigDecimal, Scale[S]] = validateScale(scale) implicit val __p: Validate.Plain[BigDecimal, Precision[P]] = validatePrecision(precision) Codec.simple( bd => bd.toString, st => refineV[Precision[P] And Scale[S]](BigDecimal(st)), Type.numeric ) } } skunk.codec.numeric.numeric(3, 4) } object numeric extends NumericCodecs
Example 11
Source File: Refined.scala From neotypes with MIT License | 5 votes |
package neotypes package refined import exceptions.{PropertyNotFoundException, IncoercibleException} import mappers.{ParameterMapper, ResultMapper, TypeHint, ValueMapper} import eu.timepit.refined.api.{Refined, RefinedType} import org.neo4j.driver.v1.Value trait RefinedMappers { implicit final def refinedValueMapper[T, P](implicit mapper: ValueMapper[T], rt: RefinedType.AuxT[Refined[T, P], T]): ValueMapper[Refined[T, P]] = new ValueMapper[Refined[T, P]] { override def to(fieldName: String, value: Option[Value]): Either[Throwable, Refined[T, P]] = value match { case None => Left(PropertyNotFoundException(s"Property $fieldName not found")) case Some(value) => mapper .to(fieldName, Some(value)) .flatMap(t => rt.refine(t).left.map(msg => IncoercibleException(msg, None.orNull))) } } implicit final def refinedResultMapper[T, P](implicit marshallable: ValueMapper[Refined[T, P]]): ResultMapper[Refined[T, P]] = new ResultMapper[Refined[T, P]] { override def to(fields: List[(String, Value)], typeHint: Option[TypeHint]): Either[Throwable, Refined[T, P]] = fields .headOption .fold(ifEmpty = marshallable.to("", None)) { case (name, value) => marshallable.to(name, Some(value)) } } implicit final def RefinedParameterMapper[T, P](implicit mapper: ParameterMapper[T]): ParameterMapper[Refined[T, P]] = mapper.contramap(refinedValue => refinedValue.value) }
Example 12
Source File: RefinedSpec.scala From neotypes with MIT License | 5 votes |
package neotypes.refined import neotypes.{CleaningIntegrationSpec, FutureTestkit} import neotypes.exceptions.IncoercibleException import neotypes.implicits.mappers.all._ import neotypes.implicits.syntax.cypher._ import neotypes.implicits.syntax.string._ import neotypes.refined.implicits._ import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.auto._ import eu.timepit.refined.numeric.Interval import scala.concurrent.Future final class RefinedSpec extends CleaningIntegrationSpec[Future](FutureTestkit) { import RefinedSpec.{Level, User} it should "insert and retrieve one refined value" in execute { s => val L1: Level = 1 for { _ <- c"CREATE (level: Level { value: ${L1} })".query[Unit].execute(s) level <- "MATCH (level: Level) RETURN level.value".query[Level].single(s) } yield assert(level == L1) } it should "insert and retrieve multiple refined values" in execute { s => val L1: Level = 1 val L2: Level = 2 for { _ <- c"CREATE (level: Level { value: ${L1} })".query[Unit].execute(s) _ <- c"CREATE (level: Level { value: ${L2} })".query[Unit].execute(s) levels <- "MATCH (level: Level) RETURN level.value ORDER BY level.value ASC".query[Level].list(s) } yield assert(levels == List(L1, L2)) } it should "insert and retrieve wrapped refined values" in execute { s => val L1: Level = 1 val L2: Level = 2 val levels = List(Option(L1), Option(L2)) for { _ <- c"CREATE (levels: Levels { values: ${levels} })".query[Unit].execute(s) levels <- "MATCH (levels: Levels) UNWIND levels.values AS level RETURN level".query[Option[Level]].list(s) } yield assert(levels == levels) } it should "retrieve refined values inside a case class" in execute { s => for { _ <- "CREATE (user: User { name: \"Balmung\", level: 99 })".query[Unit].execute(s) user <- "MATCH (user: User { name: \"Balmung\" }) RETURN user".query[User].single(s) } yield assert(user == User(name = "Balmung", level = 99)) } it should "fail if a single value does not satisfy the refinement condition" in execute { s => recoverToSucceededIf[IncoercibleException] { for { _ <- "CREATE (level: Level { value: -1 })".query[Unit].execute(s) level <- "MATCH (level: Level) RETURN level".query[Level].single(s) } yield level } } it should "fail if at least one of multiple values does not satisfy the refinement condition" in execute { s => recoverToSucceededIf[IncoercibleException] { for { _ <- "CREATE (level: Level { value: 3 })".query[Unit].execute(s) _ <- "CREATE (level: Level { value: -1 })".query[Unit].execute(s) _ <- "CREATE (level: Level { value: 5 })".query[Unit].execute(s) levels <- "MATCH (level: Level) RETURN level".query[Level].list(s) } yield levels } } it should "fail if at least one wrapped value does not satisfy the refinement condition" in execute { s => recoverToSucceededIf[IncoercibleException] { for { _ <- "CREATE (levels: Levels { values: [3, -1, 5] })".query[Unit].execute(s) levels <- "MATCH (levels: Levels) UNWIND levels.values AS level RETURN level".query[Option[Level]].list(s) } yield levels } } it should "fail if at least one value inside a case class does not satisfy the refinement condition" in execute { s => recoverToSucceededIf[IncoercibleException] { for { _ <- "CREATE (user: User { name: \"???\", level: -1 })".query[Unit].execute(s) user <- "MATCH (user: User { name: \"???\" }) RETURN user".query[User].single(s) } yield user } } } object RefinedSpec { type Level = Int Refined Interval.Closed[W.`1`.T, W.`99`.T] final case class User(name: String, level: Level) }
Example 13
Source File: XStrEncoder.scala From scalaz-deriving with GNU Lesser General Public License v3.0 | 5 votes |
// Copyright: 2017 - 2020 Sam Halliday // License: http://www.gnu.org/licenses/lgpl-3.0.en.html package xmlformat import scalaz._, Scalaz._ import simulacrum._ @typeclass trait XStrEncoder[A] { self => def toXml(a: A): XString // for performance final def xmap[B](@unused f: A => B, g: B => A): XStrEncoder[B] = contramap(g) final def contramap[B](g: B => A): XStrEncoder[B] = b => toXml(g(b)) } object XStrEncoder extends XStrEncoderScalaz with XStrEncoderRefined with XStrEncoderStdlib { implicit val contravariant: Contravariant[XStrEncoder] = new Contravariant[XStrEncoder] { def contramap[A, B](fa: XStrEncoder[A])(f: B => A): XStrEncoder[B] = b => fa.toXml(f(b)) } // JVM data types implicit val string: XStrEncoder[String] = s => XString(s) implicit val boolean: XStrEncoder[Boolean] = string.contramap(_.toString) implicit val short: XStrEncoder[Short] = string.contramap(_.toString) implicit val int: XStrEncoder[Int] = string.contramap(_.toString) implicit val long: XStrEncoder[Long] = string.contramap(_.toString) implicit val float: XStrEncoder[Float] = string.contramap(_.toString) implicit val double: XStrEncoder[Double] = string.contramap(_.toString) implicit val uuid: XStrEncoder[java.util.UUID] = string.contramap(_.toString) implicit val instant: XStrEncoder[java.time.Instant] = string.contramap(_.toString) implicit val char: XStrEncoder[Char] = string.contramap(_.toString) implicit val symbol: XStrEncoder[Symbol] = string.contramap(_.name) implicit val xstring: XStrEncoder[XString] = identity } private[xmlformat] trait XStrEncoderScalaz { this: XStrEncoder.type => implicit def disjunction[ A: XStrEncoder, B: XStrEncoder ]: XStrEncoder[A \/ B] = { case -\/(a) => XStrEncoder[A].toXml(a) case \/-(b) => XStrEncoder[B].toXml(b) } } // WORKAROUND https://github.com/scala/bug/issues/10753 private[xmlformat] trait XStrEncoderRefined { this: XStrEncoder.type => import eu.timepit.refined.api.Refined implicit def refined[A: XStrEncoder, B]: XStrEncoder[A Refined B] = XStrEncoder[A].contramap(_.value) } private[xmlformat] trait XStrEncoderStdlib { this: XStrEncoder.type => implicit def either[ A: XStrEncoder, B: XStrEncoder ]: XStrEncoder[Either[A, B]] = disjunction[A, B].contramap(_.disjunction) import scala.concurrent.duration.FiniteDuration implicit def finite: XStrEncoder[FiniteDuration] = long.contramap(_.toMillis) }
Example 14
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 15
Source File: package.scala From pfhais with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package com.wegtam.books.pfhais import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.collection._ import eu.timepit.refined.numeric._ import eu.timepit.refined.string._ package object tapir { // A string containing a database login which must be non empty. type DatabaseLogin = String Refined NonEmpty // A string containing a database password which must be non empty. type DatabasePassword = String Refined NonEmpty // A string containing a database url. type DatabaseUrl = String Refined Uri // A string that must not be empty. type NonEmptyString = String Refined NonEmpty // A TCP port number which is valid in the range of 1 to 65535. type PortNumber = Int Refined Interval.Closed[W.`1`.T, W.`65535`.T] }
Example 16
Source File: Show.scala From laserdisc with MIT License | 5 votes |
package laserdisc package protocol import eu.timepit.refined.api.Refined import scala.annotation.implicitNotFound @implicitNotFound( """Implicit not found Show[${A}]. Try writing your own, for example: implicit final val myShow: Show[${A}] = new Show[${A}] { override final def show(a: ${A}): String = ??? } """ ) trait Show[A] { def show(a: A): String final def contramap[B](f: B => A): Show[B] = Show.instance(show _ compose f) } object Show extends ShowInstances { @inline final def apply[A](implicit instance: Show[A]): Show[A] = instance final def const[A](s: =>String): Show[A] = new Show[A] { override def show(a: A): String = s } final def unsafeFromToString[A]: Show[A] = new Show[A] { override def show(a: A): String = a.toString } final def instance[A](f: A => String): Show[A] = new Show[A] { override def show(a: A): String = f(a) } } private[protocol] sealed trait ShowInstances { private[this] final val refinedDoubleCases: PartialFunction[Refined[Double, _], String] = { case d if d.value == Double.NegativeInfinity => "-inf" case d if d.value == Double.PositiveInfinity => "+inf" case d => d.value.toString } implicit final val doubleShow: Show[Double] = Show.unsafeFromToString implicit final val intShow: Show[Int] = Show.unsafeFromToString implicit final val longShow: Show[Long] = Show.unsafeFromToString implicit final val stringShow: Show[String] = Show.instance(identity) implicit final val symbolShow: Show[Symbol] = Show.instance(_.name) implicit final val connectionNameShow: Show[ConnectionName] = Show.unsafeFromToString implicit final val dbIndexShow: Show[DbIndex] = Show.unsafeFromToString implicit final val globPatternShow: Show[GlobPattern] = Show.unsafeFromToString implicit final val hostShow: Show[Host] = Show.unsafeFromToString implicit final val indexShow: Show[Index] = Show.unsafeFromToString implicit final val keyShow: Show[Key] = Show.unsafeFromToString implicit final val latitudeShow: Show[Latitude] = Show.unsafeFromToString implicit final val longitudeShow: Show[Longitude] = Show.unsafeFromToString implicit final val nodeIdShow: Show[NodeId] = Show.unsafeFromToString implicit final val nonNegDoubleShow: Show[NonNegDouble] = Show.instance(refinedDoubleCases) implicit final val nonNegIntShow: Show[NonNegInt] = Show.unsafeFromToString implicit final val nonNegLongShow: Show[NonNegLong] = Show.unsafeFromToString implicit final val nonZeroDoubleShow: Show[NonZeroDouble] = Show.instance(refinedDoubleCases) implicit final val nonZeroIntShow: Show[NonZeroInt] = Show.unsafeFromToString implicit final val nonZeroLongShow: Show[NonZeroLong] = Show.unsafeFromToString implicit final val portShow: Show[Port] = Show.unsafeFromToString implicit final val posIntShow: Show[PosInt] = Show.unsafeFromToString implicit final val posLongShow: Show[PosLong] = Show.unsafeFromToString implicit final val rangeOffsetShow: Show[RangeOffset] = Show.unsafeFromToString implicit final val slotShow: Show[Slot] = Show.unsafeFromToString implicit final val stringLengthShow: Show[StringLength] = Show.unsafeFromToString implicit final val validDoubleShow: Show[ValidDouble] = Show.instance(refinedDoubleCases) }
Example 17
Source File: package.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config import eu.timepit.refined.api.{ RefType, Refined, Validate } package object refined extends NumericSupport with StringSupport with CharSupport with BooleanSupport with CollectionSupport { def asRefined[A, P]( desc: ConfigDescriptor[A] )( implicit ev: Validate[A, P] ): ConfigDescriptor[Refined[A, P]] = desc .xmapEither[Refined[A, P]]( RefType.applyRef[Refined[A, P]](_), rf => Right(rf.value) ) }
Example 18
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 19
Source File: generators.scala From pfps-shopping-cart with Apache License 2.0 | 5 votes |
package shop import eu.timepit.refined.api.Refined import io.estatico.newtype.ops._ import io.estatico.newtype.Coercible import java.util.UUID import org.scalacheck.Gen import shop.domain.brand._ import shop.domain.cart._ import shop.domain.category._ import shop.domain.checkout._ import shop.domain.item._ import squants.market._ object generators { def cbUuid[A: Coercible[UUID, *]]: Gen[A] = Gen.uuid.map(_.coerce[A]) def cbStr[A: Coercible[String, *]]: Gen[A] = genNonEmptyString.map(_.coerce[A]) def cbInt[A: Coercible[Int, *]]: Gen[A] = Gen.posNum[Int].map(_.coerce[A]) val genMoney: Gen[Money] = Gen.posNum[Long].map(n => USD(BigDecimal(n))) val genNonEmptyString: Gen[String] = Gen .chooseNum(21, 40) .flatMap { n => Gen.buildableOfN[String, Char](n, Gen.alphaChar) } val brandGen: Gen[Brand] = for { i <- cbUuid[BrandId] n <- cbStr[BrandName] } yield Brand(i, n) val categoryGen: Gen[Category] = for { i <- cbUuid[CategoryId] n <- cbStr[CategoryName] } yield Category(i, n) val itemGen: Gen[Item] = for { i <- cbUuid[ItemId] n <- cbStr[ItemName] d <- cbStr[ItemDescription] p <- genMoney b <- brandGen c <- categoryGen } yield Item(i, n, d, p, b, c) val cartItemGen: Gen[CartItem] = for { i <- itemGen q <- cbInt[Quantity] } yield CartItem(i, q) val cartTotalGen: Gen[CartTotal] = for { i <- Gen.nonEmptyListOf(cartItemGen) t <- genMoney } yield CartTotal(i, t) val itemMapGen: Gen[(ItemId, Quantity)] = for { i <- cbUuid[ItemId] q <- cbInt[Quantity] } yield i -> q val cartGen: Gen[Cart] = Gen.nonEmptyMap(itemMapGen).map(Cart.apply) val cardGen: Gen[Card] = for { n <- genNonEmptyString.map[CardNamePred](Refined.unsafeApply) u <- Gen.posNum[Long].map[CardNumberPred](Refined.unsafeApply) x <- Gen.posNum[Int].map[CardExpirationPred](x => Refined.unsafeApply(x.toString)) c <- Gen.posNum[Int].map[CardCVVPred](Refined.unsafeApply) } yield Card(CardName(n), CardNumber(u), CardExpiration(x), CardCVV(c)) }
Example 20
Source File: item.scala From pfps-shopping-cart with Apache License 2.0 | 5 votes |
package shop.domain import eu.timepit.refined.api.Refined import eu.timepit.refined.string.{ Uuid, ValidBigDecimal } import eu.timepit.refined.types.string.NonEmptyString import io.estatico.newtype.macros.newtype import java.util.UUID import shop.domain.brand._ import shop.domain.category._ import squants.market._ object item { @newtype case class ItemId(value: UUID) @newtype case class ItemName(value: String) @newtype case class ItemDescription(value: String) case class Item( uuid: ItemId, name: ItemName, description: ItemDescription, price: Money, brand: Brand, category: Category ) // ----- Create item ------ @newtype case class ItemNameParam(value: NonEmptyString) @newtype case class ItemDescriptionParam(value: NonEmptyString) @newtype case class PriceParam(value: String Refined ValidBigDecimal) case class CreateItemParam( name: ItemNameParam, description: ItemDescriptionParam, price: PriceParam, brandId: BrandId, categoryId: CategoryId ) { def toDomain: CreateItem = CreateItem( ItemName(name.value.value), ItemDescription(description.value.value), USD(BigDecimal(price.value.value)), brandId, categoryId ) } case class CreateItem( name: ItemName, description: ItemDescription, price: Money, brandId: BrandId, categoryId: CategoryId ) // ----- Update item ------ @newtype case class ItemIdParam(value: String Refined Uuid) case class UpdateItemParam( id: ItemIdParam, price: PriceParam ) { def toDomain: UpdateItem = UpdateItem( ItemId(UUID.fromString(id.value.value)), USD(BigDecimal(price.value.value)) ) } case class UpdateItem( id: ItemId, price: Money ) }
Example 21
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 22
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 23
Source File: RefinedDecodersSpec.scala From phobos with Apache License 2.0 | 5 votes |
package ru.tinkoff.phobos.refined import eu.timepit.refined.api.Refined import eu.timepit.refined.refineMV import eu.timepit.refined.string.MatchesRegex import eu.timepit.refined.types.numeric.NonNegLong import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import ru.tinkoff.phobos.annotations.{ElementCodec, XmlCodec} import ru.tinkoff.phobos.decoding.XmlDecoder import ru.tinkoff.phobos.syntax.{attr, text} import ru.tinkoff.phobos.testString._ import shapeless.{Witness => W} class RefinedDecodersSpec extends AnyWordSpec with Matchers { type NumericAtLeastTo = MatchesRegex[W.`"[0-9]{2,}"`.T] @XmlCodec("test") case class Test(x: Int, y: Refined[String, NumericAtLeastTo]) @ElementCodec case class Foo(@attr bar: Int, @text baz: NonNegLong) @XmlCodec("qux") case class Qux(str: String, foo: Foo) "refined decoder" should { "decode element correctly" in { val sampleXml = """ | <?xml version='1.0' encoding='UTF-8'?> | <test> | <x>2</x> | <y>123</y> | </test> """.stripMargin.minimized val expectedResult = Test(2, refineMV[NumericAtLeastTo]("123")) XmlDecoder[Test].decode(sampleXml) shouldEqual (Right(expectedResult)) } "decode text correctly" in { val sampleXml = """ | <?xml version='1.0' encoding='UTF-8'?> | <qux> | <str>42</str> | <foo bar="42">1000</foo> | </qux> """.stripMargin.minimized val expectedResult = Qux("42", Foo(42, NonNegLong(1000L))) XmlDecoder[Qux].decode(sampleXml) shouldEqual Right(expectedResult) } "provide verbose errorst" in { @XmlCodec("test") case class Test2(x: Int, y: Refined[String, NumericAtLeastTo]) @ElementCodec case class Foo2(@attr bar: Int, @text baz: NonNegLong) @XmlCodec("qux") case class Qux2(str: String, foo: Foo2) val sampleXml0 = """ | <?xml version='1.0' encoding='UTF-8'?> | <test> | <x>2</x> | <y>1</y> | </test> """.stripMargin.minimized XmlDecoder[Test2] .decode(sampleXml0) .left .map(_.text) shouldEqual Left( """Failed to verify RefinedDecodersSpec.this.NumericAtLeastTo refinement for value=1 of raw type String: Predicate failed: "1".matches("[0-9]{2,}").""" ) val sampleXml1 = """ | <?xml version='1.0' encoding='UTF-8'?> | <qux> | <str>42</str> | <foo bar="42">-1000</foo> | </qux> """.stripMargin.minimized XmlDecoder[Qux2] .decode(sampleXml1) .left .map(_.text) shouldEqual Left( """Failed to verify eu.timepit.refined.numeric.NonNegative refinement for value=-1000 of raw type Long: Predicate (-1000 < 0) did not fail.""" ) } } }
Example 24
Source File: RefinedEncodersSpec.scala From phobos with Apache License 2.0 | 5 votes |
package ru.tinkoff.phobos.refined import eu.timepit.refined.api.Refined import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import ru.tinkoff.phobos.annotations.{ElementCodec, XmlCodec} import eu.timepit.refined.refineMV import eu.timepit.refined.string.MatchesRegex import eu.timepit.refined.types.numeric.NonNegLong import ru.tinkoff.phobos.encoding.XmlEncoder import ru.tinkoff.phobos.syntax.{attr, text} import shapeless.{Witness => W} import ru.tinkoff.phobos.testString._ class RefinedEncodersSpec extends AnyWordSpec with Matchers { type NumericAtLeastTo = MatchesRegex[W.`"[0-9]{2,}"`.T] @XmlCodec("test") case class Test(x: Int, y: Refined[String, NumericAtLeastTo]) @ElementCodec case class Foo(@attr bar: Int, @text baz: NonNegLong) @XmlCodec("qux") case class Qux(str: String, foo: Foo) "refined encoder" should { "encode element correctly" in { val value = Test(2, refineMV[NumericAtLeastTo]("123")) val expectedResult = """ | <?xml version='1.0' encoding='UTF-8'?> | <test> | <x>2</x> | <y>123</y> | </test> """.stripMargin.minimized XmlEncoder[Test].encode(value) shouldEqual expectedResult } "encode text correctly" in { val qux = Qux("42", Foo(42, NonNegLong(1000L))) val xml = XmlEncoder[Qux].encode(qux) assert( xml == """ | <?xml version='1.0' encoding='UTF-8'?> | <qux> | <str>42</str> | <foo bar="42">1000</foo> | </qux> """.stripMargin.minimized) } } }
Example 25
Source File: UserRepository.scala From whirlwind-tour-akka-typed with Apache License 2.0 | 5 votes |
package de.heikoseeberger.wtat import akka.actor.typed.{ ActorRef, Behavior } import akka.persistence.typed.scaladsl.PersistentActor import akka.persistence.typed.scaladsl.PersistentActor.{ CommandHandler, Effect } import eu.timepit.refined.api.Refined import java.io.{ Serializable => JavaSerializable } import org.apache.logging.log4j.scala.Logging object UserRepository extends Logging { sealed trait Serializable extends JavaSerializable sealed trait Command sealed trait Event final case class AddUser(user: User, replyTo: ActorRef[AddUserReply]) extends Command with Serializable sealed trait AddUserReply final case class UsernameTaken(username: String) extends AddUserReply with Serializable final case class UserAdded(user: User) extends AddUserReply with Event with Serializable final case class RemoveUser(username: String, replyTo: ActorRef[RemoveUserReply]) extends Command with Serializable sealed trait RemoveUserReply final case class UsernameUnknown(username: String) extends RemoveUserReply with Serializable final case class UserRemoved(username: String) extends RemoveUserReply with Event with Serializable final case object Stop extends Command final case class State(usernames: Set[String] = Set.empty) final val Name = "user-repository" def apply(): Behavior[Command] = PersistentActor.immutable(Name, State(), commandHandler, eventHandler) def addUser(user: User)(replyTo: ActorRef[AddUserReply]): AddUser = AddUser(user, replyTo) def removeUser(username: String)(replyTo: ActorRef[RemoveUserReply]): RemoveUser = RemoveUser(username, replyTo) private def commandHandler = CommandHandler[Command, Event, State] { case (_, State(usernames), AddUser(user @ User(Refined(username), _), replyTo)) => if (usernames.contains(username)) { logger.info(s"Username $username taken") replyTo ! UsernameTaken(username) Effect.none } else { val userAdded = UserAdded(user) Effect .persist(userAdded) .andThen { _ => logger.info(s"User with username $username added") replyTo ! userAdded } } case (_, State(usernames), RemoveUser(username, replyTo)) => if (!usernames.contains(username)) { logger.info(s"Username $username unknown") replyTo ! UsernameUnknown(username) Effect.none } else { val userRemoved = UserRemoved(username) Effect .persist(userRemoved) .andThen { _ => logger.info(s"User with username $username removed") replyTo ! userRemoved } } case (_, _, Stop) => Effect.stop } private def eventHandler(state: State, event: Event) = event match { case UserAdded(user) => state.copy(state.usernames + user.username.value) case UserRemoved(username) => state.copy(state.usernames - username) } }
Example 26
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 27
Source File: MacroUtils.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.macros import eu.timepit.refined.api.{Refined, RefType} import scala.reflect.macros.blackbox import scala.util.{Success, Try} import shapeless.tag.@@ trait MacroUtils { val c: blackbox.Context import c.universe.weakTypeOf def abort(msg: String): Nothing = c.abort(c.enclosingPosition, msg) def eval[T](t: c.Expr[T]): T = { // Duplicate and untypecheck before calling `eval`, see: // http://www.scala-lang.org/api/2.12.0/scala-reflect/scala/reflect/macros/Evals.html#eval[T]%28expr:Evals.this.Expr[T]%29:T val expr = c.Expr[T](c.untypecheck(t.tree.duplicate)) // Try evaluating expr twice before failing, see // https://github.com/fthomas/refined/issues/3 tryN(2, c.eval(expr)) } def tryN[T](n: Int, t: => T): T = Stream.fill(n)(Try(t)).collectFirst { case Success(r) => r }.getOrElse(t) protected def refTypeInstance[F[_, _]](rt: c.Expr[RefType[F]]): RefType[F] = if (rt.tree.tpe =:= weakTypeOf[RefType[Refined]]) RefType.refinedRefType.asInstanceOf[RefType[F]] else if (rt.tree.tpe =:= weakTypeOf[RefType[@@]]) RefType.tagRefType.asInstanceOf[RefType[F]] else eval(rt) }
Example 28
Source File: ScalazSpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.scalaz import eu.timepit.refined.W import eu.timepit.refined.api.{Refined, RefinedTypeOps} import eu.timepit.refined.numeric.Interval import eu.timepit.refined.types.numeric.PosInt import org.scalacheck.Prop._ import org.scalacheck.Properties import scalaz.Validation class ScalazSpec extends Properties("scalaz") { property("Validate when Valid") = secure { import syntax._ PosInt.validate(5) ?= Validation.success(PosInt.unsafeFrom(5)) } property("Validate when Invalid") = secure { import syntax._ PosInt.validate(0) ?= Validation.failureNel("Predicate failed: (0 > 0).") } property("validate without import") = secure { type OneToTen = Int Refined Interval.Closed[W.`1`.T, W.`10`.T] object OneToTen extends RefinedTypeOps[OneToTen, Int] with ScalazRefinedTypeOpsSyntax OneToTen.validate(5) ?= Validation.success(OneToTen.unsafeFrom(5)) } }
Example 29
Source File: RefineVBenchmark.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.benchmark import eu.timepit.refined.api.Refined import eu.timepit.refined.numeric.Positive import eu.timepit.refined.refineV import eu.timepit.refined.string.Regex import java.util.concurrent.TimeUnit import org.openjdk.jmh.annotations.{Benchmark, BenchmarkMode, Mode, OutputTimeUnit} @BenchmarkMode(Array(Mode.AverageTime)) class RefineVBenchmark { @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) def refineV_Positive: Either[String, Int Refined Positive] = refineV[Positive](1) @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) def refineV_Regex: Either[String, String Refined Regex] = refineV[Regex](".*") }
Example 30
Source File: InferMacroBenchmark.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.benchmark import org.openjdk.jmh.annotations._ import scala.reflect.runtime.currentMirror import scala.tools.reflect.ToolBox @BenchmarkMode(Array(Mode.AverageTime)) @State(Scope.Thread) class InferMacroBenchmark { private val toolBox = currentMirror.mkToolBox() private val autoInfer_Greater_tree = toolBox.parse(""" import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.auto.autoInfer import eu.timepit.refined.numeric.Greater val a: Int Refined Greater[W.`5`.T] = Refined.unsafeApply(10) val b: Int Refined Greater[W.`0`.T] = a """) @Benchmark def autoInfer_Greater: Any = toolBox.eval(autoInfer_Greater_tree) }
Example 31
Source File: RefTypeConfigConvertSpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.pureconfig import com.typesafe.config.ConfigValueType 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 pureconfig._ import pureconfig.error.{CannotConvert, ConfigReaderFailures, ConvertFailure, WrongType} import pureconfig.generic.auto._ class RefTypeConfigConvertSpec extends Properties("RefTypeConfigConvert") { type PosInt = Int Refined Positive case class Config(value: PosInt) property("load success") = secure { loadConfigWithValue("1") ?= Right(Config(1)) } property("load failure (predicate)") = secure { val expected1 = Left( ConfigReaderFailures( ConvertFailure( reason = CannotConvert( value = "0", toType = "eu.timepit.refined.api.Refined[Int,eu.timepit.refined.numeric.Greater[shapeless.nat._0]]", because = "Predicate failed: (0 > 0)." ), location = None, path = "value" ) ) ) // Allow "scala.Int" instead of just "Int" in the toType parameter. // For some reason Scala 2.12 with sbt 1.1.2 uses the former. val expected2 = Left( ConfigReaderFailures( ConvertFailure( reason = CannotConvert( value = "0", toType = "eu.timepit.refined.api.Refined[scala.Int,eu.timepit.refined.numeric.Greater[shapeless.nat._0]]", because = "Predicate failed: (0 > 0)." ), location = None, path = "value" ) ) ) val actual = loadConfigWithValue("0") (actual ?= expected1) || (actual ?= expected2) } property("load failure (wrong type)") = secure { loadConfigWithValue("abc") =? Left( ConfigReaderFailures( ConvertFailure( reason = WrongType( foundType = ConfigValueType.STRING, expectedTypes = Set(ConfigValueType.NUMBER) ), location = None, path = "value" ) ) ) } property("roundtrip success") = secure { val config = Config(1) val configValue = ConfigConvert[Config].to(config) ConfigConvert[Config].from(configValue) ?= Right(config) } def loadConfigWithValue(value: String): Either[ConfigReaderFailures, Config] = ConfigSource.string(s"value = $value").load[Config] }
Example 32
Source File: RefTypeRedSpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.scopt 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 scopt._ class RefTypeReadSpec extends Properties("RefTypeRead") { type PosInt = Int Refined Positive case class Config(foo: PosInt) val parser = new OptionParser[Config]("tests") { opt[PosInt]('f', "foo") .action((x, c) => c.copy(foo = x)) .text("foo is a positive integer property") } property("load success") = secure { loadConfigWithValue("10") =? Some(Config(10)) } property("load failure (predicate)") = secure { loadConfigWithValue("0") =? None } property("load failure (wrong type)") = secure { loadConfigWithValue("abc") =? None } def loadConfigWithValue(value: String): Option[Config] = parser.parse(Array("-f", value), Config(1)) }
Example 33
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 34
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)) }
Example 35
Source File: PackageSpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.scalacheck import eu.timepit.refined.api.Refined import eu.timepit.refined.numeric.Positive import eu.timepit.refined.types.all._ import org.scalacheck.{Cogen, Prop, Properties} class PackageSpec extends Properties("Package") { // this is just copied from core since core’s test configuration is built for scalacheck 1.14 only def wellTyped[A](body: => A): Prop = Prop.secure { body true } property("Cogen[Short Refined Positive]") = wellTyped(Cogen[Short Refined Positive]) property("Cogen[LowerCaseChar]") = wellTyped(Cogen[LowerCaseChar]) property("Cogen[NonEmptyString]") = wellTyped(Cogen[NonEmptyString]) property("Cogen[PosInt]") = wellTyped(Cogen[PosInt]) }
Example 36
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 37
Source File: StringArbitrarySpec.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, Size} import eu.timepit.refined.generic.Equal import eu.timepit.refined.scalacheck.generic._ import eu.timepit.refined.scalacheck.numeric._ import eu.timepit.refined.scalacheck.string._ import eu.timepit.refined.string._ import eu.timepit.refined.types.string.{ FiniteString, NonEmptyFiniteString, NonEmptyString, TrimmedString } import org.scalacheck.Properties class StringArbitrarySpec extends Properties("StringArbitrary") { property("EndsWith[S]") = checkArbitraryRefinedType[String Refined EndsWith[W.`"abc"`.T]] property("StartsWith[S]") = checkArbitraryRefinedType[String Refined StartsWith[W.`"abc"`.T]] property("NonEmptyString") = checkArbitraryRefinedType[NonEmptyString] property("TrimmedString") = checkArbitraryRefinedType[TrimmedString] property("MaxSize[16]") = checkArbitraryRefinedType[String Refined MaxSize[W.`16`.T]] property("FiniteString[10]") = checkArbitraryRefinedType[FiniteString[W.`10`.T]] property("Size[Equal[8]]") = checkArbitraryRefinedType[String Refined Size[Equal[W.`8`.T]]] property("NonEmptyFiniteString[10]") = checkArbitraryRefinedType[NonEmptyFiniteString[W.`10`.T]] property("Uuid") = checkArbitraryRefinedType[String Refined Uuid] }
Example 38
Source File: CharArbitrarySpec.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.boolean.Or import eu.timepit.refined.char._ import eu.timepit.refined.numeric.Interval import eu.timepit.refined.scalacheck.boolean._ import eu.timepit.refined.scalacheck.char._ import eu.timepit.refined.scalacheck.numeric._ import eu.timepit.refined.types.char.{LowerCaseChar, UpperCaseChar} import org.scalacheck.Properties class CharArbitrarySpec extends Properties("CharArbitrary") { property("Digit") = checkArbitraryRefinedType[Char Refined Digit] property("Letter") = checkArbitraryRefinedType[Char Refined Letter] property("LowerCaseChar") = checkArbitraryRefinedType[LowerCaseChar] property("UpperCaseChar") = checkArbitraryRefinedType[UpperCaseChar] property("Whitespace") = checkArbitraryRefinedType[Char Refined Whitespace] property("LetterOrDigit") = checkArbitraryRefinedType[Char Refined LetterOrDigit] property("HexDigit") = { type HexDigit = Digit Or Interval.Closed[W.`'a'`.T, W.`'f'`.T] checkArbitraryRefinedType[Char Refined HexDigit] } }
Example 39
Source File: RefTypeCodecSpec.scala From refined with MIT License | 5 votes |
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 40
Source File: TypeableSpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.shapeless.typeable import eu.timepit.refined.W import eu.timepit.refined.api.{Refined, RefinedTypeOps} import eu.timepit.refined.string.MatchesRegex import eu.timepit.refined.types.numeric.PosInt import org.scalacheck.Prop._ import org.scalacheck.Properties import shapeless.Typeable class TypeableSpec extends Properties("shapeless") { property("Typeable cast success") = secure { val value: PosInt = PosInt.unsafeFrom(5) typeableCast[PosInt](5) ?= Some(value) } property("Typeable cast fail") = secure { typeableCast[PosInt](0) ?= None } property("Typeable describe") = secure { typeableDescribe[PosInt] ?= "Refined[Int, Greater[_0]]" } property("Typeable cast success string regex") = secure { type Word = String Refined MatchesRegex[W.`"[a-zA-Z]*"`.T] object Word extends RefinedTypeOps[Word, String] val value: Word = Word.unsafeFrom("AlloweD") typeableCast[Word]("AlloweD") ?= Some(value) } property("Typeable cast fail string regex") = secure { type Word = String Refined MatchesRegex[W.`"[a-zA-Z]*"`.T] typeableCast[Word]("Not Allowed") ?= None } property("Typeable string regex describe") = secure { type Word = String Refined MatchesRegex[W.`"[a-zA-Z]*"`.T] typeableDescribe[Word] ?= """Refined[String, MatchesRegex[String([a-zA-Z]*)]]""" } private def typeableDescribe[T](implicit T: Typeable[T]): String = T.describe private def typeableCast[T](value: Any)(implicit T: Typeable[T]): Option[T] = T.cast(value) }
Example 41
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 42
Source File: digests.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.types import eu.timepit.refined.W import eu.timepit.refined.api.{Refined, RefinedTypeOps} import eu.timepit.refined.boolean.And import eu.timepit.refined.collection.Size import eu.timepit.refined.generic.Equal import eu.timepit.refined.string.HexStringSpec object digests { type MD5 = String Refined (HexStringSpec And Size[Equal[W.`32`.T]]) object MD5 extends RefinedTypeOps[MD5, String] type SHA1 = String Refined (HexStringSpec And Size[Equal[W.`40`.T]]) object SHA1 extends RefinedTypeOps[SHA1, String] type SHA224 = String Refined (HexStringSpec And Size[Equal[W.`56`.T]]) object SHA224 extends RefinedTypeOps[SHA224, String] type SHA256 = String Refined (HexStringSpec And Size[Equal[W.`64`.T]]) object SHA256 extends RefinedTypeOps[SHA256, String] type SHA384 = String Refined (HexStringSpec And Size[Equal[W.`96`.T]]) object SHA384 extends RefinedTypeOps[SHA384, String] type SHA512 = String Refined (HexStringSpec And Size[Equal[W.`128`.T]]) object SHA512 extends RefinedTypeOps[SHA512, String] } trait DigestTypes { final type MD5 = digests.MD5 final val MD5 = digests.MD5 final type SHA1 = digests.SHA1 final val SHA1 = digests.SHA1 final type SHA224 = digests.SHA224 final val SHA224 = digests.SHA224 final type SHA256 = digests.SHA256 final val SHA256 = digests.SHA256 final type SHA384 = digests.SHA384 final val SHA384 = digests.SHA384 final type SHA512 = digests.SHA512 final val SHA512 = digests.SHA512 }
Example 43
Source File: AutoSpec.scala From refined with MIT License | 5 votes |
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 44
Source File: RefineMSpec.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.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 45
Source File: BigLiteralsSpec.scala From refined with MIT License | 5 votes |
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 46
Source File: RefineSyntaxSpec.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.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 47
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 48
Source File: SyntaxSpec.scala From refined with MIT License | 5 votes |
package eu.timepit.refined.cats import _root_.cats.data.{NonEmptyList, Validated} import eu.timepit.refined.W import eu.timepit.refined.api.{Refined, RefinedTypeOps} import eu.timepit.refined.numeric.{Interval, Positive} import eu.timepit.refined.refineMV import eu.timepit.refined.types.numeric.PosInt import org.scalacheck.Prop._ import org.scalacheck.Properties class SyntaxSpec extends Properties("syntax") { property("ValidateNel when Valid") = secure { import syntax._ PosInt.validateNel(5) ?= Validated.Valid(PosInt.unsafeFrom(5)) } property("ValidateNel when Invalid") = secure { import syntax._ PosInt.validateNel(-1) ?= Validated.invalidNel("Predicate failed: (-1 > 0).") } property("validateNel without import") = secure { type OneToTen = Int Refined Interval.Closed[W.`1`.T, W.`10`.T] object OneToTen extends RefinedTypeOps[OneToTen, Int] with CatsRefinedTypeOpsSyntax OneToTen.validateNel(5) ?= Validated.valid(OneToTen.unsafeFrom(5)) } property("ValidateNec when Valid") = secure { import syntax._ PosInt.validateNec(5) ?= Validated.Valid(PosInt.unsafeFrom(5)) } property("ValidateNec when Invalid") = secure { import syntax._ PosInt.validateNec(-1) ?= Validated.invalidNec("Predicate failed: (-1 > 0).") } property("validateNec without import") = secure { type OneToTen = Int Refined Interval.Closed[W.`1`.T, W.`10`.T] object OneToTen extends RefinedTypeOps[OneToTen, Int] with CatsRefinedTypeOpsSyntax OneToTen.validateNec(5) ?= Validated.valid(OneToTen.unsafeFrom(5)) } property("NonEmptyList refinedSize (1)") = secure { import syntax._ NonEmptyList.of("one").refinedSize ?= refineMV[Positive](1) } property("NonEmptyList refinedSize (> 1)") = secure { import syntax._ NonEmptyList.of("one", "two", "three").refinedSize ?= refineMV[Positive](3) } }
Example 49
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 50
Source File: Sha1.scala From scala-steward with Apache License 2.0 | 5 votes |
package org.scalasteward.core.git import cats.Eq import cats.implicits._ import eu.timepit.refined.W import eu.timepit.refined.api.{Refined, RefinedTypeOps} import eu.timepit.refined.boolean.{And, Or} import eu.timepit.refined.char.Digit import eu.timepit.refined.collection.{Forall, Size} import eu.timepit.refined.generic.Equal import eu.timepit.refined.numeric.Interval import io.circe.refined._ import io.circe.{Decoder, Encoder} import org.scalasteward.core.git.Sha1.HexString final case class Sha1(value: HexString) object Sha1 { type HexDigit = Digit Or Interval.Closed[W.`'a'`.T, W.`'f'`.T] type HexString = String Refined (Forall[HexDigit] And Size[Equal[W.`40`.T]]) object HexString extends RefinedTypeOps[HexString, String] def from(s: String): Either[Throwable, Sha1] = HexString.from(s).bimap(new Throwable(_), Sha1.apply) implicit val sha1Eq: Eq[Sha1] = Eq.by(_.value.value) implicit val sha1Decoder: Decoder[Sha1] = Decoder[HexString].map(Sha1.apply) implicit val sha1Encoder: Encoder[Sha1] = Encoder[HexString].contramap(_.value) }
Example 51
Source File: string.scala From scala-steward with Apache License 2.0 | 5 votes |
package org.scalasteward.core.util import cats.Foldable import cats.implicits._ import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.MinSize import eu.timepit.refined.refineV import eu.timepit.refined.types.numeric.NonNegBigInt import org.scalasteward.core.util.Change.{Changed, Unchanged} import scala.util.Try import scala.util.matching.Regex import shapeless.Witness object string { type MinLengthString[N] = String Refined MinSize[N] def splitBetweenLowerAndUpperChars(s: String): List[String] = splitBetween2CharMatches("\\p{javaLowerCase}\\p{javaUpperCase}".r)(s) private def splitBetween2CharMatches(regex: Regex)(s: String): List[String] = { val bounds = regex.findAllIn(s).matchData.map(_.start + 1).toList val indices = 0 +: bounds :+ s.length indices.sliding(2).collect { case i1 :: i2 :: Nil => s.substring(i1, i2) }.toList } }