本文整理汇总了Scala中org.scalacheck.Arbitrary类的典型用法代码示例。如果您正苦于以下问题:Scala Arbitrary类的具体用法?Scala Arbitrary怎么用?Scala Arbitrary使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Arbitrary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: gen
//设置package包名称以及导入依赖的类
package org.dsa.iot.scala
import scala.collection.JavaConverters._
import org.dsa.iot.dslink.node.value.Value
import org.dsa.iot.dslink.util.json.{ JsonArray, JsonObject }
import org.scalacheck.{ Gen, Arbitrary }
import org.scalatest.{ BeforeAndAfterAll, Matchers, Suite, WordSpecLike }
import org.scalatest.prop.GeneratorDrivenPropertyChecks
trait AbstractSpec extends Suite
with WordSpecLike
with Matchers
with BeforeAndAfterAll
with GeneratorDrivenPropertyChecks {
import Arbitrary._
object gen {
val ids = Gen.identifier.map(_.take(10))
val scalars = Gen.oneOf(arbitrary[Number], arbitrary[Boolean], arbitrary[String], arbitrary[Array[Byte]])
val scalarLists = Gen.resize(10, Gen.listOf(scalars))
val scalarJavaLists = scalarLists.map(_.asJava)
val scalarMaps = Gen.resize(10, Gen.mapOf(Gen.zip(ids, scalars)))
val scalarJavaMaps = scalarMaps.map(_.asJava)
val anyLists = Gen.resize(10, Gen.listOf(Gen.oneOf(scalars, scalarLists, scalarMaps)))
val anyMaps = Gen.resize(10, Gen.mapOf(Gen.zip(ids, Gen.oneOf(scalars, scalarLists, scalarMaps))))
val any = Gen.oneOf(scalars, anyLists, anyMaps)
}
object valueGen {
val bools = arbitrary[Boolean] map (new Value(_))
val ints = arbitrary[Int] map (new Value(_))
val longs = arbitrary[Long] map (new Value(_))
val shorts = arbitrary[Short] map (new Value(_))
val bytes = arbitrary[Byte] map (new Value(_))
val doubles = arbitrary[Double] map (new Value(_))
val floats = arbitrary[Float] map (new Value(_))
val numbers = Gen.oneOf(ints, longs, shorts, bytes, doubles, floats)
val strings = arbitrary[String] map (new Value(_))
val binary = arbitrary[Array[Byte]] map (new Value(_))
val scalarArrays = gen.scalarLists map (x => new JsonArray(x.asJava))
val scalarMaps = gen.scalarMaps map (x => new JsonObject(x.asInstanceOf[Map[String, Object]].asJava))
val arrays = scalarArrays map (new Value(_))
val maps = scalarMaps map (new Value(_))
}
}
示例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)
}
示例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)
}
示例4:
//设置package包名称以及导入依赖的类
package roc
package postgresql
import java.nio.charset.StandardCharsets
import org.scalacheck.Arbitrary._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._
trait PostgresqlLexicalGen extends ScalaCheck {
// see http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html
// for more on what constitues a valid SQL Identifier
protected val UnicodeCapitalEnglish = '\u0041' to '\u005A'
protected val UnicodeLowerEnglish = '\u0061' to '\u007A'
protected val UnicodeNonLatin = '\u0400' to '\u1FFE'
protected val UnicodeUnderscore = "_".getBytes(StandardCharsets.UTF_8).map(_.toChar).head
protected val UnicodeDollarSign = "$".getBytes(StandardCharsets.UTF_8).map(_.toChar).head
protected val UnicodeNumbers = '\u0030' to '\u0039'
protected val BeginningChars = UnicodeUnderscore :: List(UnicodeCapitalEnglish,
UnicodeLowerEnglish, UnicodeNonLatin).flatten
protected val SubsequentChars = UnicodeDollarSign :: BeginningChars ::: UnicodeNumbers.toList
protected lazy val genValidBeginningIdentifier: Gen[Char] = for {
char <- Gen.oneOf(BeginningChars)
} yield char
protected lazy val genValidSubsequentIdentifier: Gen[Char] = for {
char <- Gen.oneOf(SubsequentChars)
} yield char
protected lazy val genValidSQLIdentifier: Gen[String] = for {
firstChar <- genValidBeginningIdentifier
chars <- Gen.listOf(genValidSubsequentIdentifier)
} yield {
val xs = firstChar :: chars
xs.map(_.toString).reduce(_ + _)
}
protected lazy val genValidNumberOfShortColumns: Gen[Short] =
Gen.chooseNum[Short](0, 1663) // the maximum number of Postgresql columns is 1663
protected lazy val genValidNumberOfIntColumns: Gen[Int] =
genValidNumberOfShortColumns.map(_.toInt)
protected lazy val genValidNonZeroNumberOfShortColumns: Gen[Short] =
Gen.chooseNum[Short](1, 1663) // the maximum number of Postgresql columns is 1663
}
示例5: 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))
}
}
示例6: from
//设置package包名称以及导入依赖的类
package psug201607._3_bijection
import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import org.typelevel.discipline
trait <=>[A,B] {
def from(a : A) : B
def to(b : B) : A
def laws(implicit A : Arbitrary[A], B : Arbitrary[B]) = new discipline.Laws {
def iso = new SimpleRuleSet("iso",
"idA" -> forAll( (a:A) => to(from(a)) == a),
"idB" -> forAll( (b:B) => from(to(b)) == b)
)
}
}
示例7: arbNewtype
//设置package包名称以及导入依赖的类
package newts
import cats.instances.AllInstances
import newts.syntax.AllSyntax
import org.scalacheck.{Arbitrary, Cogen}
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FunSuite, Matchers}
import org.typelevel.discipline.scalatest.Discipline
trait NewtsSuite extends FunSuite
with Matchers
with GeneratorDrivenPropertyChecks
with Discipline
with AllSyntax
with AllInstances
with cats.syntax.AllSyntax
with ArbitraryInstances
trait ArbitraryInstances {
def arbNewtype[S, A: Arbitrary](implicit newtype: Newtype.Aux[S, A]): Arbitrary[S] =
Arbitrary(arbitrary[A].map(newtype.wrap))
def cogenNewtype[S, A: Cogen](implicit newtype: Newtype.Aux[S, A]): Cogen[S] =
Cogen[A].contramap(newtype.unwrap)
implicit val allArbitrary: Arbitrary[All] = arbNewtype[All, Boolean]
implicit val anyArbitrary: Arbitrary[Any] = arbNewtype[Any, Boolean]
implicit def multArbitrary[A:Arbitrary]: Arbitrary[Mult[A]] = arbNewtype[Mult[A], A]
implicit def dualArbitrary[A: Arbitrary]: Arbitrary[Dual[A]] = arbNewtype[Dual[A], A]
implicit def firstArbitrary[A: Arbitrary]: Arbitrary[First[A]] = arbNewtype[First[A], A]
implicit def lastArbitrary[A: Arbitrary]: Arbitrary[Last[A]] = arbNewtype[Last[A], A]
implicit def firstOptionArbitrary[A: Arbitrary]: Arbitrary[FirstOption[A]] = arbNewtype[FirstOption[A], Option[A]]
implicit def lastOptionArbitrary[A: Arbitrary]: Arbitrary[LastOption[A]] = arbNewtype[LastOption[A], Option[A]]
implicit def minArbitrary[A: Arbitrary]: Arbitrary[Min[A]] = arbNewtype[Min[A], A]
implicit def maxArbitrary[A: Arbitrary]: Arbitrary[Max[A]] = arbNewtype[Max[A], A]
implicit def zipListArbitrary[A: Arbitrary]: Arbitrary[ZipList[A]] = arbNewtype[ZipList[A], List[A]]
implicit val allCogen: Cogen[All] = cogenNewtype[All, Boolean]
implicit val anyCogen: Cogen[Any] = cogenNewtype[Any, Boolean]
implicit def multCogen[A: Cogen]: Cogen[Mult[A]] = cogenNewtype[Mult[A], A]
implicit def dualCogen[A: Cogen]: Cogen[Dual[A]] = cogenNewtype[Dual[A], A]
implicit def firstCogen[A: Cogen]: Cogen[First[A]] = cogenNewtype[First[A], A]
implicit def lastCogen[A: Cogen]: Cogen[Last[A]] = cogenNewtype[Last[A], A]
implicit def firstOptionCogen[A: Cogen]: Cogen[FirstOption[A]] = cogenNewtype[FirstOption[A], Option[A]]
implicit def lastOptionCogen[A: Cogen] : Cogen[LastOption[A]] = cogenNewtype[LastOption[A], Option[A]]
implicit def minOptionCogen[A: Cogen] : Cogen[Min[A]] = cogenNewtype[Min[A], A]
implicit def maxOptionCogen[A: Cogen] : Cogen[Max[A]] = cogenNewtype[Max[A], A]
implicit def zipListCogen[A: Cogen]: Cogen[ZipList[A]] = cogenNewtype[ZipList[A], List[A]]
}
示例8: 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]]
}
}
示例9: AvroSpec
//设置package包名称以及导入依赖的类
package com.lukecycon.avro
import org.scalatest.FreeSpec
import org.scalatest.prop.Checkers
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop._
class AvroSpec extends FreeSpec with Checkers {
def roundTrip[T: AvroFormat](v: T, comp: Boolean = false) =
Avro.read(Avro.write(v, comp), comp)
def checkPrimative[T: Arbitrary: AvroFormat](name: String) =
s"Avro roundTrip should be identity for $name" - {
"uncompressed" in {
check { i: T =>
roundTrip(i) == Right(i)
}
}
"compressed" in {
check { i: T =>
roundTrip(i, true) == Right(i)
}
}
}
checkPrimative[Boolean]("Boolean")
checkPrimative[Int]("Int")
checkPrimative[Long]("Long")
checkPrimative[Float]("Float")
checkPrimative[Double]("Double")
checkPrimative[Seq[Byte]]("bytes")
checkPrimative[String]("Sstring")
checkPrimative[Option[Int]]("Option[_]")
checkPrimative[Either[Int, String]]("Either[_]")
checkPrimative[List[Int]]("List[_]")
checkPrimative[Map[String, Int]]("Map[String, _]")
}
示例10: TermTests
//设置package包名称以及导入依赖的类
package io.aecor.liberator.tests
import cats.kernel.laws.GroupLaws
import cats.laws.discipline.{ MonadTests, SerializableTests }
import cats.{ Eq, Eval, Id, Monad }
import io.aecor.liberator.Term
import org.scalacheck.{ Arbitrary, Cogen, Gen }
class TermTests extends LiberatorSuite with TermInstances {
trait M[F[_]]
implicit def mf: M[Id] = new M[Id] {}
checkAll("Term[M, Int]", GroupLaws[Term[M, Int]].monoid)
checkAll("Term[M, ?]", MonadTests[Term[M, ?]].monad[Int, Int, Int])
checkAll("Monad[Term[M, ?]]", SerializableTests.serializable(Monad[Term[M, ?]]))
}
sealed trait TermInstances {
private def termGen[M[_[_]], A](maxDepth: Int)(implicit A: Arbitrary[A]): Gen[Term[M, A]] = {
val noFlatMapped =
Gen.oneOf(A.arbitrary.map(Term.pure[M, A]), A.arbitrary.map(Term.pure[M, A]))
val nextDepth = Gen.chooseNum(1, math.max(1, maxDepth - 1))
def withFlatMapped =
for {
fDepth <- nextDepth
freeDepth <- nextDepth
f <- Arbitrary
.arbFunction1[A, Term[M, A]](
Arbitrary(termGen[M, A](fDepth)),
Cogen[Unit].contramap(_ => ())
)
.arbitrary
freeFA <- termGen[M, A](freeDepth)
} yield freeFA.flatMap(f)
if (maxDepth <= 1) noFlatMapped
else Gen.oneOf(noFlatMapped, withFlatMapped)
}
implicit def termArbitrary[M[_[_]], A](implicit A: Arbitrary[A]): Arbitrary[Term[M, A]] =
Arbitrary(termGen[M, A](4))
implicit def termEq[M[_[_]], A, F[_]](implicit mf: M[F],
eqA: Eq[F[A]],
F: Monad[F]): Eq[Term[M, A]] =
new Eq[Term[M, A]] {
override def eqv(x: Term[M, A], y: Term[M, A]): Boolean =
eqA.eqv(x(mf), y(mf))
}
}
示例11: Generator
//设置package包名称以及导入依赖的类
package generators
import org.scalacheck.{Arbitrary, Gen}
object Generator {
def modelGen: Gen[Model] = for {
s <- Gen.choose(1, 10).flatMap(size => Gen.listOfN(size,Gen.alphaNumChar)).map(_.mkString)
i <- Arbitrary.arbInt.arbitrary
b <-Arbitrary.arbBool.arbitrary
} yield Model(
str = s,
int = i,
bool = b
)
}
case class Model(str: String, int: Int, bool: Boolean)
示例12: Generators
//设置package包名称以及导入依赖的类
package com.github.hgiddens.ausms
import org.scalacheck.{ Arbitrary, Gen }
import org.scalacheck.Arbitrary.arbitrary
import scalaz.Scalaz._
object Generators {
implicit def arbMessage: Arbitrary[Message] =
Arbitrary(for {
content <- arbitrary[String]
message <- Gen.fromOption(Message.fromString(content))
} yield message)
implicit def arbMessageId: Arbitrary[MessageId] =
Arbitrary(Gen.resultOf(MessageId.apply _))
implicit def arbPhoneNumber: Arbitrary[PhoneNumber] =
Arbitrary(for {
digits <- Gen.listOfN(8, Gen.choose(0, 9))
number = s"04${digits.mkString}"
phoneNumber <- Gen.fromOption(PhoneNumber.fromString(number))
} yield phoneNumber)
}
示例13: StandardArbitraries
//设置package包名称以及导入依赖的类
package movio.cinema.test
import org.scalacheck.Arbitrary
import org.scalacheck.Gen
trait DateTimeArbitrary {
import org.joda.time._
implicit val arbLocalDateTime: Arbitrary[LocalDateTime] =
Arbitrary(Gen.posNum[Long] map (new LocalDateTime(_)))
implicit val arbDateTime: Arbitrary[DateTime] =
Arbitrary(Gen.posNum[Long] map (new DateTime(_)))
}
trait PlayJsonArbitrary {
import java.math.BigDecimal
import play.api.libs.json._
import Arbitrary.arbitrary
import Gen._
implicit val arbJsonObject: Arbitrary[JsObject] = Arbitrary(jsonObjectNode)
implicit val arbJsonArray: Arbitrary[JsArray] = Arbitrary(jsonArrayNode)
lazy val shortText: Gen[String] =
for {
n ? choose(0, 4)
chars ? listOfN(n, alphaNumChar)
} yield chars.mkString
lazy val jsonWholeNumberNode: Gen[JsNumber] = arbitrary[Long] map (n ? JsNumber(new BigDecimal(n)))
lazy val jsonDecimalNumberNode: Gen[JsNumber] = arbitrary[Double] map (n ? JsNumber(new BigDecimal(n)))
lazy val jsonNumberNode: Gen[JsNumber] = oneOf(jsonWholeNumberNode, jsonDecimalNumberNode)
lazy val jsonStringNode: Gen[JsString] = shortText map JsString.apply
lazy val jsonBoolNode: Gen[JsBoolean] = oneOf(true, false) map JsBoolean.apply
lazy val jsonNullNode: Gen[JsNull.type] = const(JsNull)
lazy val jsonValueNode: Gen[JsValue] =
oneOf(jsonNumberNode, jsonStringNode, jsonBoolNode, jsonNullNode, jsonArrayNode, jsonObjectNode)
lazy val jsonArrayNode: Gen[JsArray] =
for {
n ? choose(1, 4)
values ? listOfN(n, jsonValueNode)
} yield JsArray(values)
lazy val jsonObjectNode: Gen[JsObject] =
for {
n ? choose(1, 4)
keys ? listOfN(n, shortText)
values ? listOfN(n, jsonValueNode)
} yield JsObject(keys zip values)
}
object StandardArbitraries extends DateTimeArbitrary with PlayJsonArbitrary
示例14: Test
//设置package包名称以及导入依赖的类
package scalachecklib
import shapeless._
import shapeless.ops.function._
import cats.implicits._
import org.scalacheck.{Arbitrary, Prop}
import org.scalacheck.Gen
import Prop.forAll
import org.scalatest.exceptions._
import org.scalacheck.Shapeless._
object Test {
def testSuccess[F, R, L <: HList](method: F, answer: L)(
implicit A: Arbitrary[L],
fntop: FnToProduct.Aux[F, L ? R]
): Prop = {
val rightGen = genRightAnswer(answer)
val rightProp = forAll(rightGen)({ p ?
val result = Either.catchOnly[GeneratorDrivenPropertyCheckFailedException]({
fntop(method)(p)
})
result match {
case Left(exc) ?
exc.cause match {
case Some(originalException) ? throw originalException
case _ ? false
}
case _ ? true
}
})
val wrongGen = genWrongAnswer(answer)
val wrongProp = forAll(wrongGen)({ p ?
Either.catchNonFatal({ fntop(method)(p) }).isLeft
})
Prop.all(rightProp, wrongProp)
}
def genRightAnswer[L <: HList](answer: L): Gen[L] =
Gen.const(answer)
def genWrongAnswer[L <: HList](l: L)(
implicit A: Arbitrary[L]
): Gen[L] =
A.arbitrary.suchThat(_ != l)
}
示例15: weightedEdgeList
//设置package包名称以及导入依赖的类
package tiki.tests.arbitrary
import org.scalacheck.Arbitrary._
import org.scalacheck.{Arbitrary, Gen}
import tiki.WeightedEdge
import tiki.implicits._
trait ArbitraryWeightedEdgeList extends ArbitrarySet {
def weightedEdgeList[A: Arbitrary] : Gen[List[WeightedEdge[A]]] = for {
xs <- arbitrary[Set[A]]
ys <- arbitrary[Double]
if xs.nonEmpty
} yield {
xs.iterator.sliding(2).foldLeft(List.empty[WeightedEdge[A]])(
(acc, v) => (v.head --> v.last :# ys) :: acc)
}
def weightedEdgeStream[A: Arbitrary]: Gen[Stream[WeightedEdge[A]]]
= for (xs <- arbitrary[List[WeightedEdge[A]]]) yield xs.toStream
implicit def arbitraryWeightedEdgeStream[A:Arbitrary]: Arbitrary[Stream[WeightedEdge[A]]]
= Arbitrary(weightedEdgeStream)
implicit def arbitraryWeightedEdgeList[A:Arbitrary]: Arbitrary[List[WeightedEdge[A]]]
= Arbitrary(weightedEdgeList)
}