akka.http.scaladsl.testkit.ScalatestRouteTest Scala Examples

The following examples show how to use akka.http.scaladsl.testkit.ScalatestRouteTest. 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: RealmDirectivesSpec.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.directives

import java.net.URLEncoder

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.commons.http.JsonLdCirceSupport._
import ch.epfl.bluebrain.nexus.commons.test.EitherValues
import ch.epfl.bluebrain.nexus.iam.directives.RealmDirectives._
import ch.epfl.bluebrain.nexus.iam.routes.SearchParams
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.implicits._
import io.circe.generic.auto._
import org.mockito.IdiomaticMockito
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class RealmDirectivesSpec
    extends AnyWordSpecLike
    with ScalatestRouteTest
    with Matchers
    with ScalaFutures
    with EitherValues
    with IdiomaticMockito {

  private def route: Route = {
    (get & searchParams) { params =>
      complete(params)

    }
  }

  private def encode(s: AbsoluteIri) = URLEncoder.encode(s.asString, "UTF-8")

  "Realm directives" should {
    "return query params" in {
      val createdBy: AbsoluteIri = url"http://example.com/created"
      val updatedBy: AbsoluteIri = url"http://example.com/updated"
      val tpe: AbsoluteIri       = url"http://example.com/tpe"
      val tpe2: AbsoluteIri      = url"http://example.com/tpe2"
      Get(
        s"/?rev=2&deprecated=true&type=${encode(tpe)}&type=${encode(tpe2)}&createdBy=${encode(createdBy)}&updatedBy=${encode(updatedBy)}"
      ) ~> route ~> check {
        responseAs[SearchParams] shouldEqual SearchParams(
          Some(true),
          Some(2L),
          Some(createdBy),
          Some(updatedBy),
          Set(tpe, tpe2)
        )
      }
    }
  }

} 
Example 2
Source File: PermissionSpec.scala    From akka-http-extensions   with Mozilla Public License 2.0 5 votes vote down vote up
package akka.http.extensions


import java.util.UUID

import akka.http.extensions.security._
import akka.http.extensions.stubs.{InMemorySessionController, InMemoryLoginController}
import akka.http.scaladsl.model.{DateTime, StatusCodes}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.model.headers.{HttpCookie, Cookie, `Set-Cookie`}
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{WordSpec}
import scala.collection.mutable
import scala.concurrent.Future
import scala.concurrent.duration._
import com.github.t3hnar.bcrypt._


class PermissionSpec extends ExtensionsTestBase with PermissionControllers
{
  "application with authorization" should{
    "check permissions" in {
      val loginController = new TestLoginController
      val sessionController = new TestSessionController
      import akka.http.scaladsl.server._
      val logins = new Logins(loginController, sessionController)
      val routes = logins.routes
      Put("/users/register?username=anton&password=test2test&[email protected]") ~> Route.seal(routes) ~> check {
        status shouldEqual OK
      }

      val permission = new Permissions(sessionController,loginController)

      Put("/add/drug?name=potion1") ~> permission.routes ~> check {
        rejection
      }

      Put("/users/[email protected]&password=test2test") ~> logins.routes ~> check {
        status shouldEqual OK
      }

      val antonToken = sessionController.tokenByUsername(anton.username).get

      Put("/add/drug?name=potion1&kind=user") ~> Cookie("X-Token" -> antonToken) ~> permission.routes ~> check {
        status shouldEqual OK
        responseAs[String] shouldEqual s"drug potion1 added!"
        permission.drugs.contains("potion1") shouldEqual true
      }

      Put("/add/drug?name=potion2&kind=user") ~> permission.routes ~> check {
        rejection
      }

      val antonR = sessionController.userByToken(antonToken).get //get user with hashed password
      permission.add2realm(antonR,VIPRealm)

      permission.checkRights(antonR,SpecialRealm) shouldEqual false
      permission.checkRights(antonR,VIPRealm) shouldEqual true


      Put(s"/users/register?username=${liz.username}&password=${liz.password}&email=${liz.email}") ~> Route.seal(routes) ~> check {
        status shouldEqual OK
      }

      val lizToken =  sessionController.tokenByUsername(liz.username).get
      val lizR = sessionController.userByToken(lizToken).get

      permission.add2realm(lizR,SpecialRealm)
      permission.checkRights(lizR,SpecialRealm) shouldEqual true
      permission.checkRights(lizR,VIPRealm) shouldEqual false


    Put("/add/drug?name=potion2&kind=special") ~> Cookie("X-Token" -> antonToken) ~> permission.routes ~> check {
      permission.drugs.contains("potion2") shouldEqual false
      rejection
    }
    Put("/add/drug?name=potion2&kind=special") ~> Cookie("X-Token" -> lizToken) ~> permission.routes ~> check {
      status shouldEqual OK
      permission.drugs.contains("potion2") shouldEqual true
      responseAs[String] shouldEqual s"drug potion2 added!"
    }

    Put("/add/drug?name=potion3&kind=vip") ~> Cookie("X-Token" -> lizToken) ~> permission.routes ~> check {
    //  permission.drugs.contains("potion3") shouldEqual false
      rejection
    }
    Put("/add/drug?name=potion3&kind=vip") ~> Cookie("X-Token" -> antonToken) ~> permission.routes ~> check {
      status shouldEqual OK
      permission.drugs.contains("potion3") shouldEqual true
      responseAs[String] shouldEqual s"drug potion3 added!"
   }
  }
}

} 
Example 3
Source File: ExtensionsTestBase.scala    From akka-http-extensions   with Mozilla Public License 2.0 5 votes vote down vote up
package akka.http.extensions

import akka.http.extensions.security._
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest._
import org.scalatest.concurrent.ScalaFutures
import scala.concurrent.duration._

class ExtensionsTestBase extends WordSpec
  with Directives
  with ScalaFutures
  with ScalatestRouteTest
  with Matchers
{

  val anton = LoginInfo("anton", "test2test", "[email protected]")
  val paul = LoginInfo("paul", "test2paul", "[email protected]")
  val liz = LoginInfo("liz", "test2liz", "[email protected]")
  
  val timeout = 500 millis

} 
Example 4
Source File: AkkaHttpHelpersTest.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.server

import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.Marshalling.WithFixedContentType
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import akka.stream.testkit.scaladsl._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FunSuite, Matchers}

import scala.concurrent.duration._

class AkkaHttpHelpersTest extends FunSuite with Matchers with ScalaFutures with ScalatestRouteTest {

  import AkkaHttpHelpers._

  override implicit val patienceConfig: PatienceConfig = PatienceConfig(10.seconds)

  private[this] implicit val system: ActorSystem = ActorSystem()
  private[this] implicit val materializer = ActorMaterializer()(system)
  private[this] implicit val marshaller = Marshaller.strict[Int, String] {
    received =>
      WithFixedContentType(MediaTypes.`application/json`, () => String.valueOf(received))
  }

  test("Should work for empty Source") {
    whenReady(Source.empty[Int].via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) {
      _ shouldBe "[]"
    }
  }

  test("Should work for single element in Source") {
    whenReady(Source.single(1).via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) {
      _ shouldBe "[1]"
    }
  }

  test("Should work for multiple elements element in Source") {
    whenReady(Source(List(1, 2, 3)).via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) {
      _ shouldBe "[1,2,3]"
    }
  }

  test("asJsonArray is incremental") {
    val (pub, sub) = TestSource.probe[Int]
      .via(asJsonArray)
      .map(_.data().utf8String)
      .toMat(TestSink.probe[String])(Keep.both)
      .run()

    pub.sendNext(1)
    sub.request(10)
    sub.expectNext("[")
    pub.sendNext(2)
    sub.expectNext("1")
    pub.sendNext(3)
    sub.expectNext(",2")
    pub.sendComplete()
    sub.expectNext(",3")
    sub.expectNext("]")
    sub.expectComplete()
  }

  test("completeAsJson works properly") {
    val source = Source(List(1, 2, 3))

    Get() ~> completeAsJson(source) ~> check {
      chunks should have size (5)
      responseAs[String] shouldEqual "[1,2,3]"
    }
  }

} 
Example 5
Source File: FrontendResourcesSupportTest.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.server

import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FunSuite, Matchers}

class FrontendResourcesSupportTest extends FunSuite with ScalatestRouteTest with Matchers {

  val route = FrontendResourcesSupport.frontendResourcesRouting

  test("It is possible to GET index.html") {
    Get() ~> route ~> check {
      handled shouldBe true
    }
  }

  test("It is possible to GET style.css") {
    Get("/css/style.css") ~> route ~> check {
      handled shouldBe true
    }
  }

  test("It is possible to GET frontend-launcher.js") {
    Get("/frontend-launcher.js") ~> route ~> check {
      handled shouldBe true
    }
  }

  test("It is possible to GET frontend-fastopt.js") {
    Get("/frontend-fastopt.js") ~> route ~> check {
      handled shouldBe true
    }
  }

  test("It is possible to GET frontend-fastopt.js.map") {
    Get("/frontend-fastopt.js.map") ~> route ~> check {
      handled shouldBe true
    }
  }

  test("It is possible to GET frontend-jsdeps.js") {
    Get("/frontend-jsdeps.js") ~> route ~> check {
      handled shouldBe true
    }
  }

  test("It is possible to GET something from WebJars") {
    Get("/webjars/vis/4.15.0/dist/vis.min.css") ~> route ~> check {
      handled shouldBe true
    }
  }

} 
Example 6
Source File: ArchiveSupportTest.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.server

import java.util.UUID

import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.scaladsl.Source
import akkaviz.persistence.ReceivedRecord
import org.scalatest.{Matchers, FunSuite}

class ArchiveSupportTest extends FunSuite with ScalatestRouteTest with Matchers {

  val uuid = UUID.randomUUID()

  val ofGet = Get("/messages/of/ref")
  val betweenGet = Get("/messages/between/ref/ref2")

  test("Allows to get archive of Actor") {
    val arch = new ArchiveSupport {
      override def isArchiveEnabled: Boolean = true

      override def receivedBetween(ref: String, ref2: String): Source[ReceivedRecord, _] = fail("Should not be called")

      override def receivedOf(ref: String): Source[ReceivedRecord, _] =
        Source.single(ReceivedRecord(uuid, 100, ref, akkaviz.persistence.To, "second", "{}"))
    }

    ofGet ~> arch.archiveRouting ~> check {
      responseAs[String] shouldBe
        """[{"timestamp":"100","direction":">","from":"ref","to":"second","payload":"{}"}]"""
    }
  }

  test("Allows to get archive between two Actors") {
    val arch = new ArchiveSupport {
      override def isArchiveEnabled: Boolean = true

      override def receivedBetween(ref: String, ref2: String): Source[ReceivedRecord, _] =
        Source.single(ReceivedRecord(uuid, 200, ref, akkaviz.persistence.To, ref2, "{}"))

      override def receivedOf(ref: String): Source[ReceivedRecord, _] = fail("Should not be called")
    }

    betweenGet ~> arch.archiveRouting ~> check {
      responseAs[String] shouldBe
        """[{"timestamp":"200","direction":">","from":"ref","to":"ref2","payload":"{}"}]"""
    }
  }

  test("Archive could be disabled") {
    val arch = new ArchiveSupport {
      override def isArchiveEnabled: Boolean = false

      override def receivedBetween(ref: String, ref2: String): Source[ReceivedRecord, _] = fail("Should not be called")

      override def receivedOf(ref: String): Source[ReceivedRecord, _] = fail("Should not be called")
    }

    ofGet ~> arch.archiveRouting ~> check {
      handled shouldBe false
    }

    betweenGet ~> arch.archiveRouting ~> check {
      handled shouldBe false
    }
  }

} 
Example 7
Source File: HealthCheckRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.mockito.Mockito.doReturn
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.OneInstancePerTest
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import cats.effect._
import vinyldns.core.health.HealthCheck.HealthCheckError
import vinyldns.core.health.HealthService

class HealthCheckRoutingSpec
    extends AnyWordSpec
    with ScalatestRouteTest
    with HealthCheckRoute
    with OneInstancePerTest
    with Matchers
    with MockitoSugar {

  val healthService: HealthService = mock[HealthService]

  "GET on the healthcheck" should {
    "return OK when all datastores return a positive result" in {
      doReturn(IO.pure(List())).when(healthService).checkHealth()
      Get("/health") ~> healthCheckRoute ~> check {
        status shouldBe StatusCodes.OK
      }
    }

    "return a 500 when the zone manager returns any error" in {
      val err = HealthCheckError("an error!")
      doReturn(IO.pure(List(err))).when(healthService).checkHealth()
      Get("/health") ~> healthCheckRoute ~> check {
        status shouldBe StatusCodes.InternalServerError
      }
    }
  }
} 
Example 8
Source File: BlueGreenRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class BlueGreenRoutingSpec
    extends AnyWordSpec
    with ScalatestRouteTest
    with BlueGreenRoute
    with Matchers {

  def actorRefFactory: ActorSystem = system

  "GET color" should {
    "return blue" in {
      Get("/color") ~> colorRoute ~> check {
        response.status shouldBe StatusCodes.OK

        // set in the application.conf in src/test/resources
        responseAs[String] shouldBe "blue"
      }
    }
  }
} 
Example 9
Source File: PrometheusRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

import akka.http.scaladsl.model.{HttpProtocol, HttpResponse, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.dropwizard.DropwizardExports
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.BeforeAndAfterEach
import vinyldns.core.VinylDNSMetrics

class PrometheusRoutingSpec
    extends AnyWordSpec
    with ScalatestRouteTest
    with PrometheusRoute
    with BeforeAndAfterEach
    with MockitoSugar
    with Matchers {

  val metricRegistry = VinylDNSMetrics.metricsRegistry

  val collectorRegistry = CollectorRegistry.defaultRegistry

  collectorRegistry.register(new DropwizardExports(metricRegistry))

  "GET /metrics/prometheus" should {
    "return metrics logged in prometheus" in {
      Get("/metrics/prometheus") ~> prometheusRoute ~> check {
        response.status shouldBe StatusCodes.OK
        val resultStatus = responseAs[HttpResponse]
        resultStatus.protocol shouldBe HttpProtocol("HTTP/1.1")
      }
    }
  }
} 
Example 10
Source File: VinylDNSRouteTestHelper.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives.{complete, extractUnmatchedPath}
import akka.http.scaladsl.server.{MalformedRequestContentRejection, RejectionHandler}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.json4s.MappingException

trait VinylDNSRouteTestHelper { this: ScalatestRouteTest =>
  import scala.concurrent.duration._
  import akka.http.scaladsl.testkit.RouteTestTimeout

  implicit val testTimeout = RouteTestTimeout(10.seconds)

  implicit def validationRejectionHandler: RejectionHandler =
    RejectionHandler
      .newBuilder()
      .handle {
        case MalformedRequestContentRejection(msg, MappingException(_, _)) =>
          complete(
            HttpResponse(
              status = StatusCodes.BadRequest,
              entity = HttpEntity(ContentTypes.`application/json`, msg)
            )
          )
      }
      .handleNotFound {
        extractUnmatchedPath { p =>
          complete((StatusCodes.NotFound, s"The requested path [$p] does not exist."))
        }
      }
      .result()
} 
Example 11
Source File: StatusRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import cats.effect.{ContextShift, IO}
import fs2.concurrent.SignallingRef
import org.scalatest._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar

class StatusRoutingSpec
    extends AnyWordSpec
    with ScalatestRouteTest
    with StatusRoute
    with OneInstancePerTest
    with VinylDNSJsonProtocol
    with BeforeAndAfterEach
    with MockitoSugar
    with Matchers {

  def actorRefFactory: ActorSystem = system

  private implicit val cs: ContextShift[IO] =
    IO.contextShift(scala.concurrent.ExecutionContext.global)

  val processingDisabled: SignallingRef[IO, Boolean] =
    fs2.concurrent.SignallingRef[IO, Boolean](false).unsafeRunSync()

  "GET /status" should {
    "return the current status of true" in {
      Get("/status") ~> statusRoute ~> check {
        response.status shouldBe StatusCodes.OK
        val resultStatus = responseAs[CurrentStatus]
        resultStatus.processingDisabled shouldBe false
        resultStatus.color shouldBe "blue"
        resultStatus.keyName shouldBe "vinyldns."
        resultStatus.version shouldBe "unset"
      }
    }
  }

  "POST /status" should {
    "disable processing" in {
      Post("/status?processingDisabled=true") ~> statusRoute ~> check {
        response.status shouldBe StatusCodes.OK
        val resultStatus = responseAs[CurrentStatus]
        resultStatus.processingDisabled shouldBe true
      }
    }

    "enable processing" in {
      Post("/status?processingDisabled=false") ~> statusRoute ~> check {
        response.status shouldBe StatusCodes.OK
        val resultStatus = responseAs[CurrentStatus]
        resultStatus.processingDisabled shouldBe false

        // remember, the signal is the opposite of intent
        processingDisabled.get.unsafeRunSync() shouldBe false
      }
    }
  }
} 
Example 12
Source File: PingRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class PingRoutingSpec extends AnyWordSpec with ScalatestRouteTest with PingRoute with Matchers {

  def actorRefFactory: ActorSystem = system

  "GET ping" should {
    "return PONG" in {
      Get("/ping") ~> pingRoute ~> check {
        response.status shouldBe StatusCodes.OK
        responseAs[String] shouldBe "PONG"
      }
    }
  }
} 
Example 13
Source File: HttpApiSpec.scala    From jwt-akka-http   with MIT License 5 votes vote down vote up
package ba.codecentric

import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.{ HttpHeader, StatusCodes }
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{ Matchers, WordSpec }

class HttpApiSpec extends WordSpec with Matchers with ScalatestRouteTest {
  import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
  import io.circe.generic.auto._
  import HttpApi._

  "HttpApi" should {
    "return 403 Unauthorized upon GET / " in {
      Get() ~> routes ~> check {
        status shouldBe StatusCodes.Unauthorized
      }
    }

    "return 403 Unauthorized when credentials are incorrect" in {
      Post("/", LoginRequest("admin", "something")) ~> routes ~> check {
        header(AccessTokenHeaderName) shouldBe Some(_: HttpHeader)
        status shouldBe StatusCodes.Unauthorized
      }
    }

    "return JWT token upon POST /" in {
      Post("/", LoginRequest("admin", "admin")) ~> routes ~> check {
        header(AccessTokenHeaderName) shouldBe Some(_: HttpHeader)
        status shouldBe StatusCodes.OK
      }
    }

    "access secured content after providing a correct JWT upon GET /" in {
      Post("/", LoginRequest("admin", "admin")) ~> routes ~> check {
        header(AccessTokenHeaderName).map { accessTokenHeader =>
          Get("/").addHeader(RawHeader("Authorization", accessTokenHeader.value())) ~> routes ~> check {
            status shouldBe StatusCodes.OK
          }
        }
      }
    }
  }
} 
Example 14
Source File: WsApiSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.interfaces.http

import mist.api.data._
import akka.http.scaladsl.testkit.{ScalatestRouteTest, WSProbe}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import io.hydrosphere.mist.core.logging.LogEvent
import io.hydrosphere.mist.master.Messages.StatusMessages._
import io.hydrosphere.mist.master.EventsStreamer
import org.mockito.Mockito._
import org.scalatest.{FunSpec, Matchers}

import scala.concurrent.duration._

class WsApiSpec extends FunSpec
  with Matchers
  with ScalatestRouteTest {

  val mat = ActorMaterializer()
  implicit val keepAlive = 30 seconds

  it("should stream all events") {
    val testSource = Source[UpdateStatusEvent](List(
      StartedEvent("1", 1), StartedEvent("2", 1)
    ))

    val streamer = mock(classOf[EventsStreamer])
    when(streamer.eventsSource()).thenReturn(testSource)

    val route = new WSApi(streamer).route

    val client = WSProbe()

    WS("/v2/api/ws/all", client.flow) ~> route ~> check {
      isWebSocketUpgrade shouldBe true

      client.expectMessage("""{"id":"1","time":1,"event":"started"}""")
      client.expectMessage("""{"id":"2","time":1,"event":"started"}""")
    }
  }

  it("should stream for particular job") {

    val testSource = Source[SystemEvent](List(
      StartedEvent("1", 1),
      StartedEvent("2", 1),
      ReceivedLogs("1", Seq(LogEvent("1", "test", 1, 1, None)), 0),
      FinishedEvent("1", 1, JsMap("result" -> JsNumber(42)))
    ))

    val streamer = mock(classOf[EventsStreamer])
    when(streamer.eventsSource()).thenReturn(testSource)

    val route = new WSApi(streamer).route

    val client = WSProbe()

    WS("/v2/api/ws/jobs/1?withLogs=true", client.flow) ~> route ~> check {
      isWebSocketUpgrade shouldBe true

      client.expectMessage("""{"id":"1","time":1,"event":"started"}""")
      client.expectMessage("""{"id":"1","events":[{"from":"1","message":"test","timeStamp":1,"level":1}],"fileOffset":0,"event":"logs"}""")
      client.expectMessage("""{"id":"1","time":1,"result":{"result":42},"event":"finished"}""")
    }
  }

  it("should filter received logs events if flag wasn't set") {
    val testSource = Source[SystemEvent](List(
      StartedEvent("1", 1),
      StartedEvent("2", 1),
      ReceivedLogs("1", Seq(LogEvent("1", "test", 1, 1, None)), 0),
      FinishedEvent("1", 1, JsMap("result" -> JsNumber(42)))
    ))

    val streamer = mock(classOf[EventsStreamer])
    when(streamer.eventsSource()).thenReturn(testSource)

    val route = new WSApi(streamer).route

    val client = WSProbe()

    WS("/v2/api/ws/jobs/1", client.flow) ~> route ~> check {
      isWebSocketUpgrade shouldBe true

      client.expectMessage("""{"id":"1","time":1,"event":"started"}""")
      client.expectMessage("""{"id":"1","time":1,"result":{"result":42},"event":"finished"}""")
    }
  }
} 
Example 15
Source File: IdentitiesRoutesSpec.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.routes

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.commons.test.Resources
import ch.epfl.bluebrain.nexus.iam.auth.{AccessToken, TokenRejection}
import ch.epfl.bluebrain.nexus.iam.config.{AppConfig, Settings}
import ch.epfl.bluebrain.nexus.iam.marshallers.instances._
import ch.epfl.bluebrain.nexus.iam.realms._
import ch.epfl.bluebrain.nexus.iam.testsyntax._
import ch.epfl.bluebrain.nexus.iam.types.Caller
import ch.epfl.bluebrain.nexus.iam.types.IamError.InvalidAccessToken
import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Authenticated, User}
import com.typesafe.config.{Config, ConfigFactory}
import io.circe.Json
import monix.eval.Task
import org.mockito.matchers.MacroBasedMatchers
import org.mockito.{IdiomaticMockito, Mockito}
import org.scalatest.BeforeAndAfter
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import scala.concurrent.duration._

//noinspection TypeAnnotation
class IdentitiesRoutesSpec
    extends AnyWordSpecLike
    with Matchers
    with ScalatestRouteTest
    with BeforeAndAfter
    with MacroBasedMatchers
    with Resources
    with ScalaFutures
    with IdiomaticMockito {

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(3.seconds, 100.milliseconds)

  override def testConfig: Config = ConfigFactory.load("test.conf")

  private val appConfig: AppConfig = Settings(system).appConfig
  private implicit val http        = appConfig.http

  private val realms: Realms[Task] = mock[Realms[Task]]

  before {
    Mockito.reset(realms)
  }

  "The IdentitiesRoutes" should {
    val routes = Routes.wrap(new IdentitiesRoutes(realms).routes)
    "return forbidden" in {
      val err = InvalidAccessToken(TokenRejection.InvalidAccessToken)
      realms.caller(any[AccessToken]) shouldReturn Task.raiseError(err)
      Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check {
        status shouldEqual StatusCodes.Unauthorized
      }
    }
    "return anonymous" in {
      realms.caller(any[AccessToken]) shouldReturn Task.pure(Caller.anonymous)
      Get("/identities") ~> routes ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[Json].sort shouldEqual jsonContentOf("/identities/anonymous.json")
      }
    }
    "return all identities" in {
      val user   = User("theuser", "therealm")
      val auth   = Authenticated("therealm")
      val caller = Caller(user, Set(user, Anonymous, auth))
      realms.caller(any[AccessToken]) shouldReturn Task.pure(caller)
      Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[Json].sort shouldEqual jsonContentOf("/identities/identities.json")
      }
    }
  }
} 
Example 16
Source File: Issue143.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import _root_.issues.issue143.server.akkaHttp.{ Handler, Resource }
import akka.http.scaladsl.model._
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.scaladsl.Source
import cats.implicits._
import java.io.File
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import scala.concurrent.Future
import scala.concurrent.duration._

class Issue143 extends FunSuite with Matchers with EitherValues with ScalaFutures with ScalatestRouteTest {
  override implicit val patienceConfig = PatienceConfig(10.seconds, 1.second)

  override def testConfigSource =
    s"""
      |akka.loglevel = OFF
    """.stripMargin

  test("Ensure that failed uploads are cleaned up afterwards") {
    val tempDest = File.createTempFile("guardrail.", ".dat")
    val route = Resource.routes(new Handler {
      def uploadFile(
          respond: Resource.UploadFileResponse.type
      )(file: (File, Option[String], akka.http.scaladsl.model.ContentType)): Future[Resource.UploadFileResponse] =
        Future.successful(respond.Created)
      def uploadFileMapFileField(fieldName: String, fileName: Option[String], contentType: akka.http.scaladsl.model.ContentType): java.io.File =
        tempDest
    })

    val chunks        = 1000
    val data          = "foo"
    val contentLength = chunks * data.length
    val req = Post("/file").withEntity(
      Multipart
        .FormData(
          Multipart.FormData.BodyPart(
            "file",
            HttpEntity(
              ContentTypes.`text/plain(UTF-8)`,
              contentLength,
              Source.fromIterator(() => List.fill(chunks)(akka.util.ByteString.fromString(data)).toIterator)
            )
          )
        )
        .toEntity
        .withSizeLimit(1001)
    )

    // Working around https://github.com/akka/akka-http/issues/2381
    // The following test fails under some 2.11.12 configurations
    // (fails in TravisCI, passes in OSX; may be related to filesystem or
    //  other system particulars)
    // req ~> route ~> check {
    //   status should equal(StatusCodes.RequestEntityTooLarge)
    //   tempDest.exists() should equal(false)
    // }

    // The following workaround seems to work:

    val resp = Route.asyncHandler(route).apply(req).futureValue
    resp.status should equal(StatusCodes.RequestEntityTooLarge)
    tempDest.exists() should equal(false)
  }
} 
Example 17
Source File: Issue184.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.unmarshalling.Unmarshaller
import cats.instances.future._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import scala.concurrent.Future
import io.circe._


    Delete("/1234?query=2345")
      .withEntity(
        Multipart
          .FormData(
            Multipart.FormData.BodyPart.Strict("form", "3456")
          )
          .toEntity
      ) ~> route ~> check {
      response.status shouldBe (StatusCodes.NoContent)
    }
  }
} 
Example 18
Source File: Issue121.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.unmarshalling.Unmarshaller
import cats.instances.future._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import scala.concurrent.Future
import io.circe._

class Issue121Suite extends FunSuite with Matchers with EitherValues with ScalaFutures with ScalatestRouteTest {
  override implicit val patienceConfig = PatienceConfig(10 seconds, 1 second)

  test("akka-http server can respond with 204") {
    import issues.issue121.server.akkaHttp.{ Handler, Resource }
    val route = Resource.routes(new Handler {
      override def deleteFoo(respond: Resource.DeleteFooResponse.type)(id: Long): Future[Resource.DeleteFooResponse] =
        Future.successful(respond.NoContent)
    })

    Delete("/entity").withEntity(FormData("id" -> "1234").toEntity) ~> route ~> check {
      status should equal(StatusCodes.NoContent)
      response.entity.contentType should equal(ContentTypes.NoContentType)
      response.entity.contentLengthOption should equal(Some(0))
    }
  }

  test("akka-http client can respond with 204") {
    import issues.issue121.client.akkaHttp.Client

    def noContentResponse: HttpRequest => Future[HttpResponse] = _ => Future.successful(HttpResponse(204))

    
    Client
      .httpClient(noContentResponse, "http://localhost:80")
      .deleteFoo(1234)
      .fold(
        _ => failTest("Error"),
        _.fold(
          handleNoContent = ()
        )
      )
      .futureValue
  }
} 
Example 19
package features

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import modules.AllModulesTest
import org.scalatest.{FeatureSpec, Matchers}

class HealthCheckEndpointFeature
  extends FeatureSpec
    with Matchers
    with ScalatestRouteTest {

  val modules = new AllModulesTest
  val route = modules.endpoints.routes

  feature("health check api") {
    scenario("successful get") {
      Get(s"/api/health-check") ~> route ~> check {
        status shouldBe StatusCodes.OK
        responseAs[String] shouldBe "ok"
      }
    }
  }
} 
Example 20
Source File: UserEndpointFeature.scala    From akka-http-microservice-templates   with MIT License 5 votes vote down vote up
package features

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import modules.AllModulesTest
import org.scalatest.{BeforeAndAfterAll, FeatureSpec, Matchers}

class UserEndpointFeature
  extends FeatureSpec
    with Matchers
    with ScalatestRouteTest
    with BeforeAndAfterAll {

  val modules = new AllModulesTest

  val routes = modules.endpoints.routes

  val httpEntity: (String) => HttpEntity.Strict = (str: String) => HttpEntity(ContentTypes.`application/json`, str)

  feature("user api") {
    scenario("success creation") {
      val validUser =
        """
          {
            "username": "gabfssilva",
            "age": 24
          }
        """

      Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check {
        status shouldBe StatusCodes.Created
      }
    }

    scenario("success get after success creation") {
      val validUser =
        """
          {
            "username": "gabfssilva",
            "age": 24
          }
        """

      Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check {
        status shouldBe StatusCodes.Created

        Get(header("Location").orNull.value()) ~> routes ~> check {
          status shouldBe StatusCodes.OK
        }
      }
    }


    scenario("invalid id on get") {
      Get(s"/api/users/1") ~> routes ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }

    scenario("no body") {
      Post(s"/api/users", httpEntity("{}")) ~> routes ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }

    scenario("body without age") {
      val invalidUser =
        """
        {
          "username": "gabfssilva"
        }
        """

      Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }

    scenario("body without username") {
      val invalidUser =
        """
        {
          "age": 24
        }
        """

      Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }
  }
} 
Example 21
package features

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import modules.AllModules
import org.scalatest.{FeatureSpec, Matchers}

class HealthCheckEndpointFeature
  extends FeatureSpec
    with Matchers
    with ScalatestRouteTest {

  val modules = new AllModules
  val route = modules.endpoints.routes

  feature("health check api") {
    scenario("successful get") {
      Get(s"/api/health-check") ~> route ~> check {
        status shouldBe StatusCodes.OK
        responseAs[String] shouldBe "ok"
      }
    }
  }
} 
Example 22
package features

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import modules.AllModules
import org.scalatest.{FeatureSpec, Matchers}

class HealthCheckEndpointFeature
  extends FeatureSpec
    with Matchers
    with ScalatestRouteTest {

  val modules = new AllModules
  val route = modules.endpoints.routes

  feature("health check api") {
    scenario("successful get") {
      Get(s"/api/health-check") ~> route ~> check {
        status shouldBe StatusCodes.OK
        responseAs[String] shouldBe "ok"
      }
    }
  }
} 
Example 23
Source File: UserEndpointFeature.scala    From akka-http-microservice-templates   with MIT License 5 votes vote down vote up
package features

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import modules.AllModules
import org.scalatest.{BeforeAndAfterAll, FeatureSpec, Matchers}
import utils.EmbeddedPostgreSQL

class UserEndpointFeature
  extends FeatureSpec
    with Matchers
    with ScalatestRouteTest
    with BeforeAndAfterAll {

  val modules = new AllModules

  override def beforeAll(): Unit = {
    EmbeddedPostgreSQL.start
  }

  override def afterAll(): Unit = {
    EmbeddedPostgreSQL.stop
  }

  val routes = modules.endpoints.routes

  val httpEntity: (String) => HttpEntity.Strict = (str: String) => HttpEntity(ContentTypes.`application/json`, str)

  feature("user api") {
    scenario("success creation") {
      val validUser =
        """
          {
            "username": "gabfssilva",
            "age": 24
          }
        """

      Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check {
        status shouldBe StatusCodes.Created
      }
    }

    scenario("success get after success creation") {
      val validUser =
        """
          {
            "username": "gabfssilva",
            "age": 24
          }
        """

      Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check {
        status shouldBe StatusCodes.Created

        Get(header("Location").orNull.value()) ~> routes ~> check {
          status shouldBe StatusCodes.OK
        }
      }
    }


    scenario("invalid id on get") {
      Get(s"/api/users/asd") ~> routes ~> check {
        status shouldBe StatusCodes.NotFound
      }
    }

    scenario("no body") {
      Post(s"/api/users", httpEntity("{}")) ~> routes ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }

    scenario("body without age") {
      val invalidUser =
        """
        {
          "username": "gabfssilva"
        }
        """

      Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }

    scenario("body without username") {
      val invalidUser =
        """
        {
          "age": 24
        }
        """

      Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }
  }
} 
Example 24
Source File: GreetingEndpointFeature.scala    From akka-http-microservice-templates   with MIT License 5 votes vote down vote up
package io.github.gabfssilva.features

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import io.github.gabfssilva.modules.AllModules
import org.scalatest.{FeatureSpec, Matchers}

class GreetingEndpointFeature
  extends FeatureSpec
    with Matchers
    with ScalatestRouteTest {

  val modules = new AllModules
  val route = modules.endpoints.routes

  feature("greeting api") {
    scenario("successful get") {
      Get(s"/api/greetings?name=gabriel&greeting=hello") ~> route ~> check {
        status shouldBe StatusCodes.OK
        responseAs[String] should include(s"hello, gabriel")
      }
    }

    scenario("unprocessable entity get") {
      Get(s"/api/greetings?name=gabriel&greeting=") ~> route ~> check {
        status shouldBe StatusCodes.BadRequest
      }
    }
  }
} 
Example 25
package io.github.gabfssilva.features

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import io.github.gabfssilva.modules.AllModules
import org.scalatest.{FeatureSpec, Matchers}

class HealthCheckEndpointFeature
  extends FeatureSpec
    with Matchers
    with ScalatestRouteTest {

  val modules = new AllModules
  val route = modules.endpoints.routes

  feature("health check api") {
    scenario("successful get") {
      Get(s"/api/health-check") ~> route ~> check {
        status shouldBe StatusCodes.OK
        responseAs[String] shouldBe "ok"
      }
    }
  }
} 
Example 26
Source File: DonutQueryParametersTest.scala    From learn-akka   with Apache License 2.0 5 votes vote down vote up
package com.allaboutscala.learn.akka.http

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.allaboutscala.learn.akka.http.routes.DonutRoutes
import org.scalatest.{Matchers, WordSpec}


class DonutQueryParametersTest
  extends WordSpec
    with Matchers
    with ScalatestRouteTest {

  val donutRoutes = new DonutRoutes().route()

  "Query Parameters Tests" should {
    "match the output for the URL /donut/prices?donutName" in {
      Get("/donut/prices?donutName=plain%20donut") ~> donutRoutes ~> check {
        responseAs[String] shouldEqual "Received parameter: donutName=plain donut"
        status shouldEqual StatusCodes.OK
      }
    }



    "Check for required donutName query parameter at /donut/prices" in {
      Get("/donut/prices?") ~> Route.seal(donutRoutes) ~> check {
        responseAs[String] shouldEqual "Request is missing required query parameter 'donutName'"
        status shouldEqual StatusCodes.NotFound
      }
    }



    "Validate the pass-through of required and optional parameters in /donut/bake" in {
      Get("/donut/bake?donutName=plain%20donut&topping=chocolate") ~> donutRoutes ~> check {
        responseAs[String] shouldEqual "Received parameters: donutName=plain donut and topping=chocolate"
        status shouldEqual StatusCodes.OK
      }
    }



    "Verify the optional parameter topping for /donut/bake" in {
      Get("/donut/bake?donutName=plain%20donut") ~> donutRoutes ~> check {
        responseAs[String] shouldEqual "Received parameters: donutName=plain donut and topping=sprinkles"
        status shouldEqual StatusCodes.OK
      }
    }



    "Verify typed parameters for /ingredients" in {
      Get("/ingredients?donutName=plain%20donut&priceLevel=1.50") ~> donutRoutes ~> check {
        responseAs[String] shouldEqual "Received parameters: donutName=plain donut, priceLevel=1.5"
        status shouldEqual StatusCodes.OK
      }
    }



    "Check for wrong types being passed through to the priceLevel query param at /ingredients" in {
      Get("/ingredients?donutName=plain%20donut&priceLevel=cheap") ~> Route.seal(donutRoutes) ~> check {
        responseAs[String] shouldEqual """The query parameter 'priceLevel' was malformed:
                                         |'cheap' is not a valid 64-bit floating point value""".stripMargin
        status shouldEqual StatusCodes.BadRequest
      }
    }



    "Verify CSV parameters for /bake-donuts" in {
      Get("/bake-donuts?ingredients=flour,sugar,vanilla") ~> donutRoutes ~> check {
        responseAs[String] shouldEqual "Received CSV parameter: ingredients=List(flour, sugar, vanilla)"
        status shouldEqual StatusCodes.OK
      }
    }
  }
} 
Example 27
Source File: ModelServiceSpec.scala    From full-scala-stack   with Apache License 2.0 5 votes vote down vote up
package api

import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, HttpResponse, MessageEntity, RequestEntity}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import dao.{CRUDOperations, MockRepository, Repository}
import de.heikoseeberger.akkahttpupickle.UpickleSupport
import mail.{CourierPostman, Postman}
import model.{SampleModelObject, SimpleSearch}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import routes.{ModelRoutes, SampleModelObjectRoute}
import upickle.default._
import util.ModelPickler
import zio.{IO, ZIO}
import zioslick.RepositoryException

import scala.concurrent.ExecutionContext


class ModelServiceSpec
  extends AnyWordSpec
    with Matchers
    with ScalatestRouteTest
    with ZIODirectives
  with UpickleSupport
    with ModelPickler
 {

  val objects = Seq(
    SampleModelObject(0, "Zero"),
    SampleModelObject(1, "One"),
    SampleModelObject(2, "Two"),
    SampleModelObject(3, "Three"),
    SampleModelObject(4, "Four"),
  )

  val service = new SampleModelObjectRoute  with MockRepository with CourierPostman with Config {
    override def repository: Repository.Service = new Repository.Service {
      override val sampleModelObjectOps: CRUDOperations[SampleModelObject, Int, SimpleSearch, Any] = new MockOps {
        override def search(search: Option[SimpleSearch])(
          implicit session: Any
        ): IO[RepositoryException, Seq[SampleModelObject]] = ZIO.succeed(objects)
        override def get(pk: Int)(implicit session: Any): IO[RepositoryException, Option[SampleModelObject]] =
          ZIO.succeed(objects.headOption)

      }
    }
  }

  //TODO test your route here, we would probably not have a test like the one below in reality, since it's super simple.
  "The Service" should  {
    "return one objects on a get" in {
      Get("/sampleModelObject/1") ~> service.crudRoute.route("") ~> check {
        val res = responseAs[Seq[SampleModelObject]].headOption

        println(res)
        res shouldEqual objects.headOption
      }
    }
    "return some objects on a search" in {
      Post("/sampleModelObject/search", HttpEntity(ContentTypes.`application/json`, write(SimpleSearch()))) ~> service.crudRoute.route("") ~> check {
        val str = responseAs[ujson.Value]
        val res = responseAs[Seq[SampleModelObject]]

        println(res)
        res shouldEqual objects
      }
    }
  }
} 
Example 28
Source File: ModelServiceIntegrationSpec.scala    From full-scala-stack   with Apache License 2.0 5 votes vote down vote up
package api

import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import de.heikoseeberger.akkahttpupickle.UpickleSupport
import model.{SampleModelObject, SimpleSearch}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.{AnyWordSpec, AnyWordSpecLike}
import routes.ModelRoutes
import upickle.default._
import util.ModelPickler

import scala.concurrent.ExecutionContext


class ModelServiceIntegrationSpec
  extends AnyWordSpec
    with Matchers
    with ScalatestRouteTest
    with ZIODirectives
  with UpickleSupport
    with ModelPickler
    {

  val service = new ModelRoutes with LiveEnvironment

  //TODO test your route here, we would probably not have a test like the one below in reality, since it's super simple.
      "The Service" should  {
        "return one objects on a get" in {
          Get("/api/sampleModelObject/1") ~> service.apiRoute("") ~> check {
            val res = responseAs[Seq[SampleModelObject]].headOption

            println(res)
            assert(res.nonEmpty)
          }
        }
        "return some objects on a search" in {
          Post("/api/sampleModelObject/search", HttpEntity(ContentTypes.`application/json`, write(SimpleSearch()))) ~> service.apiRoute("") ~> check {
            val str = responseAs[ujson.Value]
            val res = responseAs[Seq[SampleModelObject]]

            println(res)
            assert(res.nonEmpty)
          }
        }
      }

} 
Example 29
Source File: WebSocketRoutesSpec.scala    From sync3k-server   with Apache License 2.0 5 votes vote down vote up
package sync3k.routes

import akka.http.scaladsl.testkit.{ ScalatestRouteTest, WSProbe }
import net.manub.embeddedkafka.EmbeddedKafka
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpec }

class WebSocketRoutesSpec extends WordSpec with Matchers with ScalatestRouteTest with WebSocketRoutes with EmbeddedKafka with BeforeAndAfterAll {
  override implicit var kafkaServer: String = "localhost:6001"

  val baseRoots = Table(
    "base url",
    "/ws",
    "/kafka/test-1",
    "/kafka/test-2"
  )

  override def beforeAll(): Unit = {
    super.beforeAll()
    EmbeddedKafka.start()
  }

  override def afterAll(): Unit = {
    EmbeddedKafka.stop()
    super.afterAll()
  }

  forAll(baseRoots) { baseRoot =>
    baseRoot should {
      "echo updates" in {
        val wsClient = WSProbe()

        WS(s"$baseRoot/0", wsClient.flow) ~> webSocketRoutes ~> check {
          isWebSocketUpgrade shouldBe true

          wsClient.sendMessage("test1")
          wsClient.expectMessage("""{"id":0,"message":"test1"}""")

          wsClient.sendMessage("test2")
          wsClient.expectMessage("""{"id":1,"message":"test2"}""")

          wsClient.sendCompletion()
          wsClient.expectCompletion()
        }
      }

      "replay updates" in {
        val wsClient2 = WSProbe()

        WS(s"$baseRoot/0", wsClient2.flow) ~> webSocketRoutes ~> check {
          isWebSocketUpgrade shouldBe true

          wsClient2.expectMessage("""{"id":0,"message":"test1"}""")
          wsClient2.expectMessage("""{"id":1,"message":"test2"}""")
          wsClient2.sendCompletion()
          wsClient2.expectCompletion()
        }
      }

      "skip to offset" in {
        val wsClient3 = WSProbe()

        WS(s"$baseRoot/1", wsClient3.flow) ~> webSocketRoutes ~> check {
          isWebSocketUpgrade shouldBe true

          wsClient3.expectMessage("""{"id":1,"message":"test2"}""")
          wsClient3.sendCompletion()
          wsClient3.expectCompletion()
        }
      }
    }
  }
} 
Example 30
Source File: PropertiesApiSuite.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.archaius

import java.io.StringReader
import java.util.Properties

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.testkit.RouteTestTimeout
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.netflix.atlas.akka.RequestHandler
import com.netflix.atlas.json.Json
import com.netflix.spectator.api.DefaultRegistry
import com.netflix.spectator.api.ManualClock
import org.scalatest.funsuite.AnyFunSuite

class PropertiesApiSuite extends AnyFunSuite with ScalatestRouteTest {
  import scala.concurrent.duration._
  implicit val routeTestTimeout = RouteTestTimeout(5.second)

  val clock = new ManualClock()
  val registry = new DefaultRegistry(clock)
  val propContext = new PropertiesContext(registry)
  val endpoint = new PropertiesApi(propContext, system)
  val routes = RequestHandler.standardOptions(endpoint.routes)

  private def assertJsonContentType(response: HttpResponse): Unit = {
    assert(response.entity.contentType.mediaType === MediaTypes.`application/json`)
  }

  private def assertResponse(response: HttpResponse, expected: StatusCode): Unit = {
    assert(response.status === expected)
    assertJsonContentType(response)
  }

  test("no asg") {
    Get("/api/v1/property") ~> routes ~> check {
      assert(response.status === StatusCodes.BadRequest)
    }
  }

  test("empty") {
    propContext.update(Nil)
    Get("/api/v1/property?asg=foo-main-v001") ~>
    addHeader(Accept(MediaTypes.`application/json`)) ~>
    routes ~>
    check {
      assertResponse(response, StatusCodes.OK)
      assert(responseAs[String] === "[]")
    }
  }

  test("properties response") {
    propContext.update(
      List(
        PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L),
        PropertiesApi.Property("foo-main::1", "foo-main", "1", "2", 12345L),
        PropertiesApi.Property("bar-main::c", "bar-main", "c", "d", 12345L)
      )
    )
    Get("/api/v1/property?asg=foo-main-v001") ~> routes ~> check {
      assert(response.status === StatusCodes.OK)
      val props = new Properties
      props.load(new StringReader(responseAs[String]))
      assert(props.size === 2)
      assert(props.getProperty("a") === "b")
      assert(props.getProperty("1") === "2")
    }
  }

  test("json response") {
    propContext.update(
      List(
        PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L)
      )
    )
    Get("/api/v1/property?asg=foo-main-v001") ~>
    addHeader(Accept(MediaTypes.`application/json`)) ~>
    routes ~>
    check {
      assertResponse(response, StatusCodes.OK)
      val props = Json.decode[List[PropertiesApi.Property]](responseAs[String])
      assert(props === List(PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L)))
    }
  }
} 
Example 31
Source File: StatsApiSuite.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.lwc

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.RouteTestTimeout
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.netflix.atlas.akka.RequestHandler
import com.netflix.atlas.core.model.Datapoint
import com.netflix.atlas.json.Json
import com.netflix.spectator.atlas.impl.Subscription
import com.typesafe.config.ConfigFactory
import org.scalatest.BeforeAndAfter
import org.scalatest.funsuite.AnyFunSuite

class StatsApiSuite extends AnyFunSuite with ScalatestRouteTest with BeforeAndAfter {

  import scala.jdk.CollectionConverters._
  import scala.concurrent.duration._

  private implicit val routeTestTimeout = RouteTestTimeout(5.second)

  private val config = ConfigFactory.load()
  private val evaluator = new ExpressionsEvaluator(config)
  private val endpoint = new StatsApi(evaluator)
  private val routes = RequestHandler.standardOptions(endpoint.routes)

  private def assertJsonContentType(response: HttpResponse): Unit = {
    assert(response.entity.contentType.mediaType === MediaTypes.`application/json`)
  }

  private def assertResponse(response: HttpResponse, expected: StatusCode): Unit = {
    assert(response.status === expected)
    assertJsonContentType(response)
  }

  before {
    evaluator.clear()
  }

  test("empty") {
    Get("/api/v1/stats") ~> routes ~> check {
      assertResponse(response, StatusCodes.OK)
      assert(responseAs[String] === "[]")
    }
  }

  test("has data") {
    // Add sample subscription
    val subs = List(
      new Subscription()
        .withId("1")
        .withExpression("name,ssCpuUser,:eq,:sum"),
      new Subscription()
        .withId("2")
        .withExpression("name,ssCpuSystem,:eq,:sum")
    )
    evaluator.sync(subs.asJava)

    // Stats only get updated when data is sent
    val datapoints = List(
      Datapoint(Map("name" -> "ssCpuUser", "node" -> "i-1"), 60000, 42.0),
      Datapoint(Map("name" -> "ssCpuUser", "node" -> "i-2"), 60000, 44.0)
    )
    evaluator.eval(60000, datapoints)

    // Query the data
    Get("/api/v1/stats") ~> routes ~> check {
      assertResponse(response, StatusCodes.OK)
      val stats = Json.decode[List[ExpressionsEvaluator.SubscriptionStats]](responseAs[String])
      assert(stats.length === 1)
      assert(stats.head.updateCount.get() === 2)
    }
  }
} 
Example 32
Source File: InputReadSuite.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema
package akkaHttp
import akka.http.scaladsl.server.Directives.provide
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import ru.tinkoff.tschema.typeDSL.DSLAtom
import shapeless.ops.hlist.Selector
import shapeless.{HList, HNil, Witness}

class InputReadSuite extends AnyFlatSpec with Matchers with ScalatestRouteTest {
  import InputReadSuite._
  val route = MkRoute.of(api)(handler)(MagicalInput("Sergey") :: HNil)

  "generated route" should "answer with hello" in {
    Get("/magic") ~> route ~> check {
      responseAs[String] shouldBe "Hello, Sergey!"
    }
  }

}

final case class MagicalInput(value: String)

final case class magicParam[name](name: Witness.Aux[name]) extends DSLAtom

object magicParam {
  implicit def serve[In <: HList, name](
      implicit sel: Selector[In, MagicalInput]
  ): Serve.Add[magicParam[name], In, name, MagicalInput] =
    Serve.serveAddIn(in => provide(sel(in)))
}

object InputReadSuite {
  import syntax._
  def api = get |> operation("magic") |> magicParam("hello") |> $$[String]
  object handler {
    def magic(hello: MagicalInput) = s"Hello, ${hello.value}!"
  }
} 
Example 33
Source File: InnerSuite.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.akkaHttp

import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToResponseMarshaller}
import akka.http.scaladsl.model.{ContentTypes, HttpResponse}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ru.tinkoff.tschema.syntax._

import org.scalatest.flatspec.AsyncFlatSpec
import org.scalatest.matchers.should.Matchers
import scala.language.reflectiveCalls

class InnerSuite extends AsyncFlatSpec with ScalatestRouteTest with Matchers {

  object impl {
    object first {
      def get: String           = "first"
      def post(message: String) = s"first $message"
    }
    val second = new {
      def get: String           = "second"
      def post(message: String) = s"second $message"
    }
  }

  implicit val unitAsPlainText: ToResponseMarshaller[Unit] =
    Marshaller.strict(_ => Marshalling.WithFixedContentType(ContentTypes.NoContentType, () => HttpResponse()))

  def api =
    (
      groupPrefix("first") |> ((
        opGet |> $$[String]
      ) <> (
        opPost |> queryParam[String]("message") |> $$[String]
      ))
    ) <> (
      groupPrefix("second") |> ((
        opGet |> $$[String]
      ) <> (
        opPost |> body[String]("message") |> $$[String]
      ))
    )

  val route = MkRoute(api)(impl)

  "first group" should "handle get" in Get("/first") ~> route ~> check {
    responseAs[String] shouldBe "first"
  }

  it should "handle post" in Post("/first?message=hello+oleg") ~> route ~> check {
    responseAs[String] shouldBe "first hello oleg"
  }

  "second group" should "handle get" in Get("/second") ~> route ~> check {
    responseAs[String] shouldBe "second"
  }

  it should "handle post" in Post("/second", "hello oleg") ~> route ~> check {
    responseAs[String] shouldBe "second hello oleg"
  }

} 
Example 34
Source File: MultiParamSpec.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.akkaHttp

import akka.http.scaladsl.server.{Directives, MissingQueryParamRejection}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ru.tinkoff.tschema.akkaHttp.MultiParamSpec.{Page, route}
import ru.tinkoff.tschema.param.HttpParam
import shapeless.Witness

import scala.language.reflectiveCalls
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class MultiParamSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest {
  "Multi parameter case class" should "require first param" in {
    Get("/required") ~> route ~> check {
      rejections should contain(MissingQueryParamRejection("from"))
    }
  }

  it should "require second param" in {
    Get("/required?from=3") ~> route ~> check {
      rejections should contain(MissingQueryParamRejection("to"))
    }
  }

  it should "not require optional field" in {
    Get("/required?from=3&to=5") ~> route ~> check {
      responseAs[String] shouldBe Page(3, 5).toString
    }
  }

  it should "supply optional field" in {
    Get("/required?from=3&to=5&hmm=true") ~> route ~> check {
      responseAs[String] shouldBe Page(3, 5, Some(true)).toString
    }
  }

  it should "not require whole optional record" in {
    Get("/optional?from=3") ~> route ~> check {
      responseAs[String] shouldBe None.toString
    }
    Get("/optional?to=3") ~> route ~> check {
      responseAs[String] shouldBe None.toString
    }
    Get("/optional") ~> route ~> check {
      responseAs[String] shouldBe None.toString
    }
  }

  it should "supply optional record" in {
    Get("/optional?from=3&to=5&hmm=false") ~> route ~> check {
      responseAs[String] shouldBe Some(Page(3, 5, Some(false))).toString
    }
  }

  it should "supply partial optional record with optional fields" in {
    Get("/optional?from=3&to=5") ~> route ~> check {
      responseAs[String] shouldBe Some(Page(3, 5)).toString
    }
  }

}

object MultiParamSpec {
  val page = Witness.`"page"`
  final case class Page(from: Int, to: Long, hmm: Option[Boolean] = None)
  object Page {
    implicit val pageParam: HttpParam[Page] = HttpParam.generate
  }

  val api = {
    import ru.tinkoff.tschema.syntax._
    (operation("required") |> queryParam[Page]("page") |> complete[String]) <|>
      (operation("optional") |> queryParam[Option[Page]]("page") |> complete[String])
  }

  val handler = new {
    def required(page: Page): String         = page.toString
    def optional(page: Option[Page]): String = page.toString
  }

  val route = MkRoute(api)(handler)

  import Directives._
  val kek = Directives.parameter("kek".as[Option[String]])(os => complete(os))

  parameters(("raw".as[Boolean], "offset".as[Int], "pageSize".as[Int]))
} 
Example 35
Source File: ServeSpec.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.akkaHttp

import akka.http.scaladsl.model.Multipart.FormData
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model.{HttpEntity, Uri}
import akka.http.scaladsl.server.MissingQueryParamRejection
import akka.http.scaladsl.testkit.ScalatestRouteTest
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import ru.tinkoff.tschema.syntax

class ServeSpec extends AnyWordSpec with Matchers with ScalatestRouteTest {
  trait Small

  import ru.tinkoff.tschema.syntax._
  val dsl = syntax

  val intAnswer = 42

  object handler {
    val int = 42

    def repeat(body: String, n: Int) = body * n

    def multiply(x: Long, y: Double) = f"result is ${x * y}%.2f"

    def size(args: List[Int]) = args.size

    def min(args: List[Int]) = args.min
  }

  def api = (keyPrefix("int") :> get :> complete[Int]) ~
    (keyPrefix("repeat") :> reqBody[String] :> queryParam[Int]("n") :> post :> complete[String]) ~
    (keyPrefix("multiply") :> formField[Long]("x") :> formField[Double]("y") :> post :> complete[String]) ~
    (keyPrefix("size") :> queryParams[Option[Int]]("args") :> post :> complete[Int]) ~
    (keyPrefix("min") :> queryParams[Int]("args") :> post :> complete[Int])

  val route = MkRoute(api)(handler)

  "Simple service" should {
    "return a simple int" in {
      Get("/int") ~> route ~> check {
        responseAs[Int] shouldEqual intAnswer
      }
    }

    "multiply string by n times" in {
      Post(Uri("/repeat").withQuery(Query("n" -> "5")), "batman") ~> route ~> check {
        responseAs[String] shouldEqual ("batman" * 5)
      }
    }

    "multiply numbers from formdata" in {
      Post(Uri("/multiply"), FormData(Map("x" -> HttpEntity("3"), "y" -> HttpEntity("1.211")))) ~>
        route ~>
        check {
          responseAs[String] shouldEqual f"result is ${3.63}%.2f"
        }
    }

    "return size of empty args" in {
      Post(Uri("/size")) ~> route ~> check {
        responseAs[Int] shouldEqual 0
      }
    }

    "return size of non empty args" in {
      Post(Uri("/size").withQuery(Query(List("1", "2", "3").map("args" -> _): _*))) ~> route ~> check {
        responseAs[Int] shouldEqual 3
      }
    }

    "return min of non empty args" in {
      Post(Uri("/min").withQuery(Query(List("3", "1", "2").map("args" -> _): _*))) ~> route ~> check {
        responseAs[Int] shouldEqual 1
      }
    }

    "reject on min with empty args" in {
      Post(Uri("/min")) ~> route ~> check {
        rejection shouldEqual MissingQueryParamRejection("args")
      }
    }
  }
} 
Example 36
Source File: InputReadSuite.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema
package akkaHttp
import akka.http.scaladsl.server.Directives.provide
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import ru.tinkoff.tschema.typeDSL.DSLAtom
import shapeless.ops.hlist.Selector
import shapeless.{HList, HNil}

class InputReadSuite extends AnyFlatSpec with Matchers with ScalatestRouteTest {
  import InputReadSuite._
  val route = MkRoute.of(api)(handler)(MagicalInput("Sergey") :: HNil)

  "generated route" should "answer with hello" in {
    Get("/magic") ~> route ~> check {
      responseAs[String] shouldBe "Hello, Sergey!"
    }
  }

}

final case class MagicalInput(value: String)

final case class magicParam[name <: Singleton](name: name) extends DSLAtom

object magicParam {
  implicit def serve[In <: HList, name <: Singleton](implicit
      sel: Selector[In, MagicalInput]
  ): Serve.Add[magicParam[name], In, name, MagicalInput] =
    Serve.serveAddIn(in => provide(sel(in)))
}

object InputReadSuite {
  import syntax._
  def api = get |> operation("magic") |> magicParam("hello") |> $$[String]
  object handler {
    def magic(hello: MagicalInput) = s"Hello, ${hello.value}!"
  }
} 
Example 37
Source File: ResourceDecoderSpec.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.serializers

import java.time.Instant

import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Resources}
import ch.epfl.bluebrain.nexus.iam.client.types.Identity.User
import ch.epfl.bluebrain.nexus.kg.TestHelper
import ch.epfl.bluebrain.nexus.kg.config.Schemas
import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef
import ch.epfl.bluebrain.nexus.kg.resources.{Id, ResourceF, ResourceGraph}
import ch.epfl.bluebrain.nexus.rdf.implicits._
import io.circe.Decoder
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{Inspectors, OptionValues}

class ResourceDecoderSpec
    extends AnyWordSpecLike
    with Matchers
    with Inspectors
    with EitherValues
    with ScalatestRouteTest
    with OptionValues
    with Resources
    with TestHelper {

  private val json                                     = jsonContentOf("/serialization/resource.json")
  private val projectRef                               = ProjectRef(genUUID)
  private val id                                       = url"http://example.com/prefix/myId"
  private val graph                                    = json.toGraph(id).rightValue
  private implicit val decoder: Decoder[ResourceGraph] = ResourceF.resourceGraphDecoder(projectRef)

  private val model = ResourceF(
    Id(projectRef, url"http://example.com/prefix/myId"),
    1L,
    Set(url"https://example.com/vocab/A", url"https://example.com/vocab/B"),
    deprecated = false,
    Map.empty,
    None,
    Instant.parse("2020-01-17T12:45:01.479676Z"),
    Instant.parse("2020-01-17T13:45:01.479676Z"),
    User("john", "bbp"),
    User("brenda", "bbp"),
    Schemas.unconstrainedRef,
    graph
  )

  "A resource" should {
    "be decoded" in {
      json.as[ResourceGraph].rightValue shouldEqual model
    }
  }

} 
Example 38
Source File: MutateRouteSpec.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.http

import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.typesafe.config.ConfigFactory
import org.apache.s2graph.core.Management.JsonModel.Prop
import org.apache.s2graph.core.S2Graph
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec}
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsValue, Json}

class MutateRouteSpec extends WordSpec with Matchers with PlayJsonSupport with ScalaFutures with ScalatestRouteTest with S2GraphMutateRoute with BeforeAndAfterAll {

  import scala.collection.JavaConverters._

  val dbUrl = "jdbc:h2:file:./var/metastore_mutate_route;MODE=MYSQL;AUTO_SERVER=true"
  val config =
    ConfigFactory.parseMap(Map("db.default.url" -> dbUrl).asJava)
  lazy val s2graph = new S2Graph(config.withFallback(ConfigFactory.load()))
  override val logger = LoggerFactory.getLogger(this.getClass)

  override def afterAll(): Unit = {
    s2graph.shutdown(true)
  }

  lazy val routes = mutateRoute

  val serviceName = "kakaoFavorites"
  val columnName = "userName"

  "MutateRoute" should {

    "be able to insert vertex (POST /mutate/vertex/insert)" in {
      s2graph.management.createService(serviceName, "localhost", s"${serviceName}-dev", 1, None)
      s2graph.management.createServiceColumn(serviceName, columnName, "string", Seq(Prop("age", "0", "integer")))

      // {"timestamp": 10, "serviceName": "s2graph", "columnName": "user", "id": 1, "props": {}}
      val param = Json.obj(
        "timestamp" -> 10,
        "serviceName" -> serviceName,
        "columnName" -> columnName,
        "id" -> "user_a",
        "props" -> Json.obj(
          "age" -> 20
        )
      )

      val entity = Marshal(param).to[MessageEntity].futureValue
      val request = Post("/vertex/insert").withEntity(entity)

      request ~> routes ~> check {
        status should ===(StatusCodes.OK)
        contentType should ===(ContentTypes.`application/json`)

        val response = entityAs[JsValue]
        response should ===(Json.toJson(Seq(true)))
      }
    }
  }
} 
Example 39
Source File: CreateDonutTest.scala    From learn-akka   with Apache License 2.0 5 votes vote down vote up
package com.allaboutscala.learn.akka.http

import akka.http.scaladsl.model.{HttpEntity, HttpMethods, HttpRequest, MediaTypes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.util.ByteString
import com.allaboutscala.learn.akka.http.routes.DonutRoutes
import org.scalatest.{Matchers, WordSpec}


class CreateDonutTest
  extends WordSpec
    with Matchers
    with ScalatestRouteTest {

  val donutRoutes = new DonutRoutes().route()

  "Donut API" should {
    "Create a valid Donut when posting JSON to /create-donut path" in {
      val jsonDonutInput = ByteString("""{"name":"plain donut", "price":1.50}""")
      val httpPostCreateDonut = HttpRequest(
        uri = "http://localhost:8080/create-donut",
        method = HttpMethods.POST,
        entity = HttpEntity(MediaTypes.`application/json`, jsonDonutInput))

      httpPostCreateDonut ~> donutRoutes ~> check {
        status.isSuccess() shouldEqual true
        status.intValue() shouldEqual 201
        status.reason shouldEqual "Created"
      }
    }
  }

} 
Example 40
Source File: SchedulerTestkit.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package mass.job

import akka.actor.ActorSystem
import akka.http.scaladsl.testkit.{ RouteTestTimeout, ScalatestRouteTest }
import com.typesafe.scalalogging.StrictLogging
import fusion.inject.guice.testkit.GuiceApplicationTestkit
import fusion.json.jackson.http.JacksonSupport
import org.scalatest.BeforeAndAfterAll
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import scala.concurrent.duration._

abstract class SchedulerTestkit
    extends GuiceApplicationTestkit
    with AnyWordSpecLike
    with Matchers
    with BeforeAndAfterAll
    with ScalatestRouteTest
    with StrictLogging {
  override protected def createActorSystem(): ActorSystem = application.classicSystem
  implicit def routeTestTimeout: RouteTestTimeout = RouteTestTimeout(10.seconds)
  protected val jobScheduler: JobScheduler = injectInstance[JobScheduler]
  protected val jacksonSupport: JacksonSupport = injectInstance[JacksonSupport]
} 
Example 41
Source File: ControllerSpec.scala    From akka-ddd-cqrs-es-example   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.bank.adaptor.util

import akka.http.scaladsl.model.{ HttpEntity, MediaTypes }
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestKitBase
import akka.util.ByteString
import com.github.j5ik2o.scalatestplus.db.{ MySQLdConfig, UserWithPassword }
import com.wix.mysql.distribution.Version.v5_6_21
import io.circe.Encoder
import io.circe.syntax._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.PropertyChecks
import org.scalatest.time.{ Millis, Seconds, Span }
import org.scalatest.{ BeforeAndAfterAll, FreeSpecLike, Matchers }

import scala.concurrent.duration._

object ControllerSpec {

  implicit class JsonOps[A](val self: A) extends AnyVal {
    def toEntity(implicit enc: Encoder[A]): HttpEntity.Strict =
      HttpEntity(MediaTypes.`application/json`, ByteString(self.asJson.noSpaces))
  }

}

abstract class ControllerSpec
    extends FreeSpecLike
    with PropertyChecks
    with Matchers
    with BeforeAndAfterAll
    with ScalaFutures
    with FlywayWithMySQLSpecSupport
    with ScalatestRouteTest
    with TestKitBase {
  override implicit val patienceConfig: PatienceConfig =
    PatienceConfig(timeout = Span(10, Seconds), interval = Span(200, Millis))

  override def afterAll: Unit = cleanUp()

  override protected lazy val mySQLdConfig: MySQLdConfig = MySQLdConfig(
    version = v5_6_21,
    port = Some(12345),
    userWithPassword = Some(UserWithPassword("bank", "passwd")),
    timeout = Some((30 seconds) * sys.env.getOrElse("SBT_TEST_TIME_FACTOR", "1").toDouble)
  )

} 
Example 42
Source File: CustomRouteTestKit.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.testkit

import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestKitBase
import com.typesafe.config.Config
import org.scalatest.Suite
import org.squbs.lifecycle.GracefulStop
import org.squbs.unicomplex.{Unicomplex, UnicomplexBoot}

abstract class CustomRouteTestKit(val boot: UnicomplexBoot) extends {
  implicit override val system = boot.actorSystem
} with TestKitBase with Suite with ScalatestRouteTest with DebugTiming with PortGetter {

  def this() {
    this(CustomTestKit.boot())
  }

  def this(actorSystemName: String) {
    this(CustomTestKit.boot(Option(actorSystemName)))
  }

  def this(config: Config) {
    this(CustomTestKit.boot(config = Option(config)))
  }

  def this(resources: Seq[String], withClassPath: Boolean) {
    this(CustomTestKit.boot(resources = Option(resources), withClassPath = Option(withClassPath)))
  }

  def this(actorSystemName: String, resources: Seq[String], withClassPath: Boolean) {
    this(CustomTestKit.boot(Option(actorSystemName), resources = Option(resources), withClassPath = Option(withClassPath)))
  }

  def this(config: Config, resources: Seq[String], withClassPath: Boolean) {
    this(CustomTestKit.boot(config = Option(config), resources = Option(resources), withClassPath = Option(withClassPath)))
  }

  override protected def beforeAll(): Unit = {
    CustomTestKit.checkInit(system)
  }

  override protected def afterAll(): Unit = {
    Unicomplex(system).uniActor ! GracefulStop
  }
} 
Example 43
Source File: ValidationDirectivesSpec.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.pattern.validation

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.directives.MethodDirectives
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FunSpecLike, Matchers}
import org.squbs.pattern.validation.ValidationDirectives.{validate => _}
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

object MyJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val PersonFormat: RootJsonFormat[Person] = jsonFormat4(Person)
}

class ValidationDirectivesSpec extends FunSpecLike with Matchers with ScalatestRouteTest{

  val ValidationPassed = "Validation Passed"

  import MyJsonProtocol._
  import org.squbs.pattern.validation.SampleValidators._

  val route: Route =
    (path("person") & MethodDirectives.post) {
      entity(as[Person]) { person =>
        import ValidationDirectives._
        validate(person) {
          complete(ValidationPassed)
        }
      }
    }

  describe("ValidationDirectives") {

    it(s"should return [$ValidationPassed] string with 200 for a valid content without middle name") {
      Post("/person", Person("John", "Smith", age = 25)) ~> route ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[String] shouldEqual ValidationPassed
      }
    }

    it(s"should return [$ValidationPassed] string with 200 for a valid content with middle name") {
      Post("/person", Person("John", "Smith", Some("Mike"), age = 25)) ~> route ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[String] shouldEqual ValidationPassed
      }
    }

    it("should reject with Last Name") {
      Post("/person", Person("John", "", age = 25)) ~> route ~> check {
        rejections shouldEqual List(ValidationRejection("Last Name"))
      }
    }

    it("should reject with middleName") {
      Post("/person", Person("John", "Smith", Some(""), age = 25)) ~> route ~> check {
        rejections shouldEqual List(ValidationRejection("middleName"))
      }
    }

    it("should reject with Last Name, middleName, age") {
      Post("/person", Person("John", "", Some(""), age = -1)) ~> route ~> check {
        rejections shouldEqual List(ValidationRejection("Last Name, middleName, age"))
      }
    }
  }

} 
Example 44
Source File: MetricsEndpointSpec.scala    From prometheus-akka-http   with MIT License 5 votes vote down vote up
package com.lonelyplanet.prometheus.api

import java.io.StringWriter

import akka.http.scaladsl.model.HttpCharsets
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.lonelyplanet.prometheus.Utils._
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.{CollectorRegistry, Histogram}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.util.Random

class MetricsEndpointSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest {

  "Metrics endpoint" should "return the correct media type and charset" in {
    val api = createEndpoint(CollectorRegistry.defaultRegistry)
    Get("/metrics") ~> api.routes ~> check {
      mediaType.subType shouldBe "plain"
      mediaType.isText shouldBe true
      mediaType.params shouldBe Map("version" -> "0.0.4")
      charset shouldBe HttpCharsets.`UTF-8`
    }
  }

  it should "return serialized metrics in the prometheus text format" in {
    val registry = new CollectorRegistry()
    val api = createEndpoint(registry)
    val hist = Histogram.build().name(RandomTestName).help(RandomTestHelp).linearBuckets(0, 1, 10).register(registry)

    hist.observe(Math.abs(Random.nextDouble()))

    Get("/metrics") ~> api.routes ~> check {
      val resp = responseAs[String]
      val writer = new StringWriter()
      TextFormat.write004(writer, registry.metricFamilySamples())

      resp shouldBe writer.toString
    }
  }

  private val RandomTestName = generateRandomStringOfLength(16)
  private val RandomTestHelp = generateRandomStringOfLength(16)

  private def createEndpoint(collectorRegistry: CollectorRegistry) = {
    new MetricsEndpoint(collectorRegistry)
  }

} 
Example 45
Source File: HealthEndpointSpec.scala    From akka-http-health   with MIT License 5 votes vote down vote up
package io.github.lhotari.akka.http.health

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.mockito.Mockito._
import org.scalatest.{FunSpec, Matchers}
import org.scalatestplus.mockito.MockitoSugar

class HealthEndpointSpec extends FunSpec with Matchers with ScalatestRouteTest with MockitoSugar with HealthEndpoint {
  val mockChecker1 = mock[HealthChecker]
  val mockChecker2 = mock[HealthChecker]

  override protected def createCheckers(): Seq[HealthChecker] = Seq(mockChecker1, mockChecker2)

  describe("health endpoint") {
    it("should complete successfully when all checks are ok") {
      checkers.foreach(checker => when(checker.isHealthy()).thenReturn(true))
      Get("/health") ~> Route.seal(createHealthRoute()) ~> check {
        status shouldEqual StatusCodes.OK
      }
    }

    it("should complete successfully when a different endpoint is specified") {
      checkers.foreach(checker => when(checker.isHealthy()).thenReturn(true))
      Get("/another-endpoint") ~> Route.seal(createHealthRoute("another-endpoint")) ~> check {
        status shouldEqual StatusCodes.OK
      }
    }

    it("should return error when the wrong endpoint is specified") {
      checkers.foreach(checker => when(checker.isHealthy()).thenReturn(true))
      Get("/health") ~> Route.seal(createHealthRoute("another-endpoint")) ~> check {
        status shouldEqual StatusCodes.NotFound
      }
    }

    it("should return error when a check fails") {
      when(mockChecker2.isHealthy()).thenReturn(false)
      Get("/health") ~> Route.seal(createHealthRoute()) ~> check {
        status shouldEqual StatusCodes.ServiceUnavailable
      }
    }

    it("should have started each checker exactly once") {
      checkers.foreach(checker => verify(checker).start())
    }
  }

} 
Example 46
Source File: AkkaHttpSessionStoreTest.scala    From akka-http-pac4j   with Mozilla Public License 2.0 5 votes vote down vote up
package com.stackstate.pac4j.http

import java.util.Optional

import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.stackstate.pac4j.AkkaHttpWebContext
import com.stackstate.pac4j.store.{ForgetfulSessionStorage, InMemorySessionStorage}
import org.scalatest.{Matchers, WordSpecLike}

import scala.concurrent.duration._

class AkkaHttpSessionStoreTest extends WordSpecLike with Matchers with ScalatestRouteTest {
  "AkkaHttpSessionStore.get" should {
    "return null when the data is not available" in {
      new AkkaHttpSessionStore().get(
        new AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME),
        "mykey"
      ) shouldBe Optional.empty()
    }

    "return the data when available" in {
      val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME)
      new AkkaHttpSessionStore().set(context, "mykey", "yooo")
      new AkkaHttpSessionStore().get(context, "mykey") shouldBe Optional.of("yooo")
    }
  }
} 
Example 47
Source File: EchoServiceSpec.scala    From akka-http-spring-boot   with Apache License 2.0 5 votes vote down vote up
package sample

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.github.scalaspring.akka.http.AkkaStreamsAutoConfiguration
import com.github.scalaspring.scalatest.TestContextManagement
import org.scalatest.{FlatSpec, Matchers}
import org.springframework.context.annotation.{Configuration, Import}
import org.springframework.test.context.ContextConfiguration

@Configuration
@ContextConfiguration(classes = Array(classOf[EchoServiceSpec]))
@Import(Array(classOf[AkkaStreamsAutoConfiguration]))
class EchoServiceSpec extends FlatSpec with TestContextManagement with EchoService with ScalatestRouteTest with Matchers {

  "Echo service" should "echo" in {
    Get(s"/echo/test") ~> route ~> check {
      status shouldBe OK
      responseAs[String] shouldBe "test"
    }
  }

} 
Example 48
Source File: RouteTestSpec.scala    From akka-http-spring-boot   with Apache License 2.0 5 votes vote down vote up
package com.github.scalaspring.akka.http

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.github.scalaspring.akka.http.RouteTestSpec.EchoService
import com.typesafe.scalalogging.StrictLogging
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers}


class RouteTestSpec extends FlatSpec with EchoService with ScalatestRouteTest with Matchers with ScalaFutures with StrictLogging {

  "Echo service" should "echo" in {
    Get(s"/single/echo/hello") ~> route ~> check {
      status shouldBe OK
    }
  }

}


object RouteTestSpec {

  trait EchoService extends AkkaHttpService {
    abstract override def route: Route = {
      get {
        path("single"/ "echo" / Segment) { name =>
          complete(name)
        }
      }
    } ~ super.route
  }

} 
Example 49
Source File: DevApiSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.interfaces.http

import mist.api.data._
import mist.api.encoding.JsSyntax._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import io.hydrosphere.mist.core.CommonData.{JobParams, RunJobRequest}
import io.hydrosphere.mist.core.MockitoSugar
import io.hydrosphere.mist.core.CommonData.Action
import io.hydrosphere.mist.master.JobDetails.{Source, Status}
import io.hydrosphere.mist.master.execution.ExecutionInfo
import io.hydrosphere.mist.master.MainService
import io.hydrosphere.mist.master.interfaces.JsonCodecs
import io.hydrosphere.mist.master.models.{DevJobStartRequest, DevJobStartRequestModel}
import org.scalatest.{FunSpec, Matchers}

import scala.concurrent.Promise

class DevApiSpec extends FunSpec with Matchers with ScalatestRouteTest with MockitoSugar {

  import JsonCodecs._
  import io.hydrosphere.mist.master.TestUtils._

  it("should start job in dev mode") {
    val master = mock[MainService]
    val api = DevApi.devRoutes(master)

    val req = DevJobStartRequestModel("simple-context", "path", "className", None, None, None, "foo")

    val promise = Promise[JsData]
    promise.success(JsUnit)

    when(master.devRun(any[DevJobStartRequest], any[Source], any[Action]))
      .thenSuccess(ExecutionInfo(
        RunJobRequest("id", JobParams("path", "className", JsMap.empty, Action.Execute)),
        promise
      ))

    Post("/v2/hidden/devrun", req) ~> api ~> check {
      status shouldBe StatusCodes.OK
    }
  }
} 
Example 50
Source File: HTTPInterfaceSpec.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package akka

import akka.event.Logging
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.QueueOfferResult
import akka.stream.QueueOfferResult.Enqueued
import akka.stream.scaladsl.SourceQueueWithComplete
import akka.testkit.{TestActorRef, TestProbe}
import com.omearac.consumers.{DataConsumer, EventConsumer}
import com.omearac.http.routes.{ConsumerCommands, ProducerCommands}
import com.omearac.producers.DataProducer
import org.scalatest.{Matchers, WordSpec}

import scala.concurrent.Future


class HTTPInterfaceSpec extends WordSpec
    with Matchers with ScalatestRouteTest
    with ConsumerCommands with ProducerCommands {

    val log = Logging(system, this.getClass.getName)

    //Mocks for DataConsumer Tests
    val dataConsumer = TestActorRef(new DataConsumer)
    val manager = TestProbe()
    dataConsumer.underlyingActor.consumerStreamManager = manager.ref

    //Mocks for EventConsumer Tests
    val eventConsumer = TestActorRef(new EventConsumer)
    eventConsumer.underlyingActor.consumerStreamManager = manager.ref

    //Mocks for DataProducer Tests
    val dataProducer = TestActorRef(new DataProducer)
    val mockProducerStream: SourceQueueWithComplete[Any] = new SourceQueueWithComplete[Any] {
        override def complete(): Unit = println("complete")

        override def fail(ex: Throwable): Unit = println("fail")

        override def offer(elem: Any): Future[QueueOfferResult] = Future{Enqueued}

        override def watchCompletion(): Future[Done] = Future{Done}
    }


    "The HTTP interface to control the DataConsumerStream" should {
        "return a Already Stopped message for GET requests to /data_consumer/stop" in {
            Get("/data_consumer/stop") ~> dataConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Data Consumer Stream Already Stopped"
            }
        }

        "return a Stream Started response for GET requests to /data_consumer/start" in {
            Get("/data_consumer/start") ~> dataConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Data Consumer Stream Started"
            }
        }
    }

    "The HTTP interface to control the EventConsumerStream" should {
        "return a Already Stopped message for GET requests to /event_consumer/stop" in {
            Get("/event_consumer/stop") ~> eventConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Event Consumer Stream Already Stopped"
            }
        }

        "return a Stream Started response for GET requests to /data_consumer/start" in {
            Get("/event_consumer/start") ~> eventConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Event Consumer Stream Started"
            }
        }
    }

    "The HTTP interface to tell the DataProducer Actor to publish messages to Kafka" should {
        "return a Messages Produced message for GET requests to /data_producer/produce/10" in {
            dataProducer.underlyingActor.producerStream = mockProducerStream
            val producing = dataProducer.underlyingActor.publishData
            dataProducer.underlyingActor.context.become(producing)

            Get("/data_producer/produce/10") ~> producerHttpCommands ~> check {
                responseAs[String] shouldEqual "10 messages Produced as Ordered, Boss!"
            }
        }
    }
} 
Example 51
Source File: OrderServiceTest.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.integration

import scala.concurrent.duration._
import scala.xml.NodeSeq
import akka.actor.Props

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest

import org.scalatest.{ Matchers, WordSpec }
 
class OrderServiceTest extends WordSpec 
    with Matchers 
    with OrderService
    with ScalatestRouteTest {

  implicit val executionContext = system.dispatcher
  implicit val requestTimeout = akka.util.Timeout(1 second)
  val processOrders = 
    system.actorOf(Props(new ProcessOrders), "orders")

  "The order service" should {
    "return NotFound if the order cannot be found" in {
      Get("/orders/1") ~> routes ~> check {
        status shouldEqual StatusCodes.NotFound
      }
    }

    "return the tracking order for an order that was posted" in {
      val xmlOrder = 
      <order><customerId>customer1</customerId>
        <productId>Akka in action</productId>
        <number>10</number>
      </order>
      
      Post("/orders", xmlOrder) ~> routes ~> check {
        status shouldEqual StatusCodes.OK
        val xml = responseAs[NodeSeq]
        val id = (xml \\ "id").text.toInt
        val orderStatus = (xml \\ "status").text
        id shouldEqual 1
        orderStatus shouldEqual "received"
      }
      Get("/orders/1") ~> routes ~> check {
        status shouldEqual StatusCodes.OK
        val xml = responseAs[NodeSeq]
        val id = (xml \\ "id").text.toInt
        val orderStatus = (xml \\ "status").text
        id shouldEqual 1
        orderStatus shouldEqual "processing"
      }
    }
  }
} 
Example 52
Source File: WorkerServiceSpec.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.services

import scala.concurrent.duration._
import scala.util.{Success, Try}

import akka.actor.ActorRef
import akka.http.scaladsl.model.headers.`Cache-Control`
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import akka.testkit.TestActor.{AutoPilot, KeepRunning}
import akka.testkit.{TestKit, TestProbe}
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import org.apache.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
import org.apache.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryWorkerConfig, ResolveWorkerId}
import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, ResolveWorkerIdResult, WorkerConfig}
import org.apache.gearpump.cluster.TestUtil
import org.apache.gearpump.cluster.worker.{WorkerId, WorkerSummary}
// NOTE: This cannot be removed!!!
import org.apache.gearpump.services.util.UpickleUtil._

class WorkerServiceSpec
  extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {

  override def testConfig: Config = TestUtil.DEFAULT_CONFIG

  protected def actorRefFactory = system

  val mockWorker = TestProbe()

  protected def master = mockMaster.ref

  protected def workerRoute = new WorkerService(master, system).route

  mockWorker.setAutoPilot {
    new AutoPilot {
      def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
        case GetWorkerData(workerId) =>
          sender ! WorkerData(WorkerSummary.empty)
          KeepRunning
        case QueryWorkerConfig(workerId) =>
          sender ! WorkerConfig(null)
          KeepRunning
        case QueryHistoryMetrics(path, _, _, _) =>
          sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
          KeepRunning
      }
    }
  }

  val mockMaster = TestProbe()
  mockMaster.setAutoPilot {
    new AutoPilot {
      def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
        case ResolveWorkerId(workerId) =>
          sender ! ResolveWorkerIdResult(Success(mockWorker.ref))
          KeepRunning
      }
    }
  }

  "ConfigQueryService" should "return config for worker" in {
    implicit val customTimeout = RouteTestTimeout(15.seconds)
    (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(0, 0L))}/config")
      ~> workerRoute) ~> check {
      val responseBody = responseAs[String]
      val config = Try(ConfigFactory.parseString(responseBody))
      assert(config.isSuccess)
    }
  }

  it should "return WorkerData" in {
    implicit val customTimeout = RouteTestTimeout(15.seconds)
    (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(1, 0L))}")
      ~> workerRoute) ~> check {
      val responseBody = responseAs[String]
      val config = Try(ConfigFactory.parseString(responseBody))
      assert(config.isSuccess)

      // Check the header, should contains no-cache header.
      // Cache-Control:no-cache, max-age=0
      val noCache = header[`Cache-Control`].get.value()
      assert(noCache == "no-cache, max-age=0")
    }
  }

  "MetricsQueryService" should "return history metrics" in {
    implicit val customTimeout = RouteTestTimeout(15.seconds)
    (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(0, 0L))}/metrics/worker")
      ~> workerRoute) ~> check {
      val responseBody = responseAs[String]
      val config = Try(ConfigFactory.parseString(responseBody))
      assert(config.isSuccess)
    }
  }

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }
} 
Example 53
Source File: AdminServiceSpec.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.services

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

import akka.actor.ActorSystem
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import com.typesafe.config.Config
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import org.apache.gearpump.cluster.TestUtil

// NOTE: This cannot be removed!!!
import org.apache.gearpump.services.util.UpickleUtil._

class AdminServiceSpec
  extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {

  override def testConfig: Config = TestUtil.DEFAULT_CONFIG

  implicit def actorSystem: ActorSystem = system

  it should "shutdown the ActorSystem when receiving terminate" in {
    val route = new AdminService(actorSystem).route
    implicit val customTimeout = RouteTestTimeout(15.seconds)
    (Post(s"/terminate") ~> route) ~> check {
      assert(status.intValue() == 404)
    }

    Await.result(actorSystem.whenTerminated, 20.seconds)

    // terminate should terminate current actor system
    assert(actorSystem.whenTerminated.isCompleted)
  }
} 
Example 54
Source File: StaticServiceSpec.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.services

import scala.concurrent.duration._
import scala.util.Try

import akka.http.scaladsl.model.headers.`Cache-Control`
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import org.apache.gearpump.cluster.TestUtil
import org.apache.gearpump.util.Constants
// NOTE: This cannot be removed!!!
import org.apache.gearpump.services.util.UpickleUtil._

class StaticServiceSpec
  extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {

  override def testConfig: Config = TestUtil.UI_CONFIG
  private val supervisorPath = system.settings.config.getString(
    Constants.GEARPUMP_SERVICE_SUPERVISOR_PATH)

  protected def route = new StaticService(system, supervisorPath).route

  it should "return version" in {
    implicit val customTimeout = RouteTestTimeout(15.seconds)
    (Get(s"/version") ~> route) ~> check {
      val responseBody = responseAs[String]
      val config = Try(ConfigFactory.parseString(responseBody))
      assert(responseBody == "Unknown-Version")

      // By default, it will be cached.
      assert(header[`Cache-Control`].isEmpty)
    }
  }

  it should "get correct supervisor path" in {
    implicit val customTimeout = RouteTestTimeout(15.seconds)
    (Get(s"/supervisor-actor-path") ~> route) ~> check {
      val responseBody = responseAs[String]
      val defaultSupervisorPath = ""
      assert(responseBody == defaultSupervisorPath)
    }
  }
} 
Example 55
Source File: DefaultRouteTest.scala    From scala-for-beginners   with Apache License 2.0 5 votes vote down vote up
package com.allaboutscala.donutstore.httpserver.routes


import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{Matchers, WordSpec}

import scala.io.Source



class DefaultRouteTest
  extends WordSpec
    with Matchers
    with ScalatestRouteTest
    with TestBase {

  val defaultRoutes = new DefaultRoute().routes()

  "DonutStore" can {
    "have a welcome page at the root end point" in {
      Get("/") ~> defaultRoutes ~> check {
        responseAs[String] shouldEqual welcomePage()
      }
    }
  }

  private def welcomePage(): String = {
    val path = sys.env.getOrElse("WELCOME_PAGE_PATH", "httpServer/src/main/resources/welcome.html")
    Source.fromFile(path).mkString
  }
} 
Example 56
Source File: PublishSpec.scala    From sns   with Apache License 2.0 5 votes vote down vote up
package me.snov.sns.api

import java.util.concurrent.TimeUnit

import akka.actor.ActorRef
import akka.http.scaladsl.model.{FormData, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.{TestActor, TestProbe}
import akka.util.Timeout
import me.snov.sns.actor.PublishActor.CmdPublish
import me.snov.sns.model.{Message, MessageAttribute}
import org.scalatest.{Matchers, WordSpec}

class PublishSpec extends WordSpec with Matchers with ScalatestRouteTest {
  implicit val timeout = new Timeout(100, TimeUnit.MILLISECONDS)

  val probe = TestProbe()
  val route = PublishApi.route(probe.ref)

  "Publish requires topic ARN" in {
    val params = Map("Action" -> "Publish")
    Post("/", FormData(params)) ~> route ~> check {
      status shouldBe StatusCodes.BadRequest
    }
  }

  "Sends publish command" in {
    val params = Map(
      "Action" -> "Publish",
      "TopicArn" -> "foo",
      "Message" -> "bar"
    )

    probe.setAutoPilot(new TestActor.AutoPilot {
      def run(sender: ActorRef, msg: Any) = {
        sender ! Message(Map("default" -> "foo"))
        this
      }
    })
    Post("/", FormData(params)) ~> route ~> check {
      probe.expectMsg(CmdPublish("foo", Map("default" -> "bar"), Map.empty))
    }
  }

  "Sends publish command to TargetArn" in {
    val params = Map(
      "Action" -> "Publish",
      "TargetArn" -> "foo",
      "Message" -> "bar"
    )

    probe.setAutoPilot(new TestActor.AutoPilot {
      def run(sender: ActorRef, msg: Any) = {
        sender ! Message(Map("default" -> "foo"))
        this
      }
    })
    Post("/", FormData(params)) ~> route ~> check {
      probe.expectMsg(CmdPublish("foo", Map("default" -> "bar"), Map.empty))
    }
  }

  "Sends publish command with attributes" in {
    val params = Map(
      "Action" -> "Publish",
      "TopicArn" -> "foo",
      "Message" -> "bar",
      "MessageAttributes.entry.1.Value.DataType" -> "String",
      "MessageAttributes.entry.1.Value.StringValue" -> "AttributeValue",
      "MessageAttributes.entry.1.Name" -> "AttributeName"
    )

    probe.setAutoPilot(new TestActor.AutoPilot {
      def run(sender: ActorRef, msg: Any) = {
        sender ! Message(Map("default" -> "foo"), messageAttributes = Map("AttributeName" -> MessageAttribute("StringValue", "AttributeValue")))
        this
      }
    })
    Post("/", FormData(params)) ~> route ~> check {
      probe.expectMsg(CmdPublish("foo", Map("default" -> "bar"),Map("AttributeName" -> MessageAttribute("StringValue", "AttributeValue"))))
    }
  }
} 
Example 57
Source File: TopicSpec.scala    From sns   with Apache License 2.0 5 votes vote down vote up
package me.snov.sns.api

import java.util.concurrent.TimeUnit

import akka.actor.ActorRef
import akka.http.scaladsl.model.{FormData, HttpResponse, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.{TestActor, TestProbe}
import akka.util.Timeout
import me.snov.sns.actor.SubscribeActor.{CmdDeleteTopic, CmdCreateTopic}
import me.snov.sns.model.Topic
import org.scalatest.{Matchers, WordSpec}

class TopicSpec extends WordSpec with Matchers with ScalatestRouteTest {
  implicit val timeout = new Timeout(100, TimeUnit.MILLISECONDS)

  val probe = TestProbe()
  val route = TopicApi.route(probe.ref)

  "Requires topic name" in {
    Post("/", FormData(Map("Action" -> "CreateTopic"))) ~> route ~> check {
      status shouldBe StatusCodes.BadRequest
    }
  }

  "Validates topic name" in {
    Post("/", FormData(Map("Action" -> "CreateTopic", "Name" -> "f$$"))) ~> route ~> check {
      status shouldBe StatusCodes.BadRequest
    }
  }

  "TopicDelete validates topic name" in {
    Post("/", FormData(Map("Action" -> "DeleteTopic", "TopicArn" -> "f$$"))) ~> route ~> check {
      status shouldBe StatusCodes.BadRequest
    }
  }

  "Sends create command to actor" in {
    probe.setAutoPilot(new TestActor.AutoPilot {
      def run(sender: ActorRef, msg: Any) = {
        sender ! new Topic("foo", "bar")
        this
      }
    })
    Post("/", FormData(Map("Action" -> "CreateTopic", "Name" -> "foo"))) ~> route ~> check {
      probe.expectMsg(CmdCreateTopic("foo"))
    }
  }

  "Sends delete command to actor" in {
    probe.setAutoPilot(new TestActor.AutoPilot {
      def run(sender: ActorRef, msg: Any) = {
        sender ! new Topic("foo", "bar")
        this
      }
    })
    Post("/", FormData(Map("Action" -> "DeleteTopic", "TopicArn" -> "arn-foo"))) ~> route ~> check {
      probe.expectMsg(CmdDeleteTopic("arn-foo"))
    }
  }
} 
Example 58
Source File: EndpointsTest.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.akkahttp.server

import akka.http.scaladsl.model.StatusCodes.InternalServerError
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import endpoints4s.algebra

import scala.concurrent.Future
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec


class EndpointsEntitiesTestApi extends EndpointsTestApi with JsonEntities

class EndpointsTest extends AnyWordSpec with Matchers with ScalatestRouteTest {

  object TestRoutes extends EndpointsEntitiesTestApi {

    val singleStaticGetSegment = endpoint[Unit, Unit](
      get(path / "segment1"),
      (_: Unit) => complete("Ok")
    ).implementedBy(_ => ())

    val smokeEndpointSyncRoute =
      smokeEndpoint.implementedBy(_ => sys.error("Sorry."))

    val smokeEndpointAsyncRoute =
      smokeEndpoint.implementedByAsync(_ => Future.failed(new Exception("Sorry.")))

  }

  "Single segment route" should {

    "match single segment request" in {
      // tests:
      Get("/segment1") ~> TestRoutes.singleStaticGetSegment ~> check {
        responseAs[String] shouldEqual "Ok"
      }
    }
    "leave GET requests to other paths unhandled" in {
      Get("/segment1/segment2") ~> TestRoutes.singleStaticGetSegment ~> check {
        handled shouldBe false
      }
    }

  }

  "Routes" should {

    "Handle exceptions by default" in {
      Get("/user/foo/description?name=a&age=1") ~> TestRoutes.smokeEndpointAsyncRoute ~> check {
        handled shouldBe true
        status shouldBe InternalServerError
        responseAs[String] shouldBe "[\"Sorry.\"]"
      }
    }

  }

} 
Example 59
Source File: RoutesSpec.scala    From Learn-Scala-Programming   with MIT License 5 votes vote down vote up
package ch14

import akka.actor.ActorRef
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch14.Commands.{PurchaseArticles, RestockArticles}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{Matchers, WordSpec}

import scala.concurrent.duration._

class RoutesSpec
    extends WordSpec
    with Matchers
    with ScalaFutures
    with ScalatestRouteTest
    with Routes {

  override lazy val config: Config = Config.load()

  DB.initialize(config.database)

  override lazy val inventory: ActorRef =
    system.actorOf(InventoryActor.props, "inventory")

  "Routes" should {
    "return no articles in the beginning" in {
      val request = HttpRequest(uri = "/inventory")
      implicit val timeout: Duration = 3.seconds
      request ~> routes ~> check {
        status shouldBe StatusCodes.OK
        contentType shouldBe ContentTypes.`application/json`
        entityAs[String] shouldBe """{"state":{}}"""
      }
    }
    "be able to add article (POST /articles/eggs)" in {
      val request = Post("/articles/eggs")
      request ~> routes ~> check {
        status shouldBe StatusCodes.Created
        contentType shouldBe ContentTypes.`application/json`
        entityAs[String] shouldBe """{"name":"eggs","count":0}"""
      }
    }
    "not be able to delete article (delete /articles/no)" in {
      val request = Delete("/articles/no-such-article")
      request ~> Route.seal(routes) ~> check {
        status shouldBe StatusCodes.NotFound
      }
    }
    "not be able to add article twice (POST /articles/eggs)" in {
      val request = Post("/articles/eggs")
      request ~> routes ~> check {
        status shouldBe StatusCodes.Conflict
      }
    }
    "be able to restock articles (POST /restock)" in {
      val restock = RestockArticles(Map("eggs" -> 10, "chocolate" -> 20))
      val entity  = Marshal(restock).to[MessageEntity].futureValue // futureValue is from ScalaFutures
      val request = Post("/restock").withEntity(entity)
      request ~> routes ~> check {
        status shouldBe StatusCodes.OK
        contentType shouldBe ContentTypes.`application/json`
        entityAs[String] shouldBe """{"stock":{"eggs":10,"chocolate":20}}"""
      }
    }
    "be able to purchase articles (POST /purchase)" in {
      val restock = PurchaseArticles(Map("eggs" -> 5, "chocolate" -> 10))
      val entity  = Marshal(restock).to[MessageEntity].futureValue // futureValue is from ScalaFutures
      val request = Post("/purchase").withEntity(entity)
      request ~> routes ~> check {
        status shouldBe StatusCodes.OK
        contentType shouldBe ContentTypes.`application/json`
        entityAs[String] shouldBe """{"order":{"eggs":5,"chocolate":10}}"""
      }
    }
    "not be able to purchase articles (POST /purchase)" in {
      val restock = PurchaseArticles(Map("eggs" -> 50, "chocolate" -> 10))
      val entity  = Marshal(restock).to[MessageEntity].futureValue // futureValue is from ScalaFutures
      val request = Post("/purchase").withEntity(entity)
      request ~> routes ~> check {
        status shouldBe StatusCodes.Conflict
      }
    }
  }
} 
Example 60
Source File: ApiTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.monitoring.metrics

import akka.http.scaladsl.model.headers.HttpEncodings._
import akka.http.scaladsl.model.headers.{`Accept-Encoding`, `Content-Encoding`, HttpEncoding, HttpEncodings}
import akka.http.scaladsl.model.{HttpCharsets, HttpEntity, HttpResponse}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import kamon.prometheus.PrometheusReporter
import org.apache.openwhisk.core.monitoring.metrics.OpenWhiskEvents.MetricConfig
import org.junit.runner.RunWith
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.junit.JUnitRunner
import org.scalatest.matchers.Matcher
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
import pureconfig.loadConfigOrThrow
import io.prometheus.client.CollectorRegistry
import pureconfig.generic.auto._

import scala.concurrent.duration.DurationInt

@RunWith(classOf[JUnitRunner])
class ApiTests
    extends FlatSpec
    with Matchers
    with ScalatestRouteTest
    with EventsTestHelper
    with ScalaFutures
    with BeforeAndAfterAll {
  implicit val timeoutConfig = PatienceConfig(1.minute)

  private var api: PrometheusEventsApi = _
  private var consumer: EventConsumer = _

  override protected def beforeAll(): Unit = {
    super.beforeAll()
    CollectorRegistry.defaultRegistry.clear()
    val metricConfig = loadConfigOrThrow[MetricConfig](system.settings.config, "user-events")
    val mericRecorder = PrometheusRecorder(new PrometheusReporter, metricConfig)
    consumer = createConsumer(56754, system.settings.config, mericRecorder)
    api = new PrometheusEventsApi(consumer, createExporter())
  }

  protected override def afterAll(): Unit = {
    consumer.shutdown().futureValue
    super.afterAll()
  }

  behavior of "EventsApi"

  it should "respond ping request" in {
    Get("/ping") ~> api.routes ~> check {
      //Due to retries using a random port does not immediately result in failure
      handled shouldBe true
    }
  }

  it should "respond metrics request" in {
    Get("/metrics") ~> `Accept-Encoding`(gzip) ~> api.routes ~> check {
      contentType.charsetOption shouldBe Some(HttpCharsets.`UTF-8`)
      contentType.mediaType.params("version") shouldBe "0.0.4"
      response should haveContentEncoding(gzip)
    }
  }

  private def haveContentEncoding(encoding: HttpEncoding): Matcher[HttpResponse] =
    be(encoding) compose {
      (_: HttpResponse).header[`Content-Encoding`].map(_.encodings.head).getOrElse(HttpEncodings.identity)
    }

  private def createExporter(): PrometheusExporter = () => HttpEntity(PrometheusExporter.textV4, "foo".getBytes)
} 
Example 61
Source File: PrometheusTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.common
import akka.http.scaladsl.coding.Gzip
import akka.http.scaladsl.model.{HttpCharsets, HttpResponse}
import akka.http.scaladsl.model.headers.HttpEncodings.gzip
import akka.http.scaladsl.model.headers.{`Accept-Encoding`, `Content-Encoding`, HttpEncoding, HttpEncodings}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.unmarshalling.Unmarshal
import com.typesafe.config.ConfigFactory
import kamon.Kamon
import org.junit.runner.RunWith
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.junit.JUnitRunner
import org.scalatest.matchers.Matcher
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import scala.concurrent.duration._

@RunWith(classOf[JUnitRunner])
class PrometheusTests extends FlatSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll with ScalaFutures {
  behavior of "Prometheus"

  override protected def beforeAll(): Unit = {
    super.beforeAll()
    //Modify Kamon to have a very small tick interval
    val newConfig = ConfigFactory.parseString("""kamon {
      |  metric {
      |    tick-interval = 50 ms
      |    optimistic-tick-alignment = no
      |  }
      |}""".stripMargin).withFallback(ConfigFactory.load())
    Kamon.reconfigure(newConfig)
  }

  override protected def afterAll(): Unit = {
    super.afterAll()
    Kamon.reconfigure(ConfigFactory.load())
  }

  it should "respond to /metrics" in {
    val api = new KamonPrometheus
    Kamon.counter("foo_bar").withoutTags().increment(42)

    //Sleep to ensure that Kamon metrics are pushed to reporters
    Thread.sleep(2.seconds.toMillis)
    Get("/metrics") ~> `Accept-Encoding`(gzip) ~> api.route ~> check {
      // Check that response confirms to what Prometheus scrapper accepts
      contentType.charsetOption shouldBe Some(HttpCharsets.`UTF-8`)
      contentType.mediaType.params("version") shouldBe "0.0.4"
      response should haveContentEncoding(gzip)

      val responseText = Unmarshal(Gzip.decodeMessage(response)).to[String].futureValue
      withClue(responseText) {
        responseText should include("foo_bar")
      }
    }
    api.close()
  }

  it should "not be enabled by default" in {
    Get("/metrics") ~> MetricsRoute() ~> check {
      handled shouldBe false
    }
  }

  private def haveContentEncoding(encoding: HttpEncoding): Matcher[HttpResponse] =
    be(encoding) compose {
      (_: HttpResponse).header[`Content-Encoding`].map(_.encodings.head).getOrElse(HttpEncodings.identity)
    }
} 
Example 62
Source File: KafkaMetricsTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.connector.kafka

import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import org.apache.kafka.common.MetricName
import org.apache.kafka.common.metrics.{KafkaMetric, Measurable, MetricConfig}
import org.apache.kafka.common.utils.Time
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{FlatSpec, Matchers}
import spray.json._
import spray.json.DefaultJsonProtocol._

import scala.collection.JavaConverters._
import scala.concurrent.Future

@RunWith(classOf[JUnitRunner])
class KafkaMetricsTests extends FlatSpec with Matchers with ScalatestRouteTest {
  behavior of "KafkaMetrics"

  it should "render metrics as json" in {
    val metricName = new MetricName(
      "bytes-consumed-total",
      "consumer-fetch-manager-metrics",
      "The total number of bytes consumed",
      Map("client-id" -> "event-consumer").asJava)
    val valueProvider: Measurable = (config: MetricConfig, now: Long) => 42
    val metrics = new KafkaMetric(this, metricName, valueProvider, new MetricConfig(), Time.SYSTEM)

    val route = KafkaMetricRoute(() => Future.successful(Map(metricName -> metrics)))
    Get("/metrics/kafka") ~> route ~> check {
      //Due to retries using a random port does not immediately result in failure
      handled shouldBe true
      responseAs[JsArray].elements.size shouldBe 1
    }
  }
} 
Example 63
Source File: TestKit.scala    From introduction-to-akkahttp   with Apache License 2.0 5 votes vote down vote up
package com.shashank.akkahttp.basic.routing

import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives._
import akka.stream.{ActorMaterializer, Materializer}
import org.scalatest.{ Matchers, WordSpec }
import akka.http.scaladsl.testkit.ScalatestRouteTest



object TestKit extends WordSpec with Matchers with ScalatestRouteTest {

  def main(args: Array[String]) {

    val route =
      path("welcome"){
        get{
          complete {
            "welcome to rest service"
          }
        }
      } ~
        path("demo"){
          get{
            complete {
              "welcome to demonstration"
            }
          }
        }


    val getRequest = HttpRequest(GET, "/welcome")

    getRequest ~> route ~> check {
      status.intValue shouldEqual 200
      entityAs[String] shouldEqual "welcome to rest service"
    }

    system.terminate()
  }

} 
Example 64
Source File: HttpMetricsDirectivesSpec.scala    From akka-http-metrics   with Apache License 2.0 5 votes vote down vote up
package fr.davit.akka.http.metrics.core.scaladsl.server

import akka.http.scaladsl.marshalling.PredefinedToEntityMarshallers._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import fr.davit.akka.http.metrics.core.TestRegistry
import fr.davit.akka.http.metrics.core.scaladsl.model.PathLabelHeader
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class HttpMetricsDirectivesSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest {

  import HttpMetricsDirectives._

  "HttpMetricsDirectives" should "expose the registry" in {
    implicit val marshaller = StringMarshaller.compose[TestRegistry](r => s"active: ${r.active.value()}")
    val registry            = new TestRegistry()
    registry.active.inc()

    val route = path("metrics") {
      metrics(registry)
    }

    Get("/metrics") ~> route ~> check {
      responseAs[String] shouldBe "active: 1"
    }
  }

  it should "put label on path" in {
    val route = pathPrefixLabeled("api") {
      pathPrefix("user" / LongNumber) { _ =>
        path("address") {
          complete(StatusCodes.OK)
        }
      }
    }

    Get("/api/user/1234/address") ~> route ~> check {
      header[PathLabelHeader] shouldBe Some(PathLabelHeader("/api"))
    }
  }

  it should "combine labelled segments" in {
    val route = pathPrefixLabeled("api") {
      pathPrefixLabeled("user" / LongNumber, "user/:userId") { _ =>
        pathLabeled("address") {
          complete(StatusCodes.OK)
        }
      }
    }

    Get("/api/user/1234/address") ~> route ~> check {
      header[PathLabelHeader] shouldBe Some(PathLabelHeader("/api/user/:userId/address"))
    }
  }

  it should "not add extra header when label directives are not used" in {
    val route = pathPrefix("api") {
      pathPrefix("user" / LongNumber) { _ =>
        path("address") {
          complete(StatusCodes.OK)
        }
      }
    }

    Get("/api/user/1234/address") ~> route ~> check {
      header[PathLabelHeader] shouldBe empty
    }
  }
} 
Example 65
Source File: PrometheusMarshallersSpec.scala    From akka-http-metrics   with Apache License 2.0 5 votes vote down vote up
package fr.davit.akka.http.metrics.prometheus.marshalling

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import fr.davit.akka.http.metrics.core.HttpMetricsRegistry.StatusGroupDimension
import fr.davit.akka.http.metrics.core.scaladsl.server.HttpMetricsDirectives.metrics
import fr.davit.akka.http.metrics.prometheus.{PrometheusRegistry, PrometheusSettings}
import io.prometheus.client.CollectorRegistry
import org.scalatest.BeforeAndAfterAll
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration._

class PrometheusMarshallersSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll {

  trait Fixture extends PrometheusMarshallers {

    val registry = PrometheusRegistry(
      new CollectorRegistry(),
      PrometheusSettings.default.withIncludeStatusDimension(true)
    )

    io.prometheus.client.Counter
      .build("other_metric", "An other metric")
      .register(registry.underlying)
  }

  override def afterAll(): Unit = {
    cleanUp()
    super.afterAll()
  }

  "PrometheusMarshallers" should "expose metrics as prometheus format" in new Fixture {
    // register labeled metrics so they appear at least once
    // use metrics so they appear in the report
    val dimensions = Seq(StatusGroupDimension(StatusCodes.OK))
    registry.requests.inc()
    registry.receivedBytes.update(10)
    registry.active.inc()
    registry.responses.inc(dimensions)
    registry.errors.inc(dimensions)
    registry.duration.observe(1.second, dimensions)
    registry.sentBytes.update(10, dimensions)

    Get() ~> metrics(registry) ~> check {
      response.entity.contentType shouldBe PrometheusMarshallers.PrometheusContentType
      val text = responseAs[String]
      // println(text)
      val metrics = text
        .split('\n')
        .filterNot(_.startsWith("#"))
        .map(_.takeWhile(c => c != ' ' && c != '{'))
        .distinct
      metrics should contain theSameElementsAs Seq(
        "akka_http_requests_active",
        "akka_http_requests_total",
        "akka_http_requests_size_bytes_bucket",
        "akka_http_requests_size_bytes_count",
        "akka_http_requests_size_bytes_sum",
        "akka_http_responses_total",
        "akka_http_responses_errors_total",
        "akka_http_responses_duration_seconds_bucket",
        "akka_http_responses_duration_seconds_count",
        "akka_http_responses_duration_seconds_sum",
        "akka_http_responses_size_bytes_bucket",
        "akka_http_responses_size_bytes_count",
        "akka_http_responses_size_bytes_sum",
        "akka_http_connections_active",
        "akka_http_connections_total",
        "other_metric"
      )
    }
  }
} 
Example 66
Source File: DropwizardMarshallersSpec.scala    From akka-http-metrics   with Apache License 2.0 5 votes vote down vote up
package fr.davit.akka.http.metrics.dropwizard.marshalling

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import fr.davit.akka.http.metrics.core.HttpMetricsRegistry.StatusGroupDimension
import fr.davit.akka.http.metrics.core.scaladsl.server.HttpMetricsDirectives._
import fr.davit.akka.http.metrics.dropwizard.DropwizardRegistry
import org.scalatest.BeforeAndAfterAll
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import spray.json.{DefaultJsonProtocol, JsValue}

import scala.concurrent.duration._

class DropwizardMarshallersSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll {

  private case class JsonResponse(metrics: Map[String, JsValue])

  private trait Fixture extends SprayJsonSupport with DefaultJsonProtocol with DropwizardMarshallers {
    implicit val metricsFormat = jsonFormat1(JsonResponse)

    val registry = DropwizardRegistry()
    registry.underlying.counter("other.metric")
  }

  override def afterAll(): Unit = {
    cleanUp()
    super.afterAll()
  }

  "DropwizardMarshallers" should "expose metrics as json format" in new Fixture {
    // use metrics so they appear in the report
    val dimensions = Seq(StatusGroupDimension(StatusCodes.OK))
    registry.requests.inc()
    registry.receivedBytes.update(10)
    registry.active.inc()
    registry.responses.inc(dimensions)
    registry.errors.inc()
    registry.duration.observe(1.second, dimensions)
    registry.sentBytes.update(10)

    Get() ~> metrics(registry) ~> check {
      val json = responseAs[JsonResponse]
      // println(json)
      json.metrics.keys should contain theSameElementsAs Seq(
        "akka.http.requests.active",
        "akka.http.requests",
        "akka.http.requests.bytes",
        "akka.http.responses{status=2xx}",
        "akka.http.responses.errors",
        "akka.http.responses.duration{status=2xx}",
        "akka.http.responses.bytes",
        "other.metric"
      ).toSet
    }
  }

} 
Example 67
Source File: JustinDirectivesTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.httpapi

import akka.http.scaladsl.server.directives._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import justin.db.consistenthashing.NodeId
import justin.db.vectorclocks.{Counter, VectorClock}
import org.scalatest.{FlatSpec, Matchers}

class JustinDirectivesTest extends FlatSpec with Matchers with ScalatestRouteTest
  with RouteDirectives
  with JustinDirectives {

  behavior of "Justin Directives"

  it should "provide empty VectorClock instance when no header is passed" in {
    Get("/") ~> withVectorClockHeader(x => complete(x.vectorClock.toString)) ~> check {
      responseAs[String] shouldBe VectorClockHeader.empty.vectorClock.toString
    }
  }

  it should "provide instance of VectorClock build upon passed header" in {
    val vClock = VectorClock(Map(NodeId(1) -> Counter(1), NodeId(2) -> Counter(2), NodeId(3) -> Counter(9)))
    val header = VectorClockHeader(vClock)

    Get("/").addHeader(header) ~> withVectorClockHeader(x => complete(x.vectorClock.toString)) ~> check {
      responseAs[String] shouldBe vClock.toString
    }
  }
} 
Example 68
Source File: HydraDirectivesSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.core.http

import akka.http.scaladsl.model.headers.Location
import akka.http.scaladsl.model.{StatusCodes, Uri}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpecLike

class HydraDirectivesSpec
    extends Matchers
    with AnyFunSpecLike
    with ScalatestRouteTest
    with HydraDirectives {

  describe("Hydra Directives") {
    it("completes with location header") {
      Get() ~> completeWithLocationHeader(StatusCodes.OK, 123) ~> check {
        header[Location].get.uri shouldBe Uri("http://example.com/123")
      }
    }
    it("imperatively completes") {
      Get() ~> imperativelyComplete((ctx) => ctx.complete("DONE")) ~> check {
        responseAs[String] shouldBe "DONE"
      }
    }
  }

} 
Example 69
Source File: HealthEndpointSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.http

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.flatspec.AnyFlatSpecLike
import org.scalatest.matchers.should.Matchers

class HealthEndpointSpec
    extends Matchers
    with AnyFlatSpecLike
    with ScalatestRouteTest {

  "The HealthEndpoint" should "return a 200" in {
    Get("/health") ~> HealthEndpoint.route ~> check {
      status shouldEqual StatusCodes.OK
    }
  }
} 
Example 70
Source File: IngestorsEndpointSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.http

import akka.actor.Actor
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import hydra.common.util.ActorUtils
import hydra.ingest.IngestorInfo
import hydra.ingest.services.IngestorRegistry.{FindAll, FindByName, LookupResult}
import org.joda.time.DateTime
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import scala.concurrent.duration._


class IngestorsEndpointSpec
    extends Matchers
    with AnyWordSpecLike
    with ScalatestRouteTest
    with HydraIngestJsonSupport {

  val ingestorsRoute = new IngestorRegistryEndpoint().route

  override def afterAll = {
    super.afterAll()
    TestKit.shutdownActorSystem(
      system,
      verifySystemShutdown = true,
      duration = 10 seconds
    )
  }

  val probe = TestProbe()

  val ingestorInfo = IngestorInfo(
    ActorUtils.actorName(probe.ref),
    "test",
    probe.ref.path,
    DateTime.now
  )

  val registry = TestActorRef(
    new Actor {

      override def receive = {
        case FindByName("tester") => sender ! LookupResult(Seq(ingestorInfo))
        case FindAll              => sender ! LookupResult(Seq(ingestorInfo))
      }
    },
    "ingestor_registry"
  ).underlyingActor

  "The ingestors endpoint" should {

    "returns all ingestors" in {
      Get("/ingestors") ~> ingestorsRoute ~> check {
        val r = responseAs[Seq[IngestorInfo]]
        r.size shouldBe 1
        r(0).path shouldBe ingestorInfo.path
        r(0).group shouldBe ingestorInfo.group
        r(0).path shouldBe ingestorInfo.path
        r(0).registeredAt shouldBe ingestorInfo.registeredAt.withMillisOfSecond(
          0
        )
      }
    }
  }
} 
Example 71
Source File: BaseRoutesSpec.scala    From avoin-voitto   with MIT License 5 votes vote down vote up
package liigavoitto.api

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{ Matchers, WordSpec }

class BaseRoutesSpec extends WordSpec with Matchers with ScalatestRouteTest {

  "BaseRoute" should {
    "answer to /ping request" in {
      Get("/ping") ~> BaseRoutes.baseRoutes ~> check {
        status shouldBe StatusCodes.OK
        responseAs[String] shouldBe "PONG"
      }
    }
  }

} 
Example 72
Source File: ApiRoutesSpec.scala    From avoin-voitto   with MIT License 5 votes vote down vote up
package liigavoitto.api

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.ActorMaterializer
import org.scalatest.{ Matchers, WordSpec }

class ApiRoutesSpec extends WordSpec with Matchers with ScalatestRouteTest with ApiRoutes {

  implicit val actorMaterializer: ActorMaterializer = ActorMaterializer()

  "SimpleRoute" should {
    "answer to GET requests to `/report/s24-123456`" in {
      Get("/report/s24-123456") ~> apiRoutes ~> check {
        status shouldBe StatusCodes.OK
      }
    }
    
    "handle reports in two languages" in {
      Get("/report/s24-123456?lang=sv") ~> apiRoutes ~> check {
        status shouldBe StatusCodes.OK
        responseAs[String] should include("lang: sv")
      }
    }
  }

  override val handler = new ApiHandler() {
    override def report(id: String, lang: String) = s"OK, $id. lang: $lang"
  }
} 
Example 73
Source File: AdminRouteSpec.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.http

import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.typesafe.config.ConfigFactory
import org.apache.s2graph.core.Management.JsonModel.Prop
import org.apache.s2graph.core.S2Graph
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec}
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsString, JsValue, Json}

class AdminRoutesSpec extends WordSpec with Matchers with ScalaFutures with ScalatestRouteTest with S2GraphAdminRoute with BeforeAndAfterAll {
  import scala.collection.JavaConverters._

  val dbUrl = "jdbc:h2:file:./var/metastore_admin_route;MODE=MYSQL;AUTO_SERVER=true"
  val config =
    ConfigFactory.parseMap(Map("db.default.url" -> dbUrl).asJava)
  lazy val s2graph = new S2Graph(config.withFallback(ConfigFactory.load()))
  override val logger = LoggerFactory.getLogger(this.getClass)

  override def afterAll(): Unit = {
    s2graph.shutdown(true)
  }

  lazy val routes = adminRoute

  val serviceName = "kakaoFavorites"
  val columnName = "userName"

  "AdminRoute" should {
    "be able to create service (POST /createService)" in {
      val serviceParam = Json.obj(
        "serviceName" -> serviceName,
        "compressionAlgorithm" -> "gz"
      )

      val serviceEntity = Marshal(serviceParam).to[MessageEntity].futureValue
      val request = Post("/createService").withEntity(serviceEntity)

      request ~> routes ~> check {
        status should ===(StatusCodes.Created)
        contentType should ===(ContentTypes.`application/json`)

        val response = entityAs[JsValue]

        (response \\ "name").head should ===(JsString("kakaoFavorites"))
        (response \\ "status").head should ===(JsString("ok"))
      }
    }

    "return service if present (GET /getService/{serviceName})" in {
      val request = HttpRequest(uri = s"/getService/$serviceName")

      request ~> routes ~> check {
        status should ===(StatusCodes.OK)
        contentType should ===(ContentTypes.`application/json`)

        val response = entityAs[JsValue]

        (response \\ "name").head should ===(JsString("kakaoFavorites"))
      }
    }

    "be able to create serviceColumn (POST /createServiceColumn)" in {
      val serviceColumnParam = Json.obj(
        "serviceName" -> serviceName,
        "columnName" -> columnName,
        "columnType" -> "string",
        "props" -> Json.toJson(
          Seq(
            Json.obj("name" -> "age", "defaultValue" -> "-1", "dataType" -> "integer")
          )
        )
      )

      val serviceColumnEntity = Marshal(serviceColumnParam).to[MessageEntity].futureValue
      val request = Post("/createServiceColumn").withEntity(serviceColumnEntity)

      request ~> routes ~> check {
        status should ===(StatusCodes.Created)
        contentType should ===(ContentTypes.`application/json`)

        val response = entityAs[JsValue]

        (response \\ "serviceName").head should ===(JsString("kakaoFavorites"))
        (response \\ "columnName").head should ===(JsString("userName"))
        (response \\ "status").head should ===(JsString("ok"))
      }
    }
  }
} 
Example 74
Source File: StatsDirectiveSpec.scala    From opencensus-scala   with Apache License 2.0 5 votes vote down vote up
package io.opencensus.scala.akka.http

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import io.opencensus.scala.http.testSuite.MockStats
import io.opencensus.scala.stats.{Distribution, MeasurementDouble}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class StatsDirectiveSpec
    extends AnyFlatSpec
    with ScalatestRouteTest
    with Matchers {

  def statsDirectiveWithMock: (StatsDirective, MockStats) = {
    val mockStats = new MockStats
    val directive = new StatsDirective {
      override private[http] val stats = mockStats
    }
    (directive, mockStats)
  }

  def routeWithMock = {
    val (directive, mock) = statsDirectiveWithMock

    val route = directive.recordRequest("routeName") {
      complete(StatusCodes.OK)
    }

    (route, mock)
  }

  it should "register the correct view" in {
    val (route, mock) = routeWithMock

    Get("/foo") ~> route ~> check {
      status shouldBe StatusCodes.OK

      mock.registeredViews should have length 1

      val serverLatency = mock.registeredViews.head

      serverLatency.name shouldBe "opencensus.io/http/server/server_latency"
      serverLatency.measure.name shouldBe "opencensus.io/http/server/server_latency"
      serverLatency.aggregation shouldBe a[Distribution]
    }
  }

  it should "record the correct measure value" in {
    val (route, mock) = routeWithMock

    Get("/foo") ~> route ~> check {
      status shouldBe StatusCodes.OK

      mock.recordedMeasurements should have length 1

      val (measurement, _) = mock.recordedMeasurements.head

      measurement match {
        case MeasurementDouble(measure, value) =>
          measure.name shouldBe "opencensus.io/http/server/server_latency"
          value.toInt shouldBe >(0)
        case other => fail(s"Expected MeasurementDouble got $other")
      }
    }
  }

  it should "record the correct measure tags" in {
    val (route, mock) = routeWithMock

    Get("/foo") ~> route ~> check {
      status shouldBe StatusCodes.OK
      mock.recordedMeasurements should have length 1
      val (_, tags) = mock.recordedMeasurements.head

      val tagsKeyValues =
        tags.map(tag => (tag.key.getName, tag.value.asString()))

      val expectedTags = List(
        "http_server_method" -> "GET",
        "http_server_route"  -> "routeName",
        "http_server_status" -> "200"
      )

      tagsKeyValues should contain theSameElementsAs expectedTags
    }
  }
} 
Example 75
Source File: PaginationDirectivesWithDefaults.scala    From akka-http-extensions   with Apache License 2.0 5 votes vote down vote up
package com.lonelyplanet.akka.http.extensions

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration.FiniteDuration

class PaginationDirectivesWithDefaults extends PaginationSpec {

  override def testConfigSource =
    """akka.http.extensions.pagination.defaults.enabled = true
      | akka.http.extensions.pagination.defaults.offset = 0
      | akka.http.extensions.pagination.defaults.limit = 50
    """.stripMargin

  "Pagination with defaults" should "not have page if no page is requested" in {

    Get("/filter-test") ~> paginationRoute ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] === "NoPage"
    }

    Get("/filter-test") ~> paginationOrDefaultsRoute ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] === "NoPage"
    }
  }

  it should "have a page with defaults if one of the parameters is set" in {
    Get("/filter-test?offset=1") ~> paginationRoute ~> check {
      responseAs[String] shouldEqual PageRequest(1, 50, Map.empty).toString
    }

    Get("/filter-test?limit=100") ~> paginationRoute ~> check {
      responseAs[String] shouldEqual PageRequest(0, 100, Map.empty).toString
    }

    Get("/filter-test?offset=1") ~> paginationOrDefaultsRoute ~> check {
      responseAs[String] shouldEqual PageRequest(1, 50, Map.empty).toString
    }

    Get("/filter-test?limit=100") ~> paginationOrDefaultsRoute ~> check {
      responseAs[String] shouldEqual PageRequest(0, 100, Map.empty).toString
    }
  }

  it should "return the page object that was requested" in {
    Get("/filter-test?offset=1&limit=10") ~> paginationRoute ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] shouldEqual PageRequest(1, 10, Map.empty).toString
    }

    Get("/filter-test?offset=1&limit=10") ~> paginationOrDefaultsRoute ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] shouldEqual PageRequest(1, 10, Map.empty).toString
    }
  }

  it should "return the page object with sorting that was requested" in {
    Get("/filter-test?offset=1&limit=10&sort=name,asc;age,desc") ~> paginationRoute ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] shouldEqual PageRequest(1, 10, Map("name" -> Order.Asc, "age" -> Order.Desc)).toString
    }

    Get("/filter-test?offset=1&limit=10&sort=name,asc;age,desc") ~> paginationOrDefaultsRoute ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] shouldEqual PageRequest(1, 10, Map("name" -> Order.Asc, "age" -> Order.Desc)).toString
    }
  }
} 
Example 76
Source File: SecurityTest.scala    From Conseil   with Apache License 2.0 5 votes vote down vote up
package tech.cryptonomic.conseil.api.security

import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Millis, Seconds, Span}
import org.scalatest.{Matchers, WordSpec}
import tech.cryptonomic.conseil.api.security.Security.SecurityApi

class SecurityTest extends WordSpec with Matchers with ScalatestRouteTest with ScalaFutures {

  implicit override val patienceConfig = PatienceConfig(timeout = Span(2, Seconds), interval = Span(20, Millis))

  "The SecurityApi" should {

      "valid itself" in {
        SecurityApi(Set.empty, None).isValid shouldBe false
        SecurityApi(Set.empty, Some(false)).isValid shouldBe false

        SecurityApi(Set("some-key"), Some(false)).isValid shouldBe true
        SecurityApi(Set("some-key"), None).isValid shouldBe true
        SecurityApi(Set.empty, Some(true)).isValid shouldBe true
        SecurityApi(Set("some-key"), Some(true)).isValid shouldBe true
      }

      "validate a given key" in {
        SecurityApi(Set("some-key"), None).validateApiKey(Some("some-key")).futureValue shouldBe true
        SecurityApi(Set("some-key"), Some(true)).validateApiKey(Some("some-key")).futureValue shouldBe true

        SecurityApi(Set.empty, None).validateApiKey(Some("some-key")).futureValue shouldBe false
        SecurityApi(Set.empty, Some(true)).validateApiKey(Some("some-key")).futureValue shouldBe false

        SecurityApi(Set.empty, None).validateApiKey(None).futureValue shouldBe false
        SecurityApi(Set.empty, Some(true)).validateApiKey(None).futureValue shouldBe true
      }

    }
} 
Example 77
Source File: AppInfoRoutesSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.storage.routes

import java.util.regex.Pattern.quote

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.storage.config.{AppConfig, Settings}
import ch.epfl.bluebrain.nexus.storage.routes.instances._
import ch.epfl.bluebrain.nexus.storage.utils.Resources
import ch.epfl.bluebrain.nexus.storage.{AkkaSource, IamIdentitiesClient, Storages}
import io.circe.Json
import monix.eval.Task
import org.mockito.IdiomaticMockito
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class AppInfoRoutesSpec
    extends AnyWordSpecLike
    with Matchers
    with ScalatestRouteTest
    with IdiomaticMockito
    with Resources {

  "the app info routes" should {

    implicit val config: AppConfig                        = Settings(system).appConfig
    implicit val iamIdentities: IamIdentitiesClient[Task] = mock[IamIdentitiesClient[Task]]
    val route: Route                                      = Routes(mock[Storages[Task, AkkaSource]])

    "return application information" in {
      Get("/") ~> route ~> check {
        status shouldEqual OK
        responseAs[Json] shouldEqual
          jsonContentOf("/app-info.json", Map(quote("{version}") -> config.description.version))
      }
    }
  }
} 
Example 78
Source File: StorageDirectivesSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.storage.routes

import java.util.regex.Pattern.quote

import akka.http.scaladsl.model.{StatusCodes, Uri}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.storage.JsonLdCirceSupport._
import ch.epfl.bluebrain.nexus.storage.routes.Routes.exceptionHandler
import ch.epfl.bluebrain.nexus.storage.routes.StorageDirectives._
import ch.epfl.bluebrain.nexus.storage.utils.Resources
import io.circe.Json
import org.scalatest.Inspectors
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class StorageDirectivesSpec
    extends AnyWordSpecLike
    with Matchers
    with ScalatestRouteTest
    with Inspectors
    with Resources {

  "the storage directives" when {

    def pathInvalidJson(path: Uri.Path): Json =
      jsonContentOf(
        "/error.json",
        Map(
          quote("{type}") -> "PathInvalid",
          quote(
            "{reason}"
          )               -> s"The provided location inside the bucket 'name' with the relative path '$path' is invalid."
        )
      )

    "dealing with file path extraction" should {
      val route = handleExceptions(exceptionHandler) {
        (extractRelativeFilePath("name") & get) { path =>
          complete(s"$path")
        }
      }

      "reject when path contains 2 slashes" in {
        Get("///") ~> route ~> check {
          status shouldEqual StatusCodes.BadRequest
          responseAs[Json] shouldEqual pathInvalidJson(Uri.Path.Empty)
        }
      }

      "reject when path does not end with a segment" in {
        Get("/some/path/") ~> route ~> check {
          status shouldEqual StatusCodes.BadRequest
          responseAs[Json] shouldEqual pathInvalidJson(Uri.Path("some/path/"))
        }
      }

      "return path" in {
        Get("/some/path/file.txt") ~> route ~> check {
          responseAs[String] shouldEqual "some/path/file.txt"
        }
      }
    }

    "dealing with path validation" should {
      def route(path: Uri.Path) =
        handleExceptions(exceptionHandler) {
          (validatePath("name", path) & get) {
            complete(s"$path")
          }
        }

      "reject when some of the segments is . or .." in {
        val paths = List(Uri.Path("/./other/file.txt"), Uri.Path("/some/../file.txt"))
        forAll(paths) { path =>
          Get(path.toString()) ~> route(path) ~> check {
            status shouldEqual StatusCodes.BadRequest
            responseAs[Json] shouldEqual pathInvalidJson(path)
          }
        }
      }

      "pass" in {
        Get("/some/path") ~> route(Uri.Path("/some/path")) ~> check {
          handled shouldEqual true
        }
      }
    }
  }
} 
Example 79
Source File: RealmDirectivesSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.directives

import java.net.URLEncoder

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.commons.http.JsonLdCirceSupport._
import ch.epfl.bluebrain.nexus.iam.directives.RealmDirectives._
import ch.epfl.bluebrain.nexus.iam.routes.SearchParams
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.util.EitherValues
import io.circe.generic.auto._
import org.mockito.IdiomaticMockito
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class RealmDirectivesSpec
    extends AnyWordSpecLike
    with ScalatestRouteTest
    with Matchers
    with ScalaFutures
    with EitherValues
    with IdiomaticMockito {

  private def route: Route = {
    (get & searchParams) { params => complete(params) }
  }

  private def encode(s: AbsoluteIri) = URLEncoder.encode(s.asString, "UTF-8")

  "Realm directives" should {
    "return query params" in {
      val createdBy: AbsoluteIri = url"http://example.com/created"
      val updatedBy: AbsoluteIri = url"http://example.com/updated"
      val tpe: AbsoluteIri       = url"http://example.com/tpe"
      val tpe2: AbsoluteIri      = url"http://example.com/tpe2"
      Get(
        s"/?rev=2&deprecated=true&type=${encode(tpe)}&type=${encode(tpe2)}&createdBy=${encode(createdBy)}&updatedBy=${encode(updatedBy)}"
      ) ~> route ~> check {
        responseAs[SearchParams] shouldEqual SearchParams(
          Some(true),
          Some(2L),
          Some(createdBy),
          Some(updatedBy),
          Set(tpe, tpe2)
        )
      }
    }
  }

} 
Example 80
Source File: IdentitiesRoutesSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.routes

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.iam.acls.Acls
import ch.epfl.bluebrain.nexus.iam.auth.{AccessToken, TokenRejection}
import ch.epfl.bluebrain.nexus.iam.realms._
import ch.epfl.bluebrain.nexus.iam.testsyntax._
import ch.epfl.bluebrain.nexus.iam.types.Caller
import ch.epfl.bluebrain.nexus.iam.types.IamError.InvalidAccessToken
import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Authenticated, User}
import ch.epfl.bluebrain.nexus.service.config.Settings
import ch.epfl.bluebrain.nexus.service.marshallers.instances._
import ch.epfl.bluebrain.nexus.service.routes.Routes
import ch.epfl.bluebrain.nexus.util.Resources
import com.typesafe.config.{Config, ConfigFactory}
import io.circe.Json
import monix.eval.Task
import org.mockito.matchers.MacroBasedMatchers
import org.mockito.{IdiomaticMockito, Mockito}
import org.scalatest.BeforeAndAfter
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import scala.concurrent.duration._

//noinspection TypeAnnotation
class IdentitiesRoutesSpec
    extends AnyWordSpecLike
    with Matchers
    with ScalatestRouteTest
    with BeforeAndAfter
    with MacroBasedMatchers
    with Resources
    with ScalaFutures
    with IdiomaticMockito {

  implicit override def patienceConfig: PatienceConfig = PatienceConfig(3.seconds, 100.milliseconds)

  override def testConfig: Config = ConfigFactory.load("test.conf")

  private val config        = Settings(system).serviceConfig
  implicit private val http = config.http

  private val realms: Realms[Task] = mock[Realms[Task]]
  private val acls: Acls[Task]     = mock[Acls[Task]]

  before {
    Mockito.reset(realms, acls)
  }

  "The IdentitiesRoutes" should {
    val routes = Routes.wrap(new IdentitiesRoutes(acls, realms).routes)
    "return forbidden" in {
      val err = InvalidAccessToken(TokenRejection.InvalidAccessToken)
      realms.caller(any[AccessToken]) shouldReturn Task.raiseError(err)
      Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check {
        status shouldEqual StatusCodes.Unauthorized
      }
    }
    "return anonymous" in {
      realms.caller(any[AccessToken]) shouldReturn Task.pure(Caller.anonymous)
      Get("/identities") ~> routes ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[Json].sort shouldEqual jsonContentOf("/identities/anonymous.json")
      }
    }
    "return all identities" in {
      val user   = User("theuser", "therealm")
      val auth   = Authenticated("therealm")
      val caller = Caller(user, Set(user, Anonymous, auth))
      realms.caller(any[AccessToken]) shouldReturn Task.pure(caller)
      Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[Json].sort shouldEqual jsonContentOf("/identities/identities.json")
      }
    }
  }
} 
Example 81
Source File: ResourceDecoderSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.serializers

import java.time.Instant

import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Resources}
import ch.epfl.bluebrain.nexus.iam.types.Identity.User
import ch.epfl.bluebrain.nexus.kg.TestHelper
import ch.epfl.bluebrain.nexus.kg.config.Schemas
import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef
import ch.epfl.bluebrain.nexus.kg.resources.{Id, ResourceF, ResourceGraph}
import ch.epfl.bluebrain.nexus.rdf.implicits._
import io.circe.Decoder
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{Inspectors, OptionValues}

class ResourceDecoderSpec
    extends AnyWordSpecLike
    with Matchers
    with Inspectors
    with EitherValues
    with ScalatestRouteTest
    with OptionValues
    with Resources
    with TestHelper {

  private val json                                     = jsonContentOf("/serialization/resource.json")
  private val projectRef                               = ProjectRef(genUUID)
  private val id                                       = url"http://example.com/prefix/myId"
  private val graph                                    = json.toGraph(id).rightValue
  implicit private val decoder: Decoder[ResourceGraph] = ResourceF.resourceGraphDecoder(projectRef)

  private val model = ResourceF(
    Id(projectRef, url"http://example.com/prefix/myId"),
    1L,
    Set(url"https://example.com/vocab/A", url"https://example.com/vocab/B"),
    deprecated = false,
    Map.empty,
    None,
    Instant.parse("2020-01-17T12:45:01.479676Z"),
    Instant.parse("2020-01-17T13:45:01.479676Z"),
    User("john", "bbp"),
    User("brenda", "bbp"),
    Schemas.unconstrainedRef,
    graph
  )

  "A resource" should {
    "be decoded" in {
      json.as[ResourceGraph].rightValue shouldEqual model
    }
  }

} 
Example 82
Source File: RejectionHandlingSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.commons.http

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Rejection
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.util.EitherValues
import com.typesafe.config.{Config, ConfigFactory}
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
import io.circe.{Json, Printer}
import io.circe.parser._
import org.scalatest.Inspectors
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class RejectionHandlingSpec
    extends AnyWordSpecLike
    with Matchers
    with Inspectors
    with ScalatestRouteTest
    with EitherValues {

  class Custom extends Rejection

  override def testConfig: Config       = ConfigFactory.empty()
  implicit private val printer: Printer = Printer.spaces2.copy(dropNullValues = true)

  "A default rejection handler" should {
    val handler =
      RejectionHandling { _: Custom =>
        StatusCodes.InternalServerError -> Json.obj("reason" -> Json.fromString("custom"))
      }.withFallback(RejectionHandling.notFound)

    "handle not found" in {
      val route = handleRejections(handler)(pathEnd(complete("ok")))
      Get("/a") ~> route ~> check {
        val expected =
          s"""{
             |  "@context": "https://bluebrain.github.io/nexus/contexts/error.json",
             |  "@type": "NotFound",
             |  "reason": "The requested resource could not be found."
             |}""".stripMargin
        status shouldEqual StatusCodes.NotFound
        responseAs[Json] shouldEqual parse(expected).rightValue
      }
    }

    "handle missing query param" in {
      val route = handleRejections(handler)(parameter("rev".as[Long])(_ => complete("ok")))
      Get("/a") ~> route ~> check {
        val expected =
          s"""{
             |  "@context": "https://bluebrain.github.io/nexus/contexts/error.json",
             |  "@type": "MissingQueryParam",
             |  "reason": "Request is missing required query parameter 'rev'."
             |}""".stripMargin
        status shouldEqual StatusCodes.BadRequest
        responseAs[Json] shouldEqual parse(expected).rightValue
      }
    }

    "handle custom" in {
      val route = handleRejections(handler)(reject(new Custom))
      Get("/a") ~> route ~> check {
        val expected =
          s"""{
             |  "reason": "custom"
             |}""".stripMargin
        status shouldEqual StatusCodes.InternalServerError
        responseAs[Json] shouldEqual parse(expected).rightValue
      }
    }
  }

} 
Example 83
Source File: PrefixDirectivesSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.commons.http.directives

import akka.http.scaladsl.model.{StatusCodes, Uri}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.commons.http.directives.PrefixDirectives._
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.Inspectors
import org.scalatest.matchers.should.Matchers

class PrefixDirectivesSpec extends AnyWordSpecLike with Matchers with Inspectors with ScalatestRouteTest {

  override def testConfig: Config = ConfigFactory.empty()

  "A PrefixDirective" should {

    "match the prefix uri" in {
      forAll(
        Map(
          ""         -> "",
          "/"        -> "",
          "///"      -> "",
          "/dev"     -> "/dev",
          "/dev/"    -> "/dev",
          "/dev///"  -> "/dev",
          "/dev/sn/" -> "/dev/sn"
        ).toList
      ) {
        case (suffix, prefix) =>
          val uri   = Uri("http://localhost:80" + suffix)
          val route = uriPrefix(uri) {
            path("remainder") {
              get {
                complete(StatusCodes.OK)
              }
            }
          }

          Get(prefix + "/remainder") ~> route ~> check {
            status shouldEqual StatusCodes.OK
          }
      }
    }
  }
} 
Example 84
Source File: StaticResourceIamAdminRoutesSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.commons.http.routes

import java.util.UUID

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.commons.http.RdfMediaTypes
import org.scalatest.Inspectors
import java.util.regex.Pattern.quote

import ch.epfl.bluebrain.nexus.util.Resources
import com.typesafe.config.{Config, ConfigFactory}
import io.circe.parser.parse
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class StaticResourceIamAdminRoutesSpec
    extends AnyWordSpecLike
    with Matchers
    with Inspectors
    with ScalatestRouteTest
    with Resources {

  val baseUri = "http://nexus.example.com/v1"

  override def testConfig: Config = ConfigFactory.empty()

  val staticRoutes = new StaticResourceRoutes(
    Map(
      "/contexts/context1" -> "/commons/static-routes-test/contexts/context1.json",
      "/contexts/context2" -> "/commons/static-routes-test/contexts/context2.json",
      "/schemas/schema1"   -> "/commons/static-routes-test/schemas/schema1.json",
      "/schemas/schema2"   -> "/commons/static-routes-test/schemas/schema2.json"
    ),
    "test",
    baseUri
  ).routes

  val baseReplacement = Map(
    quote("{{base}}") -> baseUri
  )
  val files           = Map(
    "/v1/test/contexts/context1" -> jsonContentOf(
      "/commons/static-routes-test/contexts/context1.json",
      baseReplacement
    ),
    "/v1/test/contexts/context2" -> jsonContentOf(
      "/commons/static-routes-test/contexts/context2.json",
      baseReplacement
    ),
    "/v1/test/schemas/schema1"   -> jsonContentOf("/commons/static-routes-test/schemas/schema1.json", baseReplacement),
    "/v1/test/schemas/schema2"   -> jsonContentOf("/commons/static-routes-test/schemas/schema2.json", baseReplacement)
  )

  "A StaticResourceRoutes" should {

    "return static resources" in {
      forAll(files.toList) {
        case (path, json) =>
          Get(path) ~> staticRoutes ~> check {
            status shouldEqual StatusCodes.OK
            contentType shouldEqual RdfMediaTypes.`application/ld+json`.toContentType
            parse(responseAs[String]).toOption.get shouldEqual json
          }
      }

    }

    "return 404 when resource doesn't exist" in {
      Get(s"/v1/test/schemas/${UUID.randomUUID().toString}") ~> staticRoutes ~> check {
        rejections shouldEqual Seq()
      }
    }
  }

} 
Example 85
Source File: QueryDirectivesSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.admin.directives

import java.net.URLEncoder
import java.util.UUID

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives.{complete, get}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import ch.epfl.bluebrain.nexus.admin.routes.SearchParams
import ch.epfl.bluebrain.nexus.admin.routes.SearchParams.Field
import ch.epfl.bluebrain.nexus.commons.http.JsonLdCirceSupport._
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig
import ch.epfl.bluebrain.nexus.service.config.Settings
import ch.epfl.bluebrain.nexus.service.routes.Routes
import ch.epfl.bluebrain.nexus.util.EitherValues
import io.circe.generic.auto._
import org.mockito.IdiomaticMockito
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class QueryDirectivesSpec
    extends AnyWordSpecLike
    with ScalatestRouteTest
    with Matchers
    with ScalaFutures
    with EitherValues
    with IdiomaticMockito {

  private def genIri: AbsoluteIri              = url"http://nexus.example.com/${UUID.randomUUID()}"
  private def encode(url: AbsoluteIri): String = URLEncoder.encode(url.asString, "UTF-8")
  private val config                           = Settings(system).serviceConfig
  implicit private val http: HttpConfig        = config.http

  private def routes(inner: Route): Route =
    Routes.wrap(inner)

  "Query directives" should {

    "handle query params" in {
      val createdBy     = genIri
      val updatedBy     = genIri
      val type1         = genIri
      val type2         = genIri
      def projectParams =
        Routes.wrap(
          (get & QueryDirectives.searchParamsProjects) { params => complete(StatusCodes.OK -> params) }
        )

      Get("/") ~> routes(projectParams) ~> check {
        responseAs[SearchParams] shouldEqual SearchParams.empty
      }

      Get(
        s"/?rev=1&deprecated=true&label=myLabel&type=${encode(type1)}&type=${encode(type2)}&createdBy=${encode(createdBy)}&updatedBy=${encode(updatedBy)}"
      ) ~> routes(projectParams) ~> check {
        responseAs[SearchParams] shouldEqual
          SearchParams(
            rev = Some(1L),
            deprecated = Some(true),
            projectLabel = Some(Field("myLabel", exactMatch = false)),
            types = Set(type1, type2),
            createdBy = Some(createdBy),
            updatedBy = Some(updatedBy)
          )

      }
    }
  }
} 
Example 86
Source File: PaginationSpec.scala    From akka-http-extensions   with Apache License 2.0 5 votes vote down vote up
package com.lonelyplanet.akka.http.extensions

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration.FiniteDuration

class PaginationSpec extends FlatSpec with PaginationDirectives with Matchers with ScalatestRouteTest {
  implicit val routeTestTimeout: RouteTestTimeout = RouteTestTimeout(FiniteDuration(10, "s"))
  val config = testConfig

  def paginationRoute =
    path("filter-test") {
      withOptionalPagination { page =>
        complete {
          page match {
            case Some(p) => p.toString
            case None    => "NoPage"
          }
        }
      }
    }

  def paginationOrDefaultsRoute =
    path("filter-test") {
      withPagination { page =>
        complete {
          page.toString
        }
      }
    }
} 
Example 87
Source File: ExceptionHandlingSpec.scala    From akka-http-extensions   with Apache License 2.0 5 votes vote down vote up
package com.lonelyplanet.akka.http.extensions

import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FlatSpec, Matchers}
import akka.http.scaladsl.model.StatusCodes._
import com.lonelyplanet.akka.http.extensions.fixtures.ErrorResponses
import spray.json._

class ExceptionHandlingSpec extends FlatSpec with Matchers with ScalatestRouteTest {

  it should "return correct status codes" in {
    val routing = new Routing

    Get("doesnt-exist") ~> routing.route ~> check {
      val json = responseAs[String].parseJson
      json shouldBe ErrorResponses.defaultErrorResponse
      response.status shouldBe NotFound
    }

    Get("doesnt-exist") ~> addHeader("X-Trace-Token", "test") ~> routing.route ~> check {
      val json = responseAs[String].parseJson
      json shouldBe ErrorResponses.errorResponseWithToken("test")
      response.status shouldBe NotFound
    }

    Get("/exception") ~> routing.route ~> check {
      response.status shouldBe InternalServerError
    }

    Post("/") ~> routing.route ~> check {
      response.status shouldBe MethodNotAllowed
    }

    Get("/resource") ~> routing.route ~> check {
      response.status shouldBe NotFound
    }
  }
} 
Example 88
Source File: ExpiresDirectiveSpec.scala    From akka-http-extensions   with Apache License 2.0 5 votes vote down vote up
package com.lonelyplanet.akka.http.extensions.directives

import akka.http.scaladsl.model.DateTime
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FlatSpec, Matchers}
import akka.http.scaladsl.server.Directives._
import ExpiresDirective._
import akka.http.scaladsl.model.StatusCodes.OK

class ExpiresDirectiveSpec extends FlatSpec with Matchers with ScalatestRouteTest {
  private val expirationDate = DateTime.now

  private val route = path("test") {
    expires(expirationDate) {
      complete {
        "OK"
      }
    }
  }

  "ExpiresDirective" should "set `Expires` header correctly" in {
    Get("/test") ~> route ~> check {
      status shouldBe OK
      responseAs[String] shouldBe "OK"
      header("Expires").get.value shouldBe expirationDate.toRfc1123DateTimeString
    }
  }
} 
Example 89
Source File: CallServiceSpec.scala    From microservice-dependency-graph   with MIT License 5 votes vote down vote up
package io.github.rlazoti.servicestats.services

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.util.ByteString
import org.scalatest._

class CallServiceSpec extends WordSpec with Matchers with ScalatestRouteTest {

  val API = new Object with CallService

  "CallService API" should {

    "Send POST to /calling should add the CallService" in {
      val jsonRequest = ByteString(
        s"""
        |{
        |"serviceCaller":"checkout",
        |"serviceCalled":"users",
        |"endpointCalled":"findById"
        |}
        """.stripMargin)

      val postRequest = HttpRequest(
        HttpMethods.POST,
        uri = "/calling",
        entity = HttpEntity(MediaTypes.`application/json`, jsonRequest))

      postRequest ~> API.routes ~> check {
        status.isSuccess() shouldEqual true
      }
    }

    // This test needs a Redis instance running...
    "Send GET to /graphdata?time=01.01 should return the graph nodes ands links for that time" in {
      val getRequest = HttpRequest(
        HttpMethods.GET,
        uri = "/graphdata?time=01.01"
      )

      getRequest ~> API.routes ~> check {
        status.isSuccess() shouldEqual true
        contentType shouldBe `application/json`
      }
    }

    "Send GET to /graphdata should be rejected by a missing parameter 'time'" in {
      val getRequest = HttpRequest(
        HttpMethods.GET,
        uri = "/graphdata"
      )

      getRequest ~> API.routes ~> check {
        handled shouldBe false
        rejections.size shouldBe 1
      }
    }

  }

} 
Example 90
Source File: ShipmentViewEndpointSpec.scala    From ddd-leaven-akka-v2   with MIT License 5 votes vote down vote up
package ecommerce.shipping.app

import akka.http.scaladsl.model.StatusCodes.NotFound
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import akka.testkit.TestDuration
import com.typesafe.config.ConfigFactory
import ecommerce.sales.view.ViewTestSupport
import ecommerce.shipping.view.{ShipmentDao, ShipmentView}
import ecommerce.shipping.{ShippingSerializationHintsProvider, ShippingStatus}
import org.json4s.Formats
import org.scalatest.{BeforeAndAfter, Matchers, WordSpecLike}
import pl.newicom.dddd.serialization.JsonSerHints._
import pl.newicom.dddd.utils.UUIDSupport.uuid7

import scala.concurrent.duration.DurationInt

class ShipmentViewEndpointSpec extends WordSpecLike with Matchers with ScalatestRouteTest
  with ViewTestSupport with BeforeAndAfter {

  override lazy val config = ConfigFactory.load
  implicit val formats: Formats = new ShippingSerializationHintsProvider().hints()

  implicit val routeTimeout = RouteTestTimeout(3.seconds dilated)

  lazy val dao = new ShipmentDao
  val shipmentId = uuid7

  before {
    viewStore.run {
      dao.createOrUpdate(ShipmentView(shipmentId, "order-1", ShippingStatus.Delivered))
    }.futureValue
  }

  after {
    viewStore.run {
      dao.remove(shipmentId)
    }.futureValue
  }

  "Shipment view endpoint" should {

    def response = responseAs[String]

    val route: Route = new ShipmentViewEndpoint().route(viewStore)

    "respond to /shipment/all with all shipments" in {
      Get("/shipment/all") ~> route ~> check {
        response should include (shipmentId)
      }
    }

    "respond to /shipment/{shipmentId} with requested shipment" in {
      Get(s"/shipment/$shipmentId") ~> route ~> check {
        response should include (shipmentId)
      }
    }

    "respond to /shipment/{shipmentId} with NotFound if shipment unknown" in {
      Get(s"/shipment/invalid") ~> route ~> check {
        status shouldBe NotFound
      }
    }

  }

  def ensureSchemaDropped = dao.ensureSchemaDropped
  def ensureSchemaCreated = dao.ensureSchemaCreated

} 
Example 91
Source File: ReservationViewEndpointSpec.scala    From ddd-leaven-akka-v2   with MIT License 5 votes vote down vote up
package ecommerce.sales.app

import java.sql.Date

import akka.http.scaladsl.model.StatusCodes.NotFound
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.typesafe.config.ConfigFactory
import ecommerce.sales.view.{ReservationDao, ReservationView, ViewTestSupport}
import ecommerce.sales.{ReservationStatus, SalesSerializationHintsProvider}
import org.joda.time.DateTime._
import org.json4s.Formats
import org.scalatest.{BeforeAndAfter, Matchers, WordSpecLike}
import pl.newicom.dddd.serialization.JsonSerHints._
import pl.newicom.dddd.utils.UUIDSupport.uuid7

class ReservationViewEndpointSpec extends WordSpecLike with Matchers with ScalatestRouteTest with ViewTestSupport with BeforeAndAfter {

  override lazy val config = ConfigFactory.load
  implicit val formats: Formats = new SalesSerializationHintsProvider().hints()

  lazy val dao = new ReservationDao
  val reservationId = uuid7

  before {
    viewStore.run {
      dao.createOrUpdate(ReservationView(reservationId, "client-1", ReservationStatus.Opened, new Date(now.getMillis)))
    }.futureValue
  }

  after {
    viewStore.run {
      dao.remove(reservationId)
    }.futureValue
  }

  "Reservation view endpoint" should {

    def response = responseAs[String]

    val route: Route = new ReservationViewEndpoint().route(viewStore)

    "respond to /reservation/all with all reservations" in {
      Get("/reservation/all") ~> route ~> check {
        response should include (reservationId)
      }
    }

    "respond to /reservation/{reservationId} with requested reservation" in {
      Get(s"/reservation/$reservationId") ~> route ~> check {
        response should include (reservationId)
      }
    }

    "respond to /reservation/{reservationId} with NotFound if reservation unknown" in {
      Get(s"/reservation/invalid") ~> route ~> check {
        status shouldBe NotFound
      }
    }

  }

  def ensureSchemaDropped = dao.ensureSchemaDropped
  def ensureSchemaCreated = dao.ensureSchemaCreated

} 
Example 92
Source File: ClusterHttpManagementRouteProviderSpec.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management.cluster

import akka.actor.ExtendedActorSystem
import akka.cluster.Cluster
import akka.http.scaladsl.model.{ StatusCodes, Uri }
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.management.scaladsl.ManagementRouteProviderSettings
import org.scalatest.{ Matchers, WordSpec }

object ClusterHttpManagementRouteProviderSpec {}

class ClusterHttpManagementRouteProviderSpec extends WordSpec with ScalatestRouteTest with Matchers {

  val cluster = Cluster(system)

  "Cluster HTTP Management Route" should {
    val routes = ClusterHttpManagementRouteProvider(
      system.asInstanceOf[ExtendedActorSystem]
    )
    "not expose write operations when readOnly set" in {
      val readOnlyRoutes = routes.routes(
        ManagementRouteProviderSettings(
          Uri("http://localhost"),
          readOnly = true
        )
      )
      Get("/cluster/members") ~> readOnlyRoutes ~> check {
        handled shouldEqual true
        status shouldEqual StatusCodes.OK
      }
      Post("/cluster/members") ~> readOnlyRoutes ~> check {
        status shouldEqual StatusCodes.MethodNotAllowed
      }
      Get("/cluster/members/member1") ~> readOnlyRoutes ~> check {
        handled shouldEqual true
        status shouldEqual StatusCodes.NotFound
      }
      Delete("/cluster/members/member1") ~> readOnlyRoutes ~> check {
        status shouldEqual StatusCodes.MethodNotAllowed
      }
      Put("/cluster/members/member1") ~> readOnlyRoutes ~> check {
        status shouldEqual StatusCodes.MethodNotAllowed
      }
    }

    "expose write when readOnly false" in {
      val allRoutes = routes.routes(
        ManagementRouteProviderSettings(
          Uri("http://localhost"),
          readOnly = false
        )
      )
      Get("/cluster/members") ~> allRoutes ~> check {
        handled shouldEqual true
      }
      Get("/cluster/members/member1") ~> allRoutes ~> check {
        handled shouldEqual true
        status shouldEqual StatusCodes.NotFound
      }
      Delete("/cluster/members/member1") ~> allRoutes ~> check {
        handled shouldEqual true
        status shouldEqual StatusCodes.NotFound
      }
      Put("/cluster/members/member1") ~> allRoutes ~> check {
        handled shouldEqual true
        status shouldEqual StatusCodes.NotFound
      }
    }
  }

} 
Example 93
Source File: LogLevelRoutesSpec.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management.loglevels.logback

import akka.actor.ExtendedActorSystem
import akka.http.javadsl.server.MalformedQueryParamRejection
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.management.scaladsl.ManagementRouteProviderSettings
import org.scalatest.Matchers
import org.scalatest.WordSpec
import org.slf4j.LoggerFactory
import akka.event.{ Logging => ClassicLogging }

class LogLevelRoutesSpec extends WordSpec with Matchers with ScalatestRouteTest {

  override def testConfigSource: String =
    """
      akka.loglevel = INFO
      """

  val routes = LogLevelRoutes
    .createExtension(system.asInstanceOf[ExtendedActorSystem])
    .routes(ManagementRouteProviderSettings(Uri("https://example.com"), readOnly = false))

  "The logback log level routes" must {

    "show log level of a Logger" in {
      Get("/loglevel/logback?logger=LogLevelRoutesSpec") ~> routes ~> check {
        responseAs[String]
      }
    }

    "change log level of a Logger" in {
      Put("/loglevel/logback?logger=LogLevelRoutesSpec&level=DEBUG") ~> routes ~> check {
        response.status should ===(StatusCodes.OK)
        LoggerFactory.getLogger("LogLevelRoutesSpec").isDebugEnabled should ===(true)
      }
    }

    "fail for unknown log level" in {
      Put("/loglevel/logback?logger=LogLevelRoutesSpec&level=MONKEY") ~> routes ~> check {
        rejection shouldBe an[MalformedQueryParamRejection]
      }
    }

    "not change loglevel if read only" in {
      val readOnlyRoutes = LogLevelRoutes
        .createExtension(system.asInstanceOf[ExtendedActorSystem])
        .routes(ManagementRouteProviderSettings(Uri("https://example.com"), readOnly = true))
      Put("/loglevel/logback?logger=LogLevelRoutesSpec&level=DEBUG") ~> readOnlyRoutes ~> check {
        response.status should ===(StatusCodes.Forbidden)
      }
    }

    "allow inspecting classic Akka loglevel" in {
      Get("/loglevel/akka") ~> routes ~> check {
        response.status should ===(StatusCodes.OK)
        responseAs[String] should ===("INFO")
      }
    }

    "allow changing classic Akka loglevel" in {
      Put("/loglevel/akka?level=DEBUG") ~> routes ~> check {
        response.status should ===(StatusCodes.OK)
        system.eventStream.logLevel should ===(ClassicLogging.DebugLevel)
      }
    }
  }

} 
Example 94
Source File: HealthCheckRoutesSpec.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management

import akka.actor.ExtendedActorSystem
import akka.http.scaladsl.model.{ StatusCodes, Uri }
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.management.scaladsl.{ HealthChecks, ManagementRouteProviderSettings }
import org.scalatest.{ Matchers, WordSpec }

import scala.concurrent.Future

class HealthCheckRoutesSpec extends WordSpec with Matchers with ScalatestRouteTest {

  private val eas = system.asInstanceOf[ExtendedActorSystem]

  private def testRoute(
      readyResultValue: Future[Either[String, Unit]] = Future.successful(Right(())),
      aliveResultValue: Future[Either[String, Unit]] = Future.successful(Right(()))
  ): Route = {
    new HealthCheckRoutes(eas) {
      override protected val healthChecks: HealthChecks = new HealthChecks {
        override def readyResult(): Future[Either[String, Unit]] = readyResultValue
        override def ready(): Future[Boolean] = readyResultValue.map(_.isRight)
        override def aliveResult(): Future[Either[String, Unit]] = aliveResultValue
        override def alive(): Future[Boolean] = aliveResultValue.map(_.isRight)
      }
    }.routes(ManagementRouteProviderSettings(Uri("http://whocares"), readOnly = false))
  }

  tests("/ready", result => testRoute(readyResultValue = result))
  tests("/alive", result => testRoute(aliveResultValue = result))

  def tests(endpoint: String, route: Future[Either[String, Unit]] => Route) = {
    s"Health check ${endpoint} endpoint" should {
      "return 200 for Right" in {
        Get(endpoint) ~> route(Future.successful(Right(()))) ~> check {
          status shouldEqual StatusCodes.OK
        }
      }
      "return 500 for Left" in {
        Get(endpoint) ~> route(Future.successful(Left("com.someclass.MyCheck"))) ~> check {
          status shouldEqual StatusCodes.InternalServerError
          responseAs[String] shouldEqual "Not Healthy: com.someclass.MyCheck"
        }
      }
      "return 500 for fail" in {
        Get(endpoint) ~> route(Future.failed(new RuntimeException("darn it"))) ~> check {
          status shouldEqual StatusCodes.InternalServerError
          responseAs[String] shouldEqual "Health Check Failed: darn it"
        }
      }
    }
  }
} 
Example 95
Source File: HttpContactPointRoutesSpec.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management.cluster.bootstrap.contactpoint

import akka.cluster.{ Cluster, ClusterEvent }
import akka.event.NoLogging
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.management.cluster.bootstrap.ClusterBootstrapSettings
import akka.testkit.{ SocketUtil, TestProbe }
import org.scalatest.concurrent.Eventually
import org.scalatest.time.{ Millis, Seconds, Span }
import org.scalatest.{ Matchers, WordSpecLike }

class HttpContactPointRoutesSpec
    extends WordSpecLike
    with Matchers
    with ScalatestRouteTest
    with HttpBootstrapJsonProtocol
    with Eventually {

  implicit override val patienceConfig: PatienceConfig =
    PatienceConfig(timeout = scaled(Span(3, Seconds)), interval = scaled(Span(50, Millis)))

  override def testConfigSource =
    s"""
    akka {
      remote {
        netty.tcp {
          hostname = "127.0.0.1"
          port = ${SocketUtil.temporaryServerAddress("127.0.0.1").getPort}
        }
      }
    }
    """.stripMargin

  "Http Bootstrap routes" should {

    val settings = ClusterBootstrapSettings(system.settings.config, NoLogging)
    val httpBootstrap = new HttpClusterBootstrapRoutes(settings)

    "empty list if node is not part of a cluster" in {
      ClusterBootstrapRequests.bootstrapSeedNodes("") ~> httpBootstrap.routes ~> check {
        responseAs[String] should include(""""seedNodes":[]""")
      }
    }

    "include seed nodes when part of a cluster" in {
      val cluster = Cluster(system)
      cluster.join(cluster.selfAddress)

      val p = TestProbe()
      cluster.subscribe(p.ref, ClusterEvent.InitialStateAsEvents, classOf[ClusterEvent.MemberUp])
      val up = p.expectMsgType[ClusterEvent.MemberUp]
      up.member should ===(cluster.selfMember)

      eventually {
        ClusterBootstrapRequests.bootstrapSeedNodes("") ~> httpBootstrap.routes ~> check {
          val response = responseAs[HttpBootstrapJsonProtocol.SeedNodes]
          response.seedNodes should !==(Set.empty)
          response.seedNodes.map(_.node) should contain(cluster.selfAddress)
        }
      }
    }
  }

} 
Example 96
Source File: AkkaHttpMarshallingSuite.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
package com.bot4s.telegram.marshalling

import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.RequestEntity
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.util.ByteString
import com.bot4s.telegram.api.TestUtils
import com.bot4s.telegram.marshalling.AkkaHttpMarshalling.underscore_case_marshaller
import com.bot4s.telegram.methods.SendDocument
import com.bot4s.telegram.models.{AkkaInputFile, InputFile}
import org.scalatest.{FunSuite, Matchers}

class AkkaHttpMarshallingSuite extends FunSuite with ScalatestRouteTest with Matchers with TestUtils {

  test("Correctly serialize top-level string members in Akka multipart requests") {
    val captionWithLineBreak = "this is a line\nand then\t another line"
    val channelId = "this_is_a_channel"
    val fileId = "and_a_file_id"

    val entity = SendDocument(channelId, InputFile(fileId), caption = Some(captionWithLineBreak))
    Post("/", Marshal(entity).to[RequestEntity]) ~> {
      formFields(('caption, 'chat_id, 'document)) {
        (caption, chat_id, document) => complete(caption + chat_id + document)
      }
    } ~> check {
      responseAs[String] shouldEqual (captionWithLineBreak + channelId + fileId)
    }
  }

  test("Handles AkkaInputFile") {
    val channelId = "this_is_a_channel"
    val content = "file content"
    val entity = SendDocument(channelId, AkkaInputFile("Pepe", ByteString(content)))
    Post("/", Marshal(entity).to[RequestEntity]) ~> {
      formFields('document) {
        document => complete(document)
      }
    } ~> check {
      responseAs[ByteString] shouldEqual ByteString(content)
    }
  }
} 
Example 97
Source File: MultipleTransportTest.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.session

import akka.http.scaladsl.model.{DateTime, HttpHeader}
import akka.http.scaladsl.model.headers.{RawHeader, HttpCookie, Cookie, `Set-Cookie`}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.softwaremill.session.SessionOptions._
import com.softwaremill.session.TestData._

trait MultipleTransportTest { this: ScalatestRouteTest =>

  trait TestUsingTransport {
    def transportName: String

    def getSession: Option[String]
    def countSessionHeaders: Int
    def setSessionHeader(s: String): HttpHeader
    def isSessionExpired: Boolean

    def getRefreshToken: Option[String]
    def countRefreshTokenHeaders: Int
    def setRefreshTokenHeader(s: String): HttpHeader
    def isRefreshTokenExpired: Boolean

    def getSessionTransport: GetSessionTransport
    def setSessionTransport: SetSessionTransport
  }

  object TestUsingCookies extends TestUsingTransport {
    val sessionCookieName = sessionConfig.sessionCookieConfig.name
    val refreshTokenCookieName = sessionConfig.refreshTokenCookieConfig.name

    val transportName = "cookies"

    def cookiesMap: Map[String, HttpCookie] =
      headers.collect { case `Set-Cookie`(cookie) => cookie.name -> cookie }.toMap
    private def countCookies(name: String): Int = headers.count {
      case `Set-Cookie`(cookie) => cookie.name == name
      case _                    => false
    }

    def getSession = cookiesMap.get(sessionCookieName).map(_.value)
    def countSessionHeaders = countCookies(sessionCookieName)
    def setSessionHeader(s: String) = Cookie(sessionCookieName, s)
    def isSessionExpired = cookiesMap.get(sessionCookieName).flatMap(_.expires).contains(DateTime.MinValue)

    def getRefreshToken = cookiesMap.get(refreshTokenCookieName).map(_.value)
    def countRefreshTokenHeaders = countCookies(refreshTokenCookieName)
    def setRefreshTokenHeader(s: String) = Cookie(refreshTokenCookieName, s)
    def isRefreshTokenExpired = cookiesMap.get(refreshTokenCookieName).flatMap(_.expires).contains(DateTime.MinValue)

    def getSessionTransport = usingCookies
    def setSessionTransport = usingCookies
  }

  object TestUsingHeaders extends TestUsingTransport {
    val setSessionHeaderName = sessionConfig.sessionHeaderConfig.sendToClientHeaderName
    val sessionHeaderName = sessionConfig.sessionHeaderConfig.getFromClientHeaderName
    val setRefreshTokenHeaderName = sessionConfig.refreshTokenHeaderConfig.sendToClientHeaderName
    val refreshTokenHeaderName = sessionConfig.refreshTokenHeaderConfig.getFromClientHeaderName

    val transportName = "headers"

    private def countHeaders(name: String): Int = headers.count(_.is(name.toLowerCase))

    def getSession = header(setSessionHeaderName).map(_.value)
    def countSessionHeaders = countHeaders(setSessionHeaderName)
    def setSessionHeader(s: String) = RawHeader(sessionHeaderName, s)
    def isSessionExpired = getSession.contains("")

    def getRefreshToken = header(setRefreshTokenHeaderName).map(_.value)
    def countRefreshTokenHeaders = countHeaders(setRefreshTokenHeaderName)
    def setRefreshTokenHeader(s: String) = RawHeader(refreshTokenHeaderName, s)
    def isRefreshTokenExpired = getRefreshToken.contains("")

    def getSessionTransport = usingHeaders
    def setSessionTransport = usingHeaders
  }
} 
Example 98
Source File: AbstractRestTest.scala    From slick-akka-http-oauth2   with Apache License 2.0 4 votes vote down vote up
package rest

import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatest.{Matchers, WordSpec}
import org.specs2.mock.Mockito
import persistence.dals._
import persitence.handlers.OAuth2DataHandler
import utils.{ActorModule, ConfigurationModuleImpl, PersistenceModule}

trait AbstractRestTest  extends WordSpec with Matchers with ScalatestRouteTest with Mockito{

  trait Modules extends ConfigurationModuleImpl with ActorModule with PersistenceModule {
    val system = AbstractRestTest.this.system

    override val accountsDal =  mock[AccountsDal]
    override val oauthAuthorizationCodesDal = mock[OAuthAuthorizationCodesDal]
    override val oauthClientsDal = mock[OAuthClientsDal]
    override val oauthAccessTokensDal = mock[OAuthAccessTokensDal]
    override val oauth2DataHandler = new OAuth2DataHandler(this)
    override def config = getConfig.withFallback(super.config)
  }

  def getConfig: Config = ConfigFactory.empty();


}