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

Scala ScalaFutures类代码示例

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

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



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

示例1: myPublicAddress

//设置package包名称以及导入依赖的类
package org.zalando.hutmann.spec

import org.scalatest.concurrent.PatienceConfiguration.Interval
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Seconds, Span }
import org.scalatestplus.play.{ PlaySpec, PortNumber, WsScalaTestClient }
import play.api.Application
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.{ WSClient, WSResponse }

trait PlayUnitSpec extends PlaySpec with ScalaFutures with WsScalaTestClient {
  def myPublicAddress(): String
  implicit val portNumber: PortNumber

  def callWs(testPaymentGatewayURL: String)(implicit app: Application): WSResponse = {
    implicit val wSClient = app.injector.instanceOf[WSClient]
    val callbackURL = s"http://${myPublicAddress()}/callback"
    whenReady(
      wsUrl(testPaymentGatewayURL)
        .withQueryStringParameters("callbackURL" -> callbackURL)
        .withHttpHeaders(HeaderNames.ACCEPT -> MimeTypes.TEXT)
        .get(),
      Interval(Span(10, Seconds))
    ) { result =>
        result
      }
  }
} 
开发者ID:zalando-incubator,项目名称:hutmann,代码行数:29,代码来源:PlayUnitSpec.scala


示例2: ActorSpec

//设置package包名称以及导入依赖的类
package com.github.j5ik2o.reactive.redis

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.testkit.{ ImplicitSender, TestKit }
import akka.util.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ BeforeAndAfterAll, DiagrammedAssertions, FunSpecLike }

import scala.concurrent.duration._

abstract class ActorSpec(_system: ActorSystem)
    extends TestKit(_system)
    with ImplicitSender
    with FunSpecLike
    with DiagrammedAssertions
    with BeforeAndAfterAll
    with TimeFactorSupport
    with ScalaFutures {

  implicit override val patienceConfig: PatienceConfig = PatienceConfig(15 * timeFactor seconds)

  implicit val materializer = ActorMaterializer()

  implicit val timeout = Timeout(15 seconds)

  override protected def afterAll(): Unit = {
    shutdown()
    super.beforeAll()
  }

} 
开发者ID:j5ik2o,项目名称:reactive-redis,代码行数:33,代码来源:ActorSpec.scala


示例3: ExecutionContextBackboneCoordinatorSpec

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import scala.concurrent.ExecutionContext

import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ FlatSpec, Matchers }

import ie.zalando.pipeline.backbone.PhaseTrackingPhase.PhaseTrackingTopLevelInitPhase
import ie.zalando.pipeline.backbone.Phases.TopLevelInitializationPhase
import ie.zalando.pipeline.backbone.TestDatum

class ExecutionContextBackboneCoordinatorSpec extends FlatSpec with Matchers with ScalaFutures {

  "An ExecutionContextBackboneCoordinator" should "push a datum through the pipeline" in new Fixture {
    val ec = ExecutionContext.global
    val coordinator = new ExecutionContextBackboneCoordinator(backbone, ec)
    val f1 = coordinator.process(TestDatum(name = "Megatron"))
    val f2 = coordinator.process(TestDatum(name = "Soundwave"))
    val f3 = coordinator.process(TestDatum(name = "Shockwave"))

    f1.futureValue.isRight shouldBe true
    f1.futureValue.foreach(_.phrase shouldBe "Hello, Megatron, this was calculated on partition -1")
    f1.futureValue.foreach(_.wordCount shouldBe 8)
    f1.futureValue.foreach(_.isEven shouldBe Some(true))

    f2.futureValue.isRight shouldBe true
    f2.futureValue.foreach(_.phrase shouldBe "Hello, Soundwave, this was calculated on partition -1")
    f2.futureValue.foreach(_.wordCount shouldBe 8)
    f2.futureValue.foreach(_.isEven shouldBe Some(false))

    f3.futureValue.isRight shouldBe true
    f3.futureValue.foreach(_.phrase shouldBe "Hello, Shockwave, this was calculated on partition -1")
    f3.futureValue.foreach(_.wordCount shouldBe 8)
    f3.futureValue.foreach(_.isEven shouldBe Some(false))
  }

  "An ExecutionContextBackboneCoordinator" should "intialize and release the local phases properly" in new Fixture {

    override def driverInitPhases: Seq[TopLevelInitializationPhase[TestDatum]] = super.driverInitPhases :+ PhaseTrackingTopLevelInitPhase()

    val ec = ExecutionContext.global
    val coordinator = new ExecutionContextBackboneCoordinator(backbone, ec)
    val f1 = coordinator.process(TestDatum(name = "Megatron"))
    val f2 = coordinator.process(TestDatum(name = "Soundwave"))
    val f3 = coordinator.process(TestDatum(name = "Shockwave"))

    f1.futureValue.isRight shouldBe true
    f2.futureValue.isRight shouldBe true
    f3.futureValue.isRight shouldBe true
    f1.futureValue.foreach(_.phrase shouldBe "Hello, Megatron, this was calculated on partition -1")
    f2.futureValue.foreach(_.phrase shouldBe "Hello, Soundwave, this was calculated on partition -1")
    f3.futureValue.foreach(_.phrase shouldBe "Hello, Shockwave, this was calculated on partition -1")
    f1.futureValue.foreach(_.localReleased.get.get shouldBe true)
    f2.futureValue.foreach(_.localReleased.get.get shouldBe true)
    f3.futureValue.foreach(_.localReleased.get.get shouldBe true)
  }
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:58,代码来源:ExecutionContextBackboneCoordinatorSpec.scala


示例4: AppbuilderSpecs

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

import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers}
import shapeless.HNil

import scala.concurrent.Future

class AppbuilderSpecs extends FlatSpec with Matchers with ScalaFutures {

  import scala.concurrent.ExecutionContext.Implicits.global
  import scalaz.Scalaz._

  "Appbuilder" should "work" in {
    val optionsAB = Option(1) :@: Option(2)
    optionsAB((_: Int) + (_: Int)) should equal(Some(3))

    (Future(1) :@: Future(2) :@: Future("3")) { (a: Int, b: Int, c: String) =>
      a + b + c.toInt
    }.futureValue should equal(6)

    (List(1,2) :@: List(3,4) :@: List(5,6)) {
      (a: Int, b: Int, c: Int) => a + b + c
    } should equal(List(9, 10, 10, 11, 10, 11, 11, 12))

    (1.some :@: 2.some :@: 3.some :@: 4.some :@: 5.some :@: 6.some :@: 7.some :@: 8.some :@: 9.some :@: 10.some :@: 11.some :@: 12.some :@: 13.some :@: 14.some :@: 15.some :@: 16.some :@: 17.some :@: 18.some :@: 19.some :@: 20.some :@: 21.some :@: 22.some)
      .asTuple should equal((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22).some)
  }
} 
开发者ID:haghard,项目名称:shapeless-playbook,代码行数:30,代码来源:AppbuilderSpecs.scala


示例5: MemoryBufferSpec

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl

import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, ActorMaterializerSettings}
import akka.stream.scaladsl.{Sink, Source}
import akka.testkit.TestKit
import akka.util.ByteString
import org.scalatest.time.{Millis, Seconds, Span}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import org.scalatest.concurrent.ScalaFutures

class MemoryBufferSpec(_system: ActorSystem)
    extends TestKit(_system)
    with FlatSpecLike
    with Matchers
    with BeforeAndAfterAll
    with ScalaFutures {

  def this() = this(ActorSystem("MemoryBufferSpec"))

  implicit val defaultPatience =
    PatienceConfig(timeout = Span(5, Seconds), interval = Span(30, Millis))

  implicit val materializer = ActorMaterializer(ActorMaterializerSettings(system).withDebugLogging(true))

  "MemoryBuffer" should "emit a chunk on its output containg the concatenation of all input values" in {
    val result = Source(Vector(ByteString(1, 2, 3, 4, 5), ByteString(6, 7, 8, 9, 10, 11, 12), ByteString(13, 14)))
      .via(new MemoryBuffer(200))
      .runWith(Sink.seq)
      .futureValue

    result should have size (1)
    val chunk = result.head
    chunk.size should be(14)
    chunk.data.runWith(Sink.seq).futureValue should be(Seq(ByteString(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)))
  }

  it should "fail if more than maxSize bytes are fed into it" in {
    whenReady(
      Source(Vector(ByteString(1, 2, 3, 4, 5), ByteString(6, 7, 8, 9, 10, 11, 12), ByteString(13, 14)))
        .via(new MemoryBuffer(10))
        .runWith(Sink.seq)
        .failed
    ) { e =>
      e shouldBe a[IllegalStateException]
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:49,代码来源:MemoryBufferSpec.scala


示例6: SplitAfterSizeSpec

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl

import akka.testkit.TestKit
import akka.stream.ActorMaterializerSettings
import org.scalatest.BeforeAndAfterAll
import org.scalatest.concurrent.ScalaFutures
import akka.stream.ActorMaterializer
import akka.actor.ActorSystem
import org.scalatest.Matchers
import org.scalatest.FlatSpecLike
import akka.stream.scaladsl.Source
import akka.stream.scaladsl.Flow
import akka.util.ByteString
import akka.stream.scaladsl.Sink
import org.scalatest.time.{Millis, Seconds, Span}
import scala.concurrent.duration._

class SplitAfterSizeSpec(_system: ActorSystem)
    extends TestKit(_system)
    with FlatSpecLike
    with Matchers
    with BeforeAndAfterAll
    with ScalaFutures {

  def this() = this(ActorSystem("SplitAfterSizeSpec"))
  implicit val defaultPatience =
    PatienceConfig(timeout = Span(5, Seconds), interval = Span(30, Millis))

  implicit val materializer = ActorMaterializer(ActorMaterializerSettings(system).withDebugLogging(true))

  "SplitAfterSize" should "yield a single empty substream on no input" in {
    Source
      .empty[ByteString]
      .via(
        SplitAfterSize(10)(Flow[ByteString]).concatSubstreams
      )
      .runWith(Sink.seq)
      .futureValue should be(Seq.empty)
  }

  it should "start a new stream after the element that makes it reach a maximum, but not split the element itself" in {
    Source(Vector(ByteString(1, 2, 3, 4, 5), ByteString(6, 7, 8, 9, 10, 11, 12), ByteString(13, 14)))
      .via(
        SplitAfterSize(10)(Flow[ByteString]).prefixAndTail(10).map { case (prefix, tail) => prefix }.concatSubstreams
      )
      .runWith(Sink.seq)
      .futureValue should be(
      Seq(
        Seq(ByteString(1, 2, 3, 4, 5), ByteString(6, 7, 8, 9, 10, 11, 12)),
        Seq(ByteString(13, 14))
      )
    )
  }

} 
开发者ID:akka,项目名称:alpakka,代码行数:56,代码来源:SplitAfterSizeSpec.scala


示例7: CsvSpec

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.csv.scaladsl

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.testkit.TestKit
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Matchers, WordSpec}

abstract class CsvSpec
    extends WordSpec
    with Matchers
    with BeforeAndAfterAll
    with BeforeAndAfterEach
    with ScalaFutures {

  implicit val system = ActorSystem(this.getClass.getSimpleName)
  implicit val materializer = ActorMaterializer()

  override protected def afterAll(): Unit =
    TestKit.shutdownActorSystem(system)
} 
开发者ID:akka,项目名称:alpakka,代码行数:22,代码来源:CsvSpec.scala


示例8: PersonControllerSpec3

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

import org.scalatestplus.play._
import play.api.test._
import play.api.test.Helpers._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.inject.bind
import dao._
import org.scalatest.TestData
import play.api.Application
import dao.PersonDAO
import dao.PersonDAOMock
import play.api.inject.guice.GuiceableModule.fromPlayBinding
import com.typesafe.config.ConfigFactory
import org.scalatest.concurrent.ScalaFutures


class PersonControllerSpec3 extends PlaySpec with ScalaFutures{

  val app = new GuiceApplicationBuilder()
    .overrides(bind(classOf[PersonDAO]).to(classOf[PersonDAOMock]))
    .build

  "Find all route" should {
    "return all persons" in running(app) {
      route(app, FakeRequest(GET, "/persons")).map(status(_)) mustBe Some(OK)
      
      // this should return PersonDAOMock, because we've overriden it
      val app2PersonDao = play.api.Application.instanceCache[PersonDAO]
      val personDAO: PersonDAO = app2PersonDao(app)
      val personsFuture = personDAO.findAll
      
      whenReady(personsFuture){ persons =>
        persons.map(_.name) must contain("Mocked Person")
      }
    }
  }
} 
开发者ID:sake92,项目名称:PlayGuiceExample,代码行数:39,代码来源:PersonControllerSpec.scala


示例9: Benchmarks

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

import com.vatbox.polyjuice.internal.PolyjuiceMapper
import generators.Generator
import org.json4s.native.Serialization
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.time.{Millis, Minutes, Span}
import org.scalatest.{FreeSpec, Matchers, OptionValues, TryValues}

import scala.concurrent.ExecutionContext.Implicits.global

class Benchmarks extends FreeSpec with TryValues with OptionValues with Matchers with ScalaFutures with GeneratorDrivenPropertyChecks {
  implicit val formats = org.json4s.DefaultFormats
  val amount = 10000
  override implicit val patienceConfig = PatienceConfig(Span(1, Minutes), Span(10, Millis))
  val mapper: PolyjuiceMapper = Polyjuice.createMapper(varName = "model", userCode = s"""if (model.bool) return model.int; else return model.str;""")
  "Map many" in {
    forAll(Generator.modelGen, minSuccessful(amount)) { model =>
      val json = Serialization.write(model)
      if (model.bool) {
        val result = mapper.map[Int](json).futureValue.get
        assert(result === model.int)
      }
      else {
        val result = mapper.map[String](json).futureValue.get
        assert(result === model.str)
      }
    }
  }
} 
开发者ID:VATBox,项目名称:polyjuicelib,代码行数:32,代码来源:Benchmarks.scala


示例10: ShapeTest

//设置package包名称以及导入依赖的类
package net.scalax.fsn.database.test

import net.scalax.fsn.slick.helpers.SlickUtils
import org.scalatest._
import org.scalatest.concurrent.ScalaFutures

class ShapeTest extends FlatSpec
    with Matchers
    with EitherValues
    with ScalaFutures
    with BeforeAndAfterAll {

  import slick.jdbc.H2Profile.api._

  "shape count" should "return 0 when input a empty shape" in {
    def emptyShapeGen[S, D, T](repLike: S)(implicit implShape: Shape[FlatShapeLevel, S, D, T]) = implShape
    val emptyShape = emptyShapeGen(((), ((), ()), ()))
    SlickUtils.isShapeEmpty(emptyShape) shouldBe true
    val literalShape = emptyShapeGen(((), LiteralColumn(4), ()) -> LiteralColumn(3))
    SlickUtils.shapeLength(literalShape) shouldBe 2
    val constShape = emptyShapeGen(((), 4, ()) -> 3)
    SlickUtils.shapeLength(constShape) shouldBe 0
  }

} 
开发者ID:scalax,项目名称:ubw,代码行数:26,代码来源:EmptyIncTest.scala


示例11: DummyServiceTest

//设置package包名称以及导入依赖的类
package de.innfactory.bootstrap

import org.scalatest.concurrent.ScalaFutures
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.model.StatusCodes._
import de.innfactory.bootstrap.models.Dummy
import io.circe.generic.auto._

class DummyServiceTest extends BaseServiceTest with ScalaFutures {

  trait Context {
    val route = httpService.dummyRouter.route
  }

  "Dummy service" should {

    "retrieve empty dummy list" in new Context {
      Get("/dummy/") ~> route ~> check {
        responseAs[Seq[String]].isEmpty should be(true)
      }
    }

    "retrieve no content for a specific search" in new Context {
      Get("/dummy/1")~> addHeader("Authorization", "test") ~> route ~> check {
        status shouldBe OK
        contentType shouldBe `application/json`
      }
    }

    "test the entity" in {
      val dummy = Dummy(Some(1), "Hello")
      dummy.id shouldBe Some(1)
      dummy.dummy shouldBe "Hello"
    }
  }

} 
开发者ID:innFactory,项目名称:bootstrap-akka-http,代码行数:38,代码来源:DummyServiceTest.scala


示例12: ResultFetcherTest

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

import com.piotrglazar.receiptlottery.Token
import com.piotrglazar.receiptlottery.utils.ScalajHttpAdapter
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.scalatest.time.{Seconds, Span}
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.ExecutionContext.Implicits.global

class ResultFetcherTest extends FlatSpec with Matchers with ScalaFutures {

  implicit val timeout = PatienceConfig(Span(1, Seconds))

  val resultFetcher = new ResultFetcher("https://loteriaparagonowa.gov.pl/wyniki", new ScalajHttpAdapter(2000), global)

  val tokens = Table(("token", "result"),
    (Token("D2T1UGL9M34"), true),
    (Token("C91B2MGBM5F"), false))

  "ResultFetcher" should "find result for token" in {
    forAll(tokens) { (token: Token, expectedResult: Boolean) =>
      // when
      val result = resultFetcher.hasResult(token)

      // then
      result.futureValue shouldBe expectedResult
    }
  }

} 
开发者ID:piotrglazar,项目名称:receipt-lottery,代码行数:33,代码来源:ResultFetcherTest.scala


示例13: NotifyLaunchQueueStepImplTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.task.update.impl.steps

import akka.Done
import com.google.inject.Provider
import mesosphere.marathon.core.launchqueue.LaunchQueue
import mesosphere.marathon.core.task.bus.TaskStatusUpdateTestHelper
import mesosphere.marathon.test.Mockito
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ FunSuite, GivenWhenThen, Matchers }

import scala.concurrent.Future

class NotifyLaunchQueueStepImplTest extends FunSuite with Matchers with GivenWhenThen with Mockito with ScalaFutures {
  test("name") {
    new Fixture().step.name should equal("notifyLaunchQueue")
  }

  test("notifying launch queue") {
    Given("a status update")
    val f = new Fixture
    val expectedUpdate = TaskStatusUpdateTestHelper.running().wrapped

    When("calling processUpdate")
    f.launchQueue.notifyOfInstanceUpdate(expectedUpdate) returns Future.successful(Done)
    f.step.process(expectedUpdate).futureValue

    Then("the update is passed to the LaunchQueue")
    verify(f.launchQueue).notifyOfInstanceUpdate(expectedUpdate)
  }

  class Fixture {
    val launchQueue = mock[LaunchQueue]
    val launchQueueProvider = new Provider[LaunchQueue] {
      override def get(): LaunchQueue = launchQueue
    }
    val step = new NotifyLaunchQueueStepImpl(launchQueueProvider = launchQueueProvider)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:39,代码来源:NotifyLaunchQueueStepImplTest.scala


示例14: ActionCallerSpec

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

import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.testkit.TestKit
import com.typesafe.config.ConfigFactory
import model.{Delay, HttpCall}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpecLike, Matchers}
import play.api.libs.ws.{WSClient, WSRequest, WSResponse}

import scala.concurrent.duration._
import org.scalatest.concurrent.{ScalaFutures}
import play.api.libs.json.Json
import play.mvc.Http.Status

import scala.concurrent.Future


object ActionCallerSpec {
  // Define your test specific configuration here
  val config =
    """
    akka {
      loglevel = "WARNING"
    }
    """
}

class ActionCallerSpec extends TestKit(ActorSystem("InfraRedServiceSpec", ConfigFactory.parseString(ActionCallerSpec.config))) with FlatSpecLike with Matchers with MockFactory with ScalaFutures {

  "The ActionCaller service" should "handle multiple http calls" in {

    val ws = mock[WSClient]

    val actionCaller = new DefaultActionCaller(ws, system)

    val actions = Seq(HttpCall(method = "GET", path = "/jvc/AUX", order = 0), HttpCall(method = "GET", path = "/jvc/OFF", order = 1, delay = Some(Delay(3, TimeUnit.SECONDS))))

    val mockRequest = mock[WSRequest]
    val mockResponse = mock[WSResponse]
//    (mockResponse.status _).expects().returns(Status.OK).anyNumberOfTimes()
    (mockRequest.get: () => Future[WSResponse]).expects().returns(Future.successful(mockResponse)).anyNumberOfTimes()

    (ws.url _).expects("/jvc/AUX").returns(mockRequest)
    (ws.url _).expects("/jvc/OFF").returns(mockRequest)

    actionCaller.call(actions).futureValue(timeout(4 seconds))
  }
} 
开发者ID:jimnybob,项目名称:smartii-ir,代码行数:52,代码来源:ActionCallerSpec.scala


示例15: CameraRelayControllerTest

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

import com.intersection.camerarelay.UploadManager
import org.mockito.Matchers._
import org.scalatest.concurrent.{Futures, ScalaFutures}
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}
import play.api.libs.Files
import play.api.mvc.{Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import org.mockito.Mockito._

import scala.concurrent.Future

class CameraRelayControllerTest extends FunSpec with Matchers with MockitoSugar with BeforeAndAfter with Futures with ScalaFutures {
  var controller : CameraRelayController = _
  var uploadManager : UploadManager = _

  before {
    uploadManager = mock[UploadManager]
    controller = new CameraRelayController(uploadManager)
  }

  describe(classOf[CameraRelayControllerTest].getName) {
    it("Rejects requests without a valid siteId header : X-Site-Id") {
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
      val result = controller.uploadVideoChunk().apply(request)
      status(result) should equal(400)
    }

    it("Rejects requests without a valid Link-Time header : X-Link-Time") {
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234")).withBody(Files.TemporaryFile())
      val result: Future[Result] = controller.uploadVideoChunk().apply(request)
      status(result) should equal(400)
    }

    it("Accepts a fully formed request") {
      import scala.concurrent.ExecutionContext.Implicits.global
      when(uploadManager.handleVideoChunk(any[String],any[String],any[Files.TemporaryFile])).thenReturn(Future(()))
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
      val result: Future[Result] = controller.uploadVideoChunk().apply(request)
      status(result) should equal(202)
    }

  }
} 
开发者ID:arjunmukherjee,项目名称:camerarelay,代码行数:48,代码来源:CameraRelayControllerTest.scala


示例16: ReportsControllerTest

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

import model._
import org.jsoup.Jsoup
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FunSpec, Matchers}
import play.api.test.FakeRequest
import services.ReportService
import org.mockito.Mockito._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class ReportsControllerTest extends FunSpec with Matchers with MockitoSugar with ScalaFutures{

  describe("Reports Controller"){
    it("should display country name and count of airports in country"){
      new Setup {
        val response = reportController.getCountriesWithHighestNoOfAirports(FakeRequest()).futureValue

        response.header.status should be(200)

        val expectedFirstRow = Jsoup.parse(views.html.report("Some Title",expectedSearchResult.toList).body).select("table > tbody > tr:nth-child(1) td").text()
        expectedFirstRow should be("Australia 100")
      }
    }
  }

  trait Setup{
    val mockReportService = mock[ReportService]
    val reportController = new ReportsController(mockReportService)
    val expectedSearchResult: Vector[CountryReport] = Vector(CountryReport(Country("Australia","AUS"),100))

    when(mockReportService.findCountriesWithHighestNoOfAirports).thenReturn(Future(expectedSearchResult))
  }

} 
开发者ID:atiqsayyed,项目名称:airport,代码行数:38,代码来源:ReportsControllerTest.scala


示例17: RepeatNTimesSpec

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

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import akka.stream.testkit.TestSubscriber.Probe
import akka.stream.testkit.scaladsl.TestSink
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec}

class RepeatNTimesSpec extends WordSpec with Matchers with BeforeAndAfterAll 
  with ScalaFutures {
  
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  "RepeatNTimesSpec" must {
    "repeat 3 times" in {
      val xs = Source.single("x")
        .via(RepeatNTimes(3))
        .runWith(Sink.seq).futureValue
      
      xs should === (List("x", "x", "x"))
    }
    
    "repeat 3 things 3 times" in {
      val xs = Source.fromIterator(() => List("a", "b", "c").iterator)
        .via(RepeatNTimes(3))
        .runWith(Sink.seq).futureValue
      
      xs should === (List("a", "a", "a", "b", "b", "b", "c", "c", "c"))
    }

    "show TestSink" in {
      val probe: Probe[String] = 
        Source.fromIterator(() => List("a").iterator)
        .via(RepeatNTimes(3))
          .runWith(TestSink.probe)

      probe.requestNext("a")
      probe.requestNext("a")
      probe.requestNext("a")
      probe.expectComplete()
    }
  }

} 
开发者ID:ktoso,项目名称:scaladays-berlin-akka-streams,代码行数:48,代码来源:RepeatNTimesSpec.scala


示例18: MatrixRulesLoaderSpec

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice

import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model.RulesFileLoadError
import uk.gov.hmrc.decisionservice.model.rules.SectionCarryOver
import uk.gov.hmrc.decisionservice.ruleengine.{MatrixFactMatcher, MatrixRulesLoader, RulesFileMetaData}
import uk.gov.hmrc.play.test.UnitSpec

class MatrixRulesLoaderSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {

  val csvFilePath = "/matrix.csv"
  val csvFilePathError = "/matrix_error.csv"
  val csvMetadata = RulesFileMetaData(2, 1, csvFilePath)
  val csvMetadataError = RulesFileMetaData(2, 1, csvFilePathError)

  "matrix rules loader" should {
    "load matrix rules from a csv file" in {
      val maybeRules = MatrixRulesLoader.load(csvMetadata)
      maybeRules.isRight shouldBe true
      maybeRules.map { ruleset =>
        ruleset.rules should have size 3
        ruleset.headings should have size 2
      }
    }
    "return error if file is not found" in {
      val maybeRules = MatrixRulesLoader.load(RulesFileMetaData(2, 1, csvFilePath + "xx"))
      maybeRules.isLeft shouldBe true
      maybeRules.leftMap { error =>
        error shouldBe a [RulesFileLoadError]
      }
    }
    "return error if file contains invalid data" in {
      val maybeRules = MatrixRulesLoader.load(csvMetadataError)
      maybeRules.isLeft shouldBe true
      maybeRules.leftMap { error =>
        error shouldBe a [RulesFileLoadError]
      }
    }
    "provide valid input for an inference against fact" in {
      val matrixFacts = Map(
        ("BusinessStructure" -> SectionCarryOver("high", true)), ("Substitute" -> SectionCarryOver("high" , false))
      )
      val maybeRules = MatrixRulesLoader.load(csvMetadata)
      maybeRules.isRight shouldBe true
      maybeRules.map { ruleset =>
        ruleset.rules should have size 3
        ruleset.headings should have size 2
        val response = MatrixFactMatcher.matchFacts(matrixFacts, ruleset)
        response.isRight shouldBe true
        response.map { decision =>
          decision.value should equal("out of IR35")
        }
      }
    }
  }
} 
开发者ID:Baisysoft,项目名称:off-payroll-decision-service,代码行数:58,代码来源:MatrixRulesLoaderSpec.scala


示例19: MatrixEmptyValuesMatchingSpec

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice

import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model._
import uk.gov.hmrc.decisionservice.model.rules.{MatrixDecision, MatrixRule, MatrixRuleSet, SectionCarryOver}
import uk.gov.hmrc.decisionservice.ruleengine.MatrixFactMatcher
import uk.gov.hmrc.play.test.UnitSpec

class MatrixEmptyValuesMatchingSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {

  "matrix fact with empty values matcher" should {
    "produce fact error when fact is missing answers for which rule values are not empty" in {
      val matrixFacts = Map(
        ("BusinessStructure" -> SectionCarryOver("high", true)),
        ("Substitute" -> SectionCarryOver("" , false)),
        ("FinancialRisk" -> SectionCarryOver("" , false))
      )
      val matrixRules = List(
        MatrixRule(List(SectionCarryOver("high"  , true ),SectionCarryOver("high" , true ),SectionCarryOver("low" , true )), MatrixDecision("self employed")),
        MatrixRule(List(SectionCarryOver("high"  , true ),SectionCarryOver("low" , false),SectionCarryOver("low" , true )), MatrixDecision("in IR35")),
        MatrixRule(List(SectionCarryOver("medium", true ),SectionCarryOver("high", true ),SectionCarryOver("low" , true )), MatrixDecision("out of IR35"))
      )
      val matrixRuleSet = MatrixRuleSet(List("BusinessStructure", "Substitute", "FinancialRisk"), matrixRules)

      val response = MatrixFactMatcher.matchFacts(matrixFacts, matrixRuleSet)
      println(response)
      response.isLeft shouldBe true
      response.leftMap { error =>
        error shouldBe a [FactError]
      }
    }
    "produce rules error when fact is missing answers for which there is no match but corresponding rule values are empty in at least one rule" in {
      val matrixFacts = Map(
        ("BusinessStructure" -> SectionCarryOver("high", true)),
        ("Substitute" -> SectionCarryOver("" , false)),
        ("FinancialRisk" -> SectionCarryOver("" , false))
      )
      val matrixRules = List(
        MatrixRule(List(SectionCarryOver("high"  , true ),SectionCarryOver("high" , true ),SectionCarryOver("low" , true )), MatrixDecision("self employed")),
        MatrixRule(List(SectionCarryOver("high"  , true ),SectionCarryOver("low" , false),SectionCarryOver("low" , true )), MatrixDecision("in IR35")),
        MatrixRule(List(SectionCarryOver("medium", true ),SectionCarryOver("", true ),SectionCarryOver("" , true )), MatrixDecision("out of IR35"))
      )
      val matrixRuleSet = MatrixRuleSet(List("BusinessStructure", "Substitute", "FinancialRisk"), matrixRules)

      val response = MatrixFactMatcher.matchFacts(matrixFacts, matrixRuleSet)
      println(response)
      response.isLeft shouldBe true
      response.leftMap { error =>
        error shouldBe a [RulesFileError]
      }
    }
  }

} 
开发者ID:Baisysoft,项目名称:off-payroll-decision-service,代码行数:56,代码来源:MatrixEmptyValuesMatchingSpec.scala


示例20: PlayWSReactiveInfluxISpec

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

import com.pygmalios.reactiveinflux.itest.ITestConfig
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class PlayWSReactiveInfluxISpec extends FlatSpec with ScalaFutures {
  behavior of "ping"

  it should "send ping request to InfluxDB" in new TestScope {
    assert(reactiveInflux.ping().futureValue.influxDbVersion.startsWith("0.11"))
  }
}

private class TestScope {
  val reactiveInflux = new PlayWSReactiveInflux(ITestConfig.reactiveInfluxConfig)
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:21,代码来源:PlayWSReactiveInfluxISpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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