本文整理汇总了Scala中org.scalatest.FunSpec类的典型用法代码示例。如果您正苦于以下问题:Scala FunSpec类的具体用法?Scala FunSpec怎么用?Scala FunSpec使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FunSpec类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: ResultWriterTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.commons.output.writers
import java.io.File
import org.mockito.Mockito
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar
import scala.io.Source
class ResultWriterTest extends FunSpec with MockitoSugar {
describe("ResultWriter") {
val mockedResultWriter: ResultWriter = mock[ResultWriter]
it("should filterFilesByPrefix") {
val prefix = "ESB"
val firstResultFile = new File(s"${prefix}_results1.csv")
val secondResultFile = new File(s"${prefix}_results2.csv")
val otherFile = new File("other.csv")
val files = List(firstResultFile, secondResultFile, otherFile)
Mockito.doCallRealMethod().when(mockedResultWriter).filterFilesByPrefix(files, prefix)
val resultfiles = mockedResultWriter.filterFilesByPrefix(files, prefix)
assert(resultfiles.toSet.contains(firstResultFile))
assert(resultfiles.toSet.contains(secondResultFile))
}
it("should getIntermediateResultMaps") {
val csvContent =
"""column1,column2,column3
|value1,value2,value3""".stripMargin
val sources = List(Source.fromString(csvContent),
Source.fromString(csvContent))
Mockito.doCallRealMethod().when(mockedResultWriter).getIntermediateResultMaps(sources)
val resultMaps = mockedResultWriter.getIntermediateResultMaps(sources)
val expectedMap = Map[String, String](
"column1" -> "value1",
"column2" -> "value2",
"column3" -> "value3"
)
resultMaps.foreach(r => assert(r.toSet == expectedMap.toSet))
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:50,代码来源:ResultWriterTest.scala
示例2: RedirectionSpec
//设置package包名称以及导入依赖的类
package com.kurz
import com.kurz.services.RedisConnectionPool
import com.twitter.finagle.http.Status
import io.finch.Input
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}
class RedirectionSpec extends FunSpec with Matchers with BeforeAndAfter {
import com.kurz.Server.redirection
before {
RedisConnectionPool.instance.getResource().del("mb")
RedisConnectionPool.instance.getResource().set("mb", "http://marceloboeira.com")
}
describe ("redirection") {
describe("when the slug exists") {
it("returns with the temporary redirection status") {
redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.TemporaryRedirect)
}
it("returns with the proper header for Location") {
redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.headers) shouldBe Some(Map("Location" -> "http://marceloboeira.com"))
}
}
describe("when the slug does not exist") {
it("returns with the not found status") {
redirection(Input.get("/invalid")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.NotFound)
}
}
}
}
开发者ID:marceloboeira,项目名称:kurz,代码行数:34,代码来源:RedirectionSpec.scala
示例3: withMongoURL
//设置package包名称以及导入依赖的类
package io.scalajs.npm.mongoose
import io.scalajs.nodejs.process
import io.scalajs.npm.mongodb.{Db, MongoClient}
import org.scalatest.FunSpec
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
trait MongoDBTestSupport {
self: FunSpec =>
def withMongoURL[S](block: String => S): Any = {
process.env.get("MONGO_CONNECT") match {
case Some(url) => block(url)
case None =>
info("No MongoDB configuration. Set 'MONGO_CONNECT' (ex. MONGO_CONNECT=mongodb://localhost:27017/test)")
}
}
def withMongo[S](label: String)(block: Db => Future[S])(implicit ec: ExecutionContext): Any = {
process.env.get("MONGO_CONNECT") match {
case None =>
info("No MongoDB configuration. Set 'MONGO_CONNECT' (ex. MONGO_CONNECT=mongodb://localhost:27017/test)")
case Some(url) =>
val outcome = for {
db <- MongoClient.connectFuture(url)
result <- block(db)
} yield (db, result)
outcome onComplete {
case Success((db, _)) =>
info(s"$label: Closing connection....")
db.close()
case Failure(e) =>
throw new IllegalStateException(s"MongoDB connection failure: ${e.getMessage}")
}
}
}
}
开发者ID:scalajs-io,项目名称:mongoose,代码行数:44,代码来源:MongoDBTestSupport.scala
示例4: VarsRendererSpec
//设置package包名称以及导入依赖的类
package eu.tznvy.jancy.transpiler.rendering
import eu.tznvy.jancy.core.Host
import org.scalatest.FunSpec
import scala.collection.JavaConverters._
class VarsRendererSpec extends FunSpec {
describe("The VarsRenderer") {
it("should render vars alphabetically") {
val expected =
"""apacheMaxClients: '900'
|apacheMaxRequestsPerChild: '3000'
|backup: backup-atlanta.example.com
|ntp: ntp-atlanta.example.com
|""".stripMargin
val vars = new Host("h1")
.vars(
Map(
"apacheMaxRequestsPerChild" -> "3000",
"apacheMaxClients" -> "900",
"ntp" -> "ntp-atlanta.example.com",
"backup" -> "backup-atlanta.example.com")
.asJava
.asInstanceOf[java.util.Map[String, AnyRef]])
.getVars
.asScala
.toMap
.toArray[(String, Any)]
val actual = VarsRenderer.renderAll(vars)
assertResult(expected) { actual }
}
}
}
开发者ID:brthanmathwoag,项目名称:jancy,代码行数:40,代码来源:VarsRendererSpec.scala
示例5: TreeMatcherSpec
//设置package包名称以及导入依赖的类
package com.quoininc.treediffing
import org.scalatest.FunSpec
import scala.collection.immutable.Seq
import TreeMatcher.NodeWithMatching
class TreeMatcherSpec extends FunSpec {
describe("TreeMatcher") {
describe("match") {
it("should fully match identical tree") {
val t1 = Node(1, "ROOT", "", Seq(
Node(2, "A", "a", Seq(
Node(3, "A1", "a1"),
Node(4, "A2", "a2"))),
Node(5, "B", "b")))
val matches = t1 matchWith t1.copy()
matches foreach { t => assert(t._1 == t._2)}
}
it("should fully match very similar tree") {
val t1 = Node(1, "ROOT", "", Seq(
Node(2, "A", "a", Seq(
Node(3, "A1", "a1"),
Node(4, "A2", "a2"))),
Node(5, "B", "var")))
val t2 = Node(1, "ROOT", "", Seq(
Node(2, "A", "a", Seq(
Node(3, "A1", "a1"),
Node(4, "A2", "a2"))),
Node(5, "B", "val")))
val matches = t1 matchWith t2
assert(matches.size == 5)
}
it("should match inner node with two out of three matching leaves") {
val root = Node(1, "ROOT", "", Seq(
Node(2, "A", "a", Seq(
Node(4, "A2", "a2"),
Node(3, "A1", "a1"),
Node(5, "A3", "a3"))),
Node(6, "B", "b")))
val matches = root matchWith root.replaceNode(3, null)
assert(matches contains ((2, 2)))
}
}
}
}
开发者ID:Quoin,项目名称:tree-diffing,代码行数:55,代码来源:TreeMatcherTest.scala
示例6: DataSciencesterSpec
//设置package包名称以及导入依赖的类
package org.invisibletech.datasciencefromscratch
import DataSciencester._
import DataSciencesterTestDataFixture._
import org.scalatest.FunSpec
class DataSciencesterSpec extends FunSpec {
describe("We should be able to get the expected statistics") {
it("total number of connections") {
assert(totalConnections((users, friendships)) == 24)
}
it("number of friends of one user") {
val compiled: CompiledUserDirectory = (users, friendships)
assert(compiled.usersWithFriends(1).friends.size == 3)
}
it("avg number of friends") {
assert(averageNumberOfFriends((users, friendships)) == 2.4)
}
it("number of friends by id") {
val friends = (users, friendships)
assert(numberOfFriendsById(friends).size == 10)
assert(numberOfFriendsById(friends) == List((0,2), (1,3), (2,3), (3,3), (4,2), (5,3), (6,2), (7,2), (8,3), (9,1)))
}
it("sorted number of friends by id") {
val friends = numberOfFriendsById((users, friendships))
assert(sortedNumberOfFriendsById(friends).size == 10)
assert(sortedNumberOfFriendsById(friends) == List((1,3), (2,3), (3,3), (5,3), (8,3), (0,2), (4,2), (6,2), (7,2), (9,1)))
}
it("counts number of friends have in common with friends") {
val friends = (users, friendships)
assert(countOfCommonFoFs(friends.usersWithFriends(1), friends) == List((0,1), (2,2), (3,1)))
}
it("compiles interests for each user id") {
val interestsToUsersMap: Map[String, List[Int]] = compileInterestsToUsers(interests)
assert(interestsToUsersMap("regression") == List(3, 4))
assert(interestsToUsersMap("Python") == List(2, 3, 5))
}
it("compiles user intererests") {
val interestsToUsersMap: Map[Int, List[String]] = compileUsersToInterests(interests)
assert(interestsToUsersMap(3) == List("R", "Python", "statistics", "regression", "probability"))
}
}
}
开发者ID:InvisibleTech,项目名称:datasciencefromscratch,代码行数:55,代码来源:DataSciencesterSpec.scala
示例7: CompiledUserDirectorySpec
//设置package包名称以及导入依赖的类
package org.invisibletech.datasciencefromscratch
import DataSciencester._
import org.scalatest.FunSpec
import org.scalatest.BeforeAndAfter
class CompiledUserDirectorySpec extends FunSpec with BeforeAndAfter {
var friendships: List[(Int, Int)] = _
var users: List[User] = _
before {
friendships = List((0, 1))
users = List(
Map("id" -> 0, "name" -> "Hero"),
Map("id" -> 1, "name" -> "Dunn"))
}
describe("Relations can be made bidirectional") {
it("should show graph edge both ways") {
val result = CompiledUserDirectory(users, friendships).createBiDirectionalRelations(List((1, 2)))
assert(result == List((1, 2), (2, 1)))
}
it("will produce duplicates if 1 way relationships repeat relations") {
val result = CompiledUserDirectory(users, friendships).createBiDirectionalRelations(List((1, 2), (2, 1)))
assert(result == List((1, 2), (2, 1), (2, 1), (1, 2)))
}
}
describe("We should be able to establish friendships immutably and with delayed evaluation") {
it("should allow following friends from myself and back again") {
val result = CompiledUserDirectory(users, friendships)
assert(result.usersWithFriends.size == 2)
val herosFriends: List[scala.Function0[CompiledUser]] = result.usersWithFriends(0).friends
assert(herosFriends.size == 1)
val dunnsFriends: List[scala.Function0[CompiledUser]] = result.usersWithFriends(1).friends
assert(dunnsFriends.size == 1)
}
}
}
开发者ID:InvisibleTech,项目名称:datasciencefromscratch,代码行数:48,代码来源:CompiledUserDirectorySpec.scala
示例8: SendMetricsTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.datasender.metrics
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar
import org.hpi.esb.datasender.TestHelper.checkEquality
class SendMetricsTest extends FunSpec with MockitoSugar {
val expectedRecordNumber = 1000
val topicOffsets = Map("A" -> 10L, "B" -> 20L)
val sendMetrics = new SendMetrics(topicOffsets, expectedRecordNumber)
describe("getFailedSendsPercentage") {
it("should return 0 when expectedRecordNumber = 0") {
val failedSends = 100
val expectedRecordNumber = 0
val failedSendsResult = SendResult(expectedRecordNumber, failedSends)
assert(0.0 == failedSendsResult.failedSendsPercentage())
}
it("should calculate correctly") {
val failedSends = 10
val expectedRecordNumber = 100
val failedSendsResult = SendResult(expectedRecordNumber, failedSends)
assert(0.1 == failedSendsResult.failedSendsPercentage())
}
}
describe("getAccumulatedSendMetrics") {
val perTopicSendMetrics = Map("A" -> SendResult(expectedRecordNumber = 100L, failedSends = 10L),
"B" -> SendResult(expectedRecordNumber = 100L, failedSends = 5L))
val expectedAccumulatedSendMetrics = Map(
"expectedRecordNumber" -> 200L.toString,
"failedSends" -> 15L.toString,
"failedPercentage" -> 0.075.toString)
val accumulatedSendMetrics = sendMetrics.getAccumulatedSendResults(perTopicSendMetrics)
it("should calculate the correct overall stats") {
checkEquality[String, String](expectedAccumulatedSendMetrics, accumulatedSendMetrics)
checkEquality[String, String](accumulatedSendMetrics, expectedAccumulatedSendMetrics)
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:49,代码来源:SendMetricsTest.scala
示例9: DataSenderConfigTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.datasender.config
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar
class DataSenderConfigTest extends FunSpec with MockitoSugar {
val numberOfThreads = Option(1)
val singleColumnMode = false
describe("isNumberOfThreadsValid") {
it("should return false if number of threads is < 0") {
val numberOfThreads = Option(-1)
val config = DataSenderConfig(numberOfThreads, singleColumnMode)
assert(!config.isNumberOfThreadsValid)
}
it("should return false if number of threads is 0") {
val numberOfThreads = Option(0)
val config = DataSenderConfig(numberOfThreads, singleColumnMode)
assert(!config.isNumberOfThreadsValid)
}
it("should return true if number of threads is positive") {
val numberOfThreads = Option(1)
val config = DataSenderConfig(numberOfThreads, singleColumnMode)
assert(config.isNumberOfThreadsValid)
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:32,代码来源:DataSenderConfigTest.scala
示例10: ValidatorSeriesResultTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.datavalidator.output.model
import org.scalatest.FunSpec
class ValidatorSeriesResultTest extends FunSpec {
describe("ValidatorSeriesResultTest") {
it("should merge") {
val configValues = ConfigValues(
sendingInterval = "100",
sendingIntervalUnit = "SECONDS",
scaleFactor = "1"
)
val resultValues1 = ResultValues(
query = "Identity",
correct = true,
percentile = 1.3,
rtFulfilled = true,
validatorRunTime = 10.0
)
val resultRow1 = ValidatorResultRow(configValues, resultValues1)
val resultValues2 = ResultValues(
query = "Identity",
correct = false,
percentile = 1.4,
rtFulfilled = true,
validatorRunTime = 20.0
)
val resultRow2 = ValidatorResultRow(configValues, resultValues2)
val expectedMergedResultValue = ResultValues(
query = "Identity",
correct = false,
percentile = 1.35,
rtFulfilled = true,
validatorRunTime = 15.0
)
val expectedResultRow = ValidatorResultRow(configValues, expectedMergedResultValue)
val validatorSeriesResult = new ValidatorSeriesResult(List(resultRow1, resultRow2))
assert(expectedResultRow.toTable() == validatorSeriesResult.toTable())
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:52,代码来源:ValidatorSeriesResultTest.scala
示例11: ResultValuesTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.datavalidator.output.model
import org.scalatest.FunSpec
import ResultValues._
class ResultValuesTest extends FunSpec {
val query = "Identity"
val correct = "true"
val percentile = "1.3"
val rtFulfilled = "true"
val validatorRunTime = "10.0"
val exampleResultValues = ResultValues(
query = query,
correct = correct.toBoolean,
percentile = percentile.toDouble,
rtFulfilled = rtFulfilled.toBoolean,
validatorRunTime = validatorRunTime.toDouble
)
describe("toList") {
it("should return a list representation of the result values") {
val exampleResultValuesList = exampleResultValues.toList()
val expectedList = List(query, correct, percentile, rtFulfilled, validatorRunTime)
assert(exampleResultValuesList == expectedList)
}
}
describe("fromMap") {
it("should return a ResultValues object") {
val valueMap = Map(
QUERY_COLUMN -> query,
CORRECT_COLUMN -> correct,
PERCENTILE_COLUMN -> percentile,
RT_FULFILLED -> rtFulfilled,
VALIDATOR_RUNTIME -> validatorRunTime
)
val resultValuesFromMap = new ResultValues(valueMap)
assert(resultValuesFromMap == exampleResultValues)
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:44,代码来源:ResultValuesTest.scala
示例12: ClientTest
//设置package包名称以及导入依赖的类
package io.scalajs.npm.kafkanode
import io.scalajs.nodejs.{console, process}
import io.scalajs.util.PromiseHelper.Implicits._
import org.scalatest.FunSpec
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
class ClientTest extends FunSpec {
private val topic = "testing"
describe("Client") {
it("should produce and consume data") {
process.env.get("ZK_HOST") match {
case None =>
info("No Zookeeper host was specified. Set 'ZK_HOST=localhost:2181'")
case Some(zkConnect) =>
val client = new Client(zkConnect)
val producer = new Producer(client)
producer.createTopicsFuture(topics = js.Array(topic), async = true) foreach { _ =>
console.log(s"Created topic $topic")
}
val consumer = new Consumer(
client,
js.Array(new FetchRequest(topic = topic, offset = 0)),
new ConsumerOptions(
groupId = "kafka-node-group",
autoCommit = true,
autoCommitIntervalMs = 5000,
fetchMaxWaitMs = 100,
fetchMinBytes = 4,
fetchMaxBytes = 1024 * 1024,
fromOffset = 0L,
encoding = "utf8"
)
)
consumer.onMessage((message: String) => {
console.log("message: %j", message)
})
consumer.onError { error =>
console.log("error: %j", error)
}
}
}
}
}
开发者ID:scalajs-io,项目名称:kafka-node,代码行数:57,代码来源:ClientTest.scala
示例13: testPathStatus
//设置package包名称以及导入依赖的类
package dummy_authenticator.rest
import akka.http.scaladsl.model.StatusCodes.{CustomStatusCode, OK, Redirection, ServerError}
import akka.http.scaladsl.model.{ContentType, HttpEntity, Multipart, StatusCodes}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import dummy_authenticator.config.Configuration
import org.scalatest.concurrent.Eventually
import org.scalatest.{FunSpec, Matchers}
import scala.concurrent.duration._
import scala.language.postfixOps
trait RestTest extends FunSpec with Matchers with Eventually with ScalatestRouteTest with Routes {
val config: Configuration = Configuration.get
val BASE_PATH: String = "/" + config.app.name
val FILE_PATH: String = BASE_PATH + "/share/file"
val LIST_PATH: String = BASE_PATH + "/share/filelist"
val PATH_NONEXISTENT: String = "ShouldNotExist"
val FILE_NONEXISTENT: String = "ShouldNotExist.file"
val EMPTY_DIR: String = "{\"keys\":[]}"
def testPathStatus(path: String): Unit = {
Get(path) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status should not be a[Redirection]
status should not be a[CustomStatusCode]
}
Delete(path) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status should not be a[Redirection]
status should not be a[CustomStatusCode]
}
Put(path) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status should not be a[Redirection]
status should not be a[CustomStatusCode]
}
Post(path) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status should not be a[Redirection]
status should not be a[CustomStatusCode]
}
}
def setupFileForUpload(filename: String,
fileContent: String,
contentType: ContentType.NonBinary,
fieldName: String): Multipart.FormData.Strict = {
Multipart.FormData(
Multipart.FormData.BodyPart.Strict(fieldName, HttpEntity(contentType, fileContent), Map("filename" ? filename)))
}
}
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:59,代码来源:RestTest.scala
示例14: canAccessRoute
//设置package包名称以及导入依赖的类
package co.horn.alkes.auth
import akka.http.scaladsl.model.HttpMethod
import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST, PUT}
import akka.http.scaladsl.model.StatusCodes.{Forbidden, ServerError}
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import co.horn.alkes.config.Configuration
import co.horn.alkes.dao.DataHandler
import co.horn.alkes.dao.implementations.riak.RiakDataHandler
import co.horn.alkes.log.Logger
import co.horn.alkes.rest.Routes
import org.scalatest.{FunSpec, Matchers}
import org.scalatest.concurrent.Eventually
trait AuthTest extends FunSpec with Matchers with Eventually with ScalatestRouteTest with Routes {
val config: Configuration = Configuration.get
val dao: DataHandler = new RiakDataHandler(config)
val log: Logger = config.log.tests
// TODO: Define these all in just ONE spot. Need to keep DRY!
val BASE_PATH: String = "/" + config.app.name
val FILE_PATH: String = BASE_PATH + "/share/file"
val LIST_PATH: String = BASE_PATH + "/share/filelist"
val META_PATH: String = BASE_PATH + "/share/metadata"
val THUMB_PATH: String = BASE_PATH + "/share/thumbnail"
def canAccessRoute(token: OAuth2BearerToken, route: String, method: HttpMethod): Boolean = {
method match {
case GET =>
Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case PUT =>
Put(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case DELETE =>
Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case POST =>
Post(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case m => throw new IllegalArgumentException(s"$m is not an HttpMethod accepted by Alkes.")
}
}
}
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:56,代码来源:AuthTest.scala
示例15: WebServerSpec
//设置package包名称以及导入依赖的类
import org.scalatest.FunSpec
import io.restassured.module.scala.RestAssuredSupport.AddThenToResponse
import io.restassured.RestAssured._
import io.restassured.http.ContentType
// you need to start WebServer manually before running this Spec
class WebServerSpec extends FunSpec {
describe("WebServer") {
val req = given()
.port(8080)
describe("hello endpoint") {
it("should return hello") {
val resp = req
.when()
.get("/hello")
.Then()
.statusCode(200)
.contentType(ContentType.HTML)
.extract()
.body().asString()
assert(resp contains "Say hello to akka-http")
}
}
describe("csv upload") {
val csvContent: String =
"""
|1, ABC
|2, DEF
|
""".stripMargin
req
.when()
.multiPart("input", "someFile.csv", csvContent.getBytes)
.post("/csv-upload")
.Then()
.statusCode(200)
}
}
}
开发者ID:bassmake,项目名称:akka-http-csv-upload,代码行数:50,代码来源:WebServerSpec.scala
示例16: SerializeSpec
//设置package包名称以及导入依赖的类
package knot.msgpack
import knot.data.serialization.Serialize
import knot.testKit.TestSerCaseClass
import org.scalatest.FunSpec
import org.scalatest.Matchers._
class SerializeSpec extends FunSpec {
describe("Serialize") {
it("case class") {
val obj = TestSerCaseClass().setup()
val bytes = Serialize.from[TestSerCaseClass](obj)
val r = Serialize.to[TestSerCaseClass](bytes)
r should be(obj)
}
}
}
开发者ID:defvar,项目名称:knot,代码行数:19,代码来源:SerializeSpec.scala
示例17: IntCodecSpec
//设置package包名称以及导入依赖的类
package knot.msgpack.codec
import knot.msgpack.{MsgPackInput, MsgPackOutput}
import org.scalatest.FunSpec
import org.scalatest.Matchers._
class IntCodecSpec extends FunSpec {
val t = new IntCodec {}
val data: Array[(Int, Int)] = Array(
(Int.MinValue, 5),
(-32769, 5),
(Short.MinValue, 3),
(-129, 3),
(-128, 2),
(-33, 2),
(-32, 1),
(0, 1),
(1, 1),
(127, 1),
(128, 2),
(255, 2),
(256, 3),
(Short.MaxValue, 3),
(65535, 3),
(65536, 5),
(Int.MaxValue, 5)
)
describe("IntCodec") {
it("values") {
for (d <- data) {
val o = MsgPackOutput(128)
t.encode(o, d._1)
o.flush()
o.size should be(d._2)
val i = MsgPackInput(o.toArray())
val e = t.decode(i)
e should be(d._1)
}
}
}
}
开发者ID:defvar,项目名称:knot,代码行数:43,代码来源:IntCodecSpec.scala
示例18: BooleanCodecSpec
//设置package包名称以及导入依赖的类
package knot.msgpack.codec
import knot.msgpack.{MsgPackInput, MsgPackOutput}
import org.scalatest.FunSpec
import org.scalatest.Matchers._
class BooleanCodecSpec extends FunSpec {
val t = new BooleanCodec {}
val data: Array[(Boolean, Int)] = Array(
(false, 1),
(true, 1)
)
describe("BooleanCodec") {
it("values") {
for (d <- data) {
val o = MsgPackOutput(128)
t.encode(o, d._1)
o.flush()
o.size should be(d._2)
val i = MsgPackInput(o.toArray())
val e = t.decode(i)
e should be(d._1)
}
}
}
}
开发者ID:defvar,项目名称:knot,代码行数:28,代码来源:BooleanCodecSpec.scala
示例19: DoubleCodecSpec
//设置package包名称以及导入依赖的类
package knot.msgpack.codec
import knot.msgpack.{MsgPackInput, MsgPackOutput}
import org.scalatest.FunSpec
import org.scalatest.Matchers._
class DoubleCodecSpec extends FunSpec {
val t = new DoubleCodec {}
val data: Array[(Double, Int)] = Array(
(Double.MinValue, 9),
(0.0D, 9),
(12345.6789D, 9),
(-12345.6789D, 9),
(Double.NaN, 9),
(Double.PositiveInfinity, 9),
(Double.NegativeInfinity, 9),
(Double.MinPositiveValue, 9),
(Double.MaxValue, 9)
)
describe("DoubleCodec") {
it("values") {
for (d <- data) {
val o = MsgPackOutput(128)
t.encode(o, d._1)
o.flush()
o.size should be(d._2)
val i = MsgPackInput(o.toArray())
val e = t.decode(i)
if (d._1.isNaN) {
d._1.isNaN && e.isNaN should be(true)
} else {
e should be(d._1)
}
}
}
}
}
开发者ID:defvar,项目名称:knot,代码行数:39,代码来源:DoubleCodecSpec.scala
示例20: SchedulerSpec
//设置package包名称以及导入依赖的类
package knot.core.scheduler
import java.util.concurrent.{CountDownLatch, TimeUnit}
import org.scalatest.FunSpec
import org.scalatest.Matchers._
class SchedulerSpec extends FunSpec {
val s = new Schedulers()
describe("scheduler") {
it("scheduler is singleton") {
s.single should be theSameInstanceAs s.single
}
it("singl scheduler") {
val cdl = new CountDownLatch(2)
val start = System.currentTimeMillis()
s.single.schedule(() => cdl.countDown(), 1, 1, TimeUnit.SECONDS)
cdl.await()
val end = System.currentTimeMillis()
end - start should be(2000L +- 100L)
}
it("singl scheduler / wait next command") {
val cdl = new CountDownLatch(4)
val start = System.currentTimeMillis()
s.single.schedule(() => {
Thread.sleep(1000) // heavy job
cdl.countDown()
}, 1, 1, TimeUnit.SECONDS)
s.single.schedule(() => cdl.countDown(), 1, 1, TimeUnit.SECONDS)
cdl.await()
val end = System.currentTimeMillis()
end - start should be(4000L +- 100L)
}
}
}
开发者ID:defvar,项目名称:knot,代码行数:41,代码来源:SchedulerSpec.scala
注:本文中的org.scalatest.FunSpec类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论