org.specs2.specification.AfterAll Scala Examples

The following examples show how to use org.specs2.specification.AfterAll. 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: SubscriptionsSpec.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi

import java.util.UUID

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import org.mdedetrich.webmodels.FlowId
import org.specs2.Specification
import org.specs2.concurrent.ExecutionEnv
import org.specs2.specification.core.SpecStructure
import org.specs2.specification.{AfterAll, BeforeAll}
import org.zalando.kanadi.api.{Category, EventType, EventTypes, Events, Subscription, Subscriptions}
import org.zalando.kanadi.models.{EventTypeName, SubscriptionId}

import scala.collection.parallel.mutable
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

class SubscriptionsSpec(implicit ec: ExecutionEnv) extends Specification with Config with BeforeAll with AfterAll {
  override def is: SpecStructure = sequential ^ s2"""
      Create enough subscriptions to ensure that pagination is used $createEnoughSubscriptionsToUsePagination
    """

  val config = ConfigFactory.load()

  implicit val system       = ActorSystem()
  implicit val http         = Http()
  implicit val materializer = ActorMaterializer()

  val eventTypeName         = EventTypeName(s"Kanadi-Test-Event-${UUID.randomUUID().toString}")
  val OwningApplication     = "KANADI"
  val consumerGroup: String = UUID.randomUUID().toString
  val subscriptionsClient =
    Subscriptions(nakadiUri, None)
  val eventsClient = Events(nakadiUri, None)
  val eventsTypesClient =
    EventTypes(nakadiUri, None)
  val subscriptionIds: mutable.ParSet[SubscriptionId] = mutable.ParSet.empty

  eventTypeName.pp
  s"Consumer Group: $consumerGroup".pp

  def createEventType = eventsTypesClient.create(EventType(eventTypeName, OwningApplication, Category.Business))

  override def beforeAll =
    Await.result(createEventType, 10 seconds)

  override def afterAll = {
    Await.result(
      for {
        res1 <- Future.sequence(subscriptionIds.toList.map(s => subscriptionsClient.delete(s)))
        res2 <- eventsTypesClient.delete(eventTypeName)
      } yield (res1, res2),
      10 seconds
    )
    ()
  }

  def createEnoughSubscriptionsToUsePagination = (name: String) => {
    implicit val flowId: FlowId = Utils.randomFlowId()
    flowId.pp(name)

    val createdSubscriptions = Future.sequence(for {
      _ <- 1 to 22
      subscription = subscriptionsClient.create(
        Subscription(None, s"$OwningApplication-${UUID.randomUUID().toString}", Some(List(eventTypeName))))
    } yield {
      subscription.foreach { s =>
        subscriptionIds += s.id.get
      }
      subscription
    })

    val retrievedSubscriptions = (for {
      subscriptions <- createdSubscriptions
      retrievedSubscription = Future.sequence(subscriptions.map { subscription =>
        subscriptionsClient.createIfDoesntExist(subscription)
      })
    } yield retrievedSubscription).flatMap(a => a)

    Await.result(createdSubscriptions, 10 seconds) mustEqual Await.result(retrievedSubscriptions, 10 seconds)
  }

} 
Example 2
Source File: JsonRequestSpec.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws.ahc

import java.nio.charset.StandardCharsets

import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.util.ByteString
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.when
import org.specs2.mock.Mockito

import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.api.libs.json.JsString
import play.api.libs.json.JsValue
import play.api.libs.json.Json
import play.api.libs.ws.JsonBodyReadables
import play.api.libs.ws.JsonBodyWritables
import play.libs.ws.DefaultObjectMapper
import play.shaded.ahc.org.asynchttpclient.Response

import scala.io.Codec


class JsonRequestSpec extends Specification with Mockito with AfterAll with JsonBodyWritables {
  sequential

  implicit val system       = ActorSystem()
  implicit val materializer = Materializer.matFromSystem

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

  "set a json node" in {
    val jsValue = Json.obj("k1" -> JsString("v1"))
    val client  = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(jsValue)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("application/json")
    ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
  }

  "set a json node using the default object mapper" in {
    val objectMapper = DefaultObjectMapper.instance

    implicit val jsonReadable = body(objectMapper)
    val jsonNode              = objectMapper.readTree("""{"k1":"v1"}""")
    val client                = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(jsonNode)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("application/json")
    ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
  }

  "read an encoding of UTF-8" in {
    val json = io.Source.fromResource("test.json")(Codec.ISO8859).getLines.mkString

    val ahcResponse = mock[Response]
    val response    = new StandaloneAhcWSResponse(ahcResponse)

    when(ahcResponse.getResponseBody(StandardCharsets.UTF_8)).thenReturn(json)
    when(ahcResponse.getContentType).thenReturn("application/json")

    val value: JsValue = JsonBodyReadables.readableAsJson.transform(response)
    verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.UTF_8)
    verify(ahcResponse, times(1)).getContentType
    value.toString must beEqualTo(json)
  }

  "read an encoding of ISO-8859-1" in {
    val json = io.Source.fromResource("test.json")(Codec.ISO8859).getLines.mkString

    val ahcResponse = mock[Response]
    val response    = new StandaloneAhcWSResponse(ahcResponse)

    when(ahcResponse.getResponseBody(StandardCharsets.ISO_8859_1)).thenReturn(json)
    when(ahcResponse.getContentType).thenReturn("application/json;charset=iso-8859-1")

    val value: JsValue = JsonBodyReadables.readableAsJson.transform(response)
    verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.ISO_8859_1)
    verify(ahcResponse, times(1)).getContentType
    value.toString must beEqualTo(json)
  }
} 
Example 3
Source File: CachingSpec.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws.ahc.cache

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Route
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.FutureMatchers
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.AkkaServerProvider
import play.api.libs.ws.ahc._
import play.shaded.ahc.org.asynchttpclient._

import scala.concurrent.Future

class CachingSpec(implicit val executionEnv: ExecutionEnv)
    extends Specification
    with AkkaServerProvider
    with AfterAll
    with FutureMatchers
    with Mockito {

  val asyncHttpClient: AsyncHttpClient = {
    val config                           = AhcWSClientConfigFactory.forClientConfig()
    val ahcConfig: AsyncHttpClientConfig = new AhcConfigBuilder(config).build()
    new DefaultAsyncHttpClient(ahcConfig)
  }

  override val routes: Route = {
    import akka.http.scaladsl.server.Directives._
    path("hello") {
      respondWithHeader(RawHeader("Cache-Control", "public")) {
        val httpEntity = HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>")
        complete(httpEntity)
      }
    }
  }

  override def afterAll = {
    super.afterAll()
    asyncHttpClient.close()
  }

  "GET" should {

    "work once" in {
      val cache = mock[Cache]
      cache.get(any[EffectiveURIKey]()).returns(Future.successful(None))

      val cachingAsyncHttpClient = new CachingAsyncHttpClient(asyncHttpClient, new AhcHttpCache(cache))
      val ws                     = new StandaloneAhcWSClient(cachingAsyncHttpClient)

      ws.url(s"http://localhost:$testServerPort/hello")
        .get()
        .map { response =>
          response.body must be_==("<h1>Say hello to akka-http</h1>")
        }
        .await

      there.was(one(cache).get(EffectiveURIKey("GET", new java.net.URI(s"http://localhost:$testServerPort/hello"))))
    }
  }
} 
Example 4
Source File: RemoteSpecs.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema

import com.eclipsesource.schema.drafts.Version4
import com.eclipsesource.schema.test.{Assets, JsonSpec}
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import org.specs2.specification.core.Fragments
import org.specs2.specification.dsl.Online
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc.DefaultActionBuilder
import play.api.test.TestServer

class RemoteSpecs extends Specification with JsonSpec with Online with AfterAll {

  import Version4._

  implicit val validator: SchemaValidator = {
    SchemaValidator(Some(Version4)).addSchema(
      "http://localhost:1234/scope_foo.json",
      JsonSource.schemaFromString(
        """{
          |  "definitions": {
          |    "bar": { "type": "string" }
          |  }
          |}""".stripMargin
      ).get
    )
  }

  def createApp: Application = new GuiceApplicationBuilder()
    .appRoutes(app => {
      val Action = app.injector.instanceOf[DefaultActionBuilder]
      Assets.routes(Action)(getClass, "remotes/")
    })
    .build()

  lazy val server = TestServer(port = 1234, createApp)

  def afterAll: Unit = {
    server.stop
    Thread.sleep(1000)
  }

  def validateAjv(testName: String): Fragments = validate(testName, "ajv_tests")

  sequential

  "Validation from remote resources is possible" >> {
    {
      server.start
      Thread.sleep(1000)
    } must not(throwAn[Exception]) continueWith {
      validateMultiple(
        "ajv_tests" -> Seq(
          "5_adding_dependency_after",
          "5_recursive_references",
          "12_restoring_root_after_resolve",
          "13_root_ref_in_ref_in_remote_ref",
          "14_ref_in_remote_ref_with_id",
          "62_resolution_scope_change"
        ),
        "draft4" -> Seq("refRemote")
      )
    }
  }

  validateAjv("1_ids_in_refs")
} 
Example 5
Source File: Specs2RouteTest.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container

import akka.http.scaladsl.testkit.{RouteTest, TestFrameworkInterface}
import org.specs2.execute.{Failure, FailureException}
import org.specs2.specification.AfterAll
import org.specs2.specification.core.{Fragments, SpecificationStructure}
import org.specs2.specification.dsl.ActionDsl

trait Specs2Interface extends TestFrameworkInterface with SpecificationStructure with ActionDsl with AfterAll {

  def afterAll(): Unit = {
    cleanUp()
  }

  def failTest(msg: String) = {
    val trace = new Exception().getStackTrace.toList
    val fixedTrace = trace.drop(trace.indexWhere(_.getClassName.startsWith("org.specs2")) - 1)
    throw new FailureException(Failure(msg, stackTrace = fixedTrace))
  }

  override def map(fs: ⇒ Fragments) = super.map(fs).append(step(cleanUp()))
}

trait Specs2RouteTest extends RouteTest with Specs2Interface