akka.http.scaladsl.testkit.RouteTestTimeout Scala Examples
The following examples show how to use akka.http.scaladsl.testkit.RouteTestTimeout.
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: TestSourceRoute.scala From ohara with Apache License 2.0 | 5 votes |
package oharastream.ohara.shabondi.source import java.util.concurrent.TimeUnit import akka.http.scaladsl.model._ import akka.http.scaladsl.testkit.RouteTestTimeout import oharastream.ohara.common.data.Row import oharastream.ohara.kafka.Consumer import oharastream.ohara.metrics.BeanChannel import oharastream.ohara.metrics.basic.CounterMBean import oharastream.ohara.shabondi.{BasicShabondiTest, KafkaSupport} import org.junit.Test import org.scalatest.matchers.should.Matchers._ import spray.json.DefaultJsonProtocol._ import spray.json._ import scala.concurrent.duration.Duration import scala.jdk.CollectionConverters._ final class TestSourceRoute extends BasicShabondiTest { import oharastream.ohara.shabondi.ShabondiRouteTestSupport._ // Extend the timeout to avoid the exception: // org.scalatest.exceptions.TestFailedException: Request was neither completed nor rejected within 1 second implicit val routeTestTimeout = RouteTestTimeout(Duration(5, TimeUnit.SECONDS)) private val columnCount = 6 private val requestCount = 200 private def sourceData: Map[String, Int] = (1 to columnCount).foldLeft(Map.empty[String, Int]) { (m, v) => m + ("col-" + v -> v) } @Test def testInvalidRequest(): Unit = { val topicKey1 = createTopicKey val config = defaultSourceConfig(Seq(topicKey1)) val webServer = new WebServer(config) val request = Get("/") request ~> webServer.routes ~> check { response.status should ===(StatusCodes.MethodNotAllowed) contentType should ===(ContentTypes.`text/plain(UTF-8)`) } val request2 = Post("/") request2 ~> webServer.routes ~> check { response.status should ===(StatusCodes.BadRequest) contentType should ===(ContentTypes.`text/plain(UTF-8)`) } val jsonRow = sourceData.toJson.compactPrint val entity = HttpEntity(ContentTypes.`application/json`, jsonRow) val request3 = Post("/", entity) request3 ~> webServer.routes ~> check { response.status should ===(StatusCodes.OK) contentType should ===(ContentTypes.`text/plain(UTF-8)`) } } @Test def testSourceRoute(): Unit = { val topicKey1 = createTopicKey val config = defaultSourceConfig(Seq(topicKey1)) val webServer = new WebServer(config) try { (1 to requestCount).foreach { _ => val jsonRow = sourceData.toJson.compactPrint val entity = HttpEntity(ContentTypes.`application/json`, jsonRow) val request = Post(uri = "/", entity) request ~> webServer.routes ~> check { entityAs[String] should ===("OK") } } // assertion val rowsTopic1: Seq[Consumer.Record[Row, Array[Byte]]] = KafkaSupport.pollTopicOnce(brokerProps, topicKey1, 60, requestCount) rowsTopic1.size should ===(requestCount) rowsTopic1(0).key.get.cells.size should ===(columnCount) // assert metrics val beans = counterMBeans() beans.size should ===(1) beans(0).getValue should ===(requestCount) } finally { webServer.close() topicAdmin.deleteTopic(topicKey1) } } private def counterMBeans(): Seq[CounterMBean] = BeanChannel.local().counterMBeans().asScala.toSeq }
Example 2
Source File: StaticServiceSpec.scala From incubator-retired-gearpump with Apache License 2.0 | 5 votes |
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 3
Source File: AdminServiceSpec.scala From incubator-retired-gearpump with Apache License 2.0 | 5 votes |
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 4
Source File: WorkerServiceSpec.scala From incubator-retired-gearpump with Apache License 2.0 | 5 votes |
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 5
Source File: ShipmentViewEndpointSpec.scala From ddd-leaven-akka-v2 with MIT License | 5 votes |
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 6
Source File: PaginationDirectivesWithDefaults.scala From akka-http-extensions with Apache License 2.0 | 5 votes |
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 7
Source File: PaginationSpec.scala From akka-http-extensions with Apache License 2.0 | 5 votes |
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 8
Source File: VinylDNSRouteTestHelper.scala From vinyldns with Apache License 2.0 | 5 votes |
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 9
Source File: SchedulerTestkit.scala From fusion-data with Apache License 2.0 | 5 votes |
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 10
Source File: StatsApiSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
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 11
Source File: PropertiesApiSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
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))) } } }