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


Scala when类代码示例

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


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

示例1: RefcountedServiceTest

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

import com.twitter.util._
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito.{times, verify, when}
import org.mockito.{Matchers, Mockito}
import org.mockito.Matchers._
import com.twitter.finagle.Service

@RunWith(classOf[JUnitRunner])
class RefcountedServiceTest extends FunSuite with MockitoSugar {

  class PoolServiceWrapperHelper {
    val service = mock[Service[Any, Any]]
    when(service.close(any)) thenReturn Future.Done
    val promise = new Promise[Any]
    when(service(Matchers.any)) thenReturn promise
    val wrapper = Mockito.spy(new RefcountedService[Any, Any](service))
  }

  test("PoolServiceWrapper should call release() immediately when no requests have been made") {
    val h = new PoolServiceWrapperHelper
    import h._

    verify(service, times(0)).close(any)
    wrapper.close()
    verify(service).close(any)
  }

  test("PoolServiceWrapper should call release() after pending request finishes") {
    val h = new PoolServiceWrapperHelper
    import h._

    val f = wrapper(123)
    assert(!f.isDefined)
    verify(service)(123)

    wrapper.close()
    verify(service, times(0)).close(any)

    promise() = Return(123)
    verify(service).close(any)
    assert(f.isDefined)
    assert(Await.result(f) == 123)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:50,代码来源:RefcountedServiceTest.scala

示例2: createTiledImage

//设置package包名称以及导入依赖的类
package net.xylophones.frogger.test

import net.xylophones.frogger._
import org.mockito.Mockito.when
import org.scalajs.dom.raw.HTMLImageElement
import org.scalatest.mockito.MockitoSugar

trait FroggerTestSugar extends MockitoSugar {

  def createTiledImage(width: Int, height: Int): TiledImage = {
    val htmlImage = mock[HTMLImageElement]
    val image = new Image(htmlImage)
    when(htmlImage.width).thenReturn(20)
    when(htmlImage.height).thenReturn(10)

    new TiledImage(image, width, height)
  }

  def createSprite(width: Int, height: Int): Sprite = {
    val spriteImage = mock[Image]
    when(spriteImage.width).thenReturn(5)
    when(spriteImage.height).thenReturn(5)

    new Sprite(spriteImage, 5)
  }

  def createModel(channel: Channel, channelPosition: Vector): Model = {
    val layers = Layers(
      scoreTitle = mock[ScoreTitleLayer],
      scoreLayer = mock[ScoreLayer],
      scoreSpace = mock[BackgroundLayer],
      homePlaceholder = mock[BackgroundLayer],
      frog = mock[Sprite],
      statusLayer = mock[StatusLayer],
      timeLayer = mock[TimeLayer],
      channels = Seq(channel),
      homes = Seq(),
      frogLayer = mock[FrogLayer]
    )

    val pos = layers.all.map(_ => channelPosition)

    Model(layers=layers, positions = pos)
  }
} 
开发者ID:wjsrobertson,项目名称:scalajs-frogger,代码行数:46,代码来源:FroggerTestSugar.scala

示例3: UserRepositorySpec

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

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestKit}
import akka.util.Timeout
import com.github.t3hnar.bcrypt._
import org.cristal.model.{NewUser, User}
import org.cristal.repository.UserRepository.UserCreated
import org.cristal.repository.dao.UserDAO
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito.when
import org.scalatest.concurrent.Eventually
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.concurrent.Future
import scala.concurrent.duration._

class UserRepositorySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll with Eventually with MockitoSugar {
  implicit val duration: Timeout = 10 seconds
  def this() = this(ActorSystem("UserRepositorySpecSystem"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "An UserRepository Actor" should {
    "Create a new user" in {
      val userDAO = mock[UserDAO]
      val passowod = "my_password"
      val encryptedPassword = passowod.bcrypt
      when(userDAO.insert(any())).thenReturn(Future.successful(()))
      val userRepository = system.actorOf(UserRepository.props(userDAO))
      val newUser = NewUser("name", passowod, "[email protected]", "John", "Doe")
      userRepository ! UserRepository.CreateUser(newUser, self)
      expectMsgPF() {
        case UserCreated(User("name", encryptedPassword, "[email protected]", "John", "Doe")) => ()
      }
    }
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:43,代码来源:UserRepositorySpec.scala

示例4: NetworkTest

//设置package包名称以及导入依赖的类
package se.andrisak.backprop.algo

import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}

import scala.util.Random


class NetworkTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
  val RANDOM_VALUE = 0.2
  val INPUT_LAYER_NEURON_COUNT = 1
  val HIDDEN_LAYER_NEURON_COUNT = 1
  val INPUT = 0.528593

  val random = mock[Random]
  when(random.nextDouble()).thenReturn(RANDOM_VALUE)

  test("test that clearInput clears all node input") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
    network.getInputLayer.neurons.head.addInput(0.534543)
    network.getHiddenLayer.neurons.head.addInput(0.6854543)
    network.clearInputs()

    network.getInputLayer.neurons.head.getInput should equal(0.0)
    network.getHiddenLayer.neurons.head.getInput should equal(0.0)
  }

  test("init of input layer should add the input to input neurons") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
    network.initInputLayer(List(INPUT))

    network.getInputLayer.neurons.head.getInput should equal(INPUT)
  }

  test("adding more input values than input neurons should throw an exception") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)

    intercept[IllegalArgumentException] {
      network.initInputLayer(List(INPUT, INPUT))
    }
  }
} 
开发者ID:andrisak,项目名称:backprop,代码行数:44,代码来源:NetworkTest.scala

示例5: NeuronTest

//设置package包名称以及导入依赖的类
package se.andrisak.backprop.algo

import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}

import scala.util.Random


class NeuronTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
  val NEURON_NAME = "neuron"
  val NEURON_NAME2 = "neuron2"
  val RANDOM_VALUE = 0.53
  val random = mock[Random]
  when(random.nextDouble()).thenReturn(RANDOM_VALUE)
  val neuron = new Neuron(NEURON_NAME, random)

  test("input should be stored and be cleared") {
    val input = 0.543
    neuron.addInput(input)

    neuron.getInput should equal (input)
    neuron.clearInput()
    neuron.getInput should equal (0)
  }

  test("neurons should be connected with a ForwardLink") {
    val neuron2 = new Neuron(NEURON_NAME2, random)

    neuron.connectToNeuronsInLayer(List(neuron2))

    val link = neuron.getLinkTo(neuron2)
    link.to should equal(neuron2)
    link.weight should equal(RANDOM_VALUE)
    link should equal(neuron.getNextLayerLinks.head)
  }

  test("neurons should be connected with a ReverseLink") {
    val neuron2 = new Neuron(NEURON_NAME2, random)

    neuron.connectToNeuronsInPreviousLayer(List(neuron2))

    neuron.getPreviousLayerNeurons.head should equal(neuron2)
  }

  test("test the sigmoid computation") {
    neuron.output should equal(0.5)
  }

} 
开发者ID:andrisak,项目名称:backprop,代码行数:51,代码来源:NeuronTest.scala

示例6: DatabaseReaderActivitySpec

//设置package包名称以及导入依赖的类
package test.yumi.pipeline.activities

import java.util.Properties

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions
import org.mockito.Mockito.{verify, when}
import test.yumi.pipeline.MockSessionSpec
import yumi.YumiMap
import yumi.pipeline.activities.DatabaseReaderActivity

class DatabaseReaderActivitySpec extends MockSessionSpec {

  it should "load sql server table as spark view" in new MockSessionScope {

    // Arrange
    val url = "url"
    val table = "table_name"
    val as = "as"
    val driver = "com.mysql.Driver"
    val properties = Map("batchSize" -> "2000")
    val expectedProperties = new Properties()
    properties.foreach {
      case (key, value) =>
        expectedProperties.setProperty(key, value)
    }
    expectedProperties.put(JDBCOptions.JDBC_DRIVER_CLASS, driver)

    val parameters = createParameters()
      .add("url", url)
      .add("table", table)
      .add("driver", driver)
      .add("as", as)
      .add("properties", properties)
      .build()
    val sessionData = YumiMap()
    val dataFrame = mock[DataFrame]

    when(dataFrameReader.jdbc(any[String], any[String], any[Properties])).thenReturn(dataFrame)

    // Act
    val activity = new DatabaseReaderActivity(parameters)
    val resultSessionData = activity.invoke(sessionData)

    // Assert
    verify(sparkSession).read
    verify(dataFrameReader)
      .jdbc(url, table, expectedProperties)
    verify(dataFrame).createTempView(as)

    resultSessionData === sessionData
  }
} 
开发者ID:coderdiaries,项目名称:yumi,代码行数:54,代码来源:DatabaseReaderActivitySpec.scala

示例7: DatabaseWriterActivitySpec

//设置package包名称以及导入依赖的类
package test.yumi.pipeline.activities

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions
import org.mockito.Mockito.{verify, when}
import test.yumi.pipeline.MockSessionSpec
import yumi.YumiMap
import yumi.pipeline.activities.DatabaseWriterActivity

class DatabaseWriterActivitySpec extends MockSessionSpec {

  it should "write to database table from spark view" in new MockSessionScope {

    // Arrange
    val url = "jdbc:postgresql://yumi.rds.amazonaws.com:5432/yumi_postgresql?user=yumi&password=somepassword"
    val table = "table_name"
    val as = "as"
    val mode = "append"
    val jdbcDriverClass = "org.postgresql.Driver"
    val properties = Map("batchSize" -> "2000")

    val completeOptions: Map[String, String] = properties +
      (JDBCOptions.JDBC_TABLE_NAME -> as) +
      (JDBCOptions.JDBC_DRIVER_CLASS -> jdbcDriverClass) +
      ("url" -> url)

    val parameters = createParameters()
      .add("url", url)
      .add("table", table)
      .add("as", as)
      .add("properties", properties)
      .add("mode", mode)
      .add("driver", jdbcDriverClass)
      .build()
    val sessionData = YumiMap()
    val dataFrame = mock[DataFrame]

    when(sparkSession.table(table)).thenReturn(dataFrame)

    // Act
    val activity = new DatabaseWriterActivity(parameters)
    val resultSessionData = activity.invoke(sessionData)

    // Assert
    verify(dataFrameWriter).write(dataFrame, "jdbc:postgresql", mode, url, completeOptions)

    resultSessionData === sessionData
  }
} 
开发者ID:coderdiaries,项目名称:yumi,代码行数:50,代码来源:DatabaseWriterActivitySpec.scala

示例8: ExceptionSourceFilterTest

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

import com.twitter.finagle.{Service, SourcedException, Failure}
import com.twitter.util.{Await, Future}

import org.junit.runner.RunWith

import org.mockito.Matchers.anyInt
import org.mockito.Mockito.when
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class ExceptionSourceFilterTest extends FunSuite with MockitoSugar {
  test("ExceptionSourceFilter should add a name to sourced exceptions") {
    val service = mock[Service[Int, Int]]
    val e = new SourcedException{}
    when(service(anyInt)).thenReturn(Future.exception(e))
    val composed = new ExceptionSourceFilter("name") andThen service
    val actual = intercept[SourcedException] {
      Await.result(composed(0))
    }
    assert(actual.serviceName == "name")
  }

  test("ExceptionSourceFilter should add a name to failures") {
    val service = mock[Service[Int, Int]]
    val e = new Failure("everything sucks")
    when(service(anyInt)).thenReturn(Future.exception(e))
    val composed = new ExceptionSourceFilter("name") andThen service
    val actual = intercept[Failure] {
      Await.result(composed(0))
    }
    assert(actual.getSource(Failure.Source.Service) == Some("name"))
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:38,代码来源:ExceptionSourceFilterTest.scala

示例9: StatsFactoryWrapperTest

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

import com.twitter.finagle.{ClientConnection, ServiceFactory}
import com.twitter.finagle.stats.InMemoryStatsReceiver
import com.twitter.util.{Await, Future}
import org.junit.runner.RunWith
import org.mockito.Matchers.any
import org.mockito.Mockito.{verify, when}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class StatsFactoryWrapperTest extends FunSuite with MockitoSugar {
  val underlying = mock[ServiceFactory[Int, Int]]
  val rex = new RuntimeException
  val t = new Throwable(rex)

  test("report exceptions on Service creation failure") {
    val receiver = new InMemoryStatsReceiver
    val statsFac = new StatsFactoryWrapper(underlying, receiver)

    when(underlying(any[ClientConnection])) thenReturn Future.exception(t)

    intercept[Throwable] {
      Await.result(statsFac(ClientConnection.nil))
    }

    val expected = Map(
      List("failures", t.getClass.getName, rex.getClass.getName) -> 1)
    assert(receiver.counters == expected)
    verify(underlying)(ClientConnection.nil)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:35,代码来源:StatsFactoryWrapperTest.scala

示例10: OptionallyServableFilterTest

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

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import com.twitter.finagle.{NotServableException, Service}
import org.mockito.Mockito.{times, verify, when}
import org.mockito.Matchers._
import com.twitter.util.{Await, Future}

@RunWith(classOf[JUnitRunner])
class OptionallyServableFilterTest extends FunSuite with MockitoSugar {

  class OptionnallyServableFilterHelper {
    val underlying = mock[Service[String, String]]
    when(underlying.close(any)) thenReturn Future.Done

    val fn = mock[String => Future[Boolean]]
    val service = new OptionallyServableFilter(fn) andThen underlying
    val request = "request"
    val response = Future.value("response")
  }

  test("OptionallyServableFilter should passes through when fn returns true") {
    val h = new OptionnallyServableFilterHelper
    import h._

    when(fn.apply(request)) thenReturn Future.value(true)
    when(underlying(request)) thenReturn response
    assert(Await.result(service(request)) == Await.result(response))

    verify(fn).apply(request)
  }

  test("OptionallyServableFilter should throws NotServableException when fn returns false") {
    val h = new OptionnallyServableFilterHelper
    import h._

    when(fn.apply(request)) thenReturn Future.value(false)

    intercept[NotServableException] {
      Await.result(service(request))
    }
    verify(underlying, times(0)).apply(any[String])
    verify(fn).apply(request)
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:50,代码来源:OptionallyServableFilterTest.scala

示例11: CloseOnReleaseServiceTest

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

import org.junit.runner.RunWith
import org.mockito.Mockito.{verify, when, times}
import org.mockito.Matchers._
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import com.twitter.finagle.{WriteException, Service, Status}
import com.twitter.util.{Await, Promise, Future}

@RunWith(classOf[JUnitRunner])
class CloseOnReleaseServiceTest extends FunSuite with MockitoSugar {

  class Helper {
    val service = mock[Service[Any, Any]]
    when(service.close(any)) thenReturn Future.Done
    val promise = new Promise[Any]
    when(service(any)) thenReturn promise
    when(service.status) thenReturn Status.Open
    val wrapper = new CloseOnReleaseService(service)
  }

  test("only call release on the underlying service once") {
    val h = new Helper
    import h._
    
    assert(wrapper.isAvailable)
    verify(service, times(1)).status

    wrapper.close()
    verify(service, times(1)).close(any)
    wrapper.close()
    verify(service, times(1)).close(any)
    
    assert(!wrapper.isAvailable)
    verify(service, times(1)).status
  }

  test("throw a write exception if we attempt to use a released service") {
    val h = new Helper
    import h._

    wrapper.close()
    intercept[WriteException] {
      Await.result(wrapper(132))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:50,代码来源:CloseOnReleaseServiceTest.scala

示例12: MemorySpaceTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.mux.lease.exp

import com.twitter.conversions.storage.intToStorageUnitableWholeNumber
import com.twitter.util.StorageUnit
import org.mockito.Mockito.{when, verify}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class MemorySpaceTest extends FunSuite with MockitoSugar {
  test("MemorySpace#left should find the number of bytes left before we hit minDiscount") {
    val nfo = mock[JvmInfo]
    when(nfo.remaining()).thenReturn(10.megabytes)
    val range = StorageUnit.zero
    val minDiscount = 5.megabytes
    val maxDiscount = StorageUnit.zero
    val rSnooper = mock[RequestSnooper]
    val space = new MemorySpace(nfo, minDiscount, maxDiscount, rSnooper)
    assert(space.left == 5.megabytes)
    verify(nfo).remaining()
  }

  test("MemorySpace should be able to compute a discount correctly") {
    val nfo = mock[JvmInfo]
    val minDiscount = 5.megabytes
    val maxDiscount = 10.megabytes
    val rSnooper = mock[RequestSnooper]
    when(rSnooper.handleBytes()).thenReturn(2.megabytes)
    val rnd = mock[GenerationalRandom]
    when(rnd.apply()).thenReturn(107.megabytes.inBytes.toInt)
    val space =
      new MemorySpace(nfo, minDiscount, maxDiscount, rSnooper, NullLogsReceiver, rnd)
    assert(space.discount() == 7.megabytes)
    verify(rnd).apply()
    verify(rSnooper).handleBytes()
  }

  test("MemorySpace should be able to default to a max") {
    val nfo = mock[JvmInfo]
    val minDiscount = 5.megabytes
    val maxDiscount = 8.megabytes
    val rSnooper = mock[RequestSnooper]
    when(rSnooper.handleBytes()).thenReturn(9.megabytes)
    val rnd = mock[GenerationalRandom]
    val space =
      new MemorySpace(nfo, minDiscount, maxDiscount, rSnooper, NullLogsReceiver, rnd)
    assert(space.discount() == 8.megabytes)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:52,代码来源:MemorySpaceTest.scala

示例13: GenerationalRandomTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.mux.lease.exp

import org.junit.runner.RunWith
import org.mockito.Mockito.{when, verify, times}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import scala.util.Random

@RunWith(classOf[JUnitRunner])
class GenerationalRandomTest extends FunSuite with MockitoSugar {
  test("GenerationalRandom stays the same intragenerationally") {
    val nfo = mock[JvmInfo]
    when(nfo.generation()).thenReturn(0)
    val rnd = new Random(12334)
    val gen = new GenerationalRandom(nfo, rnd)
    verify(nfo).generation()

    val x = gen()
    verify(nfo, times(2)).generation()

    assert(gen() == x)
    verify(nfo, times(3)).generation()
  }

  test("GenerationalRandom changes intergenerationally") {
    val nfo = mock[JvmInfo]
    when(nfo.generation()).thenReturn(0)
    val rnd = new Random(12334)
    val gen = new GenerationalRandom(nfo, rnd)
    verify(nfo).generation()

    val x = gen()
    verify(nfo, times(2)).generation()

    assert(gen() == x)
    verify(nfo, times(3)).generation()

    when(nfo.generation()).thenReturn(1)

    assert(gen() != x)
    verify(nfo, times(5)).generation()
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:45,代码来源:GenerationalRandomTest.scala

示例14: RequestSnooperTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.mux.lease.exp

import com.twitter.util.{Time, MockTimer}
import com.twitter.conversions.time.intToTimeableNumber
import com.twitter.conversions.storage.intToStorageUnitableWholeNumber
import org.junit.runner.RunWith
import org.mockito.Mockito.when
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class RequestSnooperTest extends FunSuite with MockitoSugar {
  test("RequestSnooper should compute handleBytes reasonably") {
    val ctr = mock[ByteCounter]
    val quantile = 0.50

    when(ctr.rate()).thenReturn(1)

    Time.withCurrentTimeFrozen { ctl =>
      when(ctr.lastGc).thenReturn(Time.now - 5.seconds)

      val tmr = new MockTimer()
      val snooper = new RequestSnooper(ctr, quantile, timer = tmr)
      for (_ <- 0 until 50)
        snooper.observe(1.second)
      for (_ <- 0 until 50)
        snooper.observe(2.seconds)
      for (_ <- 0 until 50)
        snooper.observe(3.seconds)
      ctl.advance(12.seconds)
      tmr.tick()
      assert(snooper.handleBytes() == 2000.bytes)
    }
  }

  test("RequestSnooper should discard results that overlap with a gc") {
    val ctr = mock[ByteCounter]
    val quantile = 0.50

    when(ctr.rate()).thenReturn(1)

    Time.withCurrentTimeFrozen { ctl =>
      when(ctr.lastGc).thenReturn(Time.now - 5.seconds)

      val tmr = new MockTimer()
      val snooper = new RequestSnooper(ctr, quantile, timer = tmr)
      for (_ <- 0 until 50)
        snooper.observe(1.second)
      for (_ <- 0 until 50)
        snooper.observe(2.seconds)
      for (_ <- 0 until 50)
        snooper.observe(3.seconds)
      for (_ <- 0 until 1000)
        snooper.observe(8.seconds)
      ctl.advance(12.seconds)
      tmr.tick()
      assert(snooper.handleBytes() == 2000.bytes)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:62,代码来源:RequestSnooperTest.scala

示例15: ThriftServerFramedCodecTest

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

import com.twitter.finagle.Service
import com.twitter.finagle.tracing._
import com.twitter.finagle.util.ByteArrays
import com.twitter.util.Future
import org.apache.thrift.protocol.{TBinaryProtocol, TMessage, TMessageType}
import org.junit.runner.RunWith
import org.mockito.Matchers
import org.mockito.Mockito.when
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class ThriftServerFramedCodecTest extends FunSuite with MockitoSugar {
  val protocolFactory = new TBinaryProtocol.Factory()

  test("ThriftServerTracingFilter read header correctly") {
    val traceId = TraceId(Some(SpanId(1L)), None, SpanId(2L), Some(true), Flags().setDebug)
    val bufferingTracer = new BufferingTracer
    Trace.letTracer(bufferingTracer) {
      val filter = new TTwitterServerFilter("service", protocolFactory)
  
      val upgradeMsg = new OutputBuffer(protocolFactory)
      upgradeMsg().writeMessageBegin(new TMessage(ThriftTracing.CanTraceMethodName, TMessageType.CALL, 0))
      val options = new thrift.ConnectionOptions
      options.write(upgradeMsg())
      upgradeMsg().writeMessageEnd()
  
      val service = mock[Service[Array[Byte], Array[Byte]]]
      when(service(Matchers.any[Array[Byte]])).thenReturn(Future(Array[Byte]()))
  
      // now finagle knows we can handle the headers
      filter(upgradeMsg.toArray, service)
  
      // let's create a header
      val header = new thrift.RequestHeader
      header.setSpan_id(2L)
      header.setTrace_id(1L)
      header.setSampled(true)
      header.setFlags(1L)
  
      val ignoreMsg = new OutputBuffer(protocolFactory)
      ignoreMsg().writeMessageBegin(new TMessage("ignoreme", TMessageType.CALL, 0))
      new thrift.ConnectionOptions().write(ignoreMsg())
      ignoreMsg().writeMessageEnd()
  
      filter(ByteArrays.concat(OutputBuffer.messageToArray(header, protocolFactory), ignoreMsg.toArray), service)
  
      bufferingTracer.iterator foreach { record =>
        assert(record.traceId == traceId)
        assert(record.traceId.flags == traceId.flags)
      }
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:58,代码来源:ThriftServerFramedCodecTest.scala


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