org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks Scala Examples
The following examples show how to use org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: DataReprsTest.scala From polynote with Apache License 2.0 | 5 votes |
package polynote.runtime package test import org.scalacheck.{Arbitrary, Gen} import Arbitrary.arbitrary import org.scalatest.{FreeSpec, Matchers} import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.reflect.runtime.universe.TypeTag class DataReprsTest extends FreeSpec with Matchers with ScalaCheckDrivenPropertyChecks { implicit val arbString: Arbitrary[String] = Arbitrary(Gen.listOf(arbitrary[Char]).map(_.mkString)) def test[T : Arbitrary](implicit typeTag: TypeTag[T], reprsOf: ReprsOf.DataReprsOf[T]): Unit = { s"${typeTag}" in { forAll { (value: T) => reprsOf.encode(value) } } } "DataReprsOf checks" - { "Maps" - { test[Map[String, String]] test[Map[String, Int]] test[Map[String, Map[String, Int]]] test[List[Map[Int, String]]] } "Sequences" - { test[List[String]] test[List[Int]] } "Structs" - { test[(String, Int, Map[Int, String])] test[List[(Int, Boolean, String, String, Option[Int], Option[String], List[String], Map[String, Int])]] } } }
Example 2
Source File: MouseSuite.scala From mouse with MIT License | 5 votes |
package mouse import cats._ import cats.instances.AllInstances import org.scalactic.TripleEqualsSupport.BToAEquivalenceConstraint import org.scalactic.{CanEqual, Equivalence} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks trait MouseSuite extends AnyFunSuite with Matchers with ScalaCheckDrivenPropertyChecks with AllSharedSyntax with AllInstances { implicit val eq0 = new Eq[NumberFormatException] { override def eqv(x: NumberFormatException, y: NumberFormatException): Boolean = x.getMessage == y.getMessage } implicit val eq1 = new Eq[IllegalArgumentException] { override def eqv(x: IllegalArgumentException, y: IllegalArgumentException): Boolean = x.getMessage == y.getMessage } final class MouseEquivalence[T](T: Eq[T]) extends Equivalence[T] { def areEquivalent(a: T, b: T): Boolean = T.eqv(a, b) } implicit def mouseCanEqual[A, B](implicit A: Eq[A], ev: B <:< A): CanEqual[A, B] = new BToAEquivalenceConstraint[A, B](new MouseEquivalence(A), ev) }
Example 3
Source File: OdinSpec.scala From odin with Apache License 2.0 | 5 votes |
package io.odin import java.time.LocalDateTime import cats.effect.{Clock, Timer} import cats.{Applicative, Eval} import io.odin.formatter.Formatter import io.odin.meta.Position import org.scalacheck.{Arbitrary, Cogen, Gen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.{Checkers, ScalaCheckDrivenPropertyChecks} import org.typelevel.discipline.Laws import scala.concurrent.duration.{FiniteDuration, TimeUnit} trait OdinSpec extends AnyFlatSpec with Matchers with Checkers with ScalaCheckDrivenPropertyChecks with EqInstances { def checkAll(name: String, ruleSet: Laws#RuleSet): Unit = { for ((id, prop) <- ruleSet.all.properties) it should (name + "." + id) in { check(prop) } } def zeroTimer[F[_]](implicit F: Applicative[F]): Timer[F] = new Timer[F] { def clock: Clock[F] = new Clock[F] { def realTime(unit: TimeUnit): F[Long] = F.pure(0L) def monotonic(unit: TimeUnit): F[Long] = F.pure(0L) } def sleep(duration: FiniteDuration): F[Unit] = ??? } val lineSeparator: String = System.lineSeparator() val nonEmptyStringGen: Gen[String] = Gen.nonEmptyListOf(Gen.alphaNumChar).map(_.mkString) val levelGen: Gen[Level] = Gen.oneOf(Level.Trace, Level.Debug, Level.Info, Level.Warn, Level.Error) implicit val levelArbitrary: Arbitrary[Level] = Arbitrary(levelGen) val positionGen: Gen[Position] = for { fileName <- nonEmptyStringGen enclosureName <- Gen.uuid.map(_.toString) packageName <- nonEmptyStringGen line <- Gen.posNum[Int] } yield { Position(fileName, enclosureName, packageName, line) } implicit val positionArbitrary: Arbitrary[Position] = Arbitrary(positionGen) val loggerMessageGen: Gen[LoggerMessage] = { val startTime = System.currentTimeMillis() for { level <- levelGen msg <- Gen.alphaNumStr context <- Gen.mapOfN(20, nonEmptyStringGen.flatMap(key => nonEmptyStringGen.map(key -> _))) exception <- Gen.option(Arbitrary.arbitrary[Throwable]) position <- positionGen threadName <- nonEmptyStringGen timestamp <- Gen.choose(0, startTime) } yield { LoggerMessage( level = level, message = Eval.now(msg), context = context, exception = exception, position = position, threadName = threadName, timestamp = timestamp ) } } implicit val loggerMessageArbitrary: Arbitrary[LoggerMessage] = Arbitrary(loggerMessageGen) implicit val cogenLoggerMessage: Cogen[LoggerMessage] = Cogen[LoggerMessage]((msg: LoggerMessage) => msg.level.hashCode().toLong + msg.message.value.hashCode().toLong) val formatterGen: Gen[Formatter] = Gen.oneOf(Formatter.default, Formatter.colorful) implicit val formatterArbitrary: Arbitrary[Formatter] = Arbitrary(formatterGen) val localDateTimeGen: Gen[LocalDateTime] = for { year <- Gen.choose(0, LocalDateTime.now().getYear) month <- Gen.choose(1, 12) day <- Gen.choose(1, 28) hour <- Gen.choose(0, 23) minute <- Gen.choose(0, 59) second <- Gen.choose(0, 59) } yield { LocalDateTime.of(year, month, day, hour, minute, second) } implicit val localDateTimeArbitrary: Arbitrary[LocalDateTime] = Arbitrary(localDateTimeGen) }
Example 4
Source File: StringEncodingUtilitiesTest.scala From morpheus with Apache License 2.0 | 5 votes |
package org.opencypher.morpheus.api.io.util import org.opencypher.okapi.impl.util.StringEncodingUtilities._ import org.opencypher.okapi.testing.BaseTestSuite import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class StringEncodingUtilitiesTest extends BaseTestSuite with ScalaCheckDrivenPropertyChecks { it("encodes arbitrary strings with only letters, digits, underscores, hashes, and 'at' symbols") { forAll { s: String => val encoded = s.encodeSpecialCharacters val decoded = encoded.decodeSpecialCharacters s should equal(decoded) encoded.forall { c => (c.isLetterOrDigit && c.isAscii) || c == '_' || c == '@' } } } }
Example 5
Source File: SparkTableTest.scala From morpheus with Apache License 2.0 | 5 votes |
package org.opencypher.morpheus.impl import org.apache.spark.sql.types._ import org.apache.spark.sql.{Row, functions} import org.opencypher.morpheus.impl.table.SparkTable.{DataFrameTable, _} import org.opencypher.morpheus.testing.MorpheusTestSuite import org.opencypher.okapi.testing.Bag import org.opencypher.okapi.testing.Bag._ import org.scalatest.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.collection.mutable.WrappedArray.ofLong class SparkTableTest extends MorpheusTestSuite with Matchers with ScalaCheckDrivenPropertyChecks { import morpheus.sparkSession.sqlContext.implicits._ it("it should cast integer columns to long") { val df = sparkSession.createDataFrame(List( Row(1, 2L, Array(42), Array(42), Array(42L), Row(42, 42L)) ).asJava, StructType(Seq( StructField("a", IntegerType, nullable = true), StructField("b", LongType, nullable = false), StructField("c", ArrayType(IntegerType, containsNull = true), nullable = true), StructField("d", ArrayType(IntegerType, containsNull = false), nullable = false), StructField("e", ArrayType(LongType, containsNull = false), nullable = false), StructField("f", StructType(Seq( StructField("foo", IntegerType, true), StructField("bar", LongType, false) )), nullable = true) ))) val updatedDf = df.castToLong updatedDf.schema should equal(StructType(Seq( StructField("a", LongType, nullable = true), StructField("b", LongType, nullable = false), StructField("c", ArrayType(LongType, containsNull = true), nullable = true), StructField("d", ArrayType(LongType, containsNull = false), nullable = false), StructField("e", ArrayType(LongType, containsNull = false), nullable = false), StructField("f", StructType(Seq( StructField("foo", LongType, true), StructField("bar", LongType, true) )), nullable = false) ))) updatedDf.collect().toBag should equal(Bag( Row(1L, 2L, new ofLong(Array(42L)), new ofLong(Array(42L)), new ofLong(Array(42L)), Row(42L, 42L)) )) } // These tests verifies that https://issues.apache.org/jira/browse/SPARK-26572 is still fixed describe("distinct workaround") { it("detects if the Spark bug is still fixed") { val baseTable = Seq(1, 1).toDF("idx") // Uses Spark distinct val distinctWithId = baseTable.distinct.withColumn("id", functions.monotonically_increasing_id()) val monotonicallyOnLeft = distinctWithId.join(baseTable, "idx") // Bug in Spark: "monotonically_increasing_id" is pushed down when it shouldn't be. Push down only happens when the // DF containing the "monotonically_increasing_id" expression is on the left side of the join. monotonicallyOnLeft.select("id").collect().map(_.get(0)).distinct.length shouldBe 1 } } }
Example 6
Source File: BsonCodecInstancesTest.scala From circe-bson with Apache License 2.0 | 5 votes |
package io.circe.bson import io.circe.{ Json, JsonNumber } import io.circe.testing.ArbitraryInstances import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import reactivemongo.bson.BSONDecimal import scala.util.{ Failure, Success, Try } class BsonCodecInstancesTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks with ArbitraryInstances { override def transformJsonNumber(n: JsonNumber): JsonNumber = Try(BSONDecimal.parse(n.toString)).flatten match { case Success(_) => n case Failure(_) => JsonNumber.fromString("0").get } test("BsonCodecInstances should round-trip JSON values") { forAll { json: Json => assert(Right(json) === jsonToBson(json).flatMap(bsonToJson)) } } test("BsonCodecInstances should support BSON Date values") { val json = Json.obj("myDate" -> Json.obj("$date" -> Json.fromLong(1570040789432L))) assert(Right(json) === jsonToBson(json).flatMap(bsonToJson)) } }
Example 7
Source File: JobTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless import org.scalacheck.Arbitrary import org.scalatest.BeforeAndAfterAll import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers class JobTests extends AnyFreeSpec with BeforeAndAfterAll with SparkTesting with ScalaCheckDrivenPropertyChecks with Matchers { "map" - { "identity" in { def check[T](implicit arb: Arbitrary[T]) = forAll { t: T => Job(t).map(identity).run() shouldEqual Job(t).run() } check[Int] } val f1: Int => Int = _ + 1 val f2: Int => Int = (i: Int) => i * i "composition" in forAll { i: Int => Job(i).map(f1).map(f2).run() shouldEqual Job(i).map(f1 andThen f2).run() } } "flatMap" - { val f1: Int => Job[Int] = (i: Int) => Job(i + 1) val f2: Int => Job[Int] = (i: Int) => Job(i * i) "left identity" in forAll { i: Int => Job(i).flatMap(f1).run() shouldEqual f1(i).run() } "right identity" in forAll { i: Int => Job(i).flatMap(i => Job.apply(i)).run() shouldEqual Job(i).run() } "associativity" in forAll { i: Int => Job(i).flatMap(f1).flatMap(f2).run() shouldEqual Job(i).flatMap(ii => f1(ii).flatMap(f2)).run() } } "properties" - { "read back" in forAll { (k:String, v: String) => val scopedKey = "frameless.tests." + k Job(1).withLocalProperty(scopedKey,v).run() sc.getLocalProperty(scopedKey) shouldBe v } } }
Example 8
Source File: CirceSuite.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras import cats.instances._ import cats.syntax._ import io.circe.testing.{ ArbitraryInstances, EqInstances } import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.{ Checkers, ScalaCheckDrivenPropertyChecks } import org.typelevel.discipline.Laws import scala.language.implicitConversions trait CirceSuite extends AnyFlatSpec with ScalaCheckDrivenPropertyChecks with AllInstances with AllInstancesBinCompat0 with AllInstancesBinCompat1 with AllInstancesBinCompat2 with AllInstancesBinCompat3 with AllInstancesBinCompat4 with AllInstancesBinCompat5 with AllInstancesBinCompat6 with AllSyntax with AllSyntaxBinCompat0 with AllSyntaxBinCompat1 with AllSyntaxBinCompat2 with AllSyntaxBinCompat3 with AllSyntaxBinCompat4 with AllSyntaxBinCompat5 with AllSyntaxBinCompat6 with ArbitraryInstances with EqInstances { override def convertToEqualizer[T](left: T): Equalizer[T] = sys.error("Intentionally ambiguous implicit for Equalizer") implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab) def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach { case ((id, prop), 0) => name should s"obey $id" in Checkers.check(prop) case ((id, prop), _) => it should s"obey $id" in Checkers.check(prop) } }
Example 9
Source File: DomainValidationsSpec.scala From vinyldns with Apache License 2.0 | 5 votes |
package vinyldns.api.domain import cats.scalatest.ValidatedMatchers import org.scalacheck._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest._ import org.scalatest.propspec.AnyPropSpec import org.scalatest.matchers.should.Matchers import vinyldns.api.ValidationTestImprovements._ import vinyldns.core.domain.{InvalidDomainName, InvalidLength} class DomainValidationsSpec extends AnyPropSpec with Matchers with ScalaCheckDrivenPropertyChecks with ValidatedMatchers { import Gen._ import vinyldns.api.domain.DomainValidations._ import vinyldns.api.DomainGenerator._ import vinyldns.api.IpAddressGenerator._ property("Shortest domain name should be valid") { validateHostName("a.") shouldBe valid } property("Longest domain name should be valid") { val name = ("a" * 50 + ".") * 5 validateHostName(name) shouldBe valid } property("Domain name should pass property-based testing") { forAll(domainGenerator) { domain: String => whenever(validateHostName(domain).isValid) { domain.length should be > 0 domain.length should be < 256 (domain should fullyMatch).regex(validFQDNRegex) domain should endWith(".") } } } property("Domain names beginning with invalid characters should fail with InvalidDomainName") { validateHostName("/slash.domain.name.").failWith[InvalidDomainName] validateHostName("-hyphen.domain.name.").failWith[InvalidDomainName] } property("Domain names with underscores should pass property-based testing") { validateHostName("_underscore.domain.name.").isValid validateHostName("under_score.domain.name.").isValid validateHostName("underscore._domain.name.").isValid } property("Valid Ipv4 addresses should pass property-based testing") { forAll(validIpv4Gen) { validIp: String => val res = validateIpv4Address(validIp) res shouldBe valid (validIp should fullyMatch).regex(validIpv4Regex) } } property("Invalid Ipv4 addresses should fail property-based testing") { forAll(invalidIpGen) { invalidIp: String => whenever(validateIpv4Address(invalidIp).isInvalid) { (invalidIp shouldNot fullyMatch).regex(validIpv4Regex) } } } property("Valid string lengths should pass property-based testing") { val validDescGen: Gen[String] = listOfN(255, alphaNumChar).map(_.mkString) forAll(option(validDescGen)) { desc: Option[String] => validateStringLength(desc, None, 255) shouldBe valid } } property("Description of None and Some(\"\") should succeed") { validateStringLength(Some(""), None, 255) shouldBe valid validateStringLength(None, None, 255) shouldBe valid } property("String exceeding maximum description length should fail with InvalidLength") { val invalidDesc = "a" * 256 validateStringLength(Some(invalidDesc), None, 255).failWith[InvalidLength] } }
Example 10
Source File: consk.scala From kittens with Apache License 2.0 | 5 votes |
package cats.derived import alleycats.ConsK import cats.laws.discipline.SerializableTests import org.scalacheck.Arbitrary import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class ConsKSuite extends KittensSuite with ScalaCheckDrivenPropertyChecks { import ConsKSuite._ import TestDefns._ def checkConsK[F[_], A : Arbitrary](nil: F[A])(fromSeq: Seq[A] => F[A])(implicit F: ConsK[F]): Unit = forAll((xs: List[A]) => assert(xs.foldRight(nil)(F.cons) == fromSeq(xs))) def testConsK(context: String)(implicit iList: ConsK[IList], snoc: ConsK[Snoc]): Unit = { test(s"$context.ConsK[IList]")(checkConsK[IList, Int](INil())(IList.fromSeq)) test(s"$context.ConsK[Snoc]")(checkConsK[Snoc, Int](SNil())(xs => Snoc.fromSeq(xs.reverse))) checkAll(s"$context.ConsK is Serializable", SerializableTests.serializable(ConsK[IList])) } { import auto.consK._ testConsK("auto") } { import cached.consK._ testConsK("cached") } { import semiInstances._ testConsK("semi") } } object ConsKSuite { import TestDefns._ object semiInstances { implicit val iList: ConsK[IList] = semiauto.consK[IList] implicit val snoc: ConsK[Snoc] = semiauto.consK[Snoc] } }
Example 11
Source File: FoldedTests.scala From aecor with MIT License | 5 votes |
package aecor.tests import aecor.data.Folded import cats.{ CoflatMap, Eval, Later, Monad, MonadError, Semigroupal } import cats.laws.{ ApplicativeLaws, CoflatMapLaws, FlatMapLaws, MonadLaws } import cats.laws.discipline._ import Folded.syntax._ import org.scalacheck.{ Arbitrary, Cogen } import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuiteLike import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.typelevel.discipline.scalatest.Discipline import cats.implicits._ class FoldedTests extends AnyFunSuiteLike with Matchers with ScalaCheckDrivenPropertyChecks with Discipline with StrictCatsEquality { implicit def arbitraryFolded[A](implicit A: Arbitrary[Option[A]]): Arbitrary[Folded[A]] = Arbitrary(A.arbitrary.map(_.map(_.next).getOrElse(impossible))) implicit def cogenFolded[A](implicit A: Cogen[Option[A]]): Cogen[Folded[A]] = A.contramap(_.toOption) checkAll("Folded[Int]", SemigroupalTests[Folded].semigroupal[Int, Int, Int]) checkAll("Cartesian[Folded]", SerializableTests.serializable(Semigroupal[Folded])) checkAll("Folded[Int]", CoflatMapTests[Folded].coflatMap[Int, Int, Int]) checkAll("CoflatMap[Folded]", SerializableTests.serializable(CoflatMap[Folded])) checkAll("Folded[Int]", MonadTests[Folded].monad[Int, Int, Int]) checkAll("Monad[Folded]", SerializableTests.serializable(Monad[Folded])) checkAll("Folded with Unit", MonadErrorTests[Folded, Unit].monadError[Int, Int, Int]) checkAll("MonadError[Folded, Unit]", SerializableTests.serializable(MonadError[Folded, Unit])) test("show") { impossible[Int].show should ===("Impossible") 1.next.show should ===("Next(1)") forAll { fs: Folded[String] => fs.show should ===(fs.toString) } } // The following tests check laws which are a different formulation of // laws that are checked. Since these laws are more or less duplicates of // existing laws, we don't check them for all types that have the relevant // instances. test("Kleisli associativity") { forAll { (l: Long, f: Long => Folded[Int], g: Int => Folded[Char], h: Char => Folded[String]) => val isEq = FlatMapLaws[Folded].kleisliAssociativity(f, g, h, l) isEq.lhs should ===(isEq.rhs) } } test("Cokleisli associativity") { forAll { (l: Folded[Long], f: Folded[Long] => Int, g: Folded[Int] => Char, h: Folded[Char] => String) => val isEq = CoflatMapLaws[Folded].cokleisliAssociativity(f, g, h, l) isEq.lhs should ===(isEq.rhs) } } test("applicative composition") { forAll { (fa: Folded[Int], fab: Folded[Int => Long], fbc: Folded[Long => Char]) => val isEq = ApplicativeLaws[Folded].applicativeComposition(fa, fab, fbc) isEq.lhs should ===(isEq.rhs) } } val monadLaws = MonadLaws[Folded] test("Kleisli left identity") { forAll { (a: Int, f: Int => Folded[Long]) => val isEq = monadLaws.kleisliLeftIdentity(a, f) isEq.lhs should ===(isEq.rhs) } } test("Kleisli right identity") { forAll { (a: Int, f: Int => Folded[Long]) => val isEq = monadLaws.kleisliRightIdentity(a, f) isEq.lhs should ===(isEq.rhs) } } test("map2Eval is lazy") { val bomb: Eval[Folded[Int]] = Later(sys.error("boom")) impossible[Int].map2Eval(bomb)(_ + _).value should ===(impossible[Int]) } }
Example 12
Source File: GlobalIssuesSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.pr import com.mwz.sonar.scala.pr.Generators._ import org.scalacheck.ScalacheckShapeless._ import org.scalatest.Inspectors import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.sonar.api.batch.fs.internal.TestInputFileBuilder import org.sonar.api.batch.rule.Severity import org.sonar.api.rule.RuleKey class GlobalIssuesSpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { it should "add a new issue" in { val issues = new GlobalIssues val file = TestInputFileBuilder .create("", "test.scala") .build val issue = Issue( key = RuleKey.of("repo", "rule"), file = file, line = 10, severity = Severity.MAJOR, message = "test" ) issues.add(issue) issues.allIssues shouldBe Map(file -> List(issue)) } it should "return all issues" in { forAll { (issues: List[Issue]) => whenever(issues.nonEmpty) { val globalIssues = new GlobalIssues val expected = issues.groupBy(_.file) issues.foreach(globalIssues.add) Inspectors.forAll(globalIssues.allIssues) { case (file, issues) => issues should contain theSameElementsAs expected(file) } } } } }
Example 13
Source File: JsTest.scala From scalaz-deriving with GNU Lesser General Public License v3.0 | 5 votes |
// Copyright: 2017 - 2020 Sam Halliday // License: http://www.gnu.org/licenses/lgpl-3.0.en.html package jsonformat import org.scalatest._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import JsDecoder.ops._ import JsEncoder.ops._ import internal.FastToIList._ import scalaz._, Scalaz._ import org.scalatest.flatspec.AnyFlatSpec abstract class JsTest extends AnyFlatSpec with NonImplicitAssertions with ScalaCheckDrivenPropertyChecks { type Position = org.scalactic.source.Position type Assertion = org.scalatest.Assertion implicit class EncoderHelper[T: JsEncoder](t: T) { def jsonString: String = CompactPrinter(t.toJson) } implicit class DecoderHelper(s: String) { def parseAs[A: JsDecoder]: String \/ A = JsParser(s) >>= (_.as[A]) } // inefficient constructors that are convenient in tests implicit class JsArrayCompanionOps(self: JsArray.type) { def apply(vs: JsValue*): JsArray = JsArray(vs.toIList) } implicit class JsObjectCompanionOps(self: JsObject.type) { def apply(vs: (String, JsValue)*): JsObject = JsObject(vs.toIList) } }
Example 14
Source File: CommonAccountsApiSpec.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.http import com.wavesplatform.api.common.CommonAccountsApi import com.wavesplatform.common.utils._ import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.{DataEntry, Diff, StringDataEntry, diffs} import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction} import com.wavesplatform.{BlocksTransactionsHelpers, TransactionGen, history} import monix.execution.Scheduler.Implicits.global import org.scalatest.{FreeSpec, Matchers} import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class CommonAccountsApiSpec extends FreeSpec with Matchers with WithDomain with TransactionGen with BlocksTransactionsHelpers with ScalaCheckDrivenPropertyChecks { "Data stream" - { "handles non-existent address" in { val entry1 = StringDataEntry("test", "test") val entry2 = StringDataEntry("test1", "test") val entry3 = StringDataEntry("test2", "test") val preconditions = for { acc <- accountGen ts = System.currentTimeMillis() fee <- smallFeeGen genesis = GenesisTransaction.create(acc.toAddress, diffs.ENOUGH_AMT, ts).explicitGet() data1 = DataTransaction.selfSigned(1.toByte, acc, Seq(entry1), fee, ts).explicitGet() data2 = DataTransaction.selfSigned(1.toByte, acc, Seq(entry2), fee, ts).explicitGet() data3 = DataTransaction.selfSigned(1.toByte, acc, Seq(entry3), fee, ts).explicitGet() (block1, mbs1) = UnsafeBlocks.unsafeChainBaseAndMicro(history.randomSig, Seq(genesis), Seq(Seq(data1)), acc, 3, ts) (block2, mbs2) = UnsafeBlocks.unsafeChainBaseAndMicro(mbs1.last.totalResBlockSig, Seq(data2), Seq(Seq(data3)), acc, 3, ts) } yield (acc, block1, mbs1.head, block2, mbs2.head) forAll(preconditions) { case (acc, block1, mb1, block2, mb2) => withDomain(domainSettingsWithFS(TestFunctionalitySettings.withFeatures(BlockchainFeatures.NG, BlockchainFeatures.DataTransaction))) { d => val commonAccountsApi = CommonAccountsApi(d.blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), d.db, d.blockchainUpdater) def dataList(): Set[DataEntry[_]] = commonAccountsApi.dataStream(acc.toAddress, None).toListL.runSyncUnsafe().toSet d.appendBlock(block1) dataList() shouldBe empty d.appendMicroBlock(mb1) dataList() shouldBe Set(entry1) d.appendBlock(block2) dataList() shouldBe Set(entry1, entry2) d.appendMicroBlock(mb2) dataList() shouldBe Set(entry1, entry2, entry3) } } } } }
Example 15
Source File: ScriptComplexityMiningConstraintSuite.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.mining import com.typesafe.config.ConfigFactory import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils._ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.settings.WavesSettings import com.wavesplatform.state.diffs.TransactionDiffer import com.wavesplatform.state.{AccountScriptInfo, Blockchain, LeaseBalance} import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.{DataTransaction, Transaction, TxVersion} import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen import org.scalamock.scalatest.PathMockFactory import org.scalatest.{FlatSpec, Matchers} import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class ScriptComplexityMiningConstraintSuite extends FlatSpec with Matchers with ScalaCheckDrivenPropertyChecks with PathMockFactory with TransactionGen with NoShrink { private val settings = WavesSettings.fromRootConfig(ConfigFactory.load()) private val complexity = OneDimensionalMiningConstraint(1000, TxEstimators.scriptsComplexity, "MaxScriptsComplexityInBlock") private val maxTxs = OneDimensionalMiningConstraint(3, TxEstimators.one, "MaxTxsInMicroBlock") private val constraint = MultiDimensionalMiningConstraint(complexity, maxTxs) val (script, _) = ScriptCompiler.compile("true", ScriptEstimatorV3).explicitGet() "ScriptComplexityMiningConstraint" should "accept non-scripted txs after limit" in { forAll(preconditions) { case (acc1, tx1, tx2, tx3) => val blockchain = stub[Blockchain] (blockchain.settings _).when().returning(settings.blockchainSettings) (blockchain.height _).when().returning(1) (blockchain.activatedFeatures _).when().returning(Map(BlockchainFeatures.DataTransaction.id -> 0)) val txDiffer = TransactionDiffer(Some(System.currentTimeMillis() - 1000), System.currentTimeMillis())(blockchain, _: Transaction).resultE.explicitGet() (blockchain.balance _).when(*, *).returning(10000000) (blockchain.leaseBalance _).when(*).returning(LeaseBalance(0, 0)) (blockchain.accountScript _).when(tx1.sender.toAddress).returning(Some(AccountScriptInfo(acc1.publicKey, script, 1000, Map.empty))) (blockchain.accountScript _).when(*).returning(None) val c1 = constraint.put(blockchain, tx1, txDiffer(tx1)) val cOverfilled = c1.put(blockchain, tx1, txDiffer(tx1)) cOverfilled.isOverfilled shouldBe true val c2 = c1.put(blockchain, tx2, txDiffer(tx2)) c2.isFull shouldBe false val c3 = c2.put(blockchain, tx3, txDiffer(tx3)) c3.isFull shouldBe true c3.isOverfilled shouldBe false } } private[this] def preconditions: Gen[(KeyPair, DataTransaction, DataTransaction, DataTransaction)] = for { acc1 <- accountGen acc2 <- accountGen tx1 = DataTransaction.selfSigned(TxVersion.V1, acc1, Nil, 1000000, System.currentTimeMillis()).explicitGet() tx2 = DataTransaction.selfSigned(TxVersion.V1, acc2, Nil, 1000000, System.currentTimeMillis()).explicitGet() tx3 = DataTransaction.selfSigned(TxVersion.V1, acc2, Nil, 1000000, System.currentTimeMillis()).explicitGet() } yield (acc1, tx1, tx2, tx3) }
Example 16
Source File: CirceSuite.scala From circe-jackson with Apache License 2.0 | 5 votes |
package io.circe.jackson import cats.instances.AllInstances import cats.syntax.{ AllSyntax, EitherOps } import io.circe.Json import io.circe.testing.{ ArbitraryInstances, EqInstances } import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.typelevel.discipline.scalatest.FlatSpecDiscipline import scala.language.implicitConversions trait CirceSuite extends AnyFlatSpec with FlatSpecDiscipline with ScalaCheckDrivenPropertyChecks with AllInstances with AllSyntax with ArbitraryInstances with EqInstances { override def convertToEqualizer[T](left: T): Equalizer[T] = sys.error("Intentionally ambiguous implicit for Equalizer") implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab) val glossary: Json = Json.obj( "glossary" -> Json.obj( "title" -> Json.fromString("example glossary"), "GlossDiv" -> Json.obj( "title" -> Json.fromString("S"), "GlossList" -> Json.obj( "GlossEntry" -> Json.obj( "ID" -> Json.fromString("SGML"), "SortAs" -> Json.fromString("SGML"), "GlossTerm" -> Json.fromString("Standard Generalized Markup Language"), "Acronym" -> Json.fromString("SGML"), "Abbrev" -> Json.fromString("ISO 8879:1986"), "GlossDef" -> Json.obj( "para" -> Json.fromString( "A meta-markup language, used to create markup languages such as DocBook." ), "GlossSeeAlso" -> Json.arr(Json.fromString("GML"), Json.fromString("XML")) ), "GlossSee" -> Json.fromString("markup") ) ) ) ) ) }
Example 17
Source File: BigQueryClientTest.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.bigquery import com.spotify.scio.bigquery.client.BigQuery import org.scalacheck.Gen import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec class BigQueryClientTest extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { "BigQueryClient" should "throw an exception when an empty or null ProjectId is provided" in { assertThrows[IllegalArgumentException] { BigQuery("") } assertThrows[IllegalArgumentException] { BigQuery(null) } } it should "work with non-empty ProjectId" in { val projectIdGen = Gen.alphaNumStr.suchThat(_.nonEmpty) forAll(projectIdGen)(projectId => BigQuery(projectId)) } }
Example 18
Source File: RepeatablesSpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
import scalapb.e2e.repeatables.RepeatablesTest import scalapb.e2e.repeatables.RepeatablesTest.Nested import org.scalatest._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalacheck.{Arbitrary, Gen} import scalapb.json4s.JsonFormat import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class JsonSpec extends AnyFlatSpec with ScalaCheckDrivenPropertyChecks with Matchers { val nestedGen = Arbitrary.arbitrary[Option[Int]].map(s => Nested(nestedField = s)) val repGen = for { strings <- Gen.listOf(Arbitrary.arbitrary[String]) ints <- Gen.listOf(Arbitrary.arbitrary[Int]) doubles <- Gen.listOf(Arbitrary.arbitrary[Double]) nesteds <- Gen.listOf(nestedGen) } yield RepeatablesTest( strings = strings, ints = ints, doubles = doubles, nesteds = nesteds ) "fromJson" should "invert toJson (single)" in { val rep = RepeatablesTest( strings = Seq("s1", "s2"), ints = Seq(14, 19), doubles = Seq(3.14, 2.17), nesteds = Seq(Nested()) ) val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } "fromJson" should "invert toJson" in { forAll(repGen) { rep => val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } } }
Example 19
Source File: ArbitrarySpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
package scalapb.json4s import scalapb.e2e.repeatables.RepeatablesTest import scalapb.e2e.repeatables.RepeatablesTest.Nested import org.scalatest._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalacheck.{Arbitrary, Gen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class ArbitrarySpec extends AnyFlatSpec with ScalaCheckDrivenPropertyChecks with Matchers { val nestedGen = Arbitrary.arbitrary[Option[Int]].map(s => Nested(nestedField = s)) val repGen = for { strings <- Gen.listOf(Arbitrary.arbitrary[String]) ints <- Gen.listOf(Arbitrary.arbitrary[Int]) doubles <- Gen.listOf(Arbitrary.arbitrary[Double]) nesteds <- Gen.listOf(nestedGen) } yield RepeatablesTest( strings = strings, ints = ints, doubles = doubles, nesteds = nesteds ) "fromJson" should "invert toJson (single)" in { val rep = RepeatablesTest( strings = Seq("s1", "s2"), ints = Seq(14, 19), doubles = Seq(3.14, 2.17), nesteds = Seq(Nested()) ) val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } "fromJson" should "invert toJson" in { forAll(repGen) { rep => val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } } }
Example 20
Source File: MergeByCommitCallbackTest.scala From monix-kafka with Apache License 2.0 | 5 votes |
package monix.kafka import monix.eval.Task import monix.kafka.config.AutoOffsetReset import monix.reactive.Observable import org.apache.kafka.clients.producer.ProducerRecord import org.scalatest.{FunSuite, Matchers} import scala.concurrent.duration._ import scala.concurrent.Await import monix.execution.Scheduler.Implicits.global import org.apache.kafka.clients.consumer.OffsetCommitCallback import org.apache.kafka.common.TopicPartition import org.scalacheck.Gen import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class MergeByCommitCallbackTest extends FunSuite with KafkaTestKit with ScalaCheckDrivenPropertyChecks with Matchers { val commitCallbacks: List[Commit] = List.fill(4)(new Commit { override def commitBatchSync(batch: Map[TopicPartition, Long]): Task[Unit] = Task.unit override def commitBatchAsync(batch: Map[TopicPartition, Long], callback: OffsetCommitCallback): Task[Unit] = Task.unit }) val committableOffsetsGen: Gen[CommittableOffset] = for { partition <- Gen.posNum[Int] offset <- Gen.posNum[Long] commit <- Gen.oneOf(commitCallbacks) } yield CommittableOffset(new TopicPartition("topic", partition), offset, commit) test("merge by commit callback works") { forAll(Gen.nonEmptyListOf(committableOffsetsGen)) { offsets => val partitions = offsets.map(_.topicPartition) val received: List[CommittableOffsetBatch] = CommittableOffsetBatch.mergeByCommitCallback(offsets) received.foreach { batch => partitions should contain allElementsOf batch.offsets.keys } received.size should be <= 4 } } test("merge by commit callback for multiple consumers") { withRunningKafka { val count = 10000 val topicName = "monix-kafka-merge-by-commit" val producerCfg = KafkaProducerConfig.default.copy( bootstrapServers = List("127.0.0.1:6001"), clientId = "monix-kafka-1-0-producer-test" ) val producer = KafkaProducerSink[String, String](producerCfg, io) val pushT = Observable .range(0, count) .map(msg => new ProducerRecord(topicName, "obs", msg.toString)) .bufferIntrospective(1024) .consumeWith(producer) val listT = Observable .range(0, 4) .mergeMap(i => createConsumer(i.toInt, topicName).take(500)) .bufferTumbling(2000) .map(CommittableOffsetBatch.mergeByCommitCallback) .map { offsetBatches => assert(offsetBatches.length == 4) } .completedL Await.result(Task.parZip2(listT, pushT).runToFuture, 60.seconds) } } private def createConsumer(i: Int, topicName: String): Observable[CommittableOffset] = { val cfg = KafkaConsumerConfig.default.copy( bootstrapServers = List("127.0.0.1:6001"), groupId = s"kafka-tests-$i", autoOffsetReset = AutoOffsetReset.Earliest ) KafkaConsumerObservable .manualCommit[String, String](cfg, List(topicName)) .executeOn(io) .map(_.committableOffset) } }
Example 21
Source File: MergeByCommitCallbackTest.scala From monix-kafka with Apache License 2.0 | 5 votes |
package monix.kafka import monix.eval.Task import monix.kafka.config.AutoOffsetReset import monix.reactive.Observable import org.apache.kafka.clients.producer.ProducerRecord import org.scalatest.{FunSuite, Matchers} import scala.concurrent.duration._ import scala.concurrent.Await import monix.execution.Scheduler.Implicits.global import org.apache.kafka.clients.consumer.OffsetCommitCallback import org.apache.kafka.common.TopicPartition import org.scalacheck.Gen import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class MergeByCommitCallbackTest extends FunSuite with KafkaTestKit with ScalaCheckDrivenPropertyChecks with Matchers { val commitCallbacks: List[Commit] = List.fill(4)(new Commit { override def commitBatchSync(batch: Map[TopicPartition, Long]): Task[Unit] = Task.unit override def commitBatchAsync(batch: Map[TopicPartition, Long], callback: OffsetCommitCallback): Task[Unit] = Task.unit }) val committableOffsetsGen: Gen[CommittableOffset] = for { partition <- Gen.posNum[Int] offset <- Gen.posNum[Long] commit <- Gen.oneOf(commitCallbacks) } yield CommittableOffset(new TopicPartition("topic", partition), offset, commit) test("merge by commit callback works") { forAll(Gen.nonEmptyListOf(committableOffsetsGen)) { offsets => val partitions = offsets.map(_.topicPartition) val received: List[CommittableOffsetBatch] = CommittableOffsetBatch.mergeByCommitCallback(offsets) received.foreach { batch => partitions should contain allElementsOf batch.offsets.keys } received.size should be <= 4 } } test("merge by commit callback for multiple consumers") { withRunningKafka { val count = 10000 val topicName = "monix-kafka-merge-by-commit" val producerCfg = KafkaProducerConfig.default.copy( bootstrapServers = List("127.0.0.1:6001"), clientId = "monix-kafka-1-0-producer-test" ) val producer = KafkaProducerSink[String, String](producerCfg, io) val pushT = Observable .range(0, count) .map(msg => new ProducerRecord(topicName, "obs", msg.toString)) .bufferIntrospective(1024) .consumeWith(producer) val listT = Observable .range(0, 4) .mergeMap(i => createConsumer(i.toInt, topicName).take(500)) .bufferTumbling(2000) .map(CommittableOffsetBatch.mergeByCommitCallback) .map { offsetBatches => assert(offsetBatches.length == 4) } .completedL Await.result(Task.parZip2(listT, pushT).runToFuture, 60.seconds) } } private def createConsumer(i: Int, topicName: String): Observable[CommittableOffset] = { val cfg = KafkaConsumerConfig.default.copy( bootstrapServers = List("127.0.0.1:6001"), groupId = s"kafka-tests-$i", autoOffsetReset = AutoOffsetReset.Earliest ) KafkaConsumerObservable .manualCommit[String, String](cfg, List(topicName)) .executeOn(io) .map(_.committableOffset) } }
Example 22
Source File: MergeByCommitCallbackTest.scala From monix-kafka with Apache License 2.0 | 5 votes |
package monix.kafka import monix.eval.Task import monix.kafka.config.AutoOffsetReset import monix.reactive.Observable import org.apache.kafka.clients.producer.ProducerRecord import org.scalatest.{FunSuite, Matchers} import scala.concurrent.duration._ import scala.concurrent.Await import monix.execution.Scheduler.Implicits.global import org.apache.kafka.clients.consumer.OffsetCommitCallback import org.apache.kafka.common.TopicPartition import org.scalacheck.Gen import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class MergeByCommitCallbackTest extends FunSuite with KafkaTestKit with ScalaCheckDrivenPropertyChecks with Matchers { val commitCallbacks: List[Commit] = List.fill(4)(new Commit { override def commitBatchSync(batch: Map[TopicPartition, Long]): Task[Unit] = Task.unit override def commitBatchAsync(batch: Map[TopicPartition, Long], callback: OffsetCommitCallback): Task[Unit] = Task.unit }) val committableOffsetsGen: Gen[CommittableOffset] = for { partition <- Gen.posNum[Int] offset <- Gen.posNum[Long] commit <- Gen.oneOf(commitCallbacks) } yield CommittableOffset(new TopicPartition("topic", partition), offset, commit) test("merge by commit callback works") { forAll(Gen.nonEmptyListOf(committableOffsetsGen)) { offsets => val partitions = offsets.map(_.topicPartition) val received: List[CommittableOffsetBatch] = CommittableOffsetBatch.mergeByCommitCallback(offsets) received.foreach { batch => partitions should contain allElementsOf batch.offsets.keys } received.size should be <= 4 } } test("merge by commit callback for multiple consumers") { withRunningKafka { val count = 10000 val topicName = "monix-kafka-merge-by-commit" val producerCfg = KafkaProducerConfig.default.copy( bootstrapServers = List("127.0.0.1:6001"), clientId = "monix-kafka-1-0-producer-test" ) val producer = KafkaProducerSink[String, String](producerCfg, io) val pushT = Observable .range(0, count) .map(msg => new ProducerRecord(topicName, "obs", msg.toString)) .bufferIntrospective(1024) .consumeWith(producer) val listT = Observable .range(0, 4) .mergeMap(i => createConsumer(i.toInt, topicName).take(500)) .bufferTumbling(2000) .map(CommittableOffsetBatch.mergeByCommitCallback) .map { offsetBatches => assert(offsetBatches.length == 4) } .completedL Await.result(Task.parZip2(listT, pushT).runToFuture, 60.seconds) } } private def createConsumer(i: Int, topicName: String): Observable[CommittableOffset] = { val cfg = KafkaConsumerConfig.default.copy( bootstrapServers = List("127.0.0.1:6001"), groupId = s"kafka-tests-$i", autoOffsetReset = AutoOffsetReset.Earliest ) KafkaConsumerObservable .manualCommit[String, String](cfg, List(topicName)) .executeOn(io) .map(_.committableOffset) } }
Example 23
Source File: PluginFrontendSpec.scala From protoc-bridge with Apache License 2.0 | 5 votes |
package protocbridge.frontend import java.io.ByteArrayInputStream import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class PluginFrontendSpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { def expected(error: String) = CodeGeneratorResponse.newBuilder().setError(error).build() def actual(error: String) = CodeGeneratorResponse.parseFrom( PluginFrontend.createCodeGeneratorResponseWithError(error) ) "createCodeGeneratorResponseWithError" should "create valid objects" in { actual("") must be(expected("")) actual("foo") must be(expected("foo")) actual("\u2035") must be(expected("\u2035")) actual("a" * 128) must be(expected("a" * 128)) actual("a" * 256) must be(expected("a" * 256)) actual("\u3714\u3715" * 256) must be(expected("\u3714\u3715" * 256)) actual("abc" * 1000) must be(expected("abc" * 1000)) forAll(MinSuccessful(1000)) { s: String => actual(s) must be(expected(s)) } } "readInputStreamToByteArray" should "read the input stream to a byte array" in { def readInput(bs: Array[Byte]) = PluginFrontend.readInputStreamToByteArray(new ByteArrayInputStream(bs)) readInput(Array.empty) must be(Array()) readInput(Array[Byte](1, 2, 3, 4)) must be(Array(1, 2, 3, 4)) val special = Array.tabulate[Byte](10000) { n => (n % 37).toByte } readInput(special) must be(special) } }
Example 24
Source File: EscapingTests.scala From circe-yaml with Apache License 2.0 | 5 votes |
package io.circe.yaml import io.circe.Encoder import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.util.{ Success, Try } import org.scalatest.matchers.should.Matchers class EscapingTests extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { import io.circe.syntax._ import io.circe.yaml.Printer.spaces2.pretty import io.circe.yaml.parser.parse // according to the YAML spec (section 5.1: character set) def isPrintable(c: Char): Boolean = ('\t' == c) || ('\n' == c) || ('\r' == c) || (' ' <= c && c <= '~') || ('\u0085' == c) || ('\u00a0' <= c && c <= '\ud7ff') || ('\ue000' <= c && c <= '\ufffd') def test1(c: Char): Unit = { val r = "'\\u%04X'".format(c.toInt) def repr[A](a: A): (String, A) = (r, a) val json = c.toString.asJson val s = pretty(json) if (s.contains(c)) repr(isPrintable(c)) shouldBe repr(true) else () // we do not enforce that printable chars are never escaped repr(s.forall(isPrintable)) shouldBe repr(true) repr(Try(parse(s))) shouldBe repr(Success(Right(json))) } "Escaping" should "properly escape JSON string values (all chars)" in { // exhaustive test: 65k test cases (Char.MinValue to Char.MaxValue).map(_.toChar).foreach(test1) } def test2(s0: String): Unit = { val json = s0.asJson val s1 = pretty(json) s1.forall(isPrintable) parse(s1) shouldBe Right(json) } it should "properly escape JSON string values" in { forAll { (s0: String) => test2(s0) } } def test3(c: Char): Unit = { val m = Map(c.toString -> c.toInt) val o = Encoder[Map[String, Int]].apply(m) parser.parse(printer.print(o)).right.flatMap(_.as[Map[String, Int]]) shouldBe Right(m) } it should "properly escape JSON object keys" in { // exhaustive test: 65k test cases (Char.MinValue to Char.MaxValue).map(_.toChar).foreach(test3) } }
Example 25
Source File: PatchSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.pr import scala.io.Source import org.scalatest.EitherValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class PatchSpec extends AnyFlatSpec with Matchers with EitherValues with ScalaCheckDrivenPropertyChecks { def patch(path: String): String = Source .fromResource(path) .getLines() .mkString("\n") it should "fail to parse an invalid patch" in { forAll((s: String) => Patch.parse(s) shouldBe Left(PatchError(s))) } it should "parse successfully a patch with additions only" in { val expected: Map[FileLine, PatchLine] = (69 to 84).zipWithIndex.map { case (fileLine, index) => (FileLine(fileLine), PatchLine(index + 1)) }.toMap Patch.parse(patch("patches/add.patch")).right.value shouldBe expected } it should "parse successfully a patch with deletions only" in { val expected: Map[FileLine, PatchLine] = List( List(26 -> 1, 27 -> 2, 28 -> 3, 29 -> 6, 30 -> 7, 31 -> 8), List(43 -> 10, 44 -> 11, 45 -> 12, 46 -> 15, 47 -> 16, 48 -> 20, 49 -> 21, 50 -> 22) ).flatten.map { case (k, v) => FileLine(k) -> PatchLine(v) }.toMap Patch.parse(patch("patches/del.patch")).right.value shouldBe expected } it should "parse successfully a patch with additions, deletions and modifications" in { val expected: Map[FileLine, PatchLine] = List( (43 to 50).zipWithIndex.map(a => (a._1, a._2 + 1)), List(60 -> 10, 61 -> 11, 62 -> 12, 63 -> 15, 64 -> 16, 65 -> 17), List(77 -> 19, 78 -> 20, 79 -> 21, 80 -> 23, 81 -> 24, 82 -> 25, 83 -> 26) ).flatten.map { case (k, v) => FileLine(k) -> PatchLine(v) }.toMap Patch.parse(patch("patches/add-del-mod.patch")).right.value shouldBe expected } }
Example 26
Source File: ScalastyleRulesReposotorySpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.metadata package scalastyle import cats.data.Chain import cats.data.NonEmptyChain import enumeratum.scalacheck._ import org.scalacheck.Prop._ import org.scalacheck.Prop._ import org.scalacheck.ScalacheckShapeless._ import org.scalacheck._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.Checkers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class ScalastyleRulesRepositorySpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks with Checkers { implicit def chainArbOf[T](implicit a: Arbitrary[T]): Arbitrary[Chain[T]] = Arbitrary(Gen.listOf[T](a.arbitrary).map(Chain.apply)) def nonEmptyChainOf[T](implicit a: Arbitrary[T]): Gen[Chain[T]] = Gen.nonEmptyListOf[T](a.arbitrary).map(Chain.apply) it should "not create an additional rule from a non-template rule" in { forAll { rule: Rule => val extraParam = ScalastyleRulesRepository.extraParam(rule.key) val expected = rule.copy( template = false, params = Chain(extraParam) ) ScalastyleRulesRepository.fromTemplate(rule.copy(params = Chain.empty)) shouldBe NonEmptyChain.one( expected ) } } it should "not create an additional rule if the instance is blacklisted" in { check( forAllNoShrink( Arbitrary.arbitrary[Rule], nonEmptyChainOf[Param], Gen.oneOf(ScalastyleRulesRepository.SkipTemplateInstances.toList) ) { (rule, params, className) => val newRule = rule.copy(key = className, params = params) val extraParam = ScalastyleRulesRepository.extraParam(newRule.key) val expected = newRule.copy( key = className + "-template", template = true, params = params :+ extraParam ) ScalastyleRulesRepository.fromTemplate(newRule) === NonEmptyChain.one(expected) } ) } it should "create an additional rule for templates" in { check( forAllNoShrink( Arbitrary.arbitrary[Rule], nonEmptyChainOf[Param] ) { (rule, params) => val newRule = rule.copy(params = params) val extraParam = ScalastyleRulesRepository.extraParam(newRule.key) val instance = newRule.copy( template = false, params = params :+ extraParam ) val template = instance.copy( key = instance.key + "-template", template = true ) ScalastyleRulesRepository.fromTemplate(newRule) === NonEmptyChain(template, instance) } ) } it should "create an additional param with scalastyle class name" in { val expected = Param( name = "ruleClass", typ = ParamType.String, description = "Scalastyle's rule (checker) class name.", default = "scalastyle.class.name.test" ) ScalastyleRulesRepository.extraParam("scalastyle.class.name.test") shouldBe expected } }
Example 27
Source File: AtomicSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package tests import java.util.UUID import org.scalatest.Inside import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import cats.implicits._ import laws.MyUUID import laws.TestArbInstances.arbUuid import laws.TestInstances.atomic._ import laws.TestTypes.{ CaseClass, Whatever } class AtomicSpec extends BaseSpec with ScalaCheckDrivenPropertyChecks with Inside { val atomic = Atomic[MyUUID] val whatever = Atomic[Whatever.type] "Automatic Model derivation" in { atomic.description should === ("MyUUID") atomic.uuid should === (uuid"85a168db-6ce3-47e7-b8aa-e45aa075d523") } "equals + hashCode" in { checkEqHash(atomic, atomic) checkNotEqHash(atomic, whatever) checkNotEqHash(atomic, Atomic[String]) } "Serializable" in { checkSer(atomic) checkSer(whatever) } "stringRepr/fromString and binaryRepr/fromBinary" in { forAll { u: MyUUID => roundtripStr(u)(atomic) should === (u) roundtripBin(u)(atomic) should === (u) } } "custom Atomic has higher priority than built-in" in { import laws.TestInstances.atomic.bad._ Model.Atom.atom[Int].uuid should === (laws.TestInstances.atomic.bad.atomicInt.uuid) } "have higher priority than generic Reified" in { // derived instance: val r1 = Reified[CaseClass] // define an atomic: val constUuid = uuid"3ba1f17e-c0cd-4b17-8cca-771e90b60498" val r2 = { object ACC extends Atomic[CaseClass] with Atomic.FallbackBinary[CaseClass] { def description: String = "CaseClass" def fromString(s: String): Either[Atomic.Error, CaseClass] = { try { Either.right(CaseClass(s.toLong)) } catch { case ex: IllegalArgumentException => Either.left(Atomic.Error(ex.getMessage)) } } def stringRepr(a: CaseClass): String = a.n.toString val uuid: UUID = constUuid } implicit val atomicCaseClass: Atomic[CaseClass] = ACC // now this should take priority over the derived instance: Reified[CaseClass] } r1.model should !== (r2.model) inside (r1.model) { case _: core.Model.Atom => fail("not expected an Atom") case _ => // OK } inside (r2.model) { case a: core.Model.Atom => a.uuid should === (constUuid) } } }
Example 28
Source File: CanonicalReprSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package tests import cats.Order import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import core.CanonicalRepr import laws.TestArbInstances.{ arbModel, arbCanonicalRepr, arbSymbol } import laws.TestArbInstances.forTestData.arbDefsAdt1 import laws.TestTypes.adts.defs.Adt1 class CanonicalReprSpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { val ord = Order[CanonicalRepr] "fold-unfold" should "be an identity" in { forAll { x: Int => foldUnfold(x) should === (x) } forAll { x: String => foldUnfold(x) should === (x) } forAll { x: Model => foldUnfold(x) should === (x) } forAll { x: Adt1 => foldUnfold(x) should === (x) } } def foldUnfold[A](a: A)(implicit r: Reified[A]): A = CanonicalRepr.roundtrip(a)(r) "Order[CanonicalRepr]" should "be consistent with .equals" in { forAll { (x: CanonicalRepr, y: CanonicalRepr) => if (ord.eqv(x, y)) { x should === (y) } else { x should !== (y) } } } "product" should "create correct HCons/HNil" in { import CanonicalRepr.{ HCons, HNil } val act = CanonicalRepr.product( 'a -> CanonicalRepr.Atom("1"), 'b -> CanonicalRepr.Atom("2"), 'c -> CanonicalRepr.Atom("3") ) val exp = HCons( 'a, CanonicalRepr.Atom("1"), HCons( 'b, CanonicalRepr.Atom("2"), HCons( 'c, CanonicalRepr.Atom("3"), HNil ) ) ) act should === (exp) CanonicalRepr.product() should === (HNil) } }
Example 29
Source File: DTCSuite.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.tests import java.time.temporal.ChronoField import java.time.temporal.ChronoUnit._ import java.time.{Duration, LocalDate, LocalTime} import dtc.TimeZoneId import org.scalacheck.{Arbitrary, Gen} import org.scalatest.funspec.AnyFunSpecLike import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.typelevel.discipline.scalatest.FunSpecDiscipline trait DTCSuite extends AnyFunSpecLike with Matchers with ScalaCheckDrivenPropertyChecks with FunSpecDiscipline { override implicit val generatorDrivenConfig: PropertyCheckConfiguration = PropertyCheckConfiguration( minSuccessful = 100 ) private val nanoOfDayRange = ChronoField.NANO_OF_DAY.range() val genLocalTime: Gen[LocalTime] = Gen.choose(nanoOfDayRange.getMinimum, nanoOfDayRange.getMaximum).map(LocalTime.ofNanoOfDay) implicit val arbLocalTime: Arbitrary[LocalTime] = Arbitrary(genLocalTime) val genDuration: Gen[Duration] = Gen.choose(Long.MinValue / 1000, Long.MaxValue / 1000) .map(l => Duration.of(l, MILLIS)) implicit val arbDuration = Arbitrary(genDuration) def genDateTimeFromSameOffsetPeriod(period: SameZoneOffsetPeriod): Gen[(LocalDate, LocalTime, TimeZoneId)] = for { date <- Gen.choose(period.startDate.toEpochDay + 1L, period.endDate.toEpochDay - 1L).map(LocalDate.ofEpochDay) timeBounds <- Gen.const( if (date == period.startDate && date == period.endDate) (period.startTime, period.endTime) else if (date == period.startDate) (period.startTime, LocalTime.MAX) else if (date == period.endDate) (LocalTime.MAX, period.endTime) else (LocalTime.MIN, LocalTime.MAX) ) time <- Gen.choose(timeBounds._1.toNanoOfDay, timeBounds._2.toNanoOfDay).map(LocalTime.ofNanoOfDay) } yield (date, time, period.zone) }
Example 30
Source File: NumericSpec.scala From finagle-postgres with Apache License 2.0 | 5 votes |
package com.twitter.finagle.postgres.integration import com.twitter.finagle.Postgres import com.twitter.finagle.postgres._ import com.twitter.util.{Await, Future} import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class NumericSpec extends Spec with ScalaCheckDrivenPropertyChecks { for { hostPort <- sys.env.get("PG_HOST_PORT") user <- sys.env.get("PG_USER") password = sys.env.get("PG_PASSWORD") dbname <- sys.env.get("PG_DBNAME") useSsl = sys.env.getOrElse("USE_PG_SSL", "0") == "1" } yield { val binaryClient = Postgres.Client() .database(dbname) .withCredentials(user, password) .withBinaryParams(true) .withBinaryResults(true) .newRichClient(hostPort) val textClient = Postgres.Client() .database(dbname) .withCredentials(user, password) .withBinaryParams(false) .withBinaryResults(false) .newRichClient(hostPort) Await.result((textClient.query( """ |DROP TABLE IF EXISTS numeric_test; |CREATE TABLE numeric_test(d DECIMAL NOT NULL); """.stripMargin))) def rowsOf(qr: QueryResponse): Future[Seq[Row]] = qr match { case OK(_) => Future.value(Seq.empty) case ResultSet(rs) => rs.toSeq } def testBinaryEncode(in: BigDecimal) = Await.result { for { _ <- binaryClient.execute("DELETE FROM numeric_test") _ <- binaryClient.prepareAndExecute("INSERT INTO numeric_test VALUES($1)", Param(in)) r <- textClient.query("SELECT * FROM numeric_test") rows <- rowsOf(r) } yield rows.map(_.get[BigDecimal](0)) must equal(Seq(in)) } def testBinaryDecode(in: BigDecimal) = Await.result { for { _ <- textClient.execute("DELETE FROM numeric_test") _ <- textClient.prepareAndExecute("INSERT INTO numeric_test VALUES($1)", Param(in)) r <- binaryClient.query("SELECT * FROM numeric_test") rows <- rowsOf(r) } yield rows.map(_.get[BigDecimal](0)) must equal(Seq(in)) } "Binary client" should { "encode decimal agree with text client" in forAll { in: BigDecimal => testBinaryEncode(in) } "decode decimal agree with text client" in forAll { in: BigDecimal => testBinaryDecode(in) } } } }
Example 31
Source File: DurationGeneratorsSpec.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.scalacheck import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import play.api.libs.json.scalacheck.DurationGenerators._ import scala.concurrent.duration.{Duration, FiniteDuration} class DurationGeneratorsSpec extends AnyWordSpec with ScalaCheckDrivenPropertyChecks { "Arbitrary[FiniteDuration]" should { "always produce a valid finite value" in { forAll() { (duration: FiniteDuration) => assert(duration.isFinite) } } } "Arbitrary[Duration]" should { "always produce a valid value" in { forAll() { (duration: Duration) => assert(duration ne null) } } } }
Example 32
Source File: CirceSuite.scala From circe-magnolia with Apache License 2.0 | 5 votes |
package io.circe.tests import cats.instances.AllInstances import cats.kernel.Eq import cats.syntax.{AllSyntax, EitherOps} import io.circe.testing.{ArbitraryInstances, EqInstances} import org.scalatest.FlatSpec import org.scalatestplus.scalacheck.{Checkers, ScalaCheckDrivenPropertyChecks} import org.typelevel.discipline.Laws trait CirceSuite extends FlatSpec with ScalaCheckDrivenPropertyChecks with AllInstances with AllSyntax with ArbitraryInstances with Checkers with EqInstances { override def convertToEqualizer[T](left: T): Equalizer[T] = sys.error("Intentionally ambiguous implicit for Equalizer") implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab) def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach { case ((id, prop), 0) => name should s"obey $id" in check(prop) case ((id, prop), _) => it should s"obey $id" in check(prop) } implicit def eqSeq[A: Eq]: Eq[Seq[A]] = Eq.by((_: Seq[A]).toVector)( cats.kernel.instances.vector.catsKernelStdEqForVector[A] ) }
Example 33
Source File: BumpOrderingSpec.scala From sbt-autoversion with Apache License 2.0 | 5 votes |
package autoversion.model import autoversion.model.BumpOrdering.bumpOrdering import org.scalacheck.Gen import org.scalatest.{FlatSpec, Matchers} import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import sbtrelease.Version.Bump class BumpOrderingSpec extends FlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { override implicit val generatorDrivenConfig = PropertyCheckConfiguration(minSuccessful = 30) private val bumpGen: Gen[Bump] = Gen.oneOf(Bump.Major, Bump.Minor, Bump.Bugfix) private val bumpListGen = Gen.nonEmptyListOf(bumpGen) it should "always prioritize a major bump" in { forAll(bumpListGen) { bumps => if (bumps.contains(Bump.Major)) { bumps.max shouldBe Bump.Major } } } it should "prioritize a minor bump if there is no major bump" in { forAll(bumpListGen) { bumps => if (!bumps.contains(Bump.Major) && bumps.contains(Bump.Minor)) { bumps.max shouldBe Bump.Minor } } } it should "prioritize a bugfix bump if there is no other kinds of bump" in { forAll(bumpListGen) { bumps => if (bumps.forall(_ == Bump.Bugfix)) { bumps.max shouldBe Bump.Bugfix } } } }
Example 34
Source File: ResponseSpec.scala From scredis with Apache License 2.0 | 5 votes |
package scredis.protocol import java.nio.ByteBuffer import org.scalatest._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scredis.{ClusterSlotRange, ClusterSlotRangeNodeInfo, Server} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class ResponseSpec extends AnyWordSpec with ScalaCheckDrivenPropertyChecks with Inside with GivenWhenThen with BeforeAndAfterAll with Matchers { "ArrayResponse" when { "parsedAsClusterSlotsResponse" should { "correctly decode an example" in { val bytes = "*3\r\n*4\r\n:5461\r\n:10922\r\n*2\r\n$9\r\n127.0.0.1\r\n:7002\r\n*2\r\n$9\r\n127.0.0.1\r\n:7004\r\n*4\r\n:0\r\n:5460\r\n*2\r\n$9\r\n127.0.0.1\r\n:7000\r\n*2\r\n$9\r\n127.0.0.1\r\n:7003\r\n*4\r\n:10923\r\n:16383\r\n*2\r\n$9\r\n127.0.0.1\r\n:7001\r\n*2\r\n$9\r\n127.0.0.1\r\n:7005\r\n".getBytes(Protocol.Encoding) val response = Protocol.decode(ByteBuffer.wrap(bytes)).asInstanceOf[ArrayResponse] val parsed = response.parsedAsClusterSlotsResponse[Vector] println(parsed) parsed should have size (3) parsed.head should be (ClusterSlotRange((5461,10922), ClusterSlotRangeNodeInfo(Server("127.0.0.1",7002),None), List(ClusterSlotRangeNodeInfo(Server("127.0.0.1",7004),None)))) } } } }
Example 35
Source File: RequestSpec.scala From scredis with Apache License 2.0 | 5 votes |
package scredis.protocol.requests import org.scalatest._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scredis.{ClusterNode, Server} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class RequestSpec extends AnyWordSpec with ScalaCheckDrivenPropertyChecks with Inside with GivenWhenThen with BeforeAndAfterAll with Matchers { "bla" should { "decode example" in { val example = """389afe686935b70115e1efd4f29df552569340a2 127.0.0.1:7004 slave 8d7ef440da8196d56150313f86c4b0be90aa9501 0 1429605082642 5 connected |623f66a717d77220a720a325d1a72ead108794e4 127.0.0.1:7003 slave 2593da8ffa32710544119ca8cb42a88c566589d3 0 1429605082141 4 connected |8d7ef440da8196d56150313f86c4b0be90aa9501 127.0.0.1:7002 master - 0 1429605081639 3 connected 5461-10922 |2593da8ffa32710544119ca8cb42a88c566589d3 127.0.0.1:7000 myself,master - 0 0 1 connected 0-5460 22 1024-3333 |789684c5046734068810407e2e9b282c16ca18f2 127.0.0.1:7001 master - 0 1429605080638 2 connected 10923-16383 |bad2c77fd9e8091f2deda8a5289ae8a473d957a8 127.0.0.1:7005 slave 789684c5046734068810407e2e9b282c16ca18f2 0 1429605082642 6 connected |""".stripMargin val res = ClusterRequests.parseClusterNodes(example) res should have length(6) inside (res(3)) { case ClusterNode( "2593da8ffa32710544119ca8cb42a88c566589d3", Server("127.0.0.1",7000), flags, None, 0, 0, 1, true, slots) => flags should contain theSameElementsAs Seq("myself","master") slots should contain theSameElementsAs Seq((0L,5460L),(22L,22L),(1024L,3333L)) case _ => fail() } } } }
Example 36
Source File: ClusterCRC16Spec.scala From scredis with Apache License 2.0 | 5 votes |
package scredis.protocol import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class ClusterCRC16Spec extends AnyWordSpec with Matchers with ScalaCheckDrivenPropertyChecks with TableDrivenPropertyChecks { val examples = Table( ("input", "output"), ("", 0x0), ("123456789", 0x31C3), ("sfger132515", 0xA45C), ("hae9Napahngaikeethievubaibogiech", 0x58CE), ("AAAAAAAAAAAAAAAAAAAAAA", 0x92cd), ("Hello, World!", 0x4FD6) ) "getSlot" should { "yield the same hash for a tag within a string as for the plain tag" in { forAll { (tag: String, left:String, right:String) => whenever(!left.contains("{") && tag.nonEmpty && !tag.contains("}")) { val key = s"$left{$tag}$right" ClusterCRC16.getSlot(key) should be(ClusterCRC16.getSlot(tag)) } } } "solve all examples correctly" in { forAll (examples) { (in:String, out:Int) => ClusterCRC16.getCRC16(in) shouldBe out } } } }
Example 37
Source File: RedisClusterSpec.scala From scredis with Apache License 2.0 | 5 votes |
package scredis import org.scalatest.concurrent.ScalaFutures import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.concurrent.ExecutionContext.Implicits.global import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class RedisClusterSpec extends AnyWordSpec with Matchers with ScalaFutures with ScalaCheckDrivenPropertyChecks { val keys = org.scalacheck.Arbitrary.arbString.arbitrary // we assume there is a local cluster started on ports 7000 - 7005 // see testing.md lazy val cluster = RedisCluster(Server("localhost",7000)) val badSeed1 = Server("localhost",7777) val badSeed2 = Server("localhost",2302) val badSeeds = List(badSeed1, badSeed2, Server("localhost",7003)) "connection to cluster" should { "work for a single valid seed node" in { val info = cluster.clusterInfo().futureValue info("cluster_state") should be ("ok") info("cluster_known_nodes").toInt should be (6) // 6 total nodes info("cluster_size").toInt should be (3) // 3 master nodes } "work when some of the seed nodes are offline" in { val badServers = RedisCluster(badSeeds) val info = badServers.clusterInfo().futureValue info("cluster_state") should be ("ok") info("cluster_known_nodes").toInt should be (6) // 6 total nodes info("cluster_size").toInt should be (3) // 3 master nodes } } "writes to cluster" should { "be readable" in { forAll { (key:String, value: String) => whenever (value.nonEmpty) { val res = for { _ <- cluster.set(key, value) g <- cluster.get(key) } yield g.get res.futureValue should be(value) } } } "be idempotent" in { forAll { (key:String, value: String) => whenever (value.nonEmpty) { val res = for { _ <- cluster.set(key, value) g1 <- cluster.get(key) _ <- cluster.set(key, value) g2 <- cluster.get(key) } yield (g1.get,g2.get) res.futureValue should be(value,value) } } } } // TODO basic test for each supported / unsupported command }
Example 38
Source File: HttpErrorFunctionsSpec.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.http import com.github.ghik.silencer.silent import org.scalacheck.Gen import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.TryValues import org.scalatest.wordspec.AnyWordSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.util.Try @silent("deprecated") class HttpErrorFunctionsSpec extends AnyWordSpec with Matchers with ScalaCheckDrivenPropertyChecks with TableDrivenPropertyChecks with TryValues { "HttpErrorFunctions" should { "return the response if the status code is between 200 and 299" in new HttpErrorFunctions { forAll(Gen.choose(200, 299)) { statusCode: Int => val expectedResponse = HttpResponse(statusCode, "") handleResponse(exampleVerb, exampleUrl)(expectedResponse) should be(expectedResponse) } } "return the correct exception if the status code is 400" in { expectA[BadRequestException](forStatus = 400) } "return the correct exception if the status code is 404" in { expectA[NotFoundException](forStatus = 404) } "return the correct exception for all other status codes" in { forAll(Gen.choose(0, 199))(expectA[Exception](_)) forAll(Gen.choose(400, 499).suchThat(!Seq(400, 404).contains(_)))(expectA[Upstream4xxResponse](_, Some(500))) forAll(Gen.choose(500, 599))(expectA[Upstream5xxResponse](_, Some(502))) forAll(Gen.choose(600, 1000))(expectA[Exception](_)) } } val exampleVerb = "GET" val exampleUrl = "http://example.com/something" val exampleBody = "this is the string body" def expectA[T: Manifest](forStatus: Int, reportStatus: Option[Int] = None): Unit = new HttpErrorFunctions { val e = Try(handleResponse(exampleVerb, exampleUrl)(HttpResponse(forStatus, exampleBody))).failure.exception e should be(a[T]) e.getMessage should (include(exampleUrl) and include(exampleVerb) and include(exampleBody)) reportStatus.map { s => e should have('upstreamResponseCode (forStatus)) e should have('reportAs (s)) } } }
Example 39
Source File: CirceSuite.scala From circe-optics with Apache License 2.0 | 5 votes |
package io.circe.optics import cats.kernel.Eq import cats.instances.AllInstances import cats.syntax.{ AllSyntax, EitherOps } import io.circe.testing.{ ArbitraryInstances, EqInstances } import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.{ Checkers, ScalaCheckDrivenPropertyChecks } import org.typelevel.discipline.Laws import org.typelevel.discipline.scalatest.FlatSpecDiscipline import scala.language.implicitConversions trait CirceSuite extends AnyFlatSpec with FlatSpecDiscipline with ScalaCheckDrivenPropertyChecks with AllInstances with AllSyntax with ArbitraryInstances with EqInstances { override def convertToEqualizer[T](left: T): Equalizer[T] = sys.error("Intentionally ambiguous implicit for Equalizer") implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab) def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach { case ((id, prop), 0) => name should s"obey $id" in Checkers.check(prop) case ((id, prop), _) => it should s"obey $id" in Checkers.check(prop) } def assertEq[A: Eq](expected: A, actual: A): Unit = assert( expected === actual, s"""Expected did not match actual: | |Expected: $expected |Actual: $actual""" ) }
Example 40
Source File: SharedExtensionsPropertyTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import com.avsystem.commons.SharedExtensions._ import org.scalacheck.{Gen, Shrink} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class SharedExtensionsPropertyTest extends AnyFunSuite with Matchers with ScalaCheckDrivenPropertyChecks { implicit def shrinkNonEmpty[C[_] <: Iterable[_], T](implicit base: Shrink[C[T]]): Shrink[C[T]] = Shrink(base.shrink(_).filter(_.nonEmpty)) private val elementGen = Gen.alphaChar private val listGen = Gen.listOf(elementGen) private val listWithElementGen = for { list <- Gen.nonEmptyListOf(elementGen) elem <- Gen.oneOf(list) } yield (list, elem) test("indexOfOpt(elem) should return Opt.Empty if the element does not occur in the list") { forAll(listGen, elementGen) { (elemList, element) => elemList.filterNot(_ == element).indexOfOpt(element) shouldEqual Opt.Empty } } test("indexOfOpt(elem) should not return Opt.Empty when the element occurs in the list") { forAll(listWithElementGen) { case (elemList, elem) => elemList.indexOfOpt(elem) should not equal Opt.Empty } } test("indexOfOpt(elem).getOrElse(-1) should behave identically to indexOf(elem)") { forAll(listGen, elementGen) { (elemList, element) => elemList.indexOf(element) shouldEqual elemList.indexOfOpt(element).getOrElse(-1) } } test("indexWhereOpt(elem).getOrElse(-1) should behave identically to indexWhere(elem)") { forAll(listGen, elementGen) { (elemList, element) => elemList.indexWhere(_ == element) shouldEqual elemList.indexWhereOpt(_ == element).getOrElse(-1) } } }
Example 41
Source File: PropertyTests.scala From cats-stm with Apache License 2.0 | 5 votes |
package io.github.timwspence.cats.stm import cats.effect.{ContextShift, IO, Timer} import cats.instances.list._ import cats.syntax.functor._ import cats.syntax.traverse._ import org.scalacheck._ import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.concurrent.ExecutionContext import scala.util.Random class MaintainsInvariants extends AnyFunSuite with ScalaCheckDrivenPropertyChecks with Matchers { implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global implicit val timer: Timer[IO] = IO.timer(executionContext) implicit val cs: ContextShift[IO] = IO.contextShift(executionContext) val tvarGen: Gen[TVar[Long]] = for { value <- Gen.posNum[Long] } yield TVar.of(value).commit[IO].unsafeRunSync val txnGen: List[TVar[Long]] => Gen[STM[Unit]] = tvars => for { fromIdx <- Gen.choose(0, tvars.length - 1) toIdx <- Gen.choose(0, tvars.length - 1) suchThat (_ != fromIdx) txn <- for { balance <- tvars(fromIdx).get transfer = Math.abs(Random.nextLong()) % balance _ <- tvars(fromIdx).modify(_ - transfer) _ <- tvars(toIdx).modify(_ + transfer) } yield () } yield txn val gen: Gen[(Long, List[TVar[Long]], IO[Unit])] = for { tvars <- Gen.listOfN(50, tvarGen) total = tvars.foldLeft(0L)((acc, tvar) => acc + tvar.value) txns <- Gen.listOf(txnGen(tvars)) commit = txns.traverse(_.commit[IO].start) run = commit.flatMap(l => l.traverse(_.join)).void } yield (total, tvars, run) test("Transactions maintain invariants") { forAll(gen) { g => val total = g._1 val tvars = g._2 val txn = g._3 txn.unsafeRunSync() tvars.map(_.value).sum shouldBe total } } }
Example 42
Source File: Cron4sLawSuite.scala From cron4s with Apache License 2.0 | 4 votes |
package cron4s.testkit import cats.instances.AllInstances import cats.syntax.AllSyntax import cron4s.platform.Platform import org.typelevel.discipline.scalatest.FunSuiteDiscipline import org.scalactic.anyvals.{PosInt, PosZInt} import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import org.scalatest.propspec.AnyPropSpec import org.scalatest.prop.Configuration import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks trait TestSettings extends Configuration { lazy val defaultPropertyCheckConfig: PropertyCheckConfiguration = PropertyCheckConfiguration( minSuccessful = if (Platform.isJvm) PosInt(50) else PosInt(5), minSize = PosZInt(0), sizeRange = if (Platform.isJvm) PosZInt(10) else PosZInt(5), workers = PosInt(1) ) lazy val slowPropertyCheckConfig: PropertyCheckConfiguration = if (Platform.isJvm) defaultPropertyCheckConfig else PropertyCheckConfiguration(minSuccessful = 1, sizeRange = 1) } trait Cron4sLawSuite extends AnyFunSuite with Matchers with ScalaCheckDrivenPropertyChecks with FunSuiteDiscipline with TestSettings with AllInstances with AllSyntax { implicit override val generatorDrivenConfig: PropertyCheckConfiguration = defaultPropertyCheckConfig } trait SlowCron4sLawSuite extends Cron4sLawSuite { implicit override val generatorDrivenConfig: PropertyCheckConfiguration = slowPropertyCheckConfig } abstract class Cron4sPropSpec extends AnyPropSpec with TestSettings { override implicit val generatorDrivenConfig: PropertyCheckConfiguration = defaultPropertyCheckConfig } abstract class SlowCron4sPropSpec extends AnyPropSpec with TestSettings { override implicit val generatorDrivenConfig: PropertyCheckConfiguration = slowPropertyCheckConfig }
Example 43
Source File: T04PropertyBasedTest.scala From big-data-rosetta-code with Apache License 2.0 | 4 votes |
package com.spotify.bdrc.testing import com.google.common.collect.MinMaxPriorityQueue import org.scalacheck.Prop._ import org.scalacheck.{Gen, Properties} import org.scalatest.propspec.AnyPropSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.collection.JavaConverters._ object Utils { def top[T: Ordering](xs: Seq[T], num: Int): Seq[T] = { if (xs.isEmpty) { Seq.empty[T] } else { val size = math.min(num, xs.size) val ord = implicitly[Ordering[T]] MinMaxPriorityQueue .orderedBy(ord.reverse) .expectedSize(size) .maximumSize(size) .create[T](xs.asJava) .asScala .toSeq .sorted(ord.reverse) } } def split(input: String): Seq[String] = input .split("[^a-zA-Z']+") .filter(_.nonEmpty) .map(_.toLowerCase) def cosineSim(v1: Seq[Double], v2: Seq[Double]): Double = { require(v1.length == v2.length) var s1 = 0.0 var s2 = 0.0 var dp = 0.0 var i = 0 while (i < v1.length) { s1 += v1(i) * v1(i) s2 += v2(i) * v2(i) dp += v1(i) * v2(i) i += 1 } dp / math.sqrt(s1 * s2) } } class PropertyBasedTest extends AnyPropSpec with ScalaCheckDrivenPropertyChecks with Matchers { property("top") { forAll { xs: Seq[Long] => Utils.top(xs, 5) shouldBe xs.sorted.reverse.take(5) } } property("split") { forAll { line: String => Utils.split(line).forall(_.matches("[a-z']+")) } } // Generator for List[Double] of 100 doubles between -100.0 and 100.0 val genVector = Gen.listOfN(100, Gen.choose(-100.0, 100.0)) property("cosineSim") { forAll(genVector, genVector) { (v1, v2) => val s1 = Utils.cosineSim(v1, v2) val s2 = Utils.cosineSim(v2, v1) s1 should (be >= -1.0 and be <= 1.0) s1 shouldBe s2 Utils.cosineSim(v1, v1) shouldBe 1.0 Utils.cosineSim(v1, v1.map(-_)) shouldBe -1.0 } } }