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

Scala GivenWhenThen类代码示例

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

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



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

示例1: MonitoringEndpointsSpec

//设置package包名称以及导入依赖的类
package org.danielwojda.obfuscator.functionaltests

import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
import org.danielwojda.obfuscator.functionaltests.dsl.AkkaImplicits
import org.danielwojda.obfuscator.functionaltests.dsl.HttpEntityImplicitConverters._
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, GivenWhenThen, Matchers}

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps

class MonitoringEndpointsSpec extends FlatSpec with Matchers with GivenWhenThen with ScalaFutures with AkkaImplicits {

  override implicit val patienceConfig = PatienceConfig(timeout = 2 seconds)
  implicit val timeout = Timeout(patienceConfig.timeout)

  "Service" should "expose the 'status' endpoint which always returns OK" in {
    When("a 'status' endpoint is called")
    val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://localhost:8080/private/status"))

    Then("Http status 200 and OK body is returned")
    whenReady(responseFuture) { response =>
      response.status shouldBe StatusCodes.OK
      response.entity.asString shouldBe "OK"
    }
  }

} 
开发者ID:wojda,项目名称:obfuscate,代码行数:32,代码来源:MonitoringEndpointsSpec.scala


示例2: AppSpec

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

import org.scalatest.{FeatureSpec, GivenWhenThen}

class AppSpec extends FeatureSpec with GivenWhenThen {

  info("As an app developer I want to be able to access the app, its settings and properties")

  feature("Application class") {
    scenario("can be instantiated in Headless mode") {
      Given("a default location app.Main for the app")
      When("the class is instantiated as a headless")
      val application = new app.Main(true)
      Then("the object should be instantiated")
      assert(application.isInstanceOf[app.Main])
    }
  }
} 
开发者ID:Y-Experiment,项目名称:LW3D,代码行数:19,代码来源:AppSpec.scala


示例3: TransferServiceSpec

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

import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{FunSpec, GivenWhenThen, Matchers}

class TransferServiceSpec extends FunSpec with Matchers with TableDrivenPropertyChecks with GivenWhenThen {
  describe("TransferService"){
    it("can transfer money from source account to target account"){
      val srcAccount = new Account("xx",100.0)
      val targetAccount = new Account("yy", 50.0)
      TransferService.transfer(srcAccount, targetAccount, 50.0)
      srcAccount.balance shouldBe 50.0
      targetAccount.balance shouldBe 100.0
    }
    it("transfer should fail if not enough balance in source account"){
      pending
    }
    //this is a scalatest table-driven-property-check example
    it("can transfer any amount of money"){
      val example =
        Table(
          ("source account balance","target account balance","transfer amount"," expected source account balance","expected target account balance"),
          (100, 50, 50, 50, 100),
          (77, 0, 50, 27, 50)
        )
      forAll(example){ (srcBalance, targetBalance, amount, expSrcBalance,expTargetBalance) =>
        Given(s"source account who's owner is xx,have balance: $srcBalance")
        val srcAccount = new Account("xx", srcBalance)
        And(s"target account who's owner is yy, have balance: $targetBalance")
        val targetAccount = new Account("yy", targetBalance)
        When(s"Transfer $amount from srcAccount to targetAccount")
        TransferService.transfer(srcAccount, targetAccount, amount)
        Then(s"srcAccount should have balance $expSrcBalance")
        srcAccount.balance shouldBe expSrcBalance
        And(s"targetAccount should have balance $expTargetBalance")
        targetAccount.balance shouldBe expTargetBalance
      }
    }
  }
} 
开发者ID:notyy,项目名称:scalaTrainning,代码行数:41,代码来源:TransferServiceSpec.scala


示例4: HttpEventStreamServletTest

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

import javax.servlet.http.HttpServletResponse

import akka.actor.ActorRef
import mesosphere.marathon._
import mesosphere.marathon.api.TestAuthFixture
import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import org.scalatest.{ GivenWhenThen, Matchers }

class HttpEventStreamServletTest extends MarathonSpec with Matchers with Mockito with GivenWhenThen {

  test("access without authentication is denied") {
    Given("An unauthenticated request")
    val f = new Fixture
    val resource = f.streamServlet()
    val response = mock[HttpServletResponse]
    f.auth.authenticated = false

    When("we try to attach to the event stream")
    resource.doGet(f.auth.request, response)

    Then("we receive a NotAuthenticated response")
    verify(response).setStatus(f.auth.NotAuthenticatedStatus)
  }

  test("access without authorization is denied") {
    Given("An unauthorized request")
    val f = new Fixture
    val resource = f.streamServlet()
    val response = mock[HttpServletResponse]
    f.auth.authenticated = true
    f.auth.authorized = false

    When("we try to attach to the event stream")
    resource.doGet(f.auth.request, response)

    Then("we receive a Unauthorized response")
    verify(response).setStatus(f.auth.UnauthorizedStatus)
  }

  class Fixture {
    val actor = mock[ActorRef]
    val auth = new TestAuthFixture
    val config = AllConf.withTestConfig("--event_subscriber", "http_callback")
    def streamServlet() = new HttpEventStreamServlet(actor, config, auth.auth, auth.auth)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:49,代码来源:HttpEventStreamServletTest.scala


示例5: HttpEventSSEHandleTest

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

import java.util.Collections
import javax.servlet.http.HttpServletRequest

import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import org.eclipse.jetty.servlets.EventSource.Emitter
import org.scalatest.{ GivenWhenThen, Matchers }
import mesosphere.marathon.stream._

class HttpEventSSEHandleTest extends MarathonSpec with Matchers with Mockito with GivenWhenThen {

  test("events should be filtered") {
    Given("An emiter")
    val emitter = mock[Emitter]
    Given("An request with params")
    val req = mock[HttpServletRequest]
    req.getParameterMap returns Map("event_type" -> Array("xyz"))

    Given("handler for request is created")
    val handle = new HttpEventSSEHandle(req, emitter)

    When("Want to sent unwanted event")
    handle.sendEvent("any event", "")

    Then("event should NOT be sent")
    verify(emitter, never).event("any event", "")

    When("Want to sent subscribed event")
    handle.sendEvent("xyz", "")

    Then("event should be sent")
    verify(emitter).event("xyz", "")
  }

  test("events should NOT be filtered") {
    Given("An emiter")
    val emitter = mock[Emitter]

    Given("An request without params")
    val req = mock[HttpServletRequest]
    req.getParameterMap returns Collections.emptyMap()

    Given("handler for request is created")
    val handle = new HttpEventSSEHandle(req, emitter)

    When("Want to sent event")
    handle.sendEvent("any event", "")
    Then("event should NOT be sent")

    verify(emitter).event("any event", "")
    When("Want to sent event")

    handle.sendEvent("xyz", "")

    Then("event should be sent")
    verify(emitter).event("xyz", "")
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:61,代码来源:HttpEventSSEHandleTest.scala


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


示例7: ReadinessCheckSerializerTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.state

import mesosphere.marathon.core.readiness.ReadinessCheckTestHelper
import org.scalatest.{ GivenWhenThen, Matchers, FunSuite }
import mesosphere.marathon.Protos

class ReadinessCheckSerializerTest extends FunSuite with Matchers with GivenWhenThen {
  test("get defaultHttp for empty protobuf") {
    Given("an empty protobuf")
    val proto = Protos.ReadinessCheckDefinition.getDefaultInstance
    When("reading it")
    val check = ReadinessCheckSerializer.fromProto(proto)
    Then("we get the defaults")
    check should equal(ReadinessCheckTestHelper.defaultHttp)
  }

  test("defaultHttp example serialized/deserializes") {
    Given("a defaultHttp readinessCheck")
    val defaultHttp = ReadinessCheckTestHelper.defaultHttp
    When("serializing it to a proto")
    val proto = ReadinessCheckSerializer.toProto(defaultHttp)
    And("deserializing it again")
    val reread = ReadinessCheckSerializer.fromProto(proto)
    Then("we get the original check back")
    reread should equal(defaultHttp)
  }

  test("alternativeHttps example serialized/deserializes") {
    Given("a alternativeHttps readinessCheck")
    val alternativeHttps = ReadinessCheckTestHelper.alternativeHttps
    When("serializing it to a proto")
    val proto = ReadinessCheckSerializer.toProto(alternativeHttps)
    And("deserializing it again")
    val reread = ReadinessCheckSerializer.fromProto(proto)
    Then("we get the original check back")
    reread should equal(alternativeHttps)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:39,代码来源:ReadinessCheckSerializerTest.scala


示例8: MarathonTaskTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.state

import com.google.common.collect.Lists
import mesosphere.marathon.Protos.MarathonTask
import mesosphere.marathon.test.MarathonSpec
import org.scalatest.{ GivenWhenThen, Matchers }

class MarathonTaskTest extends MarathonSpec with GivenWhenThen with Matchers {

  test("toProto returns the encapsulated MarathonTask") {
    Given("A state created from a task")
    val encapsulatedTask = makeTask("app/dummy", 42000, version = Some("123"))
    val state = MarathonTaskState(encapsulatedTask)

    When("We call the toProto function")
    val proto = state.toProto

    Then("The returned proto equals the one passed in")
    proto shouldEqual encapsulatedTask
  }

  test("mergeFromProto returns a sane instance") {
    Given("A state created from a task with version")
    val dummy = makeTask("app/dummy", 42000, version = Some("123"))
    val dummyState = MarathonTaskState(dummy)

    When("We call the mergeFromProto function on that state")
    val proto = makeTask("app/foo", 23000, version = None)
    val merged = dummyState.mergeFromProto(proto)

    Then("The 'merged' state does not have a version because mergeFromProto does not merge but create a new instance based on the given proto")
    merged.toProto shouldEqual proto
  }

  test("mergeFromProto bytes returns a sane instance") {
    Given("A state created from a task with version")
    val dummy = makeTask("app/dummy", 42000, version = Some("123"))
    val dummyState = MarathonTaskState(dummy)

    When("We call the mergeFromProto function using a byte array")
    val proto = makeTask("app/foo", 23000, version = None)
    val merged = dummyState.mergeFromProto(proto.toByteArray)

    Then("The 'merged' state does not have a version because mergeFromProto does not merge but cerate a new instance based on the given proto")
    merged.toProto shouldEqual proto
  }

  private[this] def makeTask(id: String, port: Int, version: Option[String]) = {
    val builder = MarathonTask.newBuilder()
      .addAllPorts(Lists.newArrayList(port))
      .setId(id)

    version.map(builder.setVersion)
    builder.setCondition(MarathonTask.Condition.Staging)

    builder.build()
  }

} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:60,代码来源:MarathonTaskTest.scala


示例9: IOTest

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

import mesosphere.marathon.test.MarathonSpec
import org.scalatest.{ GivenWhenThen, Matchers }

class IOTest extends MarathonSpec with GivenWhenThen with Matchers {

  test("Compress / unCompress works") {
    Given("A byte array")
    val hello = 1.to(100).map(num => s"Hello number $num!").mkString(", ").getBytes("UTF-8")

    When("compress and decompress")
    val compressed = IO.gzipCompress(hello)
    val uncompressed = IO.gzipUncompress(compressed)

    Then("compressed is smaller and round trip works")
    compressed.length should be < uncompressed.length
    uncompressed should be(hello)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:21,代码来源:IOTest.scala


示例10: ReadinessCheckResultFormatTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.v2.json

import mesosphere.marathon.api.JsonTestHelper
import mesosphere.marathon.core.readiness.{ HttpResponse, ReadinessCheckResult }
import mesosphere.marathon.core.task.Task
import org.scalatest.{ FunSuite, GivenWhenThen, Matchers }
import play.api.libs.json.Json

class ReadinessCheckResultFormatTest extends FunSuite with Matchers with GivenWhenThen {
  import Formats._

  test("ReadinessCheckResult is convertible to JSON") {
    JsonTestHelper.assertThatJsonOf(Fixture.readinessCheckResult).correspondsToJsonString(Fixture.readinessCheckJson)
  }

  test("ReadinessCheckResult is readable from JSON") {
    val readinessCheckResult = Json.parse(Fixture.readinessCheckJson).as[ReadinessCheckResult]

    readinessCheckResult should equal(Fixture.readinessCheckResult)
  }

  object Fixture {
    val httpResponse = HttpResponse(200, "application/json", "{}")
    val readinessCheckResult = ReadinessCheckResult(
      "readinessCheck",
      Task.Id("/foo/bar"),
      ready = true,
      Some(httpResponse))

    val readinessCheckJson =
      """
        |{
        |  "name": "readinessCheck",
        |  "taskId": "/foo/bar",
        |  "ready": true,
        |  "lastResponse": {
        |    "contentType": "application/json",
        |    "status": 200,
        |    "body": "{}"
        |  }
        |}
      """.stripMargin
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:45,代码来源:ReadinessCheckResultFormatTest.scala


示例11: LeaderResourceTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.v2

import mesosphere.marathon._
import mesosphere.marathon.api.TestAuthFixture
import mesosphere.marathon.core.election.ElectionService
import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import org.scalatest.{ GivenWhenThen, Matchers }

class LeaderResourceTest extends MarathonSpec with Matchers with Mockito with GivenWhenThen {

  test("access without authentication is denied") {
    Given("An unauthenticated request")
    val f = new Fixture
    val resource = f.leaderResource()
    f.auth.authenticated = false

    When("we try to get the leader info")
    val index = resource.index(f.auth.request)
    Then("we receive a NotAuthenticated response")
    index.getStatus should be(f.auth.NotAuthenticatedStatus)

    When("we try to delete the current leader")
    val delete = resource.delete(f.auth.request)
    Then("we receive a NotAuthenticated response")
    delete.getStatus should be(f.auth.NotAuthenticatedStatus)
  }

  test("access without authorization is denied") {
    Given("An unauthenticated request")
    val f = new Fixture
    val resource = f.leaderResource()
    f.auth.authenticated = true
    f.auth.authorized = false

    When("we try to get the leader info")
    val index = resource.index(f.auth.request)
    Then("we receive a Unauthorized response")
    index.getStatus should be(f.auth.UnauthorizedStatus)

    When("we try to delete the current leader")
    val delete = resource.delete(f.auth.request)
    Then("we receive a Unauthorized response")
    delete.getStatus should be(f.auth.UnauthorizedStatus)
  }

  class Fixture {
    val schedulerService = mock[MarathonSchedulerService]
    val electionService = mock[ElectionService]
    val auth = new TestAuthFixture
    val config = AllConf.withTestConfig("--event_subscriber", "http_callback")
    def leaderResource() = new LeaderResource(electionService, config, auth.auth, auth.auth)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:54,代码来源:LeaderResourceTest.scala


示例12: InfoResourceTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.v2

import mesosphere.chaos.http.HttpConf
import mesosphere.marathon.api.TestAuthFixture
import mesosphere.marathon.core.election.ElectionService
import mesosphere.marathon.storage.repository.FrameworkIdRepository
import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import mesosphere.marathon.MarathonConf
import mesosphere.util.state.MesosLeaderInfo
import org.scalatest.{ GivenWhenThen, Matchers }

class InfoResourceTest extends MarathonSpec with Matchers with Mockito with GivenWhenThen {

  test("access without authentication is denied") {
    Given("An unauthenticated request")
    val f = new Fixture
    val resource = f.infoResource()
    f.auth.authenticated = false

    When("we try to fetch the info")
    val index = resource.index(f.auth.request)

    Then("we receive a NotAuthenticated response")
    index.getStatus should be(f.auth.NotAuthenticatedStatus)
  }

  test("access without authorization is denied") {
    Given("An unauthorized request")
    val f = new Fixture
    val resource = f.infoResource()
    f.auth.authenticated = true
    f.auth.authorized = false

    When("we try to fetch the info")
    val index = resource.index(f.auth.request)

    Then("we receive a NotAuthenticated response")
    index.getStatus should be(f.auth.UnauthorizedStatus)
  }

  class Fixture {
    val leaderInfo = mock[MesosLeaderInfo]
    val electionService = mock[ElectionService]
    val auth = new TestAuthFixture
    val config = mock[MarathonConf with HttpConf]
    val frameworkIdRepository = mock[FrameworkIdRepository]

    def infoResource() = new InfoResource(leaderInfo, frameworkIdRepository, electionService, auth.auth, auth.auth, config)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:51,代码来源:InfoResourceTest.scala


示例13: AppDefinitionMesosHealthCheckValidationTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.validation

import mesosphere.marathon.core.health.{ HealthCheck, MarathonHttpHealthCheck, MesosCommandHealthCheck, MesosHttpHealthCheck }
import mesosphere.marathon.core.plugin.PluginManager
import mesosphere.marathon.state._
import mesosphere.marathon.test.MarathonSpec
import org.scalatest.{ GivenWhenThen, Matchers }

class AppDefinitionMesosHealthCheckValidationTest extends MarathonSpec with Matchers with GivenWhenThen {

  lazy val validAppDefinition = AppDefinition.validAppDefinition(Set.empty)(PluginManager.None)

  test("app with 0 Mesos health checks is valid") {
    val f = new Fixture
    Given("an app with only Marathon Health Checks")
    val app = f.app()

    Then("the app is considered valid")
    validAppDefinition(app).isSuccess shouldBe true
  }

  test("app with 1 Mesos health check is valid") {
    val f = new Fixture
    Given("an app with one health check")
    val app = f.app(healthChecks = Set(MesosCommandHealthCheck(command = Command("true"))))

    Then("the app is considered valid")
    validAppDefinition(app).isSuccess shouldBe true
  }

  test("app with more than 1 non-command Mesos health check is invalid") {
    val f = new Fixture
    Given("an app with one health check")
    val app = f.app(healthChecks = Set(MesosHttpHealthCheck(port = Some(80)), MesosHttpHealthCheck()))

    Then("the app is considered invalid")
    validAppDefinition(app).isFailure shouldBe true
  }

  test("app with more than 1 command Mesos health check is valid") {
    val f = new Fixture
    Given("an app with one health check")
    val app = f.app(healthChecks = Set(
      MesosCommandHealthCheck(command = Command("true")),
      MesosCommandHealthCheck(command = Command("true"))))

    Then("the app is considered valid")
    validAppDefinition(app).isSuccess shouldBe true
  }

  class Fixture {
    def app(healthChecks: Set[_ <: HealthCheck] = Set(MarathonHttpHealthCheck())): AppDefinition =
      AppDefinition(
        id = PathId("/test"),
        cmd = Some("sleep 1000"),
        instances = 1,
        healthChecks = healthChecks
      )
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:61,代码来源:AppDefinitionMesosHealthCheckValidationTest.scala


示例14: InstanceOpFactoryHelperTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.tasks

import mesosphere.marathon.core.instance.TestInstanceBuilder
import mesosphere.marathon.core.instance.update.InstanceUpdateOperation
import mesosphere.marathon.core.launcher.impl.InstanceOpFactoryHelper
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.state.PathId
import mesosphere.marathon.test.{ MarathonSpec, MarathonTestHelper, Mockito }
import org.apache.mesos.{ Protos => Mesos }
import org.scalatest.{ GivenWhenThen, Matchers }

class InstanceOpFactoryHelperTest extends MarathonSpec with GivenWhenThen with Mockito with Matchers {

  test("exception when newTask.taskId and taskInfo.id don't match") {
    val f = new Fixture

    Given("A non-matching task and taskInfo")
    val builder = TestInstanceBuilder.newBuilderWithLaunchedTask(f.runSpecId)
    val task: Task.LaunchedEphemeral = builder.pickFirstTask()
    val taskInfo = MarathonTestHelper.makeOneCPUTask(Task.Id.forRunSpec(f.runSpecId)).build()

    When("We create a launch operation")
    val error = intercept[AssertionError] {
      f.helper.launchEphemeral(taskInfo, task, builder.getInstance())
    }

    Then("An exception is thrown")
    error.getMessage shouldEqual "assumption failed: marathon task id and mesos task id must be equal"
  }

  test("Create a launch TaskOp") {
    val f = new Fixture

    Given("a task and a taskInfo")
    val builder = TestInstanceBuilder.newBuilderWithLaunchedTask(f.runSpecId)
    val instance = builder.getInstance()
    val task: Task.LaunchedEphemeral = builder.pickFirstTask()
    val taskInfo = MarathonTestHelper.makeOneCPUTask(task.taskId).build()

    When("We create a launch operation")
    val launch = f.helper.launchEphemeral(taskInfo, task, instance)

    Then("The result is as expected")
    launch.stateOp shouldEqual InstanceUpdateOperation.LaunchEphemeral(instance)
    launch.taskInfo shouldEqual taskInfo
    launch.oldInstance shouldBe empty
    launch.offerOperations should have size 1
    launch.offerOperations.head.getType shouldEqual Mesos.Offer.Operation.Type.LAUNCH
  }

  class Fixture {
    val runSpecId = PathId("/test")
    val helper = new InstanceOpFactoryHelper(Some("principal"), Some("role"))
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:56,代码来源:InstanceOpFactoryHelperTest.scala


示例15: ResourceMatchTest

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

import mesosphere.marathon.tasks.{ PortsMatch, PortsMatcher }
import mesosphere.marathon.test.MarathonTestHelper
import org.scalatest.{ FunSuite, GivenWhenThen, Matchers }

import scala.collection.immutable.Seq

class ResourceMatchTest
    extends FunSuite with GivenWhenThen with Matchers {
  test("resources include all matched reservations") {
    Given("a resource match with reservations")
    val memReservation = MarathonTestHelper.reservation(principal = "memPrincipal", labels = Map("resource" -> "mem"))
    val portReservation = MarathonTestHelper.reservation(principal = "portPrincipal", labels = Map("resource" -> "ports"))

    val resourceMatch = ResourceMatcher.ResourceMatch(
      scalarMatches = Seq(
        GeneralScalarMatch(
          "mem", 128.0,
          consumed = Seq(GeneralScalarMatch.Consumption(128.0, "role1", reservation = Some(memReservation))),
          scope = ScalarMatchResult.Scope.NoneDisk
        )
      ),
      portsMatch = PortsMatch(Seq(Some(PortsMatcher.PortWithRole("role2", 80, reservation = Some(portReservation)))))
    )

    When("converting it to resources")
    val resources = resourceMatch.resources

    Then("the resources should refer to the reservations")
    resources should equal(
      Seq(
        MarathonTestHelper.scalarResource("mem", 128, "role1", reservation = Some(memReservation)),
        MarathonTestHelper.portsResource(80, 80, "role2", reservation = Some(portReservation))
      )
    )
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:39,代码来源:ResourceMatchTest.scala


示例16: PersistentVolumeValidationTest

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

import com.wix.accord._
import mesosphere.marathon.state.{ PersistentVolume, PersistentVolumeInfo, Volume }
import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import org.apache.mesos
import org.scalatest.{ GivenWhenThen, Matchers }

class PersistentVolumeValidationTest extends MarathonSpec with GivenWhenThen with Mockito with Matchers {

  test("create a PersistentVolume with no validation violations") {
    Given("a PersistentVolume with no validation violations")
    val path = "path"
    val volume = PersistentVolume(path, PersistentVolumeInfo(1), mesos.Protos.Volume.Mode.RW)

    When("The volume is created and validation succeeded")
    volume should not be null
    val validation = Volume.validVolume(Set())(volume)

    Then("A validation exists with no error message")
    validation.isSuccess should be (true)
  }

  test("create a PersistentVolume with validation violation in containerPath") {
    Given("a PersistentVolume with validation violation in containerPath")
    val path = "/path"
    val volume = PersistentVolume(path, PersistentVolumeInfo(1), mesos.Protos.Volume.Mode.RW)

    When("The volume is created and validation failed")
    volume should not be null
    volume.containerPath should be (path)
    val validation = Volume.validVolume(Set())(volume)
    validation.isSuccess should be (false)

    Then("A validation exists with a readable error message")
    validation match {
      case Failure(violations) =>
        violations should contain (RuleViolation("/path", "value must not contain \"/\"", Some("containerPath")))
      case Success =>
        fail("validation should fail!")
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:44,代码来源:PersistentVolumeValidationTest.scala


示例17: ByIdPredicateTest

//设置package包名称以及导入依赖的类
package ml.sparkling.graph.operators.predicates

import org.scalatest.{FlatSpec, GivenWhenThen}


class ByIdPredicateTest extends FlatSpec with GivenWhenThen {

  "True" should "be returned if correct id is given" in{
    Given("Vertex id and predicate")
    val vertexId=1l
    val predicate=ByIdPredicate(vertexId)
    When("Checked")
    val checkResult: Boolean = predicate.apply(vertexId)
    Then("should return true")
    assert(checkResult)
  }

  "False" should "be returned if incorrect id is given" in{
    Given("Vertex id and predicate")
    val vertexId=1l
    val predicate=ByIdPredicate(vertexId)
    When("Checked")
    val checkResult: Boolean = predicate.apply(2*vertexId)
    Then("should return false")
    assert(!checkResult)
  }

} 
开发者ID:sparkling-graph,项目名称:sparkling-graph,代码行数:29,代码来源:ByIdPredicateTest.scala


示例18: VertexMeasureConfigurationTest

//设置package包名称以及导入依赖的类
package ml.sparkling.graph.api.operators.measures

import ml.sparkling.graph.api.operators.IterativeComputation.BucketSizeProvider
import org.apache.spark.graphx.Graph
import org.scalatest.{FlatSpec, GivenWhenThen}



class VertexMeasureConfigurationTest extends FlatSpec with GivenWhenThen  {

  "Creation without parameters" should "be possible" in{
    VertexMeasureConfiguration()
  }

  "Creation with undirected flag" should "be possible" in{
    Given("Directed flag")
    val flag=false
    When("Configuration creation")
    VertexMeasureConfiguration(treatAsUndirected = flag )
  }

  "Creation with bucket size provider" should "be possible" in{
    Given("Bucker size provider")
    val provider:BucketSizeProvider[Long,Long]=(g:Graph[Long,Long])=>1l
    When("Configuration creation")
    VertexMeasureConfiguration(bucketSizeProvider = provider)
  }

  "Creation with bucket size provider and directed flag" should "be possible" in{
    Given("Bucker size provider")
    val provider:BucketSizeProvider[Long,Long]=(g:Graph[Long,Long])=>1l
    When("Configuration creation")
    VertexMeasureConfiguration( false, provider)
  }
} 
开发者ID:sparkling-graph,项目名称:sparkling-graph,代码行数:36,代码来源:VertexMeasureConfigurationTest.scala


示例19: ReadFromFileSpec

//设置package包名称以及导入依赖的类
import org.scalatest.{FeatureSpec, GivenWhenThen}


class ReadFromFileSpec extends FeatureSpec with GivenWhenThen {

  info("As a user from PSP1")
  info("I want to calculate the mean of a file compound by decimal numbers")
  info("So I don't have to type them manually")
  info("And save my time")

  feature("Calculate mean") {
    scenario("User sends a file with the numbers, one per line") {
      val fileName = getClass.getResource("test.txt").getFile
      Given("the file is not empty")
      assert(scala.io.Source.fromFile(fileName).getLines().nonEmpty)
      Given("the file has just numbers")
      assert(!scala.io.Source.fromFile(fileName).getLines().exists(!ReadFromFile.isAllDigits(_)))
      When("the mean is calculated for that file")
      val list = ReadFromFile.getListFromFile(fileName)
      val mean = list.mean
      Then("the result should be a decimal number")
      assert(mean.isInstanceOf[Double])
    }
  }
} 
开发者ID:camilosampedro,项目名称:PSP-TDD,代码行数:26,代码来源:ReadFromFileSpec.scala


示例20: IotHubSinkConnectorTest

//设置package包名称以及导入依赖的类
package com.microsoft.azure.iot.kafka.connect.sink

import com.microsoft.azure.iot.kafka.connect.source.JsonSerialization
import com.microsoft.azure.iot.kafka.connect.sink.testhelpers.SinkTestConfig
import org.apache.kafka.connect.errors.ConnectException
import org.scalatest.{FlatSpec, GivenWhenThen}

class IotHubSinkConnectorTest extends FlatSpec with GivenWhenThen with JsonSerialization {

  "IotHubSinkConnector" should "validate all input properties and generate right set of task config properties" in {
    Given("Valid set of input properties")
    val inputProperties1 = SinkTestConfig.sinkConnectorTestProps
    var connector = new IotHubSinkConnector

    When("Start and TaskConfig are called in right order")
    connector.start(inputProperties1)

    Then("The TaskConfigs have all the expected properties")
    var taskConfigs = connector.taskConfigs(2)
    assert(taskConfigs.size() == 2)
    for (i <- 0 until 2) {
      val taskConfig: java.util.Map[String, String] = taskConfigs.get(i)
      assert(taskConfig.containsKey(IotHubSinkConfig.IotHubConnectionString))
    }

    Given("Valid set of input properties")
    val inputProperties2 = SinkTestConfig.sinkConnectorTestProps2
    connector = new IotHubSinkConnector

    When("Start and TaskConfig are called in right order")
    connector.start(inputProperties2)

    Then("The TaskConfigs have all the expected properties")
    taskConfigs = connector.taskConfigs(2)
    assert(taskConfigs.size() == 2)
    for (i <- 0 until 2) {
      val taskConfig: java.util.Map[String, String] = taskConfigs.get(i)
      assert(taskConfig.containsKey(IotHubSinkConfig.IotHubConnectionString))
    }
  }

  it should "throw an exception if invalid config properties are supplied" in {
    Given("Input properties without the required values values")
    val inputPropertiesWithoutRequiredValues = SinkTestConfig.invalidSinkConnectorTestProps
    var connector = new IotHubSinkConnector

    When("Connector.Start throws a ConnectException")
    intercept[ConnectException] {
      connector.start(inputPropertiesWithoutRequiredValues)
    }

    Given("Input properties with invalid values")
    val inputPropertiesWithInvalidValue = SinkTestConfig.invalidSinkConnectorTestProps2
    connector = new IotHubSinkConnector

    When("Connector.Start throws a ConnectException")
    intercept[ConnectException] {
      connector.start(inputPropertiesWithInvalidValue)
    }
  }
} 
开发者ID:Azure,项目名称:toketi-kafka-connect-iothub,代码行数:62,代码来源:IotHubSinkConnectorTest.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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