• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala ScalaCheck类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了ScalaCheck类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
    }
  }
} 
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:38,代码来源:RefusedByRateLimiterErrorSpec.scala


示例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)
} 
开发者ID:janstenpickle,项目名称:uscala-cats,代码行数:31,代码来源:ApplicativeSpec.scala


示例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))
  }
} 
开发者ID:ShiftForward,项目名称:apso,代码行数:17,代码来源:CounterPairSpec.scala


示例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))
      }
    }

  }

} 
开发者ID:ioaccept,项目名称:pizza,代码行数:57,代码来源:StoveSpecification.scala


示例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)
    }
  }
} 
开发者ID:sihingkk,项目名称:shortest-edit-script-scala,代码行数:57,代码来源:MyersDiffTest.scala


示例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)
  }
} 
开发者ID:mediachain,项目名称:oldchain,代码行数:35,代码来源:CborASTSpec.scala


示例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('|')
} 
开发者ID:janstenpickle,项目名称:scala-vault,代码行数:52,代码来源:RuleSpec.scala


示例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)
} 
开发者ID:janstenpickle,项目名称:scala-vault,代码行数:57,代码来源:PolicyIT.scala


示例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))
} 
开发者ID:janstenpickle,项目名称:scala-vault,代码行数:52,代码来源:UserPassIT.scala


示例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)
} 
开发者ID:janstenpickle,项目名称:scala-vault,代码行数:39,代码来源:AuthIT.scala


示例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
  }

} 
开发者ID:aimacode,项目名称:aima-scala,代码行数:33,代码来源:ReflexVacuumAgentProgramSpec.scala


示例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))
    }
  }
} 
开发者ID:hydra-technologies,项目名称:alphard-sbt,代码行数:61,代码来源:PropertiesTest.scala


示例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)
  }

} 
开发者ID:hydra-technologies,项目名称:alphard-sbt,代码行数:56,代码来源:RichCloseableTest.scala


示例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


示例16: ListOrderBookCancelingSpec

//设置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 ListOrderBookCancelingSpec 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) =>
    ListOrderBook.handle(
      () => ei, ListOrderBook.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) =>
    (ListOrderBook.handle(
      () => ei, _: ListOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => ListOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(ListOrderBook.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) =>
    (ListOrderBook.handle(
      () => ei, _: ListOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => ListOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(ListOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

} 
开发者ID:PacktPublishing,项目名称:Scala-High-Performance-Programming,代码行数:54,代码来源:ListOrderBookCancelingSpec.scala


示例17: QueueOrderBookCancelingSpec

//设置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 QueueOrderBookCancelingSpec 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) =>
    QueueOrderBook.handle(
      () => ei, QueueOrderBook.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) =>
    (QueueOrderBook.handle(
      () => ei, _: QueueOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => QueueOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(QueueOrderBook.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) =>
    (QueueOrderBook.handle(
      () => ei, _: QueueOrderBook, AddLimitOrder(ci, o))).andThen {
      case (ob, _) => QueueOrderBook.handle(
        () => ei, ob, CancelOrder(ci, o.id))._2
    }(QueueOrderBook.empty) ==== OrderCanceled(ei, o.id)
  }

} 
开发者ID:PacktPublishing,项目名称:Scala-High-Performance-Programming,代码行数:54,代码来源:QueueOrderBookCancelingSpec.scala


示例18: ZeroOrPosLong

//设置package包名称以及导入依赖的类
package org.pico.hashids

import org.pico.hashids.syntax._
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification

case class ZeroOrPosLong(value: Long)

case class Size(size: Int)

class CheckHashids extends Specification with ScalaCheck {
  import CheckHashids._

  "List of random zero or positive longs should encode then decode" in {
    prop { (a: List[ZeroOrPosLong], salt: String) =>
      implicit val hashid = Hashids.reference(salt)

      a.raw.hashid.unhashid ==== a.raw
    }
  }

  "List of random zero or positive longs should encode then decode" in {
    prop { (a: List[ZeroOrPosLong], salt: String) =>
      implicit val hashid = Hashids.reference(salt = salt)

      a.raw.hashid.unhashid ==== a.raw
    }
  }

  "List of random zero or positive longs should encode then decode and honour min hash length" in {
    prop { (a: List[ZeroOrPosLong], salt: String, minHashLength: Size) =>
      implicit val hashid = Hashids.reference(salt = salt, minHashLength = minHashLength.size)

      val hash = a.raw.hashid

      hash.unhashid ==== a.raw
      hash.length must be >= minHashLength.size when !a.isEmpty
    }
  }
}

object CheckHashids {
  implicit val arbitraryZeroOrPosLong: Arbitrary[ZeroOrPosLong] = Arbitrary {
    Gen.chooseNum(0L, Long.MaxValue, 2L, 75527867232L).map(ZeroOrPosLong(_))
  }

  implicit val arbitrarySize: Arbitrary[Size] = Arbitrary {
    Gen.chooseNum(0, 50).map(Size(_))
  }

  implicit class RichListZeroOrPosLong(self: List[ZeroOrPosLong]) {
    def raw = self.map(_.value)
  }
} 
开发者ID:pico-works,项目名称:pico-hashids,代码行数:56,代码来源:CheckHashids.scala


示例19: RaySpec

//设置package包名称以及导入依赖的类
import math.{Ray, Vector3}
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Prop._
import org.specs2.{ScalaCheck, Specification}

class RaySpec extends Specification with ScalaCheck {

  //TODO separate special cases of reflection and refraction
  def is =
    s2"""
  A ray should
    calculate the direction of a reflection correctly $testReflection
    calculate the direction of a refraction correctly $testRefraction
    calculate the position for a given marching diretion

  """

  val testReflection = forAll { (dir: Vector3, o: Vector3) =>
    {
      val ray = Ray(origin = o, direction = dir.normalized)
      val rray = ray.reflectedAt(o, -ray.direction)
      (rray.direction + ray.direction).length < 0.01 && rray.depth == ray.depth + 1 && ray.n == rray.n
    }
  }

  val testRefraction = forAll { (dir: Vector3, o: Vector3, norm: Vector3) =>
    {
      val ray = Ray(origin = o, direction = dir.normalized)
      val refractedRay =
        ray.refractedAt(position = o, normal = norm, newN = 1f)

      refractedRay match {
        case None => false
        case Some(rray) =>
          (rray.direction - ray.direction).length < 0.01 && rray.depth == ray.depth + 1 && rray.n == 1
      }
    }
  }

  implicit lazy val VectorGen: Arbitrary[Vector3] =
    Arbitrary {
      for {
        x: Double <- Gen.choose(-.9, .9)
        y: Double <- Gen.choose(-.9, .9)
        z: Double <- Gen.choose(-.9, .9)
      } yield Vector3(x, y, z)
    }

} 
开发者ID:wookenny,项目名称:scalarty,代码行数:50,代码来源:RaySpec.scala


示例20: AABBSpec

//设置package包名称以及导入依赖的类
import math.{AABB, Ray, Vector3}
import org.specs2.{ScalaCheck, Specification}

class AABBSpec extends Specification with ScalaCheck {
  def is = s2"""
   An AABB should
      be intersected frontally ${intersectFrontal}
      be intersected frontally from Inside ${intersectFrontalFromInside}
      be intersected frontally from the side $intersectFrontalFromSide
      be missed frontally ${missFrontal}

  """

  val aabb = AABB(.5f, 2, .5f, 2, .5f, 2)

  def intersectFrontal = {
    val hit = aabb.intersect(Ray(Vector3(1, 1, 0), Vector3.Z))
    (hit shouldNotEqual None) and
      (hit.get.normal shouldEqual (Vector3(0, 0, -1f)))
  }

  def intersectFrontalFromInside = {
    val hit = aabb.intersect(Ray(Vector3.ONE, Vector3.Z))
    (hit shouldNotEqual None) and
      (hit.get.normal shouldEqual (Vector3(0, 0, -1f)))
  }

  def intersectFrontalFromSide = {
    val pos = Vector3(-1, 2, 0)
    val ray = Ray(pos, (Vector3(1, 1, .5f) - pos).normalized)
    val hit = aabb.intersect(ray)
    (hit shouldNotEqual None) and
      (hit.get.normal shouldEqual (Vector3(0, 0, -1f)))
  }

  def missFrontal = {
    val hit = aabb.intersect(Ray(origin = Vector3.ZERO, direction = Vector3.Z))
    hit should be equalTo None
  }

} 
开发者ID:wookenny,项目名称:scalarty,代码行数:42,代码来源:AABBSpec.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Insets类代码示例发布时间:2022-05-23
下一篇:
Scala complete类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap