当前位置: 首页>>代码示例>>Scala>>正文


Scala Specification类代码示例

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


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

示例1: UserTokenDaoSpec

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

import scala.concurrent.Await

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.test._
import play.api.test.Helpers._

import org.joda.time.DateTime
import org.specs2.mutable.Specification

import java.util.UUID

import scala.concurrent.Await
import scala.concurrent.duration.DurationInt

import models.UserToken

class UserTokenDaoSpec extends Specification {

  val timeout = DurationInt(10).seconds
  def fakeApp = FakeApplication(additionalConfiguration = Map("mongodb.uri" -> "mongodb://localhost:27017/test"))

  def withUserTokenDao[T](t:UserTokenDao => T):T = running(fakeApp) {
    val userTokenDao = new MongoUserTokenDao
    Await.ready(userTokenDao.tokens.drop(), timeout)
    t(userTokenDao)
  }

  val token = UserToken(id=UUID.randomUUID(), userId=UUID.randomUUID(), "[email protected]", new DateTime(), true)

  "UserTokenDao" should {
    "Persist and find a token" in withUserTokenDao { userTokenDao =>
      val future = for {
        _ <- userTokenDao.save(token)
        maybeToken <- userTokenDao.find(token.id)
      } yield maybeToken.map(_ == token)
      Await.result(future, timeout) must beSome(true)
    }

    "Remove a token" in withUserTokenDao { userTokenDao =>
      val future = for {
        _ <- userTokenDao.save(token)
        _ <- userTokenDao.remove(token.id)
        maybeToken <- userTokenDao.find(token.id)
      } yield maybeToken
      Await.result(future, timeout) must beNone       
    }
  }
} 
开发者ID:Viva-con-Agua,项目名称:drops,代码行数:51,代码来源:UserTokenDaoSpec.scala

示例2: HelloWorldTestSpecs

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

import net.liftweb._
import http._
import net.liftweb.util._
import net.liftweb.common._
import Helpers._
import lib._
import org.specs2.mutable.Specification
import org.specs2.specification.AroundExample
import org.specs2.execute.AsResult


object HelloWorldTestSpecs extends Specification with AroundExample{
  val session = new LiftSession("", randomString(20), Empty)
  val stableTime = now

  
  def around[T : AsResult](body: =>T) = {
    S.initIfUninitted(session) {
      DependencyFactory.time.doWith(stableTime) {
        AsResult( body)  // execute t inside a http session
      }
    }
  }

  "HelloWorld Snippet" should {
    "Put the time in the node" in {
      val hello = new HelloWorld
      Thread.sleep(1000) // make sure the time changes

      val str = hello.howdy(<span>Welcome to your Lift app at <span id="time">Time goes here</span></span>).toString

      str.indexOf(stableTime.toString) must be >= 0
      str must startWith("<span>Welcome to")
    }
  }
} 
开发者ID:EasterTheBunny,项目名称:ourdistrict,代码行数:40,代码来源:HelloWorldTest.scala

示例3: PaginatedResponseRetrieverSpec

//设置package包名称以及导入依赖的类
package com.dwolla.awssdk.utils

import com.amazonaws.services.ecs.AmazonECSAsync
import com.amazonaws.services.ecs.model.{ListClustersRequest, ListClustersResult, ListContainerInstancesRequest, ListContainerInstancesResult}
import com.dwolla.awssdk.AmazonAsyncMockingImplicits._
import com.dwolla.awssdk.utils.PaginatedResponseRetriever._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.collection.JavaConverters._

class PaginatedResponseRetrieverSpec(implicit ee: ExecutionEnv) extends Specification with Mockito {

  trait Setup extends Scope {
    val mockEcsClient = mock[AmazonECSAsync]
  }

  "PaginatedResponseRetriever" should {
    "make all the requests necessary to fetch all paginated results" in new Setup {
      def reqWithNextToken(x: Option[Int]) = new ListContainerInstancesRequest().withCluster("cluster1").withNextToken(x.map(i ? s"next-token-$i").orNull)

      def res(x: Int, y: Option[Int] = None) = Right(new ListContainerInstancesResult().withContainerInstanceArns(s"arn$x").withNextToken(y.map(i ? s"next-token-$i").orNull))

      val pages = 1 to 50
      val pairs = pages.sliding(2).toSeq.map {
        case Vector(1, y) ? reqWithNextToken(None) ? res(1, Option(y))
        case Vector(x, y) if x > 1 && y < pages.last ? reqWithNextToken(Option(x)) ? res(x, Option(y))
        case Vector(x, _) ? reqWithNextToken(Option(x)) ? res(x, None)
      }

      mockedMethod(mockEcsClient.listContainerInstancesAsync) answers (pairs: _*)

      val output = fetchAll(() ? new ListContainerInstancesRequest().withCluster("cluster1"),mockEcsClient.listContainerInstancesAsync)
        .map(_.flatMap(_.getContainerInstanceArns.asScala.toList))

      output must containTheSameElementsAs(pages.dropRight(1).map(x ? s"arn$x")).await
    }

    "support default request factory" in new Setup {
      new ListClustersResult() completes mockEcsClient.listClustersAsync

      val output = fetchAllWithDefaultRequestsVia(mockEcsClient.listClustersAsync)

      output must contain(new ListClustersResult()).await
    }

    "support builder syntax with factory as initial parameter" in new Setup {
      new ListClustersResult() completes mockEcsClient.listClustersAsync

      val output = fetchAllWithRequestsLike(() ? new ListClustersRequest).via(mockEcsClient.listClustersAsync)

      output must contain(new ListClustersResult()).await
    }
  }
} 
开发者ID:Dwolla,项目名称:scala-aws-utils,代码行数:58,代码来源:PaginatedResponseRetrieverSpec.scala

示例4: CheckoutSpec

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

import org.specs2.mutable.Specification
import Checkout._

class CheckoutSpec extends Specification {
  "Shopping cart" should {
    "cost nothing when there are no items" in {
      costOf(ShoppingCart()) mustEqual 0.00
    }

    "cost 60p for 1 apple" in {
      costOf(ShoppingCart(Apple)) mustEqual 0.60
    }

    "cost £1.20 for 2 apples" in {
      costOf(ShoppingCart(Apple, Apple)) mustEqual 1.20
    }

    "cost 25p for 1 orange" in {
      costOf(ShoppingCart(Orange)) mustEqual 0.25
    }

    "cost 50p for 2 oranges" in {
      costOf(ShoppingCart(Orange, Orange)) mustEqual 0.50
    }

    "£2.05 for 3 apples and 1 orange" in {
      costOf(ShoppingCart(Apple, Apple, Orange, Apple)) mustEqual 2.05
    }

    "cost 20p for 1 banana" in {
      costOf(ShoppingCart(Banana)) mustEqual 0.20
    }
  }
} 
开发者ID:gbs-scala,项目名称:ScalaCode,代码行数:37,代码来源:CheckoutSpec.scala

示例5: SearchDataTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.hotels

import org.specs2.matcher.DataTables
import org.specs2.mutable.Specification


class SearchDataTest extends Specification with DataTables {
  "Hotels dataset" should {
    "have the correct number of elements" >> {
      SearchData.trainDataEncoded.size must_== SearchData.TrainSetSize
      SearchData.trainLabels.size must_== SearchData.TrainSetSize
      SearchData.testDataEncoded.size must_== SearchData.TestSetSize
      SearchData.testLabels.size must_== SearchData.TestSetSize
    }

    "have primitives in train data" >> {
      "elementClass" |
      SearchData.trainDataEncoded.next().next().getClass |
      SearchData.trainingAndTestData()._1.head._2.next().getClass |> { elementClass =>
        elementClass.isPrimitive must beTrue
      }
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:25,代码来源:SearchDataTest.scala

示例6: KNearestNeighborsTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.knn

import com.danylchuk.swiftlearner.data.{FisherIris, Mnist}
import org.specs2.mutable.Specification


class KNearestNeighborsTest extends Specification {
  "KNearestNeighbors" should {
    "sort the flowers from the Fisher Iris dataset" >> {
      val (trainingSet, testSet) = FisherIris.trainingAndTestData(Some(0L))

      val classifier = new KNearestNeighbors(trainingSet)

      val accuracy = (for ((species, params) <- testSet) yield {
        classifier.predict(params, 1) == species
      }).count { x: Boolean => x } / testSet.size.toDouble

      accuracy must be_>(0.8)  // 0.94 is typical
    }

    "sort the digits from the MNIST dataset" >> {
      val (trainingSet, testSet) = Mnist.shuffledTrainingAndTestDataDouble(nTrainPoints = 700, randomSeed = Some(0L))
      val expectedAccuracy = 0.8
      // 0.89 with 3000 points; better with more; the current naive algorithm is slow

      val classifier = new KNearestNeighbors(trainingSet)

      val accuracy = (for ((species, params) <- testSet) yield {
        classifier.predict(params, 1) == species
      }).count { x: Boolean => x } / testSet.size.toDouble

      accuracy must be_>(expectedAccuracy)
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:36,代码来源:KNearestNeighborsTest.scala

示例7: GeneticTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.ga

import org.specs2.mutable.Specification


class GeneticTest extends Specification {
  "Genetic algorithm" should {
    "solve the Hello World example" >> {
      val result = new Genetic[HelloGenetic](50, 10).optimize(100, 30000L)
      result.genome must_== HelloGenetic.HelloDouble
      result.fitness must_== 0
    }

    "sort the flowers from the Fisher Iris dataset" >> {
      val testSet = GeneticIris.testSet

      val classifier = new Genetic[GeneticIris](100, 10)
        .optimize(200, 60000L).genome

      val accuracy = (for ((species, params) <- testSet) yield {
        GeneticIris.predict(classifier, params) == species
      }).count { x: Boolean => x } / testSet.size.toDouble

      accuracy must be_>(0.7)  // 0.94 is typical
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:28,代码来源:GeneticTest.scala

示例8: KMeansTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.kmeans

import com.danylchuk.swiftlearner.data.FisherIris
import org.specs2.mutable.Specification


class KMeansTest extends Specification{
  "KMeans" should {
    "create clusters similar to the known Iris dataset labels" >> {
      val (knownLabels, data) = FisherIris.irisData.unzip
      val k = knownLabels.distinct.size
      val kMeans = new KMeans(data, k)

      // Now, we have a small problem because the label values are different,
      // although the sets they define should be similar.

      // Pair the labels. Then the most common k pairs will be the correct labels,
      // and we can count the rest to find the number of errors and the accuracy.
      val labelPairs = knownLabels zip kMeans.labels
      val groups = labelPairs.groupBy(identity).values.toVector
      val errorGroups = groups.sortWith((a, b) => a.size > b.size).drop(k)
      val nErrors = errorGroups.map(_.size).sum
      val accuracy = 1.0 - nErrors.toDouble / data.size

      accuracy must be_>(0.8)  // typical is 0.87
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:29,代码来源:KMeansTest.scala

示例9: MnistTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.data

import org.specs2.matcher.DataTables
import org.specs2.mutable.Specification


class MnistTest extends Specification with DataTables {
  "MNIST dataset" should {
    "have the correct number of elements" >> {
      Mnist.trainImagesByteArray.size must_== Mnist.TrainSetSize
      Mnist.trainLabels.size must_== Mnist.TrainSetSize
      Mnist.testImages.size must_== Mnist.TestSetSize
      Mnist.testLabels.size must_== Mnist.TestSetSize
    }

    "have primitives in trainImages" >> {
      "elementClass" |
      Mnist.trainImagesByteArray(0)(0).getClass |
      Mnist.trainImages.next()(0).getClass |
      Mnist.trainImagesDouble.next()(0).getClass |
      Mnist.trainingAndTestDataDouble()._1.head._2.head.getClass |> { elementClass =>
        elementClass.isPrimitive must beTrue
      }
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:27,代码来源:MnistTest.scala

示例10: GaussianNaiveBayesTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.bayes

import com.danylchuk.swiftlearner.data.FisherIris
import org.specs2.mutable.Specification


class GaussianNaiveBayesTest extends Specification {
  "GaussianNaiveBayes" should {
    "sort the flowers from the Fisher Iris dataset" >> {
      val (trainingSet, testSet) = FisherIris.trainingAndTestData(Some(0L))

      val classifier = GaussianNaiveBayes.fromTrainingSet(trainingSet)

      val accuracy = (for ((species, params) <- testSet) yield {
        classifier.predict(params) == species
      }).count { x: Boolean => x } / testSet.size.toDouble

      accuracy must be_>(0.8)  // 0.94 is typical
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:22,代码来源:GaussianNaiveBayesTest.scala

示例11: VectorOpTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.math

import com.danylchuk.swiftlearner.math.VectorOp._
import org.specs2.mutable.Specification


class VectorOpTest extends Specification {
  "VectorOp dot product" should {
    "calculate dot product of two vectors" >> {
      Vector(2.0, 3.0) * Vector(4.0, 5.0) must_== 2 * 4 + 3 * 5
    }
    "throw IllegalArgumentException on non-matching size" >> {
      {
        Vector(2.0, 3.0) * Vector(4.0)
      } must throwA(
        new IllegalArgumentException("requirement failed: vector size mismatch"))
    }
  }

  "VectorOp.distance" should {
    "calculate the distance correctly" >> {
      distance(Vector(0, 0), Vector(10, 0)) must_== 10
      distance(Vector(0, 0), Vector(0, 10)) must_== 10
      distance(Vector(0, 0), Vector(3, 4)) must_== 5
      distance(Vector(0, 0), Vector(4, 3)) must_== 5
      distance(Vector(3, 0), Vector(0, 4)) must_== 5
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:30,代码来源:VectorOpTest.scala

示例12: StatTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.math

import org.specs2.mutable.Specification


class StatTest extends Specification {
  "Stat" should {
    "calculate the mean correctly" >> {
      Stat.mean(Seq(0.8, 1.2)) must beCloseTo(1.0 +/- 0.0001)
      Stat.mean(Seq(1.9, 2.1)) must beCloseTo(2.0 +/- 0.0001)
    }

    "calculate the variance correctly" >> {
      Stat.variance(Seq(0.8, 1.2)) must beCloseTo(0.04 +/- 0.0001)
      Stat.variance(Seq(1.9, 2.1)) must beCloseTo(0.01 +/- 0.0001)
    }

    "calculate the standard deviation correctly" >> {
      Stat.stdDev(Seq(0.8, 1.2)) must beCloseTo(0.2 +/- 0.0001)
      Stat.stdDev(Seq(1.9, 2.1)) must beCloseTo(0.1 +/- 0.0001)
    }

    "calculate Gaussian probability density correctly" >> {
      val normalDistributionMax = 1 / math.sqrt(2 * math.Pi)
      Stat.gaussianDensity(0, 0, 1) must beCloseTo(normalDistributionMax +/- 0.0001)
      Stat.gaussianDensity(1, 1, 1) must beCloseTo(normalDistributionMax +/- 0.0001)
      Stat.gaussianDensity(0, 0, 2) must beCloseTo(0.2821 +/- 0.0001)
      Stat.gaussianDensity(0, 1, 2) must beCloseTo(0.2197 +/- 0.0001)
      Stat.gaussianDensity(1, 0, 2) must beCloseTo(0.2197 +/- 0.0001)
      Stat.gaussianDensity(1, 0, 1) must beCloseTo(0.2420 +/- 0.0001)
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:34,代码来源:StatTest.scala

示例13: MatrixOpTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.math

import org.specs2.mutable.Specification


class MatrixOpTest extends Specification {
  "MatrixOp" should {
    "mulMatrixByColumnFloat" >> {
      val a = Array(1.0f, 2.0f, 3.0f, 5.0f, 7.0f, 9.0f, 99.99f, 99.99f, 99.99f)
      val x = Array(11.0f, 13.0f, 17.0f)
      val result = MatrixOp.mulMatrixByColumnFloat(a, x, 2, 3)
      val expected = Array(11.0f * 1.0f + 13.0f * 2.0f + 17.0f * 3.0f,
                           11.0f * 5.0f + 13.0f * 7.0f + 17.0f * 9.0f)
      result must_== expected
    }

    "mulMatrixByColumnDouble" >> {
      val a = Array(1.0, 2.0, 3.0, 5.0, 7.0, 9.0, 99.99, 99.99, 99.99)
      val x = Array(11.0, 13.0, 17.0)
      val result = MatrixOp.mulMatrixByColumnDouble(a, x, 2, 3)
      val expected = Array(11.0 * 1.0 + 13.0 * 2.0 + 17.0 * 3.0,
                           11.0 * 5.0 + 13.0 * 7.0 + 17.0 * 9.0)
      result must_== expected
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:27,代码来源:MatrixOpTest.scala

示例14: ServiceSpec

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

import org.http4s._
import org.http4s.testing.Http4sMatchers
import org.specs2.mutable.Specification

object ServiceSpec extends Specification with Http4sMatchers {
  "Service.api" >> {
    "/now.json has status 200" >> {
      val request = Request(Method.GET, Uri.uri("/now.json"))
      val response = unsafeGetResponse(Service.api, request)
      response must haveStatus(Status.Ok)
    }
    "/version has MediaType application/json" >> {
      val request = Request(Method.GET, Uri.uri("/version"))
      val response = unsafeGetResponse(Service.api, request)
      response must haveMediaType(MediaType.`application/json`)
    }
  }

  "Service.assets" >> {
    "/client-opt.js contains 'Hello, world!'" >> {
      val path = s"/${BuildInfo.moduleName}/${BuildInfo.version}/client-opt.js"
      val request = Request(Method.GET, Uri(path = path))
      val response = unsafeGetResponse(Service.assets, request)
      response must haveBody(contain("Hello, world!"))
    }
  }

  def unsafeGetResponse(service: HttpService, request: Request): Response =
    service.run(request).unsafeRun().orNotFound
} 
开发者ID:fthomas,项目名称:kartograffel,代码行数:33,代码来源:ServiceSpec.scala

示例15: CheckoutSpec

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

import org.specs2.mutable.Specification
import Checkout._

class CheckoutSpec extends Specification {
  "Shopping cart" should {
    "cost nothing when there are no items" in {
      costOf(ShoppingCart()) mustEqual 0.00
    }

    "cost 60p for 1 apple" in {
      costOf(ShoppingCart(Apple)) mustEqual 0.60
    }

    "cost £1.20 for 2 apples" in {
      costOf(ShoppingCart(Apple, Apple)) mustEqual 1.20
    }

    "cost 25p for 1 orange" in {
      costOf(ShoppingCart(Orange)) mustEqual 0.25
    }

    "cost 50p for 2 oranges" in {
      costOf(ShoppingCart(Orange, Orange)) mustEqual 0.50
    }

    "£2.05 for 3 apples and 1 orange" in {
      costOf(ShoppingCart(Apple, Apple, Orange, Apple)) mustEqual 2.05
    }

   }
} 
开发者ID:vubalasu,项目名称:shoping-cart-demo,代码行数:34,代码来源:CheckoutSpec.scala


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