• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Matcher类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中org.specs2.matcher.Matcher的典型用法代码示例。如果您正苦于以下问题:Scala Matcher类的具体用法?Scala Matcher怎么用?Scala Matcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Matcher类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: beRejectedWithMessage

//设置package包名称以及导入依赖的类
package com.wix.pay.twocheckout

import com.wix.pay.testkit.LibPayTestSupport
import com.wix.pay.twocheckout.tokenization.RSAPublicKey
import com.wix.pay.{PaymentErrorException, PaymentRejectedException}
import org.json4s.ParserUtil.ParseException
import org.specs2.matcher.Matcher
import org.specs2.matcher.MustThrownMatchers._

import scala.reflect.ClassTag
import scala.util.Try

trait TwocheckoutTestSupport extends LibPayTestSupport {
  val sellerId = "someSellerId"
  val publishableKey = "somePublishableKey"
  val privateKey = "somePrivateKey"
  val somePretoken = "somePretoken"
  val token = "someToken"
  val someMerchant = TwocheckoutMerchant(sellerId, publishableKey, privateKey)
  val someMerchantStr = JsonTwocheckoutMerchantParser.stringify(someMerchant)

  val somePublicKey = RSAPublicKey(
    "AMroNi0ZH7gGJPzgZP11kwEl++ZZgmQeQpqD69Ghgp72cPMNDDe217HzPrULQEUBQwyX21i1ZagHU9jJTSbHMwtoZRCCa8AiWvxBtO1XJ7" +
      "4nU9heeQScyf3M25Lu9wxPKVfaTrMcXi879TjZm8TNqr89jBqCF1NUtDO+EFFi4OStKf9ILd0DMBYBhOdxBkBmBSy8VIhw0n0JI6RhSERv" +
      "LI6Ia7n63VEOCC8zfdTUwmp2e4g7M0DHvOPqZ9Ldoy4g5DQqQZW/qRVYgKgxlOXUBnJD7HquMg1oWWrYL0zWmBBEG/aOOOpgxqrCM7fmml" +
      "0A4dKqS4blxeT99p7Tori9VBM=",
    "AQAB"
  )

  def beRejectedWithMessage(message: String): Matcher[Try[String]] = beFailedTry.like { case e: PaymentRejectedException => e.message mustEqual message }
  def failWithMessage(message: String): Matcher[Try[String]] = beFailedTry.like { case e: PaymentErrorException => e.message must contain(message) }

  def beParseError: Matcher[Try[String]] = failWithCause[ParseException]
  def beUnsupportedError: Matcher[Try[String]] = failWithCause[UnsupportedOperationException]
  private def failWithCause[T : ClassTag]: Matcher[Try[String]] = beFailedTry.like { case e: PaymentErrorException => e.cause must beAnInstanceOf[T] }
} 
开发者ID:wix,项目名称:libpay-2checkout,代码行数:37,代码来源:TwocheckoutTestSupport.scala


示例2: containBillingAddress

//设置package包名称以及导入依赖的类
package com.wix.pay.stripe.drivers

import java.util

import com.wix.pay.creditcard.{AddressDetailed, PublicCreditCardOptionalFields}
import com.wix.pay.model.{Customer, IncludedCharges, OrderItem, ShippingAddress}
import com.wix.pay.stripe._
import org.specs2.matcher.{Matcher, Matchers}

trait StripeMatchers { self : Matchers =>

  def containBillingAddress(billingAddress: AddressDetailed): Matcher[MappedParams] = {
    be_===(billingAddress) ^^ {
      StripeAdditionalInfoReConstructor.reconstructBillingAddress(_: MappedParams)
    }
  }

  def containCustomer(customer: Customer): Matcher[MappedParams] = {
    be_===(customer) ^^ {
      StripeAdditionalInfoReConstructor.reconstructCustomer(_: MappedParams)
    }
  }

  def containInvoiceId(invoiceId: String): Matcher[MappedParams] = {
    be_===(invoiceId) ^^ {
      StripeAdditionalInfoReConstructor.reconstructInvoiceId(_: MappedParams)
    }
  }

  def containShippingAddress(shippingAddress: ShippingAddress): Matcher[MappedParams] = {
    be_===(shippingAddress) ^^ {
      StripeAdditionalInfoReConstructor.reconstructShippingAddress(_: MappedParams)
    }
  }

  def containOrderItems(orderItems: Seq[OrderItem]): Matcher[MappedParams] = {
    be_===(orderItems) ^^ {
      StripeAdditionalInfoReConstructor.reconstructOrderItems(_: MappedParams)
    }
  }

  def containIncludedCharges(includedCharges: IncludedCharges): Matcher[MappedParams] = {
    be_===(includedCharges) ^^ {
      StripeAdditionalInfoReConstructor.reconstructIncludedCharges(_: MappedParams)
    }
  }

  def haveFieldParams(fields: PublicCreditCardOptionalFields): Matcher[util.LinkedHashMap[String, Object]] = {
    be_===(fields.billingAddress.get) ^^ {(_:util.LinkedHashMap[String, Object]).get("address_line1").toString} and
      be_===(fields.billingPostalCode.get) ^^ {(_:util.LinkedHashMap[String, Object]).get("address_zip").toString} and
      be_===(fields.holderName.get) ^^ {(_:util.LinkedHashMap[String, Object]).get("name").toString}
  }

  def haveAnyEmptyFields(): Matcher[util.LinkedHashMap[String, Object]] = {
    beTrue ^^ {(_:util.LinkedHashMap[String, Object]).containsKey("address_line1")} or
      beTrue ^^ {(_:util.LinkedHashMap[String, Object]).containsKey("address_zip")}
  }
} 
开发者ID:wix,项目名称:libpay-stripe,代码行数:59,代码来源:StripeMatchers.scala


示例3: XpctSpec

//设置package包名称以及导入依赖的类
package tryp
package unit

import org.specs2.matcher.{MatchResultCombinators, NumericMatchers, OptionMatchers, Matcher}
import MatchResultCombinators._
import Fs2Sleep.Sleep_IO

object XpctSpec
extends IOSpec
with FixedPool
{
  def name = "spec"

  val threads = 5

  implicit val scheduler = Scheduler.fromFixedDaemonPool(1)

  def is = s2"""
  test $test
  """

  import matcher._

  val rand: IO[Int] = IO(Random.int().abs % 100)

  var x = false

  def failOnce = IO(if (x) 1 else { x = true; sys.error("boom") })

  def test = {
    for {
      _ <- failOnce must_== 1 retry 1
      r <- {
        for {
          target <- IO.pure(Option(2)) must beASome[Int]
          a <- rand.xp
          b <- IO(a) must be_>=(1)
          c <- IO(Option(b)) must contain(a)
          _ <- IO(b) must_== target
        } yield (target, b, c)
      }.retryEvery(1000, 1.millisecond)
      (target, b, c) = r
      d <- IO(List(-1, -2, b, -3)) must contain(be_>=(0))
      _ <- IO(b) must_== target
      _ <- IO(b) mustNot be(0)
      _ <- IO(None: Option[Int]) mustNot contain(1)
    } yield ()
  }
} 
开发者ID:tek,项目名称:pulsar,代码行数:50,代码来源:xpct.scala


示例4: authorizationParser

//设置package包名称以及导入依赖的类
package com.wix.pay.tranzila

import org.specs2.matcher.{AlwaysMatcher, Matcher, Matchers}

trait TranzilaMatchers extends Matchers {
  def authorizationParser: TranzilaAuthorizationParser

  def beMerchant(username: Matcher[String] = AlwaysMatcher()): Matcher[TranzilaMerchant] = {
    username ^^ { (_: TranzilaMerchant).username aka "username" }
  }

  def beAuthorization(index: Matcher[String] = AlwaysMatcher(),
                      confirmationCode: Matcher[String] = AlwaysMatcher()): Matcher[TranzilaAuthorization] = {
    index ^^ { (_: TranzilaAuthorization).index aka "currency" } and
      confirmationCode ^^ { (_: TranzilaAuthorization).confirmationCode aka "confirmation code" }
  }

  def beAuthorizationKey(authorization: Matcher[TranzilaAuthorization]): Matcher[String] = {
    authorization ^^ { authorizationParser.parse(_: String) aka "parsed authorization"}
  }

}

object TranzilaMatchers extends TranzilaMatchers {
  override val authorizationParser = new JsonTranzilaAuthorizationParser()
} 
开发者ID:wix,项目名称:libpay-tranzila,代码行数:27,代码来源:TranzilaMatchers.scala


示例5: SimpleHttpRequestMatcher

//设置package包名称以及导入依赖的类
package com.dwolla.testutils.httpclient

import org.apache.http.client.methods.HttpRequestBase
import org.specs2.matcher.{Expectable, MatchResult, Matcher}

case class SimpleHttpRequestMatcher(req: HttpRequestBase) extends Matcher[HttpRequestBase] {
  override def apply[S <: HttpRequestBase](t: Expectable[S]): MatchResult[S] = {
    val actualValue = t.value
    val test = actualValue != null && req.getMethod == actualValue.getMethod && req.getURI == actualValue.getURI
    result(test, s"${t.description} is the same as ${req.toString}", s"${t.description} is not the same as ${req.toString}", t)
  }
}

object SimpleHttpRequestMatcher {
  def http(req: HttpRequestBase) = SimpleHttpRequestMatcher(req)
} 
开发者ID:Dwolla,项目名称:scala-cloudflare,代码行数:17,代码来源:SimpleHttpRequestMatcher.scala


示例6: serializationBufSize

//设置package包名称以及导入依赖的类
package eu.shiftforward.apso

import java.io._
import org.specs2.matcher.{ Expectable, Matcher }
import org.specs2.mutable.SpecificationLike
import scala.reflect.ClassTag

trait CustomMatchers extends SpecificationLike {
  def serializationBufSize = 10000

  def beSerializable[T <: AnyRef: ClassTag]: Matcher[T] = { obj: T =>
    val buffer = new ByteArrayOutputStream(serializationBufSize)

    val out = new ObjectOutputStream(buffer)
    out.writeObject(obj) must
      not(throwA[NotSerializableException]) and not(throwAn[InvalidClassException])
    // val in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray))
    // in.readObject() must beAnInstanceOf[T] and
    //   not(throwA[InvalidClassException]) and not(throwA[StreamCorruptedException])
  }

  def exist: Matcher[File] = new Matcher[File] {
    def apply[S <: File](v: Expectable[S]) = {
      result(v.value.exists(), v.value.getName + " exists", v.value.getName + " does not exist", v)
    }
  }
} 
开发者ID:ShiftForward,项目名称:apso,代码行数:28,代码来源:CustomMatchers.scala


示例7: MessageStatusResponseSpec

//设置package包名称以及导入依赖的类
package com.github.hgiddens.ausms
package telstra

import io.circe.Json
import io.circe.syntax._
import org.specs2.matcher.{ Matcher, MatcherMacros }
import org.specs2.mutable.Specification

object MessageStatusResponseSpec extends Specification with MatcherMacros {
  def body(status: String) =
    Json.obj(
      "to" -> "0400000000".asJson,
      "receivedTimestamp" -> "2015-02-05T14:10:14+11:00".asJson,
      "sentTimestamp" -> "2015-02-05T14:10:12+11:00".asJson,
      "status" -> status.asJson
    )

  def beResponseWithStatus(status: DeliveryStatus): Matcher[MessageStatusResponse] =
    matchA[MessageStatusResponse].status(status)

  "Decoding JSON" should {
    "decode PEND status" in {
      body("PEND").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Pending))
    }

    "decode SENT status" in {
      body("SENT").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Sent))
    }

    "decode DELIVRD status" in {
      body("DELIVRD").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Delivered))
    }

    "decode READ status" in {
      body("READ").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Read))
    }
  }
} 
开发者ID:hgiddens,项目名称:au-sms,代码行数:39,代码来源:ResourcesSpec.scala


示例8: ColorHashTest

//设置package包名称以及导入依赖的类
package com.github.tkqubo.colorHash

import org.specs2.matcher.Matcher
import org.specs2.mutable.Specification


// scalastyle:off magic.number
class ColorHashTest extends Specification {
  "ColorHashTest" should {
    "hsl" in {
      ColorHash().hsl("yo") === Hsl(326, 0.35d, 0.5d)
      ColorHash().hsl("more complex text") === Hsl(194, 0.5, 0.65)
    }

    "hex" in {
      ColorHash().hex("yo") === "#AC5385"
      ColorHash().hex("more complex text") === "#79BED2"
      ColorHash().hex("this") === "#783A52"
      ColorHash().hex("that") === "#C587B2"
      ColorHash().hex("??") === "#A7D279"
    }

    "rgb" in {
      ColorHash().rgb("yo") === Rgb(172, 83, 133)
      ColorHash().rgb("more complex text") === Rgb(121, 190, 210)
    }

    "apply" should {
      "pass with default parameters" in {
        val instance = ColorHash()
        instance.lightness === ColorHash.defaultParam
        instance.saturation === ColorHash.defaultParam
        instance.hash must beSameMethod(ColorHash.defaultHash)
      }

      "pass with custom parameters" in {
        val instance = ColorHash(Seq(0.1, 0.2), Seq(0.0, 0.5), _.length)
        instance.lightness === Seq(0.0, 0.5)
        instance.saturation === Seq(0.1, 0.2)
        instance.hash("1234567890") === 10L
      }
    }
  }

  private def beSameMethod(expected: String => Long): Matcher[(String => Long)] = { actual: (String => Long) =>
    (1 to 10).forall { _ =>
      val text: String = scala.util.Random.alphanumeric.take(10).mkString
      expected(text) aka s"hash for $text" must_=== actual(text)
    }
  }
} 
开发者ID:tkqubo,项目名称:scala-color-hash,代码行数:52,代码来源:ColorHashTest.scala


示例9: JsonDengionlineMerchantParserTest

//设置package包名称以及导入依赖的类
package com.wix.pay.dengionline


import org.specs2.matcher.MustMatchers._
import org.specs2.matcher.{AlwaysMatcher, Matcher}
import org.specs2.mutable.SpecWithJUnit
import org.specs2.specification.Scope


class JsonDengionlineMerchantParserTest extends SpecWithJUnit {
  trait Ctx extends Scope {
    val merchantParser: DengionlineMerchantParser = new JsonDengionlineMerchantParser

    def beDengionlineMerchant(siteId: Matcher[String] = AlwaysMatcher(),
                              salt: Matcher[String] = AlwaysMatcher()): Matcher[DengionlineMerchant] = {
      siteId ^^ { (_: DengionlineMerchant).siteId aka "siteId" } and
        salt ^^ { (_: DengionlineMerchant).salt aka "salt" }
    }

    val someMerchant = DengionlineMerchant(
      siteId = "some site ID",
      salt = "some salt"
    )
  }

  "stringify and then parse" should {
    "yield a merchant similar to the original one" in new Ctx {
      val merchantKey = merchantParser.stringify(someMerchant)
      merchantParser.parse(merchantKey) must beDengionlineMerchant(
        siteId = ===(someMerchant.siteId),
        salt = ===(someMerchant.salt)
      )
    }
  }
} 
开发者ID:wix,项目名称:libpay-dengionline,代码行数:36,代码来源:JsonDengionlineMerchantParserTest.scala


示例10: authorizationParser

//设置package包名称以及导入依赖的类
package com.wix.pay.dengionline

import org.specs2.matcher.{AlwaysMatcher, Matcher, Matchers}

trait DengionlineMatchers extends Matchers {
  def authorizationParser: DengionlineAuthorizationParser

  def beAuthorization(transactionId: Matcher[String] = AlwaysMatcher()): Matcher[DengionlineAuthorization] = {
    transactionId ^^ { (_: DengionlineAuthorization).transactionId aka "transactionId" }
  }

  def beAuthorizationKey(authorization: Matcher[DengionlineAuthorization]): Matcher[String] = {
    authorization ^^ { authorizationParser.parse(_: String) aka "parsed authorization"}
  }
}

object DengionlineMatchers extends DengionlineMatchers {
  override val authorizationParser = new JsonDengionlineAuthorizationParser()
} 
开发者ID:wix,项目名称:libpay-dengionline,代码行数:20,代码来源:DengionlineMatchers.scala


示例11: containSlice

//设置package包名称以及导入依赖的类
package com.dwolla.testutils.matchers

import org.specs2.matcher.{Expectable, MatchResult, Matcher}

import util.Try

trait AdditionalSeqMatchers
  extends ContainSliceMatcher
    with StartWithMatcher
    with EndWithMatcher

trait ContainSliceMatcher {
  def containSlice[T](expected: T*): ContainSlice[T] = new ContainSlice[T](expected: _*)

  class ContainSlice[T](expected: T*) extends Matcher[Seq[T]] {
    override def apply[S <: Seq[T]](t: Expectable[S]): MatchResult[S] = {
      val prettySlice = s"( ${expected.mkString(", ")} )"
      result(
        test = t.value.containsSlice(expected),
        okMessage = s"${t.description} contains the slice $prettySlice",
        koMessage = s"${t.description} does not contain the slice $prettySlice",
        value = t
      )
    }
  }

}

trait StartWithMatcher {
  def startWith[T](expected: T): StartWith[T] = new StartWith[T](expected)

  class StartWith[T](expected: T) extends Matcher[Seq[T]] {
    override def apply[S <: Seq[T]](t: Expectable[S]): MatchResult[S] = result(
      test = t.value.headOption.exists(_ == expected),
      okMessage = s"""${t.description} starts with "$expected"""",
      koMessage = s"""${t.description} does not start with "$expected"""",
      value = t
    )
  }

}

trait EndWithMatcher {
  def endWith[T](expected: T): EndWith[T] = new EndWith[T](expected)

  class EndWith[T](expected: T) extends Matcher[Seq[T]] {
    override def apply[S <: Seq[T]](t: Expectable[S]): MatchResult[S] = result(
      test = Try {
        t.value.last == expected
      }.getOrElse(false),
      okMessage = s"""${t.description} ends with "$expected"""",
      koMessage = if (t.value.isEmpty)
        s"""The provided (but empty) sequence does not end with "$expected""""
      else
        s"""${t.description} does not end with "$expected"""",
      value = t
    )
  }

} 
开发者ID:Dwolla,项目名称:sbt-docker-containers,代码行数:61,代码来源:AdditionalSeqMatchers.scala


示例12: JsonAuthorizeNetMerchantParserTest

//设置package包名称以及导入依赖的类
package com.wix.pay.authorizenet


import net.authorize.{Environment, Merchant}
import org.specs2.matcher.Matcher
import org.specs2.matcher.MustMatchers._
import org.specs2.mutable.SpecWithJUnit
import org.specs2.specification.Scope




class JsonAuthorizeNetMerchantParserTest extends SpecWithJUnit {

  trait Ctx extends Scope {
    val parser = new JsonAuthorizeNetMerchantParser
  }

  def beMerchant(merchant: Merchant): Matcher[Merchant] = {
    be_===(merchant.getDeviceType) ^^ { (_: Merchant).getDeviceType aka "device type" } and
      be_===(merchant.getEnvironment) ^^ { (_: Merchant).getEnvironment aka "environment" } and
      be_===(merchant.getLogin) ^^ { (_: Merchant).getLogin aka "login" } and
      be_===(merchant.getMarketType) ^^ { (_: Merchant).getMarketType aka "market type" } and
      be_===(merchant.getMD5Value) ^^ { (_: Merchant).getMD5Value aka "MD5 value" } and
      be_===(merchant.getTransactionKey) ^^ { (_: Merchant).getTransactionKey aka "transaction key" } and
      be_===(merchant.getUserRef) ^^ { (_: Merchant).getUserRef aka "user ref" }
  }


  "stringify and then parse" should {
    "yield a merchant similar to the original one" in new Ctx {
      val merchant = Merchant.createMerchant(Environment.PRODUCTION, "kuki", "buki")
      val strMerchant = parser.stringify(merchant)

      parser.parse(Environment.PRODUCTION, strMerchant) must beMerchant(merchant)
    }
  }
} 
开发者ID:wix,项目名称:libpay-authorizenet,代码行数:39,代码来源:JsonAuthorizeNetMerchantParserTest.scala


示例13: JsonPaguelofacilMerchantParserTest

//设置package包名称以及导入依赖的类
package com.wix.pay.paguelofacil


import org.specs2.matcher.MustMatchers._
import org.specs2.matcher.{AlwaysMatcher, Matcher}
import org.specs2.mutable.SpecWithJUnit
import org.specs2.specification.Scope


class JsonPaguelofacilMerchantParserTest extends SpecWithJUnit {
  trait Ctx extends Scope {
    val merchantParser: PaguelofacilMerchantParser = new JsonPaguelofacilMerchantParser

    def bePaguelofacilMerchant(cclw: Matcher[String] = AlwaysMatcher()): Matcher[PaguelofacilMerchant] = {
      cclw ^^ { (_: PaguelofacilMerchant).cclw aka "cclw" }
    }

    val someMerchant = PaguelofacilMerchant(
      cclw = "some CCLW"
    )
  }

  "stringify and then parse" should {
    "yield a merchant similar to the original one" in new Ctx {
      val merchantKey = merchantParser.stringify(someMerchant)
      merchantParser.parse(merchantKey) must bePaguelofacilMerchant(
        cclw = ===(someMerchant.cclw)
      )
    }
  }
} 
开发者ID:wix,项目名称:libpay-paguelofacil,代码行数:32,代码来源:JsonPaguelofacilMerchantParserTest.scala


示例14: authorizationParser

//设置package包名称以及导入依赖的类
package com.wix.pay.paguelofacil

import org.specs2.matcher.{AlwaysMatcher, Matcher, Matchers}

trait PaguelofacilMatchers extends Matchers {
  def authorizationParser: PaguelofacilAuthorizationParser

  def beAuthorization(authRefNum: Matcher[String] = AlwaysMatcher()): Matcher[PaguelofacilAuthorization] = {
    authRefNum ^^ { (_: PaguelofacilAuthorization).authRefNum aka "authRefNum" }
  }

  def beAuthorizationKey(authorization: Matcher[PaguelofacilAuthorization]): Matcher[String] = {
    authorization ^^ { authorizationParser.parse(_: String) aka "parsed authorization"}
  }
}

object PaguelofacilMatchers extends PaguelofacilMatchers {
  override val authorizationParser = new JsonPaguelofacilAuthorizationParser()
} 
开发者ID:wix,项目名称:libpay-paguelofacil,代码行数:20,代码来源:PaguelofacilMatchers.scala


示例15: beSameScalaCodeAs

//设置package包名称以及导入依赖的类
package sqlpt.thriftplugin.testhelpers

import java.util.StringTokenizer
import org.specs2.matcher.Matcher
import org.specs2.matcher.Matchers._
import sqlpt.thriftplugin.Utils.BasicThriftParser
import treehugger.forest._

trait CodeTreeMatchers {
  def beSameScalaCodeAs(codeStr: String): Matcher[Tree] = {
    def tokenized(sourceCode: String): List[String] = {
      val Delimiters = " \n()[]{},;:"

      def toList(t: StringTokenizer): List[String] =
        if(t.hasMoreTokens)
          t.nextToken :: toList(t)
        else
          Nil

      toList(new StringTokenizer(sourceCode, Delimiters, true)).filterNot(_.trim.isEmpty)
    }

    (
      (tree: Tree) =>
        tokenized(codeStr) == tokenized(treeToString(tree)),

      (tree: Tree) =>
        s"${treeToString(tree)}\n\nis not the same scala code as:\n$codeStr"
    )
  }
}

trait Helpers extends BasicThriftParser with CodeTreeMatchers 
开发者ID:pmellati,项目名称:sbt-sqlpt-thrift,代码行数:34,代码来源:Helpers.scala


示例16: beRightXor

//设置package包名称以及导入依赖的类
package io.mediachain

import org.specs2.matcher.Matcher
import org.specs2.execute.{Failure, Result}
import org.specs2.matcher.MatchersImplicits._
import cats.data.Xor

trait XorMatchers {
  def beRightXor[T](checker: (T => Result)): Matcher[Xor[_, T]] = {
    (x: Xor[_, T]) => x match {
      case Xor.Right(value) =>
        checker(value)
      case _ =>
        new Failure(s"Xor value was instance of Xor.Left: $x")
    }
  }

  def beRightXor: Matcher[Xor[_, _]] = { (x: Xor[_, _]) =>
    (x.isRight, s"Xor value was instance of Xor.Left: $x")
  }

  def beLeftXor[T](checker: (T => Result)): Matcher[Xor[T, _]] = {
    (x: Xor[T, _]) => x match {
      case Xor.Left(value) =>
        checker(value)
      case _ =>
        new Failure(s"Xor value was instance of Xor.Right: $x")
    }
  }

  def beLeftXor: Matcher[Xor[_, _]] = { (x: Xor[_, _]) =>
    (x.isLeft, s"Xor value was instance of Xor.Right: $x")
  }
} 
开发者ID:mediachain,项目名称:oldchain,代码行数:35,代码来源:XorMatchers.scala


示例17: Common

//设置package包名称以及导入依赖的类
package crudex_tests.web

import scalaz._, Scalaz._

import crudex.model.{UserId, ThingId}

import io.circe.Decoder
import org.http4s.EntityDecoder
import org.http4s.circe.jsonOf

import scalaz.concurrent.Task
import org.specs2.matcher.Matcher
import org.specs2.matcher.MatchersImplicits._

object Common {

  //TODO cannot find Task matchers in scalaz spec2. scalaz-concurrent-spec2?
  def returnTheSameValue[A]: Matcher[Task[Tuple2[A,A]]] = { pair: Task[Tuple2[A, A]] => {
       val unwrapped = pair.unsafePerformSync
       (unwrapped._1 == unwrapped._2, s"Not matching ${unwrapped._1} and ${unwrapped._2}")
     }
  }

  def returnValueOf[A](res: A): Matcher[Task[A]] = { task: Task[A] =>
    (res == task.unsafePerformSync, s"did not match ${res}")
  }

  case class SpecException(s: String) extends Exception

  def assertSome[A](aop : Option[A], msg: => String) : Task[A] =
    for {
      res <- aop match {
        case None => Task.fail(SpecException(msg))
        case Some(a) => a.pure[Task]
      }
    } yield(res)

  def assertNone[A](aop : Option[A], msg: => String) : Task[Unit] =
    for {
      res <- aop match {
        case Some(_) => Task.fail(SpecException(msg))
        case None => ().pure[Task]
      }
    } yield(res)

  object instances {
    implicit def evHttp4sFromJsonDecoder[A](implicit ev: Decoder[A]): EntityDecoder[A] = jsonOf[A]

    implicit val evUserIdDecoder: Decoder[UserId] = Decoder.decodeInt.map(UserId.apply)
    implicit val evThingIdDecoder: Decoder[ThingId] = Decoder.decodeInt.map(ThingId.apply)
  }
} 
开发者ID:rpeszek,项目名称:crud-ex-backent-http4s,代码行数:53,代码来源:Common.scala


示例18: mockContext

//设置package包名称以及导入依赖的类
package macroni

import org.specs2.mock.Mockito
import org.specs2.matcher.Matcher
import scala.reflect.{ClassTag, runtime}
import scala.reflect.macros.Universe
import scala.reflect.macros.blackbox
import macroni.compiler.CompileResult
import macroni.matcher.CompilingTreeMatcher

trait ContextMock extends Mockito {
  def mockContext[C <: blackbox.Context : ClassTag]: C = {
    val mocked = mock[C]
    mocked.universe returns runtime.universe.asInstanceOf[Universe]
    mocked
  }

  implicit def MacroToRuntimeTree(tree: Universe#Tree): runtime.universe.Tree = tree.asInstanceOf[runtime.universe.Tree]
  implicit def RuntimeToMacroTreeMatcher[T <% Matcher[runtime.universe.Tree]](matcher: T): Matcher[Universe#Tree] = implicitly[Matcher[runtime.universe.Tree]](matcher).asInstanceOf[Matcher[Universe#Tree]]
}

object ContextMock extends ContextMock 
开发者ID:cornerman,项目名称:macroni,代码行数:23,代码来源:ContextMock.scala


示例19: authorizationParser

//设置package包名称以及导入依赖的类
package com.wix.pay.mercadopago

import org.specs2.matcher.{AlwaysMatcher, Matcher, Matchers}

trait MercadopagoMatchers extends Matchers {
  def authorizationParser: MercadopagoAuthorizationParser

  def beMerchant(clientId: Matcher[String] = AlwaysMatcher(),
                 clientSecret: Matcher[String] = AlwaysMatcher(),
                 countryCode: Matcher[String] = AlwaysMatcher()): Matcher[MercadopagoMerchant] = {
    clientId ^^ { (_: MercadopagoMerchant).clientId aka "client ID" } and
      clientSecret ^^ { (_: MercadopagoMerchant).clientSecret aka "client Secret" } and
      countryCode ^^ { (_: MercadopagoMerchant).countryCode aka "country code" }
  }

  def beAuthorization(): Matcher[MercadopagoAuthorization] = {
    AlwaysMatcher()
  }

  def beAuthorizationKey(authorization: Matcher[MercadopagoAuthorization]): Matcher[String] = {
    authorization ^^ { authorizationParser.parse(_: String) aka "parsed authorization"}
  }
}

object MercadopagoMatchers extends MercadopagoMatchers {
  override val authorizationParser = new JsonMercadopagoAuthorizationParser()
} 
开发者ID:wix,项目名称:libpay-mercadopago,代码行数:28,代码来源:MercadopagoMatchers.scala


示例20: TokenizeRequestParserTest

//设置package包名称以及导入依赖的类
package com.wix.pay.mercadopago

import com.wix.pay.mercadopago.model._
import org.specs2.matcher.MustMatchers._
import org.specs2.matcher.{AlwaysMatcher, Matcher}
import org.specs2.mutable.SpecWithJUnit
import org.specs2.specification.Scope

class TokenizeRequestParserTest extends SpecWithJUnit {
  trait Ctx extends Scope {
    def beTokenizeRequest(card_number: Matcher[String] = AlwaysMatcher(),
                          security_code: Matcher[Option[String]] = AlwaysMatcher(),
                          expiration_month: Matcher[Int] = AlwaysMatcher(),
                          expiration_year: Matcher[Int] = AlwaysMatcher(),
                          cardholder: Matcher[CardHolder] = AlwaysMatcher()): Matcher[TokenizeRequest] = {
      card_number ^^ { (_: TokenizeRequest).card_number aka "card_number" } and
        security_code ^^ { (_: TokenizeRequest).security_code aka "security_code" } and
        expiration_month ^^ { (_: TokenizeRequest).expiration_month aka "expiration_month" } and
        expiration_year ^^ { (_: TokenizeRequest).expiration_year aka "expiration_year" } and
        cardholder ^^ { (_: TokenizeRequest).cardholder aka "cardholder" }
    }

    val someTokenizeRequest = TokenizeRequest(
      card_number = "some card number",
      security_code = Some("some security code"),
      expiration_month = 12,
      expiration_year = 2020,
      cardholder = CardHolder(
        name = "some cardholder name",
        identification = Identification(
          subtype = "some subtype",
          number = "some number",
          `type` = IdentificationTypes.cpf
        )
      )
    )
  }

  "stringify and then parse" should {
    "yield an object similar to the original one" in new Ctx {
      val str = TokenizeRequestParser.stringify(someTokenizeRequest)
      TokenizeRequestParser.parse(str) must beTokenizeRequest(
        card_number = ===(someTokenizeRequest.card_number),
        security_code = ===(someTokenizeRequest.security_code),
        expiration_month = ===(someTokenizeRequest.expiration_month),
        expiration_year = ===(someTokenizeRequest.expiration_year),
        cardholder = ===(someTokenizeRequest.cardholder)
      )
    }
  }
} 
开发者ID:wix,项目名称:libpay-mercadopago,代码行数:52,代码来源:TokenizeRequestParserTest.scala



注:本文中的org.specs2.matcher.Matcher类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala SnapshotOffer类代码示例发布时间:2022-05-23
下一篇:
Scala PrimitiveTypeName类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap