org.scalatest.Succeeded Scala Examples

The following examples show how to use org.scalatest.Succeeded. 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: TrackerImplTest.scala    From daml   with Apache License 2.0 5 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.platform.apiserver.services.tracking

import akka.NotUsed
import akka.stream.OverflowStrategy
import akka.stream.scaladsl.{Keep, Source, SourceQueueWithComplete}
import akka.stream.testkit.TestSubscriber
import akka.stream.testkit.scaladsl.TestSink
import com.daml.ledger.api.testing.utils.{
  AkkaBeforeAndAfterAll,
  IsStatusException,
  TestingException
}
import com.daml.ledger.api.v1.command_service.SubmitAndWaitRequest
import com.daml.ledger.api.v1.commands.Commands
import com.daml.ledger.api.v1.completion.Completion
import com.daml.dec.DirectExecutionContext
import com.google.rpc.status.{Status => RpcStatus}
import io.grpc.Status
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterEach, Matchers, Succeeded, WordSpec}

import scala.concurrent.ExecutionContext.Implicits.global

class TrackerImplTest
    extends WordSpec
    with Matchers
    with BeforeAndAfterEach
    with ScalaFutures
    with AkkaBeforeAndAfterAll {

  private var sut: Tracker = _
  private var consumer: TestSubscriber.Probe[NotUsed] = _
  private var queue: SourceQueueWithComplete[TrackerImpl.QueueInput] = _

  private def input(cid: Int) = SubmitAndWaitRequest(Some(Commands(commandId = cid.toString)))

  override protected def beforeEach(): Unit = {
    val (q, sink) = Source
      .queue[TrackerImpl.QueueInput](1, OverflowStrategy.dropNew)
      .map { in =>
        in.context.success(Completion(in.value.getCommands.commandId, Some(RpcStatus())))
        NotUsed
      }
      .toMat(TestSink.probe[NotUsed])(Keep.both)
      .run()
    queue = q
    sut = new TrackerImpl(q)
    consumer = sink
  }

  override protected def afterEach(): Unit = {
    consumer.cancel()
    queue.complete()
  }

  "Tracker Implementation" when {

    "input is submitted, and the queue is available" should {

      "work successfully" in {

        val resultF1 = sut.track(input(1))
        consumer.requestNext()
        val resultF = resultF1.flatMap(_ => sut.track(input(2)))(DirectExecutionContext)
        consumer.requestNext()
        whenReady(resultF)(_ => Succeeded)
      }
    }

    "input is submitted, and the queue is backpressuring" should {

      "return a RESOURCE_EXHAUSTED error" in {

        sut.track(input(1))
        whenReady(sut.track(input(2)).failed)(IsStatusException(Status.RESOURCE_EXHAUSTED))
      }
    }

    "input is submitted, and the queue has been completed" should {

      "return an ABORTED error" in {

        queue.complete()
        whenReady(sut.track(input(2)).failed)(IsStatusException(Status.ABORTED))
      }
    }

    "input is submitted, and the queue has failed" should {

      "return an ABORTED error" in {

        queue.fail(TestingException("The queue fails with this error."))
        whenReady(sut.track(input(2)).failed)(IsStatusException(Status.ABORTED))
      }
    }
  }
} 
Example 2
Source File: GenEncodingSpec.scala    From daml   with Apache License 2.0 5 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.ledger.client.binding.encoding
import com.daml.ledger.client.binding.{Primitive => P}
import org.scalatest.{Succeeded, WordSpec}
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import scalaz.Show

class GenEncodingSpec extends WordSpec with GeneratorDrivenPropertyChecks {
  import ShowEncoding.Implicits._

  implicit override val generatorDrivenConfig = PropertyCheckConfiguration(minSuccessful = 10000)

  "P.Text arbitrary Gen should not generate \\u0000, PostgreSQL does not like it" in forAll(
    GenEncoding.postgresSafe.primitive.valueText) { text: P.Text =>
    val show: Show[P.Text] = implicitly
    if (text.forall(_ != '\u0000')) Succeeded
    else
      fail(
        s"P.Text generator produced a string with unexpected character, text: ${show.show(text)}")
  }

} 
Example 3
Source File: CustomMatcher.scala    From daml   with Apache License 2.0 5 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.scalatest

import org.scalatest.{Assertion, Succeeded}
import scalaz.syntax.show._
import scalaz.{Equal, Show}

object CustomMatcher {

  final implicit class CustomMatcherOps[A](val underlying: A) extends AnyVal {

    def should_===(other: A)(implicit eqEv: Equal[A], showEv: Show[A]): Assertion =
      if (eqEv.equal(underlying, other)) Succeeded
      else reportFailure(underlying, " =/= ", other)

    def should_=/=(other: A)(implicit eqEv: Equal[A], showEv: Show[A]): Assertion =
      if (eqEv.equal(underlying, other)) reportFailure(underlying, " === ", other)
      else Succeeded

    private def reportFailure(underlying: A, str: String, other: A)(
        implicit showEv: Show[A]): Assertion =
      throw CustomMatcherException(s"${underlying.shows}$str${other.shows}")
  }

  case class CustomMatcherException(c: String) extends RuntimeException(c)
} 
Example 4
Source File: TopicMatchers.scala    From kafka-configurator   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.sky.kafka.matchers

import com.sky.kafka.configurator.Topic
import org.scalatest.matchers.{ MatchResult, Matcher }
import org.scalatest.{ Matchers, Succeeded }

trait TopicMatchers extends Matchers {

  class TopicIsEquivalent(right: Topic) extends Matcher[Topic] {
    override def apply(left: Topic) = {
      val name = left.name == right.name
      val partitions = left.partitions == right.partitions
      val replication = left.replicationFactor == right.replicationFactor
      val config = (left.config should contain allElementsOf right.config).isInstanceOf[Succeeded.type]

      MatchResult(
        name && partitions && replication && config,
        s"$left is not equivalent to $right",
        s"$left is equivalent to $right"
      )
    }
  }

  def beEquivalentTo(topic: Topic) = new TopicIsEquivalent(topic)
} 
Example 5
Source File: UdashIconsTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.bootstrap.utils

import com.avsystem.commons.concurrent.RunNowEC
import io.udash.bootstrap.UdashBootstrap
import io.udash.bootstrap.utils.UdashIcons.FontAwesome._
import io.udash.css.{CssStyle, CssView}
import io.udash.properties.single.Property
import io.udash.testing.AsyncUdashCoreFrontendTest
import org.scalajs.dom._
import org.scalatest.Succeeded
import scalatags.JsDom.all._

import scala.concurrent.Future

class UdashIconsTest extends AsyncUdashCoreFrontendTest with CssView {
  override protected def beforeAll(): Unit = document.body.appendChild(UdashBootstrap.loadFontAwesome())

  "Bootstrap icons" should {
    document.body.appendChild(UdashBootstrap.loadFontAwesome())

    "work with .styleIf" in {
      import UdashIcons.FontAwesome.Regular._
      val p: Property[Boolean] = Property(false)
      val el = span(
        addressBook.styleIf(p),
        angry.styleIf(p.transform(!_)),
        heart.styleIf(p)
      ).render

      Future.successful(assert(
        (Iterator(el.classList.length should be(2)) ++ (0 to 10).iterator.map { i =>
          p.set(!p.get)
          el.classList.length should be(if (i % 2 == 0) 3 else 2)
        }).forall(_ == Succeeded)
      ))
    }

    "apply appropriate FontAwesome Free unicodes to the :before pseudoselector" in {
      Future.sequence(
        Iterator(
          valuesOfType[CssStyle](Brands).iterator,
          valuesOfType[CssStyle](Regular).iterator,
          valuesOfType[CssStyle](Solid).iterator
        ).flatten.map { iconStyle =>
          val icon = i(iconStyle).render
          document.body.appendChild(icon)

          (for {
            _ <- retrying {
              window.getComputedStyle(icon).fontFamily should (equal("\"Font Awesome 5 Free\"") or equal("\"Font Awesome 5 Brands\""))
            }
            r <- retrying {
              window.getComputedStyle(icon, ":before").content.replaceAll("\"|\'", "").head.toHexString should
                (startWith("f") and have length 4)
            }
          } yield r).andThen { case _ => document.body.removeChild(icon) }(RunNowEC)
        }
      ).map(assertions => assert(assertions.forall(_ == Succeeded)))
    }
  }
} 
Example 6
Source File: AsyncUdashSharedTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.testing

import org.scalactic.source.Position
import org.scalajs.dom
import org.scalatest.{Assertion, Succeeded}

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.scalajs.concurrent.JSExecutionContext
import scala.scalajs.js.Date
import scala.util.{Failure, Success}

trait AsyncUdashSharedTest extends AsyncUdashSharedTestBase {
  override implicit def executionContext: ExecutionContext = JSExecutionContext.queue

  override def retrying(code: => Any)(implicit patienceConfig: PatienceConfig, pos: Position): Future[Assertion] = {
    val start = Date.now()
    val p = Promise[Assertion]
    var lastEx: Option[Throwable] = None
    def startTest(): Unit = {
      dom.window.setTimeout(() => {
        if (patienceConfig.timeout.toMillis > Date.now() - start) {
          try {
            code
            p.complete(Success(Succeeded))
          } catch {
            case ex: Throwable =>
              lastEx = Some(ex)
              startTest()
          }
        } else {
          p.complete(Failure(lastEx.getOrElse(RetryingTimeout())))
        }
      }, patienceConfig.interval.toMillis.toDouble)
    }
    startTest()
    p.future
  }
} 
Example 7
Source File: PartitionsToSegmentsTest.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.replicator

import cats.data.{NonEmptySet => Nes}
import cats.implicits._
import com.evolutiongaming.kafka.journal.eventual.cassandra.{SegmentNr, Segments}
import com.evolutiongaming.catshelper.DataHelper._
import com.evolutiongaming.skafka.Partition
import org.scalatest.Succeeded
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers

import scala.collection.immutable.SortedSet
import scala.util.Try

class PartitionsToSegmentsTest extends AnyFunSuite with Matchers {
  for {
    (partitions, partitionNrs, segmentNrs) <- List(
      (20,  Nes.of(0),       SortedSet(0, 20, 40, 60, 80)),
      (30,  Nes.of(0),       SortedSet(0, 30, 60, 90)),
      (100, Nes.of(0, 1, 2), SortedSet(0, 1, 2)),
      (1,   Nes.of(0),       (0 until 100).toSortedSet))
  } {
    test(s"partitions: $partitions, segmentNrs: $segmentNrs, partitionNrs: $partitionNrs") {
      val result = for {
        segmentNrs           <- segmentNrs.toList.traverse { a => SegmentNr.of[Try](a.toLong) }
        partitionNrs         <- partitionNrs.toNel.traverse { a => Partition.of[Try](a) }
        partitionsToSegments <- PartitionsToSegments.of[Try](partitions, Segments.default)
      } yield {
        val actual = partitionsToSegments(partitionNrs.toNes)
        actual shouldEqual segmentNrs.toSortedSet
      }
      result shouldEqual Succeeded.pure[Try]
    }
  }
} 
Example 8
Source File: IOSuite.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal

import cats.Parallel
import cats.effect.{Clock, Concurrent, ContextShift, IO, Timer}
import cats.implicits._
import com.evolutiongaming.smetrics.MeasureDuration
import org.scalatest.Succeeded

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

object IOSuite {
  val Timeout: FiniteDuration = 5.seconds

  implicit val executor: ExecutionContextExecutor = ExecutionContext.global

  implicit val contextShiftIO: ContextShift[IO]     = IO.contextShift(executor)
  implicit val concurrentIO: Concurrent[IO]         = IO.ioConcurrentEffect
  implicit val timerIO: Timer[IO]                   = IO.timer(executor)
  implicit val parallel: Parallel[IO]               = IO.ioParallel
  implicit val measureDuration: MeasureDuration[IO] = MeasureDuration.fromClock(Clock[IO])

  def runIO[A](io: IO[A], timeout: FiniteDuration = Timeout): Future[Succeeded.type] = {
    io.timeout(timeout).as(Succeeded).unsafeToFuture
  }

  implicit class IOOps[A](val self: IO[A]) extends AnyVal {
    def run(timeout: FiniteDuration = Timeout): Future[Succeeded.type] = runIO(self, timeout)
  }
} 
Example 9
Source File: ScratchTests.scala    From ScalaClean   with Apache License 2.0 5 votes vote down vote up
package scalaclean

import org.scalatest.{ Canceled, Failed, OutcomeOf, Pending, Succeeded }
import org.scalatest.exceptions.TestPendingException

class ScratchTests extends AbstractProjectTests {
  test("scratch") {
    OutcomeOf.outcomeOf(deadCodeProjectTest("scratch")) match {
      case Succeeded   =>
      case Canceled(e) => throw e
      case Pending     => throw new TestPendingException()
      case Failed(e)   =>
        Console.err.println(e)
        e.getStackTrace.take(7).foreach(e => Console.err.println(s"\tat $e"))
        throw new TestPendingException()
    }
  }

//  test("scratch1") {
//    privatiserProjectTest("scratch1")
//  }
//
} 
Example 10
Source File: TrackingSpec.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package cmwell.tracking

import cmwell.util.string.Base64.encodeBase64URLSafeString
import org.scalatest.{FlatSpec, Matchers, Succeeded}


class TrackingSpec extends FlatSpec with Matchers {
  "TrackingId encode decode" should "be successful" in {
    val actorId = "myAwesomeActor"
    val originalTid = TrackingId(actorId)

    originalTid.token match {
      case TrackingId(extractedTid) => extractedTid should equal(originalTid)
      case _ => Failed
    }
  }

  "Malformed token (not base64)" should "be None when unapplied" in
    assertNotValid("bla bla")

  "Malformed token (without createTime)" should "be None when unapplied" in
    assertNotValid(encodeBase64URLSafeString("id"))

  "Malformed token (malformed createTime)" should "be None when unapplied" in
    assertNotValid(encodeBase64URLSafeString("id|not-a-long"))

  private def assertNotValid(payload: String) = payload match {
    case TrackingId(_) => Failed
    case _ => Succeeded
  }
} 
Example 11
Source File: AdditionalAssertions.scala    From ScalaWebTest   with Apache License 2.0 5 votes vote down vote up
package org.scalawebtest.integration

import org.scalactic.source.Position
import org.scalatest.{Assertion, Succeeded, Suite}

import scala.reflect.ClassTag

trait AdditionalAssertions {self: Suite =>
    def assertThrowsAndTestMessage[T <: AnyRef](f: => Any)(messageTest: String => Assertion)(implicit classTag: ClassTag[T], pos: Position): Assertion = {
    val clazz = classTag.runtimeClass
    val threwExpectedException =
      try {
        f
        false
      }
      catch {
          case u: Throwable =>
            messageTest(u.getMessage)
            if (!clazz.isAssignableFrom(u.getClass)) {
              fail(s"didn't throw expected exception ${clazz.getCanonicalName}")
            }
            else true
      }
    if (threwExpectedException) {
      Succeeded
    }
    else {
      fail(s"didn't throw expected exception ${clazz.getCanonicalName}")
    }
  }

} 
Example 12
Source File: IOSuite.scala    From skafka   with MIT License 5 votes vote down vote up
package com.evolutiongaming.skafka

import cats.Parallel
import cats.effect.{Clock, Concurrent, ContextShift, IO, Timer}
import cats.implicits._
import com.evolutiongaming.catshelper.FromFuture
import com.evolutiongaming.smetrics.MeasureDuration
import org.scalatest.Succeeded

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

object IOSuite {
  val Timeout: FiniteDuration = 10.seconds

  implicit val executor: ExecutionContextExecutor = ExecutionContext.global

  implicit val contextShiftIO: ContextShift[IO]     = IO.contextShift(executor)
  implicit val concurrentIO: Concurrent[IO]         = IO.ioConcurrentEffect
  implicit val timerIO: Timer[IO]                   = IO.timer(executor)
  implicit val parallelIO: Parallel[IO]             = IO.ioParallel
  implicit val fromFutureIO: FromFuture[IO]         = FromFuture.lift[IO]
  implicit val measureDuration: MeasureDuration[IO] = MeasureDuration.fromClock[IO](Clock[IO])

  def runIO[A](io: IO[A], timeout: FiniteDuration = Timeout): Future[Succeeded.type] = {
    io.timeout(timeout).as(Succeeded).unsafeToFuture
  }

  implicit class IOOps[A](val self: IO[A]) extends AnyVal {
    def run(timeout: FiniteDuration = Timeout): Future[Succeeded.type] = runIO(self, timeout)
  }
} 
Example 13
Source File: EffectTestSupport.scala    From cats-effect-testing   with Apache License 2.0 5 votes vote down vote up
package cats.effect.testing.scalatest

import cats.effect._
import cats.implicits._
import scala.concurrent.Future
import org.scalatest.{Assertion, Succeeded}


trait EffectTestSupport {

  implicit def syncIoToFutureAssertion(io: SyncIO[Assertion]): Future[Assertion] =
    io.toIO.unsafeToFuture
  implicit def ioToFutureAssertion(io: IO[Assertion]): Future[Assertion] =
    io.unsafeToFuture
  implicit def syncIoUnitToFutureAssertion(io: SyncIO[Unit]): Future[Assertion] =
    io.toIO.as(Succeeded).unsafeToFuture
  implicit def ioUnitToFutureAssertion(io: IO[Unit]): Future[Assertion] =
    io.as(Succeeded).unsafeToFuture
} 
Example 14
Source File: AssertingSyntax.scala    From cats-effect-testing   with Apache License 2.0 5 votes vote down vote up
package cats.effect.testing.scalatest

import cats.Functor
import cats.effect.Sync
import org.scalatest.{Assertion, Assertions, Succeeded}
import cats.implicits._


    def assertThrows[E <: Throwable](implicit F: Sync[F], ct: reflect.ClassTag[E]): F[Assertion] =
      self.attempt.flatMap {
        case Left(t: E) => F.pure(Succeeded: Assertion)
        case Left(t) =>
          F.delay(
            fail(
              s"Expected an exception of type ${ct.runtimeClass.getName} but got an exception: $t"
            )
          )
        case Right(a) =>
          F.delay(
            fail(s"Expected an exception of type ${ct.runtimeClass.getName} but got a result: $a")
          )
      }
  }
} 
Example 15
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 16
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))
  }
}