本文整理汇总了Scala中org.scalatest.matchers.Matcher类的典型用法代码示例。如果您正苦于以下问题:Scala Matcher类的具体用法?Scala Matcher怎么用?Scala Matcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Matcher类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: HttpExportSpec
//设置package包名称以及导入依赖的类
package com.github.norwae.ignifera
import akka.http.scaladsl.model.HttpEntity
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.{CollectorRegistry, Gauge}
import org.scalatest.matchers.{MatchResult, Matcher}
import org.scalatest.{FlatSpec, Matchers}
import scala.concurrent.duration._
class HttpExportSpec extends FlatSpec with Matchers {
"The http export object" should "include metrics provided by the collector" in {
val export = new HttpExport {
override val registry: CollectorRegistry = new CollectorRegistry()
}
val gauge = Gauge.build("testgauge", "Test").register(export.registry)
gauge.inc()
val reply = export.exportReply
val entity = reply.entity.asInstanceOf[HttpEntity.Strict]
val string = entity.data.utf8String
string should containSubstring("testgauge")
}
it should "have the correct content type" in {
val reply = new HttpExport {}.exportReply
reply.entity.contentType.value.toLowerCase shouldEqual TextFormat.CONTENT_TYPE_004.toLowerCase
}
it should "include the default metrics" in {
val reply = new HttpExport {}.exportReply
val entity = reply.entity.asInstanceOf[HttpEntity.Strict]
val string = entity.data.utf8String
string should containSubstring("process_cpu_seconds_total")
string should containSubstring("jvm_classes_loaded")
}
private def containSubstring(expected: String) =
Matcher[String](left => MatchResult(left.contains(expected), s"Contain $expected", s"not contain $expected"))
}
开发者ID:Norwae,项目名称:ignifera,代码行数:40,代码来源:HttpExportSpec.scala
示例2: serialize
//设置package包名称以及导入依赖的类
package com.commodityvectors.snapshotmatchers.playJson
import com.commodityvectors.snapshotmatchers.{SnapshotLoader, SnapshotMessages, SnapshotSerializer}
import org.scalactic.Equality
import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.libs.json.{JsValue, Json, Reads}
trait PlayJsonSnapshotMatcher extends SnapshotLoader with SnapshotMessages {
implicit lazy val playJsonSerializer = new SnapshotSerializer[JsValue] {
override def serialize(in: JsValue): String = Json.prettyPrint(in)
}
class JsonDeserializerShouldMatch[T](in: T)(implicit reads: Reads[T], equals: Equality[T]) extends Matcher[String] {
override def apply(explicitId: String): MatchResult = {
loadSnapshot(explicitId) match {
case Some(content) =>
val parsed = Json.parse(content).as[T]
val isEquals = equals.areEqual(parsed, in)
MatchResult(isEquals, errorMessage(in.toString, parsed.toString), ContentsAreEqual)
case None => MatchResult(matches = false, s"Could not find snapshot for id: $explicitId", ContentsAreEqual)
}
}
}
def deserializeAs[T](in: T)(implicit reads: Reads[T], equals: Equality[T]) = new JsonDeserializerShouldMatch[T](in)
}
开发者ID:commodityvectors,项目名称:scalatest-snapshot-matchers,代码行数:27,代码来源:PlayJsonSnapshotMatcher.scala
示例3: SameTypeMatcher
//设置package包名称以及导入依赖的类
package knot.testKit
import org.scalatest.matchers.{MatchResult, Matcher}
import scala.reflect.runtime.universe
import scala.reflect.runtime.universe._
trait ReflectTypeMatchers {
case class SameTypeMatcher(right: Type) extends Matcher[Type] {
override def apply(left: universe.Type): MatchResult = {
MatchResult(
left =:= right,
s"universe.Type $left not same type with $right",
s"universe.Type $left same type with $right",
)
}
}
def sameType(tpe: Type) = new SameTypeMatcher(tpe)
}
object ReflectTypeMatchers extends ReflectTypeMatchers
开发者ID:defvar,项目名称:knot,代码行数:24,代码来源:ReflectTypeMatcher.scala
示例4: equalsToJson
//设置package包名称以及导入依赖的类
package pokestats.util
import org.scalactic.Prettifier
import org.scalatest.matchers.{MatchResult, Matcher}
import org.skyscreamer.jsonassert.{JSONCompare, JSONCompareMode}
trait JsonEqualityMatcher {
def equalsToJson(spread: String): Matcher[String] = {
new Matcher[String] {
def apply(left: String): MatchResult = {
val result =
JSONCompare.compareJSON(left, spread, JSONCompareMode.STRICT)
MatchResult(
!result.failed(),
result.getMessage,
"jsons are equal"
)
}
override def toString: String =
"jsonEqual (" + Prettifier.default(spread) + ")"
}
}
}
开发者ID:guilgaly,项目名称:pokemon-stats,代码行数:24,代码来源:JsonEqualityMatcher.scala
示例5: now
//设置package包名称以及导入依赖的类
package uk.vitalcode.dateparser
import java.time.LocalDateTime
import org.scalatest._
import org.scalatest.matchers.{MatchResult, Matcher}
trait ExamplesSupport extends fixture.FreeSpec with fixture.TestDataFixture with Matchers {
protected val currentDate: LocalDateTime
private val dateTimeProvider = new DateTimeProvider {
override def now: LocalDateTime = currentDate
}
private def parseAs(right: List[DateTimeInterval]): Matcher[String] = new Matcher[String] {
def apply(left: String): MatchResult = {
val actual = DateTimeInterval.of(left, dateTimeProvider)
MatchResult(
actual == right,
s"String [$left] results in [$actual] which is not the same as expected [$right]",
s"String [$left] results in $right but it must not"
)
}
}
protected def expected(expectation: DateTimeInterval*) =
(text: FixtureParam) => text.name should parseAs(expectation.toList)
}
开发者ID:vitalcode,项目名称:date-time-range-parser,代码行数:31,代码来源:ExamplesSupport.scala
示例6: SwaveSpec
//设置package包名称以及导入依赖的类
package swave.core
import scala.concurrent.duration._
import org.scalatest.matchers.{MatchResult, Matcher}
import org.scalatest._
import swave.core.util._
abstract class SwaveSpec extends FreeSpec with StreamEnvShutdown {
type Timeout = SwaveSpec.Timeout
def Timeout = SwaveSpec.Timeout
def produce[T](expected: T*)(implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] = produceSeq(expected)
def produceSeq[T](expected: Seq[T])(implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] =
equal(expected).matcher[Seq[T]].compose(_.drainTo(Drain.seq(100)).await(timeout.duration))
def produceError[T](expected: Throwable)(implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] =
equal(expected).matcher[Throwable].compose(_.drainTo(Drain.ignore).failed.await(timeout.duration))
def produceErrorLike[T](pf: PartialFunction[Throwable, Unit])(
implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] =
new Matcher[Spout[T]] {
def apply(left: Spout[T]) = {
val error = left.drainTo(Drain.ignore).failed.await(timeout.duration)
inside(error)(pf)
MatchResult(true, "", "")
}
}
def timed[U](block: ? U): FiniteDuration = {
val start = System.nanoTime()
block
(System.nanoTime() - start).nanos
}
}
object SwaveSpec {
final case class Timeout(duration: FiniteDuration = Duration.Zero)
}
trait StreamEnvShutdown extends Matchers with Inside with BeforeAndAfterAll { this: Suite ?
implicit val env: StreamEnv
override val invokeBeforeAllAndAfterAllEvenIfNoTestsAreExpected = true
override protected def afterAll(): Unit = {
env.shutdown().awaitTermination(2.seconds)
afterTermination()
}
protected def afterTermination(): Unit = ()
}
开发者ID:sirthias,项目名称:swave,代码行数:51,代码来源:SwaveSpec.scala
示例7: SetMatcher
//设置package包名称以及导入依赖的类
package org.hammerlab.test.matchers.seqs
import org.scalatest.matchers.{ MatchResult, Matcher }
case class SetMatcher[T](expected: Set[T])
extends Matcher[Set[T]] {
val seqMatcher =
SeqMatcher[T](
expected.toSeq,
matchOrder = false
)
override def apply(actual: Set[T]): MatchResult =
seqMatcher(actual.toSeq)
}
object SetMatcher {
def setMatch[T](expected: Iterable[(T)]): Matcher[Set[T]] =
SetMatcher[T](expected.toSet)
}
开发者ID:hammerlab,项目名称:test-utils,代码行数:21,代码来源:SetMatcher.scala
示例8: MapMatcher
//设置package包名称以及导入依赖的类
package org.hammerlab.test.matchers.seqs
import org.scalatest.matchers.{ MatchResult, Matcher }
// Operate on common superclass of collection.{im,}mutable.Map
import collection.Map
case class MapMatcher[K: Ordering, V: Ordering](expected: Map[K, V]) extends Matcher[Map[K, V]] {
val seqMatcher = PairSeqMatcher[K, V](expected.toSeq, matchOrder = false)
override def apply(actual: Map[K, V]): MatchResult = {
seqMatcher.apply(actual.toSeq)
}
}
object MapMatcher {
def mapMatch[K: Ordering, V: Ordering](expected: Map[K, V]): Matcher[Map[K, V]] = MapMatcher(expected)
def mapMatch[K: Ordering, V: Ordering](expected: (K, V)*): Matcher[Map[K, V]] = MapMatcher(expected.toMap)
}
开发者ID:hammerlab,项目名称:test-utils,代码行数:20,代码来源:MapMatcher.scala
示例9: ArrMatcher
//设置package包名称以及导入依赖的类
package org.hammerlab.test.matchers.seqs
import org.scalatest.matchers.{ MatchResult, Matcher }
case class ArrMatcher[T](expected: Iterable[T],
matchOrder: Boolean = true)
extends Matcher[Array[T]] {
override def apply(actual: Array[T]): MatchResult =
SeqMatcher[T](expected, matchOrder)
.apply(actual)
}
object ArrMatcher {
def arrMatch[T](expected: Iterable[T]): Matcher[Array[T]] = ArrMatcher[T](expected.toSeq)
def arrMatch[T](expected: Iterator[T]): Matcher[Array[T]] = ArrMatcher[T](expected.toSeq)
}
开发者ID:hammerlab,项目名称:test-utils,代码行数:17,代码来源:ArrMatcher.scala
示例10: FileMatcher
//设置package包名称以及导入依赖的类
package org.hammerlab.test.matchers.files
import org.hammerlab.paths.Path
import org.hammerlab.test.resources.File
import org.scalatest.Matchers
import org.scalatest.matchers.{ MatchResult, Matcher }
class FileMatcher(expected: Path, binaryMatch: Boolean = false)
extends Matcher[Path]
with Matchers {
override def apply(actual: Path): MatchResult =
if (expected.isDirectory)
MatchResult(
false,
s"'Expected' file $expected should not be a directory",
s"<unused>"
)
else if (actual.isDirectory)
MatchResult(
false,
s"'Actual' file $actual should not be a directory",
s"<unused>"
)
else {
val expectedStr = expected.read
val actualStr = actual.read
// Hook into scalatest's usual String-comparison logic, which includes a nice diff summary when the strings
// differ.
be(expectedStr).apply(actualStr)
}
}
object FileMatcher {
def fileMatch(expectedFile: String): FileMatcher = new FileMatcher(File(expectedFile))
def fileMatch(expectedFile: File): FileMatcher = new FileMatcher(expectedFile)
}
开发者ID:hammerlab,项目名称:test-utils,代码行数:40,代码来源:FileMatcher.scala
示例11: firstLinesMatch
//设置package包名称以及导入依赖的类
package org.hammerlab
import org.hammerlab.test.matchers.lines.Line
import org.scalatest.matchers.Matcher
package object test {
def firstLinesMatch(lines: Line*): Matcher[String] =
org.hammerlab.test.matchers.lines.Matcher(
prefix = true,
lines: _*
)
def linesMatch(lines: Line*): Matcher[String] =
org.hammerlab.test.matchers.lines.Matcher(
prefix = false,
lines: _*
)
}
开发者ID:hammerlab,项目名称:test-utils,代码行数:19,代码来源:package.scala
示例12: parseTo
//设置package包名称以及导入依赖的类
package com.tecsisa.lightql
package parser
import com.tecsisa.lightql.ast.Query
import fastparse.core.Parsed.Success
import org.scalatest.Matchers
import org.scalatest.matchers.{ MatchResult, Matcher }
trait QueryMatchers extends Matchers {
type Success = fastparse.core.Parsed.Success[Query, _, _]
type Failure = fastparse.core.Parsed.Failure[_, _]
def parseTo(query: Query): Matcher[String] = new Matcher[String] {
override def apply(left: String): MatchResult = {
val parsed = LightqlParser.parse(left)
val (msg, passes) = parsed match {
case Success(v, _) => (s"but parsed to $v", parsed.get.value == query)
case error: Failure => (s"with failure: ${error.msg}", false)
}
MatchResult(
passes,
s"The string `$left` didn't match the expected query: $query $msg",
s"The string `$left` matched the expected query: $query"
)
}
}
def notParse: Matcher[String] = new Matcher[String] {
override def apply(left: String): MatchResult = {
val parsed = LightqlParser.parse(left)
val (msg, passes) = parsed match {
case Success(v, _) => (v, false)
case error: Failure => (error.msg, true)
}
MatchResult(
passes,
s"The string `$left` should not parse, however it did parse to: $msg",
s"The string did not parse wih failure: $msg"
)
}
}
}
object QueryMatchers extends QueryMatchers
开发者ID:Tecsisa,项目名称:lightQL,代码行数:47,代码来源:QueryMatchers.scala
示例13: ContentMatcher
//设置package包名称以及导入依赖的类
package ${package}
import java.io.File
import scala.io.Source
import org.scalatest.matchers.{MatchResult, Matcher}
trait CustomMatchers {
class ContentMatcher(content: String) extends Matcher[File] {
def apply(left: File): MatchResult = {
def trimLines(s: String): String = s.split("\n").map(_.trim).mkString("\n")
MatchResult(
trimLines(Source.fromFile(left).mkString).contains(trimLines(content)),
s"$left did not contain: $content" ,
s"$left contains $content"
)
}
}
def containTrimmed(content: String) = new ContentMatcher(content)
}
开发者ID:DANS-KNAW,项目名称:easy-module-archetype,代码行数:23,代码来源:CustomMatchers.scala
示例14: materializer
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.support
import akka.stream.ActorMaterializer
import com.fasterxml.jackson.databind.JsonMappingException
import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.mvc.Result
import uk.gov.hmrc.play.http.HttpResponse
import uk.gov.hmrc.play.test.UnitSpec
import scala.util.Try
trait ErrorResultMatchers { this: UnitSpec =>
implicit def materializer: ActorMaterializer
class ErrorResultMatcher(expectedResult: Result) extends Matcher[HttpResponse] {
override def apply(left: HttpResponse): MatchResult = {
val expectedBodyJson = jsonBodyOf(expectedResult)
val rawNegatedFailureMessage =
s"""Response had expected status ${expectedResult.header.status} and body "$expectedBodyJson""""
if (left.status != expectedResult.header.status) {
MatchResult(
false,
s"""Response had status ${left.status} not expected status ${expectedResult.header.status}""",
rawNegatedFailureMessage
)
} else {
Try(left.json)
.map(json =>
MatchResult(
json == expectedBodyJson,
s"""Response had body "$json" not expected body "$expectedBodyJson""",
rawNegatedFailureMessage))
.recover {
case e: JsonMappingException =>
MatchResult(
false,
s"""Response had body "${left.body}" which did not parse as JSON due to exception:\n$e""",
rawNegatedFailureMessage)
}.get
}
}
}
def matchErrorResult(expectedResult: Result) = new ErrorResultMatcher(expectedResult)
}
开发者ID:hmrc,项目名称:agent-invitations,代码行数:49,代码来源:ErrorResultMatchers.scala
示例15: AkkadmeyDBFirstTest
//设置package包名称以及导入依赖的类
package com.harmeetsingh13.chapter1
import akka.actor.ActorSystem
import akka.testkit.TestActorRef
import com.harmeetsingh13.chapter1.examples.AkkadmeyDBFirst
import com.harmeetsingh13.chapter1.messages.SetRequest
import org.scalatest.{Matchers, FunSpecLike, BeforeAndAfterEach, FunSpec}
import org.scalatest.matchers.Matcher
class AkkadmeyDBFirstTest extends FunSpecLike with Matchers with BeforeAndAfterEach{
implicit val system = ActorSystem()
describe("akkadmey-db-first-test"){
describe("given SetRequest"){
it("should place key/value into map"){
val actorRef = TestActorRef(new AkkadmeyDBFirst)
actorRef ! SetRequest("key", "value")
val akkadmeyDb = actorRef.underlyingActor
akkadmeyDb.map.get("key") should equal (Some("value"))
}
}
}
}
开发者ID:harmeetsingh0013,项目名称:Akka-practice-using-scala,代码行数:25,代码来源:AkkadmeyDBFirstTest.scala
示例16: areEqual
//设置package包名称以及导入依赖的类
package argus.macros
import org.scalactic.Equality
import org.scalatest.matchers.{ MatchResult, Matcher }
import scala.tools.reflect.ToolBox
trait ASTMatchers {
val runtimeUniverse = scala.reflect.runtime.universe
import runtimeUniverse._
import scala.reflect.runtime.currentMirror
val toolbox = currentMirror.mkToolBox()
// For testing equality between trees in tests
implicit val treeEq = new Equality[Tree] {
def areEqual(a: Tree, b: Any): Boolean =
b match {
// equalsStructure bug: https://github.com/scalamacros/paradise/issues/80
case c: Tree => showRaw(a) == showRaw(c) //.equalsStructure(c)
case _ => false
}
}
implicit val valDefEq = new Equality[ValDef] {
def areEqual(a: ValDef, b: Any): Boolean =
b match {
case c: ValDef => showRaw(a) == showRaw(c)
case _ => false
}
}
implicit val listTreeEq = new Equality[List[Tree]] {
def areEqual(a: List[Tree], b: Any): Boolean =
b match {
case c: List[_] => a.size == c.size && a.zip(c).forall { case(x,y) => treeEq.areEqual(x,y) }
case _ => false
}
}
val extractCodecNameAndType: PartialFunction[Tree, (String, String)] = {
case q"implicit val $name: $typ = $_" => (name.toString, typ.toString)
}
}
开发者ID:aishfenton,项目名称:Argus,代码行数:46,代码来源:ASTMatchers.scala
示例17: beSameJsonAs
//设置package包名称以及导入依赖的类
package argus.macros
import argus.json.JsonDiff
import org.scalactic.Equality
import cats.syntax.either._
import io.circe._
import org.scalatest.matchers.{ MatchResult, Matcher }
// TODO Should refactor this into somewhere generally useful.
trait JsonMatchers {
def beSameJsonAs(jrStr: String): Matcher[Json] = new Matcher[Json] {
def apply(jl: Json) = {
val jr = parser.parse(jrStr).toOption.get
beSameJsonAs(jr)(jl)
}
}
def beSameJsonAs(jr: Json): Matcher[Json] = new Matcher[Json] {
def apply(jl: Json) = {
val diff = JsonDiff.diff(jl, jr)
MatchResult(diff.isEmpty, "Differences found in json: " + diff.mkString(","), "No differences found!")
}
}
implicit val jsonEq = new Equality[Json] {
def areEqual(a: Json, b: Any): Boolean =
b match {
case c: Json => JsonDiff.diff(a, c) == Nil
case c: String => JsonDiff.diff(a, parser.parse(c).toOption.get) == Nil
case _ => false
}
}
}
开发者ID:aishfenton,项目名称:Argus,代码行数:36,代码来源:JsonMatchers.scala
示例18: ProduceError
//设置package包名称以及导入依赖的类
package com.wavesplatform.http
import akka.http.scaladsl.testkit.RouteTest
import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.libs.json._
import com.wavesplatform.http.ApiMarshallers._
import scorex.api.http.ApiError
trait ApiErrorMatchers { this: RouteTest =>
class ProduceError(error: ApiError) extends Matcher[RouteTestResult] {
override def apply(left: RouteTestResult): MatchResult = left ~> check {
if (response.status != error.code) {
MatchResult(false, "got {0} while expecting {1}, response was {2}",
"got expected status code {0}",
IndexedSeq(response.status, error.code, response.entity))
} else {
val responseJson = responseAs[JsObject]
MatchResult(responseJson == error.json,
"expected {0}, but instead got {1}",
"expected not to get {0}, but instead did get it",
IndexedSeq(error.json, responseJson))
}
}
}
def produce(error: ApiError) = new ProduceError(error)
}
开发者ID:wavesplatform,项目名称:Waves,代码行数:28,代码来源:ApiErrorMatchers.scala
示例19: TestUtils
//设置package包名称以及导入依赖的类
package flumina
import org.scalatest.matchers.{MatchResult, Matcher}
import scala.annotation.tailrec
object TestUtils {
private class RespectOrderMatcher[A](f: A => Long) extends Matcher[Seq[A]] {
override def apply(left: Seq[A]): MatchResult = {
@tailrec
def loop(list: List[A]): MatchResult = list match {
case first :: second :: tail =>
if (f(first) < f(second)) loop(second :: tail)
else MatchResult(false, s"$first is not less $second", s"$first is less $second")
case _ => MatchResult(matches = true, "", "")
}
loop(left.toList)
}
}
def respectOrder[A](f: A => Long): Matcher[Seq[A]] = new RespectOrderMatcher[A](f)
}
开发者ID:vectos,项目名称:flumina,代码行数:24,代码来源:TestUtils.scala
示例20: beSameJsonAs
//设置package包名称以及导入依赖的类
package vegas
import argus.json.JsonDiff
import org.scalactic.Equality
import io.circe._
import org.scalatest.matchers.{ MatchResult, Matcher }
// TODO This is copy-and-pasted from argus. Really needs to be put somewhere shared.
trait JsonMatchers {
def beSameJsonAs(jrStr: String): Matcher[Json] = new Matcher[Json] {
def apply(jl: Json) = {
val jr = parser.parse(jrStr).right.get
beSameJsonAs(jr)(jl)
}
}
def beSameJsonAs(jr: Json): Matcher[Json] = new Matcher[Json] {
def apply(jl: Json) = {
val diff = JsonDiff.diff(jl, jr)
MatchResult(diff.isEmpty, "Differences found in json: " + diff.mkString(","), "No differences found!")
}
}
implicit val jsonEq = new Equality[Json] {
def areEqual(a: Json, b: Any): Boolean =
b match {
case c: Json => JsonDiff.diff(a, c) == Nil
case c: String => JsonDiff.diff(a, parser.parse(c).right.get) == Nil
case _ => false
}
}
}
开发者ID:vegas-viz,项目名称:Vegas,代码行数:35,代码来源:JsonMatchers.scala
注:本文中的org.scalatest.matchers.Matcher类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论