本文整理汇总了Scala中org.scalatest.GivenWhenThen类的典型用法代码示例。如果您正苦于以下问题:Scala GivenWhenThen类的具体用法?Scala GivenWhenThen怎么用?Scala GivenWhenThen使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GivenWhenThen类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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"
}
}
}
示例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])
}
}
}
示例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
}
}
}
}
示例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)
}
}
示例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", "")
}
}
示例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)
}
}
示例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)
}
}
示例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()
}
}
示例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)
}
}
示例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
}
}
示例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)
}
}
示例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)
}
}
示例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
)
}
}
示例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"))
}
}
示例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))
)
)
}
}