本文整理汇总了Scala中org.scalacheck.Gen类的典型用法代码示例。如果您正苦于以下问题:Scala Gen类的具体用法?Scala Gen怎么用?Scala Gen使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Gen类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: createQueue
//设置package包名称以及导入依赖的类
package com.hivehome.kafka.connect.sqs
import com.amazonaws.regions.{Region, Regions}
import com.amazonaws.services.sqs.AmazonSQSClient
import com.amazonaws.services.sqs.model.{CreateQueueRequest, SendMessageRequest, SendMessageResult}
import org.scalacheck.Gen
import scala.collection.JavaConverters._
trait SQSSupport {
val queueName = Gen.alphaStr
.map(a => s"test-connect-${a.take(10)}")
.sample.get
var queueUrl: String = null
val sqs = new AmazonSQSClient()
sqs.setRegion(Region.getRegion(Regions.EU_WEST_1))
def createQueue(): Unit = {
val request = new CreateQueueRequest(queueName)
.withAttributes(Map("VisibilityTimeout" -> "2").asJava)
val result = sqs.createQueue(request)
queueUrl = result.getQueueUrl
println("Url for created Queue = " + queueUrl)
}
def deleteQueue(): Unit = {
sqs.deleteQueue(queueUrl)
}
def sendMessage(msgText: String): SendMessageResult = {
sqs.sendMessage(new SendMessageRequest()
.withQueueUrl(queueUrl)
.withMessageBody(msgText))
}
}
示例2: BarcoderTest
//设置package包名称以及导入依赖的类
package kokellab.utils.misc
import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import com.google.zxing.BarcodeFormat
import org.scalacheck.Gen
import org.scalatest.prop.{GeneratorDrivenPropertyChecks, PropertyChecks}
import org.scalatest.{Matchers, PropSpec}
class BarcoderTest extends PropSpec with GeneratorDrivenPropertyChecks with Matchers {
def fakeEncodeDecode(text: String, barcodeFormat: BarcodeFormat, dimensions: (Int, Int), imageFormat: String): String =
if (text.isEmpty) text else encodeDecode(text.toUpperCase, barcodeFormat, dimensions, imageFormat)
def genBoundedList[T](maxSize: Int, gen: Gen[T]): Gen[List[T]] =
Gen.choose(0, maxSize) flatMap (size => Gen.listOfN(size, gen))
def genBoundedString(maxSize: Int, gen: Gen[Char]): Gen[String] =
Gen.choose(0, maxSize) flatMap (size => Gen.listOfN(size, gen) map (_.mkString))
def encodeDecode(text: String, codeFormat: BarcodeFormat, dimensions: (Int, Int), imageFormat: String): String = {
val barcoder = new Barcoder(codeFormat, imageFormat, dimensions._1, dimensions._2)
val os = new ByteArrayOutputStream()
barcoder.encode(text, os)
val is = new ByteArrayInputStream(os.toByteArray)
barcoder.decode(is)
}
val imageFormatGen = Gen.oneOf("png", "jpg", "gif")
def test(barcodeFormat: BarcodeFormat, dimensionsGen: Gen[(Int, Int)], stringGen: Gen[String]) = {
property(s"Decoding an encoded string should yield the original string for ${barcodeFormat.name} codes") {
forAll(imageFormatGen, stringGen, dimensionsGen) { (imageFormat: String, text: String, dimensions: (Int, Int)) =>
fakeEncodeDecode(text, barcodeFormat, dimensions, imageFormat) should equal (text.toUpperCase)
}
}
}
val rectangularGen: Gen[(Int, Int)] = for {
width <- Gen.choose(20, 100)
height <- Gen.choose(20, 100)
} yield (width, height)
val squareGen: Gen[(Int, Int)] = for {
size <- Gen.choose(20, 100)
} yield (size, size)
val code39And93Gen: Gen[String] = genBoundedString(48, Gen.frequency((36, Gen.alphaNumChar), (7, Gen.oneOf('-', '.', '$', '/', '+', '%', ' '))))
test(BarcodeFormat.CODE_39, rectangularGen, code39And93Gen)
test(BarcodeFormat.CODE_93, rectangularGen, code39And93Gen)
// TODO this fails due to https://github.com/zxing/zxing/issues/716
// there's nothing I can do now
// test(BarcodeFormat.CODE_128, rectangularGen, genBoundedString(48, Gen.choose[Char](0x20, 127)))
// TODO QR codes break; also not my fault
// test(BarcodeFormat.QR_CODE, squareGen, genBoundedString(4296, Gen.frequency((36, Gen.alphaNumChar), (8, Gen.oneOf('-', '.', '$', '/', '+', '%', ' ', ':')))))
}
示例3: 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(_))
}
}
示例4: 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)
}
示例5: 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)
}
示例6: 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))
}
}
示例7: 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))
}
}
示例8: 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)
示例9: SessionManagerBasicEncoderTest
//设置package包名称以及导入依赖的类
package com.softwaremill.session
import org.scalacheck.{Gen, Prop, Properties}
object SessionManagerBasicEncoderTest extends Properties("SessionManagerBasicEncoder") {
import Prop._
val secretGen = Gen.choose(64, 256).flatMap(size => Gen.listOfN(size, Gen.alphaNumChar).map(_.mkString))
property("encode+decode") = forAllNoShrink(secretGen) { (secret: String) =>
forAll { (encrypt: Boolean, useMaxAgeSeconds: Boolean, data: Map[String, String]) =>
val config = SessionConfig.default(secret)
.copy(sessionEncryptData = encrypt)
.copy(sessionMaxAgeSeconds = if (useMaxAgeSeconds) Some(3600L) else None)
val manager = new SessionManager[Map[String, String]](config).clientSessionManager
manager.decode(manager.encode(data)) == SessionResult.Decoded(data)
}
}
property("doesn't decode expired session") = forAllNoShrink(secretGen) { (secret: String) =>
forAll { (encrypt: Boolean, data: Map[String, String]) =>
val config = SessionConfig.default(secret)
.copy(sessionEncryptData = encrypt)
.copy(sessionMaxAgeSeconds = Some(20L)) // expires after 20s
val managerPast = new SessionManager[Map[String, String]](config) {
override def nowMillis = 8172L * 1000L
}.clientSessionManager
val managerFuture = new SessionManager[Map[String, String]](config) {
override def nowMillis = (8172L + 600L) * 1000L // 600s later
}.clientSessionManager
managerFuture.decode(managerPast.encode(data)) == SessionResult.Expired
}
}
}
示例10: pure
//设置package包名称以及导入依赖的类
package org.scalacheck.support.cats
import cats.Monad
import cats.Semigroup
import cats.syntax.semigroup._
import org.scalacheck.Gen
trait Instances {
implicit val genMonad: Monad[Gen] = new Monad[Gen] {
def pure[A](a: A): Gen[A] = Gen.const(a)
def flatMap[A, B](fa: Gen[A])(f: A => Gen[B]): Gen[B] = fa flatMap f
def tailRecM[A, B](a: A)(f: (A) ? Gen[Either[A, B]]): Gen[B] =
f(a) flatMap {
case Right(b) => pure(b)
case Left(aa) => tailRecM(aa)(f)
}
}
implicit def genSemigroup[T: Semigroup]: Semigroup[Gen[T]] = new Semigroup[Gen[T]] {
def combine(g1: Gen[T], g2: Gen[T]): Gen[T] = for { t1 <- g1; t2 <- g2 } yield t1 |+| t2
}
}
object Instances extends Instances
示例11: jwtClaimsSetGen
//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.jwt.generators.nimbus
import java.time.{Duration, ZonedDateTime}
import java.util.Date
import com.fortysevendeg.scalacheck.datetime.GenDateTime._
import com.fortysevendeg.scalacheck.datetime.instances.jdk8._
import com.fortysevendeg.scalacheck.datetime.jdk8.granularity.minutes
import com.nimbusds.jwt.JWTClaimsSet
import org.scalacheck.Gen
trait JWTClaimsSetGen {
def jwtClaimsSetGen(
customClaims: Seq[(String, Any)] = Seq.empty): Gen[JWTClaimsSet] =
for {
issuer <- Gen.alphaStr suchThat (!_.isEmpty)
subject <- Gen.alphaStr suchThat (!_.isEmpty)
now = ZonedDateTime.now
issuedAt <- Gen.const(now).map(t => Date.from(t.toInstant))
expiration <- genDateTimeWithinRange(now.plusMinutes(5),
Duration
.ofMinutes(25))
.map(t => Date.from(t.toInstant))
builder = new JWTClaimsSet.Builder()
.issuer(issuer)
.subject(subject)
.issueTime(issuedAt)
.expirationTime(expiration)
} yield
customClaims
.foldLeft(builder)((b, claim) => b.claim(claim._1, claim._2))
.build()
}
示例12: NameGenerator
//设置package包名称以及导入依赖的类
package prisoners_dilemma
import org.scalacheck.Gen
object NameGenerator {
val VOWELS = Seq('A','E','I','O','U')
def isVowel(c:Char) = VOWELS.contains(c.toUpper)
val CONSONANTS = ('B' to 'Z').filterNot(isVowel).filterNot(_ == 'Q')
val consonant: Gen[Char] =
Gen.oneOf(CONSONANTS)
val vowel: Gen[Char] =
Gen.oneOf(VOWELS)
val syllable = for {
c1 <- consonant
v <- vowel
c2 <- consonant
} yield c1.toString + v + c2
val pronounceableStr = for {
n <- Gen.choose(1,4)
parts <- Gen.listOfN(n, syllable)
} yield parts.mkString("").toLowerCase.capitalize
}
示例13: DimondKataTest
//设置package包名称以及导入依赖的类
import org.scalacheck.Gen
import org.scalatest._
import org.scalatest.prop._
import DimondKata.Line
class DimondKataTest extends FunSuite with Matchers with PropertyChecks {
val chars = Gen.alphaUpperChar
def charIdx(c: Char) = c.toInt - 'A'.toInt
test("property: dimond's number of lines equal to twice char index + 1") {
property { case (char, dimond) =>
dimond.size should equal((charIdx(char) * 2) + 1)
}
}
test("property: dimond has a non-zero number of lines") {
property { case (char, dimond) =>
dimond.size should not(equal(0))
}
}
test("property: all dimond's lines are of the same size") {
property { case (char, dimond) =>
dimond.foreach { line =>
line.size should equal(dimond(0).size)
}
}
}
test("property: dimond's single line size is equal dimond's number of lines (square)") {
property { case (char, dimond) =>
dimond.foreach { line =>
line.size should equal(dimond.size)
}
}
}
test("property: first line has always 'A' in the middle") {
property { case (char, dimond) =>
val firstLine = dimond(0)
firstLine(DimondKata.middle(char)) should equal('A')
(firstLine.take(dimond.size/2) ++ firstLine.drop(dimond.size/2 + 1)).filter(_ != ' ').size should equal(0)
}
}
def property(check: (Char, List[Line]) => Unit) = {
forAll(chars) { char =>
check(char, DimondKata.dimond(char))
}
}
}
示例14: 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)
}
示例15: MetadataAPISpec
//设置package包名称以及导入依赖的类
package llsm.io.metadata
import java.nio.file.{Path, Paths}
import cats.free._
import cats.instances.try_._
import llsm.algebras.{Metadata, MetadataF}
import org.scalacheck.Gen
import org.scalacheck.Shrink
import org.scalatest.Matchers._
import scala.util.{Failure, Success, Try}
class MetadataAPISpec extends MetadataSuite {
implicit val noShrink: Shrink[Int] = Shrink.shrinkAny
val xGen = Gen.choose(2, 256)
val yGen = Gen.choose(2, 256)
val zGen = Gen.choose(2, 10)
val cGen = Gen.choose(2, 3)
val tGen = Gen.choose(2, 3)
"MetadataAPI" should "allow programs to be defined using the Free Monad and Applicative machinery" in forAll(
(xGen, "x"),
(yGen, "y"),
(zGen, "z"),
(cGen, "c"),
(tGen, "t"),
minSuccessful(10)) {
(w: Int, h: Int, z: Int, c: Int, t: Int) =>
val imgPath: String = s"16bit-unsigned&pixelType=uint16&lengths=$w,$h,$z,$c,$t&axes=X,Y,Z,Channel,Time.fake"
val r = scala.util.Random
val channel = r.nextInt(c)
val time = r.nextInt(t)
def program[M[_]: Metadata](path: Path): Free[M, FileMetadata] =
Metadata[M].readMetadata(path)
program[MetadataF](Paths.get(imgPath)).foldMap(metaMockCompiler[Try](channel*time, channel, time)) match {
case Success(FileMetadata(FilenameMetadata(_, _, st, ch, _, _, _), wave, cam, _, _, img)) => {
img match {
case Some(ImgMetadata(dims, _)) => {
dims should equal (Array(w.toLong, h.toLong, z.toLong, c.toLong, t.toLong).filter(_ > 1L))
}
case None => fail("Failed to read Image metadata")
}
st should equal (channel * time)
ch should equal (channel)
}
case Failure(e) => fail(e)
}
}
}