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

Scala forAll类代码示例

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

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



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

示例1: FailureSpec

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

import org.scalacheck.Prop.forAll
import org.specs2._
import roc.types.failures._

final class FailureSpec extends Specification with ScalaCheck { def is = s2"""

  BinaryDecodingUnsupportedFailure
    must have correct error message  $testBinaryDecodingFailureErrMsg

  TextDecodingUnsupportedFailure
    must have correct error message  $testTextDecodingFailureErrMsg

  NullDecodedFailure
    must have correct error message  $testNullDecodedFailureErrMsg

  ElementDecodingFailure
    must have correct error message $testElementDecodingFailureErrMsg
                                                                           """

  val testBinaryDecodingFailureErrMsg = forAll { s: String =>
    val failure = new BinaryDecodingUnsupportedFailure(s)
    failure.getMessage() must_== s"Binary decoding of type $s is currently unsupported."
  }

  val testTextDecodingFailureErrMsg = forAll { s: String =>
    val failure = new TextDecodingUnsupportedFailure(s)
    failure.getMessage() must_== s"Text decoding of type $s is currently unsupported."
  }

  val testNullDecodedFailureErrMsg = forAll { s: String =>
    val failure = new NullDecodedFailure(s)
    failure.getMessage() must_== 
      s"A NULL value was decoded for type $s. Hint: use the Option[$s] decoder, or ensure that Postgres cannot return NULL for the requested value."
  }

  val testElementDecodingFailureErrMsg = forAll { (s: String, t: Throwable) =>
    val failure = new ElementDecodingFailure(s, t)
    failure.getMessage() must_== s"Failure to decode $s. ${t.getMessage()}"
  }
} 
开发者ID:finagle,项目名称:roc,代码行数:44,代码来源:FailureSpec.scala


示例2: MessagesSpec

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

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._

final class MessagesSpec extends Specification with ScalaCheck { def is = s2"""

  PasswordMessage
    should MD5 encrypt a password with given salt           $pmEncrypt
                                                                            """

  val pmEncrypt = forAll { (user: String, pm: PasswordMessage, salt: Array[Byte]) =>
    val md = MessageDigest.getInstance("MD5")
    md.update((pm.password+ user).getBytes(StandardCharsets.UTF_8))
    val unsaltedHexStr = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("")(_ + _)
    val saltedBytes = unsaltedHexStr.getBytes ++ salt
    md.reset()
    md.update(saltedBytes)
    val passwd = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("md5")(_ + _)
    passwd must_== PasswordMessage.encryptMD5Passwd(user, pm.password, salt)
  }
  
  lazy val genByte: Gen[Byte] = arbitrary[Byte]
  lazy val genSalt: Gen[Array[Byte]] = Gen.containerOfN[Array, Byte](4, genByte)
  lazy val genPasswordMessage: Gen[PasswordMessage] = for {
    password    <-  arbitrary[String]
  } yield new PasswordMessage(password)
  implicit lazy val implicitPasswordMessage: Arbitrary[PasswordMessage] = 
    Arbitrary(genPasswordMessage)
} 
开发者ID:finagle,项目名称:roc,代码行数:36,代码来源:MessageSpec.scala


示例3: ResultsSpec

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

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._
import org.specs2.mock.Mockito
import org.specs2.specification.core._
import roc.postgresql.failures.ElementNotFoundFailure

final class ResultsSpec extends Specification with ScalaCheck with Mockito { def is = s2"""

  Row
    get(column) must throw ElementNotFound failure for unknown column name  $columnNotFound
                                                                           """
  
  val columnNotFound = forAll { sym: Symbol =>
    val row = new Row(List.empty[Element])
    row.get(sym) must throwA[ElementNotFoundFailure]
  }

  lazy val genSymbol: Gen[Symbol] = for {
    str <-  arbitrary[String]
  } yield Symbol(str)
  implicit lazy val arbitrarySymbol: Arbitrary[Symbol] =
    Arbitrary(genSymbol)
} 
开发者ID:finagle,项目名称:roc,代码行数:29,代码来源:ResultsSpec.scala


示例4: NativeExampleSuite

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

import com.holdenkarau.spark.testing._
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Prop.forAll
import org.scalatest.FunSuite
import org.scalatest.prop.Checkers
import org.scalatest.Matchers._

class NativeExampleSuite extends FunSuite
    with SharedSparkContext with Checkers with RDDComparisons {

  test("local sum") {
    val input = Array(1, 2, 3)
    val sumMagic = new SumJNI()
    val result = sumMagic.sum(input)
    val expected = 6
    assert(result === expected)
  }

  test("super simple test") {
    val input = sc.parallelize(List(("hi", Array(1, 2, 3))))
    val result = NativeExample.jniSum(input).collect()
    val expected = List(("hi", 6))
    assert(result === expected)
  }

  test("native call should find sum correctly") {
    val property = forAll(
      RDDGenerator.genRDD[(String, Array[Int])](sc)(
        Arbitrary.arbitrary[(String, Array[Int])])) {
      rdd =>
        val expected = rdd.mapValues(_.sum)
        val result = NativeExample.jniSum(rdd)
        compareRDDWithOrder(expected, result).isEmpty
    }
    check(property)
  }

  test("JNA support") {
    val input = Array(1, 2, 3)
    assert(6 === SumJNA.sum(input, input.size))
  }

  test("JNA Fortran support") {
    val input = Array(1, 2, 3)
    assert(6 === SumFJNA.easySum(input.size, input))
  }
} 
开发者ID:gourimahapatra,项目名称:high-performance-spark,代码行数:50,代码来源:NativeExample.scala


示例5: StringSpecification

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

import org.scalacheck.Properties
import org.scalacheck.Prop.forAll

object StringSpecification extends Properties("String") {

  property("startsWith") = forAll { (a: String, b: String) =>
    (a+b).startsWith(a)
  }

  property("concatenate") = forAll { (a: String, b: String) =>
    (a+b).length >= a.length && (a+b).length >= b.length
  }

  property("substring") = forAll { (a: String, b: String, c: String) =>
    (a+b+c).substring(a.length, a.length+b.length) == b
  }

  //TODO see https://github.com/rickynils/scalacheck/blob/master/doc/UserGuide.md
} 
开发者ID:rysh,项目名称:my-scala-playground,代码行数:22,代码来源:StringSpecification.scala


示例6: maxBounded

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

import cats.kernel.Eq
import cats.kernel.laws.OrderLaws
import cats.laws._
import cats.laws.discipline._
import cats.syntax.order._
import org.scalacheck.{Arbitrary, Cogen}
import org.scalacheck.Prop.forAll

trait BoundedTests[A] extends OrderLaws[A] {
  def maxBounded(implicit maxBounded: MaxBounded[A]): RuleSet = new OrderProperties(
    name = "MaxBounded",
    parent = Some(order),
    "maxValue is the maximum" -> forAll((a: A) => (maxBounded.maxValue max a) <-> maxBounded.maxValue)
  )

  def minBounded(implicit minBounded: MinBounded[A]): RuleSet = new OrderProperties(
    name = "MaxBounded",
    parent = Some(order),
    "minValue is the minimum" -> forAll((a: A) => (minBounded.minValue min a) <-> minBounded.minValue)
  )
}

object BoundedTests {
  def apply[A: Eq: Arbitrary: Cogen]: BoundedTests[A] =
    new BoundedTests[A] {
      def Equ = Eq[A]
      def Arb = implicitly[Arbitrary[A]]
      def Cog = implicitly[Cogen[A]]
    }
} 
开发者ID:julien-truffaut,项目名称:newts,代码行数:33,代码来源:BoundedTests.scala


示例7: Generators

//设置package包名称以及导入依赖的类
package better.testing.palindrome

import Generators._
import org.scalacheck._
import org.scalacheck.Prop.forAll
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.prop.PropertyChecks
import org.scalatest.PropSpec

object Generators {
  val palindromeGen: Gen[String] = for {
    s <- arbitrary[String]
  } yield s
}

object PalindromeCheck extends Properties("Palindrome") with PalindromeCheckers {
  property("checkReverse") = forAll(palindromeGen) { s =>
    checkReverse(s)
  }
}

class PalindromeSpecifications extends PropSpec with PropertyChecks with PalindromeCheckers {
  import org.scalatest._
  import Matchers._

  property("checkReverse") { forAll(palindromeGen) { s =>
    checkReverse(s) shouldBe true
  }}
} 
开发者ID:Mharlin,项目名称:better-testing-workshop,代码行数:30,代码来源:PalindromeCheck.scala


示例8: Generators

//设置package包名称以及导入依赖的类
package better.testing.palindrome

import Generators._
import org.scalacheck._
import org.scalacheck.Prop.forAll
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.prop.PropertyChecks
import org.scalatest.PropSpec

object Generators {

  val palindromeGen: Gen[String] = for {
    base <- arbitrary[String]
    middle <- Gen.option(arbitrary[Char])
  } yield base + middle.getOrElse("") + base.reverse

  val maybePalindromeGen: Gen[String] = Gen.oneOf(palindromeGen,arbitrary[String])

}

object PalindromeCheck extends Properties("Palindrome") with PalindromeCheckers {
  property("checkReverse") = forAll(palindromeGen) { s =>
    checkReverse(s)
  }

  property("checkIndices") = forAll(maybePalindromeGen) { s =>
    checkIndices(s) == checkReverse(s)
  }
}

class PalindromeSpecifications extends PropSpec with PropertyChecks with PalindromeCheckers {
  import org.scalatest._
  import Matchers._

  property("checkReverse") { forAll(palindromeGen) { s =>
    checkReverse(s) shouldBe true
  }}

  property("checkIndices") { forAll(palindromeGen) { s =>
    checkIndices(s) shouldBe true
  }}

  property("checkIndices returns false when not palindrome") { forAll(maybePalindromeGen) { s =>
    checkIndices(s) shouldBe checkReverse(s)
  }}
} 
开发者ID:Mharlin,项目名称:better-testing-workshop,代码行数:47,代码来源:PalindromeCheck.scala


示例9: TensorFlowTypeSpec

//设置package包名称以及导入依赖的类
package shapeless.datatype.tensorflow

import java.net.URI

import org.joda.time.Instant
import org.scalacheck.Prop.{all, forAll}
import org.scalacheck.ScalacheckShapeless._
import org.scalacheck._
import org.tensorflow.example.{Feature, Int64List}
import shapeless._
import shapeless.datatype.record._

import scala.collection.JavaConverters._

object TensorFlowTypeSpec extends Properties("TensorFlowType") {

  import shapeless.datatype.test.Records._
  import shapeless.datatype.test.SerializableUtils._

  implicit def compareByteArrays(x: Array[Byte], y: Array[Byte]) = java.util.Arrays.equals(x, y)
  implicit def compareIntArrays(x: Array[Int], y: Array[Int]) = java.util.Arrays.equals(x, y)
  implicit def compareDouble(x: Double, y: Double) = x.toFloat == y.toFloat

  def roundTrip[A, L <: HList](m: A)
                              (implicit
                               gen: LabelledGeneric.Aux[A, L],
                               fromL: FromFeatures[L],
                               toL: ToFeatures[L],
                               mr: MatchRecord[L]): Prop = {
    val t = ensureSerializable(TensorFlowType[A])
    val rm = RecordMatcher[A]
    all(
      t.fromExample(t.toExample(m)).exists(rm(_, m)),
      t.fromExampleBuilder(t.toExampleBuilder(m)).exists(rm(_, m)))
  }

  implicit val timestampTensorFlowMappableType = TensorFlowType.at[Instant](
    TensorFlowType.toLongs(_).map(new Instant(_)),
    xs => TensorFlowType.fromLongs(xs.map(_.getMillis)))
  property("required") = forAll { m: Required => roundTrip(m) }
  property("optional") = forAll { m: Optional => roundTrip(m) }
  property("repeated") = forAll { m: Repeated => roundTrip(m) }
  property("mixed") = forAll { m: Mixed => roundTrip(m) }
  property("seqs") = forAll { m: Seqs => roundTrip(m) }

  implicit val uriTensorFlowType = TensorFlowType.at[URI](
    TensorFlowType.toStrings(_).map(URI.create),
    xs => TensorFlowType.fromStrings(xs.map(_.toString)))
  property("custom") = forAll { m: Custom => roundTrip(m)}

} 
开发者ID:nevillelyh,项目名称:shapeless-datatype,代码行数:52,代码来源:TensorFlowTypeSpec.scala


示例10: DatastoreTypeSpec

//设置package包名称以及导入依赖的类
package shapeless.datatype.datastore

import java.net.URI

import com.google.datastore.v1.client.DatastoreHelper._
import org.scalacheck.Prop.{all, forAll}
import org.scalacheck.ScalacheckShapeless._
import org.scalacheck._
import shapeless._
import shapeless.datatype.record._

object DatastoreTypeSpec extends Properties("DatastoreType") {

  import shapeless.datatype.test.Records._
  import shapeless.datatype.test.SerializableUtils._

  implicit def compareByteArrays(x: Array[Byte], y: Array[Byte]) = java.util.Arrays.equals(x, y)
  implicit def compareIntArrays(x: Array[Int], y: Array[Int]) = java.util.Arrays.equals(x, y)

  def roundTrip[A, L <: HList](m: A)
                              (implicit
                               gen: LabelledGeneric.Aux[A, L],
                               fromL: FromEntity[L],
                               toL: ToEntity[L],
                               mr: MatchRecord[L]): Prop = {
    val t = ensureSerializable(DatastoreType[A])
    val rm = RecordMatcher[A]
    all(
      t.fromEntity(t.toEntity(m)).exists(rm(_, m)),
      t.fromEntityBuilder(t.toEntityBuilder(m)).exists(rm(_, m)))
  }

  property("required") = forAll { m: Required => roundTrip(m) }
  property("optional") = forAll { m: Optional => roundTrip(m) }
  property("repeated") = forAll { m: Repeated => roundTrip(m) }
  property("mixed") = forAll { m: Mixed => roundTrip(m) }
  property("nested") = forAll { m: Nested => roundTrip(m) }
  property("seqs") = forAll { m: Seqs => roundTrip(m) }

  implicit val uriDatastoreType = DatastoreType.at[URI](
    v => URI.create(v.getStringValue), u => makeValue(u.toString).build())
  property("custom") = forAll { m: Custom => roundTrip(m)}

} 
开发者ID:nevillelyh,项目名称:shapeless-datatype,代码行数:45,代码来源:DatastoreTypeSpec.scala


示例11: AtomicBitSetSpec

//设置package包名称以及导入依赖的类
package uk.co.odinconsultants.bitset

import org.junit.runner.RunWith
import org.scalacheck.Gen.choose
import org.scalacheck.Prop.forAll
import org.scalatest.junit.JUnitRunner
import org.scalatest.{Matchers, WordSpec}

@RunWith(classOf[JUnitRunner])
class AtomicBitSetSpec extends WordSpec with Matchers {

  val smallInteger = choose(0,1000)

  "bitset" should {
    "indicate when everything is set" in {
      val propSmallInteger = forAll(smallInteger) { n =>
        val toTest = new AtomicBitSet(n)
        for (i <- 0 to n) toTest.set(i.toLong)
        toTest.isEverythingSet
      }
    }
  }
} 
开发者ID:PhillHenry,项目名称:palgorithms,代码行数:24,代码来源:AtomicBitSetSpec.scala


示例12: TimeValidationSpec

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

import com.redbubble.hawk.params._
import com.redbubble.hawk.spec.Generators
import com.redbubble.hawk.util.Time
import com.redbubble.hawk.util.Time._
import com.redbubble.hawk.validate.TimeValidation.{acceptableTimeDelta, validate}
import com.redbubble.hawk.{HeaderValidationMethod, _}
import com.redbubble.util.spec.SpecHelper
import org.scalacheck.Prop.forAll
import org.scalacheck.Properties
import org.specs2.mutable.Specification

final class TimeValidationSpec extends Specification with SpecHelper with Generators {
  val credentials = Credentials(KeyId("fred"), Key("d0p1h1n5"), Sha256)

  val timestamps = new Properties("Timestamps") {
    property("are valid if within the interval") = forAll { (time: Time) =>
      val delta = nowUtc.minus(time).getStandardSeconds
      if (delta > acceptableTimeDelta.getStandardSeconds) {
        validate(credentials, context(time), HeaderValidationMethod) must beLeft
      } else {
        validate(credentials, context(time), HeaderValidationMethod) must beRight
      }
    }
  }

  s2"Validating timestamps$timestamps"

  private def context(time: Time): ValidatableRequestContext = {
    val header = RequestAuthorisationHeader(
      KeyId("fred"), time, Nonce(Base64Encoded("nonce")), None, Some(ExtendedData("data")), MAC(Base64Encoded("base64")))
    ValidatableRequestContext(RequestContext(Get, Host("example.com"), Port(80), UriPath("/"), None), header)
  }
} 
开发者ID:redbubble,项目名称:finagle-hawk,代码行数:36,代码来源:TimeValidationSpec.scala


示例13: WindowedMaxTest

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

import org.junit.runner.RunWith
import org.scalacheck.Gen
import org.scalacheck.Prop.forAll
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.prop.Checkers

@RunWith(classOf[JUnitRunner])
class WindowedMaxTest extends FunSuite with Checkers {
  test("return max") {
    check {
      forAll { ary: Array[Long] =>
        forAll(Gen.posNum[Int]) { window: Int =>
          val w = new WindowedMax(window)
          for (v <- ary) w.add(v)

          val expected =
            if (ary.isEmpty) Long.MinValue
            else if (window > ary.length) ary.max
            else ary.takeRight(window).max

          expected == w.get
        }
      }
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:30,代码来源:WindowedMaxTest.scala


示例14: Converter1Test2

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

import org.scalacheck.Gen
import org.scalacheck.Prop.forAll
import org.scalatest.FlatSpec
import org.scalatest.prop.Checkers


class Converter1Test2 extends FlatSpec with Checkers {
  behavior of "Converter1"

  "toInt" should "produce length of names for all symbols" in {
    // ScalaTest style
    check((x: String) => Converter1(x).toInt == x.length)
  }
  it should "produce length for ASCII symbols" in {
    // ScalaCheck style
    val usAsciiStringGen = Gen.containerOf[Array, Char](Gen.choose[Char](0, 127)).map(_.mkString)
    forAll(usAsciiStringGen) { x: String => Converter1(x).toInt == x.length }
  }
} 
开发者ID:ysden123,项目名称:poc,代码行数:22,代码来源:Converter1Test2.scala


示例15: MonadLawsCheck

//设置package包名称以及导入依赖的类
import MonadLaws._
import org.scalacheck._
import org.scalacheck.Properties
import org.scalacheck.Prop.forAll

import Arbitrary.arbitrary

import scala.language.higherKinds

sealed abstract class MonadLawsCheck[M[_]](name: String)(
  implicit MO: Monad[M],
  AMI: Arbitrary[M[Int]],
  AMS: Arbitrary[M[String]],
  AMB: Arbitrary[M[Boolean]]
) extends Properties(s"$name Monad Laws Check") {

  property(" Left identity") = forAll {
    (a: Int, f: Int => M[Int]) => Laws.leftIdentity(MO)(a)(f)
  }

  property(" Right identity") = forAll {
    (ma: M[Int]) => Laws.rightIdentity(MO)(ma)
  }

  property(" Associativity") = forAll {
    (ma: M[Int], f: Int => M[String], g: String => M[Boolean]) => Laws.associativity(MO)(ma)(f)(g)
  }


  property(" Left identity No Infix") = forAll {
    (a: Int, f: Int => M[Int]) => LawsNoInfix.leftIdentity(MO)(a)(f)
  }

  property(" Right identity No Infix") = forAll {
    (ma: M[Int]) => LawsNoInfix.rightIdentity(MO)(ma)
  }

  property(" Associativity No Infix") = forAll {
    (ma: M[Int], f: Int => M[String], g: String => M[Boolean]) => LawsNoInfix.associativity(MO)(ma)(f)(g)
  }
}

object IdMonadLawsCheck extends MonadLawsCheck[Id]("Id")
object ListMonadLawsCheck extends MonadLawsCheck[List]("List")
object OptionMonadLawsCheck extends MonadLawsCheck[Option]("Option") 
开发者ID:barambani,项目名称:Laws,代码行数:46,代码来源:MonadLawsCheck.scala


示例16: P08Check

//设置package包名称以及导入依赖的类
package jp.co.dwango.s99

import org.scalacheck.Prop.forAll
import org.scalacheck.Properties

class P08Check extends Properties("P08") {
  def duplicates(list: List[Int]): Int = {
    @scala.annotation.tailrec
    def loop(list: List[Int], curr: Int, count: Int): Int = list match {
      case Nil => count
      case x :: xs =>
        if (curr == x) loop(xs, curr, count + 1) else loop(xs, x, count)
    }
    list match {
      case x :: xs => loop(xs, x, 0)
      case Nil => 0
    }
  }
  property("compress()") = forAll { (s: List[Int]) =>
    P08.compress(s).length == s.length - duplicates(s)
  }
} 
开发者ID:dwango,项目名称:S99,代码行数:23,代码来源:P08Check.scala


示例17: P16Check

//设置package包名称以及导入依赖的类
package jp.co.dwango.s99

import org.scalacheck.{Gen, Properties}
import Gen.listOf, Gen.chooseNum
import org.scalacheck.Prop.forAll

class P16Check extends Properties("P16") {
  property("drop()") =
    forAll(listOf(chooseNum(Int.MinValue, Int.MaxValue)), chooseNum(1, 10)) {
      (s: List[Int], i: Int) =>
        (P16.drop(i, s) == s.zipWithIndex
          .map { case (e, j) => (e, j + 1) }
          .filterNot {
            case (e, j) =>
              j % i == 0
          }
          .map { _._1 })
    }
} 
开发者ID:dwango,项目名称:S99,代码行数:20,代码来源:P16Check.scala


示例18: SubjectSpec

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

import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen, Properties}
import shapeless.{:+:, ::, CNil, Coproduct, Generic, HList, HNil, Inl, Inr, Lazy}

object SubjectSpec extends Properties("Subject") {
  object derive {
    implicit def hlistGen[H](implicit arb: Arbitrary[H]): Arbitrary[H :: HNil] =
      Arbitrary[H :: HNil](arb.arbitrary.map(_ :: HNil))

    implicit def anyValGen[S <: Subject, H <: HList](implicit gen: Generic.Aux[S, H],
                                                     arb: Arbitrary[H]): Arbitrary[S] =
      Arbitrary[S](arb.arbitrary.map(r => gen.from(r)))

    implicit def cnilGen[H](implicit hArb: Lazy[Arbitrary[H]]): Arbitrary[H :+: CNil] =
      Arbitrary[H :+: CNil](hArb.value.arbitrary.map(h => Inl(h)))

    implicit def coproductGen[H, T <: Coproduct](implicit hArb: Lazy[Arbitrary[H]],
                                                 tArb: Arbitrary[T]): Arbitrary[H :+: T] =
      Arbitrary[H :+: T](
        Gen.oneOf(hArb.value.arbitrary.map(h => Inl(h)), tArb.arbitrary.map(t => Inr(t))))

    def deriveGen[T, R](implicit gen: Generic.Aux[T, R], arb: Lazy[Arbitrary[R]]): Arbitrary[T] =
      Arbitrary[T](arb.value.arbitrary.map(r => gen.from(r)))

    val arb: Arbitrary[Subject] = deriveGen
  }

  implicit val arbSubject: Arbitrary[Subject] = derive.arb

  property("any subject can be serialized and deserialized") = forAll { expected: Subject =>
    val asString = expected.toString
    val actual   = Subject(asString)

    actual == expected
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:39,代码来源:SubjectSpec.scala


示例19: BasicFunctionalitySpec

//设置package包名称以及导入依赖的类
package jp.ne.opt.chronoscala

import jp.ne.opt.chronoscala.Imports._
import org.scalacheck.Prop.forAll
import org.scalacheck.{Prop, Properties}

object BasicFunctionalitySpec extends Properties("ZonedDateTime") with Gens {

  property("ZonedDateTime equality") = Prop.secure {
    forAll(zonedDateTimeGen) { zonedDateTime =>
      zonedDateTime == zonedDateTime
    }
  }

  property("zonedDateTime < (zonedDateTime + 1.hour)") = Prop.secure {
    forAll(zonedDateTimeGen) { zonedDateTime =>
      zonedDateTime < (zonedDateTime + 1.hour)
    }
  }
} 
开发者ID:opt-tech,项目名称:chronoscala,代码行数:21,代码来源:BasicFunctionalitySpec.scala


示例20: DecodeResultSpec

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

import scala.util.Try

import org.scalacheck.Properties
import org.scalacheck.Prop.forAll

class DecodeResultSpec extends Properties("DecodeResult") with Generators {

  property("toEither") = forAll { (either: Either[String, Int]) =>
    DecodeResult(either).toEither == either
  }

  property("map") = forAll { (result: DecodeResult[String, Int]) =>
    result.map(_.toString).toEither == result.toEither.right.map(_.toString)
  }

  property("map") = forAll { (left: Left[String, Int]) =>
    Try(DecodeResult(left).map(_ => throw new Exception("oops"))).isSuccess
  }

  property("flatMap") = forAll { (result: DecodeResult[String, Int]) =>
    result.flatMap(_ => result) == result
  }

  property("flatMap") = forAll { (either: Either[String, Int]) =>
    DecodeResult(either).flatMap(_ => DecodeResult(Left("oops"))).isFail
  }

  property("recoverWith") = forAll { (result: DecodeResult[String, Int], recovered: DecodeResult[String, Int]) =>
    if (result.isOk)
      result.recoverWith { case _ if true => recovered } == result
    else
      result.recoverWith { case _ if true => recovered } == recovered
  }

  property("recoverWith") = forAll { (result: DecodeResult[String, Int], recovered: DecodeResult[String, Int]) =>
    result.recoverWith { case a: String if false => recovered } == result
  }

} 
开发者ID:mrvisser,项目名称:scoder,代码行数:42,代码来源:DecodeResultSpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala ActorContext类代码示例发布时间:2022-05-23
下一篇:
Scala FileIO类代码示例发布时间: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