本文整理汇总了Scala中cats.data.Validated.Invalid类的典型用法代码示例。如果您正苦于以下问题:Scala Invalid类的具体用法?Scala Invalid怎么用?Scala Invalid使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Invalid类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: AssetProcessing
//设置package包名称以及导入依赖的类
package templates
import aws.Interpreter.ErrorsOr
import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, Validated, ValidatedNel}
import com.amazonaws.regions.{Region, Regions}
import com.ovoenergy.comms.model.{Channel, CommManifest}
object AssetProcessing {
private val assetTemplateReferenceRegex = "(?:'|\")(?: *)(assets)(?:/[^(\"')]+)(?: *)(?:'|\")".r
case class ProcessedFiles(templateFiles: List[UploadedTemplateFile], assetFiles: List[UploadedTemplateFile])
def processAssets(region: Regions,
assetsS3Bucket: String,
commManifest: CommManifest,
uploadedFiles: List[UploadedTemplateFile]): ErrorsOr[ProcessedFiles] = {
import cats.syntax.traverse._
import cats.instances.list._
val (assetFiles, nonAssetFiles) = uploadedFiles.partition(_.fileType == Asset)
val processedTemplateFiles: Validated[NonEmptyList[String], List[UploadedTemplateFile]] = nonAssetFiles
.traverseU(templateFile => {
replaceAssetReferences(region, assetsS3Bucket, templateFile.channel, commManifest, templateFile.contents)
.map(contents => templateFile.copy(contents = contents))
})
processedTemplateFiles.map(ProcessedFiles(_, assetFiles)).toEither
}
private def replaceAssetReferences(region: Regions,
assetsS3Bucket: String,
channel: Channel,
commManifest: CommManifest,
contents: Array[Byte]): ValidatedNel[String, Array[Byte]] = {
def replaceReferences(s3Endpoint: String, contentsString: String) = {
val replacementAssetsPath = s"$s3Endpoint/assets"
assetTemplateReferenceRegex
.replaceAllIn(contentsString, m => m.group(0).replaceFirst(m.group(1), replacementAssetsPath))
.getBytes
}
determineS3Endpoint(region, assetsS3Bucket, channel, commManifest).map(replaceReferences(_, new String(contents)))
}
private def determineS3Endpoint(region: Regions,
assetsS3Bucket: String,
channel: Channel,
commManifest: CommManifest): ValidatedNel[String, String] = {
if (!Region.getRegion(region).isServiceSupported("s3")) {
Invalid(NonEmptyList.of("S3 not supported in region selected"))
} else if (!Region.getRegion(region).hasHttpsEndpoint("s3")) {
Invalid(NonEmptyList.of("No https support for s3 in region selected"))
} else {
val s3ServiceEndpoint = Region.getRegion(region).getServiceEndpoint("s3")
Valid(
s"https://$s3ServiceEndpoint/$assetsS3Bucket/${commManifest.commType.toString.toLowerCase}/${commManifest.name}/${commManifest.version}/${channel.toString.toLowerCase}")
}
}
}
示例2: ValidatedTest
//设置package包名称以及导入依赖的类
package objektwerks.validated
import org.scalatest.{FunSuite, Matchers}
class ValidatedTest extends FunSuite with Matchers {
test("instances") {
import cats.data.Validated
import cats.data.Validated.Valid
import cats.data.Validated.Invalid
Validated.Valid(3) shouldEqual Valid(3)
Validated.Invalid("three") shouldEqual Invalid("three")
Validated.valid[String, Int](3) shouldEqual Valid(3)
Validated.invalid[String, Int]("three") shouldEqual Invalid("three")
}
test("syntax") {
import cats.syntax.validated._
import cats.data.Validated.Valid
import cats.data.Validated.Invalid
3.valid[String] shouldEqual Valid(3)
"three".invalid[Int] shouldEqual Invalid("three")
}
test("methods") {
import cats.data.Validated
import cats.syntax.validated._
import cats.data.Validated.Valid
Validated.catchOnly[NumberFormatException]("three".toInt).isInvalid shouldBe true
Validated.catchNonFatal(sys.error("Nonfatal")).isInvalid shouldBe true
Validated.fromTry(scala.util.Try("three".toInt)).isInvalid shouldBe true
Validated.fromEither[String, Int](Left("Error")).isInvalid shouldBe true
Validated.fromOption[String, Int](None, "Error").isInvalid shouldBe true
3.valid.map(_ * 3) shouldEqual Valid(9)
}
}
示例3: ProfileValidation
//设置package包名称以及导入依赖的类
package com.ovoenergy.orchestration.profile
import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, Validated}
import cats.{Apply, Semigroup}
import com.ovoenergy.comms.model.InvalidProfile
import com.ovoenergy.orchestration.domain.CustomerProfile
import com.ovoenergy.orchestration.logging.LoggingWithMDC
import com.ovoenergy.orchestration.processes.Orchestrator.ErrorDetails
object ProfileValidation extends LoggingWithMDC {
case class ValidationError(message: String)
case class ValidationErrors(errors: NonEmptyList[ValidationError]) {
def errorsString: String = {
errors.map(_.message).toList.mkString(", ")
}
}
object ValidationErrors {
def apply(message: String): ValidationErrors = ValidationErrors(ValidationError(message))
def apply(error: ValidationError): ValidationErrors = ValidationErrors(NonEmptyList.of(error))
implicit val sg = new Semigroup[ValidationErrors] {
def combine(x: ValidationErrors, y: ValidationErrors): ValidationErrors =
ValidationErrors(x.errors.concat(y.errors))
}
}
private type ValidationErrorsOr[A] = Validated[ValidationErrors, A]
def apply(customerProfile: CustomerProfile): Either[ErrorDetails, CustomerProfile] = {
val firstName: ValidationErrorsOr[String] = {
if (customerProfile.name.firstName.isEmpty) Validated.invalid(ValidationErrors("Customer has no first name"))
else Validated.valid(customerProfile.name.firstName)
}
val lastName: ValidationErrorsOr[String] = {
if (customerProfile.name.lastName.isEmpty) Validated.invalid(ValidationErrors("Customer has no last name"))
else Validated.valid(customerProfile.name.lastName)
}
val profileOrErrors = Apply[ValidationErrorsOr].map2(firstName, lastName) {
case (validFirstName, validLastName) =>
customerProfile
}
profileOrErrors match {
case Valid(profile) => Right(profile)
case Invalid(errors) =>
Left(ErrorDetails(errors.errorsString, InvalidProfile))
}
}
}
示例4: ValidationContext
//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.compile
import cats.data.Validated.{Invalid, Valid}
import cats.data.{ValidatedNel, _}
import pl.touk.nussknacker.engine.compile.ProcessCompilationError.{NoParentContext, NodeId, OverwrittenVariable}
import pl.touk.nussknacker.engine.definition.DefinitionExtractor.{ClazzRef, PlainClazzDefinition}
case class ValidationContext(variables: Map[String, ClazzRef] = Map.empty,
typesInformation: List[PlainClazzDefinition] = List.empty,
parent: Option[ValidationContext] = None) {
def apply(name: String): ClazzRef =
get(name).getOrElse(throw new RuntimeException(s"Unknown variable: $name"))
def get(name: String): Option[ClazzRef] =
variables.get(name)
def contains(name: String): Boolean = variables.contains(name)
def withVariable(name: String, value: ClazzRef)(implicit nodeId: NodeId): ValidatedNel[PartSubGraphCompilationError, ValidationContext] =
if (variables.contains(name)) Invalid(NonEmptyList.of(OverwrittenVariable(name))) else Valid(copy(variables = variables + (name -> value)))
def getTypeInfo(clazzRef: ClazzRef): PlainClazzDefinition = {
typesInformation.find(_.clazzName == clazzRef).getOrElse(throw new RuntimeException(s"Unknown clazz ref: $clazzRef"))
}
def pushNewContext() : ValidationContext
= ValidationContext(Map(), typesInformation, Some(this))
def popContext(implicit nodeId: NodeId) : ValidatedNel[PartSubGraphCompilationError, ValidationContext] = parent match {
case Some(ctx) => Valid(ctx)
case None => Invalid(NonEmptyList.of(NoParentContext(nodeId.id)))
}
}
示例5: readConfigFromArgs
//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.process.runner
import java.io.{File, FileReader}
import cats.data.Validated.{Invalid, Valid}
import com.typesafe.config.{Config, ConfigFactory}
import org.apache.commons.io.IOUtils
import pl.touk.nussknacker.engine.api.process.ProcessConfigCreator
import pl.touk.nussknacker.engine.canonicalgraph.CanonicalProcess
import pl.touk.nussknacker.engine.canonize.ProcessCanonizer
import pl.touk.nussknacker.engine.graph.EspProcess
import pl.touk.nussknacker.engine.marshall.ProcessMarshaller
import pl.touk.nussknacker.engine.util.ThreadUtils
trait FlinkRunner {
private val ProcessMarshaller = new ProcessMarshaller
protected def readConfigFromArgs(args: Array[String]): Config = {
val optionalConfigArg = if (args.length > 1) Some(args(1)) else None
readConfigFromArg(optionalConfigArg)
}
protected def loadCreator(config: Config): ProcessConfigCreator =
ThreadUtils.loadUsingContextLoader(config.getString("processConfigCreatorClass")).newInstance().asInstanceOf[ProcessConfigCreator]
protected def readProcessFromArg(arg: String): EspProcess = {
val canonicalJson = if (arg.startsWith("@")) {
IOUtils.toString(new FileReader(arg.substring(1)))
} else {
arg
}
ProcessMarshaller.fromJson(canonicalJson).toValidatedNel[Any, CanonicalProcess] andThen { canonical =>
ProcessCanonizer.uncanonize(canonical)
} match {
case Valid(p) => p
case Invalid(err) => throw new IllegalArgumentException(err.toList.mkString("Unmarshalling errors: ", ", ", ""))
}
}
private def readConfigFromArg(arg: Option[String]): Config =
arg match {
case Some(name) if name.startsWith("@") =>
ConfigFactory.parseFile(new File(name.substring(1)))
case Some(string) =>
ConfigFactory.parseString(string)
case None =>
ConfigFactory.load()
}
}
示例6: LineParserSpec
//设置package包名称以及导入依赖的类
package ch.becompany.akka.io.csv
import cats.data.NonEmptyList
import cats.data.Validated.{Invalid, Valid}
import org.scalatest._
class LineParserSpec extends FlatSpec with Matchers with EitherValues {
import Parsers._
case class Record(a: String, b: String)
"A LineParser" should "parse lines" in {
val line = List("foo", "bar")
val result = LineParser[Record](line)
result shouldBe Valid(Record("foo", "bar"))
}
"A LineParser" should "fail on missing elements" in {
val line = List("foo")
val result = LineParser[Record](line)
result shouldBe Invalid(NonEmptyList("Excepted list element."))
}
"A LineParser" should "fail on surplus elements" in {
val line = List("foo", "bar", "baz")
val result = LineParser[Record](line)
result shouldBe Invalid(NonEmptyList("""Expected end, got "baz"."""))
}
}
示例7: FeedFilters
//设置package包名称以及导入依赖的类
package com.eddsteel.feedfilter
import model._
import model.config._
import model.Errors.{ConfigLoadError, ConfigParseError}
import cats.data.{NonEmptyList, ValidatedNel}
import cats.data.Validated.{Invalid, Valid}
import cats.implicits._
import scala.io.Source
object FeedFilters {
type ConfigErrors = NonEmptyList[ConfigParseError]
def allFeeds: Either[ConfigErrors, List[FeedFilter[String]]] = {
def accumulate[L, R](in: List[ValidatedNel[L, R]]): Either[NonEmptyList[L], List[R]] = {
val (lefts, rights) = in.foldRight((List.empty[L], List.empty[R])) {
case (Invalid(es), (ls, rs)) => (es.toList ++ ls, rs)
case (Valid(r), (ls, rs)) => (ls, r :: rs)
}
lefts match {
case (l :: ls) =>
Left[NonEmptyList[L], List[R]](NonEmptyList(l, ls))
case _ =>
Right[NonEmptyList[L], List[R]](rights)
}
}
def wrap[R](either: Either[ConfigParseError, R]): Either[ConfigErrors, R] =
either.leftMap(NonEmptyList(_, Nil))
val sourceE: Either[ConfigErrors, String] =
wrap(
Either
.catchOnly[RuntimeException](Source.fromResource("feeds.yaml"))
.map(_.mkString)
.leftMap[ConfigParseError](e => ConfigLoadError(e)))
for {
source <- sourceE
config <- wrap(YamlFeedConfig.parse(source.mkString))
validatedConfig <- accumulate(config.map(_.toFeedConfig))
filters = validatedConfig.map(_.toFeedFilter)
} yield filters
}
}
示例8: required
//设置package包名称以及导入依赖的类
package allawala.chassis.core.validation
import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, ValidatedNel}
trait ValidateRequired {
protected def required[T](name: String, value: Option[T]): ValidatedNel[ValidationError, T] = value match {
case Some(v) => Valid(v)
case None => Invalid(NonEmptyList.of(RequiredField(name)))
}
protected def requiredString(name: String, value: Option[String]): ValidatedNel[ValidationError, String] =
required[String](name, value)
}
trait ValidateUnexpected {
protected def unexpected[T](name: String, value: Option[T]): ValidatedNel[ValidationError, Option[T]] = value match {
case Some(v) => Invalid(NonEmptyList.of(UnexpectedField(name)))
case None => Valid(value)
}
protected def unexpectedString(name: String, value: Option[String]): ValidatedNel[ValidationError, Option[String]] =
unexpected[String](name, value)
}
trait ValidateNotBlank {
protected def notBlank(name: String, value: String): ValidatedNel[ValidationError, String] =
if (value.trim.isEmpty) Invalid(NonEmptyList.of(NotBlank(name))) else Valid(value)
protected def notBlank(name: String, value: Option[String]): ValidatedNel[ValidationError, Option[String]] = value match {
case Some(v) => notBlank(name, v).map(_ => value)
case None => Invalid(NonEmptyList.of(NotBlank(name)))
}
}
trait ValidateMinLength {
protected def minLength(name: String, value: String, min: Int): ValidatedNel[ValidationError, String] =
if (value.trim.length < min) Invalid(NonEmptyList.of(MinLength(name, min))) else Valid(value)
protected def minLength(name: String, value: Option[String], min: Int): ValidatedNel[ValidationError, Option[String]] = value match {
case Some(v) => minLength(name, v, min).map(_ => value)
case None => Invalid(NonEmptyList.of(MinLength(name, min)))
}
}
trait ValidateMaxLength {
protected def maxLength(name: String, value: String, max: Int): ValidatedNel[ValidationError, String] =
if (value.trim.length > max) Invalid(NonEmptyList.of(MaxLength(name, max))) else Valid(value)
protected def maxLength(name: String, value: Option[String], max: Int): ValidatedNel[ValidationError, Option[String]] = value match {
case Some(v) => maxLength(name, v, max).map(_ => value)
case None => Invalid(NonEmptyList.of(MaxLength(name, max)))
}
}
trait Validate
extends ValidateRequired
with ValidateUnexpected
with ValidateNotBlank
with ValidateMinLength
with ValidateMaxLength
示例9: S3TemplateRepo
//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.composer.repo
import cats.Id
import cats.data.{ReaderT, ValidatedNel}
import cats.data.Validated.{Invalid, Valid}
import com.ovoenergy.comms.model._
import com.ovoenergy.comms.templates.model.template.processed.email.EmailTemplate
import com.ovoenergy.comms.templates.model.template.processed.sms.SMSTemplate
import com.ovoenergy.comms.templates.{TemplatesContext, TemplatesRepo}
object S3TemplateRepo {
type ErrorOr[A] = Either[String, A]
// TODO caching: cache template files indefinitely, fragments for 5 minutes
def getEmailTemplate(commManifest: CommManifest) = ReaderT[ErrorOr, TemplatesContext, EmailTemplate[Id]] { context =>
val template = TemplatesRepo.getTemplate(context, commManifest).map(_.email)
wrangle(template, commManifest)
}
def getSMSTemplate(commManifest: CommManifest) = ReaderT[ErrorOr, TemplatesContext, SMSTemplate[Id]] { context =>
val template = TemplatesRepo.getTemplate(context, commManifest).map(_.sms)
wrangle(template, commManifest)
}
private def wrangle[A](validated: ValidatedNel[String, Option[A]], commManifest: CommManifest): ErrorOr[A] =
validated match {
case Invalid(errs) =>
Left(
s"""The specified template (${commManifest.commType}, ${commManifest.name}, ${commManifest.version}) does not exist or is not valid.
|The following errors were encountered:
|
|${errs.toList.map(e => s" - $e").mkString("\n")}
|""".stripMargin)
case Valid(None) =>
Left(
s"The specified template (${commManifest.commType}, ${commManifest.name}, ${commManifest.version}) does not contain an email template.")
case Valid(Some(result)) => Right(result)
}
}
示例10: HandlebarsWrapper
//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.composer.rendering
import com.github.jknack.handlebars.helper.DefaultHelperRegistry
import com.github.jknack.handlebars.io.StringTemplateSource
import com.github.jknack.handlebars.{Handlebars, Helper, Options}
import java.util.{Map => JMap}
import cats.data.Validated.{Invalid, Valid}
import com.ovoenergy.comms.model.{InvalidTemplate, MissingTemplateData}
import com.ovoenergy.comms.templates.model.HandlebarsTemplate
import scala.collection.mutable
import scala.util.{Failure, Success, Try}
private[rendering] object HandlebarsWrapper {
def render(filename: String, template: HandlebarsTemplate)(context: JMap[String, AnyRef]): ErrorsOr[String] = {
val missingKeys = mutable.Set.empty[String]
val helperRegistry = {
val reg = new DefaultHelperRegistry()
reg.registerHelperMissing(new Helper[JMap[String, AnyRef]] {
override def apply(context: JMap[String, AnyRef], options: Options): AnyRef = {
missingKeys.add(options.helperName)
""
}
})
reg
}
val handlebars = new Handlebars().`with`(helperRegistry)
Try {
val compiledTemplate = handlebars.compile(new StringTemplateSource(filename, template.rawExpandedContent))
compiledTemplate.apply(context)
} match { // note: Try has a `fold` function in Scala 2.12 :)
case Success(result) =>
if (missingKeys.isEmpty)
Valid(result)
else
Invalid(Errors(missingKeys = missingKeys.toSet, exceptions = Nil, MissingTemplateData))
case Failure(e) =>
Invalid(Errors(missingKeys = Set.empty, exceptions = List(e), InvalidTemplate))
}
}
}
示例11: BookValidationValidatedSpec
//设置package包名称以及导入依赖的类
package fp.validated
import cats.data.NonEmptyList
import cats.data.Validated.{Invalid, Valid}
import fp.InvalidParameter
import org.scalatest.{Matchers, WordSpec}
class BookValidationValidatedSpec extends WordSpec with Matchers with BookValidationService {
import fp.BookData._
"BookValidation" should {
"Validate a book" in {
val validated = validateBook(theFountainhead)
validated should === (Valid(NonEmptyList(theFountainhead, Nil)))
}
"Validate books" in {
val validatedBooks = validateBooks(List(theFountainhead, atlasShrugged))
validatedBooks should === (Valid(NonEmptyList(theFountainhead, atlasShrugged :: Nil)))
}
"Accumulate errors on a book" in {
val validated = validateBook(titlelessBook)
validated should === (
Invalid(
NonEmptyList(
InvalidParameter("title must not be empty"),
InvalidParameter("Book has invalid genre") :: Nil
)
)
)
}
"Accumulate errors on books" in {
val validatedBooks = validateBooks(List(titlelessBook, theCountOfMontecristo, theFountainhead))
validatedBooks should === (
Invalid(
NonEmptyList(
InvalidParameter("title must not be empty"),
InvalidParameter("Book has invalid genre") :: InvalidParameter("isbn has not a valid format") :: Nil
)
)
)
}
}
}
示例12: HandlebarsWrapper
//设置package包名称以及导入依赖的类
package postman.infrastructure.rendering
import com.github.jknack.handlebars.helper.DefaultHelperRegistry
import com.github.jknack.handlebars.io.StringTemplateSource
import com.github.jknack.handlebars.{Handlebars, Helper, Options}
import java.util.{Map => JMap}
import cats.data.Validated.{Invalid, Valid}
import com.ovoenergy.comms.model.{InvalidTemplate, MissingTemplateData}
import com.ovoenergy.comms.templates.model.HandlebarsTemplate
import scala.collection.mutable
import scala.util.{Failure, Success, Try}
private[rendering] object HandlebarsWrapper {
def render(filename: String, template: HandlebarsTemplate)(context: JMap[String, AnyRef]): ErrorsOr[String] = {
val missingKeys = mutable.Set.empty[String]
val helperRegistry = {
val reg = new DefaultHelperRegistry()
reg.registerHelperMissing(new Helper[JMap[String, AnyRef]] {
override def apply(context: JMap[String, AnyRef], options: Options): AnyRef = {
missingKeys.add(options.helperName)
""
}
})
reg
}
val handlebars = new Handlebars().`with`(helperRegistry)
Try {
val compiledTemplate = handlebars.compile(new StringTemplateSource(filename, template.rawExpandedContent))
compiledTemplate.apply(context)
} match { // note: Try has a `fold` function in Scala 2.12 :)
case Success(result) =>
if (missingKeys.isEmpty)
Valid(result)
else
Invalid(Errors(missingKeys = missingKeys.toSet, exceptions = Nil, MissingTemplateData))
case Failure(e) =>
Invalid(Errors(missingKeys = Set.empty, exceptions = List(e), InvalidTemplate))
}
}
}
示例13: S3TemplateRepo
//设置package包名称以及导入依赖的类
package postman.infrastructure.templates
import cats.Id
import cats.data.{ReaderT, ValidatedNel}
import cats.data.Validated.{Invalid, Valid}
import com.ovoenergy.comms.model._
import com.ovoenergy.comms.templates.model.template.processed.email.EmailTemplate
import com.ovoenergy.comms.templates.model.template.processed.sms.SMSTemplate
import com.ovoenergy.comms.templates.{TemplatesContext, TemplatesRepo}
object S3TemplateRepo {
type ErrorOr[A] = Either[String, A]
def getEmailTemplate(commManifest: CommManifest) = ReaderT[ErrorOr, TemplatesContext, EmailTemplate[Id]] { context =>
val template = TemplatesRepo.getTemplate(context, commManifest).map(_.email)
wrangle(template, commManifest)
}
def getSMSTemplate(commManifest: CommManifest) = ReaderT[ErrorOr, TemplatesContext, SMSTemplate[Id]] { context =>
val template = TemplatesRepo.getTemplate(context, commManifest).map(_.sms)
wrangle(template, commManifest)
}
private def wrangle[A](validated: ValidatedNel[String, Option[A]], commManifest: CommManifest): ErrorOr[A] =
validated match {
case Invalid(errs) =>
Left(
s"""The specified template (${commManifest.commType}, ${commManifest.name}, ${commManifest.version}) does not exist or is not valid.
|The following errors were encountered:
|
|${errs.toList.map(e => s" - $e").mkString("\n")}
|""".stripMargin)
case Valid(None) =>
Left(
s"The specified template (${commManifest.commType}, ${commManifest.name}, ${commManifest.version}) does not contain an email template.")
case Valid(Some(result)) => Right(result)
}
}
示例14: CreateActor
//设置package包名称以及导入依赖的类
package net.cucumbersome.rpgRoller.warhammer.player.actions
import cats.data.Validated.{Invalid, Valid}
import net.cucumbersome.rpgRoller.warhammer.player.CombatActorValidator.validate
import net.cucumbersome.rpgRoller.warhammer.player.{ActorRepository, CombatActorPresenter}
import scala.concurrent.{ExecutionContext, Future}
object CreateActor {
def createActor(repository: ActorRepository)(toBeSaved: CombatActorPresenter)(implicit ec: ExecutionContext): Future[CommandResult] =
validate(toBeSaved) match {
case Invalid(errors) => Future.successful(CommandFailed(errors.map(_.error).toList))
case Valid(ca) => repository.add(ca).map(_ => Ok)
}
}
trait CommandResult
case object Ok extends CommandResult
case class CommandFailed(errors: List[String]) extends CommandResult
示例15: LeagueEndpointArgsValidatorsTest
//设置package包名称以及导入依赖的类
package com.github.agaro1121.http.client
import cats.data.NonEmptyList
import cats.data.Validated.{Invalid, invalidNel}
import com.github.agaro1121.common.PathOfExileTestSuite
import com.github.agaro1121.exception.{BadLadder, BadLadderLimit, BadLadderTrack}
class LeagueEndpointArgsValidatorsTest extends PathOfExileTestSuite {
"LeagueEndpointArgsValidators" should {
val SampleId: String = "Hardcore"
"validate ladder is either 0 or 1" in {
val response = pathOfExileClient.getLeague(SampleId, ladder = Some(5))
response.isInvalid shouldBe true
response shouldBe invalidNel(BadLadder(s"The value of ladder can only be zero or 1"))
}
"validate Ladder Limit is not greater than 200 when ladder = 1" in {
val response = pathOfExileClient.getLeague(SampleId, ladder = Some(1), ladderLimit = Some(201))
response.isInvalid shouldBe true
response shouldBe invalidNel(BadLadderLimit(s"The value of ladderLimit must be less than 200 when ladder is 1"))
}
"validate Ladder Track is not set if ladder is not equal to 1" in {
val response = pathOfExileClient.getLeague(SampleId, ladder = Some(0), ladderTrack = Some(5))
response.isInvalid shouldBe true
response shouldBe invalidNel(BadLadderTrack(s"LadderTrack can only be set when ladder is 1"))
}
"validate Ladder Offset is not set if ladder is not equal to 1" in {
val response = pathOfExileClient.getLeague(SampleId, ladder = Some(0), ladderOffset = Some(5))
response.isInvalid shouldBe true
response shouldBe invalidNel(BadLadderLimit(s"LadderOffset can only be set when ladder is 1"))
}
"validate ladder is either 0 or 1 and " +
"validate Ladder Track is not set if ladder is not equal to 1 and " +
"validate Ladder Offset is not set if ladder is not equal to 1" in {
val response = pathOfExileClient.getLeague(SampleId, ladder = Some(5), ladderOffset = Some(5), ladderTrack = Some(5))
response.isInvalid shouldBe true
response shouldBe Invalid(NonEmptyList(
BadLadder("The value of ladder can only be zero or 1"),
List(
BadLadderLimit("LadderOffset can only be set when ladder is 1"),
BadLadderTrack("LadderTrack can only be set when ladder is 1")
)
))
}
}
}