本文整理汇总了Scala中org.specs2.Specification类的典型用法代码示例。如果您正苦于以下问题:Scala Specification类的具体用法?Scala Specification怎么用?Scala Specification使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Specification类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: RefusedByRateLimiterErrorSpec
//设置package包名称以及导入依赖的类
package com.lookout.ratelimitingfilter
import com.twitter.finagle.http.{Request, Status}
import org.specs2.{Specification, ScalaCheck}
import io.circe.syntax._
import io.circe.jawn._
import com.lookout.ratelimitingfilter.models._
class RefusedByRateLimiterErrorSpec extends Specification with ScalaCheck with Arbitraries {
def is = s2"""
RefusedByRateLimiterError object
it should not lose data on roundtrips to JSON $dataIntegrity
it should contain a `message` field $messageField
it should create a response with 429 status $statusCode
"""
def fields(error: RefusedByRateLimiterError): Seq[String] =
error.asJson.asObject.toList.flatMap(_.fields)
def dataIntegrity = prop {
(error: RefusedByRateLimiterError) => {
(decode[RefusedByRateLimiterError](error.asJson.noSpaces)) must_== Right(error)
}
}
def messageField = prop {
(error: RefusedByRateLimiterError) => {
fields(error) must contain("message")
}
}
def statusCode = prop {
(error: RefusedByRateLimiterError) => {
error.toResponse.status must_== Status.TooManyRequests
}
}
}
示例2: TestLogisticRegression
//设置package包名称以及导入依赖的类
package com.zobot.ai.spark
import breeze.linalg.Matrix
import com.zobot.ai.spark.helpers.LogisticRegressionHelpers
import org.apache.spark.ml.classification.LogisticRegression
import org.apache.spark.ml.linalg.Vectors
import org.specs2.Specification
class TestLogisticRegression extends Specification {
def is = s2"""
Logistic Regression
can train model $testTrainLogisticRegressionModel
"""
val context = new Context().spark
def testTrainLogisticRegressionModel = {
val model = LogisticRegressionHelpers.trainModel(new LogisticRegression, context.createDataFrame(Seq(
(1.0, Vectors.dense(0.0, 1.1, 0.1)),
(0.0, Vectors.dense(2.0, 1.0, -1.0)),
(0.0, Vectors.dense(2.0, 1.3, 1.0)),
(1.0, Vectors.dense(0.0, 1.2, -0.5))
)).toDF("label", "features"))
model.coefficientMatrix.toString().must_==("-19.086478256375067 16.278339464295065 -2.494930802874724 ")
}
}
示例3: InferenceSpec
//设置package包名称以及导入依赖的类
package org.atnos.eff
import all._
import syntax.all._
import cats.data._
import org.specs2.Specification
class InferenceSpec extends Specification { def is = s2"""
All the examples should compile ok
"""
def e1 = {
import Example1._
putAndTell[S](4).runState(0).runWriter.runReader("").run
putAndTell[S](4).runReader("").runState(0).runWriter.run
// in this case a type annotation is required on runWriter
putAndTell[S](4).runReader("").runWriter[String].runState(0).run
ok
}
}
object Example1 {
type RNG[R] = Member[State[Int, ?], R]
type Log[R] = Member[Writer[String, ?], R]
type Env[R] = Member[Reader[String, ?], R]
type S = Fx.fx3[State[Int, ?], Writer[String, ?], Reader[String, ?]]
def putAndTell[R : RNG : Log: Env](i: Int) =
for {
_ <- put(i)
_ <- tell("stored " + i)
} yield i
}
示例4: EvalEffectSpec
//设置package包名称以及导入依赖的类
package org.atnos.eff
import org.specs2.Specification
import org.atnos.eff.all._
import org.atnos.eff.syntax.all._
import cats.syntax.all._
import cats.instances.all._
import cats.instances.all._
import cats.Eval
class EvalEffectSpec extends Specification { def is = s2"""
run is stack safe with Eval $stacksafeRun
attempt is stack safe with Eval $stacksafeAttempt
recursion in Eval.defer is stack safe $stacksafeRecursion
"""
type E = Fx.fx1[Eval]
val list = (1 to 5000).toList
def stacksafeRun = {
val action = list.traverseU(i => EvalEffect.delay(i))
action.runEval.run ==== list
}
def stacksafeAttempt = {
val action = list.traverseU(i => EvalEffect.delay(i))
action.attemptEval.run ==== Right(list)
}
def stacksafeRecursion = {
def loop(i: Int): Eval[Eff[Fx.fx1[Eval], Int]] =
if (i == 0) {
Eval.now(Eff.pure(1))
} else {
Eval.now(eval.defer(loop(i - 1)).map(_ + 1))
}
loop(100000).value.runEval.run ==== 100001
}
}
示例5: SortSpec
//设置package包名称以及导入依赖的类
import com.stremlenye.sort.Sort
import org.specs2.Specification
class SortSpec extends Specification {
def is =
s2"""
Quick sort
sort sorted list ${Quick.sortSorted}
sort reversed list ${Quick.sortReversed}
sort randomed list ${Quick.sortRandomed}
sort empty list ${Quick.sortEmpty}
sort single-item list ${Quick.sortSingle}
sort equal items list ${Quick.sortEqTuple}
"""
val sorted = List(6,5,4,3,2,1)
val reversed = sorted.reverse
val randomed = List(3,4,5,2,1,6)
val empty = List.empty[Int]
val single = List(1)
val eqTuple = List(1,1)
val huge = (1 to 10000).toList
val hugeSorted = huge.reverse
object Quick {
def sortSorted = Sort.quick(sorted) mustEqual sorted
def sortReversed = Sort.quick(reversed) mustEqual sorted
def sortRandomed = Sort.quick(randomed) mustEqual sorted
def sortEmpty = Sort.quick(empty) mustEqual empty
def sortSingle = Sort.quick(single) mustEqual single
def sortEqTuple = Sort.quick(eqTuple) mustEqual eqTuple
def sortHuge = Sort.quick(huge) mustEqual hugeSorted
}
}
示例6: HelloWorldSpec
//设置package包名称以及导入依赖的类
package com.tomogle.specs2.acceptance
import org.specs2.Specification
class HelloWorldSpec extends Specification { def is =
s2"""
Specification to check the 'Hello, world' String
The 'Hello, world' String should
contain 12 characters $e1
start with 'Hello' $e2
end with 'world' $e3
"""
val underTest = "Hello, world"
def e1 = underTest must have size 12
def e2 = underTest must startWith("Hello")
def e3 = underTest must endWith("world")
}
示例7: EitherSpec
//设置package包名称以及导入依赖的类
package fpinscala.errorhandling
import org.specs2.Specification
class EitherSpec extends Specification { def is = s2"""
Either[E, A] related exercises for Chapter 4:
map function should square 2 for Right(2) and nothing for Left(NumberFormatException) $exer1
flatMap function should square the string "2" for Right("2") and Left(NumberFormatException) for Right("x") $exer2
"""
def exer1 = {
val either1 = Right(2)
val either2: Either[Exception, Int] = Left(new NumberFormatException)
either1.map(n => n * n) must_== Right(4)
either2.map(n => n * n) must_== Left(new NumberFormatException)
}
def exer2 = {
val either1 = Right("2")
val either2 = Right("x")
def squareString(s: String): Either[Exception, Int] = {
try {
val v = s.toInt
Right(v * v)
} catch {
case e: Exception => Left(e)
}
}
either1.flatMap(s => squareString(s)) must_== Right(4)
either2.flatMap(s => squareString(s)) must_== Left(new NumberFormatException)
}
}
示例8: MiscSpec
//设置package包名称以及导入依赖的类
package fpinscala.errorhandling
import org.specs2.Specification
class MiscSpec extends Specification { def is = s2"""
Answer to miscellanious exercises for Chapter 4:
Write a function to calculate the variance of a sequence using flatMap.
Using Seq(1, 3, 4, 1, 23), it should be 70.24000000000002 $exer1
Write a map2 function, which takes a function f(A, B) => C as parameter $exer2
"""
def exer1 =
Misc.variance(List(1, 3, 4, 1, 23)) must_== Some(70.24000000000002)
def exer2 = {
def calcSalary(name: String, job: String) = job match {
case "boss" => 10000.0f
case _ => name.size.toFloat * 100.0f
}
val optA = Some("Bob")
val optB = Some("boss")
Option.map2(optA, optB)(calcSalary) must_== Some(10000.0f)
Option.map2(optA, None())(calcSalary) must_== None()
Option.map2(None(), optB)(calcSalary) must_== None()
Option.map2(None(), None())(calcSalary) must_== None()
}
}
示例9: OptionSpec
//设置package包名称以及导入依赖的类
package fpinscala.errorhandling
import org.specs2.Specification
class OptionSpec extends Specification { def is = s2"""
Option[T] related exercises for Chapter 4:
Use map function to increment the value of an Option[Int] $exer1
sequence must return None if there is a None in the list $exerSeq
sequence must return Some(List(1, 2)) for List(Some(1), Some(2)) $exerSeq2
sequence must return Some(List()) for List() $exerSeq3
Traverse must square all number in List(1, 2, 3, 4) $exerTraverse
Traverse must return None for List(1, 2, oo, 4) $exerTraverseWithNone
Traverse must return Some(List()) for List() $exerTraverseWithNone2
"""
def exer1 =
Some(4).map(_ + 1) must_== Some(5)
def exerSeq = {
val options = List(Some(1), None(), Some(2), Some(3))
Option.sequence(options) must_== None()
Option.sequence_1(options) must_== None()
Option.sequence_2(options) must_== None()
Option.sequence_t(options) must_== None()
}
def exerSeq2 = {
val options = List(Some(1), Some(2))
val result = Some(List(1, 2))
Option.sequence(options) must_== result
Option.sequence_1(options) must_== result
Option.sequence_2(options) must_== result
Option.sequence_t(options) must_== result
}
def exerSeq3 = {
val options: List[Option[Int]] = List()
val result: Option[List[Int]] = Some(List())
Option.sequence(options) must_== result
Option.sequence_1(options) must_== result
Option.sequence_2(options) must_== result
Option.sequence_t(options) must_== result
}
def exerTraverse =
Option.traverse(List(1, 2, 3, 4))(n => Some(n * n)) must_== Some(List(1, 4, 9, 16))
def exerTraverseWithNone =
Option.traverse(List(1, 2, Integer.MAX_VALUE, 4))(n => if (n != Integer.MAX_VALUE) Some(n * n) else None()) must_== None()
def exerTraverseWithNone2 =
Option.traverse(List() : List[Int])(n => Some(n + 1)) must_== Some(List())
}
示例10: TreeSpec
//设置package包名称以及导入依赖的类
package fpinscala.datastructures
import org.specs2.Specification
class TreeSpec extends Specification { def is = s2"""
Given the following tree:
*
/ \
* *
/ \ / \
1 5 * 4
/ \
3 6
Its size is 5 $exer1
Its maximum node value is 6 $exer2
Its depth is 4 $exer3
It should duplicate the node values $exer4
"""
private val tree = Branch(Branch(Leaf(1), Leaf(5)), Branch(Branch(Leaf(3), Leaf(6)), Leaf(4)))
def exer1 =
Tree.size(tree) must_== 5
def exer2 =
Tree.maximum(tree) must_== 6
def exer3 =
Tree.depth(tree) must_== 3
def exer4 =
Tree.map(tree){ _ * 2 } must_== Branch(Branch(Leaf(2), Leaf(10)), Branch(Branch(Leaf(6), Leaf(12)), Leaf(8)))
}
示例11: Week1Spec
//设置package包名称以及导入依赖的类
package coursera
import org.specs2.Specification
class Week1Spec extends Specification { def is = s2"""
Specification for week1 exercises from the Scala Coursera course:
The pascal triangle for (0, 0) should be 1 ${exer1(0, 0, 1)}
The pascal triangle for (1, 0) should be 1 ${exer1(1, 0, 1)}
The pascal triangle for (1, 1) should be 1 ${exer1(1, 1, 1)}
The pascal triangle for (2, 0) should be 1 ${exer1(2, 0, 1)}
The pascal triangle for (2, 1) should be 2 ${exer1(2, 1, 2)}
The pascal triangle for (2, 2) should be 1 ${exer1(2, 2, 1)}
The pascal triangle for (3, 0) should be 1 ${exer1(3, 0, 1)}
The pascal triangle for (3, 1) should be 3 ${exer1(3, 1, 3)}
The pascal triangle for (3, 2) should be 3 ${exer1(3, 2, 3)}
The pascal triangle for (3, 3) should be 1 ${exer1(3, 3, 1)}
The pascal triangle for (4, 0) should be 1 ${exer1(4, 0, 1)}
The pascal triangle for (4, 1) should be 4 ${exer1(4, 1, 4)}
The pascal triangle for (4, 2) should be 6 ${exer1(4, 2, 6)}
The pascal triangle for (4, 3) should be 4 ${exer1(4, 3, 4)}
The pascal triangle for (4, 4) should be 1 ${exer1(4, 4, 1)}
Specifications for exercise 2, checking if the parenthesis of a string are balanced:
"(if (zero? x) max (/ 1 x))" is balanced ${exer2("(if (zero? x) max (/ 1 x))", balanced = true)}
"I told him (that it’s not (yet) done). (But he wasn’t listening)" is balanced ${exer2("I told him (that it’s not (yet) done). (But he wasn’t listening)", balanced = true)}
":((---)" is not balanced ${exer2(":((---)", balanced = false)}
"())(" is not balanced ${exer2("())(", balanced = false)}
Specifications for exercise 3, count change problem:
There are 4 ways to represent 6 with coins 1 and 2 ${exer3(4)}
"""
def exer1(row: Int, col: Int, value: Int) =
Week1.pascal(row, col) must_== value
def exer2(string: String, balanced: Boolean) =
Week1.balance(string.toList) must_== balanced
def exer3(expected: Int) =
Week1.countChange(6, List(1, 2)) must_== expected
}
示例12: NinjaNameGeneratorTest
//设置package包名称以及导入依赖的类
package model
import org.specs2.Specification
class NinjaNameGeneratorTest extends Specification { def is = s2"""
This is a specification to check the 'NinjaNameGenerator'
NinjaNameGenerator.generate should
return "" if name is "" $e1
return "Tokimimo" if name is "nico" $e2
return "" if name is a number $e3
return "Tokimimotakaari Mikarukatatamo" if name is "Nicolas Cavallo" $e4
"""
def e1 = NinjaNameGenerator.generate("") must beEqualTo("")
def e2 = NinjaNameGenerator.generate("nico") must beEqualTo("Tokimimo")
def e3 = NinjaNameGenerator.generate("1234") must beEqualTo("")
def e4 = NinjaNameGenerator.generate("Nicolas Cavallo") must beEqualTo("Tokimimotakaari Mikarukatatamo")
}
示例13: RegularizationTest
//设置package包名称以及导入依赖的类
package neuroflow.nets
import breeze.linalg.DenseVector
import neuroflow.core.Activator.Linear
import neuroflow.core.EarlyStoppingLogic.CanAverage
import neuroflow.core._
import neuroflow.core.FFN.WeightProvider.oneWeights
import neuroflow.core.Network.Vector
import neuroflow.nets.DefaultNetwork._
import org.specs2.Specification
import org.specs2.specification.core.SpecStructure
import shapeless._
import breeze.numerics._
import breeze.stats._
import scala.collection.Seq
class RegularizationTest extends Specification {
def is: SpecStructure =
s2"""
This spec will test the regularization techniques.
It should:
- Check the early stopping logic $earlyStopping
"""
def earlyStopping = {
import neuroflow.common.VectorTranslation._
val (xs, ys) = (Vector(Vector(1.0), Vector(2.0), Vector(3.0)), Vector(Vector(3.2), Vector(5.8), Vector(9.2)))
val net = Network(Input(1) :: Hidden(3, Linear) :: Output(1, Linear) :: HNil,
Settings(regularization = Some(EarlyStopping(xs, ys, 0.8))))
implicit object KBL extends CanAverage[DefaultNetwork] {
def averagedError(xs: Seq[Vector], ys: Seq[Vector]): Double = {
val errors = xs.map(net.evaluate).zip(ys).toVector.map {
case (a, b) => mean(abs(a.dv - b.dv))
}.dv
mean(errors)
}
}
net.evaluate(Vector(1.0)) must be equalTo Vector(3.0)
net.evaluate(Vector(2.0)) must be equalTo Vector(6.0)
net.evaluate(Vector(3.0)) must be equalTo Vector(9.0)
net.shouldStopEarly must be equalTo false
net.shouldStopEarly must be equalTo true
}
}
示例14: DefaultNetworkNumTest
//设置package包名称以及导入依赖的类
import neuroflow.core.Activator._
import neuroflow.core._
import org.specs2.Specification
import org.specs2.specification.core.SpecStructure
import shapeless._
class DefaultNetworkNumTest extends Specification {
def is: SpecStructure =
s2"""
This spec will test the gradients from DefaultNetwork by comparison of the derived values with
the approximated ones.
- Check the gradients $gradCheck
"""
def gradCheck = {
import neuroflow.core.FFN.WeightProvider.oneWeights
import neuroflow.nets.DefaultNetwork._
val layout =
Input(2) ::
Hidden(3, Sigmoid) ::
Hidden(4, Sigmoid) ::
Hidden(5, Sigmoid) ::
Hidden(6, Sigmoid) ::
Hidden(5, Sigmoid) ::
Hidden(4, Sigmoid) ::
Hidden(3, Sigmoid) ::
Output(2, Sigmoid) :: HNil
val netA = Network(layout, Settings(learningRate = { case _ => 1.0 }, iterations = 1, approximation = Some(Approximation(1E-5))))
val netB = Network(layout, Settings(learningRate = { case _ => 1.0 }, iterations = 1))
val xs = Seq(Vector(0.5, 0.5), Vector(1.0, 1.0))
netA.train(xs, xs)
netB.train(xs, xs)
println(netA)
println(netB)
val tolerance = 1E-3
val equal = netA.weights.zip(netB.weights).map {
case (a, b) =>
(a - b).forall { (w, v) =>
println(s"dw($w) - approx(dw($w)): " + v.abs)
v.abs < tolerance
}
}.reduce { (l, r) => l && r }
if (equal) success else failure
}
}
示例15: IoTest
//设置package包名称以及导入依赖的类
import neuroflow.application.plugin.IO.{File, Json}
import neuroflow.core.Activator.Sigmoid
import neuroflow.core._
import neuroflow.nets.DefaultNetwork.constructor
import org.specs2.Specification
import org.specs2.specification.core.SpecStructure
import shapeless._
class IoTest extends Specification {
sequential // IO race conditions will occur otherwise
def is: SpecStructure = s2"""
This spec will test IO related functionality.
It should:
- Serialize a net $serialize
- Deserialize a net $deserialize
"""
val layers = Input(2) :: Hidden(3, Sigmoid) :: Output(2, Sigmoid) :: HNil
val measure = {
import neuroflow.core.FFN.WeightProvider.zeroWeights
Network(layers)
}
val asJson = "[{\"rows\":2,\"cols\":3,\"data\":[0.0,0.0,0.0,0.0,0.0,0.0]},{\"rows\":3,\"cols\":2,\"data\":[0.0,0.0,0.0,0.0,0.0,0.0]}]"
def serialize = {
val serialized = Json.write(measure)
serialized === asJson
}
def deserialize = {
implicit val wp = Json.read(asJson)
val deserialized = Network(layers)
deserialized.weights.toArray.map(_.toArray) === measure.weights.toArray.map(_.toArray)
}
}