org.scalatestplus.scalacheck.ScalaCheckPropertyChecks Scala Examples

The following examples show how to use org.scalatestplus.scalacheck.ScalaCheckPropertyChecks. 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: TimePeriodSpec.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.libs.scala.domain

import gospeak.libs.scala.testingutils.Generators._
import gospeak.libs.testingutils.BaseSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

import scala.concurrent.duration.FiniteDuration

class TimePeriodSpec extends BaseSpec with ScalaCheckPropertyChecks {
  describe("TimePeriod") {
    it("build and transform to FiniteDuration") {
      forAll { v: FiniteDuration =>
        val p = TimePeriod.from(v)
        val r = p.toDuration.get
        r shouldBe v
      }
    }
    it("should parse and serialize to String") {
      forAll { v: TimePeriod =>
        val s = v.value
        val p = TimePeriod.from(s).get
        p shouldBe v
      }
    }
  }
} 
Example 2
Source File: MatchTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import ops._
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class MatchTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("length should return the expected value") {
    def validating(length: Int): MatchDecoder[List[Int]] = MatchDecoder[List[Int]].contramapEncoded { (m: Match) =>
      m.length should be(length)
      m
    }

    forAll(Gen.nonEmptyListOf(Arbitrary.arbitrary[Int])) { (is: List[Int]) =>
      implicit val decoder: MatchDecoder[List[Int]] = validating(is.length)

      val regex = is.map(_ => "(-?\\d+)").mkString(" ").asUnsafeRegex[List[Int]].map(_.fold(e => throw e, identity))
      regex.eval(is.mkString(" ")).next should be(is)
    }
  }

  test("Out of bound groups should generate a NoSuchGroupId") {
    def outOfBounds(i: Int): MatchDecoder[Int] = MatchDecoder.from(_.decode[Int](i))

    forAll(Gen.nonEmptyListOf(Arbitrary.arbitrary[Int]), Arbitrary.arbitrary[Int].suchThat(_ != -1)) { (is, offset) =>
      val index = is.length + 1 + offset

      implicit val decoder: MatchDecoder[Int] = outOfBounds(index)
      val regex                               = is.map(_ => "(-?\\d+)").mkString(" ").asUnsafeRegex[Int]
      regex.eval(is.mkString(" ")).next should be(DecodeResult.noSuchGroupId(index))
    }
  }
} 
Example 3
Source File: CompileResultTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

@SuppressWarnings(Array("org.wartremover.warts.Throw"))
class CompileResultTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("CompileResult.success should return a success") {
    forAll { i: Int =>
      CompileResult.success(i) should be(Right(i))
    }
  }

  test("CompileResult.apply should return a success on 'good' values") {
    forAll { i: Int =>
      CompileResult(i) should be(Right(i))
    }
  }

  test("CompileResult.apply should return a failure on 'bad' values") {
    forAll { e: Exception =>
      CompileResult(throw e) should be(Left(CompileError(e)))
    }
  }
} 
Example 4
Source File: CompilableOpsTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import implicits._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class CompilableOpsTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {

  test("asRegex should succeed for valid regular expressions") {
    "\\d+".asRegex[Int].isRight should be(true)
    "\\d+".asRegex[Int](1).isRight should be(true)

    rx"\\d+".asRegex[Int].isRight should be(true)
    rx"\\d+".asRegex[Int](1).isRight should be(true)

    "\\d+".r.asRegex[Int].isRight should be(true)
    "\\d+".r.asRegex[Int](1).isRight should be(true)
  }

  test("asRegex should fail for invalid regular expressions") {
    "[".asRegex[Int].isLeft should be(true)
    "[".asRegex[Int](1).isLeft should be(true)
  }

  test("asUnsafeRegex should succeed for valid regular expressions") {
    "\\d+".asUnsafeRegex[Int]
    "\\d+".asUnsafeRegex[Int](1)

    rx"\\d+".asUnsafeRegex[Int]
    rx"\\d+".asUnsafeRegex[Int](1)

    "\\d+".r.asUnsafeRegex[Int]
    "\\d+".r.asUnsafeRegex[Int](1)
    ()
  }

  test("asUnsafeRegex should fail for invalid regular expressions") {
    intercept[Exception]("[".asUnsafeRegex[Int])
    intercept[Exception]("[".asUnsafeRegex[Int](1))
    ()
  }

} 
Example 5
Source File: MatchIteratorTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import implicits._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

@SuppressWarnings(Array("org.wartremover.warts.While"))
class MatchIteratorTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  def toMatchIterator(is: List[Int]): Iterator[Int] =
    Regex[Int](rx"-?\d+").eval(is.mkString(" ")).map(_.fold(e => throw e, identity))

  test("MatchIterator should fail when reading more than the maximum number of elements") {
    forAll { is: List[Int] =>
      val it = toMatchIterator(is)
      while(it.hasNext) it.next()

      intercept[NoSuchElementException](it.next)
      ()
    }
  }

  test("MatchIterator should contain the expected number of elements") {
    forAll { is: List[Int] =>
      val it = toMatchIterator(is)
      is.indices.foreach(_ => it.next)
      it.hasNext should be(false)
    }
  }
} 
Example 6
Source File: GroupDecodeTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import laws.discipline.arbitrary._
import ops._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class GroupDecodeTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("Instances created through GroupDecoder.from should behave as expected") {
    forAll { (s: String, f: (Option[String] => DecodeResult[Int])) =>
      implicit val decoder: GroupDecoder[Int] = GroupDecoder.from(f)

      val r = ".*".asUnsafeRegex[Int]
      r.eval(s).next should be(f(Some(s)))
    }
  }

  test("The instance summoning method should behave as expected") {
    forAll { (f: (Option[String] => DecodeResult[Int])) =>
      implicit val decoder: GroupDecoder[Int] = GroupDecoder.from(f)

      decoder should be theSameInstanceAs GroupDecoder[Int]
    }
  }
} 
Example 7
Source File: RegexTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import implicits._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class RegexTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("All matches should be decoded as expected.") {
    forAll { is: List[Int] =>
      val regex = ("-?\\d+").asUnsafeRegex[Int].map(_.fold(e => throw e, identity))
      regex.eval(is.mkString(" ")).toList should be(is)
    }
  }

  test("Invalid regular expressions should not compile") {
    "[".asRegex[Int].isLeft should be(true)
  }

  test("Regexes obtained from a pattern should have that pattern as a toString") {
    val pattern = rx"-?\d+"
    Regex[Int](pattern).toString should be(pattern.toString)
  }
} 
Example 8
Source File: ErrorTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import DecodeError.TypeError
import laws.discipline.arbitrary._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class ErrorTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("CompileErrors should be equal if the underlying errors are the same") {
    forAll { (e1: CompileError, e2: RegexError) =>
      (e1, e2) match {
        case (CompileError(t1), CompileError(t2)) => (e1 == e2) should be(t1 == t2)
        case _                                    => e1 should not be (e2)
      }
    }
  }

  test("CompileErrors should have identical hashCodes if the underlying errors have the same hashCodes") {
    forAll { (e1: CompileError, e2: CompileError) =>
      (e1.hashCode() == e2.hashCode()) should be(e1.message.hashCode == e2.message.hashCode)
    }
  }

  test("TypeErrors should be equal if the underlying errors are the same") {
    forAll { (e1: TypeError, e2: RegexError) =>
      (e1, e2) match {
        case (TypeError(t1), TypeError(t2)) => (e1 == e2) should be(t1 == t2)
        case _                              => e1 should not be (e2)
      }
    }
  }

  test("TypeErrors should have identical hashCodes if the underlying errors have the same hashCodes") {
    forAll { (e1: TypeError, e2: TypeError) =>
      (e1.hashCode() == e2.hashCode()) should be(e1.message.hashCode == e2.message.hashCode)
    }
  }
} 
Example 9
Source File: DecodeResultTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

@SuppressWarnings(Array("org.wartremover.warts.Throw"))
class DecodeResultTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("DecodeResult.success should return a success") {
    forAll { i: Int =>
      DecodeResult.success(i) should be(Right(i))
    }
  }

  test("DecodeResult.apply should return a success on 'good' values") {
    forAll { i: Int =>
      DecodeResult(i) should be(Right(i))
    }
  }

  test("DecodeResult.apply should return a failure on 'bad' values") {
    forAll { e: Exception =>
      DecodeResult(throw e) should be(Left(DecodeError.TypeError(e)))
    }
  }

  test("DecodeResult.typeError should return a failure") {
    forAll { e: Exception =>
      DecodeResult.typeError(e) should be(Left(DecodeError.TypeError(e)))

      DecodeResult.typeError(e.getMessage) match {
        case Left(DecodeError.TypeError(m)) => m should be(e.getMessage)
        case a                              => fail(s"$a was not a type error")
      }
    }
  }

  test("DecodeResult.noSuchGroupId should return a failure ") {
    forAll { i: Int =>
      DecodeResult.noSuchGroupId(i) should be(Left(DecodeError.NoSuchGroupId(i)))
    }
  }
} 
Example 10
Source File: IOTest.scala    From cats-effect-testing   with Apache License 2.0 5 votes vote down vote up
package cats.effect.testing.scalatest.scalacheck

import cats.data.EitherT
import cats.effect.testing.scalatest.AsyncIOSpec
import cats.effect.{IO, Sync}
import org.scalatest.matchers.should.Matchers
import org.scalatest.freespec.AsyncFreeSpec
import org.scalatestplus.scalacheck.{CheckerAsserting, ScalaCheckPropertyChecks}

class IOTest extends AsyncFreeSpec with AsyncIOSpec with Matchers with ScalaCheckPropertyChecks {

  "Scalacheck IO assertions" - {

    "Assert success" in {
      forAll { (l1: List[Int], l2: List[Int]) =>
        IO.delay(l1.size + l2.size shouldBe (l1 ::: l2).size)
      }
    }

    "Assert exception" in {
      val check: IO[Unit] = forAll { (l1: List[Int], l2: List[Int]) =>
        IO.delay(l1.size + l2.size shouldBe -1)
      }

      check.assertThrows[Exception]
    }

    implicit def ioCheckingAsserting[A]: CheckerAsserting[IO[A]] { type Result = IO[Unit] } =
      new EffectCheckerAsserting

  }

  "Scalacheck EitherT[IO, Throwable, A] assertions" - {

    type Eff[A] = EitherT[IO, Throwable, A]

    "Assert success" in {
      val check = forAll { (l1: List[Int], l2: List[Int]) =>
        Sync[Eff].delay(l1.size + l2.size shouldBe (l1 ::: l2).size)
      }

      check.leftSemiflatMap[Unit](IO.raiseError).merge.assertNoException
    }

    "Assert exception" in {
      val check = forAll { (l1: List[Int], l2: List[Int]) =>
        Sync[Eff].delay(l1.size + l2.size shouldBe -1)
      }

      check.leftSemiflatMap[Unit](IO.raiseError[Unit]).merge.assertThrows[Exception]
    }

    implicit def checkingAsserting[A]: CheckerAsserting[Eff[A]] { type Result = Eff[Unit] } =
      new EffectCheckerAsserting
  }

} 
Example 11
Source File: CryptoSpec.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.libs.scala

import gospeak.libs.scala.Crypto.{AesEncrypted, AesSecretKey}
import gospeak.libs.testingutils.BaseSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class CryptoSpec extends BaseSpec with ScalaCheckPropertyChecks {
  describe("Crypto") {
    describe("base64") {
      it("should encode and decode base64") {
        forAll { v: String =>
          val base64 = Crypto.base64Encode(v)
          Crypto.base64Decode(base64).get shouldBe v
        }
      }
      it("should encode 'toto'") {
        Crypto.base64Encode("toto") shouldBe "dG90bw=="
      }
    }
    describe("md5") {
      it("should compute a md5") {
        Crypto.md5("toto") shouldBe "f71dbe52628a3f83a77ab494817525c6"
      }
    }
    describe("sha1") {
      it("should compute a sha1") {
        Crypto.sha1("toto") shouldBe "0b9c2625dc21ef05f6ad4ddf47c5f203837aa32c"
      }
    }
    describe("aes") {
      it("should generate random numbers") {
        val r1 = Crypto.secureRandom().get
        val r2 = Crypto.secureRandom().get
        r1 should not be r2
      }
      it("should encrypt and decrypt a value") {
        forAll { v: String =>
          val key = Crypto.aesGenerateKey().get
          val encrypted = Crypto.aesEncrypt(v, key).get
          Crypto.aesDecrypt(encrypted, key).get shouldBe v
        }
      }
      it("should decrypt 'toto'") {
        val key = AesSecretKey("kid1+XM7ayXTsw+1Q2k67g==")
        Crypto.aesDecrypt(AesEncrypted("r16mW6H0Lchn4OJZ2cDunumBJ+E="), key).get shouldBe "toto"
        Crypto.aesDecrypt(AesEncrypted("bTWtr9kAmDpCkVX81hNv5tkw1bI="), key).get shouldBe "toto"
      }
    }
  }
} 
Example 12
Source File: StringOpsTests.scala    From kantan.regex   with Apache License 2.0 5 votes vote down vote up
package kantan.regex

import implicits._
import kantan.codecs.laws._
import laws.discipline.arbitrary._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class StringOpsTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {

  test("evalRegex should succeed for valid regular expressions") {

    forAll { value: LegalString[Int] =>
      value.encoded.evalRegex[Int](rx"-?\d+").toList should be(List(DecodeResult.success(value.decoded)))
      value.encoded.evalRegex[Int](rx"-?\d+", 0).toList should be(List(DecodeResult.success(value.decoded)))
      value.encoded.evalRegex("-?\\d+".asUnsafeRegex[Int]).toList should be(List(DecodeResult.success(value.decoded)))
    }

    forAll { value: IllegalString[Int] =>
      every(value.encoded.evalRegex[Int](rx"-?\d+").toList) should matchPattern { case Left(_)              => }
      every(value.encoded.evalRegex[Int](rx"-?\d+", 0).toList) should matchPattern { case Left(_)           => }
      every(value.encoded.evalRegex("-?\\d+".asUnsafeRegex[Int]).toList) should matchPattern { case Left(_) => }
    }

  }

  test("unsafeEvalRegex should succeed for valid regular expressions and valid matches") {
    forAll { value: LegalString[Int] =>
      value.encoded.unsafeEvalRegex[Int](rx"-?\d+").toList should be(List(value.decoded))
      value.encoded.unsafeEvalRegex[Int](rx"-?\d+", 0).toList should be(List(value.decoded))
    }
  }

} 
Example 13
Source File: AuthQueryTypeCheckSpec.scala    From scala-pet-store   with Apache License 2.0 5 votes vote down vote up
package io.github.pauljamescleary.petstore
package infrastructure.repository.doobie

import cats.effect.IO
import doobie.scalatest.IOChecker
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import PetStoreArbitraries._
import tsec.mac.jca.HMACSHA256
import tsec.authentication.AugmentedJWT
import tsec.common.SecureRandomId
import org.scalatest.matchers.should.Matchers

class AuthQueryTypeCheckSpec
    extends AnyFunSuite
    with Matchers
    with ScalaCheckPropertyChecks
    with IOChecker {
  override def transactor: doobie.Transactor[IO] = testTransactor

  import AuthSQL._

  test("Typecheck auth queries") {
    forAll { jwt: AugmentedJWT[HMACSHA256, Long] => check(insert(jwt)) }
    forAll { jwt: AugmentedJWT[HMACSHA256, Long] => check(update(jwt)) }
    forAll { id: SecureRandomId => check(select(id)) }
    forAll { id: SecureRandomId => check(delete(id)) }
  }
} 
Example 14
Source File: OrderEndpointsSpec.scala    From scala-pet-store   with Apache License 2.0 5 votes vote down vote up
package io.github.pauljamescleary.petstore
package infrastructure.endpoint

import domain.orders._
import infrastructure.repository.inmemory._
import cats.effect._
import io.circe._
import io.circe.generic.semiauto._
import org.http4s._
import org.http4s.implicits._
import org.http4s.dsl._
import org.http4s.circe._
import org.http4s.client.dsl.Http4sClientDsl
import org.http4s.server.Router
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import tsec.mac.jca.HMACSHA256
import org.scalatest.matchers.should.Matchers

class OrderEndpointsSpec
    extends AnyFunSuite
    with Matchers
    with ScalaCheckPropertyChecks
    with PetStoreArbitraries
    with Http4sDsl[IO]
    with Http4sClientDsl[IO] {
  implicit val statusDec: EntityDecoder[IO, OrderStatus] = jsonOf
  implicit val statusEnc: EntityEncoder[IO, OrderStatus] = jsonEncoderOf

  implicit val orderEncoder: Encoder[Order] = deriveEncoder
  implicit val orderEnc: EntityEncoder[IO, Order] = jsonEncoderOf
  implicit val orderDecoder: Decoder[Order] = deriveDecoder
  implicit val orderDec: EntityDecoder[IO, Order] = jsonOf

  def getTestResources(): (AuthTest[IO], HttpApp[IO]) = {
    val userRepo = UserRepositoryInMemoryInterpreter[IO]()
    val auth = new AuthTest[IO](userRepo)
    val orderService = OrderService(OrderRepositoryInMemoryInterpreter[IO]())
    val orderEndpoint =
      OrderEndpoints.endpoints[IO, HMACSHA256](orderService, auth.securedRqHandler)
    val orderRoutes = Router(("/orders", orderEndpoint)).orNotFound
    (auth, orderRoutes)
  }

  test("place and get order") {
    val (auth, orderRoutes) = getTestResources()

    forAll { (order: Order, user: AdminUser) =>
      (for {
        createRq <- POST(order, uri"/orders")
        createRqAuth <- auth.embedToken(user.value, createRq)
        createResp <- orderRoutes.run(createRqAuth)
        orderResp <- createResp.as[Order]
        getOrderRq <- GET(Uri.unsafeFromString(s"/orders/${orderResp.id.get}"))
        getOrderRqAuth <- auth.embedToken(user.value, getOrderRq)
        getOrderResp <- orderRoutes.run(getOrderRqAuth)
        orderResp2 <- getOrderResp.as[Order]
      } yield {
        createResp.status shouldEqual Ok
        orderResp.petId shouldBe order.petId
        getOrderResp.status shouldEqual Ok
        orderResp2.userId shouldBe defined
      }).unsafeRunSync
    }
  }

  test("user roles") {
    val (auth, orderRoutes) = getTestResources()

    forAll { user: CustomerUser =>
      (for {
        deleteRq <- DELETE(Uri.unsafeFromString(s"/orders/1"))
          .flatMap(auth.embedToken(user.value, _))
        deleteResp <- orderRoutes.run(deleteRq)
      } yield {
        deleteResp.status shouldEqual Unauthorized
      }).unsafeRunSync
    }

    forAll { user: AdminUser =>
      (for {
        deleteRq <- DELETE(Uri.unsafeFromString(s"/orders/1"))
          .flatMap(auth.embedToken(user.value, _))
        deleteResp <- orderRoutes.run(deleteRq)
      } yield {
        deleteResp.status shouldEqual Ok
      }).unsafeRunSync
    }
  }
} 
Example 15
Source File: RequestsSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.account.KeyPair
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.transaction.transfer.TransferTransaction
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.{FreeSpec, Matchers, OptionValues}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import play.api.libs.json._

class RequestsSpec extends FreeSpec with Matchers with OptionValues with ScalaCheckPropertyChecks with TransactionGen with NoShrink {
  private def transferRequestGen(version: Int): Gen[(KeyPair, JsObject)] =
    (for {
      sender    <- accountGen
      recipient <- accountGen
      proofs    <- proofsGen
    } yield (
      sender,
      Json.obj(
        "type"            -> 4,
        "version"         -> version,
        "senderPublicKey" -> sender.publicKey.toString,
        "assetId"         -> JsNull,
        "attachment"      -> "",
        "feeAssetId"      -> JsNull,
        "timestamp"       -> System.currentTimeMillis(),
        "fee"             -> 100000,
        "amount"          -> 10000,
        "recipient"       -> recipient.publicKey.toAddress.stringRepr,
        "proofs"          -> JsArray(proofs.proofs.map(p => JsString(p.toString)))
      )
    )).label(s"Transfer Request v$version")

  "TransferRequest" - {
    "accepts proofs for version >= 2" in {
      TransferTransaction.supportedVersions.filter(_ >= 2).foreach { version =>
        forAll(transferRequestGen(version)) {
          case (sender, json) =>
            val request = json.as[TransferRequest]
            val tx      = request.toTxFrom(sender.publicKey).explicitGet()

            request.proofs.value should be(tx.proofs)
        }
      }

    }
  }
} 
Example 16
Source File: FeatureProviderTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.features

import com.wavesplatform.block.Block
import com.wavesplatform.settings.{BlockchainSettings, FunctionalitySettings, GenesisSettings, RewardsSettings}
import com.wavesplatform.state.Blockchain
import org.scalacheck.Gen
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class FeatureProviderTest extends FlatSpec with Matchers with ScalaCheckPropertyChecks with MockFactory {
  "blockVersionAt" should "return valid version" in {
    val fs                 = FunctionalitySettings.MAINNET
    val v3ActivationHeight = fs.blockVersion3AfterHeight
    val v4ActivationHeight = 1740000
    val v5ActivationHeight = 2000000

    val genesisAt = 1
    val plainAt   = (2 to fs.blockVersion3AfterHeight + 1).toSet
    val ngAt      = (v3ActivationHeight + 2 to v4ActivationHeight).toSet
    val rewardAt  = (v4ActivationHeight + 1 until v5ActivationHeight).toSet

    val features = Map(
      BlockchainFeatures.BlockReward.id -> v4ActivationHeight,
      BlockchainFeatures.BlockV5.id     -> v5ActivationHeight
    )

    val blockchain = mock[Blockchain]
    (blockchain.activatedFeatures _).expects().anyNumberOfTimes().returning(features)
    (blockchain.settings _).expects().anyNumberOfTimes().returning(BlockchainSettings('W', fs, GenesisSettings.MAINNET, RewardsSettings.MAINNET))

    forAll(Gen.choose(1, v5ActivationHeight * 2)) { h =>
      if (h == genesisAt) blockchain.blockVersionAt(h) shouldBe Block.GenesisBlockVersion
      else if (plainAt contains h) blockchain.blockVersionAt(h) shouldBe Block.PlainBlockVersion
      else if (ngAt contains h) blockchain.blockVersionAt(h) shouldBe Block.NgBlockVersion
      else if (rewardAt contains h) blockchain.blockVersionAt(h) shouldBe Block.RewardBlockVersion
      else blockchain.blockVersionAt(h) shouldBe Block.ProtoBlockVersion
    }

    blockchain.blockVersionAt(v3ActivationHeight) shouldBe Block.PlainBlockVersion
    blockchain.blockVersionAt(v3ActivationHeight + 1) shouldBe Block.PlainBlockVersion
    blockchain.blockVersionAt(v3ActivationHeight + 2) shouldBe Block.NgBlockVersion

    blockchain.blockVersionAt(v4ActivationHeight) shouldBe Block.NgBlockVersion
    blockchain.blockVersionAt(v4ActivationHeight + 1) shouldBe Block.RewardBlockVersion

    blockchain.blockVersionAt(v5ActivationHeight) shouldBe Block.ProtoBlockVersion
  }
} 
Example 17
Source File: TransferByIdTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs.smart.scenarios

import com.wavesplatform.common.utils._
import com.wavesplatform.db.WithState
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.lang.directives.values.{Expression, V3}
import com.wavesplatform.lang.script.v1.ExprScript
import com.wavesplatform.lang.utils.compilerContext
import com.wavesplatform.lang.v1.compiler.ExpressionCompiler
import com.wavesplatform.lang.v1.parser.Parser
import com.wavesplatform.state.BinaryDataEntry
import com.wavesplatform.state.diffs.ENOUGH_AMT
import com.wavesplatform.state.diffs.smart.smartEnabledFS
import com.wavesplatform.transaction.smart.SetScriptTransaction
import com.wavesplatform.transaction.transfer.TransferTransaction
import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction}
import com.wavesplatform.{NoShrink, TransactionGen}
import org.scalacheck.Gen
import org.scalatest.PropSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class TransferByIdTest extends PropSpec with ScalaCheckPropertyChecks with WithState with TransactionGen with NoShrink {

  val scriptSrc =
    s"""
       |match tx {
       |  case dtx: DataTransaction =>
       |    let txId    = extract(getBinary(dtx.data, "transfer_id"))
       |    let maybeTx = transferTransactionById(txId)
       |
       |    isDefined(maybeTx)
       |
       |  case _ => false
       |}
     """.stripMargin

  val expr = {
    val parsed = Parser.parseExpr(scriptSrc).get.value
    ExpressionCompiler(compilerContext(V3, Expression, isAssetScript = false), parsed).explicitGet()._1
  }

  def preconditions: Gen[(GenesisTransaction, TransferTransaction, SetScriptTransaction, DataTransaction)] =
    for {
      master    <- accountGen
      recipient <- accountGen
      ts        <- positiveIntGen
      genesis = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet()
      setScript <- selfSignedSetScriptTransactionGenP(master, ExprScript(V3, expr).explicitGet())
      transfer <- Gen.oneOf[TransferTransaction](
        transferGeneratorP(ts, master, recipient.toAddress, ENOUGH_AMT / 2),
        transferGeneratorPV2(ts, master, recipient.toAddress, ENOUGH_AMT / 2)
      )
      data <- dataTransactionGenP(master, List(BinaryDataEntry("transfer_id", transfer.id())))
    } yield (genesis, transfer, setScript, data)

  property("Transfer by id works fine") {
    forAll(preconditions) {
      case (genesis, transfer, setScript, data) =>
        assertDiffEi(
          Seq(TestBlock.create(Seq(genesis, transfer))),
          TestBlock.create(Seq(setScript, data)),
          smartEnabledFS
        )(_ shouldBe an[Right[_, _]])
    }
  }
} 
Example 18
Source File: GenesisBlockUpdateSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.events

import com.wavesplatform.settings.WavesSettings
import com.wavesplatform.state.diffs.ENOUGH_AMT
import com.wavesplatform.transaction.GenesisTransaction
import com.wavesplatform.{BlockGen, TestHelpers}
import org.scalacheck.Gen
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import com.wavesplatform.common.utils.EitherExt2

class GenesisBlockUpdateSpec extends FreeSpec with Matchers with BlockGen with ScalaCheckPropertyChecks with EventsHelpers {
  override protected def settings: WavesSettings = TestHelpers.enableNG(super.settings)

  val genesisAppendWithWavesAmountGen: Gen[(BlockAppended, Long)] = for {
    master      <- accountGen
    wavesAmount <- Gen.choose(1L, ENOUGH_AMT)
    gt = GenesisTransaction.create(master.toAddress, wavesAmount, 0).explicitGet()
    b <- blockGen(Seq(gt), master)
    ba = appendBlock(b)
  } yield (ba, wavesAmount)

  "on genesis block append" - {
    "master address balance gets correctly updated" in forAll(genesisAppendWithWavesAmountGen) {
      case (BlockAppended(_, _, _, _, _, upds), wavesAmount) =>
        upds.head.balances.head._3 shouldBe wavesAmount
    }

    "updated Waves amount is calculated correctly" in forAll(genesisAppendWithWavesAmountGen) {
      case (BlockAppended(_, _, _, updatedWavesAmount, _, _), wavesAmount) =>
        updatedWavesAmount shouldBe wavesAmount
    }
  }

} 
Example 19
Source File: BaseSpec.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais

import com.typesafe.config._
import com.wegtam.books.pfhais.pure.config._
import eu.timepit.refined.auto._
import pureconfig.loadConfig
import org.scalatest._
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks


abstract class BaseSpec extends WordSpec 
    with MustMatchers
    with ScalaCheckPropertyChecks
    with BeforeAndAfterAll
    with BeforeAndAfterEach {

  protected val config = ConfigFactory.load()
  protected val dbConfig = loadConfig[DatabaseConfig](config, "database")

  override def beforeAll(): Unit = {
    val _ = withClue("Database configuration could not be loaded!") {
      dbConfig.isRight must be(true)
    }
  }
} 
Example 20
Source File: BaseSpec.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais

import com.typesafe.config._
import com.wegtam.books.pfhais.tapir.config._
import eu.timepit.refined.auto._
import pureconfig._
import org.scalatest._
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks


abstract class BaseSpec extends AnyWordSpec 
    with MustMatchers
    with ScalaCheckPropertyChecks
    with BeforeAndAfterAll
    with BeforeAndAfterEach {

  protected val config = ConfigFactory.load()
  protected val dbConfig = ConfigSource.fromConfig(config).at("database").load[DatabaseConfig]

  override def beforeAll(): Unit = {
    val _ = withClue("Database configuration could not be loaded!") {
      dbConfig.isRight must be(true)
    }
  }
} 
Example 21
Source File: GeometryCheckers.scala    From rtree2d   with Apache License 2.0 5 votes vote down vote up
package com.github.plokhotnyuk.rtree2d.core

import TestUtils._
import org.scalacheck.Gen
import org.scalacheck.Prop._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class GeometryCheckers extends AnyWordSpec with Matchers with ScalaCheckPropertyChecks {
  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 1000)
  "EuclideanPlane.distanceCalculator" when {
    "asked to calculate distance from point to an RTree" should {
      "return a distance to a nearest part of the RTree bounding box or 0 if the point is inside it" in {
        forAll(entryListGen, floatGen, floatGen) {
          (entries: Seq[RTreeEntry[Int]], x: Float, y: Float) =>
            val t = RTree(entries)
            propBoolean(entries.nonEmpty && !intersects(t, x, y)) ==> {
              val expected = euclideanDistance(x, y, t)
              EuclideanPlane.distanceCalculator.distance(x, y, t) === expected +- 0.001f
            }
        }
      }
    }
  }
  "SphericalEarth.distanceCalculator" when {
    "asked to calculate distance from point to an RTree" should {
      "return 0 if the point is inside it" in {
        forAll(latLonEntryGen, Gen.choose[Float](0, 1), Gen.choose[Float](0, 1)) {
          (t: RTreeEntry[Int], rdx: Float, rdy: Float) =>
            val lat = t.minX + rdx * (t.maxX - t.minX)
            val lon = t.minY + rdy * (t.maxY - t.minY)
            propBoolean(intersects(t, lat, lon)) ==> {
              SphericalEarth.distanceCalculator.distance(lat, lon, t) === 0.0f +- 0.1f
            }
        }
      }
      "return a distance to the nearest edge of the RTree bounding box if point doesn't intersect and is aligned vertically" in {
        forAll(latLonEntryGen, latGen, lonGen) {
          (t: RTreeEntry[Int], lat: Float, lon: Float) =>
            propBoolean(!intersects(t, lat, lon) && alignedVertically(t, lat, lon)) ==> {
              val distancesForCorners = IndexedSeq(
                greatCircleDistance(lat, lon, t.minX, lon),
                greatCircleDistance(lat, lon, t.maxX, lon),
                greatCircleDistance(lat, lon, t.minX, t.minY),
                greatCircleDistance(lat, lon, t.minX, t.maxY),
                greatCircleDistance(lat, lon, t.maxX, t.minY),
                greatCircleDistance(lat, lon, t.maxX, t.maxY)
              )
              val expected = distancesForCorners.min
              val result = SphericalEarth.distanceCalculator.distance(lat, lon, t)
              result <= expected + 0.1f
            }
        }
      }
      "return a distance to the nearest edge of the RTree bounding box if point doesn't not intersect and is aligned horizontally" in {
        forAll(latLonEntryGen, latGen, lonGen) {
          (t: RTreeEntry[Int], lat: Float, lon: Float) =>
            propBoolean(!intersects(t, lat, lon) && alignedHorizontally(t, lat, lon)) ==> {
              val distancesForCorners = IndexedSeq(
                greatCircleDistance(lat, lon, lat, t.minY),
                greatCircleDistance(lat, lon, lat, t.maxY),
                greatCircleDistance(lat, lon, t.minX, t.minY),
                greatCircleDistance(lat, lon, t.minX, t.maxY),
                greatCircleDistance(lat, lon, t.maxX, t.minY),
                greatCircleDistance(lat, lon, t.maxX, t.maxY)
              )
              val expected = distancesForCorners.min
              val result = SphericalEarth.distanceCalculator.distance(lat, lon, t)
              result <= expected + 0.1f
            }
        }
      }
      "return a distance to the nearest corner of the RTree bounding box if point doesn't not intersect and is not aligned vertically or horizontally" in {
        forAll(latLonEntryGen, latGen, lonGen) {
          (t: RTreeEntry[Int], lat: Float, lon: Float) =>
            propBoolean(!intersects(t, lat, lon) && !alignedHorizontally(t, lat, lon) && !alignedVertically(t, lat, lon)) ==> {
              val distancesForCorners = IndexedSeq(
                greatCircleDistance(lat, lon, t.minX, t.minY),
                greatCircleDistance(lat, lon, t.minX, t.maxY),
                greatCircleDistance(lat, lon, t.maxX, t.minY),
                greatCircleDistance(lat, lon, t.maxX, t.maxY)
              )
              val expected = distancesForCorners.min
              val result = SphericalEarth.distanceCalculator.distance(lat, lon, t)
              result <= expected + 0.1f
            }
        }
      }
    }
  }
} 
Example 22
Source File: LithiumSpec.scala    From lithium   with Apache License 2.0 5 votes vote down vote up
package com.swissborg.lithium

import cats.implicits._
import cats.{Applicative, Functor, Monoid}
import com.swissborg.lithium.ArbitraryStrategy._
import com.swissborg.lithium.instances.ArbitraryTestInstances
import com.swissborg.lithium.strategy._
import com.swissborg.lithium.utils.PostResolution
import org.scalacheck.Arbitrary
import org.scalactic.anyvals._
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.Assertion
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalatest.matchers.should.Matchers

trait LithiumSpec extends AnyWordSpecLike with Matchers with ScalaCheckPropertyChecks with ArbitraryTestInstances {
  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = PosInt(1000),
                               maxDiscardedFactor = PosZDouble(5),
                               minSize = PosZInt(0),
                               sizeRange = PosZInt(100),
                               workers = PosInt(8))

  
  final def simulate[F[_]: Functor, Strat[_[_]], S <: Scenario: Arbitrary](name: String)(
    run: F[Assertion] => Assertion
  )(implicit strategy: ArbitraryStrategy[Strat[F]], ev: Strat[F] <:< Strategy[F], M: Monoid[F[PostResolution]]): Unit =
    name in {
      forAll { simulation: Simulation[F, Strat, S] =>
        run(simulation.splitBrainResolved.map(_ shouldBe true))
      }
    }

  final def simulateWithNonCleanPartitions[F[_]: Applicative, Strat[_[_]], S <: Scenario: Arbitrary](name: String)(
    run: F[Assertion] => Assertion
  )(implicit strategy: ArbitraryStrategy[Strat[F]], ev: Strat[F] <:< Strategy[F], M: Monoid[F[PostResolution]]): Unit =
    simulate[F, Union[*[_], Strat, IndirectlyConnected], WithNonCleanPartitions[S]](name)(run)
} 
Example 23
Source File: CsvSinkTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv

import java.io._
import laws.discipline.arbitrary._
import ops._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import scala.io.Codec

class CsvSinkTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("CSV data should be correctly written to an output stream (bit by bit)") {
    forAll(csv) { csv =>
      val out = new ByteArrayOutputStream()

      csv.foldLeft(out.asCsvWriter[List[String]](rfc))(_ write _).close()

      new String(out.toByteArray, Codec.UTF8.charSet) should be(csv.asCsv(rfc))
    }
  }

  test("CSV data should be correctly written to an output stream (in bulk)") {
    forAll(csv) { csv =>
      val out = new ByteArrayOutputStream()

      out.writeCsv(csv, rfc)

      new String(out.toByteArray, Codec.UTF8.charSet) should be(csv.asCsv(rfc))
    }
  }

  test("CSV data should be correctly written to a writer (bit by bit)") {
    forAll(csv) { csv =>
      val out = new StringWriter()

      csv.foldLeft(out.asCsvWriter[List[String]](rfc))(_ write _).close()

      out.toString should be(csv.asCsv(rfc))
    }
  }

  test("CSV data should be correctly written to a writer (in bulk)") {
    forAll(csv) { csv =>
      val out = new StringWriter()

      out.writeCsv(csv, rfc)

      out.toString should be(csv.asCsv(rfc))
    }
  }
} 
Example 24
Source File: RichRowSuite.scala    From spark-excel   with Apache License 2.0 5 votes vote down vote up
package com.crealytics.spark.excel

import org.apache.poi.ss.usermodel.{Cell, Row}
import org.scalacheck.Gen
import org.scalacheck.Prop.BooleanOperators
import org.scalamock.scalatest.MockFactory

import scala.util.Try
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalatest.funsuite.AnyFunSuite

trait RowGenerator extends MockFactory {
  private val MAX_WIDTH = 100

  protected case class GeneratedRow(start: Int, end: Int, lastCellNum: Int, row: Row)

  protected val rowGen: Gen[GeneratedRow] = for {
    startColumn <- Gen.choose(0, MAX_WIDTH - 1)
    endColumn <- Gen.choose(0, MAX_WIDTH - 1)
    lastCellNum <- Gen.choose(0, MAX_WIDTH - 1)
    row = stub[Row]
    _ = (row.getCell(_: Int)).when(*) returns stub[Cell]
    _ = row.getLastCellNum _ when () returns lastCellNum.toShort
  } yield GeneratedRow(startColumn, endColumn, lastCellNum, row)
}

class RichRowSuite extends AnyFunSuite with ScalaCheckPropertyChecks with RowGenerator {
  test("Invalid cell range should throw an error") {
    forAll(rowGen) { g =>
      (g.start > g.end) ==> Try {
        g.row.eachCellIterator(g.start, g.end).next()
      }.isFailure
    }
  }

  test("Valid cell range should iterate through all non-empty cells") {
    forAll(rowGen) { g =>
      (g.start <= g.end && g.start < g.lastCellNum) ==> {
        val count = g.row.eachCellIterator(g.start, g.end).size
        count === Math.min(g.end, g.lastCellNum - 1) - g.start + 1
      }
    }
  }

  test("Valid cell range should should not iterate through non-empty cells") {
    forAll(rowGen) { g =>
      (g.start <= g.end && g.start >= g.lastCellNum) ==> {
        g.row.eachCellIterator(g.start, g.end).size === 0
      }
    }
  }
} 
Example 25
Source File: DataLocatorSuite.scala    From spark-excel   with Apache License 2.0 5 votes vote down vote up
package com.crealytics.spark.excel
import com.crealytics.tags.WIP
import com.norbitltd.spoiwo.model.{CellRange, Sheet, Workbook}
import org.apache.poi.ss.SpreadsheetVersion
import org.apache.poi.ss.util.AreaReference
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import com.norbitltd.spoiwo.natures.xlsx.Model2XlsxConversions._
import org.scalacheck.Gen

import scala.collection.JavaConverters._
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class DataLocatorSuite extends AnyFunSpec with ScalaCheckPropertyChecks with Matchers with Generators {
  describe("with a table reference") {
    val dl = DataLocator(Map("dataAddress" -> s"$tableName[#All]"))
    describe("containing #All") {
      it("extracts the entire table data") {
        forAll(sheetWithTableGen) { sheet =>
          val actualData = dl.readFrom(sheet.convertAsXlsx()).map(_.map(_.value)).to[Seq]
          actualData should contain theSameElementsAs sheet.extractTableData(0)
        }
      }

      it("writes into a new table in a new sheet if no corresponding table exists") {
        forAll(sheetGenerator(withHeader = Gen.const(true), numCols = Gen.choose(1, 200))) { dataSheet =>
          val workbook = new XSSFWorkbook()
          val header = dataSheet.rows.head.cells.map(_.value.toString).toSeq
          val generatedSheet = dl.toSheet(
            header = Some(header),
            data = dataSheet.rows.tail.iterator.map(_.cells.map(_.value.toString).toSeq),
            existingWorkbook = workbook
          )
          generatedSheet.convertAsXlsx(workbook)
          val pTable = workbook.getTable(tableName)
          pTable.getSheetName should equal(tableName)
          pTable.getColumns.asScala.map(_.getName) should contain theSameElementsInOrderAs header
          val actualData = dl.readFrom(workbook).map(_.map(_.value)).to[Seq]
          actualData should contain theSameElementsAs dataSheet.rows.map(_.cells.map(_.value))
        }
      }

      it("overwrites an existing table") {
        forAll(sheetWithTableGen) { sheetWithTable =>
          val workbook = sheetWithTable.convertAsXlsx()
          val table = sheetWithTable.tables.head
          val header = table.columns.map(_.name)
          val tableData = dl.readFrom(workbook).map(_.map(c => s"new_$c")).toList
          val generatedSheet =
            dl.toSheet(header = tableData.headOption, data = tableData.iterator.drop(1), existingWorkbook = workbook)
          Workbook(generatedSheet).writeToExisting(workbook)
          val pTable = workbook.getTable(tableName)
          pTable.getSheetName should equal(sheetName)
          pTable.getColumns.asScala.map(_.getName) should contain theSameElementsInOrderAs header
          val actualData = dl.readFrom(workbook).map(_.map(_.value)).to[Seq]
          actualData should contain theSameElementsAs tableData
        }
      }
    }
  }
  describe("without any dataAddress") {
    it("defaults to starting at cell A1 in the first sheet") {
      val dl = DataLocator(Map())
      dl shouldBe a[CellRangeAddressDataLocator]
      val cradl = dl.asInstanceOf[CellRangeAddressDataLocator]
      cradl.dataAddress.getFirstCell.formatAsString() should equal("A1")
      cradl.dataAddress.getFirstCell.getSheetName should equal(null)
    }
  }
} 
Example 26
Source File: editTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.edit

import cats.implicits._
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class editTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  private val lineGen = Gen.frequency(
    3 -> Arbitrary.arbString.arbitrary,
    1 -> Gen.oneOf("scala-steward:off", "scala-steward:on"),
    1 -> Gen.alphaNumStr.map(_ + " // scala-steward:off")
  )

  private val contentGen = Gen.listOf(lineGen).map(_.mkString("\n"))

  test("splitByOffOnMarker") {
    forAll(contentGen) { s: String =>
      splitByOffOnMarker(s).foldMap { case (part, _) => part } shouldBe s
    }
  }
} 
Example 27
Source File: gitTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.git

import org.scalacheck.{Arbitrary, Gen}
import org.scalasteward.core.TestSyntax._
import org.scalasteward.core.data.Update
import org.scalasteward.core.data.Update.Single
import org.scalasteward.core.repoconfig.CommitsConfig
import org.scalasteward.core.update.show
import org.scalasteward.core.util.Nel
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class gitTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  implicit val updateArbitrary: Arbitrary[Update] = Arbitrary(for {
    groupId <- Gen.alphaStr
    artifactId <- Gen.alphaStr
    currentVersion <- Gen.alphaStr
    newerVersion <- Gen.alphaStr
  } yield Single(groupId % artifactId % currentVersion, Nel.one(newerVersion)))

  test("commitMsgFor should work with static message") {
    val commitsConfig = CommitsConfig(Some("Static message"))
    forAll { update: Update => commitMsgFor(update, commitsConfig) shouldBe "Static message" }
  }

  test("commitMsgFor should work with default message") {
    val commitsConfig = CommitsConfig(Some("${default}"))
    forAll { update: Update =>
      commitMsgFor(update, commitsConfig) shouldBe s"Update ${show.oneLiner(update)} to ${update.nextVersion}"
    }
  }

  test("commitMsgFor should work with templated message") {
    val commitsConfig =
      CommitsConfig(Some("Update ${artifactName} from ${currentVersion} to ${nextVersion}"))
    forAll { update: Update =>
      commitMsgFor(update, commitsConfig) shouldBe s"Update ${show.oneLiner(update)} from ${update.currentVersion} to ${update.nextVersion}"
    }
  }

} 
Example 28
Source File: NurtureAlgTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.nurture

import cats.data.StateT
import cats.effect.IO
import eu.timepit.refined.types.numeric.PosInt
import org.scalacheck.{Arbitrary, Gen}
import org.scalasteward.core.TestSyntax._
import org.scalasteward.core.data.ProcessResult.{Ignored, Updated}
import org.scalasteward.core.data.Update.Single
import org.scalasteward.core.data.{ProcessResult, Update}
import org.scalasteward.core.util.Nel
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class NurtureAlgTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  implicit val updateArbitrary: Arbitrary[Update] = Arbitrary(for {
    groupId <- Gen.alphaStr
    artifactId <- Gen.alphaStr
    currentVersion <- Gen.alphaStr
    newerVersion <- Gen.alphaStr
  } yield Single(groupId % artifactId % currentVersion, Nel.one(newerVersion)))

  test("processUpdates with No Limiting") {
    forAll { updates: List[Update] =>
      NurtureAlg
        .processUpdates(
          updates,
          _ => StateT[IO, Int, ProcessResult](actionAcc => IO.pure(actionAcc + 1 -> Ignored)),
          None
        )
        .runS(0)
        .unsafeRunSync() shouldBe updates.size
    }
  }

  test("processUpdates with Limiting should process all updates up to the limit") {
    forAll { updates: Set[Update] =>
      val (ignorableUpdates, appliableUpdates) = updates.toList.splitAt(updates.size / 2)
      val f: Update => StateT[IO, Int, ProcessResult] = update =>
        StateT[IO, Int, ProcessResult](actionAcc =>
          IO.pure(actionAcc + 1 -> (if (ignorableUpdates.contains(update)) Ignored else Updated))
        )
      NurtureAlg
        .processUpdates(
          ignorableUpdates ++ appliableUpdates,
          f,
          PosInt.unapply(appliableUpdates.size)
        )
        .runS(0)
        .unsafeRunSync() shouldBe updates.size
    }
  }
} 
Example 29
Source File: stringTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.util

import org.scalacheck.Gen
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class stringTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  test("splitBetweenLowerAndUpperChars(s).mkString == s") {
    forAll(Gen.asciiStr) { s: String =>
      string.splitBetweenLowerAndUpperChars(s).mkString shouldBe s
    }
  }

  test(
    "splitBetweenLowerAndUpperChars: substrings end with lower case char or all are upper case"
  ) {
    forAll(Gen.asciiStr) { s: String =>
      string
        .splitBetweenLowerAndUpperChars(s)
        .forall(sub => sub.matches(".*\\p{javaLowerCase}") || sub.matches("\\p{javaUpperCase}*"))
    }
  }

  test("splitBetweenLowerAndUpperChars: examples") {
    string.splitBetweenLowerAndUpperChars("") shouldBe List("")
    string.splitBetweenLowerAndUpperChars("a") shouldBe List("a")
    string.splitBetweenLowerAndUpperChars("A") shouldBe List("A")
    string.splitBetweenLowerAndUpperChars("aa") shouldBe List("aa")
    string.splitBetweenLowerAndUpperChars("AA") shouldBe List("AA")
    string.splitBetweenLowerAndUpperChars("aA") shouldBe List("a", "A")
    string.splitBetweenLowerAndUpperChars("aAbB") shouldBe List("a", "Ab", "B")
  }
} 
Example 30
Source File: utilTest.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.util

import cats.implicits._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import scala.collection.mutable.ListBuffer

class utilTest extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks {
  test("appendBounded") {
    val lb = new ListBuffer[Int]
    lb.appendAll(List(1, 2, 3))

    appendBounded(lb, 4, 4)
    lb.toList shouldBe List(1, 2, 3, 4)

    appendBounded(lb, 5, 4)
    lb.toList shouldBe List(3, 4, 5)

    appendBounded(lb, 6, 4)
    lb.toList shouldBe List(3, 4, 5, 6)

    appendBounded(lb, 7, 6)
    lb.toList shouldBe List(3, 4, 5, 6, 7)

    appendBounded(lb, 8, 6)
    lb.toList shouldBe List(3, 4, 5, 6, 7, 8)

    appendBounded(lb, 9, 6)
    lb.toList shouldBe List(6, 7, 8, 9)
  }

  test("bindUntilTrue: empty list") {
    bindUntilTrue(List.empty[Option[Boolean]]) shouldBe Some(false)
  }

  test("intersects") {
    intersects(List(1, 3, 5), Vector(2, 4, 6)) shouldBe false
    intersects(List(1, 3, 5), Vector(2, 3, 6)) shouldBe true
  }
} 
Example 31
Source File: OrderInstancesSpec.scala    From fs2-rabbit   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.fs2rabbit.laws

import java.time.Instant

import cats._
import cats.implicits._
import cats.kernel.laws.discipline._
import dev.profunktor.fs2rabbit.model.AmqpFieldValue._
import dev.profunktor.fs2rabbit.model._
import dev.profunktor.fs2rabbit.testkit._
import org.scalacheck.Arbitrary._
import org.scalatest.funspec.AnyFunSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.typelevel.discipline.scalatest.FunSpecDiscipline

class OrderInstancesSpec
    extends AnyFunSpec
    with FunSpecDiscipline
    with ScalaCheckPropertyChecks
    with InstantArbitraries {
  implicit val orderInstant: Order[Instant] = Order.by(_.getEpochSecond)

  checkAll("ExchangeName.OrderLaws", OrderTests[ExchangeName].order)
  checkAll("QueueName.OrderLaws", OrderTests[QueueName].order)
  checkAll("RoutingKey.OrderLaws", OrderTests[RoutingKey].order)
  checkAll("DeliveryTag.OrderLaws", OrderTests[DeliveryTag].order)
  checkAll("ConsumerTag.OrderLaws", OrderTests[ConsumerTag].order)
  checkAll("Instant.OrderLaws", OrderTests[Instant](instantOrderWithSecondPrecision).order)
  checkAll("DeliveryMode.OrderLaws", OrderTests[DeliveryMode].order)
  checkAll("ShortString.OrderLaws", OrderTests[ShortString].order)
  checkAll("TimestampVal.OrderLaws", OrderTests[TimestampVal].order)
  checkAll("DecimalVal.OrderLaws", OrderTests[DecimalVal].order)
  checkAll("ByteVal.OrderLaws", OrderTests[ByteVal].order)
  checkAll("DoubleVal.OrderLaws", OrderTests[DoubleVal].order)
  checkAll("FloatVal.OrderLaws", OrderTests[FloatVal].order)
  checkAll("ShortVal.OrderLaws", OrderTests[ShortVal].order)
  checkAll("BooleanVal.OrderLaws", OrderTests[BooleanVal].order)
  checkAll("IntVal.OrderLaws", OrderTests[IntVal].order)
  checkAll("LongVal.OrderLaws", OrderTests[LongVal].order)
  checkAll("StringVal.OrderLaws", OrderTests[StringVal].order)
  checkAll("NullVal.OrderLaws", OrderTests[NullVal.type].order)
} 
Example 32
Source File: TestSupport.scala    From cedi-dtrace   with Apache License 2.0 5 votes vote down vote up
package com.ccadllc.cedi.dtrace
package logging

import cats.effect.{ IO, Sync }

import io.circe._
import io.circe.syntax._

import org.scalacheck.Arbitrary

import org.scalatest.Suite
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

import shapeless.Lazy

trait TestSupport extends AnyWordSpecLike with Matchers with ScalaCheckPropertyChecks with TraceGenerators with TestData {
  self: Suite =>

  override def testEmitter[F[_]: Sync]: F[TraceSystem.Emitter[F]] = Sync[F].pure(LogEmitter.apply)

  val salesManagementSystem = TraceSystem(testSystemData, testEmitter[IO].unsafeRunSync, TraceSystem.realTimeTimer[IO])
  val calculateQuarterlySalesTraceContext = TraceContext(quarterlySalesCalculationSpan, true, salesManagementSystem)

  def encodeGeneratedJson[A: Arbitrary](implicit encoder: Lazy[Encoder[A]]): Unit = {
    implicit val e = encoder.value
    "encode arbitrary instances to JSON" in {
      forAll { (msg: A) => msg.asJson.noSpaces should not be (None) }
    }
  }
  def encodeSpecificJson[A](a: A, json: Json)(implicit encoder: Lazy[Encoder[A]]): Unit = {
    implicit val e = encoder.value
    "encode specific instance to JSON and ensure it matches expected" in { a.asJson shouldBe json }
  }
} 
Example 33
Source File: MoneyHeaderCodecTest.scala    From cedi-dtrace   with Apache License 2.0 5 votes vote down vote up
package com.ccadllc.cedi.dtrace
package interop
package money

import java.util.UUID

import org.scalacheck.Arbitrary
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

import MoneyHeaderCodec._

class MoneyHeaderCodecTest extends AnyWordSpec with Matchers with ScalaCheckPropertyChecks with TraceGenerators {

  implicit val arbitraryUUID: Arbitrary[UUID] = Arbitrary(genUUID)

  "the Money Header Codec" should {
    "decode correctly given any valid UUID for trace-Id and any valid long integers for parent and span ID" in {
      forAll { (traceIdValue: UUID, parentSpanIdValue: Long, spanIdValue: Long) =>
        val expectedSpanId = SpanId(traceIdValue, parentSpanIdValue, spanIdValue)
        val header = Header(
          HeaderName,
          Header.Value(s"$TraceIdHeader=$traceIdValue;$ParentIdHeader=$parentSpanIdValue;$SpanIdHeader=$spanIdValue"))
        val errorOrSpanId = headerCodec.decode(List(header))
        errorOrSpanId shouldBe Right(Header.Decoded(Some(expectedSpanId), true))
      }
    }
    "encode correctly for any valid UUID for trace-Id and any valid long integers for parent and span ID" in {
      forAll { (traceIdValue: UUID, parentSpanIdValue: Long, spanIdValue: Long) =>
        val expectedHeader = Header(
          HeaderName,
          Header.Value(s"$TraceIdHeader=$traceIdValue;$ParentIdHeader=$parentSpanIdValue;$SpanIdHeader=$spanIdValue"))
        val spanId = SpanId(traceIdValue, parentSpanIdValue, spanIdValue)
        val headers = headerCodec.encode(spanId)
        headers shouldBe List(expectedHeader)
      }
    }
    "round-trip correctly given any valid UUID for trace-Id and any valid long integers for parent and span ID" in {
      forAll { (traceIdValue: UUID, parentSpanIdValue: Long, spanIdValue: Long) =>
        val expectedSpanId = SpanId(traceIdValue, parentSpanIdValue, spanIdValue)
        val headers = headerCodec.encode(expectedSpanId)
        val errorOrSpanId = headerCodec.decode(headers)
        errorOrSpanId shouldBe Right(Header.Decoded(Some(expectedSpanId), true))
      }
    }
  }
} 
Example 34
Source File: try.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util

import cats.instances.either._
import cats.instances.int._
import cats.instances.option._
import cats.instances.tuple._
import cats.instances.unit._
import cats.kernel.laws.discipline.{ MonoidTests, SemigroupTests }
import cats.laws.discipline.arbitrary._
import cats.laws.discipline.{ MonadErrorTests, TraverseTests }
import com.twitter.util.{ Return, Throw, Try }
import org.scalatest.propspec.AnyPropSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

trait TryTest extends ArbitraryInstances with EqInstances with TryInstances

class TrySuite extends CatbirdSuite with TryTest {
  checkAll("Try[Int]", MonadErrorTests[Try, Throwable].monadError[Int, Int, Int])
  checkAll("Try[Int]", TraverseTests[Try].traverse[Int, Int, Int, Int, Option, Option])
  checkAll("Try[Int]", SemigroupTests[Try[Int]](twitterTrySemigroup[Int]).semigroup)
  checkAll("Try[Int]", MonoidTests[Try[Int]].monoid)
}

class TrySpec extends AnyPropSpec with ScalaCheckPropertyChecks with TryTest {
  property("Equality for Try should use universal equality for Throw") {
    case class SomeError(message: String) extends Exception(message)

    forAll((s: String) => assert(twitterTryEq[Int].eqv(Throw(SomeError(s)), Throw(SomeError(s)))))
  }

  property("Equality for Try should never mix up Return and Throw") {
    forAll((i: Int) => assert(!twitterTryEq[Int].eqv(Throw(new Exception), Return(i))))
  }
} 
Example 35
Source File: CsvSourceOpsTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv
package ops

import kantan.codecs.laws.CodecValue
import laws._
import laws.discipline.arbitrary._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import scala.util.Try

class CsvSourceOpsTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  type TestCase = (Int, Float, String, Boolean)

  def compare[F, A](csv: List[Either[F, A]], data: List[RowValue[A]]): Unit = {
    csv.length should be(data.length)

    csv.zip(data).foreach {
      case (Right(is), CodecValue.LegalValue(_, cs)) => is should be(cs)
      case (Left(_), CodecValue.IllegalValue(_))     =>
      case (a, b)                                    => fail(s"$a is not compatible with $b")
    }
  }

  test("CsvSource instances should have a working asCsvReader method") {
    forAll { data: List[RowValue[TestCase]] =>
      compare(
        asCsv(data, rfc)
          .asCsvReader[TestCase](rfc)
          .toList,
        data
      )
    }
  }

  test("CsvSource instances should have a working readCsv method") {
    forAll { data: List[RowValue[TestCase]] =>
      compare(
        asCsv(data, rfc)
          .readCsv[List, TestCase](rfc),
        data
      )
    }
  }

  def compareUnsafe[A](csv: => List[A], data: List[RowValue[A]]): Unit = {
    def cmp(csv: List[A], data: List[RowValue[A]]): Unit = (csv, data) match {
      case (Nil, Nil)                                                 => ()
      case (h1 :: t1, CodecValue.LegalValue(_, h2) :: t2) if h1 == h2 => cmp(t1, t2)
      case (a, b)                                                     => fail(s"$a is not compatible with $b")
    }

    Try(csv) match {
      case scala.util.Success(is) => cmp(is, data)
      case _ =>
        data.filter(_.isIllegal).nonEmpty should be(true)
        ()
    }
  }

  test("CsvSource instances should have a working asUnsafeCsvReader method") {
    forAll { data: List[RowValue[TestCase]] =>
      compareUnsafe(
        asCsv(data, rfc)
          .asUnsafeCsvReader[TestCase](rfc)
          .toList,
        data
      )
    }
  }

  test("CsvSource instances should have a working unsafeReadCsv method") {
    forAll { data: List[RowValue[TestCase]] =>
      compareUnsafe(
        asCsv(data, rfc)
          .unsafeReadCsv[List, TestCase](rfc),
        data
      )
    }
  }
} 
Example 36
Source File: ErrorTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv

import DecodeError.TypeError
import ParseError.IOError
import laws.discipline.arbitrary._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class ErrorTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("TypeErrors should be equal if the underlying errors are the same") {
    forAll { (e1: TypeError, e2: ReadError) =>
      (e1, e2) match {
        case (TypeError(t1), TypeError(t2)) => (e1 == e2) should be(t1 == t2)
        case _                              => e1 should not be (e2)
      }
    }
  }

  test("TypeErrors should have identical hashCodes if the underlying errors have identical hashCodes") {
    forAll { (e1: TypeError, e2: TypeError) =>
      (e1.hashCode() == e2.hashCode()) should be(e1.message.hashCode == e2.message.hashCode)
    }
  }

  test("IOErrors should be equal if the underlying errors are the same") {
    forAll { (e1: IOError, e2: ReadError) =>
      (e1, e2) match {
        case (IOError(t1), IOError(t2)) => (e1 == e2) should be(t1 == t2)
        case _                          => e1 should not be (e2)
      }
    }
  }

  test("IOErrors should have identical hashCodes if the underlying errors have identical hashCodes") {
    forAll { (e1: IOError, e2: IOError) =>
      (e1.hashCode() == e2.hashCode()) should be(e1.message.hashCode == e2.message.hashCode)
    }
  }
} 
Example 37
Source File: ParseResultTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

// Shapeless' Lazy macros generate code that contain null.
@SuppressWarnings(Array("org.wartremover.warts.Throw"))
class ParseResultTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("ParseResult.success should return a Right") {
    forAll { i: Int =>
      ParseResult.success(i) should be(Right(i))
    }
  }

  test("ParseResult.apply should return a Right on 'good' values") {
    forAll { i: Int =>
      ParseResult(i) should be(Right(i))
    }
  }

  test("ParseResult.apply should return a Left on 'bad' values") {
    forAll { e: Exception =>
      ParseResult(throw e) should be(Left(ParseError.IOError(e)))
    }
  }
} 
Example 38
Source File: DecodeResultTests.scala    From kantan.csv   with Apache License 2.0 5 votes vote down vote up
package kantan.csv

import laws.discipline.arbitrary._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

@SuppressWarnings(Array("org.wartremover.warts.Throw"))
class DecodeResultTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  test("DecodeResult.success should return a Right") {
    forAll { i: Int =>
      DecodeResult.success(i) should be(Right(i))
    }
  }

  test("DecodeResult.apply should return a Right on 'good' values") {
    forAll { i: Int =>
      DecodeResult(i) should be(Right(i))
    }
  }

  test("DecodeResult.apply should return a Left on 'bad' values") {
    forAll { e: Exception =>
      DecodeResult(throw e) should be(Left(DecodeError.TypeError(e)))
    }
  }

  test("DecodeResult.outOfBounds should return a Left") {
    forAll { i: Int =>
      DecodeResult.outOfBounds(i) should be(Left(DecodeError.OutOfBounds(i)))
    }
  }
} 
Example 39
Source File: KeyEscaperTest.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package mongo

import com.mongodb.internal.validator.CollectibleDocumentFieldNameValidator
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class KeyEscaperTest extends AnyFunSuite with ScalaCheckPropertyChecks {

  import KeyEscaper._
  import KeyEscaperTest._

  test("custom keys") {
    val customCases = List(
      "plain" -> "plain",
      "<plain, but strange>" -> "<plain, but strange>",
      "not_so_plain" -> "not_so_plain",
      "$" -> "\\$",
      "." -> "\\_",
      "plain$ with$ $dollars$" -> "plain$ with$ $dollars$",
      "Sentence." -> "Sentence\\_",
      "$operator" -> "\\$operator",
      "$worst.of.both.worlds" -> "\\$worst\\_of\\_both\\_worlds"
    )

    for ((input, expected) <- customCases) {
      val escaped = escape(input)
      assert(validator.validate(escaped))
      assert(escaped == expected)
      assert(unescape(escaped) == input)
    }
  }

  test("plain keys") {
    forAll(plainKeyGen) { plainKey =>
      val escaped = escape(plainKey)
      assert(validator.validate(escaped))
      assert(escaped == plainKey)
      assert(unescape(escaped) == plainKey)
    }
  }

  test("arbitrary keys") {
    forAll(deniedKeyGen) { arbitraryKey =>
      val escaped = escape(arbitraryKey)
      assert(validator.validate(escaped))
      assert(unescape(escaped) == arbitraryKey)
    }
  }
}

object KeyEscaperTest {
  def isPlain(char: Char): Boolean = char != '.' && char != '$' && char != '\\'

  val validator = new CollectibleDocumentFieldNameValidator

  val plainCharGen: Gen[Char] = Arbitrary.arbitrary[Char].filter(isPlain)
  val plainKeyGen: Gen[String] = Gen.listOf(plainCharGen).map(_.mkString)

  val deniedCharGen: Gen[Char] = Gen.oneOf('.', '$')
  val deniedKeyGen: Gen[String] = Gen.listOf(Gen.oneOf(plainCharGen, deniedCharGen)).map(_.mkString)
} 
Example 40
Source File: IsoInstantTest.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package serialization

import com.avsystem.commons.serialization.GenCodec.ReadFailure
import org.scalacheck.Gen
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class IsoInstantTest extends AnyFunSuite with ScalaCheckPropertyChecks {
  test("basic parsing") {
    assert(IsoInstant.parse("1970-01-01T00:00:00Z") == 0)
    assert(IsoInstant.parse("1970-01-01T00:00:00.000Z") == 0)
    intercept[ReadFailure](IsoInstant.parse("1970-01-01T00:00:00"))
    intercept[ReadFailure](IsoInstant.parse("1970-01-01"))
    intercept[ReadFailure](IsoInstant.parse("1970-13-01T00:00:00Z"))
    intercept[ReadFailure](IsoInstant.parse("1970-01-32T00:00:00Z"))
    intercept[ReadFailure](IsoInstant.parse("1970-01-01T25:00:00Z"))
    intercept[ReadFailure](IsoInstant.parse("1970-01-01T00:61:00Z"))
    intercept[ReadFailure](IsoInstant.parse("1970-01-01T00:00:61Z"))
  }

  test("basic formatting") {
    assert(IsoInstant.format(0) == "1970-01-01T00:00:00.000Z")
    assert(IsoInstant.format(1) == "1970-01-01T00:00:00.001Z")
  }

  test("roundtrip") {
    val genTstamp = Gen.choose[Long](-(1L << 50), 1L << 50)
    forAll(genTstamp) { l: Long =>
      assert(IsoInstant.parse(IsoInstant.format(l)) == l)
    }
  }
} 
Example 41
Source File: RedisMsgTest.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package redis.protocol

import akka.util.ByteString
import com.avsystem.commons.redis.protocol.RedisMsgScalacheck._
import org.scalacheck.Gen
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

import scala.collection.immutable.VectorBuilder


class RedisMsgTest extends AnyFunSuite with ScalaCheckPropertyChecks {
  def splitAtIndices(repr: ByteString, indices: Seq[Int]): Seq[ByteString] =
    (indices :+ repr.length).foldLeft((0, Vector.empty[ByteString])) {
      case ((prevIdx, acc), nextIdx) => (nextIdx, acc :+ repr.slice(prevIdx, nextIdx))
    }._2

  test("encoded and then decoded messages should be equal to the original messages") {
    val gen = for {
      redisMsgs <- Gen.buildableOf[Seq[RedisMsg], RedisMsg](redisProtocolMsgGen)
      splitPoints <- Gen.buildableOf[Seq[Double], Double](Gen.choose(0.0, 1.0))
    } yield (redisMsgs, splitPoints)

    forAll(gen) { case (redisMsgs, splitPoints) =>
      val repr = RedisMsg.encode(redisMsgs)
      val splitIndices = splitPoints.map(sp => (sp * (repr.size - 1)).toInt).toSet.toVector.sorted
      val encodedParts = splitAtIndices(repr, splitIndices)
      val decoded = new VectorBuilder[RedisMsg]
      val decoder = new RedisMsg.Decoder
      encodedParts.foreach(bs => decoder.decodeMore(bs)(decoded += _))
      val decodedMsgs = decoded.result()
      assert(decodedMsgs == redisMsgs)
    }
  }

  test("encoded size") {
    forAll(redisProtocolMsgGen) { msg =>
      assert(RedisMsg.encode(msg).length == RedisMsg.encodedSize(msg))
    }
  }

  test("simple string encode") {
    assert(RedisMsg.encode(SimpleStringMsg("asdf")).utf8String == "+asdf\r\n")
  }

  test("error encode") {
    assert(RedisMsg.encode(ErrorMsg("asdf")).utf8String == "-asdf\r\n")
  }

  test("bulk string encode") {
    assert(RedisMsg.encode(BulkStringMsg(ByteString("srsly"))).utf8String == "$5\r\nsrsly\r\n")
  }

  test("null bulk string encode") {
    assert(RedisMsg.encode(NullBulkStringMsg).utf8String == "$-1\r\n")
  }

  test("array encode") {
    assert(RedisMsg.encode(ArrayMsg(Vector(IntegerMsg(42), IntegerMsg(43)))).utf8String == "*2\r\n:42\r\n:43\r\n")
  }

  test("null array encode") {
    assert(RedisMsg.encode(NullArrayMsg).utf8String == "*-1\r\n")
  }

  test("integer encode") {
    assert(RedisMsg.encode(IntegerMsg(-1)).utf8String == ":-1\r\n")
  }
} 
Example 42
Source File: BaseSpec.scala    From upperbound   with MIT License 5 votes vote down vote up
package upperbound

import org.scalatest._
import cats.effect._, laws.util.TestContext
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

abstract class BaseSpec
    extends AsyncFreeSpec
    with ScalaCheckPropertyChecks
    with OptionValues
    with EitherValues {
  class Env {
    val env = TestContext()
    implicit val ctx: ContextShift[IO] = env.contextShift[IO]
    implicit val timer: Timer[IO] = env.timer[IO]
  }

  object DefaultEnv {
    val defaultEc = scala.concurrent.ExecutionContext.global
    implicit val Timer: Timer[IO] = IO.timer(defaultEc)
    implicit val ContextShift: ContextShift[IO] = IO.contextShift(defaultEc)
  }
} 
Example 43
Source File: AlgorithmsSpec.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package cmwell.util.algorithms.test

import cmwell.util.algorithms.{UFNode, UnionFind}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalatest.{Matchers, PropSpec}


  val uf: UnionFind[String] = new UnionFind(Vector(UFNode("one"), UFNode("two"), UFNode("three"), UFNode("four"), UFNode("five"), UFNode("six"))).
    union(3, 0).
    union(4, 1).
    union("three", "two")

  property("UnionFind.isConnected") {
    val cases = Table(
      ("node1", "node2", "connectivity"),
      (0      , 1      , false         ),
      (0      , 2      , false         ),
      (0      , 3      , true          ),
      (1      , 2      , true          ),
      (1      , 4      , true          ),
      (1      , 5      , false         ),
      (5      , 0      , false         ),
      (2      , 4      , true          )
    )
    forAll(cases) { (node1: Int, node2: Int, expectedConnectivity: Boolean) =>
      uf.isConnected(node1, node2) should be(expectedConnectivity)
    }
  }

  property("UnionFind.find") {
    val cases = Table(
      ("node", "root"),
      (0     , 0     ),
      (1     , 1     ),
      (2     , 1     ),
      (3     , 0     ),
      (4     , 1     ),
      (5     , 5     )
    )
    forAll(cases) { (node: Int, expectedRoot: Int) => uf.find(node) should be(expectedRoot) }
  }

  property("UnionFind.find (by content)") {
    uf.find("four") should be("one")
  }
}
// format: on 
Example 44
Source File: DownloaderSpec.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package cmwell.tools.data.downloader.streams

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.stream.scaladsl._
import akka.stream.{ActorMaterializer, Materializer}
import akka.util.ByteString
import org.scalatest._
import org.scalatest.prop._

import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock._
import com.github.tomakehurst.wiremock.core.WireMockConfiguration._

import scala.concurrent.Await
import scala.concurrent.duration._

import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks


class DownloaderSpec extends PropSpec with ScalaCheckPropertyChecks with Matchers with BeforeAndAfterAll {

  implicit val system: ActorSystem = ActorSystem("reactive-tools-system")
  implicit val mat: Materializer = ActorMaterializer()
  val host = "localhost"
  val numUuidsPerRequest = 25

  override protected def afterAll(): Unit = {
    system.terminate()
    super.afterAll()
  }

  property ("Download from uuids stream sends request blocks of uuids") {
    val uuids = Table(
      ("numUuids", "blocksToSend"),
      (1         , 1             ),
      (10        , 1             ),
      (20        , 1             ),
      (30        , 2             ),
      (60        , 3             )
    )

    forAll(uuids) { (numUuids: Int, expectedBlocksToSend: Int) =>

      // setup wiremock
      val wireMockServer = new WireMockServer(wireMockConfig().dynamicPort())
      wireMockServer.start()
      val port = wireMockServer.port
      WireMock.configureFor(host, port)

      // create sample uuids to download
      val data = for (x <- 1 to numUuids) yield s"uuid$x\n"

      // wiremock stubbing
      stubFor(post(urlPathMatching("/_out.*"))
        .willReturn(aResponse()
          .withBody("body")
          .withStatus(StatusCodes.OK.intValue)))

      // create uuid input-stream
      val in = Source.fromIterator(() => data.iterator)
        .map(ByteString.apply)
        .runWith(StreamConverters.asInputStream())

      // download mock data
      Await.result (
        Downloader.downloadFromUuidInputStream(
          baseUrl = s"$host:$port",
          numInfotonsPerRequest = numUuidsPerRequest,
          in = in)
        ,30.seconds
      )

      // verifying
      val numBlocksSent = findAll(postRequestedFor((urlPathMatching("/_out.*")))).size

      // teardown wiremock
      wireMockServer.shutdown()
      wireMockServer.stop()
      while (wireMockServer.isRunning) {}
      wireMockServer.resetRequests()

      numBlocksSent should be (expectedBlocksToSend)

    }
  }
}