play.api.inject.guice.GuiceApplicationBuilder Scala Examples
The following examples show how to use play.api.inject.guice.GuiceApplicationBuilder.
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: HelloWorldSpec.scala From play-soap with Apache License 2.0 | 5 votes |
package play.soap.sbtplugin.tester import java.net.ServerSocket import java.util.concurrent.atomic.AtomicBoolean import javax.xml.ws.Endpoint import javax.xml.ws.handler.soap._ import javax.xml.ws.handler.MessageContext import org.apache.cxf.jaxws.EndpointImpl import play.soap.testservice.client._ import scala.collection.JavaConverters._ import scala.concurrent.{Await, Future} import scala.concurrent.duration._ import scala.reflect.ClassTag import play.api.test._ import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.soap.testservice.HelloWorldImpl class HelloWorldSpec extends ServiceSpec { sequential "HelloWorld" should { "say hello" in withClient { client => await(client.sayHello("world")) must_== "Hello world" } "say hello to many people" in withClient { client => await(client.sayHelloToMany(java.util.Arrays.asList("foo", "bar"))).asScala must_== List("Hello foo", "Hello bar") } "say hello to one user" in withClient { client => val user = new User user.setName("world") await(client.sayHelloToUser(user)).getUser.getName must_== "world" } "say hello with an exception" in withClient { client => await(client.sayHelloException("world")) must throwA[HelloException_Exception].like { case e => e.getMessage must_== "Hello world" } } "dont say hello" in withClient { client => await(client.dontSayHello()) must_== ((): Unit) } "allow adding custom handlers" in { val invoked = new AtomicBoolean() withApp { app => val client = app.injector.instanceOf[HelloWorldService].helloWorld(new SOAPHandler[SOAPMessageContext] { def getHeaders = null def handleMessage(context: SOAPMessageContext) = { invoked.set(true) true } def close(context: MessageContext) = () def handleFault(context: SOAPMessageContext) = true }) await(client.sayHello("world")) must_== "Hello world" invoked.get() must_== true } } } override type ServiceClient = HelloWorldService override type Service = HelloWorld override implicit val serviceClientClass: ClassTag[HelloWorldService] = ClassTag(classOf[HelloWorldService]) override def getServiceFromClient(c: ServiceClient): Service = c.helloWorld override def createServiceImpl(): Any = new HelloWorldImpl val servicePath: String = "helloWorld" }
Example 2
Source File: JdbcPersistenceModuleSpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.javadsl.persistence.jdbc import javax.inject.Inject import org.scalatest._ import play.api.PlayException import play.api.db.DBApi import play.api.inject.guice.GuiceApplicationBuilder import play.api.inject.{ bind => playBind } import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AsyncWordSpec class JdbcPersistenceModuleSpec extends AsyncWordSpec with Matchers with BeforeAndAfterAll { "The JdbcPersistenceModule" should { "should start the service when database is not available" in { // Should be okay to build an application since Lagom configuration // enables it without a database being available. val app = new GuiceApplicationBuilder() .bindings(playBind[DbWrapper].toSelf) .configure( // Correct configuration, but the database is not available "db.default.driver" -> "org.h2.Driver", "db.default.url" -> "jdbc:h2:tcp://localhost/~/notavailable", "lagom.cluster.exit-jvm-when-system-terminated" -> "off", "lagom.cluster.bootstrap.enabled" -> "off" ) .build() val dbWrapper = app.injector.instanceOf[DbWrapper] dbWrapper should not be (null) app.stop().map(_ => succeed) } "should fail to start the service when database is not available and configured to fail fast" in { assertThrows[PlayException] { new GuiceApplicationBuilder() .bindings(playBind[DbWrapper].toSelf) .configure( // Correct configuration, but the database is not available "db.default.driver" -> "org.h2.Driver", "db.default.url" -> "jdbc:h2:tcp://localhost/~/notavailable", // And it is configured to fail fast "play.db.prototype.hikaricp.initializationFailTimeout" -> "1", "lagom.cluster.exit-jvm-when-system-terminated" -> "off", "lagom.cluster.bootstrap.enabled" -> "off" ) .build() } } } } // So that we can confirm DBApi was created class DbWrapper @Inject() (val dbApi: DBApi)
Example 3
Source File: ReleaseTwoIntegrationSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package support import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.play.guice.GuiceOneServerPerSuite import play.api.Application import play.api.http.{HeaderNames, MimeTypes, Status} import play.api.inject.guice.GuiceApplicationBuilder import support.functional.FunctionalSyntax import support.wiremock.WireMockSupport trait ReleaseTwoIntegrationSpec extends AnyWordSpec with GuiceOneServerPerSuite with WireMockSupport with Matchers with Status with HeaderNames with MimeTypes with FakeApplicationConfig with FunctionalSyntax { override implicit lazy val app: Application = new GuiceApplicationBuilder() .configure(fakeApplicationConfig + ("feature-switch.release-2.enabled" -> true)) .build() }
Example 4
Source File: IntegrationSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package support import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.play.guice.GuiceOneServerPerSuite import play.api.Application import play.api.http.{HeaderNames, MimeTypes, Status} import play.api.inject.guice.GuiceApplicationBuilder import support.functional.FunctionalSyntax import support.wiremock.WireMockSupport trait IntegrationSpec extends AnyWordSpec with GuiceOneServerPerSuite with WireMockSupport with Matchers with Status with HeaderNames with MimeTypes with FakeApplicationConfig with FunctionalSyntax { override implicit lazy val app: Application = new GuiceApplicationBuilder() .configure(fakeApplicationConfig) .build() }
Example 5
Source File: LoginStatusSpec.scala From play-ui with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.views.layouts import org.joda.time.{DateTime, DateTimeZone} import org.scalatest.{Matchers, WordSpec} import play.api.i18n._ import play.api.inject.guice.GuiceApplicationBuilder import play.api.test.Helpers.contentAsString import uk.gov.hmrc.play.views.html.layouts.loginStatus import play.api.test.Helpers._ import play.api.i18n.Messages.Implicits._ class LoginStatusSpec extends WordSpec with Matchers { implicit val application = new GuiceApplicationBuilder() .configure(Map("play.i18n.langs" -> List("en", "cy"))) .build() "The loginStatus" should { val userName = "Ivor" val previouslyLoggedInAt = new DateTime(2018, 4, 20, 16, 20, 0, 0, DateTimeZone.forID("Europe/London")) "show the first login message in English" in { implicit val lang = Lang("en") val content = contentAsString(loginStatus(userName, None, "logoutUrl")) content should include("Ivor, this is the first time you have logged in") } "show the first login message in Welsh" in { implicit val lang = Lang("cy") val content = contentAsString(loginStatus(userName, None, "logoutUrl")) content should include("Ivor, dyma’r tro cyntaf i chi fewngofnodi") } "show the previous login message in English" in { implicit val lang = Lang("en") val content = contentAsString(loginStatus(userName, Some(previouslyLoggedInAt), "logoutUrl")) content should include("Ivor, you last signed in 4:20pm, Friday 20 April 2018") } "show the previous login message in Welsh (with the day and month in Welsh)" in { implicit val lang = Lang("cy") val content = contentAsString(loginStatus(userName, Some(previouslyLoggedInAt), "logoutUrl")) content should include("Ivor, y tro diwethaf i chi fewngofnodi oedd 4:20pm, Dydd Gwener 20 Ebrill 2018") } } }
Example 6
Source File: EuExitLinksSpec.scala From play-ui with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.views.layouts import org.jsoup.Jsoup import org.scalatest.{Matchers, WordSpec} import play.api.i18n.Lang import play.api.i18n.Messages.Implicits._ import play.api.inject.guice.GuiceApplicationBuilder import play.api.test.Helpers.{contentAsString, defaultAwaitTimeout} import java.util.{List => JavaList} import uk.gov.hmrc.play.views.html.layouts.eu_exit_links import scala.collection.JavaConverters._ import scala.collection.immutable.List class EuExitLinksSpec extends WordSpec with Matchers { val englishLinkTextEntries: JavaList[String] = List( "Prepare your business for the UK leaving the EU", "Prepare for EU Exit if you live in the UK", "Living in Europe after the UK leaves the EU", "Continue to live in the UK after it leaves the EU" ).asJava val welshLinkTextEntries: JavaList[String] = List( "Paratoi eich busnes ar gyfer y DU yn gadael yr UE (Saesneg yn unig)", "Paratoi ar gyfer Ymadael â’r UE os ydych yn byw yn y DU (Saesneg yn unig)", "Byw yn Ewrop ar ôl i’r DU adael yr UE (Saesneg yn unig)", "Parhau i fyw yn y DU ar ôl iddi adael yr UE (Saesneg yn unig)" ).asJava implicit val application = new GuiceApplicationBuilder() .configure(Map("play.i18n.langs" -> List("en", "cy"))) .build() "Eu Exit Links on an English Language Page" should { implicit val lang = Lang("en") val markup = contentAsString(eu_exit_links()) val document = Jsoup.parse(markup) val links = document.getElementsByTag("a") "Include the section header" in { markup should include("<h2 class=\"heading-medium\">Prepare for EU Exit</h2>") } "Include four links" in { links.size should be(4) } "Have the correct link text in English" in { links.eachText() should be(englishLinkTextEntries) } } "Eu Exit Links on a Welsh Language Page" should { implicit val lang = Lang("cy") val markup = contentAsString(eu_exit_links()) val document = Jsoup.parse(markup) val links = document.getElementsByTag("a") "Include the section header" in { markup should include("<h2 class=\"heading-medium\">Paratoi ar gyfer Ymadael â’r UE (Saesneg yn unig)</h2>") } "Include four links" in { links.size should be(4) } "Have the correct link text in Welsh" in { links.eachText() should be(welshLinkTextEntries) } } }
Example 7
Source File: FooterLinksSpec.scala From play-ui with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.views.layouts import org.jsoup.Jsoup import org.scalatest.{Matchers, WordSpec} import play.api.i18n.Lang import play.api.test.Helpers._ import play.twirl.api.Html import uk.gov.hmrc.play.views.html.layouts.FooterLinks import play.api.i18n.Messages.Implicits._ import play.api.inject.guice.GuiceApplicationBuilder import java.util.{List => JavaList} import scala.collection.JavaConverters._ import scala.collection.immutable.List class FooterLinksSpec extends WordSpec with Matchers { implicit val application = new GuiceApplicationBuilder() .configure(Map("play.i18n.langs" -> List("en", "cy"))) .build() val englishLinkTextEntries: JavaList[String] = List( "Cookies", "Privacy policy", "Terms and conditions", "Help using GOV.UK" ).asJava val welshLinkTextEntries: JavaList[String] = List( "Cwcis", "Polisi preifatrwydd", "Telerau ac Amodau", "Help wrth ddefnyddio GOV.UK" ).asJava "The footerLinks in English" should { val footerLinks = new FooterLinks() implicit val lang = Lang("en") val content = contentAsString(footerLinks()) val document = Jsoup.parse(content) val links = document.getElementsByTag("a") "include visually hidden h2 text in English" in { implicit val lang = Lang("en") val content = contentAsString(footerLinks()) content should include("<h2 class=\"visually-hidden\">Support links</h2>") } "Have the correct link text in English" in { links.eachText() should be(englishLinkTextEntries) } } "The footerLinks in Welsh" should { val footerLinks = new FooterLinks() implicit val lang = Lang("cy") val content = contentAsString(footerLinks()) val document = Jsoup.parse(content) val links = document.getElementsByTag("a") "include visually hidden h2 text in Welsh" in { content should include("<h2 class=\"visually-hidden\">Cysylltiadau cymorth</h2>") } "Have the correct link text in Welsh" in { links.eachText() should be(welshLinkTextEntries) } } }
Example 8
Source File: WordVectorSpec.scala From tap with Apache License 2.0 | 5 votes |
package io.heta.tap import org.scalatestplus.play.PlaySpec import play.api.inject.guice.GuiceApplicationBuilder import scala.concurrent.Await import scala.concurrent.duration._ class WordVectorSpec extends PlaySpec{ //dependency injection private val app = new GuiceApplicationBuilder().build private val wordvector = app.injector.instanceOf[WordVector] "find neareast words" in { val lst = wordvector.nearestWords("day", 10) val result = Await.result(lst, 360 seconds) if(result!= None){ assert(result.get(0) == "week") assert(result.get(1) == "days") assert(result.get(2) == "morning") assert(result.get(3) == "month") assert(result.get(4) == "hours") assert(result.get(5) == "afternoon") assert(result.get(6) == "hour") assert(result.get(7) == "weekend") assert(result.get(8) == "evening") assert(result.get(9) == "time") } } }
Example 9
Source File: HttpTimeoutSpec.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.http import java.net.{ServerSocket, URI} import java.util.concurrent.TimeoutException import org.scalatest.concurrent.ScalaFutures import org.scalatest.BeforeAndAfterAll import org.scalatest.wordspec.AnyWordSpecLike import org.scalatest.matchers.should.Matchers import org.webbitserver.handler.{DelayedHttpHandler, StringHttpHandler} import org.webbitserver.netty.NettyWebServer import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.WSClient import play.api.test.WsTestClient import play.api.{Configuration, Play} import uk.gov.hmrc.http.HeaderCarrier import uk.gov.hmrc.play.http.ws.WSHttp import uk.gov.hmrc.play.test.TestHttpCore import scala.concurrent.{Await, ExecutionContext} import scala.concurrent.duration.DurationInt class HttpTimeoutSpec extends AnyWordSpecLike with Matchers with ScalaFutures with BeforeAndAfterAll { import ExecutionContext.Implicits.global lazy val fakeApplication = GuiceApplicationBuilder(configuration = Configuration("play.ws.timeout.request" -> "1000ms")).build() override def beforeAll() { super.beforeAll() Play.start(fakeApplication) } override def afterAll() { super.afterAll() Play.stop(fakeApplication) } WsTestClient.withClient{ client => "HttpCalls" should { "be gracefully timeout when no response is received within the 'timeout' frame" in { val http = new WSHttp with TestHttpCore { override val wsClient = fakeApplication.injector.instanceOf[WSClient] } // get an unused port val ss = new ServerSocket(0) ss.close() val executor = ExecutionContext.global // fromExecutorService(ExecutionContext.global) val publicUri = URI.create(s"http://localhost:${ss.getLocalPort}") val ws = new NettyWebServer(executor, ss.getLocalSocketAddress, publicUri) try { //starts web server ws.add( "/test", new DelayedHttpHandler(executor, 2000, new StringHttpHandler("application/json", "{name:'pong'}"))) ws.start().get() implicit val hc = HeaderCarrier() val start = System.currentTimeMillis() intercept[TimeoutException] { //make request to web server Await.result(http.doPost(s"$publicUri/test", "{name:'ping'}", Seq()), 5.seconds) } val diff = (System.currentTimeMillis() - start).toInt // there is test execution delay around 700ms diff should be >= 1000 diff should be < 2500 } finally { ws.stop() } } } } }
Example 10
Source File: RemoteSpecs.scala From play-json-schema-validator with Apache License 2.0 | 5 votes |
package com.eclipsesource.schema import com.eclipsesource.schema.drafts.Version4 import com.eclipsesource.schema.test.{Assets, JsonSpec} import org.specs2.mutable.Specification import org.specs2.specification.AfterAll import org.specs2.specification.core.Fragments import org.specs2.specification.dsl.Online import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.mvc.DefaultActionBuilder import play.api.test.TestServer class RemoteSpecs extends Specification with JsonSpec with Online with AfterAll { import Version4._ implicit val validator: SchemaValidator = { SchemaValidator(Some(Version4)).addSchema( "http://localhost:1234/scope_foo.json", JsonSource.schemaFromString( """{ | "definitions": { | "bar": { "type": "string" } | } |}""".stripMargin ).get ) } def createApp: Application = new GuiceApplicationBuilder() .appRoutes(app => { val Action = app.injector.instanceOf[DefaultActionBuilder] Assets.routes(Action)(getClass, "remotes/") }) .build() lazy val server = TestServer(port = 1234, createApp) def afterAll: Unit = { server.stop Thread.sleep(1000) } def validateAjv(testName: String): Fragments = validate(testName, "ajv_tests") sequential "Validation from remote resources is possible" >> { { server.start Thread.sleep(1000) } must not(throwAn[Exception]) continueWith { validateMultiple( "ajv_tests" -> Seq( "5_adding_dependency_after", "5_recursive_references", "12_restoring_root_after_resolve", "13_root_ref_in_ref_in_remote_ref", "14_ref_in_remote_ref_with_id", "62_resolution_scope_change" ), "draft4" -> Seq("refRemote") ) } } validateAjv("1_ids_in_refs") }
Example 11
Source File: ServiceSpec.scala From play-soap with Apache License 2.0 | 5 votes |
package play.soap.sbtplugin.tester import java.net.ServerSocket import java.util.concurrent.atomic.AtomicBoolean import javax.xml.ws.Endpoint import javax.xml.ws.handler.soap._ import javax.xml.ws.handler.MessageContext import org.apache.cxf.jaxws.EndpointImpl import play.soap.testservice.client._ import scala.collection.JavaConverters._ import scala.concurrent.{Await, Future} import scala.concurrent.duration._ import scala.reflect.ClassTag import play.api.test._ import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder abstract class ServiceSpec extends PlaySpecification { val servicePath: String def await[T](future: Future[T]): T = Await.result(future, 10.seconds) def withClient[T](block: Service => T): T = withApp { app => val client = app.injector.instanceOf[ServiceClient] val service = getServiceFromClient(client) block(service) } def withApp[T](block: Application => T): T = withService { port => implicit val app = new GuiceApplicationBuilder() .configure("play.soap.address" -> s"http://localhost:$port/$servicePath") .build Helpers.running(app) { block(app) } } def withService[T](block: Int => T): T = { val port = findAvailablePort() val impl = createServiceImpl() val endpoint = Endpoint.publish(s"http://localhost:$port/$servicePath", impl) try { block(port) } finally { endpoint.stop() // Need to shutdown whole engine. Note, Jetty's shutdown doesn't seem to happen synchronously, have to wait // a few seconds for the port to be released. This is why we use a different port each time. endpoint.asInstanceOf[EndpointImpl].getBus.shutdown(true) } } def findAvailablePort() = { val socket = new ServerSocket(0) try { socket.getLocalPort } finally { socket.close() } } }
Example 12
Source File: KubeServiceLocatorServer.scala From lagom-on-kube with Apache License 2.0 | 5 votes |
package me.alexray.lagom.kube.discovery import java.io.Closeable import java.net.URI import java.util.{Map => JMap} import com.lightbend.lagom.gateway.{ServiceGateway, ServiceGatewayConfig, ServiceGatewayFactory} import me.alexray.lagom.kube.discovery.impl.KubeServiceRegistryModule import me.alexray.lagom.kube.gateway.{KubeServiceGateway, KubeServiceGatewayConfig, KubeServiceGatewayFactory} import play.api.Application import play.api.Logger import play.api.Mode import play.api.Play import play.api.inject.guice.GuiceApplicationBuilder import play.api.inject.guice.GuiceableModule.fromGuiceModule import play.core.server.ServerConfig import play.core.server.ServerProvider import play.core.server.ServerWithStop import scala.util.control.NonFatal class KubeServiceLocatorServer extends Closeable { private val logger: Logger = Logger(this.getClass) @volatile private var server: ServerWithStop = _ @volatile private var gateway: KubeServiceGateway = _ def start(serviceLocatorPort: Int, serviceGatewayPort: Int, unmanagedServices: JMap[String, String]): Unit = synchronized { require(server == null, "Service locator is already running on " + server.mainAddress) val application = createApplication(KubeServiceGatewayConfig(serviceGatewayPort), unmanagedServices) Play.start(application) try { server = createServer(application, serviceLocatorPort) } catch { case NonFatal(e) => throw new RuntimeException(s"Unable to start service locator on port $serviceLocatorPort", e) } try { gateway = application.injector.instanceOf[KubeServiceGatewayFactory].start() } catch { case NonFatal(e) => throw new RuntimeException(s"Unable to start service gateway on port $serviceGatewayPort", e) } logger.info("Service locator can be reached at " + serviceLocatorAddress) logger.info("Service gateway can be reached at " + serviceGatewayAddress) } private def createApplication(serviceGatewayConfig: KubeServiceGatewayConfig, unmanagedServices: JMap[String, String]): Application = { new GuiceApplicationBuilder() .overrides(KubeServiceRegistryModule(serviceGatewayConfig, unmanagedServices)) .build() } private def createServer(application: Application, port: Int): ServerWithStop = { val config = ServerConfig(port = Some(port), mode = Mode.Test) val provider = implicitly[ServerProvider] provider.createServer(config, application) } override def close(): Unit = synchronized { if (server == null) Logger.logger.debug("Service locator was already stopped") else { logger.debug("Stopping service locator...") server.stop() server = null logger.info("Service locator stopped") } } def serviceLocatorAddress: URI = { // Converting InetSocketAddress into URL is not that simple. // Because we know the service locator is running locally, I'm hardcoding the hostname and protocol. new URI(s"http://localhost:${server.mainAddress.getPort}") } def serviceGatewayAddress: URI = { new URI(s"http://localhost:${gateway.address.getPort}") } }
Example 13
Source File: HatDataStatsProcessorSpec.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
package org.hatdex.hat.api.service.monitoring import java.util.UUID import akka.stream.Materializer import com.google.inject.AbstractModule import net.codingwell.scalaguice.ScalaModule import org.hatdex.hat.api.models.{ EndpointData, Owner } import org.hatdex.hat.api.service.applications.{ TestApplicationProvider, TrustedApplicationProvider } import org.hatdex.hat.api.service.monitoring.HatDataEventBus.DataCreatedEvent import org.hatdex.hat.authentication.models.HatUser import org.hatdex.hat.dal.ModelTranslation import org.hatdex.hat.resourceManagement.FakeHatConfiguration import org.joda.time.DateTime import org.specs2.mock.Mockito import org.specs2.specification.Scope import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.json.{ JsValue, Json } import play.api.test.PlaySpecification import play.api.{ Application, Logger } class HatDataStatsProcessorSpec extends PlaySpecification with Mockito with HatDataStatsProcessorContext { val logger = Logger(this.getClass) sequential "The `computeInboundStats` method" should { "Correctly count numbers of values for simple objects" in { val service = application.injector.instanceOf[HatDataStatsProcessor] val stats = service.computeInboundStats(simpleDataCreatedEvent) import org.hatdex.hat.api.json.DataStatsFormat._ logger.debug(s"Got back stats: ${Json.prettyPrint(Json.toJson(stats))}") stats.logEntry must be equalTo "test item" stats.statsType must be equalTo "inbound" stats.stats.length must be equalTo 1 val endpointStats = stats.stats.head endpointStats.endpoint must be equalTo "testendpoint" endpointStats.propertyStats("field") must equalTo(1) endpointStats.propertyStats("date") must equalTo(1) endpointStats.propertyStats("date_iso") must equalTo(1) endpointStats.propertyStats("anotherField") must equalTo(1) endpointStats.propertyStats("object.objectField") must equalTo(1) endpointStats.propertyStats("object.objectFieldArray[]") must equalTo(3) endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName") must equalTo(2) endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName2") must equalTo(2) } } } trait HatDataStatsProcessorContext extends Scope { import scala.concurrent.ExecutionContext.Implicits.global // Setup default users for testing val owner = HatUser(UUID.randomUUID(), "hatuser", Some("pa55w0rd"), "hatuser", Seq(Owner()), enabled = true) class ExtrasModule extends AbstractModule with ScalaModule { override def configure(): Unit = { bind[TrustedApplicationProvider].toInstance(new TestApplicationProvider(Seq())) } } lazy val application: Application = new GuiceApplicationBuilder() .configure(FakeHatConfiguration.config) .overrides(new ExtrasModule) .build() implicit lazy val materializer: Materializer = application.materializer val simpleJson: JsValue = Json.parse( """ | { | "field": "value", | "date": 1492699047, | "date_iso": "2017-04-20T14:37:27+00:00", | "anotherField": "anotherFieldValue", | "object": { | "objectField": "objectFieldValue", | "objectFieldArray": ["objectFieldArray1", "objectFieldArray2", "objectFieldArray3"], | "objectFieldObjectArray": [ | {"subObjectName": "subObject1", "subObjectName2": "subObject1-2"}, | {"subObjectName": "subObject2", "subObjectName2": "subObject2-2"} | ] | } | } """.stripMargin) val simpleDataCreatedEvent = DataCreatedEvent( "testhat.hubofallthings.net", ModelTranslation.fromInternalModel(owner).clean, DateTime.now(), "test item", Seq( EndpointData("testendpoint", Option(UUID.randomUUID()), None, None, simpleJson, None))) }
Example 14
Source File: ChatControllerSpec.scala From Scala-Reactive-Programming with MIT License | 5 votes |
package controllers import org.scalatest.concurrent.PatienceConfiguration.Timeout import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures} import org.scalatestplus.play._ import play.api.inject.guice.GuiceApplicationBuilder import play.api.test._ import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient import play.shaded.ahc.org.asynchttpclient.ws.WebSocket import scala.compat.java8.FutureConverters import scala.concurrent.Await import scala.concurrent.duration._ class ChatControllerSpec extends PlaySpec with ScalaFutures with IntegrationPatience { "ChatController" should { "reject a websocket flow if the origin is set incorrectly" in WsTestClient.withClient { client => // Pick a non standard port that will fail the (somewhat contrived) origin check... lazy val port: Int = 31337 val app = new GuiceApplicationBuilder().build() Helpers.running(TestServer(port, app)) { val myPublicAddress = s"localhost:$port" val serverURL = s"ws://$myPublicAddress/chat" val asyncHttpClient: AsyncHttpClient = client.underlying[AsyncHttpClient] val webSocketClient = new WebSocketClient(asyncHttpClient) try { val origin = "ws://example.com/ws/chat" val listener = new WebSocketClient.LoggingListener val completionStage = webSocketClient.call(serverURL, origin, listener) val f = FutureConverters.toScala(completionStage) val result = Await.result(f, atMost = 1000 millis) listener.getThrowable mustBe a[IllegalStateException] } catch { case e: IllegalStateException => e mustBe an [IllegalStateException] case e: java.util.concurrent.ExecutionException => val foo = e.getCause foo mustBe an [IllegalStateException] } } } "accept a websocket flow if the origin is set correctly" in WsTestClient.withClient { client => lazy val port: Int = Helpers.testServerPort val app = new GuiceApplicationBuilder().build() Helpers.running(TestServer(port, app)) { val myPublicAddress = s"localhost:$port" val serverURL = s"ws://$myPublicAddress/chat" val asyncHttpClient: AsyncHttpClient = client.underlying[AsyncHttpClient] val webSocketClient = new WebSocketClient(asyncHttpClient) val origin = serverURL val listener = new WebSocketClient.LoggingListener val completionStage = webSocketClient.call(serverURL, origin, listener) val f = FutureConverters.toScala(completionStage) whenReady(f, timeout = Timeout(1 second)) { webSocket => webSocket mustBe a [WebSocket] } } } } }
Example 15
Source File: PlaySpecs2Spec.scala From play-grpc with Apache License 2.0 | 5 votes |
package play.grpc.specs2 import org.junit.runner.RunWith import org.specs2.runner.JUnitRunner import play.api.inject.bind import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.WSClient import play.api.libs.ws.WSRequest import play.api.routing.Router import play.api.test._ import akka.grpc.internal.GrpcProtocolNative import example.myapp.helloworld.grpc.helloworld._ import io.grpc.Status @RunWith(classOf[JUnitRunner]) class PlaySpecs2Spec extends ForServer with ServerGrpcClient with PlaySpecification with ApplicationFactories { protected def applicationFactory: ApplicationFactory = withGuiceApp(GuiceApplicationBuilder().overrides(bind[Router].to[GreeterServiceImpl])) // RICH: Still need to work out how to make WSClient work properly with endpoints def wsUrl(path: String)(implicit running: RunningServer): WSRequest = { val ws = running.app.injector.instanceOf[WSClient] val url = running.endpoints.httpEndpoint.get.pathUrl(path) ws.url(url) } "A Play server bound to a gRPC router" should { "give a 404 when routing a non-gRPC request" >> { implicit rs: RunningServer => val result = await(wsUrl("/").get) result.status must ===(404) // Maybe should be a 426, see #396 } "give a 415 error when not using a gRPC content-type" >> { implicit rs: RunningServer => val result = await(wsUrl(s"/${GreeterService.name}/FooBar").get) result.status must ===(415) // Maybe should be a 426, see #396 } "give a grpc UNIMPLEMENTED when routing a non-existent gRPC method" >> { implicit rs: RunningServer => val result = await( wsUrl(s"/${GreeterService.name}/FooBar") .addHttpHeaders("Content-Type" -> GrpcProtocolNative.contentType.toString) .get, ) result.status must ===(200) // Maybe should be a 426, see #396 result.header("grpc-status") must beSome(Status.Code.UNIMPLEMENTED.value().toString) } "give a grpc INVALID_ARGUMENT error when routing an empty request to a gRPC method" >> { implicit rs: RunningServer => val result = await( wsUrl(s"/${GreeterService.name}/SayHello") .addHttpHeaders("Content-Type" -> GrpcProtocolNative.contentType.toString) .get, ) result.status must ===(200) // Maybe should be a 426, see #396 // grpc-status 3 means INVALID_ARGUMENT error. See https://developers.google.com/maps-booking/reference/grpc-api/status_codes result.header("grpc-status") must beSome(Status.Code.INVALID_ARGUMENT.value().toString) } "work with a gRPC client" >> { implicit rs: RunningServer => withGrpcClient[GreeterServiceClient] { client: GreeterServiceClient => val reply = await(client.sayHello(HelloRequest("Alice"))) reply.message must ===("Hello, Alice!") } } } }
Example 16
Source File: PlayScalaTestSpec.scala From play-grpc with Apache License 2.0 | 5 votes |
package play.grpc.scalatest import io.grpc.Status import org.scalatest.concurrent.IntegrationPatience import org.scalatest.concurrent.ScalaFutures import org.scalatestplus.play.PlaySpec import org.scalatestplus.play.guice.GuiceOneServerPerTest import play.api.Application import play.api.inject.bind import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.WSClient import play.api.routing.Router import akka.grpc.internal.GrpcProtocolNative import example.myapp.helloworld.grpc.helloworld._ class PlayScalaTestSpec extends PlaySpec with GuiceOneServerPerTest with ServerGrpcClient with ScalaFutures with IntegrationPatience { override def fakeApplication(): Application = { GuiceApplicationBuilder() .overrides(bind[Router].to[GreeterServiceImpl]) .build() } implicit def ws: WSClient = app.injector.instanceOf(classOf[WSClient]) "A Play server bound to a gRPC router" must { "give a 404 when routing a non-gRPC request" in { val result = wsUrl("/").get.futureValue result.status must be(404) // Maybe should be a 426, see #396 } "give a 415 error when not using a gRPC content-type" in { val result = wsUrl(s"/${GreeterService.name}/FooBar").get.futureValue result.status must be(415) } "give a grpc 'unimplemented' error when routing a non-existent gRPC method" in { val result = wsUrl(s"/${GreeterService.name}/FooBar") .addHttpHeaders("Content-Type" -> GrpcProtocolNative.contentType.toString) .get .futureValue result.status must be(200) // Maybe should be a 426, see #396 result.header("grpc-status") mustEqual Some(Status.Code.UNIMPLEMENTED.value().toString) } "give a grpc 'invalid argument' error when routing an empty request to a gRPC method" in { val result = wsUrl(s"/${GreeterService.name}/SayHello") .addHttpHeaders("Content-Type" -> GrpcProtocolNative.contentType.toString) .get .futureValue result.status must be(200) result.header("grpc-status") mustEqual Some(Status.Code.INVALID_ARGUMENT.value().toString) } "work with a gRPC client" in withGrpcClient[GreeterServiceClient] { client: GreeterServiceClient => val reply = client.sayHello(HelloRequest("Alice")).futureValue reply.message must be("Hello, Alice!") } } }
Example 17
Source File: PrometheusModuleSpec.scala From play-prometheus-filters with MIT License | 5 votes |
package com.github.stijndehaes.playprometheusfilters import io.prometheus.client.{Collector, CollectorRegistry} import org.scalatest.{BeforeAndAfter, MustMatchers, PrivateMethodTester, WordSpec} import org.scalatestplus.play.guice.GuiceOneAppPerTest import play.api.inject.guice.GuiceApplicationBuilder class PrometheusModuleSpec extends WordSpec with MustMatchers with BeforeAndAfter with PrivateMethodTester with GuiceOneAppPerTest { before { // clearing registry before each test CollectorRegistry.defaultRegistry.clear() } "PrometheusModule" should { "register default exporters when enabled" in { // default enabled val app = new GuiceApplicationBuilder() .configure(PrometheusModule.defaultExportsKey -> true) .build() val collector = app.injector.instanceOf[CollectorRegistry] val collectors = PrivateMethod[java.util.HashSet[Collector]]('collectors) (collector invokePrivate collectors()).size must be > 0 } "not register default exporters when disabled" in { // disable default exporters val app = new GuiceApplicationBuilder() .configure(PrometheusModule.defaultExportsKey -> false) .build() val collector = app.injector.instanceOf[CollectorRegistry] val collectors = PrivateMethod[java.util.HashSet[Collector]]('collectors) (collector invokePrivate collectors()).size must be (0) } } def getExporterNames: Seq[String] = { val exportNames = collection.mutable.Buffer.empty[String] val mfs = registry.metricFamilySamples() while(mfs.hasMoreElements) { exportNames += mfs.nextElement().name } exportNames } } }
Example 18
Source File: ZipkinModuleSpec.scala From play-zipkin-tracing with Apache License 2.0 | 5 votes |
package brave.play.module import java.util.Collections import akka.actor.CoordinatedShutdown import brave.Tracing import brave.play.{ZipkinTraceService, ZipkinTraceServiceLike} import org.scalatest.AsyncFlatSpec import play.api.inject.guice.GuiceApplicationBuilder import zipkin2.reporter.Sender import zipkin2.reporter.okhttp3.OkHttpSender class ZipkinModuleSpec extends AsyncFlatSpec { val injector = new GuiceApplicationBuilder() .bindings(new ZipkinModule) .injector() it should "provide an okhttp sender" in { val sender = injector.instanceOf[Sender] assert(sender.isInstanceOf[OkHttpSender]) } it should "eventually close the sender" in { // provisioning the sender so we can tell if it is closed on shutdown val sender = injector.instanceOf[Sender] // stopping the application should close the sender! injector.instanceOf[CoordinatedShutdown].run(CoordinatedShutdown.UnknownReason) map { _ => val thrown = intercept[Exception] { sender.sendSpans(Collections.emptyList[Array[Byte]]).execute() } assert(thrown.getMessage === "closed") } } it should "provide a tracing component" in instanceOfTracing { tracing => assert(Tracing.current() != null) assert(Tracing.current() == tracing) } it should "eventually close the tracing component" in instanceOfTracing { tracing => // stopping the application should close the tracing component! injector.instanceOf[CoordinatedShutdown].run(CoordinatedShutdown.UnknownReason) map { _ => assert(Tracing.current() == null) } } private def instanceOfTracing[A](test: Tracing => A): A = { val tracing = injector.instanceOf[Tracing] try { test(tracing) } finally { // Ensures there is no active Tracing object tracing.close() } } it should "provide a zipkin trace service" in { // TODO: dies due to missing dispatcher val service = injector.instanceOf[ZipkinTraceServiceLike] assert(service.isInstanceOf[ZipkinTraceService]) } }
Example 19
Source File: FinancialDataQueryParamsSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.models import org.joda.time.LocalDate import org.scalatest.TestData import org.scalatestplus.play.guice.GuiceOneAppPerTest import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import uk.gov.hmrc.vatapi.UnitSpec class FinancialDataQueryParamsSpec extends UnitSpec with GuiceOneAppPerTest { val testTime: LocalDate = LocalDate.now() implicit override def newAppForTest(testData: TestData): Application = new GuiceApplicationBuilder().configure(Map(s"Test.mtd-date" -> testTime.minusYears(10).toString)).build() "DateRangeQueryParams" should { "return an object when all the date range is within 1 year" in { val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(1).toString)), Some(Right(testTime.minusDays(1).toString))) response.isRight shouldBe true response.right.get.from shouldEqual LocalDate.parse(testTime.minusYears(1).toString) response.right.get.to shouldEqual LocalDate.parse(testTime.minusDays(1).toString) } "return an error when the date range is greater than one year" in { val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(1).toString)), Some(Right(testTime.toString))) response.isLeft shouldBe true response.left.get shouldBe "DATE_RANGE_INVALID" } "return error when the from date query parameter is missing" in { val response = FinancialDataQueryParams.from(None, Some(Right("2019-03-31"))) response.isLeft shouldBe true response.left.get shouldBe "DATE_FROM_INVALID" } "return error when the from date query parameter is not a valid date" in { val response = FinancialDataQueryParams.from(Some(Right("ABC")), Some(Right("2019-03-31"))) response.isLeft shouldBe true response.left.get shouldBe "DATE_FROM_INVALID" } "return error when the from date query parameter is before mtd-date in Config" in { val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(11).toString)), Some(Right(testTime.minusYears(10).toString))) response.isLeft shouldBe true response.left.get shouldBe "DATE_FROM_INVALID" } "return error when the to date query parameter is missing" in { val response = FinancialDataQueryParams.from(Some(Right("2019-03-31")), None) response.isLeft shouldBe true response.left.get shouldBe "DATE_TO_INVALID" } "return error when the to date query parameter is not a valid date" in { val response = FinancialDataQueryParams.from(Some(Right("2019-03-31")), Some(Right("ABC"))) response.isLeft shouldBe true response.left.get shouldBe "DATE_TO_INVALID" } "return error when the to date query parameter is a future date" in { val futureDate = LocalDate.now().plusDays(1) val response = FinancialDataQueryParams.from(Some(Right("2019-03-31")), Some(Right(futureDate.toString("yyyy-MM-dd")))) response.isLeft shouldBe true response.left.get shouldBe "DATE_TO_INVALID" } s"return error when from date is after to date" in { val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(1).toString)), Some(Right(testTime.minusYears(1).minusDays(1).toString))) response.isLeft shouldBe true response.left.get shouldBe "DATE_RANGE_INVALID" } } }
Example 20
Source File: SemanticRepositorySpecs.scala From daf-semantics with Apache License 2.0 | 5 votes |
package specs import org.junit.runner.RunWith import scala.concurrent.{ Await, Future } import scala.concurrent.duration.Duration import play.api.test._ import play.api.http.Status import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.WSResponse import play.api.libs.ws.ahc.AhcWSClient import org.specs2.runner.JUnitRunner import org.specs2.mutable.Specification import play.api.libs.json.Json //import it.almawave.linkeddata.kb.utils.ConfigHelper import scala.collection.JavaConversions._ import scala.collection.JavaConverters._ import play.twirl.api.Content import play.api.test.Helpers._ import play.api.libs.json.JsObject import java.io.File import play.api.http.Writeable import akka.stream.scaladsl.Source import play.api.mvc.MultipartFormData import play.api.libs.Files.TemporaryFile import java.nio.file.Files import org.asynchttpclient.AsyncHttpClient import play.api.libs.ws.WS import akka.util.ByteString import play.api.mvc.MultipartFormData.DataPart import play.api.mvc.MultipartFormData.FilePart import akka.stream.scaladsl.FileIO import play.api.libs.ws.WSClient /* * TODO: REWRITE */ @RunWith(classOf[JUnitRunner]) class SemanticRepositorySpecs extends Specification { def application: Application = GuiceApplicationBuilder().build() "The semantic repository" should { "call kb/v1/contexts to obtain a list of contexts" in { new WithServer(app = application, port = 9999) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse]( client.url(s"http://localhost:${port}/kb/v1/contexts").execute, Duration.Inf) response.status must be equalTo Status.OK response.json.as[Seq[JsObject]].size must be equals 0 // response.json.as[Seq[JsObject]].size must be greaterThan 0 // if pre-loaded ontologies! } } } "call kb/v1/contexts ensuring all contexts have triples" in { new WithServer(app = application, port = 9999) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse]( client.url(s"http://localhost:${port}/kb/v1/contexts").execute, Duration.Inf) val json_list = response.json.as[Seq[JsObject]] forall(json_list)((_) must not beNull) forall(json_list)(_.keys must contain("context", "triples")) forall(json_list)(item => (item \ "triples").get.as[Int] > 0) } } } } }
Example 21
Source File: ServiceSpec.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
import java.io.{File, FileNotFoundException, IOException} import java.net.ServerSocket import java.util.Base64 import it.gov.daf.entitymanager.Entity import it.gov.daf.entitymanager.client.Entity_managerClient import org.specs2.mutable.Specification import org.specs2.specification.BeforeAfterAll import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.ahc.AhcWSClient import play.api.test.WithServer import scala.concurrent.Await import scala.concurrent.duration.Duration import scala.util.{Failure, Random, Try} @SuppressWarnings( Array( "org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw", "org.wartremover.warts.Var" ) ) class ServiceSpec extends Specification with BeforeAfterAll { def getAvailablePort: Int = { try { val socket = new ServerSocket(0) try { socket.getLocalPort } finally { socket.close() } } catch { case e: IOException => throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e) } } private def constructTempDir(dirPrefix: String): Try[File] = Try { val rndrange = 10000000 val file = new File(System.getProperty("java.io.tmpdir"), s"$dirPrefix${Random.nextInt(rndrange)}") if (!file.mkdirs()) throw new RuntimeException("could not create temp directory: " + file.getAbsolutePath) file.deleteOnExit() file } private def deleteDirectory(path: File): Boolean = { if (!path.exists()) { throw new FileNotFoundException(path.getAbsolutePath) } var ret = true if (path.isDirectory) path.listFiles().foreach(f => ret = ret && deleteDirectory(f)) ret && path.delete() } var tmpDir: Try[File] = Failure[File](new Exception("")) def application: Application = GuiceApplicationBuilder(). configure("pac4j.authenticator" -> "test"). configure("janusgraph.storage.directory" -> s"${tmpDir.map(_.getCanonicalPath).getOrElse("db")}/berkeleyje"). configure("janusgraph.index.search.directory" -> s"${tmpDir.map(_.getCanonicalPath).getOrElse("db")}/lucene"). build() "The entity_manager" should { "create an entity and retrieve it correctly" in new WithServer(app = application, port = getAvailablePort) { val ws: AhcWSClient = AhcWSClient() val plainCreds = "david:david" val plainCredsBytes = plainCreds.getBytes val base64CredsBytes = Base64.getEncoder.encode(plainCredsBytes) val base64Creds = new String(base64CredsBytes) val client = new Entity_managerClient(ws)(s"http://localhost:$port") val result = Await.result(client.createEntity(s"Basic $base64Creds", Entity("DAVID")), Duration.Inf) val entity = Await.result(client.getEntity(s"Basic $base64Creds", "DAVID"), Duration.Inf) entity must beEqualTo(Entity("DAVID")) } } override def beforeAll(): Unit = tmpDir = constructTempDir("test") override def afterAll(): Unit = tmpDir.foreach(deleteDirectory(_)) }
Example 22
Source File: ServiceSpec.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
import java.io.{IOException, File => JFile} import java.net.ServerSocket import java.util.Base64 import it.gov.daf.securitymanager.client.Security_managerClient import org.specs2.mutable.Specification import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.ahc.AhcWSClient import play.api.libs.ws.{WSAuthScheme, WSResponse} import play.api.test.{WithServer, WsTestClient} import scala.concurrent.Await import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.duration.Duration //@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw")) class ServiceSpec extends Specification { def getAvailablePort: Int = { try { val socket = new ServerSocket(0) try { socket.getLocalPort } finally { socket.close() } } catch { case e: IOException => throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e) } } def application: Application = GuiceApplicationBuilder(). configure("pac4j.authenticator" -> "test"). build() "The security_manager" should { "manage user tokens correctly" in new WithServer(app = application, port = getAvailablePort) { private val token = WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(s"http://localhost:$port/security-manager/v1/token"). withAuth("david", "david", WSAuthScheme.BASIC). execute, Duration.Inf) response.body } val ws: AhcWSClient = AhcWSClient() val plainCreds = "david:david" val plainCredsBytes = plainCreds.getBytes val base64CredsBytes = Base64.getEncoder.encode(plainCredsBytes) val base64Creds = new String(base64CredsBytes) val client = new Security_managerClient(ws)(s"http://localhost:$port") val token2 = Await.result(client.token(s"Basic $base64Creds"), Duration.Inf) s""""$token2"""" must be equalTo token Await.result(client.token(s"Bearer $token2").map(token => s""""$token""""), Duration.Inf) must be equalTo token } } }
Example 23
Source File: Iot_managerSpec.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
import java.io.{IOException, File => JFile} import java.net.ServerSocket import java.util.Base64 import better.files._ import it.gov.daf.iotmanager.client.Iot_managerClient import org.specs2.mutable.Specification import org.specs2.specification.BeforeAfterAll import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.ahc.AhcWSClient import play.api.libs.ws.{WSAuthScheme, WSResponse} import play.api.test.{WithServer, WsTestClient} import scala.concurrent.Await import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.Duration import scala.util.{Failure, Try} import org.apache.solr.client.solrj.embedded.JettyConfig import org.apache.solr.client.solrj.embedded.JettySolrRunner import org.eclipse.jetty.servlet.ServletHolder @SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw")) class Iot_managerSpec extends Specification with BeforeAfterAll { import Iot_managerSpec._ def getAvailablePort: Int = { try { val socket = new ServerSocket(0) try { socket.getLocalPort } finally { socket.close() } } catch { case e: IOException => throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e) } } def application: Application = GuiceApplicationBuilder(). configure("hadoop_conf_dir" -> s"${ServiceSpec.confPath.pathAsString}"). configure("pac4j.authenticator" -> "test"). build() "The security_manager" should { "manage user tokens correctly" in new WithServer(app = application, port = getAvailablePort) { print("ciao ciao") } } override def beforeAll(): Unit = { val solrXml = new Nothing("/solr/home/solr.xml") val solrHomeDir = solrXml.getParentFile val port = 8080 val context = "/solr" // use org.apache.solr.client.solrj.embedded.JettySolrRunner val jettySolr = new Nothing(solrHomeDir.getAbsolutePath, context, port) val waitUntilTheSolrWebAppHasStarted = true jettySolr.start(waitUntilTheSolrWebAppHasStarted) } override def afterAll(): Unit = { jettySolr.stop() } } @SuppressWarnings(Array("org.wartremover.warts.Var", "org.wartremover.warts.Null")) object Iot_managerSpec { }
Example 24
Source File: CatalogControllersSpec.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
import java.io.IOException import java.net.ServerSocket import akka.actor.ActorSystem import akka.stream.ActorMaterializer import catalog_manager.yaml.MetaCatalog import org.specs2.mutable.Specification import play.api.Application import play.api.http.Status import play.api.routing.Router import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.json.{JsArray, JsValue, Json} import play.api.libs.ws.WSResponse import play.api.libs.ws.ahc.AhcWSClient import play.api.test._ import it.gov.daf.catalogmanager import it.gov.daf.catalogmanager.client.Catalog_managerClient import scala.concurrent.duration.Duration import scala.concurrent.{Await, Future} class CatalogControllersSpec extends Specification { def application: Application = GuiceApplicationBuilder().build() import catalog_manager.yaml.BodyReads.MetaCatalogReads "The catalog-manager" should { "Call catalog-manager/v1/dataset-catalogs return ok status" in new WithServer(app = application, port = 9000) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(s"http://localhost:9001/catalog-manager/v1/dataset-catalogs"). execute, Duration.Inf) println(response.status) response.status must be equalTo Status.OK } } "Call catalog-manager/v1/dataset-catalogs return a non empty list if" + "you have error maybe is necessaty to add data to db" in new WithServer(app = application, port = 9000) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(s"http://localhost:9001/catalog-manager/v1/dataset-catalogs"). execute, Duration.Inf) println(response.status) println("ALE") println(response.body) val json: JsValue = Json.parse(response.body) json.as[JsArray].value.size must be greaterThan (0) } } "The catalog-manager" should { "Call catalog-manager/v1/dataset-catalogs/{logical_uri} return ok status" in new WithServer(app = application, port = 9000) { val logicalUri = "daf://dataset/std/standard/standard/uri_cultura/standard" val url = s"http://localhost:9001/catalog-manager/v1/dataset-catalogs/$logicalUri" println(url) WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(url). execute, Duration.Inf) println(response.status) response.status must be equalTo Status.OK } } } "The catalog-manager" should { "Call catalog-manager/v1/dataset-catalogs/{anything} return 401" in new WithServer(app = application, port = 9000) { val logicalUri = "anything" val url = s"http://localhost:9001/catalog-manager/v1/dataset-catalogs/$logicalUri" println(url) WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(url). execute, Duration.Inf) println(response.status) response.status must be equalTo 401 } } } } }
Example 25
Source File: ApplicationTestBase.scala From smui with Apache License 2.0 | 5 votes |
package models import models.rules._ import org.scalatest.{BeforeAndAfterAll, Suite} import play.api.{Application, Mode} import play.api.db.{Database, Databases} import play.api.inject.Injector import play.api.inject.guice.GuiceApplicationBuilder trait ApplicationTestBase extends BeforeAndAfterAll { self: Suite => protected lazy val db: Database = Databases.inMemory() // Use logging settings from logback-test.xml for test application System.setProperty("logger.resource", "logback-test.xml") protected lazy val application: Application = new GuiceApplicationBuilder(). in(Mode.Test). configure("db.default.url" -> db.url, "db.default.driver" -> "org.h2.Driver", "db.default.username" -> "", "db.default.password" -> "", "toggle.rule-deployment.log-rule-id" -> true). build() protected lazy val injector: Injector = application.injector protected lazy val repo: SearchManagementRepository = injector.instanceOf[SearchManagementRepository] protected val (core1Id, core2Id) = (SolrIndexId(), SolrIndexId()) protected def createTestCores(): Unit = { repo.addNewSolrIndex(SolrIndex(core1Id, "core1", "First core")) repo.addNewSolrIndex(SolrIndex(core2Id, "core2", "Second core")) } protected def createTestRule(): Seq[SearchInputId] = { val synonymRules = List (SynonymRule(SynonymRuleId(), 0, "mercury", isActive = true)) val upDownRules = List( UpDownRule(UpDownRuleId(), UpDownRule.TYPE_UP, 10, "notebook", isActive = true), UpDownRule(UpDownRuleId(), UpDownRule.TYPE_UP, 10, "lenovo", isActive = false), UpDownRule(UpDownRuleId(), UpDownRule.TYPE_DOWN, 10, "battery", isActive = true) ) val deleteRules = List(DeleteRule(DeleteRuleId(), "freddy", isActive = true)) val filterRules = List(FilterRule(FilterRuleId(), "zz top", isActive = true)) val id = repo.addNewSearchInput(core1Id, "aerosmith", Seq.empty) val searchInput = SearchInputWithRules(id, "aerosmith", synonymRules, upDownRules, filterRules, isActive = true, comment = "") repo.updateSearchInput(searchInput) val shippingId = repo.addNewSearchInput(core1Id, "shipping", Seq.empty) val redirectRule = RedirectRule(RedirectRuleId(), "http://xyz.com/shipping", isActive = true) val searchInputForRedirect = SearchInputWithRules(shippingId, "shipping", redirectRules = List(redirectRule), isActive = true, comment = "") repo.updateSearchInput(searchInputForRedirect) Seq(id, shippingId) } override protected def afterAll(): Unit = { application.stop() db.shutdown() } }
Example 26
Source File: IntegrationBaseSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package support import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import org.scalatestplus.play.guice.GuiceOneServerPerSuite import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.json.{JsValue, Json} import play.api.libs.ws.{WSClient, WSRequest, WSResponse} import play.api.{Application, Environment, Mode} trait IntegrationBaseSpec extends UnitSpec with WireMockHelper with GuiceOneServerPerSuite with BeforeAndAfterEach with BeforeAndAfterAll { val mockHost: String = WireMockHelper.host val mockPort: String = WireMockHelper.wireMockPort.toString lazy val client: WSClient = app.injector.instanceOf[WSClient] def servicesConfig: Map[String, Any] = Map( "microservice.services.des.host" -> mockHost, "microservice.services.des.port" -> mockPort, "microservice.services.auth.host" -> mockHost, "microservice.services.auth.port" -> mockPort, "auditing.consumer.baseUri.port" -> mockPort, "microservice.services.non-repudiation.host" -> mockHost, "microservice.services.non-repudiation.port" -> mockPort, "feature-switch.refactor.enabled" -> true, "feature-switch.refactor.prod.enabled" -> false, "microservice.services.non-repudiation.maxTimeout" -> 5000 ) override implicit lazy val app: Application = new GuiceApplicationBuilder() .in(Environment.simple(mode = Mode.Dev)) .configure(servicesConfig) .build() override def beforeAll(): Unit = { super.beforeAll() startWireMock() } override def afterAll(): Unit = { stopWireMock() super.afterAll() } def buildRequest(path: String): WSRequest = client.url(s"http://localhost:$port$path").withFollowRedirects(false) def document(response: WSResponse): JsValue = Json.parse(response.body) }
Example 27
Source File: BaseFunctionalSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.support import org.scalatestplus.play.guice.GuiceOneServerPerSuite import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.{WSClient, WSRequest} import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.vatapi.{TestApplication, VrnGenerator} import scala.collection.mutable trait BaseFunctionalSpec extends TestApplication with WireMockHelper with GuiceOneServerPerSuite{ protected val vrn: Vrn = VrnGenerator().nextVrn() implicit val urlPathVariables: mutable.Map[String, String] = mutable.Map() lazy val client: WSClient = app.injector.instanceOf[WSClient] override lazy val app: Application = new GuiceApplicationBuilder().configure(Map( "auditing.consumer.baseUri.host" -> "localhost", "auditing.consumer.baseUri.port" -> 22222, "microservice.services.des.host" -> mockHost, "microservice.services.des.port" -> mockPort, "microservice.services.auth.host" -> mockHost, "microservice.services.auth.port" -> mockPort, "auditing.consumer.baseUri.port" -> mockPort, "access-keys.xApiKey" -> "dummy-api-key", "microservice.services.non-repudiation.host" -> mockHost, "microservice.services.non-repudiation.port" -> mockPort, "feature-switch.refactor.enabled" -> false, "feature-switch.refactor.prod.enabled" -> false )).build() def when() = new HttpVerbs()(urlPathVariables, timeout) def given() = new Givens(when()) def buildRequest(path: String): WSRequest = client.url(s"http://localhost:$port$path").withFollowRedirects(false) }
Example 28
Source File: TestingHttpApi.scala From daf-semantics with Apache License 2.0 | 5 votes |
package it.almawave.linkeddata.kb.http import play.api.inject.guice.GuiceApplicationBuilder import org.junit.Test import org.junit.After import play.api.Application import org.junit.Before import it.almawave.linkeddata.kb.utils.JSONHelper import play.api.libs.ws.WSClient import org.asynchttpclient.DefaultAsyncHttpClient import play.api.libs.ws.ssl.SystemConfiguration import akka.stream.ActorMaterializer import play.api.libs.ws.ahc.AhcWSClient import scala.concurrent.Await import scala.concurrent.duration.Duration import java.net.URL import com.typesafe.config.ConfigFactory class TestingHttpApi { var app: Application = null var conf = ConfigFactory.empty() var ws: WSClient = null var app_url = new URL("http://localhost:8080") @Test def testing_contexts() { // curl -X GET http://localhost:8999/kb/v1/prefixes/lookup?prefix=no_pref // -H "accept: application/json" // -H "content-type: application/json" val fut = ws.url(s"http://localhost:8999/kb/v1/prefixes/lookup") .withHeaders(("accept", "application/json")) .withHeaders(("content-type", "application/json")) .withFollowRedirects(true) .withQueryString(("prefix", "muapit")) .get() val results = Await.result(fut, Duration.Inf) println(results.body) } @Before def before() { app = GuiceApplicationBuilder() .build() conf = app.configuration.underlying // play.app.local.url // play.server.http.address // play.server.http.port println(JSONHelper.writeToString(conf.root().unwrapped())) app_url = new URL(conf.getString("app.local.url")) println(s"\n\nrunning at ${app_url}") val materializer = ActorMaterializer()(app.actorSystem) ws = AhcWSClient()(materializer) } @After def after() { ws.close() app.stop() } }
Example 29
Source File: ViewHelpersSpec.scala From dr-cla with BSD 3-Clause "New" or "Revised" License | 5 votes |
package helpers import org.scalatest.Matchers._ import org.scalatestplus.play.PlaySpec import org.scalatestplus.play.guice.GuiceOneAppPerTest import play.api.Mode import play.api.inject.guice.GuiceApplicationBuilder class ViewHelpersSpec extends PlaySpec with GuiceOneAppPerTest { val testOrgName = "Test Org Name" val testOrgUrl = "http://orgurl.org" val testOrgLogoUrl = "image.jpg" override implicit def fakeApplication() = new GuiceApplicationBuilder() .configure( Map( "app.organization.name" -> testOrgName, "app.organization.url" -> testOrgUrl, "app.organization.logo-url"-> testOrgLogoUrl ) ) .in(Mode.Test) .build() def viewHelper = app.injector.instanceOf[ViewHelpers] "ViewHelper" must { "give a valid organization name" in { val orgName = viewHelper.organizationName orgName mustBe a [String] orgName mustEqual testOrgName } "give a valid organization URL" in { val orgUrl = viewHelper.maybeOrganizationUrl orgUrl shouldBe defined orgUrl should contain (testOrgUrl) } "give a valid organization logo URL" in { val orgLogoUrl = viewHelper.maybeOrganizationLogoUrl orgLogoUrl shouldBe defined orgLogoUrl should contain (testOrgLogoUrl) } // todo: test loading the sample CLA in dev mode } }
Example 30
Source File: FiltersSpec.scala From dr-cla with BSD 3-Clause "New" or "Revised" License | 5 votes |
package utils import modules.{Database, DatabaseMock} import org.scalatestplus.play.PlaySpec import org.scalatestplus.play.guice.GuiceOneAppPerTest import play.api.Mode import play.api.http.HeaderNames import play.api.inject._ import play.api.inject.guice.GuiceApplicationBuilder import play.api.mvc._ import play.api.test.Helpers._ import play.api.test._ class FiltersSpec extends PlaySpec with GuiceOneAppPerTest { lazy val appBuilder = new GuiceApplicationBuilder() .overrides(bind[Database].to[DatabaseMock]) .configure("play.modules.disabled" -> Seq("org.flywaydb.play.PlayModule", "modules.DatabaseModule")) .in(Mode.Test) override def fakeApplication() = appBuilder.build() "Filters" must { "redirect to https if the request was forwarded and not https" in { val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.signedCla(None).url, Headers(HeaderNames.X_FORWARDED_PROTO -> "http"), AnyContentAsEmpty)) status(result) mustEqual MOVED_PERMANENTLY } "not force https for well-known requests" in { val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.wellKnown("test").url)) status(result) mustEqual NOT_FOUND } "not force https for non-forwarded requests" in { val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.signedCla(None).url)) status(result) mustEqual OK } "keep https for non-well-known requests" in { val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.signedCla(None).url, Headers(HeaderNames.X_FORWARDED_PROTO -> "https"), AnyContentAsEmpty)) status(result) mustEqual OK } "return the well known value when the WELL_KNOWN env var is set" in { implicit val app = appBuilder.configure("wellknown" -> "foo=bar").build() val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.wellKnown("foo").url)) status(result) mustEqual OK contentAsString(result) mustEqual "bar" } "not leak well known values" in { implicit val app = appBuilder.configure("wellknown" -> "foo=bar").build() val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.wellKnown("").url)) status(result) mustEqual NOT_FOUND } } }
Example 31
Source File: CryptoSpec.scala From dr-cla with BSD 3-Clause "New" or "Revised" License | 5 votes |
package utils import modules.{Database, DatabaseMock} import org.scalatestplus.play.PlaySpec import org.scalatestplus.play.guice.GuiceOneAppPerTest import play.api.Mode import play.api.inject._ import play.api.inject.guice.GuiceApplicationBuilder class CryptoSpec extends PlaySpec with GuiceOneAppPerTest { override implicit def fakeApplication() = new GuiceApplicationBuilder() .overrides(bind[Database].to[DatabaseMock]) .configure( Map( "play.modules.disabled" -> Seq("org.flywaydb.play.PlayModule", "modules.DatabaseModule") ) ) .in(Mode.Test) .build() lazy val crypto = new Crypto(app.configuration) "encryptAES and decryptAES" must { "work" in { val encrypted = crypto.encryptAES("hello, world") encrypted.length must equal (24) crypto.decryptAES(encrypted) must equal ("hello, world") } } }
Example 32
Source File: DBSpec.scala From dr-cla with BSD 3-Clause "New" or "Revised" License | 5 votes |
package utils import java.time.LocalDateTime import models.{ClaSignature, Contact} import modules.Database import org.flywaydb.play.PlayInitializer import org.scalatestplus.play.PlaySpec import org.scalatestplus.play.guice.GuiceOneAppPerSuite import play.api.inject.guice.GuiceApplicationBuilder import play.api.test.Helpers._ import scala.concurrent.ExecutionContext.Implicits.global import scala.util.Try class DBSpec extends PlaySpec with GuiceOneAppPerSuite { val dbUrl = sys.env.getOrElse("DATABASE_URL", "postgres://salesforcecla:password@localhost:5432/salesforcecla-test") val testConfig = Map("db.default.url" -> dbUrl) implicit override def fakeApplication() = new GuiceApplicationBuilder().configure(testConfig).build() lazy val database = app.injector.instanceOf[Database] lazy val db = app.injector.instanceOf[DB] lazy val playIntializer = app.injector.instanceOf[PlayInitializer] Try(await(database.ctx.executeQuery("drop schema salesforce cascade"))) Try(await(database.ctx.executeQuery("drop table schema_version"))) playIntializer.onStart() "Contact" must { "be creatable" in { val contact = await(db.createContact(Contact(-1, Some("foo"), "bar", "[email protected]", "foobar"))) contact.id must not equal -1 } "be creatable with null firstname" in { val contact = await(db.createContact(Contact(-1, None, "blah", "[email protected]", "blah"))) contact.id must not equal -1 } "be able to get one that exists by the gitHubId" in { val contact = await(db.findContactByGitHubId("foobar")) contact mustBe 'defined } "fail to get one that doesn't exist by a gitHubId" in { val contact = await(db.findContactByGitHubId("asdf")) contact mustBe None } "work with null firstname" in { val contact = await(db.findContactByGitHubId("blah")) contact mustBe 'defined contact.get.firstName mustBe empty } } "ClaSignature" must { "be creatable" in { val contact = Contact(-1, Some("foo"), "bar", "[email protected]", "foobar") val claSignature = await(db.createClaSignature(ClaSignature(-1, contact.gitHubId, LocalDateTime.now(), "0.0.0"))) claSignature.id must not equal -1 } "be queryable with one github id" in { val claSignatures = await(db.findClaSignaturesByGitHubIds(Set(GitHub.User("foobar")))) claSignatures.size mustEqual 1 claSignatures.head.contactGitHubId mustEqual "foobar" } "be queryable with a set of github ids" in { val claSignatures = await(db.findClaSignaturesByGitHubIds(Set(GitHub.User("foobar"), GitHub.User("jondoe")))) claSignatures.size mustEqual 1 claSignatures.head.contactGitHubId mustEqual "foobar" } } "Contact.fullNameToFirstAndLast" must { "work with no names" in { Contact.fullNameToFirstAndLast("") must equal (None, None) } "work with one name" in { Contact.fullNameToFirstAndLast("Foo") must equal (None, Some("Foo")) } "work with two names" in { Contact.fullNameToFirstAndLast("Foo Bar") must equal (Some("Foo"), Some("Bar")) } "work with three names" in { Contact.fullNameToFirstAndLast("Foo Baz Bar") must equal (Some("Foo Baz"), Some("Bar")) } } }
Example 33
Source File: ApplicationSpec.scala From dr-cla with BSD 3-Clause "New" or "Revised" License | 5 votes |
package controllers import modules.{Database, DatabaseMock} import org.scalatestplus.play.PlaySpec import org.scalatestplus.play.guice.GuiceOneAppPerTest import play.api.Mode import play.api.inject._ import play.api.inject.guice.GuiceApplicationBuilder import scala.xml.Comment class ApplicationSpec extends PlaySpec with GuiceOneAppPerTest { override implicit def fakeApplication() = new GuiceApplicationBuilder() .overrides(bind[Database].to[DatabaseMock]) .configure( Map( "play.modules.disabled" -> Seq("org.flywaydb.play.PlayModule", "modules.DatabaseModule") ) ) .in(Mode.Test) .build() lazy val applicationController = app.injector.instanceOf[Application] "svgNode" must { "work" in { val svg = applicationController.svgSymbol("custom-sprite/svg/symbols.svg", "custom16") svg.attribute("d") mustBe 'defined } "produce a comment when the file can't be found" in { val svg = applicationController.svgSymbol("asdfasdf", "custom16") svg mustBe a [Comment] } "produce a comment when the symbol can't be found" in { val svg = applicationController.svgSymbol("custom-sprite/svg/symbols.svg", "asdf") svg mustBe a [Comment] } } }
Example 34
Source File: ThingsControllerSpec.scala From swagger-check with MIT License | 5 votes |
package controllers import java.util.UUID import dal.ThingsRepository import de.leanovate.swaggercheck.playhelper._ import de.leanovate.swaggercheck.schema.model.ValidationSuccess import models.{Thing, ThingType} import org.scalacheck.{Arbitrary, Gen} import org.specs2.ScalaCheck import org.specs2.mock.Mockito import play.api.Application import play.api.inject.bind import play.api.inject.guice.GuiceApplicationBuilder import play.api.test._ import support.{Arbitraries, ThingApi} import scala.concurrent.Future class ThingsControllerSpec extends PlaySpecification with ScalaCheck with ThingApi with Mockito with Arbitraries{ "ThingController" should { "support all /things routes" in { implicit val arbitraryRequest = Arbitrary[PlayOperationVerifier](swaggerCheck.operationVerifier()) val app = testApp() prop { requestVerifier: PlayOperationVerifier => val Some(result) = route(app, requestVerifier.request) status(result) must between(200, 300) requestVerifier.responseVerifier.verify(result) must be equalTo ValidationSuccess } } } def testApp(): Application = { val mockThingsRepository = mock[ThingsRepository] mockThingsRepository.getPage(any[Option[ThingType.Value]], any[Int], any[Int]) answers { _ => Future.successful(Gen.nonEmptyListOf(Arbitrary.arbitrary[Thing]).sample.getOrElse(Seq.empty)) } mockThingsRepository.getById(any[UUID]) answers { _ => Future.successful(Arbitrary.arbitrary[Thing].sample)} new GuiceApplicationBuilder() .overrides(bind[ThingsRepository].toInstance(mockThingsRepository)) .build() } }
Example 35
Source File: PlayAPISpec.scala From playsonify with MIT License | 5 votes |
package com.alexitc.playsonify.test import java.net.URLEncoder import org.scalatest.concurrent.ScalaFutures import org.scalatestplus.play.PlaySpec import play.api.inject.guice.GuiceApplicationBuilder import play.api.mvc.Result import play.api.test.FakeRequest import play.api.test.Helpers._ import play.api.{Application, Mode} import scala.concurrent.Future def GET(url: String, extraHeaders: (String, String)*): Future[Result] = { val headers = JsonHeader :: extraHeaders.toList val request = FakeRequest("GET", url) .withHeaders(headers: _*) val response = route(application, request).get log(request, response) response } def POST(url: String, extraHeaders: (String, String)*): Future[Result] = { POST(url, None, extraHeaders: _*) } def POST(url: String, jsonBody: Option[String], extraHeaders: (String, String)*): Future[Result] = { val headers = JsonHeader :: extraHeaders.toList val json = jsonBody.getOrElse(EmptyJson) val request = FakeRequest("POST", url) .withHeaders(headers: _*) .withBody(json) val response = route(application, request).get log(request, response) response } def PUT(url: String, extraHeaders: (String, String)*): Future[Result] = { PUT(url, None, extraHeaders: _*) } def PUT(url: String, jsonBody: Option[String], extraHeaders: (String, String)*): Future[Result] = { val headers = JsonHeader :: extraHeaders.toList val json = jsonBody.getOrElse(EmptyJson) val request = FakeRequest("PUT", url) .withHeaders(headers: _*) .withBody(json) val response = route(application, request).get log(request, response) response } def DELETE(url: String, extraHeaders: (String, String)*): Future[Result] = { val headers = JsonHeader :: extraHeaders.toList val request = FakeRequest("DELETE", url) .withHeaders(headers: _*) val response = route(application, request).get log(request, response) response } } object PlayAPISpec { object Implicits { implicit class HttpExt(val params: List[(String, String)]) extends AnyVal { def toQueryString: String = { params .map { case (key, value) => val encodedKey = URLEncoder.encode(key, "UTF-8") val encodedValue = URLEncoder.encode(value, "UTF-8") List(encodedKey, encodedValue).mkString("=") } .mkString("&") } } implicit class StringUrlExt(val url: String) extends AnyVal { def withQueryParams(params: (String, String)*): String = { List(url, params.toList.toQueryString).mkString("?") } } } }
Example 36
Source File: SecurityFilterSpec.scala From play-zhewbacca with MIT License | 5 votes |
package org.zalando.zhewbacca import javax.inject.{Inject, Provider} import play.api.inject._ import play.api.inject.guice.GuiceApplicationBuilder import play.api.mvc.Results._ import play.api.mvc._ import play.api.routing.Router import play.api.test.{FakeRequest, PlaySpecification} import play.api.{Application, Mode} class SecurityFilterSpec extends PlaySpecification with BodyParsers { val testTokenInfo = TokenInfo("", Scope.Empty, "token type", "user uid", realm = "/employees") def appWithRoutes: Application = new GuiceApplicationBuilder() .in(Mode.Test) .bindings(bind[AuthProvider] to new AlwaysPassAuthProvider(testTokenInfo)) .overrides( bind[Router].toProvider[SecurityFilterTestRouterProvider]) .configure( "play.http.filters" -> "org.zalando.zhewbacca.TestingFilters", "authorisation.rules.file" -> "security_filter.conf") .build "SecurityFilter" should { "allow protected inner action to access token info" in { val response = route(appWithRoutes, FakeRequest(GET, "/")).get status(response) must beEqualTo(OK) contentAsString(response) must beEqualTo(testTokenInfo.tokenType) } "deny an access when there is no security rule for the reguest is given" in { val response = route(appWithRoutes, FakeRequest(GET, "/unprotected-by-mistake")).get status(response) must beEqualTo(FORBIDDEN) } } } class SecurityFilterTestRouterProvider @Inject() (components: ControllerComponents) extends Provider[Router] { import components.{actionBuilder => Action} import play.api.routing.sird._ override def get(): Router = Router.from { // test action returning action type. Shows the usage and makes it possible to test basic behaviour // security rules described in 'security_filter.conf' file case GET(p"/") => Action { request => import TokenInfoConverter._ Ok(request.tokenInfo.tokenType) } case GET(p"/unprotected") => Action { Ok } } }