org.scalatestplus.play.PlaySpec Scala Examples

The following examples show how to use org.scalatestplus.play.PlaySpec. 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: 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 2
Source File: CronScheduleSpec.scala    From sundial   with MIT License 5 votes vote down vote up
package model

import java.text.ParseException
import java.util.GregorianCalendar

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatestplus.play.PlaySpec

@RunWith(classOf[JUnitRunner])
class CronScheduleSpec extends PlaySpec {

  "Cron scheduler" should {

    "successfully parse cron entry for 10pm every day" in {
      val cronSchedule = CronSchedule("0", "22", "*", "*", "?")
      val date = new GregorianCalendar(2015, 10, 5, 21, 0).getTime
      val expectedNextDate = new GregorianCalendar(2015, 10, 5, 22, 0).getTime
      val nextDate = cronSchedule.nextRunAfter(date)
      nextDate must be(expectedNextDate)
    }

    "Throw exception on creation if cron schedlue is invalid" in {
      intercept[ParseException] {
        CronSchedule("0", "22", "*", "*", "*")
      }
    }
  }

} 
Example 3
Source File: PostgresJsonMarshallerTest.scala    From sundial   with MIT License 5 votes vote down vote up
package dao.postgres.marshalling

import com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE
import com.hbc.svc.sundial.v2.models.NotificationOptions
import model.{EmailNotification, PagerdutyNotification, Team}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatestplus.play.PlaySpec
import util.Json

@RunWith(classOf[JUnitRunner])
class PostgresJsonMarshallerTest extends PlaySpec {

  private val postgresJsonMarshaller = new PostgresJsonMarshaller()

  private val objectMapper = Json.mapper()
  objectMapper.setPropertyNamingStrategy(SNAKE_CASE)
  //  objectMapper.setVisibility(PropertyAccessor.FIELD,Visibility.ANY)

  "PostgresJsonMarshaller" should {

    "correctly deserialize a json string into Seq[Team]" in {
      val json =
        """
          | [{
          |   "name" : "teamName",
          |   "email" : "teamEmail",
          |   "notify_action": "on_state_change_and_failures"
          | }]
        """.stripMargin

      val expectedTeams: Seq[Team] =
        Vector(Team("teamName", "teamEmail", "on_state_change_and_failures"))
      val actualTeams = postgresJsonMarshaller.toTeams(json)
      actualTeams must be(expectedTeams)
    }

    "correctly serialise a Seq[Team] in a json string" in {
      val expectedJson =
        """
          | [{
          |   "name" : "teamName",
          |   "email" : "teamEmail",
          |   "notify_action": "on_state_change_and_failures"
          | }]
        """.stripMargin
      val expectedTeams: Seq[Team] =
        Vector(Team("teamName", "teamEmail", "on_state_change_and_failures"))
      val actualJson = postgresJsonMarshaller.toJson(expectedTeams)
      objectMapper.readTree(actualJson) must be(
        objectMapper.readTree(expectedJson))
    }

    "correctly deserialize a json string into Seq[Notification]" in {

      val json =
        """
          |[{"name":"name","email":"email","notify_action":"on_state_change_and_failures", "type": "email"},{"service_key":"service-key","api_url":"http://google.com", "type": "pagerduty","num_consecutive_failures":1}]
        """.stripMargin

      val notifications = Vector(
        EmailNotification(
          "name",
          "email",
          NotificationOptions.OnStateChangeAndFailures.toString),
        PagerdutyNotification("service-key", "http://google.com", 1)
      )

      val actualNotifications = postgresJsonMarshaller.toNotifications(json)

      actualNotifications must be(notifications)

    }

    "correctly serialise a Seq[Notification] in a json string" in {

      val json =
        """
          |[{"name":"name","email":"email","notify_action":"on_state_change_and_failures", "type": "email"},{"service_key":"service-key","api_url":"http://google.com", "type": "pagerduty","num_consecutive_failures":1}]
        """.stripMargin

      val notifications = Vector(
        EmailNotification(
          "name",
          "email",
          NotificationOptions.OnStateChangeAndFailures.toString),
        PagerdutyNotification("service-key", "http://google.com", 1)
      )

      println(s"bla1: ${postgresJsonMarshaller.toJson(notifications)}")
      println(s"bla2: ${objectMapper.writeValueAsString(notifications)}")

      objectMapper.readTree(json) must be(
        objectMapper.readTree(postgresJsonMarshaller.toJson(notifications)))

    }

  }

} 
Example 4
Source File: HierarchyRepositoryTest.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package repositories


import anorm.SqlParser.scalar
import anorm._
import models._
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.db.Database
import play.api.test.Injecting

class HierarchyRepositoryTest extends PlaySpec with GuiceOneServerPerSuite with Injecting with BeforeAndAfterEach {
  val db = inject[Database]
  val hierarchyRepository = inject[HierarchyRepository]
  val hierarchyNode1 = HierarchyNode("id1", "slugName1", "name1", "childrenLabel1", "childLabel1")
  val hierarchyNode2 = HierarchyNode("id2", "slugName2", "name2", "childrenLabel2", "childLabel2")

  val hierarchyNodes = Seq(hierarchyNode1, hierarchyNode2)

  override def beforeEach(): Unit = {
    db.withConnection { implicit connection =>
      hierarchyNodes.foreach { hierarchyNode =>
        SQL"""INSERT INTO hierarchyNode (id, slugName, name, childrenLabel, childLabel)
             VALUES (${hierarchyNode.id}, ${hierarchyNode.slugName}, ${hierarchyNode.name}, ${hierarchyNode.childrenLabel}, ${hierarchyNode.childLabel})""".executeInsert()
      }
    }
  }

  override def afterEach(): Unit = {
    db.withConnection { implicit connection =>
      SQL"TRUNCATE TABLE hierarchyNode".executeUpdate()
      SQL"TRUNCATE TABLE project_hierarchyNode".executeUpdate()
      SQL"TRUNCATE TABLE project".executeUpdate()
      ()
    }
  }

  "HierarchyRepository" should {
    "find all hierarchyNodes" in {
      hierarchyRepository.findAll() must contain theSameElementsAs hierarchyNodes
    }

    "find an hierarchyNode by id" in {
      hierarchyRepository.findById(hierarchyNode1.id) mustBe Some(hierarchyNode1)
    }

    "find an hierarchyNode by slugName" in {
      hierarchyRepository.findBySlugName(hierarchyNode1.slugName) mustBe Some(hierarchyNode1)
    }

    "delete all hierarchyNodes" in {
      hierarchyRepository.deleteAll()

      db.withConnection { implicit connection =>
        SQL"SELECT COUNT(*) FROM hierarchyNode".as(scalar[Long].single) mustBe 0
      }
    }

    "delete an hierarchyNode" in {
      hierarchyRepository.deleteById(hierarchyNode1.id)

      db.withConnection { implicit connection =>
        SQL"SELECT COUNT(*) FROM hierarchyNode WHERE id = ${hierarchyNode1.id}".as(scalar[Long].single) mustBe 0
      }
    }

    "check if an hierarchyNode exist by id" in {
      hierarchyRepository.existsById(hierarchyNode1.id) mustBe true
    }

    "save an hierarchyNode" in {
      val hierarchyNode3 = HierarchyNode("id3", "slugName3", "name3", "childrenLabel3", "childLabel3")
      hierarchyRepository.save(hierarchyNode3)
      hierarchyRepository.findById(hierarchyNode3.id) mustBe Some(hierarchyNode3)
    }

    "save all hierarchyNodes" in {
      val newHierarchyNodes = Seq(HierarchyNode("id4", "slugName4", "name4", "childrenLabel4", "childLabel4"), HierarchyNode("id5", "slugName5", "name5", "childrenLabel5", "childLabel5"))
      hierarchyRepository.saveAll(newHierarchyNodes)
      hierarchyRepository.findAll() must contain theSameElementsAs (newHierarchyNodes :+ hierarchyNode1 :+ hierarchyNode2)
    }

    "find hierarchyNodes by projectId" in {
      db.withConnection { implicit connection =>
        SQL"INSERT INTO project (id, name, repositoryUrl, stableBranch,featuresRootPath,documentationRootPath) VALUES ('id1', 'name1', 'repositoryUrl1', 'stableBranch1', 'featuresRootPath1', '/doc')".executeInsert()
        SQL"INSERT INTO project_hierarchyNode (projectId, hierarchyId) VALUES ('id1', 'id1')".executeInsert()
        SQL"INSERT INTO project_hierarchyNode (projectId, hierarchyId) VALUES ('id1', 'id2')".executeInsert()
      }
      hierarchyRepository.findAllByProjectId("id1") must contain theSameElementsAs Seq(hierarchyNode1, hierarchyNode2)
    }
  }
} 
Example 5
Source File: GherkinRepositoryTest.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package repositories

import anorm._
import controllers.dto.ProjectDocumentationDTO
import models._
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.db.Database
import play.api.test.Injecting

class GherkinRepositoryTest extends PlaySpec with GuiceOneServerPerSuite with Injecting with BeforeAndAfterEach {

  val db = inject[Database]

  val projectRepository = inject[ProjectRepository]
  val branchRepository = inject[BranchRepository]
  val featureRepository = inject[FeatureRepository]
  val scenarioRepository = inject[ScenarioRepository]

  val gherkinRepository = inject[GherkinRepository]

  val node = HierarchyNode(".01.", "eng", "Eng", "Systems", "System")
  val project1 = Project("project1", "Project 1", "repositoryUrl1", None, "branch2", None, Some("featuresRootPath1"), None)
  val branch1 = Branch(1, "branch1", isStable = false, "project1")
  val branch2 = Branch(2, "branch2", isStable = true, "project1")
  val feature1 = Feature(1, 1, "path1", None, Seq(), Some("language1"), "keyword1", "feature1", "description1", Seq(), Seq("comments1"))
  val feature2 = Feature(2, 1, "path2", None, Seq(), Some("language2"), "keyword2", "feature2", "description2", Seq(), Seq("comments1"))
  val scenario1 = Scenario(1, Seq("s_tag1", "s_tag2"), "abstractionLevel1", "caseType1", "workflowStep1", "keyword1", "scenario1", "description1", Seq(Step(1, "keyword1", "text1", Seq(Seq("argument1")), None)))
  val scenario2 = Scenario(2, Seq("s_tag2", "s_tag3"), "abstractionLevel1", "caseType1", "workflowStep1", "keyword1", "scenario2", "description1", Seq(Step(2, "keyword1", "text1", Seq(Seq("argument1")), None)))
  val scenario3 = Scenario(3, Seq("s_tag1", "s_tag3"), "abstractionLevel1", "caseType1", "workflowStep1", "keyword1", "scenario3", "description1", Seq(Step(3, "keyword1", "text1", Seq(Seq("argument1")), None)))


  override def beforeEach(): Unit = {
    projectRepository.saveAll(Seq(project1))
    branchRepository.saveAll(Seq(branch1, branch2))
    featureRepository.saveAll(Seq(feature1, feature2))
    scenarioRepository.saveAll(1, Seq(scenario1, scenario2))
    scenarioRepository.saveAll(2, Seq(scenario3))
    ()
  }

  override def afterEach(): Unit = {
    db.withConnection { implicit connection =>
      SQL"TRUNCATE TABLE project".executeUpdate()
      SQL"TRUNCATE TABLE branch".executeUpdate()
      SQL"TRUNCATE TABLE feature".executeUpdate()
      SQL"TRUNCATE TABLE feature_tag".executeUpdate()
      SQL"TRUNCATE TABLE scenario".executeUpdate()
      SQL"TRUNCATE TABLE scenario_tag".executeUpdate()
      SQL"TRUNCATE TABLE tag".executeUpdate()
      ()
    }
  }

  "DocumentationRepository" should {

    "build documentation from " in {
      val documentation: ProjectDocumentationDTO = gherkinRepository.buildProjectGherkin(ProjectMenuItem(project1.id, project1.name, branch1.name))

      documentation.id mustBe project1.id
      documentation.name mustBe project1.name
      documentation.branches.size mustBe 1
      documentation.branches.head.id mustBe branch1.id
      documentation.branches.head.name mustBe branch1.name
      documentation.branches.head.isStable mustBe branch1.isStable
      documentation.branches.head.features.size mustBe 2

      documentation.branches.head.features.head.id mustBe feature1.id
      documentation.branches.head.features.head.path mustBe feature1.path
      documentation.branches.head.features.head.scenarios.size mustBe 2
      documentation.branches.head.features.head.scenarios.head.id mustBe scenario1.id
      documentation.branches.head.features.head.scenarios(1).id mustBe scenario2.id
      documentation.branches.head.features.head.scenarios.head.name mustBe scenario1.name
      documentation.branches.head.features.head.scenarios(1).name mustBe scenario2.name

      documentation.branches.head.features(1).id mustBe feature2.id
      documentation.branches.head.features(1).path mustBe feature2.path
      documentation.branches.head.features(1).scenarios.size mustBe 1
      documentation.branches.head.features(1).scenarios.head.id mustBe scenario3.id
      documentation.branches.head.features(1).scenarios.head.name mustBe scenario3.name


      documentation.branches.head.features.head.tags mustBe Seq()
      documentation.branches.head.features(1).tags mustBe Seq()
      documentation.branches.head.features.head.scenarios.head.asInstanceOf[Scenario].tags mustBe Seq("s_tag1", "s_tag2")
      documentation.branches.head.features.head.scenarios(1).asInstanceOf[Scenario].tags mustBe Seq("s_tag2", "s_tag3")
      documentation.branches.head.features(1).scenarios.head.asInstanceOf[Scenario].tags mustBe Seq("s_tag1", "s_tag3")
    }
  }
} 
Example 6
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 7
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 8
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 9
Source File: ApplicationSpec.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api

import org.scalatestplus.play.PlaySpec
import play.api.ApplicationLoader.Context
import play.api.test.Helpers._
import play.api.test._


class ApplicationSpec extends PlaySpec with OneAppPerTestWithComponents[MockApiComponents] {

  override def createComponents(context: Context) = new MockApiComponents(context)

  "Routes" should {
    "send 404 on a bad request" in {
      route(app, FakeRequest(GET, "/boum")).map(status) mustBe Some(NOT_FOUND)
    }
  }

  "HomeController" should {
    "render the index page" in {
      val home = route(app, FakeRequest(GET, "/ping")).get
      status(home) mustBe OK
      contentType(home) mustBe Some("text/plain")
      contentAsString(home) must include("pong")
    }
  }
} 
Example 10
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 11
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 12
Source File: PlayScalaTestSpec.scala    From play-grpc   with Apache License 2.0 5 votes vote down vote up
package play.grpc.scalatest

import io.grpc.Status

import org.scalatest.concurrent.IntegrationPatience
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneServerPerTest

import play.api.Application
import play.api.inject.bind
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.WSClient
import play.api.routing.Router

import akka.grpc.internal.GrpcProtocolNative

import example.myapp.helloworld.grpc.helloworld._


class PlayScalaTestSpec
    extends PlaySpec
    with GuiceOneServerPerTest
    with ServerGrpcClient
    with ScalaFutures
    with IntegrationPatience {

  override def fakeApplication(): Application = {
    GuiceApplicationBuilder()
      .overrides(bind[Router].to[GreeterServiceImpl])
      .build()
  }

  implicit def ws: WSClient = app.injector.instanceOf(classOf[WSClient])

  "A Play server bound to a gRPC router" must {
    "give a 404 when routing a non-gRPC request" in {
      val result = wsUrl("/").get.futureValue
      result.status must be(404) // Maybe should be a 426, see #396
    }
    "give a 415 error when not using a gRPC content-type" in {
      val result = wsUrl(s"/${GreeterService.name}/FooBar").get.futureValue
      result.status must be(415)
    }
    "give a grpc 'unimplemented' error when routing a non-existent gRPC method" in {
      val result = wsUrl(s"/${GreeterService.name}/FooBar")
        .addHttpHeaders("Content-Type" -> GrpcProtocolNative.contentType.toString)
        .get
        .futureValue
      result.status must be(200) // Maybe should be a 426, see #396
      result.header("grpc-status") mustEqual Some(Status.Code.UNIMPLEMENTED.value().toString)
    }
    "give a grpc 'invalid argument' error when routing an empty request to a gRPC method" in {
      val result = wsUrl(s"/${GreeterService.name}/SayHello")
        .addHttpHeaders("Content-Type" -> GrpcProtocolNative.contentType.toString)
        .get
        .futureValue
      result.status must be(200)
      result.header("grpc-status") mustEqual Some(Status.Code.INVALID_ARGUMENT.value().toString)
    }
    "work with a gRPC client" in withGrpcClient[GreeterServiceClient] { client: GreeterServiceClient =>
      val reply = client.sayHello(HelloRequest("Alice")).futureValue
      reply.message must be("Hello, Alice!")
    }
  }
} 
Example 13
Source File: ConfigParsingSpec.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package backend

import com.typesafe.config.{Config, ConfigFactory}
import com.agilelab.dataquality.common.models.DatabaseCommon
import com.agilelab.dataquality.common.parsers.DQConfig
import com.agilelab.dataquality.common.parsers.DQConfig.AllErrorsOr
import models.config.ConfigReader
import models.sources.Database
import org.scalatestplus.play.PlaySpec

class ConfigParsingSpec extends PlaySpec {

  "Config parser" must {

    val config1: Config = ConfigFactory.parseURL(getClass.getResource("/test1.conf")).resolve()
    val config2: Config = ConfigFactory.parseURL(getClass.getResource("/test2.conf")).resolve()

    "return correct order from config1" in {
      val testOrder: String = "GetYear, YearWrongValues, TipoPrestazione, EstrazioneCodiceGenereDaCF, EstrazioneGenereDaCF, TipoPrestazioneTransform"
      val resOrder: String = ConfigReader.parseVirtualSources(config1).map(_._1).mkString(", ")

      assert(testOrder == resOrder)
    }

    "parse each object separetely" in {
      import scala.collection.JavaConverters._
      import com.agilelab.dataquality.common.instances.ConfigReaderInstances.databaseReader

      val dbConf = config1.getConfigList("Databases").asScala
      dbConf.map(x => DQConfig.parse[DatabaseCommon](x)).foreach(println)
    }

    "get all databases" in {
      val res: AllErrorsOr[Seq[Database]] = ConfigReader.parseDatabases(config1)
      println(res)
      assert(res.isValid)
    }

    "get errors" in {
      val list: AllErrorsOr[Seq[Database]] = ConfigReader.parseDatabases(config2)
      assert(list.isInvalid)
      list.valueOr(_.toList).foreach(println)
    }
  }

} 
Example 14
Source File: UtilSpec.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package backend

import com.agilelab.dataquality.common.enumerations.DBTypes
import org.scalatestplus.play.PlaySpec

class UtilSpec extends PlaySpec {

  "ui" must {
    "have access to other module code" in {
      assert(DBTypes.names == Set("ORACLE", "POSTGRES", "SQLITE"))
    }
  }

  "test" must{
    "toast" in {
      def f(i: Int, enums: Set[Any]*): Set[Any] = {
        if (enums.nonEmpty && i >= 0 && i < enums.size) enums(i)
        else Set("huj")
      }

      println(
        f(1, Set(1,2,3), Set(2,3,4))
      )
    }
  }

} 
Example 15
Source File: WordVectorSpec.scala    From tap   with Apache License 2.0 5 votes vote down vote up
package io.heta.tap

import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder

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

class WordVectorSpec extends PlaySpec{

  //dependency injection
  private val app = new GuiceApplicationBuilder().build
  private val wordvector = app.injector.instanceOf[WordVector]

  "find neareast words" in  {
    val lst = wordvector.nearestWords("day", 10)
    val result = Await.result(lst, 360 seconds)

    if(result!= None){
      assert(result.get(0) == "week")
      assert(result.get(1) == "days")
      assert(result.get(2) == "morning")
      assert(result.get(3) == "month")
      assert(result.get(4) == "hours")
      assert(result.get(5) == "afternoon")
      assert(result.get(6) == "hour")
      assert(result.get(7) == "weekend")
      assert(result.get(8) == "evening")
      assert(result.get(9) == "time")
    }
  }

} 
Example 16
Source File: ApplicationSpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
import org.scalatest.Matchers._
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Seconds, Span}
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.libs.ws.WSClient
import play.api.test.Helpers._
import scala.concurrent.duration._



class ApplicationSpec extends PlaySpec with ScalaFutures with GuiceOneServerPerSuite {
  "Application" should {
    val wsClient = app.injector.instanceOf[WSClient]
    val myPublicAddress = s"localhost:$port"

    "send 404 on a bad request" in {
      val testURL = s"http://$myPublicAddress/boom"

      whenReady(wsClient.url(testURL).get(), Timeout(1 second)) { response =>
        response.status mustBe NOT_FOUND
      }
    }

    "render the index page" in {
      val testURL = s"http://$myPublicAddress/"

      whenReady(wsClient.url(testURL).get(), Timeout(1 second)) { response =>
        response.status mustBe OK
        response.contentType should include("text/html")
      }
    }
  }
} 
Example 17
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 18
Source File: UrlsSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package io.flow.dependency.lib

import io.flow.dependency.v0.models.{ItemSummaryUndefinedType, RecommendationType}
import org.scalatestplus.play.PlaySpec
import io.flow.util.Config

class UrlsSpec extends PlaySpec with Factories {

  private[this] lazy val urls = Urls(
    new Config {
      override def optionalMap(name: String): Option[Map[String, Seq[String]]] = None
      override def optionalString(name: String): Option[String] = {
        if (name == "dependency.www.host")  {
          Some("http://localhost")
        } else {
          None
        }
      }

      override def optionalList(name: String): Option[Seq[String]] = {
        if (name == "dependency.www.host")  {
          Some(Seq("http://localhost"))
        } else {
          None
        }
      }

      override def get(name: String): Option[String] =
        if (name == "dependency.www.host")  {
          Some("http://localhost")
        } else {
          None
        }
    }
  )

  "www" in  {
    urls.www("/foo") must be("http://localhost/foo")
  }

  "recommendation" in  {
    val binary = makeRecommendation(`type` = RecommendationType.Binary)
    urls.recommendation(binary) must be(s"/binaries/${binary.`object`.id}")

    val library = makeRecommendation(`type` = RecommendationType.Library)
    urls.recommendation(library) must be(s"/libraries/${library.`object`.id}")

    val other = makeRecommendation(`type` = RecommendationType.UNDEFINED("other"))
    urls.recommendation(other) must be("#")
  }

  "itemSummary" in  {
    val binary = makeBinarySummary()
    urls.itemSummary(binary) must be(s"/binaries/${binary.id}")

    val library = makeLibrarySummary()
    urls.itemSummary(library) must be(s"/libraries/${library.id}")

    val project = makeProjectSummary()
    urls.itemSummary(project) must be(s"/projects/${project.id}")

    urls.itemSummary(ItemSummaryUndefinedType("other")) must be("#")
  }

} 
Example 19
Source File: ControllerTest.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package test

import model.json.ResultMessage
import org.scalatest.{Assertion, BeforeAndAfterAll}
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.mvc.Result
import play.api.test.Helpers._
import play.test.WithApplication

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._


  override def afterAll() {
    application.stopPlay()
  }

  def assertFutureResultStatus(future: Future[Result], status: Int) = {
    val result: Result = Await.result(future, 20 seconds)
    if(result.header.status != status){
      play.Logger.error(contentAsString(future))
    }
    assert(result.header.status == status)
  }

  def assertBodyJsonMessage(future: Future[Result], message: String, emptyExtras: Boolean): Assertion = {
    //val result: Result = Await.result(future,20 seconds)
    val bodyJson = contentAsJson(future)
    play.Logger.debug(s"BodyJson: $bodyJson")
    val jsResult = bodyJson.validate[ResultMessage]
    assert(jsResult.isSuccess)
    if(!emptyExtras) {
      assert(jsResult.get.extras.nonEmpty)
      if(jsResult.get.extras.isEmpty){
        play.Logger.debug(jsResult.toString)
      }
    }
    assert(jsResult.get.result === message)
  }

  def assertBodyJsonMessage(future: Future[Result], message: String): Assertion = {
    assertBodyJsonMessage(future, message, emptyExtras = true)
  }
} 
Example 20
Source File: ServiceTest.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package test

import org.scalatest.BeforeAndAfterAll
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.mvc.Result
import play.test.WithApplication
import services.state.ActionState

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._


  override def afterAll() {
    application.stopPlay()
  }

  def assertState(future: Future[ActionState], actionState: ActionState) = {
    val result = Await.result(future, 20 seconds)
    assert(result === actionState)
  }

  def waitFor[T](future: Future[T]): T = {
    Await.result(future, 20 seconds)
  }
} 
Example 21
Source File: ApplicationSpec.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package controllers

import modules.{Database, DatabaseMock}
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.Mode
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder

import scala.xml.Comment

class ApplicationSpec extends PlaySpec with GuiceOneAppPerTest {

  override implicit def fakeApplication() = new GuiceApplicationBuilder()
    .overrides(bind[Database].to[DatabaseMock])
    .configure(
      Map(
        "play.modules.disabled" -> Seq("org.flywaydb.play.PlayModule", "modules.DatabaseModule")
      )
    )
    .in(Mode.Test)
    .build()

  lazy val applicationController = app.injector.instanceOf[Application]

  "svgNode" must {
    "work" in {
      val svg = applicationController.svgSymbol("custom-sprite/svg/symbols.svg", "custom16")
      svg.attribute("d") mustBe 'defined
    }
    "produce a comment when the file can't be found" in {
      val svg = applicationController.svgSymbol("asdfasdf", "custom16")
      svg mustBe a [Comment]
    }
    "produce a comment when the symbol can't be found" in {
      val svg = applicationController.svgSymbol("custom-sprite/svg/symbols.svg", "asdf")
      svg mustBe a [Comment]
    }
  }

} 
Example 22
Source File: DBSpec.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package utils

import java.time.LocalDateTime

import models.{ClaSignature, Contact}
import modules.Database
import org.flywaydb.play.PlayInitializer
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.Helpers._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Try


class DBSpec extends PlaySpec with GuiceOneAppPerSuite {

  val dbUrl = sys.env.getOrElse("DATABASE_URL", "postgres://salesforcecla:password@localhost:5432/salesforcecla-test")

  val testConfig = Map("db.default.url" -> dbUrl)

  implicit override def fakeApplication() = new GuiceApplicationBuilder().configure(testConfig).build()

  lazy val database = app.injector.instanceOf[Database]
  lazy val db = app.injector.instanceOf[DB]
  lazy val playIntializer = app.injector.instanceOf[PlayInitializer]

  Try(await(database.ctx.executeQuery("drop schema salesforce cascade")))
  Try(await(database.ctx.executeQuery("drop table schema_version")))

  playIntializer.onStart()

  "Contact" must {
    "be creatable" in {
      val contact = await(db.createContact(Contact(-1, Some("foo"), "bar", "[email protected]", "foobar")))
      contact.id must not equal -1
    }
    "be creatable with null firstname" in {
      val contact = await(db.createContact(Contact(-1, None, "blah", "[email protected]", "blah")))
      contact.id must not equal -1
    }
    "be able to get one that exists by the gitHubId" in {
      val contact = await(db.findContactByGitHubId("foobar"))
      contact mustBe 'defined
    }
    "fail to get one that doesn't exist by a gitHubId" in {
      val contact = await(db.findContactByGitHubId("asdf"))
      contact mustBe None
    }
    "work with null firstname" in {
      val contact = await(db.findContactByGitHubId("blah"))
      contact mustBe 'defined
      contact.get.firstName mustBe empty
    }
  }

  "ClaSignature" must {
    "be creatable" in {
      val contact = Contact(-1, Some("foo"), "bar", "[email protected]", "foobar")
      val claSignature = await(db.createClaSignature(ClaSignature(-1, contact.gitHubId, LocalDateTime.now(), "0.0.0")))
      claSignature.id must not equal -1
    }
    "be queryable with one github id" in {
      val claSignatures = await(db.findClaSignaturesByGitHubIds(Set(GitHub.User("foobar"))))
      claSignatures.size mustEqual 1
      claSignatures.head.contactGitHubId mustEqual "foobar"
    }
    "be queryable with a set of github ids" in {
      val claSignatures = await(db.findClaSignaturesByGitHubIds(Set(GitHub.User("foobar"), GitHub.User("jondoe"))))
      claSignatures.size mustEqual 1
      claSignatures.head.contactGitHubId mustEqual "foobar"
    }
  }

  "Contact.fullNameToFirstAndLast" must {
    "work with no names" in {
      Contact.fullNameToFirstAndLast("") must equal (None, None)
    }
    "work with one name" in {
      Contact.fullNameToFirstAndLast("Foo") must equal (None, Some("Foo"))
    }
    "work with two names" in {
      Contact.fullNameToFirstAndLast("Foo Bar") must equal (Some("Foo"), Some("Bar"))
    }
    "work with three names" in {
      Contact.fullNameToFirstAndLast("Foo Baz Bar") must equal (Some("Foo Baz"), Some("Bar"))
    }
  }

} 
Example 23
Source File: CryptoSpec.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package utils

import modules.{Database, DatabaseMock}
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.Mode
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder

class CryptoSpec extends PlaySpec with GuiceOneAppPerTest {

  override implicit def fakeApplication() = new GuiceApplicationBuilder()
    .overrides(bind[Database].to[DatabaseMock])
    .configure(
      Map(
        "play.modules.disabled" -> Seq("org.flywaydb.play.PlayModule", "modules.DatabaseModule")
      )
    )
    .in(Mode.Test)
    .build()

  lazy val crypto = new Crypto(app.configuration)

  "encryptAES and decryptAES" must {
    "work" in {
      val encrypted = crypto.encryptAES("hello, world")
      encrypted.length must equal (24)
      crypto.decryptAES(encrypted) must equal ("hello, world")
    }
  }

} 
Example 24
Source File: FiltersSpec.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package utils

import modules.{Database, DatabaseMock}
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.Mode
import play.api.http.HeaderNames
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc._
import play.api.test.Helpers._
import play.api.test._

class FiltersSpec extends PlaySpec with GuiceOneAppPerTest {

  lazy val appBuilder = new GuiceApplicationBuilder()
    .overrides(bind[Database].to[DatabaseMock])
    .configure("play.modules.disabled" -> Seq("org.flywaydb.play.PlayModule", "modules.DatabaseModule"))
    .in(Mode.Test)

  override def fakeApplication() = appBuilder.build()

  "Filters" must {
    "redirect to https if the request was forwarded and not https" in {
      val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.signedCla(None).url, Headers(HeaderNames.X_FORWARDED_PROTO -> "http"), AnyContentAsEmpty))
      status(result) mustEqual MOVED_PERMANENTLY
    }
    "not force https for well-known requests" in {
      val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.wellKnown("test").url))
      status(result) mustEqual NOT_FOUND
    }
    "not force https for non-forwarded requests" in {
      val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.signedCla(None).url))
      status(result) mustEqual OK
    }
    "keep https for non-well-known requests" in {
      val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.signedCla(None).url, Headers(HeaderNames.X_FORWARDED_PROTO -> "https"), AnyContentAsEmpty))
      status(result) mustEqual OK
    }
    "return the well known value when the WELL_KNOWN env var is set" in {
      implicit val app = appBuilder.configure("wellknown" -> "foo=bar").build()
      val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.wellKnown("foo").url))
      status(result) mustEqual OK
      contentAsString(result) mustEqual "bar"
    }
    "not leak well known values" in {
      implicit val app = appBuilder.configure("wellknown" -> "foo=bar").build()
      val Some(result) = route(app, FakeRequest(GET, controllers.routes.Application.wellKnown("").url))
      status(result) mustEqual NOT_FOUND
    }
  }

} 
Example 25
Source File: ViewHelpersSpec.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package helpers

import org.scalatest.Matchers._
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.Mode
import play.api.inject.guice.GuiceApplicationBuilder

class ViewHelpersSpec extends PlaySpec with GuiceOneAppPerTest {
  val testOrgName = "Test Org Name"
  val testOrgUrl = "http://orgurl.org"
  val testOrgLogoUrl = "image.jpg"

  override implicit def fakeApplication() = new GuiceApplicationBuilder()
    .configure(
      Map(
        "app.organization.name" -> testOrgName,
        "app.organization.url" -> testOrgUrl,
        "app.organization.logo-url"-> testOrgLogoUrl
      )
    )
    .in(Mode.Test)
    .build()

  def viewHelper = app.injector.instanceOf[ViewHelpers]

  "ViewHelper" must {
    "give a valid organization name" in {
      val orgName = viewHelper.organizationName
      orgName mustBe a [String]
      orgName mustEqual testOrgName
    }
    "give a valid organization URL" in {
      val orgUrl = viewHelper.maybeOrganizationUrl
      orgUrl shouldBe defined
      orgUrl should contain (testOrgUrl)
    }
    "give a valid organization logo URL" in {
      val orgLogoUrl = viewHelper.maybeOrganizationLogoUrl
      orgLogoUrl shouldBe defined
      orgLogoUrl should contain (testOrgLogoUrl)
    }
    // todo: test loading the sample CLA in dev mode
  }
} 
Example 26
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
    }

  }
} 
Example 27
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 28
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 29
Source File: IntegrationSpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.libs.ws.WSClient

import scala.concurrent.duration.DurationInt
import scala.concurrent.Await
import org.scalatest._
import Matchers._

class IntegrationSpec extends PlaySpec with GuiceOneServerPerSuite {
  "Application" should {
    val wsClient = app.injector.instanceOf[WSClient]
    val myPublicAddress = s"localhost:$port"
    "work from within a browser" in {

      val testURL = s"http://$myPublicAddress/"

      val response = Await.result(wsClient.url(testURL).get(), 1 seconds)

      response.body should include ("<title>Shopping Page</title>")
    }
  }
}