org.scalatest.concurrent.PatienceConfiguration.Timeout Scala Examples

The following examples show how to use org.scalatest.concurrent.PatienceConfiguration.Timeout. 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: ApplicationSpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
import org.scalatest.Matchers._
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Seconds, Span}
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.libs.ws.WSClient
import play.api.test.Helpers._
import scala.concurrent.duration._



class ApplicationSpec extends PlaySpec with ScalaFutures with GuiceOneServerPerSuite {
  "Application" should {
    val wsClient = app.injector.instanceOf[WSClient]
    val myPublicAddress = s"localhost:$port"

    "send 404 on a bad request" in {
      val testURL = s"http://$myPublicAddress/boom"

      whenReady(wsClient.url(testURL).get(), Timeout(1 second)) { response =>
        response.status mustBe NOT_FOUND
      }
    }

    "render the index page" in {
      val testURL = s"http://$myPublicAddress/"

      whenReady(wsClient.url(testURL).get(), Timeout(1 second)) { response =>
        response.status mustBe OK
        response.contentType should include("text/html")
      }
    }
  }
} 
Example 2
Source File: RepositoryBundleLoaderSpec.scala    From mleap   with Apache License 2.0 5 votes vote down vote up
package ml.combust.mleap.executor.repository

import ml.combust.mleap.executor.testkit.TestUtil
import ml.combust.mleap.runtime.transformer.Pipeline
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.{FunSpec, Matchers}
import org.scalatest.concurrent.ScalaFutures

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext

class RepositoryBundleLoaderSpec extends FunSpec with ScalaFutures with Matchers {

  describe("repository bundle loader") {

    implicit val executionContext = ExecutionContext.Implicits.global

    it("loads bundle successfully") {
      val repo = new FileRepository()
      val bundleLoader = new RepositoryBundleLoader(repo, executionContext)
      val result = bundleLoader.loadBundle(TestUtil.lrUri)
      whenReady(result, Timeout(10.seconds)) {
        bundle => bundle.root shouldBe a [Pipeline]
      }

      repo.shutdown()
    }
  }
} 
Example 3
Source File: InitialSpec.scala    From embedded-kafka   with Apache License 2.0 5 votes vote down vote up
package com.tuplejump.embedded.kafka

import java.util.concurrent.{TimeUnit, CountDownLatch}

import org.apache.kafka.common.serialization.StringDeserializer
import org.scalatest.concurrent.Eventually
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.time.{Millis, Span}

class InitialSpec extends AbstractSpec with Eventually with Logging {

  private val timeout = Timeout(Span(10000, Millis))

  "Initially, EmbeddedKafka" must {
    val kafka = new EmbeddedKafka()
    val topic = "test"
    val total = 1000
    val latch = new CountDownLatch(total)

    "start embedded zookeeper and embedded kafka" in {
      kafka.isRunning should be (false)
      kafka.start()
      eventually(timeout)(kafka.isRunning)
    }
    "create a topic" in {
      kafka.createTopic(topic, 1, 1)
    }
    "publish messages to the embedded kafka instance" in {
      val config = kafka.consumerConfig(
        group = "some.group",
        kafkaConnect = kafka.kafkaConfig.hostName + ":" + kafka.kafkaConfig.port,
        zkConnect = kafka.kafkaConfig.zkConnect,
        offsetPolicy = "largest",//latest with new consumer
        autoCommitEnabled = true,
        kDeserializer = classOf[StringDeserializer],
        vDeserializer = classOf[StringDeserializer])
      val consumer = new SimpleConsumer(latch, config, topic, "consumer.group", 1, 1)

      val batch1 = for (n <- 0 until total) yield s"message-test-$n"

      logger.info(s"Publishing ${batch1.size} messages...")

      kafka.sendMessages(topic, batch1)
      latch.await(10000, TimeUnit.MILLISECONDS)
      latch.getCount should be (0)

      consumer.shutdown()
    }
    "shut down relatively cleanly for now" in {
      kafka.shutdown()
      eventually(timeout)(!kafka.isRunning)
    }
  }
} 
Example 4
Source File: HttpDeleteSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import akka.actor.ActorSystem
import com.typesafe.config.Config
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.{any, eq => is}
import org.mockito.Mockito._
import org.scalatest.concurrent.PatienceConfiguration.{Interval, Timeout}
import org.scalatest.time.{Millis, Seconds, Span}
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar
import uk.gov.hmrc.http.hooks.HttpHook

import scala.concurrent.{ExecutionContext, Future}

import uk.gov.hmrc.http.HttpReads.Implicits._

class HttpDeleteSpec extends AnyWordSpecLike with Matchers with MockitoSugar with CommonHttpBehaviour {

  import ExecutionContext.Implicits.global

  class StubbedHttpDelete(doDeleteResult: Future[HttpResponse], doDeleteWithHeaderResult: Future[HttpResponse]) extends HttpDelete with ConnectionTracingCapturing {
    val testHook1                                   = mock[HttpHook]
    val testHook2                                   = mock[HttpHook]
    val hooks                                       = Seq(testHook1, testHook2)
    override def configuration: Option[Config]      = None
    override protected def actorSystem: ActorSystem = ActorSystem("test-actor-system")

    def appName: String = ???

    def doDelete(url: String, headers: Seq[(String, String)])(implicit hc: HeaderCarrier, ec: ExecutionContext) =
      doDeleteResult
  }

  "HttpDelete" should {
    "be able to return plain responses" in {
      val response   = HttpResponse(200, testBody)
      val testDelete = new StubbedHttpDelete(Future.successful(response), Future.successful(response))
      testDelete.DELETE[HttpResponse](url, Seq("foo" -> "bar")).futureValue shouldBe response
    }

    "be able to return objects deserialised from JSON" in {
      val testDelete = new StubbedHttpDelete(Future.successful(HttpResponse(200, """{"foo":"t","bar":10}""")),
        Future.successful(HttpResponse(200, """{"foo":"t","bar":10}""")))
      testDelete
        .DELETE[TestClass](url, Seq("foo" -> "bar"))
        .futureValue(Timeout(Span(2, Seconds)), Interval(Span(15, Millis))) shouldBe TestClass("t", 10)
    }

    behave like anErrorMappingHttpCall("DELETE", (url, responseF) => new StubbedHttpDelete(responseF, responseF).DELETE[HttpResponse](url, Seq("foo" -> "bar")))
    behave like aTracingHttpCall("DELETE", "DELETE", new StubbedHttpDelete(defaultHttpResponse, defaultHttpResponse)) { _.DELETE[HttpResponse](url, Seq("foo" -> "bar")) }

    "Invoke any hooks provided" in {
      val dummyResponse       = HttpResponse(200, testBody)
      val dummyResponseFuture = Future.successful(dummyResponse)
      val dummyHeader         = Future.successful(dummyResponse)
      val testDelete          = new StubbedHttpDelete(dummyResponseFuture, dummyHeader)

      testDelete.DELETE[HttpResponse](url, Seq("header" -> "foo")).futureValue

      val respArgCaptor1 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]])
      val respArgCaptor2 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]])

      verify(testDelete.testHook1).apply(is(url), is("DELETE"), is(None), respArgCaptor1.capture())(any(), any())
      verify(testDelete.testHook2).apply(is(url), is("DELETE"), is(None), respArgCaptor2.capture())(any(), any())

      // verifying directly without ArgumentCaptor didn't work as Futures were different instances
      // e.g. Future.successful(5) != Future.successful(5)
      respArgCaptor1.getValue.futureValue shouldBe dummyResponse
      respArgCaptor2.getValue.futureValue shouldBe dummyResponse
    }
  }
} 
Example 5
Source File: JavascriptExecutorSpec.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.javascriptEngine

import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.{FlatSpec, Matchers}
import org.scalatest.concurrent.ScalaFutures._

import scala.concurrent.Future
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global

class JavascriptExecutorSpec extends FlatSpec with Matchers {
  "engine" should "execute simple script" in {

    val before = System.currentTimeMillis()

    JavascriptExecutor.execute("""
        |console.log(42)
        |
        |console.log(43 + 2 + "lalala")
      """.stripMargin).futureValue(Timeout(Duration.Inf)) should be(Result("42\n45lalala\n", ""))

    println("1 (initial): " + (System.currentTimeMillis() - before))

    val before2 = System.currentTimeMillis()

    JavascriptExecutor.execute("""
                                 |console.log(42)
                                 |
                                 |console.log(43 + 2 + "lalala")
                               """.stripMargin).futureValue(Timeout(Duration.Inf)) should be(Result("42\n45lalala\n", ""))

    println("1 (warm): " + (System.currentTimeMillis() - before2))

    val before3 = System.currentTimeMillis()

    (1 to 10).foreach(_ => JavascriptExecutor.execute("""
                                                        |console.log(42)
                                                        |
                                                        |console.log(43 + 2 + "lalala")
                                                      """.stripMargin).futureValue(Timeout(Duration.Inf)) should be(Result("42\n45lalala\n", "")))

    println("10 (seq): " + (System.currentTimeMillis() - before3))

    val before4 = System.currentTimeMillis()

    Future.sequence((1 to 10).map(_ => JavascriptExecutor.execute("""
                                     |console.log(42)
                                     |
                                     |console.log(43 + 2 + "lalala")
                                   """.stripMargin))).futureValue(Timeout(Duration.Inf))

    println("10 (par): " + (System.currentTimeMillis() - before4))

    val before5 = System.currentTimeMillis()

    Future.sequence((1 to 100).map(_ => JavascriptExecutor.execute("""
                                                                    |console.log(42)
                                                                    |
                                                                    |console.log(43 + 2 + "lalala")
                                                                  """.stripMargin))).futureValue(Timeout(Duration.Inf))

    println("100 (par): " + (System.currentTimeMillis() - before5))

    val before6 = System.currentTimeMillis()

    Future
      .sequence((1 to 1000).map(_ => JavascriptExecutor.execute("""
                                                                     |console.log(42)
                                                                     |
                                                                     |console.log(43 + 2 + "lalala")
                                                                   """.stripMargin)))
      .futureValue(Timeout(Duration.Inf))

    println("1000 (par): " + (System.currentTimeMillis() - before6))

  }
} 
Example 6
Source File: ChatControllerSpec.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package controllers

import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatestplus.play._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test._
import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient
import play.shaded.ahc.org.asynchttpclient.ws.WebSocket

import scala.compat.java8.FutureConverters
import scala.concurrent.Await
import scala.concurrent.duration._

class ChatControllerSpec extends PlaySpec with ScalaFutures with IntegrationPatience {

  "ChatController" should {

    "reject a websocket flow if the origin is set incorrectly" in WsTestClient.withClient { client =>

      // Pick a non standard port that will fail the (somewhat contrived) origin check...
      lazy val port: Int = 31337
      val app = new GuiceApplicationBuilder().build()
      Helpers.running(TestServer(port, app)) {
        val myPublicAddress = s"localhost:$port"
        val serverURL = s"ws://$myPublicAddress/chat"

        val asyncHttpClient: AsyncHttpClient = client.underlying[AsyncHttpClient]

        val webSocketClient = new WebSocketClient(asyncHttpClient)
        try {
          val origin = "ws://example.com/ws/chat"
          val listener = new WebSocketClient.LoggingListener
          val completionStage = webSocketClient.call(serverURL, origin, listener)
          val f = FutureConverters.toScala(completionStage)
          val result = Await.result(f, atMost = 1000 millis)
          listener.getThrowable mustBe a[IllegalStateException]
        } catch {
          case e: IllegalStateException =>
            e mustBe an [IllegalStateException]

          case e: java.util.concurrent.ExecutionException =>
            val foo = e.getCause
            foo mustBe an [IllegalStateException]
        }
      }
    }

    "accept a websocket flow if the origin is set correctly" in WsTestClient.withClient { client =>
      lazy val port: Int = Helpers.testServerPort
      val app = new GuiceApplicationBuilder().build()
      Helpers.running(TestServer(port, app)) {
        val myPublicAddress = s"localhost:$port"
        val serverURL = s"ws://$myPublicAddress/chat"

        val asyncHttpClient: AsyncHttpClient = client.underlying[AsyncHttpClient]

        val webSocketClient = new WebSocketClient(asyncHttpClient)

        val origin = serverURL
        val listener = new WebSocketClient.LoggingListener
        val completionStage = webSocketClient.call(serverURL, origin, listener)
        val f = FutureConverters.toScala(completionStage)

        whenReady(f, timeout = Timeout(1 second)) { webSocket =>
          webSocket mustBe a [WebSocket]
        }
      }
    }
  }

} 
Example 7
Source File: AliasTest.scala    From sumobot   with Apache License 2.0 5 votes vote down vote up
package com.sumologic.sumobot.plugins.alias

import akka.actor.{ActorSystem, Props}
import akka.testkit.TestProbe
import com.sumologic.sumobot.brain.InMemoryBrain
import com.sumologic.sumobot.core.model.IncomingMessage
import com.sumologic.sumobot.plugins.BotPlugin.InitializePlugin
import com.sumologic.sumobot.test.annotated.BotPluginTestKit
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import scala.concurrent.duration._
import org.scalatest.{Matchers, WordSpecLike}
import org.scalatest.concurrent.Eventually._

class AliasTest
  extends BotPluginTestKit(ActorSystem("AliasTest")) {

  val aliasRef = system.actorOf(Props(classOf[Alias]), "alias")
  val brainRef = system.actorOf(Props(classOf[InMemoryBrain]), "brain")
  aliasRef ! InitializePlugin(null, brainRef, null)

  "alias" should {
    "allow aliasing messages to the bot" in {
      send(instantMessage("alias 'foo' to 'bar'"))
      val otherPlugin = TestProbe()
      system.eventStream.subscribe(otherPlugin.ref, classOf[IncomingMessage])
      send(instantMessage("foo"))
      eventually(Timeout(5.seconds)) {
        val messages = otherPlugin.expectMsgAllClassOf(classOf[IncomingMessage])
        messages.foreach(msg => println(msg.canonicalText))
        messages.exists(_.canonicalText == "bar") should be (true)
      }
    }
  }
}