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

Scala Matchers类代码示例

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

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



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

示例1: Demo2Spec

//设置package包名称以及导入依赖的类
package org.scalatest.examples

// Type-constructor polymorphism

import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.examples.Demo._
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FunSpec, Matchers}

// DEMO 2 - use assume with an ensuring that compares with math.sqrt
class Demo2Spec extends FunSpec with Matchers with PropertyChecks with TypeCheckedTripleEquals {

  describe("The squareRootB function") {
    it("should compute the square root") {
      forAll { (x: Double) =>
        whenever (x >= 0.0 && !x.isPosInfinity) {
          noException should be thrownBy { squareRootB(x) }
        }
      }
    }
    it("should should throw IAE on negative input") {
      an [AssertionError] should be thrownBy {
        squareRootB(-1.0)
      }
    }
    it("should should throw IAE on positive infinity input") {
      an [AssertionError] should be thrownBy {
        squareRootB(Double.PositiveInfinity)
      }
    }
  }
} 
开发者ID:bvenners,项目名称:scalaX2016Demos,代码行数:33,代码来源:Demo2Spec.scala


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


示例3: RedirectionSpec

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

import com.kurz.services.RedisConnectionPool
import com.twitter.finagle.http.Status
import io.finch.Input
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}

class RedirectionSpec extends FunSpec with Matchers with BeforeAndAfter {
  import com.kurz.Server.redirection

  before {
    RedisConnectionPool.instance.getResource().del("mb")
    RedisConnectionPool.instance.getResource().set("mb", "http://marceloboeira.com")
  }

  describe ("redirection") {
    describe("when the slug exists") {
      it("returns with the temporary redirection status") {
        redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.TemporaryRedirect)
      }

      it("returns with the proper header for Location") {
        redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.headers) shouldBe Some(Map("Location" -> "http://marceloboeira.com"))
      }
    }

    describe("when the slug does not exist") {
      it("returns with the not found status") {
        redirection(Input.get("/invalid")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.NotFound)
      }
    }
  }
} 
开发者ID:marceloboeira,项目名称:kurz,代码行数:34,代码来源:RedirectionSpec.scala


示例4: ApiSpec

//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.registry

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestProbe
import ch.qos.logback.classic.{Level, Logger}
import org.flywaydb.core.Flyway
import org.scalatest.Matchers
import org.scalatest.fixture.FunSpec
import org.slf4j.LoggerFactory

import scala.concurrent.duration._
import scalikejdbc._

abstract class ApiSpec extends FunSpec with ScalatestRouteTest with Matchers with Protocols with SprayJsonSupport {
  case class FixtureParam(api: Api, webHookActorProbe: TestProbe)

  val databaseUrl = Option(System.getenv("npm_package_config_databaseUrl")).getOrElse("jdbc:postgresql://localhost:5432/postgres")

  // Stop Flyway from producing so much spam that Travis terminates the process.
  LoggerFactory.getLogger("org.flywaydb").asInstanceOf[Logger].setLevel(Level.WARN)

  val flyway = new Flyway()
  flyway.setDataSource(databaseUrl, "postgres", "")
  flyway.setSchemas("test")
  flyway.setLocations("classpath:/sql")

  override def testConfigSource =
    s"""
      |db.default.url = "${databaseUrl}?currentSchema=test"
      |authorization.skip = true
      |akka.loglevel = INFO
    """.stripMargin

  override def withFixture(test: OneArgTest) = {
    val webHookActorProbe = TestProbe()
    val api = new Api(webHookActorProbe.ref, testConfig, system, executor, materializer)

    webHookActorProbe.expectMsg(1 millis, WebHookActor.Process)

    DB localTx { implicit session =>
      sql"DROP SCHEMA IF EXISTS test CASCADE".update.apply()
      sql"CREATE SCHEMA test".update.apply()
    }

    flyway.migrate()

    super.withFixture(test.toNoArgTest(FixtureParam(api, webHookActorProbe)))
  }
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:51,代码来源:ApiSpec.scala


示例5: Demo11Spec

//设置package包名称以及导入依赖的类
package org.scalatest.examples

// Type-constructor polymorphism

import org.scalactic.TypeCheckedTripleEquals
import org.scalactic.anyvals.PosZDouble
import org.scalatest.examples.Demo._
import org.scalatest.prop.PropertyChecks
import org.scalatest.{LogicFunSpec, Matchers}

// (Demo 10 - PosInt in the REPL)

// DEMO 11 - Use PosZInt to weaken the require?
// Only input is changed to PosZDouble so far.
class Demo11Spec extends LogicFunSpec with Matchers with PropertyChecks with TypeCheckedTripleEquals {

  describe("The squareRoot1 function") {
    it("should compute the square root") {
      forAll { (x: PosZDouble) =>
        whenever (!x.isPosInfinity) {
          squareRoot2(x) should === (math.sqrt(x))
        }
      }
    }
    it("should should throw IAE on negative input") {
      an [IllegalArgumentException] should be thrownBy {
        squareRoot1(-1.0)
      }
    }
    it("should should throw IAE on positive infinity input") {
      an [IllegalArgumentException] should be thrownBy {
        squareRoot1(Double.PositiveInfinity)
      }
    }
  }
} 
开发者ID:bvenners,项目名称:scalaX2016Demos,代码行数:37,代码来源:Demo11Spec.scala


示例6: ChunkifyAndBuildTest

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

import java.io.File

import communication.FileManifest
import index.FileIndex
import org.scalatest.{FlatSpec, Matchers}


class ChunkifyAndBuildTest extends FlatSpec with Matchers {
  implicit val homeDirPath = "/home/mike/Programming/scala/"

  "Chunkifier and FileBuilder" should "chunkify and rebuild file properly" in {
    val originalFile = new File("src/test/resources/chunkifierTest")
    val chunksList: List[Chunk] = Chunkifier(100, originalFile)
    val fileManifest = FileManifest(new FileIndex(originalFile), 100)
    val fileBuilder = new FileBuilder(fileManifest)
    chunksList.foreach(chunk => fileBuilder.accept(chunk))
    fileBuilder.build()
    val newChunksList: List[Chunk] = Chunkifier(100, originalFile)

    chunksList.indices.foreach { i => chunksList(i).content should equal(newChunksList(i).content) }
  }
} 
开发者ID:mprzewie,项目名称:cloudia-utils,代码行数:25,代码来源:ChunkifyAndBuildTest.scala


示例7: CellSpec

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

import breeze.linalg.{DenseVector => BDV, HashVector => BHV, SparseVector => BSV}
import org.apache.spark.mllib.linalg.{Vector => OldVector, Vectors => OldVectors}
import org.scalatest.{FlatSpec, Matchers}

class CellSpec extends FlatSpec with Matchers {

  it should "check index calculation" in {

    val arr = Seq(
      Cell(10, 20),
      Cell(11, 21),
      Cell(12, 22),
      Cell(10, 22),
      Cell(12, 20)
    )

    val qrMin = arr.min
    val qrMax = arr.max
    val qrDel = (qrMax - qrMin) + 1
    val size = qrDel size

    size shouldBe 9

    Cell(10, 20) toIndex(qrMin, qrDel) shouldBe 0
    Cell(12, 20) toIndex(qrMin, qrDel) shouldBe 2
    Cell(10, 22) toIndex(qrMin, qrDel) shouldBe 6
    Cell(12, 22) toIndex(qrMin, qrDel) shouldBe 8

    0 toCell(qrMin, qrDel) shouldBe Cell(10, 20)
    2 toCell(qrMin, qrDel) shouldBe Cell(12, 20)
    6 toCell(qrMin, qrDel) shouldBe Cell(10, 22)
    8 toCell(qrMin, qrDel) shouldBe Cell(12, 22)
  }
} 
开发者ID:mraad,项目名称:spark-som-path,代码行数:37,代码来源:CellSpec.scala


示例8: SnapshotGenerationSpec

//设置package包名称以及导入依赖的类
package com.commodityvectors.snapshotmatchers

import java.io.File

import org.apache.commons.io.FileUtils
import org.scalatest.{BeforeAndAfterEach, Matchers, fixture}

import scala.util.Try

class SnapshotGenerationSpec extends fixture.WordSpec with Matchers with SnapshotMatcher with BeforeAndAfterEach {

  val snapshotFolder: String = "scalatest-snapshot-matcher-core/src/test/__snapshots__"
  val currentSpecPath: String = s"$snapshotFolder/com/commodityvectors/snapshotmatchers/SnapshotGenerationSpec"

  override def afterEach(): Unit = {
    Try(FileUtils.deleteDirectory(new File(snapshotFolder)))
  }

  "SnapshotMatcher" should {
    "generate snapshot file with expectation" in { implicit test =>
      val value: Int = 1
      value should matchSnapshot[Int]()
      FileUtils.readFileToString(
        new File(s"$currentSpecPath/snapshotmatcher-should-generate-snapshot-file-with-expectation.snap")
      ) shouldEqual "1"
    }

    "generate file with custom id" in { implicit test =>
      val value = 10
      value should matchSnapshot[Int]("customId")
      FileUtils.readFileToString(
        new File(s"$currentSpecPath/customId.snap")
      ) shouldEqual "10"
    }
  }
} 
开发者ID:commodityvectors,项目名称:scalatest-snapshot-matchers,代码行数:37,代码来源:SnapshotGenerationSpec.scala


示例9: SOMSpec

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

import breeze.linalg.DenseVector
import org.scalatest.{FlatSpec, Matchers}

class SOMSpec extends FlatSpec with Matchers {
  it should "train the SOM" in {
    val nodes = for (q <- 0 until 10) yield {
      Node(q, 0, new DenseVector[Double](Array(q, 0.0)))
    }
    nodes.length shouldBe 10
    val som = SOM(nodes)
    som.train(new DenseVector[Double](Array(5.0, 0.0)), 1.0, 0.1)
  }
} 
开发者ID:mraad,项目名称:spark-som-path,代码行数:16,代码来源:SOMSpec.scala


示例10: AX25FrameSpec

//设置package包名称以及导入依赖的类
package com.softwaremill.modemconnector.ax25

import com.softwaremill.modemconnector.FrameUtils
import org.scalatest.{BeforeAndAfter, FlatSpec, Matchers}

class AX25FrameSpec extends FlatSpec with Matchers with BeforeAndAfter {

  "A simple AX25Frame" should "contain decoded data" in {
    val ax25frame: AX25Frame = FrameUtils.ax25frameFromFile("/andrej.bin")
    new String(ax25frame.body) should equal("=4603.63N/01431.26E-Op. Andrej")
  }

  "A simple AX25Frame" should "contain sender callsign" in {
    val ax25frame: AX25Frame = FrameUtils.ax25frameFromFile("/andrej.bin")
    ax25frame.sender.callsign should equal("S57LN")
  }

  "A simple AX25Frame" should "contain destination callsign" in {
    val ax25frame: AX25Frame = FrameUtils.ax25frameFromFile("/andrej.bin")
    ax25frame.dest.callsign should equal("APRS")
  }

  "A simple AX25Frame" should "encode byte array" in {
    val ax25frame = AX25Frame(FrameUtils.ax25frameFromFile("/andrej.bin").toBytes)
    new String(ax25frame.body) should equal("=4603.63N/01431.26E-Op. Andrej")
    ax25frame.dest.callsign should equal("APRS")
    ax25frame.sender.callsign should equal("S57LN")
  }

  "An AX25Frame with digipiters" should "contain decoded data" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    new String(ax25frame.body) should equal("`'4< \\4>/]\"3k}145.500MHz qrv her=\r")
  }

  "An AX25Frame with digipiters" should "contain sender callsign" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    ax25frame.sender.toString should equal("OZ1IEP-9")
  }

  "An AX25Frame with digipiters" should "contain destination callsign" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    ax25frame.dest.toString should equal("U4TQ33")
  }

  "An AX25Frame with digipiters" should "contain digipiters" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    ax25frame.digipeaters.map(_.toString).toSeq should contain theSameElementsInOrderAs List("OZ6DIA-2", "OZ4DIA-2", "OZ4DIE-2")
  }

  "An AX25Frame with digipiters" should "encode byte array" in {
    val ax25frame = AX25Frame(FrameUtils.ax25frameFromFile("/complexFrame.bin").toBytes)
    ax25frame.digipeaters.map(_.toString).toSeq should contain theSameElementsInOrderAs List("OZ6DIA-2", "OZ4DIA-2", "OZ4DIE-2")
    ax25frame.dest.toString should equal("U4TQ33")
    ax25frame.sender.toString should equal("OZ1IEP-9")
    new String(ax25frame.body) should equal("`'4< \\4>/]\"3k}145.500MHz qrv her=\r")
  }

} 
开发者ID:softwaremill,项目名称:modem-connector,代码行数:59,代码来源:AX25FrameSpec.scala


示例11: LayoutSpec

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

import org.scalatest.{FlatSpec, Matchers}

class LayoutSpec extends FlatSpec with Matchers {

  it should "hexToPixel pixelToHex" in {
    val layout = Layout(10, 20, 100, 100, Orientation.TOP_FLAT)
    val (px, py) = layout.hexToXY(Hex(10, 20))
    val hex = layout.xyToHex(px, py).toHex
    hex.q shouldBe 10
    hex.r shouldBe 20
    hex.s shouldBe -30
  }

  it should "work on web coordinates" in {
    implicit val layout = Layout(0.0, 0.0, 1000, 1000, Orientation.TOP_FLAT)

  }

  it should "work on geo coordinates" in {
    implicit val layout = Layout(0.0, 0.0, 1, 1, Orientation.TOP_FLAT)

    Seq(
      (-180.0, -90.0),
      (-90.0, -45.0),
      (0.0, 0.0),
      (90.0, 45.0),
      (180.0, 90.0)
    )
      .foreach {
        case (lon, lat) => {
          val hex = Hex.fromXY(lon, lat)
          val (x, y) = hex.toXY()
          x shouldBe lon +- 0.1
          y shouldBe lat +- 0.1
        }
      }
  }
} 
开发者ID:mraad,项目名称:grid-hex,代码行数:41,代码来源:LayoutSpec.scala


示例12: HexSpec

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

import org.scalatest.{FlatSpec, Matchers}

class HexSpec extends FlatSpec with Matchers {

  it should "add" in {
    val h1 = Hex(10, 20, 30)
    val h2 = Hex(11, 22, 33)
    h1 + h2 shouldBe Hex(21, 42, 63)
  }

  it should "sub" in {
    val h1 = Hex(21, 42, 63)
    val h2 = Hex(11, 22, 33)
    h1 - h2 shouldBe Hex(10, 20, 30)
  }

  it should "calc length" in {
    val h1 = Hex(10, -20, 33)
    h1.length shouldBe (10 + 20 + 33) / 2
  }

  it should "range 0" in {
    val h = Hex(10, 20)
    (h range 0).head shouldBe Hex(10, 20)
  }

  it should "range 1" in {
    val h = Hex(10, 20)
    val range = h range 1
    range should contain(h)
    range should contain(h neighbor 0)
    range should contain(h neighbor 1)
    range should contain(h neighbor 2)
    range should contain(h neighbor 3)
    range should contain(h neighbor 4)
    range should contain(h neighbor 5)
  }

  it should "range 2" in {
    val h = Hex(10, 20)
    val range = h range 2
    range.length shouldBe 19
  }
} 
开发者ID:mraad,项目名称:grid-hex,代码行数:47,代码来源:HexSpec.scala


示例13: SClientIntegrationSpec

//设置package包名称以及导入依赖的类
import org.scalatest._
import org.scalatest.{FunSpecLike, Matchers}
import scala.concurrent._
import scala.concurrent.duration._
import com.akkademy.SClient
import com.akkademy.messages.KeyNotFoundException


class SClientIntegrationSpec extends FunSpecLike with Matchers {

    var client = new SClient("127.0.0.1:2552")

    describe("akkademyDb Scala Client") {
        describe("set method") {
            it("should set a value") {
                client.set("123", new Integer(123))
                val futureResult = client.get("123")
                val result = Await.result(futureResult, 10 seconds)
                result should equal(123)
            }
        }

        describe("setIfNotExists method") {
            it("should not set a value if it already exists") {
                client.setIfNotExists("key", new Integer(123))
                client.setIfNotExists("key", new Integer(555))
                val futureResult = client.get("key")
                val result = Await.result(futureResult, 10 seconds)
                result should equal(123)
            }

            it("should set a value if not exists") {
                //trick untill the server is mocked
                client.setIfNotExists("newKey", new Integer(555))
                val futureResult = client.get("newKey")
                val result = Await.result(futureResult, 10 seconds)
                result should equal(555)
            }
        }

        describe("delete method") {
            it("should delete a key if it exists") {
                client.set("123", new Integer(123))
                val futureResult = client.delete("123")
                val result = Await.result(futureResult, 10 seconds)
                result should equal("123")
            }

            it("should fail with KeyNotFoundException when deleting a key that does not exist") {
                val futureResult = client.delete("unknown")
                val thrown = intercept[KeyNotFoundException] {
                    Await.result(futureResult, 10 seconds)
                }
                thrown.key should equal("unknown")
            }
        }
    }
} 
开发者ID:miguelsaddress,项目名称:akkademy-db-client,代码行数:59,代码来源:SClientIntegrationSpec.scala


示例14: MetricNumericConverterSpec

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

import org.scalatest.WordSpec
import org.scalatest.Matchers
import akka.cluster.StandardMetrics._
import scala.util.Failure

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class MetricNumericConverterSpec extends WordSpec with Matchers with MetricNumericConverter {

  "MetricNumericConverter" must {

    "convert" in {
      convertNumber(0).isLeft should be(true)
      convertNumber(1).left.get should be(1)
      convertNumber(1L).isLeft should be(true)
      convertNumber(0.0).isRight should be(true)
    }

    "define a new metric" in {
      val Some(metric) = Metric.create(HeapMemoryUsed, 256L, decayFactor = Some(0.18))
      metric.name should be(HeapMemoryUsed)
      metric.value should be(256L)
      metric.isSmooth should be(true)
      metric.smoothValue should be(256.0 +- 0.0001)
    }

    "define an undefined value with a None " in {
      Metric.create("x", -1, None).isDefined should be(false)
      Metric.create("x", java.lang.Double.NaN, None).isDefined should be(false)
      Metric.create("x", Failure(new RuntimeException), None).isDefined should be(false)
    }

    "recognize whether a metric value is defined" in {
      defined(0) should be(true)
      defined(0.0) should be(true)
    }

    "recognize whether a metric value is not defined" in {
      defined(-1) should be(false)
      defined(-1.0) should be(false)
      defined(Double.NaN) should be(false)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:46,代码来源:MetricNumericConverterSpec.scala


示例15: MySpec

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

//#plain-spec
import akka.actor.ActorSystem
import akka.actor.Actor
import akka.actor.Props
import akka.testkit.{ TestActors, TestKit, ImplicitSender }
import org.scalatest.WordSpecLike
import org.scalatest.Matchers
import org.scalatest.BeforeAndAfterAll

//#implicit-sender
class MySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {
  //#implicit-sender

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "An Echo actor" must {

    "send back messages unchanged" in {
      val echo = system.actorOf(TestActors.echoActorProps)
      echo ! "hello world"
      expectMsg("hello world")
    }

  }
}
//#plain-spec 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:34,代码来源:PlainWordSpec.scala


示例16: ActorEndpointPathTest

//设置package包名称以及导入依赖的类
package akka.camel.internal.component

import org.scalatest.mock.MockitoSugar
import org.scalatest.Matchers
import akka.camel.TestSupport.SharedCamelSystem
import org.scalatest.WordSpec
import akka.actor.{ Actor, Props }

class ActorEndpointPathTest extends WordSpec with SharedCamelSystem with Matchers with MockitoSugar {

  def find(path: String) = ActorEndpointPath.fromCamelPath(path).findActorIn(system)

  "findActorIn returns Some(actor ref) if actor exists" in {
    val path = system.actorOf(Props(new Actor { def receive = { case _ ? } }), "knownactor").path
    find(path.toString) should be('defined)
  }

  "findActorIn returns None" when {
    "non existing valid path" in { find("akka://system/user/unknownactor") should be(None) }
  }
  "fromCamelPath throws IllegalArgumentException" when {
    "invalid path" in {
      intercept[IllegalArgumentException] {
        find("invalidpath")
      }
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:29,代码来源:ActorEndpointPathTest.scala


示例17: CamelMessageTest

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

import org.apache.camel.impl.{ DefaultExchange, DefaultMessage }
import akka.camel.TestSupport.SharedCamelSystem
import org.scalatest.Matchers
import org.scalatest.WordSpecLike

//TODO merge it with MessageScalaTest
class CamelMessageTest extends Matchers with WordSpecLike with SharedCamelSystem {

  "CamelMessage" must {

    "overwrite body and add header" in {
      val msg = sampleMessage
      CamelMessage.copyContent(CamelMessage("blah", Map("key" -> "baz")), msg)
      assert(msg.getBody === "blah")
      assert(msg.getHeader("foo") === "bar")
      assert(msg.getHeader("key") === "baz")
    }
  }

  private[camel] def sampleMessage = {
    val message = new DefaultMessage
    message.setBody("test")
    message.setHeader("foo", "bar")
    message.setExchange(new DefaultExchange(camel.context))
    message
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:30,代码来源:CamelMessageTest.scala


示例18: SplunkHecClientTest

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

import ch.qos.logback.classic.Level
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.LayoutBase
import io.policarp.logback.MockLoggingEvent
import org.scalatest.{ Matchers, WordSpec }

class SplunkHecClientTest extends WordSpec with Matchers {

  val layout = new LayoutBase[ILoggingEvent] {
    override def doLayout(event: ILoggingEvent): String = event.getMessage
  }

  "The Object" should {
    "prepare layouts in a line separated format" in {

      import SplunkHecClient.formatJsonEvents

      formatJsonEvents(Seq(), layout) shouldBe None

      val event1 = MockLoggingEvent("SomeClass", "test 1", Level.DEBUG)
      val event2 = MockLoggingEvent("SomeClass", "test 2", Level.DEBUG)
      formatJsonEvents(Seq(event1, event2), layout) shouldBe Some("test 1\n\ntest 2")
      formatJsonEvents(Seq(event1), layout) shouldBe Some("test 1")
      formatJsonEvents(Seq(event2), layout) shouldBe Some("test 2")
    }
  }

} 
开发者ID:kdrakon,项目名称:splunk-logback-hec-appender,代码行数:31,代码来源:SplunkHecClientTest.scala


示例19: SimpleKafkaProducerTest

//设置package包名称以及导入依赖的类
package com.example
import java.nio.charset.StandardCharsets

import kafka.consumer.ConsumerConfig
import kafka.utils.TestUtils
import org.scalatest.{FunSpec, Matchers}
//import org.junit.Assert._
import scala.collection.immutable.HashMap

class SimpleKafkaProducerTest extends FunSpec with Matchers{

  private val topic = "test"
  private val groupId = "group0"
  private val kafkaHelpers = new KafkaHelpers()


  case class MessageData(a: String, b: String)

  describe("The SimpleKafka Api") {
    it("Should send data using a producer") {
      //Send data to Kafka
      val kafkaApi = new SimpleKafkaProducer(kafkaHelpers.kafkaSocket(), topic)
      kafkaApi.send[MessageData](new MessageData("Hello", "World"))

      //Create consumer
      val consumerProperties = TestUtils.createConsumerProperties(kafkaHelpers.zookeeperSocket().toString(), groupId, "consumer0", -1)
      val consumer = kafka.consumer.Consumer.create(new ConsumerConfig(consumerProperties))

      val topicCountMap = HashMap(topic -> 1)
      val consumerMap = consumer.createMessageStreams(topicCountMap)
      val stream = consumerMap.get(topic).get(0)
      val iterator = stream.iterator()
      val msg = new String(iterator.next().message(), StandardCharsets.UTF_8)

      assert("{\"a\":\"Hello\",\"b\":\"World\"}" == msg)

      // cleanup
      consumer.shutdown()
    }
  }
} 
开发者ID:frossi85,项目名称:financial-statistics-crawler,代码行数:42,代码来源:SimpleKafkaProducerTest.scala


示例20: HelloEntitySpec

//设置package包名称以及导入依赖的类
package sample.helloworld.impl

import akka.Done
import akka.actor.ActorSystem
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.lightbend.lagom.scaladsl.testkit.PersistentEntityTestDriver
import org.scalactic.ConversionCheckedTripleEquals
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.concurrent.Await
import scala.concurrent.duration._


class HelloEntitySpec extends WordSpecLike with Matchers with BeforeAndAfterAll
  with ConversionCheckedTripleEquals {
  val system = ActorSystem("HelloEntitySpec", JsonSerializerRegistry.actorSystemSetupFor(HelloSerializerRegistry))

  override def afterAll(): Unit = {
    Await.ready(system.terminate, 10 seconds)
  }

  "Hello Entity " must {

    "handle UseGreeting Message and fire an event" in {
      val driver = new PersistentEntityTestDriver(system, new HelloEntity, "Hello Entity-1")
      val newMessage = "Welcome Back!!"
      val outcome = driver.run(UseGreetingMessage(newMessage))
      assert(outcome.events.toList === List(GreetingMessageChanged(newMessage)))
      assert(outcome.replies.toList === List(Done))
      assert(outcome.issues === Nil)
    }

    "handle hello Message and return a reply" in {
      val driver = new PersistentEntityTestDriver(system, new HelloEntity, "Hello Entity-2")
      val id = "Alice"
      val outcome = driver.run(Hello(id,None))


      assert(outcome.events.toList === List())
      assert(outcome.replies.toList === List("Hello, Alice!"))
      assert(outcome.issues === Nil)
    }
  }
} 
开发者ID:knoldus,项目名称:lagom-scala-wordcount.g8,代码行数:45,代码来源:HelloEntitySpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala File类代码示例发布时间:2022-05-23
下一篇:
Scala Try类代码示例发布时间: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