play.api.test.FakeRequest Scala Examples

The following examples show how to use play.api.test.FakeRequest. 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: PersonalDetailsControllerSpec.scala    From pertax-frontend   with Apache License 2.0 6 votes vote down vote up
package controllers.address

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithActiveTabAction}
import controllers.controllershelpers.{AddressJourneyCachingHelper, PersonalDetailsCardGenerator}
import models.AddressJourneyTTLModel
import models.dto.AddressPageVisitedDto
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.{times, verify, when}
import org.mockito.Matchers.{eq => meq, _}
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status.OK
import play.api.libs.json.Json
import play.api.mvc.{MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import repositories.EditAddressLockRepository
import services.{LocalSessionCache, NinoDisplayService}
import uk.gov.hmrc.http.cache.client.CacheMap
import uk.gov.hmrc.play.audit.http.connector.{AuditConnector, AuditResult}
import uk.gov.hmrc.play.audit.model.DataEvent
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec, Fixtures, LocalPartialRetriever}
import views.html.interstitial.DisplayAddressInterstitialView
import views.html.personaldetails.{AddressAlreadyUpdatedView, CannotUseServiceView, PersonalDetailsView}

import scala.concurrent.{ExecutionContext, Future}

class PersonalDetailsControllerSpec extends AddressBaseSpec {

  val ninoDisplayService = mock[NinoDisplayService]

  trait LocalSetup extends AddressControllerSetup {

    when(ninoDisplayService.getNino(any(), any())).thenReturn {
      Future.successful(Some(Fixtures.fakeNino))
    }

    def currentRequest[A]: Request[A] = FakeRequest().asInstanceOf[Request[A]]

    def controller =
      new PersonalDetailsController(
        injected[PersonalDetailsCardGenerator],
        mockEditAddressLockRepository,
        ninoDisplayService,
        mockAuthJourney,
        addressJourneyCachingHelper,
        withActiveTabAction,
        mockAuditConnector,
        cc,
        displayAddressInterstitialView,
        injected[PersonalDetailsView]
      ) {}

    "Calling AddressController.onPageLoad" should {

      "call citizenDetailsService.fakePersonDetails and return 200" in new LocalSetup {
        override def sessionCacheResponse: Option[CacheMap] =
          Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true)))))

        val result = controller.onPageLoad()(FakeRequest())

        status(result) shouldBe OK
        verify(mockLocalSessionCache, times(1))
          .cache(meq("addressPageVisitedDto"), meq(AddressPageVisitedDto(true)))(any(), any(), any())
        verify(mockEditAddressLockRepository, times(1)).get(any())
      }

      "send an audit event when user arrives on personal details page" in new LocalSetup {
        override def sessionCacheResponse: Option[CacheMap] =
          Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true)))))

        val result = controller.onPageLoad()(FakeRequest())
        val eventCaptor = ArgumentCaptor.forClass(classOf[DataEvent])

        status(result) shouldBe OK
        verify(mockAuditConnector, times(1)).sendEvent(eventCaptor.capture())(any(), any())
      }
    }
  }
} 
Example 2
Source File: PropertyEopsDeclarationResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockPropertyEopsDeclarationService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

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

class PropertyEopsDeclarationResourceSpec extends ResourceSpec
  with MockPropertyEopsDeclarationService {

  class Setup {
    val resource = new PropertyEopsDeclarationResource(
      service = mockPropertyEopsDeclarationService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  val request = FakeRequest()

  "post" should {
    "return a 204 with the response headers" when {
      "the service returns a HttpResponse containing a 204 with no json response body" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(NO_CONTENT, None, testHeaderResponse))))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NO_CONTENT
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 3
Source File: MessagesSupport.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play

import play.api.http.HttpConfiguration
import play.api.{Configuration, Environment}
import play.api.i18n._
import play.api.mvc.MessagesRequest
import play.api.test.FakeRequest

trait MessagesSupport {

  implicit lazy val messagesApi: MessagesApi = {

    val environment = Environment.simple()

    val configuration = Configuration.load(environment)

    val langs = new DefaultLangs()

    new DefaultMessagesApiProvider(
      environment       = environment,
      config            = configuration,
      langs             = langs,
      httpConfiguration = new HttpConfiguration()
    ).get
  }

  implicit val messages: Messages = new MessagesRequest(FakeRequest(), messagesApi).messages
} 
Example 4
Source File: CSRFSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.helpers

import org.scalatest.WordSpec
import org.scalatestplus.play.OneAppPerTest
import play.api.Application
import play.api.mvc.RequestHeader
import play.api.test.FakeRequest
import play.filters.csrf.CSRF.Token
import play.filters.csrf.{CSRFConfigProvider, CSRFFilter}

trait CSRFSpec extends WordSpec with OneAppPerTest {
  implicit class RichFakeRequest[T](fakeRequest: FakeRequest[T])(implicit app: Application) {
    def withCSRFToken: RequestHeader = {
      val csrfConfig = app.injector.instanceOf[CSRFConfigProvider].get
      val csrfFilter = app.injector.instanceOf[CSRFFilter]
      val token      = csrfFilter.tokenProvider.generateToken

      fakeRequest
        .copyFakeRequest(
          tags =
            fakeRequest.tags ++
              Map(
                Token.NameRequestTag -> csrfConfig.tokenName,
                Token.RequestTag     -> token
              ))
    }
  }

  implicit lazy val request = FakeRequest().withCSRFToken
} 
Example 5
Source File: TaxCalcServiceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import mocks.connectors.{MockSelfAssessmentConnector, MockTaxCalcConnector}
import play.api.test.FakeRequest
import router.errors.{IncorrectAPIVersion, UnsupportedAPIVersion}
import support.UnitSpec
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.Future

class TaxCalcServiceSpec extends UnitSpec
  with MockSelfAssessmentConnector with MockTaxCalcConnector {

  class Setup {

    object service extends TaxCalcService(
      mockTaxCalcConnector
    )
  }

  implicit val request = FakeRequest()

  "get" should {
    "return a HttpResponse" when {
      "the request contains a version 2.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.2.0+json"))
        val response = HttpResponse(200)

        MockTaxCalcConnector.get("/2.0" + request.uri)
          .returns(Future.successful(Right(response)))

        val result = await(service.get())
        result shouldBe Right(response)
      }
    }

    "return an UnsupportedAPIVersion error" when {
      "the Accept header contains an unsupported API version" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.5.0+json"))

        val result = await(service.get())
        result shouldBe Left(UnsupportedAPIVersion)
      }

      "the request contains a version 1.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.1.0+json"))

        val result = await(service.get())
        result shouldBe Left(UnsupportedAPIVersion)
      }
    }

    "return an IncorrectAPIVersion" when {
      "the Accept header contains an incorrect value" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "incorrect value"))

        val result = await(service.get())
        result shouldBe Left(IncorrectAPIVersion)
      }
    }
  }
} 
Example 6
Source File: PropertyEopsObligationsServiceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import mocks.connectors.MockPropertyConnector
import play.api.test.FakeRequest
import router.errors.{IncorrectAPIVersion, UnsupportedAPIVersion}
import support.UnitSpec
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.Future

class PropertyEopsObligationsServiceSpec extends UnitSpec
  with MockPropertyConnector {

  class Setup {

    object service extends PropertyEopsObligationsService(
      mockPropertyConnector
    )
  }

  implicit val request = FakeRequest()

  "get" should {
    "return a HttpResponse" when {
      "the request contains a version 2.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.2.0+json"))
        val response = HttpResponse(200)

        MockPropertyConnector.get("/2.0"+request.uri)
          .returns(Future.successful(Right(response)))

        val result = await(service.get())
        result shouldBe Right(response)
      }
    }

    "return an UnsupportedAPIVersion error" when {

      "the request contains a version 1.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.1.0+json"))

        val result = await(service.get())
        result shouldBe Left(UnsupportedAPIVersion)
      }

      "the Accept header contains an unsupported API version" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.5.0+json"))

        val result = await(service.get())
        result shouldBe Left(UnsupportedAPIVersion)
      }
    }

    "return an IncorrectAPIVersion" when {

      "the Accept header contains an incorrect value" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "incorrect value"))

        val result = await(service.get())
        result shouldBe Left(IncorrectAPIVersion)
      }
    }
  }
} 
Example 7
Source File: SelfEmploymentEopsDeclarationServiceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import mocks.connectors.{MockSelfAssessmentConnector, MockSelfEmploymentConnector}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import router.errors.{IncorrectAPIVersion, UnsupportedAPIVersion}
import support.UnitSpec
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.Future

class SelfEmploymentEopsDeclarationServiceSpec extends UnitSpec
  with MockSelfEmploymentConnector with MockSelfAssessmentConnector {

  class Setup {

    object service extends SelfEmploymentEopsDeclarationService(
      mockSelfEmploymentConnector
    )
  }

  implicit val request = FakeRequest()

  "post" should {
    val requestBody = Json.obj("test" -> "body")

    "return a HttpResponse" when {
      "the request contains a version 2.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.2.0+json"))
        val response = HttpResponse(200)

        MockSelfEmploymentConnector.post("/2.0"+request.uri, requestBody)
          .returns(Future.successful(Right(response)))

        val result = await(service.post(requestBody))
        result shouldBe Right(response)
      }
    }

    "return an UnsupportedAPIVersion error" when {
      "the Accept header contains an unsupported API version" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.5.0+json"))

        val result = await(service.post(requestBody))
        result shouldBe Left(UnsupportedAPIVersion)
      }

      "the request contains a version 1.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.1.0+json"))

        val result = await(service.post(requestBody))
        result shouldBe Left(UnsupportedAPIVersion)
      }
    }

    "return an IncorrectAPIVersion" when {
      "the Accept header contains an incorrect value" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "incorrect value"))

        val result = await(service.post(requestBody))
        result shouldBe Left(IncorrectAPIVersion)
      }
    }
  }
} 
Example 8
Source File: PropertyEopsDeclarationServiceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import mocks.connectors.{MockPropertyConnector, MockSelfAssessmentConnector}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import router.errors.{IncorrectAPIVersion, UnsupportedAPIVersion}
import support.UnitSpec
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.Future

class PropertyEopsDeclarationServiceSpec extends UnitSpec
  with MockPropertyConnector with MockSelfAssessmentConnector {

  class Setup {

    object service extends PropertyEopsDeclarationService(
      mockPropertyConnector
    )
  }

  implicit val request = FakeRequest()

  "post" should {
    val requestBody = Json.obj("test" -> "body")

    "return a HttpResponse" when {
      "the request contains a version 2.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.2.0+json"))
        val response = HttpResponse(200)

        MockPropertyConnector.post("/2.0"+request.uri, requestBody)
          .returns(Future.successful(Right(response)))

        val result = await(service.post(requestBody))
        result shouldBe Right(response)
      }
    }

    "return an UnsupportedAPIVersion error" when {
      "the Accept header contains an unsupported API version" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.5.0+json"))

        val result = await(service.post(requestBody))
        result shouldBe Left(UnsupportedAPIVersion)
      }

      "the request contains a version 1.0 header" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "application/vnd.hmrc.1.0+json"))

        val result = await(service.post(requestBody))
        result shouldBe Left(UnsupportedAPIVersion)
      }
    }

    "return an IncorrectAPIVersion" when {

      "the Accept header contains an incorrect value" in new Setup {
        implicit val hc = HeaderCarrier(extraHeaders = Seq(ACCEPT -> "incorrect value"))

        val result = await(service.post(requestBody))
        result shouldBe Left(IncorrectAPIVersion)
      }
    }
  }
} 
Example 9
Source File: PropertyEopsObligationsResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockTaxCalcService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

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

class PropertyEopsObligationsResourceSpec extends ResourceSpec
  with MockTaxCalcService {

  class Setup {
    val resource = new TaxCalcResource(
      service = mockTaxCalcService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  "get" should {
    "return a 200 with the response headers" when {
      "the service returns a HttpResponse containing a 200 with no json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, None, testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 10
Source File: TaxCalcResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockTaxCalcService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

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

class TaxCalcResourceSpec extends ResourceSpec
  with MockTaxCalcService {

  class Setup {
    val resource = new TaxCalcResource(
      service = mockTaxCalcService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  "get" should {
    "return a 200 with the response headers" when {
      "the service returns a HttpResponse containing a 200 with no json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, None, testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 11
Source File: FormWithCSRFSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views
package helpers
import uk.gov.hmrc.play.MessagesSupport
import play.twirl.api.Html
import play.api.test.Helpers._
import org.scalatest.{Matchers, WordSpec}
import play.api.mvc.Call
import play.api.test.FakeRequest
import play.twirl.api.HtmlFormat
import uk.gov.hmrc.play.views.html.helpers.form

class FormWithCSRFSpec extends WordSpec with Matchers with MessagesSupport with CSRFSpec {

  "@helpers.formWithCSRF" should {
    val simpleCall = Call(method = "POST", url = "/the-post-url")

    "render with the correct action attribute" in {
      val formElement =
        jsoupDocument(form(action = simpleCall)(HtmlFormat.empty))
          .select("form")

      formElement.attr("action") shouldBe "/the-post-url"
    }

    "render with the correct action including a fragment" in {
      val formElement =
        jsoupDocument(form(action = simpleCall.withFragment("tab"))(HtmlFormat.empty))
          .select("form")

      formElement.attr("action") shouldBe "/the-post-url#tab"
    }

    "render with the correct method" in {
      val getCall = Call(method = "GET", url = "/the-post-url")

      val formElement =
        jsoupDocument(form(action = getCall)(HtmlFormat.empty))
          .select("form")

      formElement.attr("method") shouldBe "GET"
    }

    "render the passed attributes" in {
      val formElement =
        jsoupDocument(form(action = simpleCall, 'attribute1 -> "value1")(HtmlFormat.empty))
          .select("form")

      formElement.attr("attribute1") shouldBe "value1"
    }

    "render multiple attributes" in {
      val formElement =
        jsoupDocument(form(action = simpleCall, 'attribute1 -> "value1", 'attribute2 -> "value2")(HtmlFormat.empty))
          .select("form")

      formElement.attr("attribute1") shouldBe "value1"
      formElement.attr("attribute2") shouldBe "value2"
    }

    "render the contents of the form" in {
      val content = Html("<p>Content</p>")
      val formElement =
        jsoupDocument(form(action = simpleCall)(content))
          .select("p")

      formElement.outerHtml shouldBe "<p>Content</p>"
    }

    "not render the CSRF token if the request does not contain the token" in {
      implicit val request = FakeRequest()
      val formElement =
        jsoupDocument(form(action = simpleCall)(HtmlFormat.empty))

      val input = formElement.select("input")
      input.size shouldBe 0
    }

    "render the CSRF token" in {
      val formElement =
        jsoupDocument(form(action = simpleCall)(HtmlFormat.empty))

      val input = formElement.select("input")
      input.size shouldBe 1

      input.attr("type")         shouldBe "hidden"
      input.attr("name")         shouldBe "csrfToken"
      input.attr("value").length should be > 0
    }
  }
} 
Example 12
Source File: SelfEmploymentEopsDeclarationResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockSelfEmploymentEopsDeclarationService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

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

class SelfEmploymentEopsDeclarationResourceSpec extends ResourceSpec
  with MockSelfEmploymentEopsDeclarationService {

  class Setup {
    val resource = new SelfEmploymentEopsDeclarationResource(
      service = mockSelfEmploymentEopsDeclarationService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  val request = FakeRequest()

  "post" should {
    "return a 204 with the response headers" when {
      "the service returns a HttpResponse containing a 204 with no json response body" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(NO_CONTENT, None, testHeaderResponse))))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NO_CONTENT
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 13
Source File: AdditionalRoutersSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.it.routers

import akka.NotUsed
import com.lightbend.lagom.scaladsl.api.ServiceLocator
import com.lightbend.lagom.scaladsl.server.LagomApplication
import com.lightbend.lagom.scaladsl.server.LagomApplicationContext
import com.lightbend.lagom.scaladsl.server.LagomServer
import com.lightbend.lagom.scaladsl.server.LocalServiceLocator
import com.lightbend.lagom.scaladsl.testkit.ServiceTest
import com.lightbend.lagom.scaladsl.testkit.ServiceTest.TestServer
import org.scalatest.concurrent.ScalaFutures
import play.api.http.DefaultWriteables
import play.api.http.HeaderNames
import play.api.libs.ws.WSClient
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.mvc
import play.api.mvc._
import play.api.routing.SimpleRouterImpl
import play.api.test.FakeHeaders
import play.api.test.FakeRequest
import play.api.test.Helpers
import play.core.j.JavaRouterAdapter
import play.api.test.Helpers._

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

class AdditionalRoutersSpec extends AnyWordSpec with Matchers with ScalaFutures {
  "A LagomServer " should {
    "be extensible with a Play Router" in withServer { server =>
      val request = FakeRequest(GET, "/hello/")
      val result  = Helpers.route(server.application.application, request).get.futureValue

      result.header.status shouldBe OK
      val body = result.body.consumeData(server.materializer).futureValue.utf8String
      body shouldBe "hello"
    }
  }

  def withServer(block: TestServer[TestApp] => Unit): Unit = {
    ServiceTest.withServer(ServiceTest.defaultSetup.withCassandra(false).withCluster(false)) { ctx =>
      new TestApp(ctx)
    } { server =>
      block(server)
    }
  }

  class TestApp(context: LagomApplicationContext)
      extends LagomApplication(context)
      with AhcWSComponents
      with LocalServiceLocator {
    override def lagomServer: LagomServer =
      serverFor[AdditionalRoutersService](new AdditionalRoutersServiceImpl)
        .additionalRouter(FixedResponseRouter("hello").withPrefix("/hello"))
  }
}


object FixedResponseRouter {
  def apply(msg: String) =
    new SimpleRouterImpl({
      case _ =>
        new Action[Unit] {
          override def parser: BodyParser[Unit] = mvc.BodyParsers.utils.empty

          override def apply(request: Request[Unit]): Future[Result] =
            Future.successful(Results.Ok(msg))

          override def executionContext: ExecutionContext =
            scala.concurrent.ExecutionContext.global
        }
    })
} 
Example 14
Source File: ServerInterpreterTest.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server

import java.net.ServerSocket

import akka.stream.scaladsl.Source
import endpoints4s.{Invalid, Valid}
import endpoints4s.algebra.server.{
  BasicAuthenticationTestSuite,
  DecodedUrl,
  EndpointsTestSuite,
  ChunkedJsonEntitiesTestSuite,
  SumTypedEntitiesTestSuite,
  TextEntitiesTestSuite
}
import play.api.Mode
import play.api.routing.Router
import play.api.test.FakeRequest
import play.core.server.{DefaultNettyServerComponents, NettyServer, ServerConfig}

import scala.concurrent.Future

class ServerInterpreterTest
    extends EndpointsTestSuite[EndpointsTestApi]
    with BasicAuthenticationTestSuite[EndpointsTestApi]
    with ChunkedJsonEntitiesTestSuite[EndpointsTestApi]
    with SumTypedEntitiesTestSuite[EndpointsTestApi]
    with TextEntitiesTestSuite[EndpointsTestApi] {

  val serverApi: EndpointsTestApi = {
    object NettyServerComponents extends DefaultNettyServerComponents {
      override lazy val serverConfig = ServerConfig(mode = Mode.Test)
      lazy val router = Router.empty
    }
    new EndpointsTestApi(
      PlayComponents.fromBuiltInComponents(NettyServerComponents),
      Map.empty
    )
  }

  def serveEndpoint[Resp](
      endpoint: serverApi.Endpoint[_, Resp],
      response: => Resp
  )(runTests: Int => Unit): Unit =
    serveRoutes(
      serverApi.routesFromEndpoints(endpoint.implementedBy(_ => response))
    )(runTests)

  def serveIdentityEndpoint[Resp](
      endpoint: serverApi.Endpoint[Resp, Resp]
  )(runTests: Int => Unit): Unit =
    serveRoutes(
      serverApi.routesFromEndpoints(endpoint.implementedBy(request => request))
    )(runTests)

  def serveStreamedEndpoint[Resp](
      endpoint: serverApi.Endpoint[_, serverApi.Chunks[Resp]],
      response: Source[Resp, _]
  )(runTests: Int => Unit): Unit =
    serveRoutes(
      serverApi.routesFromEndpoints(endpoint.implementedBy(_ => response))
    )(runTests)

  def serveStreamedEndpoint[Req, Resp](
      endpoint: serverApi.Endpoint[serverApi.Chunks[Req], Resp],
      logic: Source[Req, _] => Future[Resp]
  )(
      runTests: Int => Unit
  ): Unit =
    serveRoutes(
      serverApi.routesFromEndpoints(endpoint.implementedByAsync(logic))
    )(runTests)

  def serveRoutes(routes: Router.Routes)(runTests: Int => Unit): Unit = {
    val port = {
      val socket = new ServerSocket(0)
      try socket.getLocalPort
      finally if (socket != null) socket.close()
    }
    val config = ServerConfig(mode = Mode.Test, port = Some(port))
    val server = NettyServer.fromRouterWithComponents(config)(_ => routes)
    try {
      runTests(port)
    } finally {
      server.stop()
    }
  }

  def decodeUrl[A](url: serverApi.Url[A])(rawValue: String): DecodedUrl[A] = {
    val request = FakeRequest("GET", rawValue)
    url.decodeUrl(request) match {
      case None                  => DecodedUrl.NotMatched
      case Some(Invalid(errors)) => DecodedUrl.Malformed(errors)
      case Some(Valid(a))        => DecodedUrl.Matched(a)
    }
  }

} 
Example 15
Source File: RequestValidatorSpec.scala    From play-zhewbacca   with MIT License 5 votes vote down vote up
package org.zalando.zhewbacca

import org.specs2.mutable.Specification
import play.api.mvc._
import play.api.test.FakeRequest

import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
class RequestValidatorSpec extends Specification {

  val testTokenInfo = TokenInfo("", Scope.Empty, "token type", "user uid", realm = "/employees")

  "Request Validator" should {
    "provide token information when token is valid" in {
      val authProvider = new AuthProvider {
        override def valid(token: Option[OAuth2Token], scope: Scope): Future[AuthResult] =
          Future.successful(AuthTokenValid(testTokenInfo))
      }

      val result = Await.result(RequestValidator.validate(Scope(Set("uid")), FakeRequest(), authProvider), 1.seconds)
      result must beEqualTo(Right(testTokenInfo))
    }

    "return HTTP status 401 (unauthorized) when token was not provided" in {
      val authProvider = new AuthProvider {
        override def valid(token: Option[OAuth2Token], scope: Scope): Future[AuthResult] =
          Future.successful(AuthTokenEmpty)
      }

      val result = Await.result(RequestValidator.validate(Scope(Set("uid")), FakeRequest(), authProvider), 1.seconds)
      result must beEqualTo(Left(Results.Unauthorized))
    }

    "return HTTP status 401 (unauthorized) when token is in valid" in {
      val authProvider = new AuthProvider {
        override def valid(token: Option[OAuth2Token], scope: Scope): Future[AuthResult] =
          Future.successful(AuthTokenInvalid)
      }

      val result = Await.result(RequestValidator.validate(Scope(Set("uid")), FakeRequest(), authProvider), 1.seconds)
      result must beEqualTo(Left(Results.Unauthorized))
    }

    "return HTTP status 401 (unauthorized) when Authorization provider has failed" in {
      val authProvider = new AuthProvider {
        override def valid(token: Option[OAuth2Token], scope: Scope): Future[AuthResult] =
          Future.failed(new RuntimeException)
      }

      val result = Await.result(RequestValidator.validate(Scope(Set("uid")), FakeRequest(), authProvider), 1.seconds)
      result must beEqualTo(Left(Results.Unauthorized))
    }

    "return HTTP status 403 (forbidden) in case insufficient scopes" in {
      val authProvider = new AuthProvider {
        override def valid(token: Option[OAuth2Token], scope: Scope): Future[AuthResult] =
          Future.successful(AuthTokenInsufficient)
      }

      val result = Await.result(RequestValidator.validate(Scope(Set("uid")), FakeRequest(), authProvider), 1.seconds)
      result must beEqualTo(Left(Results.Forbidden))
    }
  }
} 
Example 16
Source File: SecurityRulesRepositorySpec.scala    From play-zhewbacca   with MIT License 5 votes vote down vote up
package org.zalando.zhewbacca

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import play.api.Configuration
import play.api.test.FakeRequest

import scala.concurrent.ExecutionContext

class SecurityRulesRepositorySpec extends Specification with Mockito {

  "SecurityRulesRepository" should {

    "load rules from default file" in {
      val provider = mock[AuthProvider]
      val repository = new SecurityRulesRepository(Configuration(), provider)
      val expectedRule = ValidateTokenRule(provider, "GET", "/foo", Scope(Set("uid", "entity.read")))

      repository.get(FakeRequest("GET", "/foo")) must beSome(expectedRule)
    }

    "load rules from custom file" in {
      val provider = mock[AuthProvider]
      val config = Configuration("authorisation.rules.file" -> "security_custom-security.conf")
      val repository = new SecurityRulesRepository(config, provider)
      val expectedRule = ValidateTokenRule(provider, "POST", "/bar.*", Scope(Set("uid")))

      repository.get(FakeRequest("POST", "/bar.*")) must beSome(expectedRule)
    }

    "raise an error when custom file is not available" in {
      val authProvider = mock[AuthProvider]
      val config = Configuration("authorisation.rules.file" -> "this-file-does-not-exist.conf")

      new SecurityRulesRepository(config, authProvider) must
        throwA[RuntimeException]("configuration file this-file-does-not-exist.conf for security rules not found")
    }

    "allow comments in security rules configuration file" in {
      val provider = mock[AuthProvider]
      val config = Configuration("authorisation.rules.file" -> "security_commented.conf")
      val repository = new SecurityRulesRepository(config, provider)
      val expectedRule = ValidateTokenRule(provider, "OPTIONS", "/", Scope(Set("app.resource.read")))

      repository.get(FakeRequest("OPTIONS", "/")) must beSome(expectedRule)
    }

    "raise an error when it cannot parse a configuration file" in {
      val authProvider = mock[AuthProvider]
        def config(fileName: String): Configuration = Configuration("authorisation.rules.file" -> fileName)

      new SecurityRulesRepository(config("security_unknown-http-method.conf"), authProvider) must throwA[RuntimeException]
      new SecurityRulesRepository(config("security_no-scopes.conf"), authProvider) must throwA[RuntimeException]
    }

    "return None if there is no configured rules for given request" in {
      val authProvider = mock[AuthProvider]
      val repository = new SecurityRulesRepository(Configuration(), authProvider)

      repository.get(FakeRequest("GET", "/unknown-uri")) must beNone
    }

    "allow explicitly to pass-through or deny a request for a specific URI" in {
      val authProvider = mock[AuthProvider]
      val configuration = Configuration("authorisation.rules.file" -> "security_pass-through.conf")
      val repository = new SecurityRulesRepository(configuration, authProvider)

      repository.get(FakeRequest("GET", "/foo")).get must beAnInstanceOf[ExplicitlyAllowedRule]
      repository.get(FakeRequest("GET", "/bar")).get must beAnInstanceOf[ExplicitlyDeniedRule]
    }

  }

} 
Example 17
Source File: SecurityFilterSpec.scala    From play-zhewbacca   with MIT License 5 votes vote down vote up
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
    }
  }
} 
Example 18
Source File: OAuth2TokenSpec.scala    From play-zhewbacca   with MIT License 5 votes vote down vote up
package org.zalando.zhewbacca

import org.specs2.mutable._
import play.api.test.FakeRequest

class OAuth2TokenSpec extends Specification {

  "OAuth2 token" should {

    "be extracted from 'Authorization' request header" in {
      val request = FakeRequest().withHeaders("Authorization" -> "Bearer 267534eb-3135-4b64-9bab-9573300a0634")
      OAuth2Token.from(request) must be equalTo Some(OAuth2Token("267534eb-3135-4b64-9bab-9573300a0634"))
    }

    "be extracted only from first 'Authorization' request header" in {
      val request = FakeRequest().withHeaders(
        "Authorization" -> "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
        "Authorization" -> "Bearer 78d6c4c9-b777-4524-9c59-dbf55a3f8ad1")

      OAuth2Token.from(request) must be equalTo None
    }

    "be empty for request without 'Authorization' header in it" in {
      val request = FakeRequest().withHeaders("Content-type" -> "application/json")
      OAuth2Token.from(request) must be equalTo None
    }

    "be empty for request without headers" in {
      val request = FakeRequest()
      OAuth2Token.from(request) must be equalTo None
    }

    "be empty for request with other type of authorization" in {
      val request = FakeRequest().withHeaders("Authorization" -> "Token 0675b082ebea09b4484b053285495458")
      OAuth2Token.from(request) must be equalTo None
    }

  }

  "toSafeString method" should {

    "mask token value except first and last 4 characters" in {
      val request = FakeRequest().withHeaders("Authorization" -> "Bearer dbc1ec97-d01a-4b10-b853-ec7dedeff8d9")
      OAuth2Token.from(request).get.toSafeString must be equalTo "dbc1...f8d9"
    }

  }

} 
Example 19
Source File: PlayAPISpec.scala    From playsonify   with MIT License 5 votes vote down vote up
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 20
Source File: MetricFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.metrics.CounterRequestMetrics.CounterRequestMetricBuilder
import com.github.stijndehaes.playprometheusfilters.metrics.{DefaultPlayUnmatchedDefaults, RequestMetric}
import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import com.typesafe.config.ConfigFactory
import io.prometheus.client.CollectorRegistry
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.mvc._
import play.api.test.Helpers._
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class MetricFilterSpec extends PlaySpec with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite {

  val configuration = Configuration(ConfigFactory.parseString(
    """play-prometheus-filters.exclude.paths = ["/test"]"""
  ))

  "Filter constructor" should {
    "Get exclude paths from configuration" in {
      implicit val mat = app.materializer
      val filter = new MetricsFilter(configuration) {
        override val metrics = List.empty[RequestMetric[_, RequestHeader, Result]]
      }

      filter.excludePaths must have size 1 // only check size since cannot compare Regex's
    }
  }

  "Apply method" should {
    "skip metrics for excluded paths" in {
      implicit val mat = app.materializer
      val collectorRegistry = mock[CollectorRegistry]
      val filter = new MetricsFilter(configuration) {
        override val metrics = List(
          CounterRequestMetricBuilder.build(collectorRegistry, DefaultPlayUnmatchedDefaults)
        )
      }

      val rh = FakeRequest("GET", "/test")
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      samples.size() mustBe 0 // expect no metrics
    }
  }
} 
Example 21
Source File: DeleteTeamMetricsApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteTeamMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val team = GiltTeam
  val user = SOME_USER

  "DELETE /organizations/:name/teams/:team/metric-names/:metric" should {
    "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NOT_FOUND)
    }

    "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 22
Source File: DeleteTeamMetricsShortcutApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteTeamMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val team = GiltTeam
  val user = SOME_USER

  "DELETE /metric-names/:metric" should {
    "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NOT_FOUND)
    }

    "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 23
Source File: DeleteOrganizationMetricsShortcutApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteOrganizationMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val user = SOME_USER

  "DELETE /metric-names/:metric" should {
    "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(NOT_FOUND)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member)))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 24
Source File: DeleteOrganizationMetricsApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteOrganizationMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val user = SOME_USER

  "DELETE /organizations/:name/metric-names/:metric" should {
    "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NOT_FOUND)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member)))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 25
Source File: StatusAndRouteCounterFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults
import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.libs.typedmap.TypedMap
import play.api.mvc.Results
import play.api.routing.{HandlerDef, Router}
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class StatusAndRouteCounterFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite  {

  private implicit val mat = app.materializer
  private val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a histogram to the prometheus registry" in {
      val collectorRegistry = mock[CollectorRegistry]
      new StatusAndRouteLatencyFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Measure the count" in {
      val filter = new StatusAndRouteCounterFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest().withAttrs( TypedMap(
        Router.Attrs.HandlerDef -> HandlerDef(null, null, "testController", "test", null, "GET", "/path", null ,null)
      ))
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(0)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe "test"
      countSample.labelValues.get(1) mustBe "200"
      countSample.labelValues.get(2) mustBe "testController"
      countSample.labelValues.get(3) mustBe "/path"
      countSample.labelValues.get(4) mustBe "GET"
    }

    "Measure the count for an unmatched route" in {
      val filter = new StatusAndRouteCounterFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).error

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(0)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString
      countSample.labelValues.get(1) mustBe "404"
      countSample.labelValues.get(2) mustBe DefaultPlayUnmatchedDefaults.UnmatchedControllerString
      countSample.labelValues.get(3) mustBe DefaultPlayUnmatchedDefaults.UnmatchedPathString
      countSample.labelValues.get(4) mustBe DefaultPlayUnmatchedDefaults.UnmatchedVerbString
    }
  }

} 
Example 26
Source File: LatencyFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.mvc._
import play.api.test.Helpers._
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class LatencyFilterSpec extends PlaySpec with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite {

  val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a histogram to the prometheus registry" in {
      implicit val mat = app.materializer
      val collectorRegistry = mock[CollectorRegistry]
      new LatencyFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Measure the latency" in {
      implicit val mat = app.materializer
      val filter = new LatencyFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(samples.size() - 2)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 0
    }
  }

} 
Example 27
Source File: StatusAndRouteLatencyFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults
import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.libs.typedmap.TypedMap
import play.api.mvc.Results
import play.api.routing.{HandlerDef, Router}
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class StatusAndRouteLatencyFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite  {

  private implicit val mat = app.materializer
  private val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a histogram to the prometheus registry" in {
      val collectorRegistry = mock[CollectorRegistry]
      new StatusAndRouteLatencyFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Measure the latency" in {
      val filter = new StatusAndRouteLatencyFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest().withAttrs( TypedMap(
        Router.Attrs.HandlerDef -> HandlerDef(null, null, "testController", "test", null, "GET", "/path", null ,null)
      ))
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(samples.size() - 2)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe "test"
      countSample.labelValues.get(1) mustBe "200"
      countSample.labelValues.get(2) mustBe "testController"
      countSample.labelValues.get(3) mustBe "/path"
      countSample.labelValues.get(4) mustBe "GET"
    }

    "Measure the latency for an unmatched route" in {
      val filter = new StatusAndRouteLatencyFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).error

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(samples.size() - 2)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString
      countSample.labelValues.get(1) mustBe "404"
      countSample.labelValues.get(2) mustBe DefaultPlayUnmatchedDefaults.UnmatchedControllerString
      countSample.labelValues.get(3) mustBe DefaultPlayUnmatchedDefaults.UnmatchedPathString
      countSample.labelValues.get(4) mustBe DefaultPlayUnmatchedDefaults.UnmatchedVerbString
    }
  }
} 
Example 28
Source File: StatusCounterFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.mvc.Results
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class StatusCounterFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite {

  private implicit val mat = app.materializer
  private val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a counter to the prometheus registry" in {
      val collectorRegistry = mock[CollectorRegistry]
      new StatusCounterFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Count the requests with status" in {
      val filter = new StatusCounterFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      samples.get(0).value mustBe 1.0
      samples.get(0).labelValues must have size 1
      samples.get(0).labelValues.get(0) mustBe "200"
    }
  }

} 
Example 29
Source File: UsersControllerSpec.scala    From play-quill-jdbc   with MIT License 5 votes vote down vote up
package controllers

import org.scalatest.TestData
import org.scalatestplus.play.{OneAppPerTest, PlaySpec}
import play.api.Application
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers._
import models.{User, Users}
import test._

import scala.util.Random

class UsersControllerSpec extends PlaySpec with OneAppPerTest {

  override def newAppForTest(testData: TestData): Application = fakeApp

  "GET /users/:id" should {
    "return 200 OK with body" in {
      val users = app.injector.instanceOf(classOf[Users])
      val name = s"Name${Random.nextLong()}"
      val user = users.create(User(0, name, true))
      val response = route(app, FakeRequest(GET, s"/users/${user.id}")).get
      status(response) mustBe OK
      val json = contentAsJson(response)
      (json \ "name").as[String] mustBe user.name
    }
  }

  "POST /users" should {
    "return 201 Created with Location header with created resource" in {
      val name = s"Name${Random.nextLong()}"
      val userJson = Json.obj("name" -> name, "isActive" -> true)
      val responseCreated = route(app, FakeRequest(POST, "/users").withJsonBody(userJson)).get
      status(responseCreated) mustBe CREATED
      val location = headers(responseCreated).get(LOCATION).get
      val responseGet = route(app, FakeRequest(GET, location)).get
      val json = contentAsJson(responseGet)
      (json \ "name").as[String] mustBe name
    }
  }

  "DELETE /users/:id" should {
    "return 204 No Content and delete resource" in {
      val users = app.injector.instanceOf(classOf[Users])
      val name = s"Name${Random.nextLong()}"
      val user = users.create(User(0, name, true))
      val response = route(app, FakeRequest(DELETE, s"/users/${user.id}")).get
      status(response) mustBe NO_CONTENT
      users.find(user.id) mustBe empty
    }
  }

  "PUT /users/:id" should {
    "return 204 No Content and update resource" in {
      val users = app.injector.instanceOf(classOf[Users])
      val name = s"Name${Random.nextLong()}"
      val user = users.create(User(0, name, true))
      val updatedName = s"Name${Random.nextLong()}"
      val updateUserJson = Json.obj("name" -> updatedName, "isActive" -> true)
      val response = route(app, FakeRequest(PUT, s"/users/${user.id}").withJsonBody(updateUserJson)).get
      status(response) mustBe NO_CONTENT
      val updatedUser = users.find(user.id)
      updatedUser.get.name mustBe updatedName
    }
  }

} 
Example 30
Source File: RouteLatencyFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults
import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.libs.typedmap.TypedMap
import play.api.mvc._
import play.api.routing.{HandlerDef, Router}
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class RouteLatencyFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite  {

  private implicit val mat = app.materializer
  private val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a histogram to the prometheus registry" in {
      val collectorRegistry = mock[CollectorRegistry]
      new RouteLatencyFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Measure the latency" in {
      val filter = new RouteLatencyFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest().withAttrs( TypedMap(
        Router.Attrs.HandlerDef -> HandlerDef(null, null, null, "test", null, null ,null ,null ,null)
      ))
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(samples.size() - 2)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 1
      countSample.labelValues.get(0) mustBe "test"
    }

    "Measure the latency for an unmatched route" in {
      val filter = new RouteLatencyFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).error

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(samples.size() - 2)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 1
      countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString
    }
  }

} 
Example 31
Source File: PrometheusControllerSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.controllers

import java.util.Collections

import io.prometheus.client.Collector.MetricFamilySamples
import io.prometheus.client.{Collector, CollectorRegistry}
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.mvc.Results
import play.api.test.FakeRequest
import play.api.test.Helpers._


class PrometheusControllerSpec extends PlaySpec with Results with MockitoSugar {

  "Get metrics method" should {
    "Return the prometheus metrics" in {
      val collectorRegistry = mock[CollectorRegistry]
      val metricsFamilySample = new MetricFamilySamples("test", Collector.Type.COUNTER, "help", Collections.emptyList())
      when(collectorRegistry.metricFamilySamples()).thenReturn(new java.util.Vector(Collections.singleton(metricsFamilySample)).elements)

      val client = new PrometheusController(collectorRegistry, stubControllerComponents())

      val request = FakeRequest(GET, "/metrics")

      val result = client.getMetrics.apply(request)
      status(result) mustBe OK
      contentAsString(result) mustBe "# HELP test help\n# TYPE test counter\n"
    }
  }

} 
Example 32
Source File: LaunchQueueControllerTest.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api.v1.controllers

import dcos.metronome.api.v1.models.QueuedJobRunMapWrites
import dcos.metronome.api.{MockApiComponents, OneAppPerTestWithComponents, TestAuthFixture}
import dcos.metronome.model.{JobId, JobRunSpec, QueuedJobRunInfo}
import dcos.metronome.queue.LaunchQueueService
import mesosphere.marathon.core.plugin.PluginManager
import mesosphere.marathon.state.Timestamp
import org.mockito.Mockito._
import org.scalatest.BeforeAndAfter
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.ApplicationLoader.Context
import play.api.test.FakeRequest
import play.api.test.Helpers.{GET, route, _}

class LaunchQueueControllerTest
    extends PlaySpec
    with OneAppPerTestWithComponents[MockApiComponents]
    with ScalaFutures
    with MockitoSugar
    with BeforeAndAfter {

  private val queueServiceMock = mock[LaunchQueueService]

  "GET /queue" should {
    "return list of jobs in the queue" in {
      val queuedJobRun = QueuedJobRunInfo(JobId("job"), Timestamp.zero, JobRunSpec())
      val queuedJobList = List(queuedJobRun)
      when(queueServiceMock.list()).thenReturn(queuedJobList)
      val response = route(app, FakeRequest(GET, "/v1/queue")).get

      status(response) mustBe OK
      contentType(response) mustBe Some("application/json")
      contentAsJson(response) mustBe QueuedJobRunMapWrites.writes(queuedJobList.groupBy(_.jobId))
    }

    "return nothing when not authorized to see the job" in {
      auth.authorized = false
      val queuedJobList = List(QueuedJobRunInfo(JobId("job"), Timestamp.zero, JobRunSpec()))
      when(queueServiceMock.list()).thenReturn(queuedJobList)
      val response = route(app, FakeRequest(GET, "/v1/queue")).get

      contentAsJson(response) mustBe QueuedJobRunMapWrites.writes(Map.empty)
    }
  }

  val auth = new TestAuthFixture

  before {
    auth.authorized = true
    auth.authenticated = true
  }

  override def createComponents(context: Context): MockApiComponents =
    new MockApiComponents(context) {
      override lazy val queueService: LaunchQueueService = queueServiceMock
      override lazy val pluginManager: PluginManager = auth.pluginManager
    }
} 
Example 33
Source File: ApplicationControllerTest.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api.v1.controllers

import dcos.metronome.api.{MockApiComponents, OneAppPerTestWithComponents}
import mesosphere.marathon.core.election.ElectionService
import org.mockito.Mockito._
import org.scalatestplus.play.PlaySpec
import org.scalatest.Matchers._
import org.scalatestplus.mockito.MockitoSugar
import play.api.ApplicationLoader.Context
import play.api.test.FakeRequest
import play.api.test.Helpers._

class ApplicationControllerTest extends PlaySpec with OneAppPerTestWithComponents[MockApiComponents] with MockitoSugar {

  val electionServiceMock = mock[ElectionService]

  "ping" should {
    "send a pong" in {
      val ping = route(app, FakeRequest(GET, "/ping")).get
      status(ping) mustBe OK
      contentType(ping) mustBe Some("text/plain")
      contentAsString(ping) must include("pong")
    }
  }

  "metrics" should {
    "give metrics as json" in {
      val metrics = route(app, FakeRequest(GET, "/v1/metrics")).get
      status(metrics) mustBe OK
      contentType(metrics) mustBe Some("application/json")
    }
  }

  "info" should {
    "send version info" in {
      val info = route(app, FakeRequest(GET, "/info")).get
      status(info) mustBe OK
      contentType(info) mustBe Some("application/json")
      (contentAsJson(info) \ "version").as[String] should include regex "\\d+.\\d+.\\d+".r
      (contentAsJson(info) \ "libVersion").as[String] should include regex "\\d+.\\d+.\\d+".r
    }
  }

  "leader" should {
    "send leader info" in {
      when(electionServiceMock.leaderHostPort).thenReturn(Some("localhost:8080"))
      val info = route(app, FakeRequest(GET, "/leader")).get
      status(info) mustBe OK
      contentType(info) mustBe Some("application/json")
      (contentAsJson(info) \ "leader").as[String] should be("localhost:8080")
    }

    "send not found" in {
      when(electionServiceMock.leaderHostPort).thenReturn(None)
      val info = route(app, FakeRequest(GET, "/leader")).get
      status(info) mustBe NOT_FOUND
      contentType(info) mustBe Some("application/json")
      (contentAsJson(info) \ "message").as[String] should be("There is no leader")
    }
  }

  override def createComponents(context: Context): MockApiComponents =
    new MockApiComponents(context) {
      override lazy val electionService = electionServiceMock
    }
} 
Example 34
Source File: Values.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.web.testingutils

import java.util.UUID

import akka.stream.Materializer
import akka.stream.testkit.NoMaterializer
import com.danielasfregola.randomdatagenerator.RandomDataGenerator
import com.mohiva.play.silhouette.api.actions._
import com.mohiva.play.silhouette.api.util.Clock
import com.mohiva.play.silhouette.api.{LoginInfo, Silhouette, SilhouetteProvider, Environment => SilhouetteEnvironment}
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import com.mohiva.play.silhouette.impl.providers.SocialProviderRegistry
import com.mohiva.play.silhouette.test._
import com.typesafe.config.ConfigFactory
import gospeak.core.domain.User
import gospeak.core.services.storage.DbConf
import gospeak.core.testingutils.Generators._
import gospeak.infra.services.AvatarSrv
import gospeak.infra.services.email.InMemoryEmailSrv
import gospeak.infra.services.storage.sql.GsRepoSql
import gospeak.web.AppConf
import gospeak.web.auth.domain.{AuthUser, CookieEnv}
import gospeak.web.auth.services.{AuthRepo, AuthSrv}
import gospeak.web.domain.Breadcrumb
import gospeak.web.utils.{UserAwareReq, UserReq}
import play.api.mvc._
import play.api.test.CSRFTokenHelper._
import play.api.test.{CSRFTokenHelper, FakeRequest, Helpers}

import scala.concurrent.ExecutionContext.Implicits.global

object Values extends RandomDataGenerator {
  // play
  // private val playEnv = Environment.simple()
  // private val ctx = ApplicationLoader.Context.create(playEnv)
  // val app = new GospeakComponents(ctx)
  val cc: ControllerComponents = Helpers.stubControllerComponents()
  private val playBodyParsers = cc.parsers
  private val messagesApi = cc.messagesApi
  private val bodyParsers: BodyParsers.Default = new BodyParsers.Default(playBodyParsers)

  // silhouette
  private val user: User = random[User]
  private val loginInfo: LoginInfo = AuthSrv.loginInfo(user.email)
  private val identity: AuthUser = AuthUser(loginInfo, user, Seq())
  protected val clock = Clock()
  private val env: SilhouetteEnvironment[CookieEnv] = FakeEnvironment[CookieEnv](Seq(identity.loginInfo -> identity))
  private val securedAction: SecuredAction = new DefaultSecuredAction(new DefaultSecuredRequestHandler(new DefaultSecuredErrorHandler(messagesApi)), bodyParsers)
  private val unsecuredAction: UnsecuredAction = new DefaultUnsecuredAction(new DefaultUnsecuredRequestHandler(new DefaultUnsecuredErrorHandler(messagesApi)), bodyParsers)
  private val userAwareAction: UserAwareAction = new DefaultUserAwareAction(new DefaultUserAwareRequestHandler(), bodyParsers)
  val silhouette: Silhouette[CookieEnv] = new SilhouetteProvider(env, securedAction, unsecuredAction, userAwareAction)
  val unsecuredReqHeader: RequestHeader = FakeRequest().withCSRFToken
  val securedReqHeader: RequestHeader = FakeRequest().withAuthenticator(identity.loginInfo)(env).withCSRFToken
  protected implicit val mat: Materializer = NoMaterializer

  // app
  val conf: AppConf = AppConf.load(ConfigFactory.load()).get
  private val dbConf = DbConf.H2(s"jdbc:h2:mem:${UUID.randomUUID()};MODE=PostgreSQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1")
  val db: GsRepoSql = new GsRepoSql(dbConf, conf.gospeak)
  private val authRepo = new AuthRepo(db.user, db.group)
  val emailSrv = new InMemoryEmailSrv()
  val authSrv = AuthSrv(conf.auth, silhouette, db.user, db.userRequest, db.group, authRepo, clock, SocialProviderRegistry(Seq()), new AvatarSrv())

  // twirl
  private val req: Request[AnyContent] = CSRFTokenHelper.addCSRFToken(FakeRequest().withAuthenticator(identity.loginInfo)(env))
  private val authenticator: CookieAuthenticator = FakeAuthenticator(loginInfo)(env, req)
  private val r: SecuredRequest[CookieEnv, AnyContent] = SecuredRequest[CookieEnv, AnyContent](identity, authenticator, req)
  val userReq: UserReq[AnyContent] = UserReq.from(conf, messagesApi, r)
  val userAwareReq: UserAwareReq[AnyContent] = userReq.userAware
  val b: Breadcrumb = Breadcrumb(Seq())
} 
Example 35
Source File: HealthControllerSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package controllers

import cats.effect.IO
import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import play.api.mvc.ControllerComponents
import play.api.test.Helpers.{GET, status}
import play.api.test.{FakeRequest, Helpers}
import vinyldns.core.health.HealthService
import vinyldns.core.health.HealthCheck._
import play.api.test.Helpers._

@RunWith(classOf[JUnitRunner])
class HealthControllerSpec extends Specification {

  val components: ControllerComponents = Helpers.stubControllerComponents()

  "HealthController" should {
    "send 200 if the healthcheck succeeds" in {
      val healthService =
        new HealthService(List(IO.unit.attempt.asHealthCheck(classOf[HealthControllerSpec])))
      val controller = new HealthController(components, healthService)

      val result = controller
        .health()
        .apply(FakeRequest(GET, "/health"))

      status(result) must beEqualTo(200)
    }
    "send 500 if a healthcheck fails" in {
      val err = IO
        .raiseError(new RuntimeException("bad!!"))
        .attempt
        .asHealthCheck(classOf[HealthControllerSpec])
      val healthService =
        new HealthService(List(IO.unit.attempt.asHealthCheck(classOf[HealthControllerSpec]), err))
      val controller = new HealthController(components, healthService)

      val result = controller
        .health()
        .apply(FakeRequest(GET, "/health"))

      status(result) must beEqualTo(500)
    }
  }
} 
Example 36
Source File: SystemStatusSpec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.controllers

import com.mohiva.play.silhouette.test._
import org.hatdex.hat.api.HATTestContext
import org.hatdex.hat.api.json.HatJsonFormats
import org.hatdex.hat.api.models.{ HatStatus, StatusKind }
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.specification.BeforeAll
import play.api.Logger
import play.api.test.{ FakeRequest, PlaySpecification }

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

class SystemStatusSpec(implicit ee: ExecutionEnv) extends PlaySpecification with Mockito with HATTestContext with BeforeAll with HatJsonFormats {

  val logger = Logger(this.getClass)

  sequential

  def beforeAll: Unit = {
    Await.result(databaseReady, 60.seconds)
  }

  "The `update` method" should {
    "Return success response after updating HAT database" in {
      val request = FakeRequest("GET", "http://hat.hubofallthings.net")

      val controller = application.injector.instanceOf[SystemStatus]
      val result = controller.update().apply(request)

      status(result) must equalTo(OK)
      (contentAsJson(result) \ "message").as[String] must be equalTo "Database updated"
    }
  }

  "The `status` method" should {
    "Return current utilisation" in {
      val request = FakeRequest("GET", "http://hat.hubofallthings.net")
        .withAuthenticator(owner.loginInfo)

      val controller = application.injector.instanceOf[SystemStatus]
      val result = controller.status().apply(request)

      status(result) must equalTo(OK)
      val stats = contentAsJson(result).as[List[HatStatus]]

      stats.length must be greaterThan 0
      stats.find(_.title == "Previous Login").get.kind must be equalTo StatusKind.Text("Never", None)
      stats.find(_.title == "Owner Email").get.kind must be equalTo StatusKind.Text("[email protected]", None)
      stats.find(_.title == "Database Storage").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "File Storage").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "Database Storage Used").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "File Storage Used").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "Database Storage Used Share").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "File Storage Used Share").get.kind must haveClass[StatusKind.Numeric]
    }

    "Return last login information when present" in {
      val authRequest = FakeRequest("GET", "http://hat.hubofallthings.net")
        .withHeaders("username" -> "hatuser", "password" -> "pa55w0rd")

      val authController = application.injector.instanceOf[Authentication]

      val request = FakeRequest("GET", "http://hat.hubofallthings.net")
        .withAuthenticator(owner.loginInfo)

      val controller = application.injector.instanceOf[SystemStatus]

      val result = for {
        _ <- authController.accessToken().apply(authRequest)
        // login twice - the second login is considered "current", not previous
        _ <- authController.accessToken().apply(authRequest)
        r <- controller.status().apply(request)
      } yield r

      status(result) must equalTo(OK)
      val stats = contentAsJson(result).as[List[HatStatus]]

      stats.length must be greaterThan 0
      stats.find(_.title == "Previous Login").get.kind must be equalTo StatusKind.Text("moments ago", None)
    }
  }
} 
Example 37
Source File: PaperlessPreferencesControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithActiveTabAction, WithBreadcrumbAction}
import models.{ActivatedOnlineFilerSelfAssessmentUser, NonFilerSelfAssessmentUser}
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.MessagesApi
import play.api.mvc.{ActionBuilder, MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.twirl.api.Html
import services.partials.PreferencesFrontendPartialService
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.domain.SaUtr
import uk.gov.hmrc.play.partials.HtmlPartial
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec, BetterOptionValues, LocalPartialRetriever, Tools}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}

class PaperlessPreferencesControllerSpec extends BaseSpec with MockitoSugar {
  import BetterOptionValues._

  override implicit lazy val app = localGuiceApplicationBuilder().build()

  val mockPreferencesFrontendPartialService = mock[PreferencesFrontendPartialService]
  val mockAuthJourney = mock[AuthJourney]

  def controller: PaperlessPreferencesController =
    new PaperlessPreferencesController(
      mockPreferencesFrontendPartialService,
      mockAuthJourney,
      injected[WithActiveTabAction],
      injected[WithBreadcrumbAction],
      injected[MessagesControllerComponents],
      injected[Tools]
    )(mock[LocalPartialRetriever], injected[ConfigDecorator], injected[TemplateRenderer], injected[ExecutionContext]) {}

  "Calling PaperlessPreferencesController.managePreferences" should {
    "Redirect to  preferences-frontend manage paperless url when a user is logged in using GG" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(request = request)
          )
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe SEE_OTHER

      val redirectUrl = redirectLocation(r).getValue
      val configDecorator = app.injector.instanceOf[ConfigDecorator]
      redirectUrl should include regex s"${configDecorator.preferencesFrontendService}/paperless/check-settings\\?returnUrl=.*\\&returnLinkText=.*"
    }

    "Return 400 for Verify users" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(
              credentials = Credentials("", "Verify"),
              confidenceLevel = ConfidenceLevel.L500,
              request = request
            ))
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe BAD_REQUEST
    }
  }
} 
Example 38
Source File: TermsConditionsControllerSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.http._
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.nisp.helpers._
import uk.gov.hmrc.nisp.utils.MockTemplateRenderer
import uk.gov.hmrc.play.partials.CachedStaticHtmlPartialRetriever
import uk.gov.hmrc.renderer.TemplateRenderer

class TermsConditionsControllerSpec extends PlaySpec with OneAppPerSuite {

  val fakeRequest = FakeRequest("GET", "/")

  val MockTermsConditionsController = new TermsConditionsController {
    override implicit val cachedStaticHtmlPartialRetriever: CachedStaticHtmlPartialRetriever = MockCachedStaticHtmlPartialRetriever

    override implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer
  }

  "GET /" should {

    "return 200" in {
      val result = MockTermsConditionsController.show(fakeRequest)
      status(result) mustBe Status.OK
    }

    "return HTML" in {
      val result = MockTermsConditionsController.show(fakeRequest)
      contentType(result) mustBe Some("text/html")
      charset(result) mustBe Some("utf-8")
    }

    "load the T&Cs page without back link" in {
      val result = contentAsString(MockTermsConditionsController.show(fakeRequest))
      result must include("The information given is based on details from your National Insurance record at the time you use the service. While we will make every effort to keep your record up to date, we do not guarantee that it will be or that it is error and omission free.")
      result must not include("<p class=\"backlink\"><a href=\"/check-your-state-pension/account\">Back</a></p>")
    }

    "load the T&Cs page with back link" in {
      val fakeRequest = FakeRequest("GET", "/?showBackLink=true")
      val result = contentAsString(MockTermsConditionsController.show(fakeRequest))
      result must include("The information given is based on details from your National Insurance record at the time you use the service. While we will make every effort to keep your record up to date, we do not guarantee that it will be or that it is error and omission free.")
      result must include("<p class=\"backlink\"><a href=\"/check-your-state-pension/account\">Back</a></p>")
    }

  }

  "GET / with showBackLink query parameter" should {

    "return 200 with flag value" in {
      val result = MockTermsConditionsController.show(fakeRequest)
      status(result) mustBe Status.OK
      contentAsString(result) must include("The information given is based on details from your National Insurance record at the time you use the service. While we will make every effort to keep your record up to date, we do not guarantee that it will be or that it is error and omission free.")
      contentAsString(result) must not include("<p class=\"backlink\"><a href=\"/check-your-state-pension/account\">Back</a></p>")
    }

    "load the T&Cs page with back link" in {
      val fakeRequest = FakeRequest("GET", "/?showBackLink=true")
      val result = contentAsString(MockTermsConditionsController.show(fakeRequest))
      result must include("The information given is based on details from your National Insurance record at the time you use the service. While we will make every effort to keep your record up to date, we do not guarantee that it will be or that it is error and omission free.")
      result must include("<p class=\"backlink\"><a href=\"/check-your-state-pension/account\">Back</a></p>")
    }

  }
} 
Example 39
Source File: RedirectControllerSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.test.Helpers._
import play.api.test.{FakeRequest, Helpers}

class RedirectControllerSpec extends PlaySpec with OneAppPerSuite {

  "GET /checkmystatepension" should {
    "redirect to /check-your-state-pension" in {
      val request = FakeRequest("GET", "/checkmystatepension")
      val result = Helpers.route(request).get
      redirectLocation(result) mustBe Some("/check-your-state-pension")
    }
  }

  "GET /checkmystatepension + query string" should {
    "redirect to /check-your-state-pension + query string" in {
      val request = FakeRequest("GET", "/checkmystatepension?p=123&q=456")
      val result = Helpers.route(request).get
      redirectLocation(result) mustBe Some("/check-your-state-pension?p=123&q=456")
    }
  }

  "GET /checkmystatepension/account" should {
    "redirect to /check-your-state-pension/account" in {
      val request = FakeRequest("GET", "/checkmystatepension/account")
      val result = Helpers.route(request).get
      redirectLocation(result) mustBe Some("/check-your-state-pension/account")
    }
  }

  "GET /checkmystatepension/account + query string" should {
    "redirect to /check-your-state-pension/account" in {
      val request = FakeRequest("GET", "/checkmystatepension/account?p=123&q=456")
      val result = Helpers.route(request).get
      redirectLocation(result) mustBe Some("/check-your-state-pension/account?p=123&q=456")
    }
  }

  "GET /checkmystatepension//account" should {
    "redirect to /check-your-state-pension/account" in {
      val request = FakeRequest("GET", "/checkmystatepension//account")
      val result = Helpers.route(request).get
      redirectLocation(result) mustBe Some("/check-your-state-pension/account")
    }
  }
} 
Example 40
Source File: CustomLanguageControllerSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import org.scalatestplus.play.OneAppPerSuite
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.play.test.UnitSpec

class CustomLanguageControllerSpec extends UnitSpec with OneAppPerSuite {

  val testLanguageController = app.injector.instanceOf[CustomLanguageController]

  "Hitting language selection endpoint" should {

    "redirect to English translated start page if English language is selected" in {
      val request = FakeRequest()
      val result = testLanguageController.switchToLanguage("english")(request)
      header("Set-Cookie", result) shouldBe Some("PLAY_LANG=en; Path=/; HTTPOnly;;PLAY_FLASH=switching-language=true; Path=/; HTTPOnly")
    }

    "redirect to Welsh translated start page if Welsh language is selected" in {
      val request = FakeRequest()
      val result = testLanguageController.switchToLanguage("cymraeg")(request)
      header("Set-Cookie", result) shouldBe Some("PLAY_LANG=cy; Path=/; HTTPOnly;;PLAY_FLASH=switching-language=true; Path=/; HTTPOnly")
    }

  }
} 
Example 41
Source File: BreadcrumbSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import org.scalatestplus.play.OneAppPerSuite
import play.api.i18n.Messages.Implicits._
import play.api.test.FakeRequest
import uk.gov.hmrc.nisp.helpers.MockBreadcrumb
import uk.gov.hmrc.play.test.UnitSpec

class BreadcrumbSpec extends UnitSpec with OneAppPerSuite {
  val fakeRequestSP = FakeRequest("GET", "/account")
  val fakeRequestNI = FakeRequest("GET", "/account/nirecord/gaps")
  val fakeRequestVolContribution = FakeRequest("GET", "/account/nirecord/voluntarycontribs")
  val fakeRequestHowToImproveGaps = FakeRequest("GET", "/account/nirecord/gapsandhowtocheck")
  val messages = applicationMessages

  "Breadcrumb utils" should {
    "return a item text as Account Home and State Pension" in {
      val bc = MockBreadcrumb.buildBreadCrumb(fakeRequestSP, messages)
      bc.lastItem.map(_.text) shouldBe Some("State Pension")
    }

    "return a item text as Account Home, State Pension and NI Record when URL is /account/nirecord/gaps" in {
      val bc = MockBreadcrumb.buildBreadCrumb(fakeRequestNI, messages)
      val breadcrumbItem = "Breadcrumb: BreadcrumbItem(Account home,http://localhost:9232/account), BreadcrumbItem(State Pension,/check-your-state-pension/account), lastItem: Some(BreadcrumbItem(NI record,/check-your-state-pension/account/nirecord))"
      bc.toString() shouldBe breadcrumbItem
    }

    "return a item text as Account Home, State Pension and NI Record when URL is /account/nirecord/voluntarycontribs" in {
      val bc = MockBreadcrumb.buildBreadCrumb(fakeRequestVolContribution, messages)
      val breadcrumbItem = "Breadcrumb: BreadcrumbItem(Account home,http://localhost:9232/account), BreadcrumbItem(State Pension,/check-your-state-pension/account), BreadcrumbItem(NI record,/check-your-state-pension/account/nirecord), lastItem: Some(BreadcrumbItem(Voluntary contributions,/check-your-state-pension/account/nirecord/voluntarycontribs))"
      bc.toString() shouldBe breadcrumbItem
    }

    "return a item text as Account Home, State Pension and NI Record when URL is /account/nirecord/gapsandhowtocheck" in {
      val bc = MockBreadcrumb.buildBreadCrumb(fakeRequestHowToImproveGaps, messages)
      val breadcrumbItem = "Breadcrumb: BreadcrumbItem(Account home,http://localhost:9232/account), BreadcrumbItem(State Pension,/check-your-state-pension/account), BreadcrumbItem(NI record,/check-your-state-pension/account/nirecord), lastItem: Some(BreadcrumbItem(Gaps in your record and how to check them,/check-your-state-pension/account/nirecord/gapsandhowtocheck))"
      bc.toString() shouldBe breadcrumbItem
    }
  }
} 
Example 42
Source File: AuthenticationContext.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.context

import com.dataengi.crm.common.context.CRMApplication
import com.dataengi.crm.configurations.{RolesConfiguration, RootConfiguration}
import com.dataengi.crm.identities.errors.UsersServiceErrors
import com.dataengi.crm.contacts.generators.EmailGen
import org.scalacheck.Gen
import play.api.mvc.AnyContentAsEmpty
import play.api.test.FakeRequest
import com.dataengi.crm.contacts.services._
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.extensions.awaits._
import com.dataengi.crm.identities.arbitraries.IdentitiesArbitrary
import com.dataengi.crm.identities.controllers.data._
import com.dataengi.crm.identities.models.User
import com.dataengi.crm.identities.services._

trait AuthenticationContext extends CRMApplication with IdentitiesArbitrary {

  lazy val authenticationService = application.injector.instanceOf[AuthenticationService]
  lazy val invitesService        = application.injector.instanceOf[InvitesService]
  lazy val rolesService          = application.injector.instanceOf[RolesService]
  lazy val companiesService      = application.injector.instanceOf[CompaniesService]
  lazy val usersService          = application.injector.instanceOf[UsersService]
  lazy val rootConfiguration     = application.injector.instanceOf[RootConfiguration]
  lazy val rolesConfiguration    = application.injector.instanceOf[RolesConfiguration]

  lazy val rootSignInData =
    SignInData(rootConfiguration.rootLoginInfo.providerKey, rootConfiguration.rootPassword)

  lazy val TestCompanyName = "TEST_COMPANY" + Gen.alphaStr.sample.get

  lazy val userEmail             = EmailGen.randomEmailsGenerator.sample.getOrElse("[email protected]")
  lazy val userPassword          = "test_password"
  lazy val userSignInData        = SignInData(userEmail, userPassword)
  lazy val userSignUpData        = SignUpData(userPassword)
  lazy val forgotPassword        = ForgotPassword(userEmail)
  lazy val userLocalhost         = "localhost"
  lazy val newPassword: String   = "new_password"
  lazy val recoverPassword       = RecoverPasswordData(newPassword)
  lazy val userChangedSignInData = SignInData(userEmail, newPassword)
  lazy val rootUser: User = {
    usersService
      .findByEmail(rootConfiguration.rootLoginInfo.providerKey)
      .toOrWithLeft(UsersServiceErrors.IdentityNotFound)
      .await()
      .value
  }

  implicit val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest()

  def inviteData(testCompanyId: Long, salesRepresentativeRoleId: Long): InviteData = InviteData(
    email = userEmail,
    companyId = testCompanyId,
    roleId = salesRepresentativeRoleId
  )

} 
Example 43
Source File: AddressControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import controllers.auth.AuthJourney
import controllers.auth.requests.UserRequest
import play.api.mvc.Request
import play.api.mvc.Results._
import play.api.test.FakeRequest
import play.api.test.Helpers._
import util.UserRequestFixture.buildUserRequest

class AddressControllerSpec extends AddressBaseSpec {

  object SUT
      extends AddressController(
        injected[AuthJourney],
        withActiveTabAction,
        cc,
        displayAddressInterstitialView
      )

  "addressJourneyEnforcer" should {

    "complete given block" when {

      "a nino and person details are present in the request" in {

        def userRequest[A]: UserRequest[A] =
          buildUserRequest(request = FakeRequest().asInstanceOf[Request[A]])

        val expectedContent = "Success"

        val result = SUT.addressJourneyEnforcer { _ => _ =>
          Ok(expectedContent)
        }(userRequest)

        status(result) shouldBe OK
        contentAsString(result) shouldBe expectedContent
      }
    }

    "show the address interstitial view page" when {

      "a nino cannot be found in the request" in {

        def userRequest[A]: UserRequest[A] =
          buildUserRequest(nino = None, request = FakeRequest().asInstanceOf[Request[A]])

        val result = SUT.addressJourneyEnforcer { _ => _ =>
          Ok("Success")
        }(userRequest)

        status(result) shouldBe OK
        contentAsString(result) should include(messages("label.you_can_see_this_part_of_your_account_if_you_complete"))
      }

      "person details cannot be found in the request" in {
        implicit def userRequest[A]: UserRequest[A] =
          buildUserRequest(personDetails = None, request = FakeRequest().asInstanceOf[Request[A]])

        val result = SUT.addressJourneyEnforcer { _ => _ =>
          Ok("Success")
        }

        status(result) shouldBe OK
        contentAsString(result) should include(messages("label.you_can_see_this_part_of_your_account_if_you_complete"))

      }
    }
  }

  "internalServerError" should {

    "return 500 and render the correct page" in {
      def userRequest[A]: UserRequest[A] =
        buildUserRequest(request = FakeRequest().asInstanceOf[Request[A]])

      val result = SUT.internalServerError(userRequest)

      status(result) shouldBe INTERNAL_SERVER_ERROR
      contentAsString(result) should include(messages("global.error.InternalServerError500.title"))
    }
  }
} 
Example 44
Source File: TaxCreditsChoiceControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import models.dto.AddressPageVisitedDto
import org.mockito.Matchers.any
import org.mockito.Mockito.{times, verify}
import play.api.http.Status.{BAD_REQUEST, OK, SEE_OTHER}
import play.api.libs.json.Json
import play.api.mvc.Request
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.http.cache.client.CacheMap
import views.html.personaldetails.TaxCreditsChoiceView

class TaxCreditsChoiceControllerSpec extends AddressBaseSpec {

  trait LocalSetup extends AddressControllerSetup {

    def controller: TaxCreditsChoiceController =
      new TaxCreditsChoiceController(
        mockAuthJourney,
        withActiveTabAction,
        cc,
        addressJourneyCachingHelper,
        injected[TaxCreditsChoiceView],
        displayAddressInterstitialView
      )

    def sessionCacheResponse: Option[CacheMap] =
      Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true)))))

    def currentRequest[A]: Request[A] = FakeRequest().asInstanceOf[Request[A]]
  }

  "onPageLoad" should {

    "return OK if there is an entry in the cache to say the user previously visited the 'personal details' page" in new LocalSetup {

      val result = controller.onPageLoad(currentRequest)

      status(result) shouldBe OK
      verify(mockLocalSessionCache, times(1)).fetch()(any(), any())
    }

    "redirect back to the start of the journey if there is no entry in the cache to say the user previously visited the 'personal details' page" in new LocalSetup {
      override def sessionCacheResponse: Option[CacheMap] = None

      val result = controller.onPageLoad(currentRequest)

      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("/personal-account/personal-details")
      verify(mockLocalSessionCache, times(1)).fetch()(any(), any())
    }
  }

  "onSubmit" should {

    "redirect to expected tax credits page when supplied with value = Yes (true)" in new LocalSetup {

      override def currentRequest[A]: Request[A] =
        FakeRequest("POST", "")
          .withFormUrlEncodedBody("taxCreditsChoice" -> "true")
          .asInstanceOf[Request[A]]

      val result =
        controller.onSubmit()(FakeRequest())

      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("/tax-credits-service/personal/change-address")
    }

    "redirect to ResidencyChoice page when supplied with value = No (false)" in new LocalSetup {

      override def currentRequest[A]: Request[A] =
        FakeRequest("POST", "")
          .withFormUrlEncodedBody("taxCreditsChoice" -> "false")
          .asInstanceOf[Request[A]]

      val result = controller.onSubmit(FakeRequest())

      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("/personal-account/your-address/residency-choice")
    }

    "return a bad request when supplied no value" in new LocalSetup {

      override def currentRequest[A]: Request[A] =
        FakeRequest("POST", "")
          .asInstanceOf[Request[A]]

      val result = controller.onSubmit(FakeRequest())

      status(result) shouldBe BAD_REQUEST
    }
  }
} 
Example 45
Source File: AddressErrorControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import controllers.bindable.{PostalAddrType, SoleAddrType}
import models.dto._
import play.api.libs.json.Json
import play.api.mvc._
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.http.cache.client.CacheMap
import views.html.personaldetails._

class AddressErrorControllerSpec extends AddressBaseSpec {

  trait LocalSetup extends AddressControllerSetup {

    def sessionCacheResponse: Option[CacheMap] =
      Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true)))))

    def currentRequest[A]: Request[A] = FakeRequest("POST", "/test").asInstanceOf[Request[A]]

    def controller: AddressErrorController =
      new AddressErrorController(
        mockAuthJourney,
        addressJourneyCachingHelper,
        withActiveTabAction,
        cc,
        displayAddressInterstitialView,
        injected[CannotUseServiceView],
        injected[AddressAlreadyUpdatedView]
      )
  }

  "cannotUseThisService" should {

    "display the cannot use this service page" in new LocalSetup {
      val result = controller.cannotUseThisService(SoleAddrType)(currentRequest)

      status(result) shouldBe OK
      contentAsString(result) should include("You cannot use this service to update your address")
    }
  }

  "showAddressAlreadyUpdated" should {

    "display the showAddressAlreadyUpdated page" in new LocalSetup {

      val result = controller.showAddressAlreadyUpdated(PostalAddrType)(currentRequest)

      status(result) shouldBe OK
      contentAsString(result) should include("Your address has already been updated")
    }
  }
} 
Example 46
Source File: NispFrontendControllerSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import org.slf4j.{Logger => Slf4JLogger}
import org.mockito.Mockito.{verify, when}
import org.mockito.ArgumentMatchers._
import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.OneAppPerSuite
import play.api.Logger
import play.api.http.Status
import play.api.mvc.Result
import play.api.test.FakeRequest
import uk.gov.hmrc.nisp.config.{ApplicationGlobal, ApplicationGlobalTrait}
import uk.gov.hmrc.nisp.helpers.{MockApplicationGlobal, MockCachedStaticHtmlPartialRetriever}
import uk.gov.hmrc.nisp.utils.MockTemplateRenderer
import uk.gov.hmrc.play.test.UnitSpec
import uk.gov.hmrc.renderer.TemplateRenderer

class NispFrontendControllerSpec extends UnitSpec with MockitoSugar with OneAppPerSuite {

  val mockLogger: Slf4JLogger = mock[Slf4JLogger]
  when(mockLogger.isErrorEnabled).thenReturn(true)

  def controller = new NispFrontendController {
    override val logger = new Logger(mockLogger)
    val cachedStaticHtmlPartialRetriever = MockCachedStaticHtmlPartialRetriever
    override implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer
    override  val applicationGlobal:ApplicationGlobalTrait = MockApplicationGlobal
  }

  implicit val request = FakeRequest()

  "onError" should {
    "should log error details" in {
      val result: Result =  controller.onError(new Exception())
      verify(mockLogger).error(anyString(), any[Exception])
    }

    "should return an Internal Server Error (500)" in {
      val result: Result =  controller.onError(new Exception())
      status(result) shouldBe Status.INTERNAL_SERVER_ERROR
    }
  }

} 
Example 47
Source File: PaperlessInterruptHelperSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.controllershelpers

import controllers.auth.requests.UserRequest
import models.{ActivatePaperlessNotAllowedResponse, ActivatePaperlessRequiresUserActionResponse, NonFilerSelfAssessmentUser, UserName}
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.mvc.Results._
import play.api.test.FakeRequest
import play.api.test.Helpers._
import services._
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.{Credentials, Name}
import util.{BaseSpec, Fixtures}

import scala.concurrent.Future

class PaperlessInterruptHelperSpec extends BaseSpec {

  "Calling PaperlessInterruptHelper.enforcePaperlessPreference" should {

    implicit val userRequest = UserRequest(
      Some(Fixtures.fakeNino),
      Some(UserName(Name(Some("Firstname"), Some("Lastname")))),
      NonFilerSelfAssessmentUser,
      Credentials("", "GovernmentGateway"),
      ConfidenceLevel.L200,
      None,
      None,
      None,
      None,
      None,
      None,
      FakeRequest()
    )

    "Redirect to paperless interupt page for a user who has no enrolments" in {
      lazy val paperlessInterruptHelper = new PaperlessInterruptHelper {
        override val preferencesFrontendService: PreferencesFrontendService =
          MockitoSugar.mock[PreferencesFrontendService]
        when(preferencesFrontendService.getPaperlessPreference()(any())) thenReturn {
          Future.successful(ActivatePaperlessRequiresUserActionResponse("/activate-paperless"))
        }
      }

      val r = paperlessInterruptHelper.enforcePaperlessPreference(Ok)
      status(r) shouldBe SEE_OTHER
      redirectLocation(await(r)) shouldBe Some("/activate-paperless")
    }

    "Return the result of the block when getPaperlessPreference does not return ActivatePaperlessRequiresUserActionResponse" in {
      lazy val paperlessInterruptHelper = new PaperlessInterruptHelper {
        override val preferencesFrontendService: PreferencesFrontendService =
          MockitoSugar.mock[PreferencesFrontendService]
        when(preferencesFrontendService.getPaperlessPreference()(any())) thenReturn {
          Future.successful(ActivatePaperlessNotAllowedResponse)
        }
      }

      val r = paperlessInterruptHelper.enforcePaperlessPreference(Ok)
      status(r) shouldBe OK
    }
  }
} 
Example 48
Source File: LanguageControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import play.api.test.FakeRequest
import play.api.test.Helpers._
import util.BaseSpec

class LanguageControllerSpec extends BaseSpec {

  trait LocalSetup {
    val c = app.injector.instanceOf[LanguageSwitchController]
  }

  "Calling LanguageController.enGb" should {
    "change the language to English and return 303" in new LocalSetup {
      val r = c.enGb()(FakeRequest("GET", ""))
      cookies(r).get("PLAY_LANG").get.value shouldBe "en"
      status(r) shouldBe SEE_OTHER
    }
  }

  "Calling LanguageController.cyGb" should {
    "change the language to Welsh and return 303" in new LocalSetup {
      val r = c.cyGb()(FakeRequest("GET", ""))
      cookies(r).get("PLAY_LANG").get.value shouldBe "cy"
      status(r) shouldBe SEE_OTHER
    }
  }
} 
Example 49
Source File: PaymentsControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import connectors._
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithBreadcrumbAction}
import models.CreatePayment
import org.joda.time.DateTime
import org.mockito.Matchers.any
import org.mockito.Mockito.when
import org.scalatestplus.mockito.MockitoSugar
import play.api.Application
import play.api.i18n.MessagesApi
import play.api.inject.bind
import play.api.mvc.{ActionBuilder, MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers.{redirectLocation, _}
import uk.gov.hmrc.renderer.TemplateRenderer
import uk.gov.hmrc.time.CurrentTaxYear
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec}

import scala.concurrent.{ExecutionContext, Future}

class PaymentsControllerSpec extends BaseSpec with CurrentTaxYear with MockitoSugar {

  override def now: () => DateTime = DateTime.now

  lazy val fakeRequest = FakeRequest("", "")

  val mockPayConnector = mock[PayApiConnector]
  val mockAuthJourney = mock[AuthJourney]

  override implicit lazy val app: Application = localGuiceApplicationBuilder()
    .overrides(
      bind[PayApiConnector].toInstance(mockPayConnector),
      bind[AuthJourney].toInstance(mockAuthJourney)
    )
    .build()

  def controller =
    new PaymentsController(
      mockPayConnector,
      mockAuthJourney,
      injected[WithBreadcrumbAction],
      injected[MessagesControllerComponents]
    )(mockLocalPartialRetriever, injected[ConfigDecorator], mock[TemplateRenderer], injected[ExecutionContext])

  when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
    override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
      block(
        buildUserRequest(
          request = request
        ))
  })

  "makePayment" should {
    "redirect to the response's nextUrl" in {

      val expectedNextUrl = "someNextUrl"
      val createPaymentResponse = CreatePayment("someJourneyId", expectedNextUrl)

      when(mockPayConnector.createPayment(any())(any(), any()))
        .thenReturn(Future.successful(Some(createPaymentResponse)))

      val result = controller.makePayment()(FakeRequest())
      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("someNextUrl")
    }

    "redirect to a BAD_REQUEST page if createPayment failed" in {

      when(mockPayConnector.createPayment(any())(any(), any()))
        .thenReturn(Future.successful(None))

      val result = controller.makePayment()(FakeRequest())
      status(result) shouldBe BAD_REQUEST
    }
  }
} 
Example 50
Source File: PublicControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import org.scalatestplus.mockito.MockitoSugar
import play.api.mvc.{MessagesControllerComponents, Session}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.http.SessionKeys
import uk.gov.hmrc.play.binders.Origin
import uk.gov.hmrc.renderer.TemplateRenderer
import util.BaseSpec
import util.Fixtures._

import scala.concurrent.ExecutionContext

class PublicControllerSpec extends BaseSpec with MockitoSugar {

  private val mockTemplateRenderer = mock[TemplateRenderer]
  private val configDecorator = injected[ConfigDecorator]

  private def controller = new PublicController(injected[MessagesControllerComponents])(
    mockLocalPartialRetriever,
    configDecorator,
    mockTemplateRenderer,
    injected[ExecutionContext]
  )

  "Calling PublicController.sessionTimeout" should {

    "return 200" in {

      val r = controller.sessionTimeout(buildFakeRequestWithAuth("GET"))
      status(r) shouldBe OK
    }
  }

  "Calling PublicController.redirectToExitSurvey" should {

    "return 303" in {

      val r = controller.redirectToExitSurvey(Origin("PERTAX"))(buildFakeRequestWithAuth("GET"))
      status(r) shouldBe SEE_OTHER
      redirectLocation(r) shouldBe Some("/feedback/PERTAX")
    }
  }

  "Calling PublicController.redirectToTaxCreditsService" should {

    "redirect to tax-credits-service/renewals/service-router" in {

      val r = controller.redirectToTaxCreditsService()(buildFakeRequestWithAuth("GET"))
      status(r) shouldBe MOVED_PERMANENTLY
      redirectLocation(r) shouldBe Some("/tax-credits-service/renewals/service-router")
    }
  }

  "Calling PublicController.redirectToPersonalDetails" should {

    "redirect to /personal-details page" in {
      val r = controller.redirectToPersonalDetails()(buildFakeRequestWithAuth("GET"))

      status(r) shouldBe SEE_OTHER
      redirectLocation(r) shouldBe Some("/personal-account/personal-details")
    }
  }

  "Calling PublicController.verifyEntryPoint" should {

    "redirect to /personal-account page with Verify auth provider" in {
      val request = FakeRequest("GET", "/personal-account/start-verify")
      val r = controller.verifyEntryPoint()(request)

      status(r) shouldBe SEE_OTHER
      redirectLocation(r) shouldBe Some("/personal-account")
      session(r) shouldBe new Session(Map(SessionKeys.authProvider -> configDecorator.authProviderVerify))
    }
  }

  "Calling PublicController.governmentGatewayEntryPoint" should {

    "redirect to /personal-account page with GG auth provider" in {
      val request = FakeRequest("GET", "/personal-account/start-government-gateway")
      val r = controller.governmentGatewayEntryPoint()(request)

      status(r) shouldBe SEE_OTHER
      redirectLocation(r) shouldBe Some("/personal-account")
      session(r) shouldBe new Session(Map(SessionKeys.authProvider -> configDecorator.authProviderGG))
    }
  }
} 
Example 51
Source File: SaWrongCredentialsControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import controllers.auth.FakeAuthJourney
import models.WrongCredentialsSelfAssessmentUser
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.MessagesApi
import play.api.mvc.MessagesControllerComponents
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.domain.{SaUtr, SaUtrGenerator}
import uk.gov.hmrc.renderer.TemplateRenderer
import util.{BaseSpec, LocalPartialRetriever}
import views.html.selfassessment.{DoYouKnowOtherCredentialsView, DoYouKnowUserIdView, FindYourUserIdView, NeedToResetPasswordView, SignInAgainView, SignedInWrongAccountView}

import scala.concurrent.ExecutionContext

class SaWrongCredentialsControllerSpec extends BaseSpec with MockitoSugar {

  val fakeAuthJourney = new FakeAuthJourney(
    WrongCredentialsSelfAssessmentUser(SaUtr(new SaUtrGenerator().nextSaUtr.utr)))

  def controller =
    new SaWrongCredentialsController(
      fakeAuthJourney,
      injected[MessagesControllerComponents],
      injected[SignedInWrongAccountView],
      injected[DoYouKnowOtherCredentialsView],
      injected[SignInAgainView],
      injected[DoYouKnowUserIdView],
      injected[NeedToResetPasswordView],
      injected[FindYourUserIdView]
    )(injected[LocalPartialRetriever], config, injected[TemplateRenderer], injected[ExecutionContext])

  "processDoYouKnowOtherCredentials" should {
    "redirect to 'Sign in using Government Gateway' page when supplied with value Yes" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "true")

      val result = controller.processDoYouKnowOtherCredentials(request)
      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.signInAgain().url)
    }

    "redirect to 'You need to use the creds you've created' page when supplied with value No (false)" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "false")

      val result = controller.processDoYouKnowOtherCredentials(request)

      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.doYouKnowUserId().url)
    }

    "return a bad request when supplied no value" in {
      val request = FakeRequest("POST", "")

      val result = controller.processDoYouKnowOtherCredentials(request)
      status(result) shouldBe BAD_REQUEST
    }
  }

  "processDoYouKnowUserId" should {
    "redirect to 'Sign in using Government Gateway' page when supplied with value Yes" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "true")

      val result = controller.processDoYouKnowUserId(request)
      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.needToResetPassword().url)
    }

    "redirect to 'You need to use the creds you've created' page when supplied with value No (false)" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "false")
      val result = controller.processDoYouKnowUserId(request)

      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.findYourUserId().url)
    }

    "return a bad request when supplied no value" in {
      val request = FakeRequest("POST", "")
      val result = controller.processDoYouKnowUserId(request)
      status(result) shouldBe BAD_REQUEST
    }
  }

  "ggSignInUrl" should {
    "be the gg-sign in url" in {
      controller.ggSignInUrl shouldBe "/gg/sign-in?continue=/personal-account&accountType=individual&origin=PERTAX"
    }
  }
} 
Example 52
Source File: UpdateAddressResponseSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import config.ConfigDecorator
import models.NonFilerSelfAssessmentUser
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.Result
import play.api.mvc.Results.Ok
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.http.HttpResponse
import util.UserRequestFixture.buildUserRequest
import util.BaseSpec

class UpdateAddressResponseSpec extends BaseSpec with I18nSupport with MockitoSugar {

  implicit val configDecorator: ConfigDecorator = injected[ConfigDecorator]

  override def messagesApi: MessagesApi = injected[MessagesApi]

  implicit val userRequest = buildUserRequest(
    saUser = NonFilerSelfAssessmentUser,
    credentials = Credentials("", "Verify"),
    confidenceLevel = ConfidenceLevel.L500,
    request = FakeRequest()
  )

  def genericFunc(): Result =
    Ok

  "UpdateAddressResponse.response" should {
    "return the block result for UpdateAddressSuccessResponse" in {
      val result = UpdateAddressSuccessResponse.response(genericFunc)
      status(result) shouldBe OK
    }

    "return BAD_REQUEST for UpdateAddressBadRequestResponse" in {
      val result = UpdateAddressBadRequestResponse.response(genericFunc)
      status(result) shouldBe BAD_REQUEST
    }

    "return INTERNAL_SERVER_ERROR for UpdateAddressUnexpectedResponse" in {
      val updateAddressResponse = UpdateAddressUnexpectedResponse(HttpResponse(123))
      val result = updateAddressResponse.response(genericFunc)
      status(result) shouldBe INTERNAL_SERVER_ERROR
    }

    "return INTERNAL_SERVER_ERROR for UpdateAddressErrorResponse" in {
      val updateAddressResponse = UpdateAddressErrorResponse(new RuntimeException("not used"))
      val result = updateAddressResponse.response(genericFunc)
      status(result) shouldBe INTERNAL_SERVER_ERROR
    }
  }
} 
Example 53
Source File: HomeViewSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package views.html

import config.ConfigDecorator
import models._
import org.jsoup.nodes.Document
import org.scalatestplus.mockito.MockitoSugar
import play.api.test.FakeRequest
import uk.gov.hmrc.auth.core.retrieve.Name
import uk.gov.hmrc.domain.SaUtrGenerator
import uk.gov.hmrc.renderer.TemplateRenderer
import util.Fixtures
import util.UserRequestFixture.buildUserRequest
import viewmodels.HomeViewModel

import scala.collection.JavaConversions._

class HomeViewSpec extends ViewSpec with MockitoSugar {

  lazy val home = injected[HomeView]

  implicit val configDecorator: ConfigDecorator = injected[ConfigDecorator]
  implicit val templateRenderer = injected[TemplateRenderer]

  val homeViewModel = HomeViewModel(Nil, Nil, Nil, true, None)

  "Rendering HomeView.scala.html" should {

    "show the users name and not 'Your account' when the user has details and is not a GG user" in {
      implicit val userRequest =
        buildUserRequest(personDetails = Some(Fixtures.buildPersonDetails), userName = None, request = FakeRequest())

      lazy val document: Document = asDocument(home(homeViewModel).toString)

      document.select("h1").exists(e => e.text == "Firstname Lastname") shouldBe true
      document.select("h1").exists(e => e.text == "Your account") shouldBe false
    }

    "show the users name and not 'Your account' when the user has no details but is a GG user" in {
      implicit val userRequest = buildUserRequest(
        personDetails = None,
        userName = Some(UserName(Name(Some("Firstname"), Some("Lastname")))),
        request = FakeRequest()
      )

      lazy val document: Document = asDocument(home(homeViewModel).toString)

      document.select("h1").exists(e => e.text == "Firstname Lastname") shouldBe true
      document.select("h1").exists(e => e.text == "Your account") shouldBe false
    }

    "show 'Your account' and not the users name when the user has no details and is not a GG user" in {
      implicit val userRequest = buildUserRequest(personDetails = None, userName = None, request = FakeRequest())

      lazy val document: Document = asDocument(home(homeViewModel).toString)

      document.select("h1").exists(e => e.text == "Your account") shouldBe true
    }

    "should not show the UTR if the user is not a self assessment user" in {
      implicit val userRequest = buildUserRequest(request = FakeRequest())

      val view = home(homeViewModel).toString

      view should not contain messages("label.home_page.utr")
    }

    "should show the UTR if the user is a self assessment user" in {
      implicit val userRequest = buildUserRequest(request = FakeRequest())
      val utr = new SaUtrGenerator().nextSaUtr.utr
      val view = home(homeViewModel.copy(saUtr = Some(utr))).toString

      view should include(messages("label.home_page.utr"))
      view should include(utr)
    }
  }
} 
Example 54
Source File: LaboratoryControllerNotFoundSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import jp.t2v.lab.play2.auth.test.Helpers.AuthFakeRequest
import model.form.LaboratoryForm
import model.form.data.LaboratoryFormData
import model.json.{LaboratoryJson, LoginJson}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import services.state


class LaboratoryControllerNotFoundSpec extends LaboratoryControllerSpec {
  val labService = mockLaboratoryService(state.NotFound)
  // Controller to be tested, with the dependencies
  lazy val controller = new LaboratoryController(labService, messagesApi)(userService, executionContext, environment)

  "Laboratory Controller on not founding operations" should {
    "return Not Found <404> status on receiving an edited laboratory" in {

      val result = controller.update.apply {
        FakeRequest()
          .withJsonBody(Json.toJson(laboratory))
          .withLoggedIn(controller)(loggedInUser)
      }
      assertFutureResultStatus(result, 404)
    }

    "return Not Found <404> status on deleting a laboratory" in {
      val result = controller.delete(laboratory.id).apply {
        FakeRequest()
          .withLoggedIn(controller)(LoginJson("admin", "adminaton"))
      }
      assertFutureResultStatus(result, 404)
    }
  }
} 
Example 55
Source File: OAuth2ProviderActionBuildersSpec.scala    From play2-oauth2-provider   with MIT License 5 votes vote down vote up
package scalaoauth2.provider

import javax.inject.Inject

import org.scalatest._
import org.scalatest.Matchers._
import play.api.mvc.{AbstractController, ControllerComponents}
import play.api.test._
import play.api.test.Helpers._
import play.api.test.FakeRequest

class OAuth2ProviderActionBuildersSpec extends FlatSpec {

  class MyController @Inject() (components: ControllerComponents)
      extends AbstractController(components)
      with OAuth2ProviderActionBuilders {

    val action = AuthorizedAction(new MockDataHandler) { request =>
      Ok(request.authInfo.user.name)
    }

  }

  it should "return BadRequest" in {
    val controller = new MyController(Helpers.stubControllerComponents())
    val result = controller.action(FakeRequest())
    status(result) should be(400)
    contentAsString(result) should be("")
  }

} 
Example 56
Source File: QueryParserTests.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.router2

import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import play.api.test.FakeRequest

class QueryParserTests extends AssertionsForJUnit {
  val request = FakeRequest("GET", "/api/myResource.v1?bool1=true&bool2=false&bool3=&bool4=1")

  @Test
  def checkTrueParsing(): Unit = {
    assert(
      CollectionResourceRouter.BooleanFlagParser("bool1", getClass).evaluate(request) ===
        Right(true))
  }

  @Test
  def checkFalseParsing(): Unit = {
    assert(
      CollectionResourceRouter.BooleanFlagParser("bool2", getClass).evaluate(request) ===
        Right(false))
  }

  @Test
  def checkEmptyParsing(): Unit = {
    assert(CollectionResourceRouter.BooleanFlagParser("bool3", getClass).evaluate(request).isLeft)
  }

  @Test
  def checkMalformedParsing(): Unit = {
    assert(CollectionResourceRouter.BooleanFlagParser("bool4", getClass).evaluate(request).isLeft)
  }
} 
Example 57
Source File: NaptimePlayRouterTest.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.router2

import akka.util.ByteString
import com.google.inject.Injector
import org.coursera.naptime.resources.RootResource
import org.coursera.naptime.schema.Handler
import org.coursera.naptime.schema.HandlerKind
import org.coursera.naptime.schema.Parameter
import org.coursera.naptime.schema.Resource
import org.coursera.naptime.schema.ResourceKind
import org.junit.Test
import org.mockito.Mockito.when
import org.mockito.Matchers.any
import org.scalatest.junit.AssertionsForJUnit
import org.scalatest.mockito.MockitoSugar
import play.api.libs.streams.Accumulator
import play.api.mvc.EssentialAction
import play.api.mvc.RequestHeader
import play.api.mvc.RequestTaggingHandler
import play.api.mvc.Result
import play.api.test.FakeRequest

class NaptimePlayRouterTest extends AssertionsForJUnit with MockitoSugar {
  object FakeHandler extends  EssentialAction with RequestTaggingHandler {
    override def tagRequest(request: RequestHeader): RequestHeader = request

    override def apply(v1: RequestHeader): Accumulator[ByteString, Result] = ???
  }

  val resourceSchema = Resource(
    kind = ResourceKind.COLLECTION,
    name = "fakeResource",
    version = Some(1L),
    parentClass = Some(classOf[RootResource].getName),
    keyType = "java.lang.String",
    valueType = "FakeModel",
    mergedType = "FakeResourceModel",
    handlers = List(
      Handler(
        kind = HandlerKind.GET,
        name = "get",
        parameters =
          List(Parameter(name = "id", `type` = "String", attributes = List.empty, default = None)),
        inputBodyType = None,
        customOutputBodyType = None,
        attributes = List.empty)),
    className = "org.coursera.naptime.FakeResource",
    attributes = List.empty)

  val resourceRouter = mock[ResourceRouter]
  val resourceRouterBuilder = mock[ResourceRouterBuilder]
  when(resourceRouterBuilder.build(any())).thenReturn(resourceRouter)
  when(resourceRouterBuilder.schema).thenReturn(resourceSchema)

  val injector = mock[Injector]
  val naptimeRoutes = NaptimeRoutes(injector, Set(resourceRouterBuilder))
  val router = new NaptimePlayRouter(naptimeRoutes)

  @Test
  def simpleRouting(): Unit = {
    when(resourceRouter.routeRequest(any(), any())).thenReturn(Some(FakeHandler))
    val handler = router.handlerFor(FakeRequest())
    assert(handler.isDefined)
  }

  @Test
  def simpleRoutingNothing(): Unit = {
    when(resourceRouter.routeRequest(any(), any())).thenReturn(None)
    val handler = router.handlerFor(FakeRequest())
    assert(handler.isEmpty)
  }

  @Test
  def generateDocumentation(): Unit = {
    val documentation = router.documentation
    assert(1 === documentation.length)
    assert(
      (
        "GET --- GET",
        "/fakeResource.v1/$id",
        "[NAPTIME] org.coursera.naptime.FakeResource.get(id: String)") ===
        documentation.head)
  }
} 
Example 58
Source File: RouterTest.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.router2

import com.google.inject.Injector
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import org.scalatest.mockito.MockitoSugar
import org.mockito.Mockito._
import org.mockito.Matchers._
import play.api.test.FakeRequest

object RouterTest {
  class Resource1
  class Resource2
  class Resource3

  abstract class ResourceRouterBuilder1 extends ResourceRouterBuilder {
    type ResourceType = Resource1
  }
  abstract class ResourceRouterBuilder2 extends ResourceRouterBuilder {
    type ResourceType = Resource2
  }
  abstract class ResourceRouterBuilder3 extends ResourceRouterBuilder {
    type ResourceType = Resource3
  }

  abstract class ResourceRouter1 extends ResourceRouter {
    type ResourceType = Resource1
  }
  abstract class ResourceRouter2 extends ResourceRouter {
    type ResourceType = Resource2
  }
  abstract class ResourceRouter3 extends ResourceRouter {
    type ResourceType = Resource3
  }
}

class RouterTest extends AssertionsForJUnit with MockitoSugar {
  import RouterTest._

  val resourceRouterBuilder1 = mock[ResourceRouterBuilder1]
  val resourceRouterBuilder2 = mock[ResourceRouterBuilder2]
  val resourceRouterBuilder3 = mock[ResourceRouterBuilder3]
  val resourceRouter1 = mock[ResourceRouter1]
  val resourceRouter2 = mock[ResourceRouter2]
  val resourceRouter3 = mock[ResourceRouter3]
  val resources = List(resourceRouterBuilder1, resourceRouterBuilder2, resourceRouterBuilder3)
  val injector = mock[Injector]
  setupStandardMocks()
  val router = new Router(injector, resources)

  private[this] def setupStandardMocks(): Unit = {
    when(resourceRouterBuilder1.build(any())).thenReturn(resourceRouter1)
    when(resourceRouterBuilder2.build(any())).thenReturn(resourceRouter2)
    when(resourceRouterBuilder3.build(any())).thenReturn(resourceRouter3)
  }
  val fakeRequest = FakeRequest("GET", "/api/foo.v1")

  @Test
  def simpleRouting(): Unit = {
    when(resourceRouter1.routeRequest(any(), any())).thenReturn(Some(null))
    val result = router.onRouteRequest(fakeRequest)
    assert(result.isDefined, "Expected result to be defined.")
    verifyZeroInteractions(resourceRouter2, resourceRouter3)
  }

  @Test
  def stopImmediately(): Unit = {
    when(resourceRouter1.routeRequest(any(), any())).thenReturn(None)
    when(resourceRouter2.routeRequest(any(), any())).thenReturn(Some(null))
    val result = router.onRouteRequest(fakeRequest)
    assert(result.isDefined, "Expected result to be defined.")
    verifyZeroInteractions(resourceRouter3)
  }

  @Test
  def handleNoMatchingRequests(): Unit = {
    when(resourceRouter1.routeRequest(any(), any())).thenReturn(None)
    when(resourceRouter2.routeRequest(any(), any())).thenReturn(None)
    when(resourceRouter3.routeRequest(any(), any())).thenReturn(None)
    val result = router.onRouteRequest(fakeRequest)
    assert(result.isEmpty, "Expected result to be empty.")
  }
} 
Example 59
Source File: FilterTest.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.ari.graphql.controllers.filters

import org.coursera.naptime.ari.graphql.GraphqlSchemaProvider
import org.coursera.naptime.ari.graphql.Models
import org.coursera.naptime.ari.graphql.SangriaGraphQlContext
import org.coursera.naptime.ari.graphql.SangriaGraphQlSchemaBuilder
import org.coursera.naptime.ari.graphql.models.MergedCourse
import org.coursera.naptime.ari.graphql.models.MergedInstructor
import org.coursera.naptime.ari.graphql.models.MergedPartner
import org.mockito.Mockito.when
import org.scalatest.concurrent.IntegrationPatience
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.junit.AssertionsForJUnit
import org.scalatest.mockito.MockitoSugar
import play.api.libs.json.Json
import play.api.test.FakeRequest
import sangria.parser.QueryParser
import sangria.schema.Schema

import scala.concurrent.Future

trait FilterTest
    extends AssertionsForJUnit
    with MockitoSugar
    with ScalaFutures
    with IntegrationPatience {

  val baseOutgoingQuery = OutgoingQuery(Json.obj(), None)

  def noopFilter(incomingQuery: IncomingQuery) = {
    Future.successful(baseOutgoingQuery)
  }

  def exceptionThrowingFilter(incomingQuery: IncomingQuery): Future[OutgoingQuery] = {
    assert(false, "This filter should not be run")
    Future.successful(baseOutgoingQuery)
  }

  val filter: Filter

  val defaultQuery =
    """
      |query {
      |  __schema {
      |    queryType {
      |      name
      |    }
      |  }
      |}
    """.stripMargin

  val graphqlSchemaProvider = mock[GraphqlSchemaProvider]

  val allResources = Set(Models.courseResource, Models.instructorResource, Models.partnersResource)

  val schemaTypes = Map(
    "org.coursera.naptime.ari.graphql.models.MergedCourse" -> MergedCourse.SCHEMA,
    "org.coursera.naptime.ari.graphql.models.MergedPartner" -> MergedPartner.SCHEMA,
    "org.coursera.naptime.ari.graphql.models.MergedInstructor" -> MergedInstructor.SCHEMA)
  val builder = new SangriaGraphQlSchemaBuilder(allResources, schemaTypes)

  val schema = builder.generateSchema().data.asInstanceOf[Schema[SangriaGraphQlContext, Any]]
  when(graphqlSchemaProvider.schema).thenReturn(schema)

  def generateIncomingQuery(query: String = defaultQuery) = {
    val document = QueryParser.parse(query).get
    val header = FakeRequest("POST", s"/graphql").withBody(query)
    val variables = Json.obj()
    val operation = None
    IncomingQuery(document, header, variables, operation, debugMode = false)
  }

  def run(incomingQuery: IncomingQuery): Future[OutgoingQuery] = {
    filter.apply(noopFilter)(incomingQuery)
  }

  def ensureNotPropagated(incomingQuery: IncomingQuery): Future[OutgoingQuery] = {
    filter.apply(exceptionThrowingFilter)(incomingQuery)
  }
} 
Example 60
Source File: RestActionTester.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.actions

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.Materializer
import org.coursera.naptime.NaptimeActionException
import org.coursera.naptime.QueryFields
import org.coursera.naptime.QueryIncludes
import org.coursera.naptime.RequestEvidence
import org.coursera.naptime.RequestPagination
import org.coursera.naptime.RestContext
import org.coursera.naptime.RestError
import org.coursera.naptime.RestResponse
import org.junit.After
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.exceptions.TestFailedException
import play.api.test.FakeRequest

import scala.concurrent.ExecutionContext
import scala.util.Try


  protected[this] implicit class RestActionTestOps[AuthType, BodyType, ResponseType](
      action: RestAction[_, AuthType, BodyType, _, _, ResponseType]) {

    def testAction(ctx: RestContext[AuthType, BodyType]): RestResponse[ResponseType] = {
      val updatedAuthEither = action.restAuthGenerator.apply(ctx.body).check(ctx.auth)

      updatedAuthEither match {
        case Left(error) => RestError(error)
        case Right(updatedAuth) =>
          val responseFuture = action.safeApply(ctx.copyWithAuth(updatedAuth)).recover {
            case e: NaptimeActionException => RestError(e)
          }

          Try(responseFuture.futureValue).recover {
            case e: TestFailedException => e.cause.map(throw _).getOrElse(throw e)
          }.get
      }
    }

    def testActionPassAuth(ctx: RestContext[AuthType, BodyType]): RestResponse[ResponseType] = {
      val responseFuture = action.safeApply(ctx).recover {
        case e: NaptimeActionException => RestError(e)
      }

      Try(responseFuture.futureValue).recover {
        case e: TestFailedException => e.cause.map(throw _).getOrElse(throw e)
      }.get
    }
  }
} 
Example 61
Source File: LoginControllerSuccessfulSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import play.api.libs.json.Json
import play.api.test.FakeRequest
import services.state


  val controller = new LoginController(userService, messagesApi)(executionContext,environment)

  "Login Controller on successful operations" should {
    "return Ok <200> status on requesting the Login Form" in {
      val result = controller.login.apply{
        FakeRequest().withJsonBody(Json.parse(
          s"""
            |{
            | "username": "${userToBeUsed.username}",
            | "password": "${userToBeUsed.password}"
            |}
          """.stripMargin))
      }
      assertFutureResultStatus(result, 200)
    }
  }
} 
Example 62
Source File: LaboratoryControllerSuccessfulSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import org.mockito.Matchers.any
import org.mockito.Mockito.when
import com.google.inject.ImplementedBy
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.test.Helpers.AuthFakeRequest
import model.Laboratory
import model.Role
import model.User
import model.form.LaboratoryForm
import model.form.data.LaboratoryFormData
import model.json.{LaboratoryJson, LoginJson}
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.test.WithApplication
import services.LaboratoryService
import services.RoomService
import services.UserService
import services.impl.LaboratoryServiceImpl
import services.state
import services.state.ActionState
import test.ControllerTest


class LaboratoryControllerSuccessfulSpec extends LaboratoryControllerSpec {
  val labService: LaboratoryService = mockLaboratoryService(state.ActionCompleted)
  // Controller to be tested, with the dependencies
  lazy val controller = new LaboratoryController(labService, messagesApi)(userService, executionContext, environment)

  "Laboratory Controller on successful operations" should {
    "return Ok <200> status on receiving an edited laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryFormData(name, location, administration)
      val laboratoryForm = LaboratoryForm.form.fill(laboratoryData)
      val result = controller.update.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withJsonBody(Json.toJson(laboratory))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status on deleting a laboratory" in {
      val result = controller.delete(laboratory.id).apply {
        FakeRequest()
          .withLoggedIn(controller)(LoginJson("admin", "adminaton"))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status on adding a new laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryJson(name, location, administration)
      val result = controller.add.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withJsonBody(Json.toJson(laboratoryData))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status when listing all laboratories" in pending
    "return laboratory list json when listing all laboratories" in pending
  }
} 
Example 63
Source File: ViewNationalInsuranceInterstitialHomeViewSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package views.html.interstitial

import config.ConfigDecorator
import org.scalatestplus.mockito.MockitoSugar
import play.api.test.FakeRequest
import play.twirl.api.Html
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import views.html.ViewSpec

class ViewNationalInsuranceInterstitialHomeViewSpec extends ViewSpec with MockitoSugar {

  override implicit lazy val app = localGuiceApplicationBuilder().build()

  lazy val view = injected[ViewNationalInsuranceInterstitialHomeView]

  implicit val templateRenderer = app.injector.instanceOf[TemplateRenderer]
  implicit val configDecorator: ConfigDecorator = injected[ConfigDecorator]
  implicit val userRequest = buildUserRequest(request = FakeRequest())

  "Rendering ViewNationalInsuranceInterstitialHomeView.scala.html" should {

    "show NINO section when a nino is present" in {
      val document = asDocument(view(Html(""), "asfa", userRequest.nino).toString)
      Option(document.select(".nino").first).isDefined shouldBe true
    }

    "show incomplete when there is no NINO" in {
      val document = asDocument(view(Html(""), "http://google.com", None).toString)
      Option(document.select(".nino").first).isDefined shouldBe false
      document.body().toString should include(messages("label.you_can_see_this_part_of_your_account_if_you_complete"))
    }

  }
} 
Example 64
Source File: LaboratoryControllerFailedSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import jp.t2v.lab.play2.auth.test.Helpers.AuthFakeRequest
import model.form.LaboratoryForm
import model.form.data.LaboratoryFormData
import model.json.LaboratoryJson
import play.api.libs.json.Json
import play.api.test.FakeRequest
import services.{LaboratoryService, state}


class LaboratoryControllerFailedSpec extends LaboratoryControllerSpec {
  val labService: LaboratoryService = mockLaboratoryService(state.Failed)
  // Controller to be tested, with the dependencies
  lazy val controller = new LaboratoryController(labService, messagesApi)(userService, executionContext, environment)

  "Laboratory Controller on failing operations" should {
    "return Failed <400> status on adding a new laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryFormData(name, location, administration)
      val laboratoryForm = LaboratoryForm.form.fill(laboratoryData)
      val result = controller.add.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withFormUrlEncodedBody(laboratoryForm.data.toSeq: _*)
      }
      assertFutureResultStatus(result, 400)
    }

    "return \"Could not add that laboratory\" response message JSON on adding a new laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryJson(name, location, administration)
      val result = controller.add.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withJsonBody(Json.toJson(laboratoryData))
      }
      assertBodyJsonMessage(result, "Could not add that laboratory")
    }
  }
} 
Example 65
Source File: NRSServiceSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.services

import org.joda.time.DateTime
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.test.FakeRequest
import uk.gov.hmrc.domain.Vrn
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.vatapi.UnitSpec
import uk.gov.hmrc.vatapi.assets.TestConstants.Auth.orgAuthContextWithNrsData
import uk.gov.hmrc.vatapi.assets.TestConstants.NRSResponse._
import uk.gov.hmrc.vatapi.assets.TestConstants.VatReturn._
import uk.gov.hmrc.vatapi.httpparsers.NrsError
import uk.gov.hmrc.vatapi.httpparsers.NrsSubmissionHttpParser.NrsSubmissionOutcome
import uk.gov.hmrc.vatapi.mocks.connectors.MockNRSConnector
import uk.gov.hmrc.vatapi.models.VatReturnDeclaration
import uk.gov.hmrc.vatapi.resources.AuthRequest

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

class NRSServiceSpec extends UnitSpec with GuiceOneAppPerSuite with MockFactory with ScalaFutures with MockNRSConnector {

  val testNRSService = new NRSService(mockNRSConnector)

  implicit val hc: HeaderCarrier = HeaderCarrier()
  implicit val req: AuthRequest[_] = new AuthRequest(orgAuthContextWithNrsData, FakeRequest().withHeaders(("Authorization", "Bearer test-bearer-token")))

  val testDateTime: DateTime = DateTime.now()

  "NRSService.submit" when {

    lazy val testVrn: Vrn = Vrn("123456789")
    def result(declaration: VatReturnDeclaration): Future[NrsSubmissionOutcome] = {
      val submission = testNRSService.convertToNrsSubmission(testVrn, declaration)
      testNRSService.submit(testVrn, submission)
    }

    "successful responses are returned from the connector" should {
      "return the correctly formatted NRS Data model" in {
        setupNrsSubmission(testVrn, nrsSubmission)(Right(nrsClientData))
        extractAwait(result(vatReturnDeclaration)) shouldBe Right(nrsClientData)
      }
    }

    "error responses are returned from the connector" should {
      "return an NRS Error model" in {
        setupNrsSubmission(testVrn, nrsSubmission)(Left(NrsError))
        extractAwait(result(vatReturnDeclaration)) shouldBe Left(NrsError)
      }
    }
  }
} 
Example 66
Source File: VersionSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package definition

import play.api.http.HeaderNames.ACCEPT
import play.api.test.FakeRequest
import support.UnitSpec
import uk.gov.hmrc.http.HeaderCarrier

class VersionSpec extends UnitSpec {

  "Versions" when {
    "retrieved from header carrier" must {
      "return None when 'Accept' header missing" in {
        Versions.getFromRequest(HeaderCarrier()) shouldBe None
      }
      "return None when 'Accept' header does not contain a version" in {
        Versions.getFromRequest(HeaderCarrier().withExtraHeaders((ACCEPT, "application/json"))) shouldBe None
      }
      "return the version when 'Accept' header contains the version" in {
        Versions.getFromRequest(HeaderCarrier().withExtraHeaders((ACCEPT, "application/vnd.hmrc.1.0+json"))) shouldBe Some("1.0")
      }
    }

    "retrieved from a request header" must {
      "work" in {
        Versions.getFromRequest(FakeRequest().withHeaders((ACCEPT, "application/vnd.hmrc.1.0+json"))) shouldBe Some("1.0")
      }
    }
  }

} 
Example 67
Source File: ControllerBaseSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.controllers

import play.api.http.{HeaderNames, MimeTypes, Status}
import play.api.mvc.{AnyContentAsEmpty, ControllerComponents}
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{FakeRequest, ResultExtractors}
import support.UnitSpec

class ControllerBaseSpec extends UnitSpec
  with Status
  with MimeTypes
  with HeaderNames
  with ResultExtractors {

  implicit lazy val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest()

  lazy val cc: ControllerComponents = stubControllerComponents()

  lazy val fakeGetRequest: FakeRequest[AnyContentAsEmpty.type] = fakeRequest.withHeaders(
    HeaderNames.AUTHORIZATION -> "Bearer Token", "X-Client-Id" -> "client-Id"
  )

  def fakePostRequest[T](body: T): FakeRequest[T] = fakeRequest.withBody(body)
} 
Example 68
Source File: HealthControllerSpec.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package controllers

import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play._
import play.api.http.ContentTypes
import play.api.mvc.Result
import play.api.test.Helpers._
import play.api.test.{FakeRequest, Helpers}

import scala.concurrent.Future


class HealthControllerSpec extends PlaySpec with MockitoSugar {

  "The HealthController" must {
    "provide an health status json" in {
      val stubControllerComponents = Helpers.stubControllerComponents()
      val controller = new HealthController(stubControllerComponents)
      val result: Future[Result] = controller.health.apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      contentType(result) mustBe Some(ContentTypes.JSON)
      (contentAsJson(result) \ "name").asOpt[String] mustBe Some("search-management-ui")
    }
  }
} 
Example 69
Source File: CoreOnlySampleSpec.scala    From play-parseq   with Apache License 2.0 5 votes vote down vote up
package controllers.s

import play.api.test.{FakeRequest, PlaySpecification, WithApplication}



  val TestStartIndexFail = 5

  "The CoreOnlySample" should {
    "respond to GET input" in new WithApplication {
      val result = route(app, FakeRequest(GET, routes.CoreOnlySample.input().url)).get
      // Assert the status and the content
      status(result) must equalTo(OK)
      contentType(result) must beSome("text/html")
      contentAsString(result) must contain("Text")
    }

    "respond to GET demo" in new WithApplication {
      val result = route(app, FakeRequest(GET, routes.CoreOnlySample.demo(TextText, TestStartIndex).url)).get
      // Assert the status and the content
      status(result) must equalTo(OK)
      contentType(result) must beSome("text/plain")
      contentAsString(result) must equalTo(TextText.substring(TestStartIndex))
    }

    "respond to GET demo with invalid start index" in new WithApplication {
      val result = route(app, FakeRequest(GET, routes.CoreOnlySample.demo(TextText, TestStartIndexFail).url)).get
      // Assert the status and the content
      status(result) must equalTo(OK)
      contentType(result) must beSome("text/plain")
      contentAsString(result) must equalTo(new CoreOnlySample(null, null)(null).DefaultFailure)
    }
  }

} 
Example 70
Source File: GARedirectControllerSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.http._
import play.api.i18n.Lang
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.nisp.config.wiring.NispFormPartialRetriever
import uk.gov.hmrc.nisp.helpers.MockCachedStaticHtmlPartialRetriever
import uk.gov.hmrc.nisp.utils.MockTemplateRenderer
import uk.gov.hmrc.play.partials.CachedStaticHtmlPartialRetriever
import uk.gov.hmrc.renderer.TemplateRenderer

class GARedirectControllerSpec  extends PlaySpec with MockitoSugar with OneAppPerSuite {

  private implicit val fakeRequest = FakeRequest("GET", "/redirect")
  private implicit val lang = Lang("en")
  private implicit val retriever = MockCachedStaticHtmlPartialRetriever
  implicit val formPartialRetriever: uk.gov.hmrc.play.partials.FormPartialRetriever = NispFormPartialRetriever
  implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer

  val testGARedirectController = new GARedirectController {

    override implicit val cachedStaticHtmlPartialRetriever: CachedStaticHtmlPartialRetriever = retriever

    override implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer
  }

  "GET /redirect" should {
    "return 200" in {
      val result = testGARedirectController.show(fakeRequest)
      status(result) mustBe Status.OK
    }

  }
}