当前位置: 首页>>代码示例>>Scala>>正文


Scala MatchResult类代码示例

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


在下文中一共展示了MatchResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: Matcher

//设置package包名称以及导入依赖的类
package org.hammerlab.test.matchers.lines

import org.scalatest.matchers
import org.scalatest.matchers.MatchResult

object Matcher {
  def apply(lines: Line*): matchers.Matcher[String] =
    apply(
      prefix = false,
      lines: _*
    )

  def apply(prefix: Boolean, lines: Line*): matchers.Matcher[String] =
    new matchers.Matcher[String] {
      override def apply(str: String): MatchResult = {

        val chars = LinesIterator(str)

        val pieces =
          lines
            .flatMap(_.pieces :+ NewLine)
            .dropRight(1)
            .iterator
            .buffered

        while (
          pieces.hasNext &&
            pieces
              .head
              .matches(chars)
        ) {
          pieces.next
        }

        val strPos = chars.pos

        def unexpectedMismatchMessage: String = {
          def piecesSample =
            pieces
              .take(100)
              .mkString(", ")

          if (!pieces.hasNext)
            s"Actual string extends beyond expected ($strPos):\n$str"
          else if (!chars.hasNext)
            s"Actual string ends before expected ($strPos); missing: $piecesSample"
          else
            s"${pieces.head} didn't match string from $strPos:\n$str"
        }

        MatchResult(
          pieces.isEmpty && (prefix || chars.isEmpty),
          unexpectedMismatchMessage,
          s"Unexpected match:\n$str"
        )
      }
    }
} 
开发者ID:hammerlab,项目名称:test-utils,代码行数:59,代码来源:Matcher.scala

示例8: 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

示例9: 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

示例10: 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

示例11: 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

示例12: checkResult

//设置package包名称以及导入依赖的类
package org.hammerlab.test.matchers.utils

import org.hammerlab.test.Suite
import org.scalatest.matchers.MatchResult

trait MatcherResultTest
  extends Suite {
  def checkResult(matchResult: MatchResult,
                  expectedFailureMsgRaw: String): Unit = {
    val expectedFailureMsg = expectedFailureMsgRaw.stripMargin
    val shouldMatch = expectedFailureMsg.isEmpty

    val actualFailureMsg =
      if (matchResult.matches)
        ""
      else
        matchResult.failureMessage

      actualFailureMsg should be(expectedFailureMsg)
  }
} 
开发者ID:hammerlab,项目名称:test-utils,代码行数:22,代码来源:MatcherResultTest.scala

示例13: AsmTestHelper

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

import org.scalatest.matchers.{BeMatcher, MatchResult}
import org.scalatest.words.MatcherWords._
import System.{lineSeparator => n}

import scala.collection.mutable

object AsmTestHelper {
  private def createLabelMappings(code: String): Map[String, Int] = {
    val result = mutable.Map[String, Int]()
    var lastLabelIdx = 0
    "(?m)^.([LT]\\d+)".r.findAllMatchIn(code).foreach { match_ =>
      assert(!result.contains(match_.group(1)))
      result(match_.group(1)) = lastLabelIdx
      lastLabelIdx += 1
    }
    result.toMap
  }

  private def createRegisterMappings(code: String): Map[String, Int] = {
    val result = mutable.Map[String, Int]()
    var lastRegIdx = 0
    "%REG(\\d+)".r.findAllMatchIn(code).foreach { match_ =>
      if (!result.contains(match_.group(1))) {
        result(match_.group(1)) = lastRegIdx
        lastRegIdx += 1
      }
    }
    result.toMap
  }

  private def stripComments: String => String = "\\s*#.*".r.replaceAllIn(_, "")

  private def normalize(code: String): String = {
    val withoutDirectives = "\r?\n?\t(.p2align 4,,15|.globl [a-zA-Z0-9_]+)".r.replaceAllIn(code, "")

    val labelMappings = createLabelMappings(code)
    val normalizedLabels = ".(([LT])\\d+)".r.replaceAllIn(withoutDirectives, match_ => s".${match_.group(2)}${labelMappings(match_.group(1))}")

    val registerMappings = createRegisterMappings(code)
    "%REG(\\d+)".r.replaceAllIn(normalizedLabels, match_ => "%REG" + registerMappings(match_.group(1)))
  }

  def isIsomorphic(left: String, right: String): MatchResult =
    BeMatcher(be(normalize(stripComments(right)))).apply(normalize(stripComments(left)))
} 
开发者ID:jspam,项目名称:mjis,代码行数:48,代码来源:AsmTestHelper.scala

示例14: 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

示例15: 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


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