本文整理汇总了Scala中org.specs2.ScalaCheck类的典型用法代码示例。如果您正苦于以下问题:Scala ScalaCheck类的具体用法?Scala ScalaCheck怎么用?Scala ScalaCheck使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ScalaCheck类的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: ApplicativeSpec
//设置package包名称以及导入依赖的类
package uscala.cats.result
import cats.std.all._
import cats.syntax.cartesian._
import org.specs2.{ScalaCheck, Specification}
import uscala.cats.syntax.result._
import applicative._
import org.scalacheck.{Gen, Prop}
import uscala.result.Result
import uscala.result.specs2.ResultMatchers
class ApplicativeSpec extends Specification with ResultMatchers with ScalaCheck {
import ApplicativeSpec._
override def is =
s2"""
Can collect multiple failures on the left of a result $test
"""
def test = Prop.forAllNoShrink(list)(errs =>
errs.foldLeft(ResultNel.ok[String, String](new String))((acc, v) =>
(acc |@| Result.fail[String, String](v).toResultNel).map(_ + _)
) must beFail.like { case a => a.unwrap must containTheSameElementsAs(errs) }
)
}
object ApplicativeSpec {
val stringGen = Gen.alphaStr.suchThat(_.nonEmpty)
val list = Gen.listOf(stringGen).suchThat(_.nonEmpty)
}
示例3: CounterPairSpec
//设置package包名称以及导入依赖的类
package eu.shiftforward.apso
import org.specs2.mutable.Specification
import org.specs2.ScalaCheck
import org.scalacheck.Gen._
@deprecated("This will be removed in a future version", "2017/07/13")
class CounterPairSpec extends Specification with ScalaCheck {
"A counter pair" should {
"store two unsigned shorts" ! prop {
(short1: Int, short2: Int) =>
val CounterPair(x, y) = CounterPair(short1, short2)
x == short1 && y == short2
}.setGens(choose(0, 65535), choose(0, 65535))
}
}
示例4: StoveSpecification
//设置package包名称以及导入依赖的类
import models.{Stove, Pizza}
import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import org.specs2.ScalaCheck
@RunWith(classOf[JUnitRunner])
class StoveSpecification extends Specification with ScalaCheck {
"The stove" should {
"return three pizza at once if the capacity is 4" in {
val stove = new Stove(4)
val listOfPizza = List(new Pizza, new Pizza, new Pizza)
stove += listOfPizza
stove.next().length must_== 3
stove.next() must beEmpty
}
"return three pizza in two parts if the capacity is 2" in {
val stove = new Stove(2)
val listOfPizza = List(new Pizza, new Pizza, new Pizza)
stove += listOfPizza
stove.next().length must_== 2
stove.next().length must_== 1
stove.next() must beEmpty
}
"returns pizza in a correct way" in {
prop { (capacity: Int, noOfP: Int) =>
var capa = Math.abs(capacity % 10)
if (capa == 0) capa = 1
var noOfPizza = Math.abs(noOfP % 50)
if (noOfPizza == 0) noOfPizza = 25
val stove = new Stove(capa)
stove += List.fill(noOfPizza)(new Pizza)
var returnedPizza = 0
var noOfNext = -1
var nextPizza: Int = 0
do {
nextPizza = stove.next().length
noOfNext += 1
returnedPizza += nextPizza
} while (nextPizza != 0)
returnedPizza must_== noOfPizza
noOfNext must_== (noOfPizza / capa + (if (noOfPizza % capa > 0) 1 else 0))
}
}
}
}
示例5: MyersDiffTest
//设置package包名称以及导入依赖的类
package diff.myers
import diff.{Change, ItemChanged, ItemAdded, ItemRemoved}
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
class MyersDiffTest extends Specification with ScalaCheck {
def comparer = new MyersDiff()
"Applying diff" should {
"always pass" in prop { (left: Seq[Int], right: Seq[Int]) =>
val changes = comparer.compare(left, right)
Change.applyChanges(left, changes) should beEqualTo(right)
}
}
"compare " should {
"handle empty list comparisons" in {
comparer.compare(Seq("a"), Seq()) should equalTo(List(ItemRemoved(0, "a")))
comparer.compare(Seq("a", "c"), Seq()) should equalTo(List(ItemRemoved(0, "a"), ItemRemoved(0, "c")))
comparer.compare(Seq(), Seq("b")) should equalTo(List(ItemAdded(0, "b")))
comparer.compare(Seq(), Seq("b", "c")) should equalTo(List(ItemAdded(0, "b"), ItemAdded(1, "c")))
comparer.compare(Seq(), Seq()) should equalTo(List())
}
"handle addition" in {
comparer.compare(Seq("A", "C"), Seq("A", "B", "C")) should equalTo(
List(ItemAdded(1, "B"))
)
}
"handle substitution" in {
comparer.compare(Seq("A", "B", "C"), Seq("E", "B", "C")) should equalTo(List(ItemChanged(0, "A", "E")))
}
"handle removal" in {
comparer.compare(Seq("A", "B", "C", "D"), Seq("A", "C", "D")) should equalTo(
List(ItemRemoved(1, "B"))
)
}
"handle equal lists" in {
comparer.compare(Seq("A", "B"), Seq("A", "B")) should equalTo(List())
}
"Myers papers example" in {
val left = Seq("A", "B", "C", "A", "B", "B", "A")
val right = Seq("C", "B", "A", "B", "A", "C")
val changes = comparer.compare(left, right)
Change.applyChanges(left, changes) should beEqualTo(right)
}
}
}
示例6: CborASTSpec
//设置package包名称以及导入依赖的类
package io.mediachain.util.cbor
import java.io.ByteArrayOutputStream
import io.mediachain.BaseSpec
import io.mediachain.util.cbor.CborAST._
import org.specs2.ScalaCheck
object CborASTSpec extends BaseSpec with ScalaCheck {
import io.mediachain.util.cbor.CValueGenerators._
import co.nstant.in.cbor.CborEncoder
def is =
s2"""
- round-trip encodes to/from cbor-java DataItems $roundTripCborJava
"""
def roundTripCborJava = prop { cVal: CValue =>
val asDataItem = toDataItem(cVal)
val converted = toDataItem(fromDataItem(asDataItem))
// We're comparing the DataItem representation because it will not
// fail if the ordering of map keys differs, whereas CMaps will not
// be equal if the ordering is different
asDataItem must_== converted
// make sure byte representation is equal
val out = new ByteArrayOutputStream
new CborEncoder(out).encode(asDataItem)
out.close()
out.toByteArray must_== CborCodec.encode(cVal)
}
}
示例7: RuleSpec
//设置package包名称以及导入依赖的类
package janstenpickle.vault.manage
import janstenpickle.vault.manage.Model.Rule
import org.scalacheck.{Gen, Prop}
import org.specs2.{ScalaCheck, Specification}
import uscala.result.specs2.ResultMatchers
class RuleSpec extends Specification with ScalaCheck with ResultMatchers {
import RuleSpec._
override def is =
s2"""
Can encode and decode policy strings $passes
Cannot decode bad policy strings $fails
"""
def passes = Prop.forAllNoShrink(Gen.listOf(ruleGen).suchThat(_.nonEmpty)) (rules =>
Rule.decode(rules.map(_.encode).mkString("\n")) must beOk.like {
case a => a must containAllOf(rules)
}
)
def fails = Prop.forAllNoShrink(Gen.listOf(badRuleGen).suchThat(_.nonEmpty)) (rules =>
Rule.decode(rules.mkString("\n")) must beFail
)
}
object RuleSpec {
val policyGen = Gen.option(Gen.oneOf("read", "write", "sudo", "deny"))
val capabilitiesGen = Gen.option(
Gen.listOf(Gen.oneOf("create", "read", "update", "delete", "list", "sudo", "deny")).
suchThat(_.nonEmpty).
map(_.distinct)
)
val ruleGen = for {
path <- Gen.alphaStr.suchThat(_.nonEmpty)
policy <- policyGen
capabilities <- capabilitiesGen
} yield Rule(path, capabilities, policy)
val badRuleGen = for {
path <- Gen.alphaStr.suchThat(_.nonEmpty)
policy <- policyGen
capabilities <- capabilitiesGen
} yield
s"""
|path "$path"
| $policy cage
| $capabilities }""".stripMargin('|')
}
示例8: PolicyIT
//设置package包名称以及导入依赖的类
package janstenpickle.vault.manage
import janstenpickle.vault.core.VaultSpec
import janstenpickle.vault.manage.Model.Rule
import org.scalacheck.{Gen, Prop}
import org.specs2.ScalaCheck
import uscala.result.Result
class PolicyIT extends VaultSpec with ScalaCheck {
import PolicyIT._
import VaultSpec._
override def is =
s2"""
Can successfully set and get policies $happy
Cannot set an invalid policy $sad
"""
lazy val underTest = Policy(config)
def happy = Prop.forAllNoShrink(
longerStrGen,
Gen.listOf(ruleGen(longerStrGen, policyGen, capabilitiesGen)).
suchThat(_.nonEmpty)) { (name, rules) =>
(underTest.set(name.toLowerCase, rules)
.attemptRun(_.getMessage()) must beOk) and
(underTest.inspect(name.toLowerCase)
.attemptRun(_.getMessage()) must beOk) and
(underTest.delete(name.toLowerCase).attemptRun(_.getMessage()) must beOk)
}
// cannot use generated values here as
// vault seems to have a failure rate limit
def sad = underTest.set(
"nic", List(Rule("cage", Some(List("kim", "copolla"))))
).attemptRun(_.getMessage()) must beFail
}
object PolicyIT {
val policyGen = Gen.option(Gen.oneOf("read", "write", "sudo", "deny"))
val capabilitiesGen =
Gen.listOf(Gen.oneOf(
"create", "read", "update", "delete", "list", "sudo", "deny")).
suchThat(_.nonEmpty).
map(_.distinct)
def ruleGen(
pathGen: Gen[String],
polGen: Gen[Option[String]],
capGen: Gen[List[String]]
) = for {
path <- pathGen
policy <- polGen
capabilities <- capGen
} yield Rule(path, Some(capabilities), policy)
}
示例9: UserPassIT
//设置package包名称以及导入依赖的类
package janstenpickle.vault.manage
import janstenpickle.vault.core.VaultSpec
import org.scalacheck.{Gen, Prop}
import org.specs2.ScalaCheck
class UserPassIT extends VaultSpec with ScalaCheck {
import UserPassIT._
import VaultSpec._
def is =
s2"""
Can create, update and delete a user $good
Cannot create a user for a non-existent client $badClient
Cannot create user with a bad policy $badPolicy
"""
lazy val underTest = UserPass(config)
lazy val authAdmin = Auth(config)
def good = Prop.forAllNoShrink(longerStrGen, longerStrGen, longerStrGen, Gen.posNum[Int], longerStrGen, policyGen)(
(username, password, newPassword, ttl, client, policy) =>
(authAdmin.enable("userpass", Some(client)).attemptRun(_.getMessage()) must beOk) and
(underTest.create(username, password, ttl, None, client).attemptRun(_.getMessage()) must beOk) and
(underTest.setPassword(username, newPassword, client).attemptRun(_.getMessage()) must beOk) and
(underTest.setPolicies(username, policy, client).attemptRun(_.getMessage()) must beOk) and
(underTest.delete(username, client).attemptRun(_.getMessage()) must beOk) and
(authAdmin.disable(client).attemptRun(_.getMessage()) must beOk)
)
def badClient = Prop.forAllNoShrink(longerStrGen, longerStrGen, Gen.posNum[Int], longerStrGen)(
(username, password, ttl, client) =>
underTest.create(username, password, ttl, None, client).attemptRun(_.getMessage()) must beFail
)
def badPolicy = Prop.forAllNoShrink(longerStrGen,
longerStrGen,
Gen.posNum[Int],
longerStrGen,
Gen.listOf(longerStrGen.suchThat(!policies.contains(_))))(
(username, password, ttl, client, policy) =>
(authAdmin.enable("userpass", Some(client)).attemptRun(_.getMessage()) must beOk) and
(underTest.create(username, password, ttl, Some(policy), client).attemptRun(_.getMessage()) must beOk) and
(authAdmin.disable(client).attemptRun(_.getMessage()) must beOk)
)
}
object UserPassIT {
val policies = List("default", "root")
val policyGen = Gen.listOf(Gen.oneOf(policies))
}
示例10: AuthIT
//设置package包名称以及导入依赖的类
package janstenpickle.vault.manage
import janstenpickle.vault.core.VaultSpec
import org.scalacheck.{Prop, Gen}
import org.specs2.ScalaCheck
class AuthIT extends VaultSpec with ScalaCheck {
import AuthIT._
import VaultSpec._
def is =
s2"""
Can enable and disable valid auth mount $happy
Cannot enable an invalid auth type $enableFail
"""
lazy val underTest = new Auth(config)
def happy = Prop.forAllNoShrink(
backends, longerStrGen, Gen.option(longerStrGen))((backend, mount, desc) =>
(underTest.enable(backend, Some(mount), desc)
.attemptRun(_.getMessage()) must beOk) and
(underTest.disable(mount).attemptRun(_.getMessage()) must beOk)
)
def enableFail = Prop.forAllNoShrink(
longerStrGen.suchThat(!backendNames.contains(_)),
longerStrGen,
Gen.option(longerStrGen))((backend, mount, desc) =>
underTest.enable(mount).attemptRun(_.getMessage()) must beFail
)
}
object AuthIT {
val backendNames = List("github", "app-id", "ldap", "userpass")
val backends = Gen.oneOf(backendNames)
}
示例11: ReflexVacuumAgentProgramSpec
//设置package包名称以及导入依赖的类
package aima.core.environment.vacuum
import aima.core.agent.{Environment, Sensor, Actuator, AgentProgram}
import org.scalacheck.Arbitrary
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
import scala.annotation.tailrec
class ReflexVacuumAgentProgramSpec extends Specification with ScalaCheck {
implicit val arbVacuumEnvironment = Arbitrary(VacuumEnvironment())
"should eventually clean environment" in prop { env: VacuumEnvironment =>
val agentProgram = new AgentProgram {
lazy val agent = new SimpleReflexVacuumAgent
lazy val actuators = Seq[Actuator](new SuckerActuator(agent), new MoveActuator(agent))
lazy val sensors = Seq[Sensor](new DirtSensor(agent), new AgentLocationSensor(agent))
}
@tailrec def eventuallyClean(currentEnv: Environment): Boolean = {
currentEnv match {
case ve: VacuumEnvironment if ve.isClean() => true
case _ => eventuallyClean(agentProgram.run(currentEnv))
}
}
eventuallyClean(env.addAgent(agentProgram.agent)) must beTrue
}
}
示例12: PropertiesTest
//设置package包名称以及导入依赖的类
package io.alphard.sbt
import io.alphard.sbt.util.Properties
import io.alphard.sbt.util.Properties._
import org.scalacheck.Prop
import org.specs2.{ScalaCheck, Specification}
import scala.language.reflectiveCalls
object PropertiesTest
extends Specification
with ScalaCheck {
lazy val is = s2"""IO provides helpers methods that should
convert a properties object to java properties object $convertPropertiesToJavaProperties
convert a properties object to json object $convertPropertiesToJson
deep merge two properties $deepMergeProperties()
"""
def convertPropertiesToJavaProperties() = {
Prop.forAll(PropertiesArbitrary.propertiesGenerator(5, 2, "")) {
(properties: Properties) =>
val javaProperties = Properties.propertiesToJavaProperties(properties)
val newProperties = Properties.javaPropertiesToProperties(javaProperties)
newProperties must_== properties
}
}
def convertPropertiesToJson() = {
Prop.forAll(PropertiesArbitrary.propertiesGenerator(5, 2, "")) {
(properties: Properties) =>
val json = Properties.propertiesToJson(properties)
val newProperties = Properties.jsonToProperties(json)
newProperties must_== properties
}
}
def deepMergeProperties() = {
//@volatile var show = true
Prop.forAll(PropertiesArbitrary.propertiesGenerator(3, 5, "first_"), PropertiesArbitrary.propertiesGenerator(4, 4, "second_")) {
(firstProperties: Properties, secondProperties: Properties) =>
val path = Path {
(for (i <- 0 to 15) yield "altered_key_" + i): _*
}
val key1 = "______THEKEY1______"
val value1 = "_____THEVALUE1_____"
val key2 = "______THEKEY2______"
val value2 = "_____THEVALUE2_____"
val alteredFirstProperties = firstProperties.+(path / key1, value1)
val alteredSecondProperties = secondProperties.+(path / key2, value2)
val alteredMergedProperties = alteredFirstProperties +++ alteredSecondProperties
(firstProperties +++ firstProperties must_== firstProperties) and
((firstProperties +++ secondProperties).size must_== firstProperties.size + secondProperties.size) and
(alteredMergedProperties.get(path / key1) must_== Some(value1)) and
(alteredMergedProperties.get(path / key2) must_== Some(value2))
}
}
}
示例13: RichCloseableTest
//设置package包名称以及导入依赖的类
package io.alphard.sbt.util
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, File}
import scala.language.reflectiveCalls
import org.specs2.specification.Fragments
import org.specs2.{Specification, ScalaCheck}
import XIO._
object RichCloseableTest
extends Specification
with ScalaCheck {
override def is: Fragments =
s2"""
RichClosable should:
Close output stream and input stream after read and write ${closeInputAndOutputStream()}
"""
def closeInputAndOutputStream() = {
val message = "Hello World!"
val byteArrayInputStream = new ByteArrayInputStream(message.getBytes) {
var isClosed: Boolean = false
override def close(): Unit = {
isClosed = true
super.close()
}
}
val byteArrayOutputStream = new ByteArrayOutputStream() {
var isClosed: Boolean = false
override def close(): Unit = {
isClosed = true
super.close()
}
}
(byteArrayInputStream, byteArrayOutputStream) foreach {
case (in, out) =>
val buffer = new Array[Byte](1024)
var read = in.read(buffer, 0, buffer.length)
while(read > -1) {
out.write(buffer, 0, read)
read = in.read(buffer, 0, buffer.length)
}
}
(byteArrayInputStream.isClosed must_== true) and
(byteArrayOutputStream.isClosed must_== true) and
new String(byteArrayOutputStream.toByteArray).equals(message)
}
}
示例14: OrderBookCancelingSpec
//设置package包名称以及导入依赖的类
package highperfscala
package orderbook
import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{OrderCanceled, OrderCancelRejected}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
class OrderBookCancelingSpec extends Specification with ScalaCheck {
"""Given empty book
|When cancel order arrives
|Then OrderCancelRejected
""".stripMargin ! Prop.forAll(OrderId.genOrderId) { id =>
OrderBook.handle(OrderBook.empty, CancelOrder(id))._2 ====
OrderCancelRejected
}
"""Given empty book
|and buy limit order added
|When cancel order arrives
|Then OrderCanceled
""".stripMargin ! Prop.forAll(BuyLimitOrder.genBuyLimitOrder) { o =>
(OrderBook.handle(_: OrderBook, AddLimitOrder(o))).andThen {
case (ob, _) => OrderBook.handle(ob, CancelOrder(o.id))._2
}(OrderBook.empty) ==== OrderCanceled
}
"""Given empty book
|and sell limit order added
|When cancel order arrives
|Then OrderCanceled
""".stripMargin ! Prop.forAll(SellLimitOrder.genSellLimitOrder) { o =>
(OrderBook.handle(_: OrderBook, AddLimitOrder(o))).andThen {
case (ob, _) => OrderBook.handle(ob, CancelOrder(o.id))._2
}(OrderBook.empty) ==== OrderCanceled
}
}
开发者ID:PacktPublishing,项目名称:Scala-High-Performance-Programming,代码行数:41,代码来源:OrderBookCancelingSpec.scala
示例15: LazyCancelOrderBookCancelingSpec
//设置package包名称以及导入依赖的类
package highperfscala.orderbook
import highperfscala.orderbook.Commands.{AddLimitOrder, CancelOrder}
import highperfscala.orderbook.Events.{OrderCancelRejected, OrderCanceled}
import org.scalacheck.Prop
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
class LazyCancelOrderBookCancelingSpec extends Specification with ScalaCheck {
"""Given empty book
|When cancel order arrives
|Then OrderCancelRejected
""".stripMargin ! Prop.forAll(
OrderId.genOrderId,
CommandInstant.genCommandInstant,
EventInstant.genEventInstant) { (id, ci, ei) =>
LazyCancelOrderBook.handle(
() => ei, LazyCancelOrderBook.empty, CancelOrder(ci, id))._2 ====
OrderCancelRejected(ei, id)
}
"""Given empty book
|and buy limit order added
|When cancel order arrives
|Then OrderCanceled
""".stripMargin ! Prop.forAll(
BuyLimitOrder.genBuyLimitOrder,
CommandInstant.genCommandInstant,
EventInstant.genEventInstant) { (o, ci, ei) =>
(LazyCancelOrderBook.handle(
() => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, o))).andThen {
case (ob, _) => LazyCancelOrderBook.handle(
() => ei, ob, CancelOrder(ci, o.id))._2
}(LazyCancelOrderBook.empty) ==== OrderCanceled(ei, o.id)
}
"""Given empty book
|and sell limit order added
|When cancel order arrives
|Then OrderCanceled
""".stripMargin ! Prop.forAll(
SellLimitOrder.genSellLimitOrder,
CommandInstant.genCommandInstant,
EventInstant.genEventInstant) { (o, ci, ei) =>
(LazyCancelOrderBook.handle(
() => ei, _: LazyCancelOrderBook, AddLimitOrder(ci, o))).andThen {
case (ob, _) => LazyCancelOrderBook.handle(
() => ei, ob, CancelOrder(ci, o.id))._2
}(LazyCancelOrderBook.empty) ==== OrderCanceled(ei, o.id)
}
}
开发者ID:PacktPublishing,项目名称:Scala-High-Performance-Programming,代码行数:54,代码来源:LazyCancelOrderBookCancelingSpec.scala