org.scalatest.compatible.Assertion Scala Examples

The following examples show how to use org.scalatest.compatible.Assertion. 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: ModelReprSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package core

import cats.implicits._

import org.scalatest.compatible.Assertion

class ModelReprSpec extends tests.BaseSpec {

  def roundtrip(m: Model): Assertion = {
    val r = reprFromModel(m)
    val m2 = modelFromRepr(r)
    assert(Model.modelEquality.eqv(m2, m))
    val r2 = reprFromModel(m2)
    assert(ModelRepr.eqInstance.eqv(r2, r))
  }

  private def reprFromModel(m: Model): ModelRepr = {
    ModelRepr.fromModel(m)
  }

  private def modelFromRepr(r: ModelRepr): Model = {
    r.toModel.fold(err => fail(sh"cannot decode ModelRepr: ${err}"), m => m)
  }

  private val modelModel = Reified[Model].model
  private val modelModelRepr = reprFromModel(modelModel)

  "Cycles/Refs" in {
    val modelUnderTest = Model.Vector(
      Model.HCons(
        '_1,
        Atomic[Int].atom,
        Model.HCons(
          '_2,
          modelModel,
          Model.HNil
        )
      )
    )

    roundtrip(modelModel)
    roundtrip(Model.Vector(modelModel))
    roundtrip(modelUnderTest)
  }

  "Long HCons" in {
    val modelUnderTest = Model.Vector(
      'a -> modelModel ::
      'b -> modelModel ::
      'c -> modelModel ::
      'd -> modelModel ::
      'e -> modelModel ::
      'f -> modelModel ::
      'g -> modelModel ::
      'h -> modelModel ::
      Model.HNil
    )

    roundtrip(modelUnderTest)
  }

  final val N = 30000

  "Encoding performance" in {
    (1 to N).map { _ =>
      reprFromModel(modelModel)
    }
  }

  "Decoding performance" in {
    (1 to N).map { _ =>
      modelFromRepr(modelModelRepr)
    }
  }
} 
Example 2
Source File: FutureUtilTest.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.util

import akka.actor.ActorSystem
import org.bitcoins.testkit.util.BitcoinSAsyncTest
import org.scalatest.compatible.Assertion

import scala.concurrent._

class FutureUtilTest extends BitcoinSAsyncTest with BitcoinSLogger {
  it must "execute futures sequentially in the correct order" in {

    val actorSystem = ActorSystem()
    implicit val ec = actorSystem.dispatcher
    val scheduler = actorSystem.scheduler

    val assertionP = Promise[Assertion]()
    val assertionF = assertionP.future

    val promise1 = Promise[Unit]()
    val promise2 = Promise[Unit]()

    val future1 = promise1.future
    val future2 = promise2.future

    future1.onComplete { _ =>
      if (future2.isCompleted) {
        assertionP.failure(new Error(s"future2 completed before future1"))
      }
    }

    future2.onComplete { _ =>
      if (!future1.isCompleted) {
        assertionP.failure(
          new Error(s"future1 was not complete by future2 completing"))
      } else {
        assertionP.success(succeed)
      }
    }

    val futs = FutureUtil.sequentially(List(1, 2)) {
      case 1 =>
        promise1.success(())
        Future.successful(1)
      case 2 =>
        promise2.success(())
        Future.successful(2)

    }

    futs.map(xs => assert(List(1, 2) == xs)).flatMap(_ => assertionF)
  }
} 
Example 3
Source File: Implicits.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.testkit

import org.scalacheck.Gen
import scala.annotation.tailrec
import org.scalatest.compatible.Assertion
import org.scalatest.exceptions.TestFailedException


    def toAssertion: Assertion =
      assertions match {
        case Seq() =>
          throw new TestFailedException(
            message = "Cannot turn an empty list into an assertion!",
            failedCodeStackDepth = 0)
        // this should force all collection kinds to
        // evaluate all their members, throwing when
        // evaluating a bad one
        case nonEmpty =>
          nonEmpty.foreach(_ => ())
          nonEmpty.last
      }
  }
} 
Example 4
Source File: ResilientStreamSpec.scala    From fs2-rabbit   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.fs2rabbit.resiliency

import cats.effect.IO
import cats.effect.concurrent.Ref
import cats.implicits._
import dev.profunktor.fs2rabbit.BaseSpec
import fs2._

import scala.concurrent.duration._
import org.scalatest.compatible.Assertion

class ResilientStreamSpec extends BaseSpec {

  private val sink: Pipe[IO, Int, Unit] = _.evalMap(putStrLn)

  val emptyAssertion: Assertion = true shouldBe true

  it should "run a stream until it's finished" in {
    val program = Stream(1, 2, 3).covary[IO].through(sink)
    ResilientStream.run(program).as(emptyAssertion).unsafeToFuture
  }

  it should "run a stream and recover in case of failure" in {
    val errorProgram = Stream.raiseError[IO](new Exception("on purpose")).through(sink)

    def p(ref: Ref[IO, Int]): Stream[IO, Unit] =
      errorProgram.handleErrorWith { t =>
        Stream.eval(ref.get) flatMap { n =>
          if (n == 0) Stream.eval(IO.unit)
          else Stream.eval(ref.update(_ - 1) *> IO.raiseError(t))
        }
      }

    Ref.of[IO, Int](2).flatMap(r => ResilientStream.run(p(r), 1.second)).as(emptyAssertion).unsafeToFuture
  }

} 
Example 5
Source File: AbstractFetchHttpTest.scala    From sttp   with Apache License 2.0 5 votes vote down vote up
package sttp.client.testing

import org.scalatest.compatible.Assertion
import sttp.client.Response

import scala.concurrent.Future
import scala.language.higherKinds

abstract class AbstractFetchHttpTest[F[_], -S] extends HttpTest[F] {
  override protected def expectRedirectResponse(
      response: F[Response[String]],
      code: Int
  ): Future[Assertion] = {
    response.toFuture().failed.map { t =>
      t.getMessage should be("Unexpected redirect")
    }
  }

  // the fetch spec requires multiple values with the same name to be sorted and joined together...
  // https://fetch.spec.whatwg.org/#concept-header-value
  override protected def cacheControlHeaders = Set("max-age=1000, no-cache")

  // the only way to set the content type is to use a Blob which has a default filename of 'blob'
  override protected def multipartStringDefaultFileName: Option[String] = Some("blob")

  // everything is reported as "scala.scalajs.js.JavaScriptException: TypeError: Failed to fetch"
  override protected def supportsSttpExceptions = false
} 
Example 6
Source File: TransactIntegrationSpec.scala    From neotypes   with MIT License 5 votes vote down vote up
package neotypes

import neotypes.implicits.mappers.all._
import neotypes.implicits.syntax.string._
import neotypes.internal.syntax.async._
import org.neo4j.driver.v1.exceptions.ClientException
import org.scalatest.compatible.Assertion
import scala.concurrent.Future
import scala.reflect.ClassTag


final class TransactIntegrationSpec[F[_]](testkit: EffectTestkit[F]) extends CleaningIntegrationSpec(testkit) {
  behavior of s"Session[${effectName}].transact"

  import TransactIntegrationSpec.CustomException

  private final def ensureCommitedTransaction[T](expectedResults: T)
                                                (txF: Transaction[F] => F[T]): Future[Assertion] =
    executeAsFuture(s => s.transact(txF)).map { results =>
      assert(results == expectedResults)
    }

  private final def ensureRollbackedTransaction[E <: Throwable : ClassTag](txF: Transaction[F] => F[Unit]): Future[Assertion] =
    recoverToSucceededIf[E] {
      executeAsFuture(s => s.transact(txF))
    } flatMap { _ =>
      executeAsFuture(s => "MATCH (n) RETURN count(n)".query[Int].single(s))
    } map { count =>
      assert(count == 0)
    }

  it should "execute & commit multiple queries inside the same transact" in
    ensureCommitedTransaction(expectedResults = List("Luis", "Dmitry")) { tx =>
      for {
        _ <- "CREATE (p: PERSON { name: \"Luis\" })".query[Unit].execute(tx)
        _ <- "CREATE (p: PERSON { name: \"Dmitry\" })".query[Unit].execute(tx)
        r <- "MATCH (p: PERSON) RETURN p.name".query[String].list(tx)
      } yield r
    }

  it should "automatically rollback if any query fails inside a transact" in
    ensureRollbackedTransaction[ClientException] { tx =>
      for {
        _ <- "CREATE (p: PERSON { name: \"Luis\" })".query[Unit].execute(tx)
        _ <- "broken cypher query".query[Unit].execute(tx)
      } yield ()
    }

  it should "automatically rollback if there is an error inside the transact" in
    ensureRollbackedTransaction[CustomException] { tx =>
      for {
        _ <- "CREATE (p: PERSON { name: \"Luis\" })".query[Unit].execute(tx)
        _ <- F.failed[Unit](CustomException)
        _ <- "CREATE (p: PERSON { name: \"Dmitry\" })".query[Unit].execute(tx)
      } yield ()
    }
}

object TransactIntegrationSpec {
  final object CustomException extends Throwable
  type CustomException = CustomException.type
} 
Example 7
Source File: AsyncIntegrationSpec.scala    From neotypes   with MIT License 5 votes vote down vote up
package neotypes

import neotypes.implicits.mappers.all._
import neotypes.implicits.syntax.string._
import org.neo4j.driver.v1.exceptions.ClientException
import org.scalatest.compatible.Assertion
import scala.concurrent.Future
import scala.reflect.ClassTag


final class AsyncIntegrationSpec[F[_]](testkit: EffectTestkit[F]) extends BaseIntegrationSpec(testkit) {
  behavior of s"Async[${effectName}]"

  it should s"execute a simple query" in {
    executeAsFuture { s =>
      "match (p: Person { name: 'Charlize Theron' }) return p.name"
        .query[String]
        .single(s)
    } map { name =>
      assert(name == "Charlize Theron")
    }
  }

  it should s"catch exceptions" in {
    recoverToSucceededIf[ClientException] {
      executeAsFuture { s =>
        "match test return p.name"
          .query[String]
          .single(s)
      }
    }
  }

  override final val initQuery: String = BaseIntegrationSpec.DEFAULT_INIT_QUERY
} 
Example 8
Source File: StreamIntegrationSpec.scala    From neotypes   with MIT License 5 votes vote down vote up
package neotypes

import neotypes.implicits.mappers.all._
import neotypes.implicits.syntax.string._
import org.neo4j.driver.v1.exceptions.ClientException
import org.scalatest.compatible.Assertion
import scala.concurrent.Future
import scala.reflect.ClassTag


final class StreamIntegrationSpec[S[_], F[_]](testkit: StreamTestkit[S, F]) extends BaseStreamSpec(testkit) {
  behavior of s"Stream[${streamName}, ${effectName}]"

  it should s"execute a streaming query" in {
    executeAsFutureList { s =>
      "match (p: Person) return p.name"
        .query[Int]
        .stream(s)
    } map { names =>
      assert(names == (0 to 10).toList)
    }
  }

  it should s"catch exceptions inside the stream" in {
    recoverToSucceededIf[ClientException] {
      executeAsFutureList { s =>
        "match test return p.name"
          .query[String]
          .stream(s)
      }
    }
  }

  override final val initQuery: String = BaseIntegrationSpec.MULTIPLE_VALUES_INIT_QUERY
} 
Example 9
Source File: ConcurrentTests.scala    From cats-effect   with Apache License 2.0 5 votes vote down vote up
package cats.effect

import cats.Eq
import cats.effect.concurrent.Ref
import cats.effect.implicits._
import cats.implicits._
import org.scalatest.compatible.Assertion
import org.scalatest.funsuite.AsyncFunSuite
import org.scalatest.Succeeded
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}

class ConcurrentTests extends AsyncFunSuite with Matchers {
  implicit override def executionContext: ExecutionContext = ExecutionContext.Implicits.global
  implicit val timer: Timer[IO] = IO.timer(executionContext)
  implicit val cs: ContextShift[IO] = IO.contextShift(executionContext)

  private val smallDelay: IO[Unit] = timer.sleep(20.millis)

  private def awaitEqual[A: Eq](t: IO[A], success: A): IO[Unit] =
    t.flatMap(a => if (Eq[A].eqv(a, success)) IO.unit else smallDelay *> awaitEqual(t, success))

  private def run(t: IO[Unit]): Future[Assertion] = t.as(Succeeded).unsafeToFuture()

  test("F.parTraverseN(n)(collection)(f)") {
    val finalValue = 100
    val r = Ref.unsafe[IO, Int](0)
    val list = List.range(0, finalValue)
    val modifies = implicitly[Concurrent[IO]].parTraverseN(3)(list)(_ => IO.shift *> r.update(_ + 1))
    run(IO.shift *> modifies.start *> awaitEqual(r.get, finalValue))
  }

  test("collection.parTraverseN(n)(f)") {
    val finalValue = 100
    val r = Ref.unsafe[IO, Int](0)
    val list = List.range(0, finalValue)
    val modifies = list.parTraverseN(3)(_ => IO.shift *> r.update(_ + 1))
    run(IO.shift *> modifies.start *> awaitEqual(r.get, finalValue))
  }

  test("F.parSequenceN(n)(collection)") {
    val finalValue = 100
    val r = Ref.unsafe[IO, Int](0)
    val list = List.fill(finalValue)(IO.shift *> r.update(_ + 1))
    val modifies = implicitly[Concurrent[IO]].parSequenceN(3)(list)
    run(IO.shift *> modifies.start *> awaitEqual(r.get, finalValue))
  }

  test("collection.parSequenceN(n)") {
    val finalValue = 100
    val r = Ref.unsafe[IO, Int](0)
    val list = List.fill(finalValue)(IO.shift *> r.update(_ + 1))
    val modifies = list.parSequenceN(3)
    run(IO.shift *> modifies.start *> awaitEqual(r.get, finalValue))
  }
} 
Example 10
Source File: AsyncTests.scala    From cats-effect   with Apache License 2.0 5 votes vote down vote up
package cats.effect

import cats.Eq
import cats.effect.concurrent.Ref
import cats.effect.implicits._
import cats.implicits._
import org.scalatest.compatible.Assertion
import org.scalatest.funsuite.AsyncFunSuite
import org.scalatest.Succeeded
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}

class AsyncTests extends AsyncFunSuite with Matchers {
  implicit override def executionContext: ExecutionContext = ExecutionContext.Implicits.global
  implicit val timer: Timer[IO] = IO.timer(executionContext)
  implicit val cs: ContextShift[IO] = IO.contextShift(executionContext)

  private val smallDelay: IO[Unit] = timer.sleep(20.millis)

  private def awaitEqual[A: Eq](t: IO[A], success: A): IO[Unit] =
    t.flatMap(a => if (Eq[A].eqv(a, success)) IO.unit else smallDelay *> awaitEqual(t, success))

  private def run(t: IO[Unit]): Future[Assertion] = t.as(Succeeded).unsafeToFuture()

  test("F.parTraverseN(n)(collection)(f)") {
    val finalValue = 100
    val r = Ref.unsafe[IO, Int](0)
    val list = List.range(0, finalValue)
    val modifies = implicitly[Async[IO]].parTraverseN(3)(list)(_ => IO.shift *> r.update(_ + 1))
    run(IO.shift *> modifies.start *> awaitEqual(r.get, finalValue))
  }

  test("F.parSequenceN(n)(collection)") {
    val finalValue = 100
    val r = Ref.unsafe[IO, Int](0)
    val list = List.fill(finalValue)(IO.shift *> r.update(_ + 1))
    val modifies = implicitly[Async[IO]].parSequenceN(3)(list)
    run(IO.shift *> modifies.start *> awaitEqual(r.get, finalValue))
  }
} 
Example 11
Source File: ResponseFormatsTest.scala    From daml   with Apache License 2.0 4 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http.json

import com.daml.http.util.Collections._

import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.stream.scaladsl.Source
import akka.util.ByteString
import org.scalacheck.Gen
import org.scalatest.compatible.Assertion
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FreeSpec, Inside, Matchers}
import scalaz.syntax.show._
import scalaz.{Show, \/}
import spray.json._

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}

class ResponseFormatsTest
    extends FreeSpec
    with Matchers
    with Inside
    with GeneratorDrivenPropertyChecks {

  implicit val asys: ActorSystem = ActorSystem(this.getClass.getSimpleName)
  implicit val mat: Materializer = Materializer(asys)
  implicit val ec: ExecutionContext = asys.dispatcher

  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 100)

  "resultJsObject should serialize Source of Errors and JsValues" in forAll(
    Gen.listOf(errorOrJsNumber),
    Gen.option(Gen.nonEmptyListOf(Gen.identifier))) { (input, warnings) =>
    import spray.json.DefaultJsonProtocol._

    val jsValWarnings: Option[JsValue] = warnings.map(_.toJson)
    val (failures, successes): (Vector[JsString], Vector[JsValue]) =
      input.toVector.partitionMap(_.leftMap(e => JsString(e.shows)))

    val jsValSource = Source[DummyError \/ JsValue](input)

    val responseF: Future[ByteString] =
      ResponseFormats
        .resultJsObject(jsValSource, jsValWarnings)
        .runFold(ByteString.empty)((b, a) => b ++ a)

    val resultF: Future[Assertion] = responseF.map { str =>
      JsonParser(str.utf8String) shouldBe expectedResult(failures, successes, jsValWarnings)
    }

    Await.result(resultF, 10.seconds)
  }

  private def expectedResult(
      failures: Vector[JsValue],
      successes: Vector[JsValue],
      warnings: Option[JsValue]): JsObject = {

    val map1: Map[String, JsValue] = warnings match {
      case Some(x) => Map("warnings" -> x)
      case None => Map.empty
    }

    val map2 =
      if (failures.isEmpty)
        Map[String, JsValue]("result" -> JsArray(successes), "status" -> JsNumber("200"))
      else
        Map[String, JsValue](
          "result" -> JsArray(successes),
          "errors" -> JsArray(failures),
          "status" -> JsNumber("501"))

    JsObject(map1 ++ map2)
  }

  private lazy val errorOrJsNumber: Gen[DummyError \/ JsNumber] = Gen.frequency(
    1 -> dummyErrorGen.map(\/.left),
    5 -> jsNumberGen.map(\/.right)
  )

  private lazy val dummyErrorGen: Gen[DummyError] = Gen.identifier.map(DummyError.apply)

  private lazy val jsNumberGen: Gen[JsNumber] = Gen.posNum[Long].map(JsNumber.apply)
}

final case class DummyError(message: String)

object DummyError {
  implicit val ShowInstance: Show[DummyError] = Show shows { e =>
    s"DummyError(${e.message})"
  }
}