本文整理汇总了Scala中org.scalatest.WordSpec类的典型用法代码示例。如果您正苦于以下问题:Scala WordSpec类的具体用法?Scala WordSpec怎么用?Scala WordSpec使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WordSpec类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: SparkServicesSpec
//设置package包名称以及导入依赖的类
package com.knoldus.couchbaseServices
import java.util.UUID
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.couchbase.client.java.document.json.JsonObject
import com.knoldus.couchbaseServices.routes.SparkService
import org.scalatest.{Matchers, WordSpec}
class SparkServicesSpec extends WordSpec with Matchers with ScalatestRouteTest with SparkService {
val documentId = "user::" + UUID.randomUUID().toString
val jsonObject = JsonObject.create().put("name", "Shivansh").put("email", "[email protected]")
val jsonDocument = persistOrUpdate(documentId, jsonObject)
"The service" should {
"be able to insert data in the couchbase" in {
Get("/insert/name/Shivansh/email/[email protected]") ~> sparkRoutes ~> check {
responseAs[String].contains("Data is successfully persisted with id") shouldEqual true
}
}
"to be able to retrieve data via N1Ql" in {
Get("/getViaN1Ql/name/Shivansh") ~> sparkRoutes ~> check {
responseAs[String].contains("[email protected]") shouldEqual true
}
}
"be able to retrieve data via View query" in {
Get("/getViaView/name/Shivansh") ~> sparkRoutes ~> check {
responseAs[String].contains("[email protected]") shouldEqual true
}
}
"be able to retrieve data via KV operation" in {
Get(s"/getViaKV/id/$documentId") ~> sparkRoutes ~> check {
responseAs[String].contains("[email protected]") shouldEqual true
}
}
"be able to update data via KV operation" in {
Get(s"/updateViaKV/name/Shivansh/email/[email protected]/id/$documentId") ~> sparkRoutes ~> check {
responseAs[String].contains("Data is successfully persisted with id") shouldEqual true
}
}
}
}
示例2: ConsoleTableReportFormatterTest
//设置package包名称以及导入依赖的类
package com.github.unknownnpc.remotedebugtool.report
import com.github.unknownnpc.remotedebugtool.domain.JvmReportRow
import org.scalatest.{Matchers, WordSpec}
class ConsoleTableReportFormatterTest extends WordSpec with Matchers {
private val validTable = "\n\n" +
"+--+---------+----+----------+---------------+--------------+" + "\n" +
"|ID| Address|Port|Class name|Breakpoint line| JVM value|" + "\n" +
"| 2|127.0.0.1|8080| | | |" + "\n" +
"| | | |ClassNameC| 15|magic result C|" + "\n" +
"| | | |ClassNameD| 19|magic result D|" + "\n" +
"| | | |ClassNameE| 20|magic result E|" + "\n" +
"| 1|localhost|8080| | | |" + "\n" +
"| | | |ClassNameA| 13|magic result A|" + "\n" +
"| | | |ClassNameB| 14|magic result B|" + "\n" +
"+--+---------+----+----------+---------------+--------------+" + "\n\n"
private val emptyTable = "\n\n" +
"+--+-------+----+----------+---------------+---------+" + "\n" +
"|ID|Address|Port|Class name|Breakpoint line|JVM value|" + "\n" +
"+--+-------+----+----------+---------------+---------+" + "\n\n"
"ConsoleTableReportFormatter" should {
"build valid table for several report rows" in {
val reportRows = List(
JvmReportRow(1, "localhost", 8080, 13, "ClassNameA", "magic result A"),
JvmReportRow(1, "localhost", 8080, 14, "ClassNameB", "magic result B"),
JvmReportRow(2, "127.0.0.1", 8080, 15, "ClassNameC", "magic result C"),
JvmReportRow(2, "127.0.0.1", 8080, 19, "ClassNameD", "magic result D"),
JvmReportRow(2, "127.0.0.1", 8080, 20, "ClassNameE", "magic result E")
)
val result = ConsoleTableReportFormatter.format(reportRows)
result should equal(validTable)
}
"print empty string if nothing to do" in {
val reportRows = List.empty
val result = ConsoleTableReportFormatter.format(reportRows)
result should equal(emptyTable)
}
}
}
示例3: MetricNumericConverterSpec
//设置package包名称以及导入依赖的类
package akka.cluster
import org.scalatest.WordSpec
import org.scalatest.Matchers
import akka.cluster.StandardMetrics._
import scala.util.Failure
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class MetricNumericConverterSpec extends WordSpec with Matchers with MetricNumericConverter {
"MetricNumericConverter" must {
"convert" in {
convertNumber(0).isLeft should be(true)
convertNumber(1).left.get should be(1)
convertNumber(1L).isLeft should be(true)
convertNumber(0.0).isRight should be(true)
}
"define a new metric" in {
val Some(metric) = Metric.create(HeapMemoryUsed, 256L, decayFactor = Some(0.18))
metric.name should be(HeapMemoryUsed)
metric.value should be(256L)
metric.isSmooth should be(true)
metric.smoothValue should be(256.0 +- 0.0001)
}
"define an undefined value with a None " in {
Metric.create("x", -1, None).isDefined should be(false)
Metric.create("x", java.lang.Double.NaN, None).isDefined should be(false)
Metric.create("x", Failure(new RuntimeException), None).isDefined should be(false)
}
"recognize whether a metric value is defined" in {
defined(0) should be(true)
defined(0.0) should be(true)
}
"recognize whether a metric value is not defined" in {
defined(-1) should be(false)
defined(-1.0) should be(false)
defined(Double.NaN) should be(false)
}
}
}
示例4: DefaultTimeoutSpec
//设置package包名称以及导入依赖的类
package akka.testkit
import org.scalatest.{ WordSpec, BeforeAndAfterAll }
import org.scalatest.Matchers
import akka.actor.ActorSystem
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class DefaultTimeoutSpec
extends WordSpec with Matchers with BeforeAndAfterAll with TestKitBase with DefaultTimeout {
implicit lazy val system = ActorSystem("AkkaCustomSpec")
override def afterAll = system.shutdown
"A spec with DefaultTimeout" should {
"use timeout from settings" in {
timeout should be(testKitSettings.DefaultTimeout)
}
}
}
示例5: PersistenceSerializerDocSpec
//设置package包名称以及导入依赖的类
package docs.persistence
import com.typesafe.config._
import scala.concurrent.duration._
import org.scalatest.WordSpec
import akka.actor.ActorSystem
import akka.serialization.{ Serializer, SerializationExtension }
import akka.testkit.TestKit
class PersistenceSerializerDocSpec extends WordSpec {
val customSerializerConfig =
"""
//#custom-serializer-config
akka.actor {
serializers {
my-payload = "docs.persistence.MyPayloadSerializer"
my-snapshot = "docs.persistence.MySnapshotSerializer"
}
serialization-bindings {
"docs.persistence.MyPayload" = my-payload
"docs.persistence.MySnapshot" = my-snapshot
}
}
//#custom-serializer-config
""".stripMargin
val system = ActorSystem("PersistenceSerializerDocSpec", ConfigFactory.parseString(customSerializerConfig))
try {
SerializationExtension(system)
} finally {
TestKit.shutdownActorSystem(system, 10.seconds, false)
}
}
class MyPayload
class MySnapshot
class MyPayloadSerializer extends Serializer {
def identifier: Int = 77124
def includeManifest: Boolean = false
def toBinary(o: AnyRef): Array[Byte] = ???
def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = ???
}
class MySnapshotSerializer extends Serializer {
def identifier: Int = 77125
def includeManifest: Boolean = false
def toBinary(o: AnyRef): Array[Byte] = ???
def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = ???
}
示例6: SplunkHecClientTest
//设置package包名称以及导入依赖的类
package io.policarp.logback.hec
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.LayoutBase
import io.policarp.logback.MockLoggingEvent
import org.scalatest.{ Matchers, WordSpec }
class SplunkHecClientTest extends WordSpec with Matchers {
val layout = new LayoutBase[ILoggingEvent] {
override def doLayout(event: ILoggingEvent): String = event.getMessage
}
"The Object" should {
"prepare layouts in a line separated format" in {
import SplunkHecClient.formatJsonEvents
formatJsonEvents(Seq(), layout) shouldBe None
val event1 = MockLoggingEvent("SomeClass", "test 1", Level.DEBUG)
val event2 = MockLoggingEvent("SomeClass", "test 2", Level.DEBUG)
formatJsonEvents(Seq(event1, event2), layout) shouldBe Some("test 1\n\ntest 2")
formatJsonEvents(Seq(event1), layout) shouldBe Some("test 1")
formatJsonEvents(Seq(event2), layout) shouldBe Some("test 2")
}
}
}
示例7: MethodDDirectivesSpec
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl
import DDirectives._
import akka.http.documenteddsl.documentation.RouteDocumentation
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec
class MethodDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {
private def check(m: MethodDDirective): Unit = m.toString must {
"be applied to documentation" in {
m.describe(RouteDocumentation()).method mustBe Some(m.toString)
}
"be counted during request handling" in {
val route = m {complete("ok")}
Get() ~> route ~> check {handled must be (m == GET)}
Post() ~> route ~> check {handled must be (m == POST)}
Delete() ~> route ~> check {handled must be (m == DELETE)}
Put() ~> route ~> check {handled must be (m == PUT)}
Head() ~> route ~> check {handled must be (m == HEAD)}
Options() ~> route ~> check {handled must be (m == OPTIONS)}
Patch() ~> route ~> check {handled must be (m == PATCH)}
}
}
check(GET)
check(POST)
check(DELETE)
check(PUT)
check(HEAD)
check(OPTIONS)
check(PATCH)
}
示例8: ParameterDDirectivesSpec
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl
import DDirectives._
import akka.http.documenteddsl.documentation.{JsonSchema, ParamDocumentation, RouteDocumentation}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec
class ParameterDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {
"Param" must {
"be applied to route documentation" in {
Param[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
name = "xxx",
schema = JsonSchema.string,
required = true,
origin = ParamDocumentation.Origin.Query)))
}
"be counted during request processing" in {
val route = Param[String]("xxx") apply {x => complete(s"$x")}
Get("/?xxx=zzz") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "zzz"}
}
"be preprocessed" in {
implicit val preprocess = new Preprocess[String] {
override def apply(x: String): String = 11 + x
}
val route = Param[String]("xxx") apply {x => complete(s"$x")}
Get("/?xxx=zzz") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "11zzz"}
}
}
"OptParam" must {
"be applied to route documentation" in {
OptParam[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
name = "xxx",
schema = JsonSchema.string,
required = false,
origin = ParamDocumentation.Origin.Query)))
}
"be counted during request processing" in {
val route = OptParam[String]("xxx") apply {x => complete(s"$x")}
Get("/?xxx=zzz") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "Some(zzz)"}
Get("/") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "None"}
}
}
}
示例9: UnmarshallingDDirectivesSpec
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl
import java.time.LocalDate
import akka.http.documenteddsl.directives.UnmarshallingDDirectives._
import akka.http.documenteddsl.documentation.OutDocumentation._
import akka.http.documenteddsl.documentation.{JsonSchema, OutDocumentation, RouteDocumentation}
import akka.http.scaladsl.model.{ContentTypes, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec
import play.api.libs.json.{Format, Json}
class UnmarshallingDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {
import UnmarshallingDDirectivesSpec._
"Out" must {
val now = LocalDate.now()
"be applied to route documentation" in {
Out[TestOut].describe(RouteDocumentation()).out mustBe Some(OutDocumentation(
success = List(
Payload.Success(
status = Status(StatusCodes.OK),
contentType = "application/json",
schema = JsonSchema.resolveSchema[TestOut],
example = None))))
}
"be applied to route documentation (concatenated)" in {
val out = Out(StatusCodes.Created, TestOut("id", Some("name"), now)) & Out(StatusCodes.NotFound, "entity not found")
out.describe(RouteDocumentation()).out mustBe Some(OutDocumentation(
failure = List(
Payload.Failure(
status = Status(StatusCodes.NotFound),
contentType = None,
description = Some("entity not found"))),
success = List(
Payload.Success(
status = Status(StatusCodes.Created),
contentType = "application/json",
schema = JsonSchema.resolveSchema[TestOut],
example = Some(Json toJson TestOut("id", Some("name"), now))))))
}
}
}
object UnmarshallingDDirectivesSpec {
case class TestOut(id: String, name: Option[String], createdAt: LocalDate)
implicit val testInFormat: Format[TestOut] = Json.format[TestOut]
}
示例10: DocumentationDDirectivesSpec
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl
import akka.http.documenteddsl.directives.DocumentationDDirectives._
import akka.http.documenteddsl.documentation.RouteDocumentation
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec
class DocumentationDDirectivesSpec extends WordSpec with DDirectivesSpec {
"Category" must {
"be applied for 1 segment" in {
Category("xxx").describe(RouteDocumentation()).category mustBe Some(List("xxx"))
}
"be applied for N segments" in {
Category("a", "b", "c").describe(RouteDocumentation()).category mustBe Some(List("a", "b", "c"))
}
}
"Title" must {
"be applied" in {
Title("xxx").describe(RouteDocumentation()).title mustBe Some("xxx")
}
}
"Description" must {
"be applied" in {
Description("xxx").describe(RouteDocumentation()).description mustBe Some("xxx")
}
}
}
示例11: FormFieldDDirectivesSpec
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl
import DDirectives._
import akka.http.documenteddsl.documentation.{JsonSchema, ParamDocumentation, RouteDocumentation}
import akka.http.scaladsl.model.FormData
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec
class FormFieldDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {
"FormField" must {
"be applied to route documentation" in {
FormField[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
name = "xxx",
schema = JsonSchema.string,
required = true,
origin = ParamDocumentation.Origin.Form)))
}
"be counted during request processing" in {
val route = FormField[String]("xxx") apply {x => complete(s"$x")}
val formData = FormData("xxx" -> "zzz")
Post("/", formData) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "zzz"}
}
"be preprocessed" in {
implicit val preprocess = new Preprocess[String] {
override def apply(x: String): String = 11 + x
}
val route = FormField[String]("xxx") apply {x => complete(s"$x")}
val formData = FormData("xxx" -> "zzz")
Post("/", formData) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "11zzz"}
}
}
"OptFormField" must {
"be applied to route documentation" in {
OptFormField[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
name = "xxx",
schema = JsonSchema.string,
required = false,
origin = ParamDocumentation.Origin.Form)))
}
"be counted during request processing" in {
val route = OptFormField[String]("xxx") apply {x => complete(s"$x")}
Post("/", FormData("xxx" -> "zzz")) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "Some(zzz)"}
Post("/", FormData()) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "None"}
}
}
}
示例12: IssuesSpec
//设置package包名称以及导入依赖的类
package io.scalaland.chimney
import org.scalatest.{MustMatchers, WordSpec}
import shapeless.HNil
class IssuesSpec extends WordSpec with MustMatchers {
import dsl._
"IssuesSpec" should {
"fix issue #19" in {
case class NewEntity(name: String)
case class Entity(id: Long, name: String, isDeleted: Boolean)
NewEntity("name")
.into[Entity]
.withFieldConst('id, 0L)
.withFieldConst('isDeleted, false)
.transform mustBe
Entity(0, "name", isDeleted = false)
}
"fix issue #21" in {
import shapeless.tag
import shapeless.tag._
sealed trait Test
case class EntityWithTag1(id: Long, name: String @@ Test)
case class EntityWithTag2(name: String @@ Test)
// This test doesn't work on 2.12+ due to:
// https://github.com/milessabin/shapeless/pull/726
// EntityWithTag1(0L, tag[Test]("name")).transformInto[EntityWithTag2] mustBe EntityWithTag2(tag[Test]("name"))
}
}
}
示例13: TapStreamRouteSpec
//设置package包名称以及导入依赖的类
import org.scalatest.{Matchers, WordSpec}
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.server._
import Directives._
import org.goingok.httpServer.{ResponseMessage, GenericApi, GoingOkAPI}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._
class TapStreamRouteSpec extends WordSpec with Matchers with ScalatestRouteTest with GoingOkAPI with Json4sSupport {
"The service" should {
"return a greeting for GET requests to the root path" in {
// tests:
Get() ~> routes ~> check {
responseAs[ResponseMessage].message shouldEqual "The current version of this API can be found at /v1"
}
}
"return an 'ok' message for GET requests to /v1/health" in {
// tests:
Get("/v1/health") ~> routes ~> check {
responseAs[ResponseMessage].message shouldEqual "ok"
}
}
"leave GET requests to other paths unhandled" in {
// tests:
Get("/someOtherPath") ~> routes ~> check {
handled shouldBe false
}
}
"return a MethodNotAllowed error for PUT requests to the root path" in {
// tests:
Put() ~> Route.seal(routes) ~> check {
status === StatusCodes.MethodNotAllowed
import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers.stringUnmarshaller
responseAs[String] shouldEqual "HTTP method not allowed, supported methods: GET"
}
}
}
}
示例14: UsersSpec
//设置package包名称以及导入依赖的类
package models
import _root_.test._
import org.scalatest.Matchers._
import org.scalatest.{ TestData, WordSpec }
import org.scalatestplus.play.OneAppPerTest
import play.api._
class UsersSpec extends WordSpec with OneAppPerTest {
override def newAppForTest(testData: TestData): Application = fakeApp
"Users" should {
"create and find" in {
val users = app.injector.instanceOf(classOf[Users])
val user = users.create(User(0L, "test1", true))
user.id !== 0L
val userFound = users.find(user.id)
userFound shouldBe defined
userFound.foreach(_.name shouldBe "test1")
}
}
}
示例15: RegionsTest
//设置package包名称以及导入依赖的类
package com.wegtam.amws.common
import java.net.URI
import com.wegtam.amws.common.MarketPlaces._
import com.wegtam.amws.common.Regions._
import org.scalatest.prop.PropertyChecks
import org.scalatest.{ MustMatchers, WordSpec }
import scala.collection.immutable.Seq
class RegionsTest extends WordSpec with MustMatchers with PropertyChecks {
private final val expectedEndpoints = Table(
("Region", "Endpoint"),
(NorthAmerica, new URI("https://mws.amazonservices.com")),
(Brazil, new URI("https://mws.amazonservices.com")),
(Europe, new URI("https://mws-eu.amazonservices.com")),
(India, new URI("https://mws.amazonservices.in")),
(China, new URI("https://mws.amazonservices.com.cn")),
(Japan, new URI("https://mws.amazonservices.jp"))
)
private final val expectedMarketplaces = Table(
("Region", "Marketplaces"),
(NorthAmerica, Seq(CA, MX, US)),
(Brazil, Seq(BR)),
(Europe, Seq(DE, ES, FR, IT, UK)),
(India, Seq(IN)),
(China, Seq(CN)),
(Japan, Seq(JP))
)
"endpoint" must {
"return the correct region endpoint" in {
forAll(expectedEndpoints) { (r: Region, u: URI) =>
r.endPoint mustEqual u
}
}
}
"marketPlaces" must {
"return the correct marketplaces for the region" in {
forAll(expectedMarketplaces) { (r: Region, mps: Seq[MarketPlace]) =>
r.marketPlaces mustEqual mps
}
}
}
}