org.scalatestplus.mockito.MockitoSugar Scala Examples

The following examples show how to use org.scalatestplus.mockito.MockitoSugar. 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: StatusRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

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

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

  def actorRefFactory: ActorSystem = system

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

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

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

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

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

        // remember, the signal is the opposite of intent
        processingDisabled.get.unsafeRunSync() shouldBe false
      }
    }
  }
} 
Example 3
Source File: HttpVerbSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import java.util

import com.typesafe.config.Config
import org.mockito.Matchers.any
import org.mockito.Mockito.when
import org.scalatest.LoneElement
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import uk.gov.hmrc.http.logging.{Authorization, ForwardedFor, RequestId, SessionId}

class HttpVerbSpec extends AnyWordSpecLike with Matchers with MockitoSugar with LoneElement {

  "applicableHeaders" should {

    "should contain the values passed in by header-carrier" in {
      val url = "http://test.me"

      implicit val hc = HeaderCarrier(
        authorization = Some(Authorization("auth")),
        sessionId     = Some(SessionId("session")),
        requestId     = Some(RequestId("request")),
        token         = Some(Token("token")),
        forwarded     = Some(ForwardedFor("forwarded"))
      )

      val httpRequest = new HttpVerb {
        override def configuration: Option[Config] = None
      }
      val result = httpRequest.applicableHeaders(url)

      result shouldBe hc.headers
    }

    "should include the User-Agent header when the 'appName' config value is present" in {

      val mockedConfig = mock[Config]
      when(mockedConfig.getStringList(any())).thenReturn(new util.ArrayList[String]())
      when(mockedConfig.getString("appName")).thenReturn("myApp")
      when(mockedConfig.hasPathOrNull("appName")).thenReturn(true)

      val httpRequest = new HttpVerb {
        override def configuration: Option[Config] = Some(mockedConfig)
      }
      val result = httpRequest.applicableHeaders("http://test.me")(HeaderCarrier())

      result.contains("User-Agent" -> "myApp") shouldBe true
    }

    "filter 'remaining headers' from request for external service calls" in {

      implicit val hc = HeaderCarrier(
        otherHeaders = Seq("foo" -> "secret!")
      )

      val httpRequest = new HttpVerb {
        override def configuration: Option[Config] = None
      }
      val result = httpRequest.applicableHeaders("http://test.me")
      result.map(_._1) should not contain "foo"
    }

    "include 'remaining headers' in request for internal service call to .service URL" in {
      implicit val hc = HeaderCarrier(
        otherHeaders = Seq("foo" -> "secret!")
      )
      val httpRequest = new HttpVerb {
        override def configuration: Option[Config] = None
      }

      for { url <- List("http://test.public.service/bar", "http://test.public.mdtp/bar") } {

        val result = httpRequest.applicableHeaders(url)
        assert(result.contains("foo" -> "secret!"), s"'other/remaining headers' for $url were not present")

      }
    }

    "include 'remaining headers' in request for internal service call to other configured internal URL pattern" in {
      val url = "http://localhost/foo" // an internal service call, according to config
      implicit val hc = HeaderCarrier(
        otherHeaders = Seq("foo" -> "secret!")
      )

      import scala.collection.JavaConversions._
      val mockedConfig = mock[Config]
      when(mockedConfig.getStringList("internalServiceHostPatterns")).thenReturn(List("localhost"))
      when(mockedConfig.hasPathOrNull("internalServiceHostPatterns")).thenReturn(true)

      val httpRequest = new HttpVerb {
        override def configuration: Option[Config] = Some(mockedConfig)
      }
      val result = httpRequest.applicableHeaders(url)
      result.contains("foo" -> "secret!") shouldBe true
    }

  }

} 
Example 4
Source File: HttpDeleteSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import akka.actor.ActorSystem
import com.typesafe.config.Config
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.{any, eq => is}
import org.mockito.Mockito._
import org.scalatest.concurrent.PatienceConfiguration.{Interval, Timeout}
import org.scalatest.time.{Millis, Seconds, Span}
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar
import uk.gov.hmrc.http.hooks.HttpHook

import scala.concurrent.{ExecutionContext, Future}

import uk.gov.hmrc.http.HttpReads.Implicits._

class HttpDeleteSpec extends AnyWordSpecLike with Matchers with MockitoSugar with CommonHttpBehaviour {

  import ExecutionContext.Implicits.global

  class StubbedHttpDelete(doDeleteResult: Future[HttpResponse], doDeleteWithHeaderResult: Future[HttpResponse]) extends HttpDelete with ConnectionTracingCapturing {
    val testHook1                                   = mock[HttpHook]
    val testHook2                                   = mock[HttpHook]
    val hooks                                       = Seq(testHook1, testHook2)
    override def configuration: Option[Config]      = None
    override protected def actorSystem: ActorSystem = ActorSystem("test-actor-system")

    def appName: String = ???

    def doDelete(url: String, headers: Seq[(String, String)])(implicit hc: HeaderCarrier, ec: ExecutionContext) =
      doDeleteResult
  }

  "HttpDelete" should {
    "be able to return plain responses" in {
      val response   = HttpResponse(200, testBody)
      val testDelete = new StubbedHttpDelete(Future.successful(response), Future.successful(response))
      testDelete.DELETE[HttpResponse](url, Seq("foo" -> "bar")).futureValue shouldBe response
    }

    "be able to return objects deserialised from JSON" in {
      val testDelete = new StubbedHttpDelete(Future.successful(HttpResponse(200, """{"foo":"t","bar":10}""")),
        Future.successful(HttpResponse(200, """{"foo":"t","bar":10}""")))
      testDelete
        .DELETE[TestClass](url, Seq("foo" -> "bar"))
        .futureValue(Timeout(Span(2, Seconds)), Interval(Span(15, Millis))) shouldBe TestClass("t", 10)
    }

    behave like anErrorMappingHttpCall("DELETE", (url, responseF) => new StubbedHttpDelete(responseF, responseF).DELETE[HttpResponse](url, Seq("foo" -> "bar")))
    behave like aTracingHttpCall("DELETE", "DELETE", new StubbedHttpDelete(defaultHttpResponse, defaultHttpResponse)) { _.DELETE[HttpResponse](url, Seq("foo" -> "bar")) }

    "Invoke any hooks provided" in {
      val dummyResponse       = HttpResponse(200, testBody)
      val dummyResponseFuture = Future.successful(dummyResponse)
      val dummyHeader         = Future.successful(dummyResponse)
      val testDelete          = new StubbedHttpDelete(dummyResponseFuture, dummyHeader)

      testDelete.DELETE[HttpResponse](url, Seq("header" -> "foo")).futureValue

      val respArgCaptor1 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]])
      val respArgCaptor2 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]])

      verify(testDelete.testHook1).apply(is(url), is("DELETE"), is(None), respArgCaptor1.capture())(any(), any())
      verify(testDelete.testHook2).apply(is(url), is("DELETE"), is(None), respArgCaptor2.capture())(any(), any())

      // verifying directly without ArgumentCaptor didn't work as Futures were different instances
      // e.g. Future.successful(5) != Future.successful(5)
      respArgCaptor1.getValue.futureValue shouldBe dummyResponse
      respArgCaptor2.getValue.futureValue shouldBe dummyResponse
    }
  }
} 
Example 5
Source File: HttpPatchSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import akka.actor.ActorSystem
import com.typesafe.config.Config
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.{any, eq => is}
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{Json, Writes}
import uk.gov.hmrc.http.hooks.{HookData, HttpHook}

import scala.concurrent.{ExecutionContext, Future}

import uk.gov.hmrc.http.HttpReads.Implicits._

class HttpPatchSpec extends AnyWordSpecLike with Matchers with CommonHttpBehaviour {
  import ExecutionContext.Implicits.global

  class StubbedHttpPatch(doPatchResult: Future[HttpResponse], doPatchWithHeaderResult: Future[HttpResponse])
      extends HttpPatch
      with ConnectionTracingCapturing
      with MockitoSugar {
    val testHook1                                   = mock[HttpHook]
    val testHook2                                   = mock[HttpHook]
    val hooks                                       = Seq(testHook1, testHook2)
    override def configuration: Option[Config]      = None
    override protected def actorSystem: ActorSystem = ActorSystem("test-actor-system")

    def doPatch[A](url: String, body: A, headers: Seq[(String, String)])(implicit rds: Writes[A], hc: HeaderCarrier, ec: ExecutionContext) =
      doPatchResult
  }

  "HttpPatch" should {
    val testObject = TestRequestClass("a", 1)
    "be able to return plain responses" in {
      val response  = HttpResponse(200, testBody)
      val testPatch = new StubbedHttpPatch(Future.successful(response), Future.successful(response))
      testPatch.PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo")).futureValue shouldBe response
    }
    "be able to return objects deserialised from JSON" in {
      val response= Future.successful(HttpResponse(200, """{"foo":"t","bar":10}"""))
      val testPatch = new StubbedHttpPatch(response, response)
      testPatch.PATCH[TestRequestClass, TestClass](url, testObject, Seq("header" -> "foo")).futureValue should be(TestClass("t", 10))
    }

    behave like anErrorMappingHttpCall(
      "PATCH",
      (url, responseF) => new StubbedHttpPatch(responseF, responseF).PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo")))
    behave like aTracingHttpCall("PATCH", "PATCH", new StubbedHttpPatch(defaultHttpResponse, defaultHttpResponse)) {
      _.PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo"))
    }

    "Invoke any hooks provided" in {
      val dummyResponse       = HttpResponse(200, testBody)
      val dummyResponseFuture = Future.successful(dummyResponse)
      val testPatch           = new StubbedHttpPatch(dummyResponseFuture, dummyResponseFuture)
      val testJson            = Json.stringify(trcreads.writes(testObject))

      testPatch.PATCH[TestRequestClass, HttpResponse](url, testObject, Seq("header" -> "foo")).futureValue

      val respArgCaptor1 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]])
      val respArgCaptor2 = ArgumentCaptor.forClass(classOf[Future[HttpResponse]])

      verify(testPatch.testHook1)
        .apply(is(url), is("PATCH"), is(Some(HookData.FromString(testJson))), respArgCaptor1.capture())(any(), any())
      verify(testPatch.testHook2)
        .apply(is(url), is("PATCH"), is(Some(HookData.FromString(testJson))), respArgCaptor2.capture())(any(), any())

      // verifying directly without ArgumentCaptor didn't work as Futures were different instances
      // e.g. Future.successful(5) != Future.successful(5)
      respArgCaptor1.getValue.futureValue shouldBe dummyResponse
      respArgCaptor2.getValue.futureValue shouldBe dummyResponse
    }
  }
} 
Example 6
Source File: WsProxySpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.http.ws

import com.github.tomakehurst.wiremock.client.VerificationException
import com.github.tomakehurst.wiremock.client.WireMock._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{BeforeAndAfterAll, OptionValues}
import org.scalatestplus.mockito.MockitoSugar
import play.api.Play
import play.api.libs.ws.WSProxyServer
import play.api.test.FakeApplication
import uk.gov.hmrc.http.HeaderCarrier

class WsProxySpec extends AnyWordSpecLike with Matchers with MockitoSugar with OptionValues with BeforeAndAfterAll {
  implicit val hc = HeaderCarrier()

  lazy val fakeApplication = FakeApplication()

  "A proxied get request" should {
    "correctly make a request via the specified proxy server" in new Setup {

      val wSProxyServer = mock[WSProxyServer]

      object ProxiedGet extends WSProxy {

        override def applicableHeaders(url: String)(implicit hc: HeaderCarrier): Seq[(String, String)] = Nil

        def wsProxyServer = Some(wSProxyServer)
      }

      val request = ProxiedGet.buildRequest("http://example.com", headers = Seq.empty)

      request.proxyServer.value shouldBe (wSProxyServer)
    }
  }

  "A proxied get request, without a defined proxy configuration, i.e. for use in environments where a proxy does not exist" should {
    "still work by making the request without using a proxy server" in new Setup {

      object ProxiedGet extends WSProxy {

        override def applicableHeaders(url: String)(implicit hc: HeaderCarrier): Seq[(String, String)] = Nil

        def wsProxyServer = None
      }

      val request = ProxiedGet.buildRequest("http://example.com", headers = Seq.empty)

      request.proxyServer shouldBe (None)
    }
  }

  class Setup extends WireMockEndpoints {

    val responseData = "ResourceABC"
    val resourcePath = s"/resource/abc"

    def endpointBaseUrl = s"http://localhost:$endpointPort"

    def fullResourceUrl = s"$endpointBaseUrl$resourcePath"

    def setupEndpointExpectations() {
      endpointMock.register(
        get(urlEqualTo(resourcePath))
          .willReturn(
            aResponse()
              .withHeader("Content-Type", "text/plain")
              .withBody(responseData)))

      proxyMock.register(
        get(urlMatching(resourcePath))
          .willReturn(aResponse().proxiedFrom(endpointBaseUrl)))
    }

    def assertEndpointWasCalled() {
      endpointMock.verifyThat(getRequestedFor(urlEqualTo(resourcePath)))
    }

    def assertCallViaProxy() {
      endpointMock.verifyThat(getRequestedFor(urlEqualTo(resourcePath)))
    }

    def assertProxyNotUsed() {
      a[VerificationException] should be thrownBy proxyMock.verifyThat(getRequestedFor(urlEqualTo(resourcePath)))
    }
  }

  override def beforeAll() {
    super.beforeAll()
    Play.start(fakeApplication)
  }

  override def afterAll() {
    super.afterAll()
    Play.stop(fakeApplication)
  }

} 
Example 7
Source File: ConnectorSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.connectors

import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar
import play.api.test.WsTestClient
import uk.gov.hmrc.http._
import uk.gov.hmrc.http.logging.{Authorization, ForwardedFor, RequestId, SessionId}

class ConnectorSpec extends AnyWordSpecLike with Matchers with MockitoSugar {
  WsTestClient.withClient(wsClient => {

    "AuthConnector.buildRequest" should {
      val builder = new WSClientRequestBuilder {
        val client = wsClient
      }

      s"add expected headers to the request" in {
        val testAuthorisation = Authorization("someauth")
        val forwarded         = ForwardedFor("forwarded")
        val token             = Token("token")
        val sessionId         = SessionId("session")
        val requestId         = RequestId("requestId")
        val deviceID          = "deviceIdTest"

        val carrier: HeaderCarrier = HeaderCarrier(
          authorization = Some(testAuthorisation),
          token         = Some(token),
          forwarded     = Some(forwarded),
          sessionId     = Some(sessionId),
          requestId     = Some(requestId),
          deviceID      = Some(deviceID),
          otherHeaders  = Seq("path" -> "/the/request/path")
        )

        val request = builder.buildRequest("http://auth.base")(carrier)
        request.headers.get(HeaderNames.authorisation).flatMap(_.headOption) shouldBe Some(testAuthorisation.value)
        request.headers.get(HeaderNames.xForwardedFor).flatMap(_.headOption) shouldBe Some(forwarded.value)
        request.headers.get(HeaderNames.token).flatMap(_.headOption)         shouldBe Some(token.value)
        request.headers.get(HeaderNames.xSessionId).flatMap(_.headOption)    shouldBe Some(sessionId.value)
        request.headers.get(HeaderNames.xRequestId).flatMap(_.headOption)    shouldBe Some(requestId.value)
        request.headers.get(HeaderNames.deviceID).flatMap(_.headOption)      shouldBe Some(deviceID)
        request.headers.get("path")                                          shouldBe None
      }
    }
  })
} 
Example 8
Source File: LoggingHandlerSpec.scala    From play-auditing   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.audit.handler

import org.mockito.Mockito._
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatestplus.mockito.MockitoSugar
import org.slf4j.Logger
import play.api.libs.json.JsString

import scala.concurrent.ExecutionContext.Implicits.global

class LoggingHandlerSpec extends AnyWordSpecLike with MockitoSugar {

  val mockLog: Logger = mock[Logger]
  val loggingHandler = new LoggingHandler(mockLog)

  "LoggingHandler" should {
    "log the event" in {
      val expectedLogContent = """DS_EventMissed_AuditRequestFailure : audit item : "FAILED_EVENT""""

      loggingHandler.sendEvent(JsString("FAILED_EVENT"))

      verify(mockLog).warn(expectedLogContent)
    }
  }
} 
Example 9
Source File: MultipleContainersSpec.scala    From testcontainers-scala   with MIT License 5 votes vote down vote up
package com.dimafeng.testcontainers

import java.util.Optional

import com.dimafeng.testcontainers.MultipleContainersSpec.{InitializableContainer, TestSpec}
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.{Args, FlatSpec, Reporter}
import org.scalatestplus.mockito.MockitoSugar

class MultipleContainersSpec extends BaseSpec[ForEachTestContainer] {
  it should "call all expected methods of the multiple containers" in {
    val container1 = mock[SampleJavaContainer]
    val container2 = mock[SampleJavaContainer]

    val containers = MultipleContainers(new SampleContainer(container1), new SampleContainer(container2))

    new TestSpec({
      assert(1 == 1)
    }, containers).run(None, Args(mock[Reporter]))

    verify(container1).beforeTest(any())
    verify(container1).start()
    verify(container1).afterTest(any(), ArgumentMatchers.eq(Optional.empty()))
    verify(container1).stop()

    verify(container2).beforeTest(any())
    verify(container2).start()
    verify(container2).afterTest(any(), ArgumentMatchers.eq(Optional.empty()))
    verify(container2).stop()
  }

  
  it should "initialize containers lazily in `MultipleContainers` to let second container be depended on start data of the first one" in {
    lazy val container1 = new InitializableContainer("after start value")
    lazy val container2 = new InitializableContainer(container1.value)

    val containers = MultipleContainers(container1, container2)

    new TestSpec({
      assert(1 == 1)
    }, containers).run(None, Args(mock[Reporter]))

    assert(container1.value == "after start value")
    assert(container2.value == "after start value")
  }
}

object MultipleContainersSpec {

  class InitializableContainer(valueToBeSetAfterStart: String) extends SingleContainer[SampleJavaContainer] with MockitoSugar {
    override implicit val container: SampleJavaContainer = mock[SampleJavaContainer]
    var value: String = _

    override def start(): Unit = {
      value = valueToBeSetAfterStart
    }
  }

  class ExampleContainerWithVariable(val variable: String) extends SingleContainer[SampleJavaContainer] with MockitoSugar {
    override implicit val container: SampleJavaContainer = mock[SampleJavaContainer]
  }

  protected class TestSpec(testBody: => Unit, _container: Container) extends FlatSpec with ForEachTestContainer {
    override val container = _container

    it should "test" in {
      testBody
    }
  }

} 
Example 10
Source File: EdgeListDataSourceTest.scala    From morpheus   with Apache License 2.0 5 votes vote down vote up
package org.opencypher.morpheus.api.io.edgelist

import java.io.{File, PrintWriter}

import org.opencypher.morpheus.testing.MorpheusTestSuite
import org.opencypher.okapi.api.graph.{GraphName, PropertyGraph}
import org.opencypher.okapi.impl.exception
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.mockito.MockitoSugar

class EdgeListDataSourceTest extends MorpheusTestSuite with BeforeAndAfterAll with MockitoSugar {

  private val edgeList: String =
    s"""
       |0 1
       |0 2
       |1 2
       |1 3
     """.stripMargin

  private val tempFile = File.createTempFile(s"morpheus_edgelist_${System.currentTimeMillis()}", "edgelist")

  private val dataSource = EdgeListDataSource(
    tempFile.getAbsolutePath,
    Map("delimiter" -> " "))

  it("should return a static schema") {
    dataSource.schema(EdgeListDataSource.GRAPH_NAME) should equal(Some(EdgeListDataSource.SCHEMA))
  }

  it("should contain only one graph named 'graph'") {
    dataSource.hasGraph(EdgeListDataSource.GRAPH_NAME) should equal(true)
    dataSource.hasGraph(GraphName("foo")) should equal(false)
  }

  it("should throw when trying to delete") {
    a[exception.UnsupportedOperationException] shouldBe thrownBy {
      dataSource.delete(EdgeListDataSource.GRAPH_NAME)
    }
  }

  it("should have only one graph name") {
    dataSource.graphNames should equal(Set(EdgeListDataSource.GRAPH_NAME))
  }

  it("should throw when trying to store a graph") {
    a[exception.UnsupportedOperationException] shouldBe thrownBy {
      dataSource.store(GraphName("foo"), mock[PropertyGraph])
    }
  }

  it("should return the test graph") {
    val graph = dataSource.graph(EdgeListDataSource.GRAPH_NAME)
    graph.nodes("n").size should equal(4)
    graph.relationships("r").size should equal(4)
  }

  override protected def beforeAll(): Unit = {
    super.beforeAll()
    new PrintWriter(tempFile.getAbsolutePath) { write(edgeList); close() }
  }

  override protected def afterAll(): Unit = {
    tempFile.delete()
    super.afterAll()
  }
} 
Example 11
Source File: APIMetricsSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.metrics
import java.util.concurrent.TimeUnit

import cats.scalatest.EitherMatchers
import com.codahale.metrics.ScheduledReporter
import com.typesafe.config.ConfigFactory
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import vinyldns.api.VinylDNSConfig

class APIMetricsSpec extends AnyWordSpec with Matchers with MockitoSugar with EitherMatchers {

  "APIMetricsSettings" should {
    "succeed with valid config" in {
      val config = ConfigFactory.parseString(
        """
          |{
          |  memory {
          |    log-enabled = true
          |    log-seconds = 5
          |  }
          |}
        """.stripMargin
      )
      APIMetrics.loadSettings(config).attempt.unsafeRunSync() shouldBe Right(
        APIMetricsSettings(MemoryMetricsSettings(logEnabled = true, logSeconds = 5))
      )
    }
    "fail with invalid config" in {
      val config = ConfigFactory.parseString(
        """
          |{
          |  memory {
          |    log-blah-enabled = true
          |    log-seconds = 5
          |  }
          |}
        """.stripMargin
      )
      APIMetrics.loadSettings(config).attempt.unsafeRunSync() shouldBe left
    }
    "default to log memory off" in {
      APIMetrics
        .loadSettings(VinylDNSConfig.vinyldnsConfig.getConfig("metrics"))
        .unsafeRunSync()
        .memory
        .logEnabled shouldBe false
    }
  }

  "APIMetrics" should {
    "start the log reporter if enabled" in {
      val reporter = mock[ScheduledReporter]
      APIMetrics
        .initialize(
          APIMetricsSettings(MemoryMetricsSettings(logEnabled = true, logSeconds = 5)),
          reporter
        )
        .unsafeRunSync()
      verify(reporter).start(5, TimeUnit.SECONDS)
    }
    "not start the log reporter if not enabled" in {
      val reporter = mock[ScheduledReporter]
      APIMetrics
        .initialize(
          APIMetricsSettings(MemoryMetricsSettings(logEnabled = false, logSeconds = 5)),
          reporter
        )
        .unsafeRunSync()
      verifyZeroInteractions(reporter)
    }
  }
} 
Example 12
Source File: ZoneChangeHandlerSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.engine

import cats.effect._
import org.mockito.ArgumentCaptor
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import vinyldns.core.TestZoneData.zoneChangePending
import vinyldns.core.domain.record.RecordSetRepository
import vinyldns.core.domain.zone.ZoneRepository.DuplicateZoneError
import vinyldns.core.domain.zone._

class ZoneChangeHandlerSpec extends AnyWordSpec with Matchers with MockitoSugar {

  trait Fixture {
    val mockZoneRepo = mock[ZoneRepository]
    val mockChangeRepo = mock[ZoneChangeRepository]
    val mockRecordSetRepo = mock[RecordSetRepository]
    val change = zoneChangePending
    val test = ZoneChangeHandler(mockZoneRepo, mockChangeRepo, mockRecordSetRepo)
  }

  "ZoneChangeHandler" should {
    "save the zone change and zone" in new Fixture {
      doReturn(IO.pure(Right(change.zone))).when(mockZoneRepo).save(change.zone)
      doReturn(IO.pure(change)).when(mockChangeRepo).save(any[ZoneChange])

      test(change).unsafeRunSync()

      val changeCaptor = ArgumentCaptor.forClass(classOf[ZoneChange])
      verify(mockChangeRepo).save(changeCaptor.capture())

      val savedChange = changeCaptor.getValue
      savedChange.status shouldBe ZoneChangeStatus.Synced
    }
  }

  "save the zone change as failed if the zone does not save" in new Fixture {
    doReturn(IO.pure(Left(DuplicateZoneError("message")))).when(mockZoneRepo).save(change.zone)
    doReturn(IO.pure(change)).when(mockChangeRepo).save(any[ZoneChange])

    test(change).unsafeRunSync()

    val changeCaptor = ArgumentCaptor.forClass(classOf[ZoneChange])
    verify(mockChangeRepo).save(changeCaptor.capture())

    val savedChange = changeCaptor.getValue
    savedChange.status shouldBe ZoneChangeStatus.Failed
    savedChange.systemMessage shouldBe Some("Zone with name \"message\" already exists.")
  }

  "save a delete zone change as synced if recordset delete succeeds" in new Fixture {
    val deleteChange = change.copy(changeType = ZoneChangeType.Delete)

    doReturn(IO.pure(Right(deleteChange.zone))).when(mockZoneRepo).save(deleteChange.zone)
    doReturn(IO.pure(()))
      .when(mockRecordSetRepo)
      .deleteRecordSetsInZone(deleteChange.zone.id, deleteChange.zone.name)
    doReturn(IO.pure(deleteChange)).when(mockChangeRepo).save(any[ZoneChange])

    test(deleteChange).unsafeRunSync()

    val changeCaptor = ArgumentCaptor.forClass(classOf[ZoneChange])
    verify(mockChangeRepo).save(changeCaptor.capture())

    val savedChange = changeCaptor.getValue
    savedChange.status shouldBe ZoneChangeStatus.Synced
  }

  "save a delete zone change as synced if recordset delete fails" in new Fixture {
    val deleteChange = change.copy(changeType = ZoneChangeType.Delete)

    doReturn(IO.pure(Right(deleteChange.zone))).when(mockZoneRepo).save(deleteChange.zone)
    doReturn(IO.raiseError(new Throwable("error")))
      .when(mockRecordSetRepo)
      .deleteRecordSetsInZone(deleteChange.zone.id, deleteChange.zone.name)
    doReturn(IO.pure(deleteChange)).when(mockChangeRepo).save(any[ZoneChange])

    test(deleteChange).unsafeRunSync()

    val changeCaptor = ArgumentCaptor.forClass(classOf[ZoneChange])
    verify(mockChangeRepo).save(changeCaptor.capture())

    val savedChange = changeCaptor.getValue
    savedChange.status shouldBe ZoneChangeStatus.Synced
  }
} 
Example 13
Source File: BatchChangeHandlerSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.engine

import cats.effect._
import org.joda.time.DateTime
import org.mockito.Matchers.any
import org.mockito.Mockito.{doReturn, verify}
import org.scalatest.BeforeAndAfterEach
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import vinyldns.api.CatsHelpers
import vinyldns.api.repository.InMemoryBatchChangeRepository
import vinyldns.core.domain.batch._
import vinyldns.core.domain.record._
import vinyldns.core.notifier.{AllNotifiers, Notification, Notifier}

import scala.concurrent.ExecutionContext

class BatchChangeHandlerSpec
    extends AnyWordSpec
    with MockitoSugar
    with BeforeAndAfterEach
    with CatsHelpers {

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

  private val batchRepo = new InMemoryBatchChangeRepository
  private val mockNotifier = mock[Notifier]
  private val notifiers = AllNotifiers(List(mockNotifier))

  private val addChange = SingleAddChange(
    Some("zoneId"),
    Some("zoneName"),
    Some("recordName"),
    "recordName.zoneName",
    RecordType.A,
    300,
    AData("1.1.1.1"),
    SingleChangeStatus.Complete,
    None,
    Some("recordChangeId"),
    Some("recordSetId"),
    List(),
    "changeId"
  )

  private val completedBatchChange = BatchChange(
    "userId",
    "userName",
    Some("comments"),
    DateTime.now,
    List(addChange),
    Some("ownerGroupId"),
    BatchChangeApprovalStatus.AutoApproved
  )

  override protected def beforeEach(): Unit =
    batchRepo.clear()

  "notify on batch change complete" in {
    doReturn(IO.unit).when(mockNotifier).notify(any[Notification[_]])

    await(batchRepo.save(completedBatchChange))

    BatchChangeHandler
      .process(batchRepo, notifiers, BatchChangeCommand(completedBatchChange.id))
      .unsafeRunSync()

    verify(mockNotifier).notify(Notification(completedBatchChange))
  }

  "notify on failure" in {
    doReturn(IO.unit).when(mockNotifier).notify(any[Notification[_]])

    val partiallyFailedBatchChange =
      completedBatchChange.copy(changes = List(addChange.copy(status = SingleChangeStatus.Failed)))

    await(batchRepo.save(partiallyFailedBatchChange))

    BatchChangeHandler
      .process(batchRepo, notifiers, BatchChangeCommand(partiallyFailedBatchChange.id))
      .unsafeRunSync()

    verify(mockNotifier).notify(Notification(partiallyFailedBatchChange))
  }
} 
Example 14
Source File: TestDataLoaderSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.repository

import java.util.UUID

import cats.effect.IO
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.mockito.Matchers._
import org.mockito.Mockito._
import vinyldns.core.domain.membership._
import vinyldns.core.domain.zone.{Zone, ZoneRepository}
import vinyldns.core.TestMembershipData._

class TestDataLoaderSpec extends AnyWordSpec with Matchers with MockitoSugar {

  val userRepo: UserRepository = mock[UserRepository]
  doReturn(IO.pure(okUser)).when(userRepo).save(any[User])
  val groupRepo: GroupRepository = mock[GroupRepository]
  doReturn(IO.pure(okGroup)).when(groupRepo).save(any[Group])
  val membershipRepo: MembershipRepository = mock[MembershipRepository]
  doReturn(IO.pure(Set()))
    .when(membershipRepo)
    .saveMembers(any[String], any[Set[String]], anyBoolean)

  "loadTestData" should {
    "succeed if filtered appropriately" in {
      val zoneRepo = mock[ZoneRepository]

      val doNotDelete = Zone("another.shared.", "email", shared = true)
      val toDelete = Set(TestDataLoader.sharedZone, TestDataLoader.nonTestSharedZone)
      val zoneResponse = toDelete + doNotDelete

      // this mock doesnt matter
      doReturn(IO.pure(Right(doNotDelete))).when(zoneRepo).save(any[Zone])

      // have zone repo return 3 zones to delete
      doReturn(IO.pure(zoneResponse)).when(zoneRepo).getZonesByFilters(any[Set[String]])

      // should filter down to 2 for this to succeed
      val out = TestDataLoader.loadTestData(userRepo, groupRepo, zoneRepo, membershipRepo)

      noException should be thrownBy out.unsafeRunSync()
    }
    "fail if more than 2 zones are filtered" in {
      val zoneRepo = mock[ZoneRepository]

      // mimic of non-test-shared, will not be filtered out
      val dataClone = TestDataLoader.nonTestSharedZone.copy(id = UUID.randomUUID().toString)
      val toDelete = Set(TestDataLoader.sharedZone, TestDataLoader.nonTestSharedZone)
      val zoneResponse = toDelete + dataClone

      // not mocking zoneRepo.save on purpose, it shouldnt be reached

      // have zone repo return 3 zones to delete
      doReturn(IO.pure(zoneResponse)).when(zoneRepo).getZonesByFilters(any[Set[String]])

      // should filters would not remove the duplicate non.test.shared
      val out = TestDataLoader.loadTestData(userRepo, groupRepo, zoneRepo, membershipRepo)

      a[RuntimeException] should be thrownBy out.unsafeRunSync()
    }
  }
} 
Example 15
Source File: GlobalAclSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.domain.access

import cats.scalatest.EitherMatchers
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import vinyldns.api.ResultHelpers
import vinyldns.core.domain.Fqdn
import vinyldns.core.domain.record.{PTRData, RecordType}

class GlobalAclSpec
    extends AnyWordSpec
    with Matchers
    with MockitoSugar
    with ResultHelpers
    with EitherMatchers {

  import vinyldns.core.TestMembershipData._
  import vinyldns.core.TestZoneData._

  private val globalAcls = GlobalAcls(
    List(GlobalAcl(List(okGroup.id, dummyGroup.id), List(".*foo.*", ".*bar.com.")))
  )

  "isAuthorized" should {
    "return false if the acl list is empty" in {
      GlobalAcls(Nil).isAuthorized(okAuth, "foo", RecordType.A, okZone, Nil) shouldBe false
    }
    "return true if the user and record are in the acl" in {
      globalAcls.isAuthorized(okAuth, "foo", RecordType.A, okZone, Nil) shouldBe true
    }
    "return true for a PTR record if the user and record match an acl" in {
      globalAcls.isAuthorized(
        okAuth,
        "foo",
        RecordType.PTR,
        zoneIp4,
        List(PTRData(Fqdn("foo.com")))
      ) shouldBe true
    }
    "normalizes the record name before testing" in {
      globalAcls.isAuthorized(okAuth, "foo.", RecordType.A, okZone, Nil) shouldBe true
    }
    "return true for a PTR record when all PTR records match an acl" in {
      globalAcls.isAuthorized(
        okAuth,
        "foo",
        RecordType.PTR,
        zoneIp4,
        List(PTRData(Fqdn("foo.com")), PTRData(Fqdn("bar.com")))
      ) shouldBe true
    }
    "return false for a PTR record if one of the PTR records does not match an acl" in {
      globalAcls.isAuthorized(
        okAuth,
        "foo",
        RecordType.PTR,
        zoneIp4,
        List(PTRData(Fqdn("foo.com")), PTRData(Fqdn("blah.net")))
      ) shouldBe false
    }
    "return false for a PTR record if the record data is empty" in {
      globalAcls.isAuthorized(okAuth, "foo", RecordType.PTR, zoneIp4, Nil) shouldBe false
    }
    "return false for a PTR record if the ACL is empty" in {
      GlobalAcls(Nil).isAuthorized(
        okAuth,
        "foo",
        RecordType.PTR,
        zoneIp4,
        List(PTRData(Fqdn("foo.com")))
      ) shouldBe false
    }
    "return false for a PTR record if the ACL is empty and the record data is empty" in {
      GlobalAcls(Nil).isAuthorized(okAuth, "foo", RecordType.PTR, zoneIp4, Nil) shouldBe false
    }
  }
} 
Example 16
Source File: MembershipValidationsSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.domain.membership

import cats.scalatest.EitherMatchers
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.BeforeAndAfterEach
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import vinyldns.api.ResultHelpers
import vinyldns.core.TestMembershipData._
import vinyldns.core.domain.auth.AuthPrincipal
import vinyldns.api.domain.zone.NotAuthorizedError
import vinyldns.core.domain.membership.User

class MembershipValidationsSpec
    extends AnyWordSpec
    with Matchers
    with MockitoSugar
    with BeforeAndAfterEach
    with ResultHelpers
    with EitherMatchers {

  import vinyldns.api.domain.membership.MembershipValidations._

  "MembershipValidations" should {
    "hasMembersAndAdmins" should {
      "return true when a group has at least one member and one admin" in {
        hasMembersAndAdmins(okGroup) should be(right)
      }

      "return an error when a group has no members" in {
        val badGroup = okGroup.copy(memberIds = Set())
        val error = leftValue(hasMembersAndAdmins(badGroup))
        error shouldBe an[InvalidGroupError]
      }

      "return an error when a group has no admins" in {
        val badGroup = okGroup.copy(adminUserIds = Set())
        val error = leftValue(hasMembersAndAdmins(badGroup))
        error shouldBe an[InvalidGroupError]
      }
    }

    "isAdmin" should {
      "return true when the user is in admin group" in {
        canEditGroup(okGroup, okAuth) should be(right)
      }
      "return true when the user is a super user" in {
        canEditGroup(okGroup, superUserAuth) should be(right)
      }
      "return an error when the user is a support admin only" in {
        val user = User("some", "new", "user", isSupport = true)
        val supportAuth = AuthPrincipal(user, Seq())
        val error = leftValue(canEditGroup(okGroup, supportAuth))
        error shouldBe an[NotAuthorizedError]
      }
      "return an error when the user has no access and is not super" in {
        val user = User("some", "new", "user")
        val nonSuperAuth = AuthPrincipal(user, Seq())
        val error = leftValue(canEditGroup(okGroup, nonSuperAuth))
        error shouldBe an[NotAuthorizedError]
      }
    }

    "canSeeGroup" should {
      "return true when the user is in the group" in {
        canSeeGroup(okGroup.id, okAuth) should be(right)
      }
      "return true when the user is a super user" in {
        canSeeGroup(okGroup.id, superUserAuth) should be(right)
      }
      "return true when the user is a support admin" in {
        val user = User("some", "new", "user", isSupport = true)
        val supportAuth = AuthPrincipal(user, Seq())
        canSeeGroup(okGroup.id, supportAuth) should be(right)
      }
      "return an error when the user has no access and is not super" in {
        val user = User("some", "new", "user")
        val nonSuperAuth = AuthPrincipal(user, Seq())
        val error = leftValue(canSeeGroup(okGroup.id, nonSuperAuth))
        error shouldBe an[NotAuthorizedError]
      }

    }
  }
} 
Example 17
Source File: Mock.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks

import org.mockito.{ArgumentMatchers => Matchers}
import org.mockito.Mockito
import org.mockito.stubbing.OngoingStubbing
import org.mockito.verification.VerificationMode
import org.scalatest.{BeforeAndAfterEach, Suite}
import org.scalatestplus.mockito.MockitoSugar

trait Mock extends MockitoSugar with BeforeAndAfterEach { _: Suite =>

  // predefined mocking functions to avoid importing
  def any[T]() = Matchers.any[T]()
  def eqTo[T](t: T) = Matchers.eq[T](t)
  def when[T](t: T) = Mockito.when(t)
  def reset[T](t: T) = Mockito.reset(t)
  def verify[T](mock: T, mode: VerificationMode) = Mockito.verify(mock, mode)
  def times(num: Int) = Mockito.times(num)

  implicit class stubbingOps[T](stubbing: OngoingStubbing[T]){
    def returns(t: T) = stubbing.thenReturn(t)
  }
} 
Example 18
Source File: PrometheusRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

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

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

  val metricRegistry = VinylDNSMetrics.metricsRegistry

  val collectorRegistry = CollectorRegistry.defaultRegistry

  collectorRegistry.register(new DropwizardExports(metricRegistry))

  "GET /metrics/prometheus" should {
    "return metrics logged in prometheus" in {
      Get("/metrics/prometheus") ~> prometheusRoute ~> check {
        response.status shouldBe StatusCodes.OK
        val resultStatus = responseAs[HttpResponse]
        resultStatus.protocol shouldBe HttpProtocol("HTTP/1.1")
      }
    }
  }
} 
Example 19
Source File: HealthCheckRoutingSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.route

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

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

  val healthService: HealthService = mock[HealthService]

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

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

import cats.effect.IO
import org.scalatestplus.mockito.MockitoSugar
import vinyldns.core.crypto.CryptoAlgebra
import vinyldns.core.domain.batch.BatchChangeRepository
import vinyldns.core.domain.membership.{
  GroupChangeRepository,
  GroupRepository,
  MembershipRepository,
  UserRepository
}
import vinyldns.core.domain.record.{RecordChangeRepository, RecordSetRepository}
import vinyldns.core.domain.zone.{ZoneChangeRepository, ZoneRepository}
import vinyldns.core.health.HealthCheck.HealthCheck

class MockDataStoreProvider extends DataStoreProvider with MockitoSugar {

  def load(config: DataStoreConfig, crypto: CryptoAlgebra): IO[LoadedDataStore] = {
    val repoConfig = config.repositories

    val user = repoConfig.user.map(_ => mock[UserRepository])
    val group = repoConfig.group.map(_ => mock[GroupRepository])
    val membership = repoConfig.membership.map(_ => mock[MembershipRepository])
    val groupChange = repoConfig.groupChange.map(_ => mock[GroupChangeRepository])
    val recordSet = repoConfig.recordSet.map(_ => mock[RecordSetRepository])
    val recordChange = repoConfig.recordChange.map(_ => mock[RecordChangeRepository])
    val zoneChange = repoConfig.zoneChange.map(_ => mock[ZoneChangeRepository])
    val zone = repoConfig.zone.map(_ => mock[ZoneRepository])
    val batchChange = repoConfig.batchChange.map(_ => mock[BatchChangeRepository])

    IO.pure(
      new LoadedDataStore(
        DataStore(
          user,
          group,
          membership,
          groupChange,
          recordSet,
          recordChange,
          zoneChange,
          zone,
          batchChange
        ),
        IO.unit,
        checkHealth()
      )
    )
  }

  def checkHealth(): HealthCheck = IO.pure(Right((): Unit))
}

class AlternateMockDataStoreProvider extends MockDataStoreProvider {

  override def load(config: DataStoreConfig, crypto: CryptoAlgebra): IO[LoadedDataStore] =
    IO.pure(new LoadedDataStore(DataStore(), shutdown(), checkHealth()))

  def shutdown(): IO[Unit] = IO.raiseError(new RuntimeException("oh no"))
}

class FailDataStoreProvider extends DataStoreProvider {
  def load(config: DataStoreConfig, crypto: CryptoAlgebra): IO[LoadedDataStore] =
    IO.raiseError(new RuntimeException("ruh roh"))
} 
Example 21
Source File: AllNotifiersSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.core.notifier

import cats.scalatest.{EitherMatchers, EitherValues, ValidatedMatchers}
import org.scalatestplus.mockito.MockitoSugar
import org.mockito.Mockito._
import cats.effect.IO
import org.scalatest.BeforeAndAfterEach
import cats.effect.ContextShift
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class AllNotifiersSpec
    extends AnyWordSpec
    with Matchers
    with MockitoSugar
    with EitherValues
    with EitherMatchers
    with ValidatedMatchers
    with BeforeAndAfterEach {

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

  val mockNotifiers = List.fill(3)(mock[Notifier])

  val notification = Notification("anything")

  override def beforeEach: Unit =
    mockNotifiers.foreach { mock =>
      reset(mock)
      when(mock.notify(notification)).thenReturn(IO.unit)
    }

  "notifier" should {
    "notify all contained notifiers" in {

      val notifier = AllNotifiers(mockNotifiers)

      notifier.notify(notification)

      mockNotifiers.foreach(verify(_).notify(notification))
    }

    "suppress errors from notifiers" in {
      val notifier = AllNotifiers(mockNotifiers)

      when(mockNotifiers(2).notify(notification)).thenReturn(IO.raiseError(new Exception("fail")))

      notifier.notify(notification).unsafeRunSync()

      mockNotifiers.foreach(verify(_).notify(notification))
    }
  }

} 
Example 22
Source File: MessageQueueLoaderSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.core.queue

import cats.effect.IO
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatestplus.mockito.MockitoSugar

import scala.concurrent.duration._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

object MockMessageQueueProvider extends MockitoSugar {

  val mockMessageQueue: MessageQueue = mock[MessageQueue]

}

class MockMessageQueueProvider extends MessageQueueProvider {

  def load(config: MessageQueueConfig): IO[MessageQueue] =
    IO.pure(MockMessageQueueProvider.mockMessageQueue)

}

class FailMessageQueueProvider extends MessageQueueProvider {

  def load(config: MessageQueueConfig): IO[MessageQueue] =
    IO.raiseError(new RuntimeException("boo"))

}

class MessageQueueLoaderSpec extends AnyWordSpec with Matchers {

  val placeholderConfig: Config = ConfigFactory.parseString("{}")
  private val pollingInterval = 250.millis
  private val messagesPerPoll = 10

  "load" should {
    "return the correct queue if properly configured" in {
      val config =
        MessageQueueConfig(
          "vinyldns.core.queue.MockMessageQueueProvider",
          pollingInterval,
          messagesPerPoll,
          placeholderConfig,
          100
        )

      val loadCall = MessageQueueLoader.load(config)
      loadCall.unsafeRunSync() shouldBe MockMessageQueueProvider.mockMessageQueue
    }
    "Error if the configured provider cannot be found" in {
      val config =
        MessageQueueConfig("bad.class", pollingInterval, messagesPerPoll, placeholderConfig, 100)

      val loadCall = MessageQueueLoader.load(config)

      a[ClassNotFoundException] shouldBe thrownBy(loadCall.unsafeRunSync())
    }
    "Error if an error is returned from external load" in {
      val config =
        MessageQueueConfig(
          "vinyldns.core.queue.FailMessageQueueProvider",
          pollingInterval,
          messagesPerPoll,
          placeholderConfig,
          100
        )

      val loadCall = MessageQueueLoader.load(config)

      a[RuntimeException] shouldBe thrownBy(loadCall.unsafeRunSync())
    }
  }
} 
Example 23
Source File: TaskSchedulerSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.core.task
import cats.effect.{ContextShift, IO, Timer}
import org.mockito.Mockito
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.BeforeAndAfterEach

import scala.concurrent.duration._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class TaskSchedulerSpec
    extends AnyWordSpec
    with Matchers
    with MockitoSugar
    with BeforeAndAfterEach {

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

  private val mockRepo = mock[TaskRepository]

  class TestTask(
      val name: String,
      val timeout: FiniteDuration,
      val runEvery: FiniteDuration,
      val checkInterval: FiniteDuration,
      testResult: IO[Unit] = IO.unit
  ) extends Task {
    def run(): IO[Unit] = testResult
  }

  override def beforeEach() = Mockito.reset(mockRepo)

  "TaskScheduler" should {
    "run a scheduled task" in {
      val task = new TestTask("test", 5.seconds, 500.millis, 500.millis)
      val spied = spy(task)
      doReturn(IO.unit).when(mockRepo).saveTask(task.name)
      doReturn(IO.pure(true)).when(mockRepo).claimTask(task.name, task.timeout, task.runEvery)
      doReturn(IO.unit).when(mockRepo).releaseTask(task.name)

      TaskScheduler.schedule(spied, mockRepo).take(1).compile.drain.unsafeRunSync()

      // We run twice because we run once on start up
      verify(spied, times(2)).run()
      verify(mockRepo, times(2)).claimTask(task.name, task.timeout, task.runEvery)
      verify(mockRepo, times(2)).releaseTask(task.name)
    }

    "release the task even on error" in {
      val task =
        new TestTask(
          "test",
          5.seconds,
          500.millis,
          500.millis,
          IO.raiseError(new RuntimeException("fail"))
        )
      doReturn(IO.unit).when(mockRepo).saveTask(task.name)
      doReturn(IO.pure(true)).when(mockRepo).claimTask(task.name, task.timeout, task.runEvery)
      doReturn(IO.unit).when(mockRepo).releaseTask(task.name)

      TaskScheduler.schedule(task, mockRepo).take(1).compile.drain.unsafeRunSync()

      // We release the task twice, once on start and once on the run
      verify(mockRepo, times(2)).releaseTask(task.name)
    }

    "fail to start if the task cannot be saved" in {
      val task = new TestTask("test", 5.seconds, 500.millis, 500.millis)
      val spied = spy(task)
      doReturn(IO.raiseError(new RuntimeException("fail"))).when(mockRepo).saveTask(task.name)

      a[RuntimeException] should be thrownBy TaskScheduler
        .schedule(task, mockRepo)
        .take(1)
        .compile
        .drain
        .unsafeRunSync()
      verify(spied, never()).run()
    }
  }
} 
Example 24
Source File: JsonEncoderSpec.scala    From logback-json-logger   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.logging
import java.io.{PrintWriter, StringWriter}
import java.net.InetAddress

import ch.qos.logback.classic.Level
import ch.qos.logback.classic.spi.{ILoggingEvent, ThrowableProxy}
import ch.qos.logback.core.ContextBase
import org.apache.commons.lang3.time.FastDateFormat
import org.mockito.Mockito.when
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import play.api.libs.json.{JsLookupResult, Json}

import scala.collection.JavaConverters._

class JsonEncoderSpec extends AnyWordSpec with Matchers with MockitoSugar {

  "Json-encoded message" should {
    "contain all required fields" in {

      val jsonEncoder = new JsonEncoder()
      val event       = mock[ILoggingEvent]

      when(event.getTimeStamp).thenReturn(1)
      when(event.getLevel).thenReturn(Level.INFO)
      when(event.getThreadName).thenReturn("my-thread")
      when(event.getFormattedMessage).thenReturn("my-message")
      when(event.getLoggerName).thenReturn("logger-name")
      when(event.getMDCPropertyMap).thenReturn(Map("myMdcProperty" -> "myMdcValue").asJava)

      val testException = new Exception("test-exception")
      val stringWriter  = new StringWriter()
      testException.printStackTrace(new PrintWriter(stringWriter))
      when(event.getThrowableProxy).thenReturn(new ThrowableProxy(testException))

      jsonEncoder.setContext {
        val ctx = new ContextBase()
        ctx.putProperty("myKey", "myValue")
        ctx
      }

      val result       = new String(jsonEncoder.encode(event), "UTF-8")
      val resultAsJson = Json.parse(result)

      (resultAsJson \ "app").asString           shouldBe "my-app-name"
      (resultAsJson \ "hostname").asString      shouldBe InetAddress.getLocalHost.getHostName
      (resultAsJson \ "timestamp").asString     shouldBe FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSSZZ").format(1)
      (resultAsJson \ "message").asString       shouldBe "my-message"
      (resultAsJson \ "exception").asString     should include("test-exception")
      (resultAsJson \ "exception").asString     should include("java.lang.Exception")
      (resultAsJson \ "exception").asString     should include(stringWriter.toString)
      (resultAsJson \ "logger").asString        shouldBe "logger-name"
      (resultAsJson \ "thread").asString        shouldBe "my-thread"
      (resultAsJson \ "level").asString         shouldBe "INFO"
      (resultAsJson \ "mykey").asString         shouldBe "myValue"
      (resultAsJson \ "mymdcproperty").asString shouldBe "myMdcValue"

    }
  }

  implicit class JsLookupResultOps(jsLookupResult: JsLookupResult) {
    def asString: String = jsLookupResult.get.as[String]
  }

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

import java.io.File

import org.mockito.Mockito._
import org.scalatest.{FunSpec, Matchers}
import org.scalatestplus.mockito.MockitoSugar

class LowDiskSpaceDetectorSpec extends FunSpec with MockitoSugar with Matchers with ProcessSpawner {
  describe("low diskspace detector") {
    val path = mock[File]
    val thresholdMB = 10
    val lowDiskSpaceDetector = new LowDiskSpaceDetector(thresholdMB = thresholdMB, path = path)

    it("should detect low diskspace") {
      when(path.getFreeSpace).thenReturn(thresholdMB * 1024 * 1024 - 1)
      lowDiskSpaceDetector.isHealthy() should equal(false)
    }

    it("should detect when diskspace is healthy") {
      when(path.getFreeSpace).thenReturn(thresholdMB * 1024 * 1024 + 1)
      lowDiskSpaceDetector.isHealthy() should equal(true)
    }
  }
} 
Example 26
Source File: HealthEndpointSpec.scala    From akka-http-health   with MIT License 5 votes vote down vote up
package io.github.lhotari.akka.http.health

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

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

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

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

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

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

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

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

} 
Example 27
Source File: DataCenterAwarenessSpec.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.cluster

import org.scalatest.{FlatSpec, Matchers}
import org.mockito.Mockito._
import akka.actor._
import akka.routing.ActorSelectionRoutee
import akka.util.ByteString
import org.scalatestplus.mockito.MockitoSugar
import org.squbs.cluster.rebalance.{CorrelateRoundRobinRoutingLogic, DataCenterAwareRebalanceLogic, DefaultCorrelation}

class DataCenterAwarenessSpec extends FlatSpec with Matchers with MockitoSugar {


  val myAddress = Address("akka.tcp", "pubsub", "10.100.194.253", 8080)
  val correlates = Seq(Address("akka.tcp", "pubsub", "10.100.65.147", 8080),
    Address("akka.tcp", "pubsub", "10.100.98.134", 8080))
  val distances = Seq(Address("akka.tcp", "pubsub", "10.210.45.119", 8080),
    Address("akka.tcp", "pubsub", "10.210.79.201", 8080))

  "DefaultCorrelation" should "extract ipv4 subnet domain" in {

    val mockAddress = Address("akka.tcp", "pubsub", "10.100.194.253", 8080)

    DefaultCorrelation().common(mockAddress) should equal("[email protected]")
  }

  "CorrelateRoundRobinRoutingLogic" should "prefer routees that correlate with itself" in {

    val routees = (correlates ++ distances).map(address => {
      val mockActorSelection = mock[ActorSelection]
      when(mockActorSelection.pathString).thenReturn(address.toString)

      ActorSelectionRoutee(mockActorSelection)
    }).toIndexedSeq

    val logic = CorrelateRoundRobinRoutingLogic(myAddress)
    logic.select("whatever", routees) match {
      case ActorSelectionRoutee(selection) =>
        selection.pathString should equal("akka.tcp://[email protected]:8080")
    }

    logic.select("whatever", routees) match {
      case ActorSelectionRoutee(selection) =>
        selection.pathString should equal("akka.tcp://[email protected]:8080")
    }

    logic.select("whatever", routees) match {
      case ActorSelectionRoutee(selection) =>
        selection.pathString should equal("akka.tcp://[email protected]:8080")
    }
  }

  "DefaultDataCenterAwareRebalanceLogic" should "rebalance with correlations in considerations" in {

    val partitionKey = ByteString("some partition")
    val partitionsToMembers = Map(partitionKey -> Set.empty[Address])
    def size(partitionKey:ByteString) = 2

    var compensation = DataCenterAwareRebalanceLogic().compensate(partitionsToMembers, correlates ++ distances, size)
    compensation.getOrElse(partitionKey, Set.empty) should equal(Set(correlates.head, distances.head))

    val morePartition = ByteString("another partition")
    compensation = DataCenterAwareRebalanceLogic().
      compensate(compensation.updated(morePartition, Set.empty), correlates ++ distances, size)
    compensation.getOrElse(partitionKey, Set.empty) should equal(Set(correlates.head, distances.head))
    compensation.getOrElse(morePartition, Set.empty) should equal(Set(correlates.head, distances.head))

    val balanced = DataCenterAwareRebalanceLogic().rebalance(compensation, (correlates ++ distances).toSet)
    balanced.getOrElse(partitionKey, Set.empty) shouldNot equal(balanced.getOrElse(morePartition, Set.empty))
  }

  "DefaultDataCenterAwareRebalanceLogic" should "rebalance after a DC failure recovery" in {

    val partitionKey = ByteString("some partition")
    val partitionsToMembers = Map(partitionKey -> Set.empty[Address])
    def size(partitionKey:ByteString) = 2

    var compensation = DataCenterAwareRebalanceLogic().compensate(partitionsToMembers, correlates ++ distances, size)
    compensation.getOrElse(partitionKey, Set.empty) should equal(Set(correlates.head, distances.head))

    val balanced = DataCenterAwareRebalanceLogic().rebalance(compensation, (correlates ++ distances).toSet)
    balanced.getOrElse(partitionKey, Set.empty) should have size 2

    //unfortunately correlates are gone?!
    compensation = DataCenterAwareRebalanceLogic().
      compensate(partitionsToMembers.updated(partitionKey, Set(distances.head)), distances, size)
    compensation.getOrElse(partitionKey, Set.empty) should equal(distances.toSet)

    val rebalanced = DataCenterAwareRebalanceLogic().rebalance(compensation, distances.toSet)
    rebalanced.getOrElse(partitionKey, Set.empty) should equal(distances.toSet)

    val recovered = DataCenterAwareRebalanceLogic().rebalance(compensation, (correlates ++ distances).toSet)
    recovered.getOrElse(partitionKey, Set.empty) should have size 2
    recovered.getOrElse(partitionKey, Set.empty) shouldNot equal(distances.toSet)
    correlates.contains(recovered.getOrElse(partitionKey, Set.empty).diff(distances.toSet).head) should equal(true)
  }
} 
Example 28
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 29
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 30
Source File: Mockito.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package utils.test

import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.{Answer, OngoingStubbing}
import org.mockito.verification.VerificationMode
import org.mockito.{ArgumentMatchers, Mockito => M}
import org.scalatestplus.mockito.MockitoSugar


trait Mockito extends MockitoSugar {

  def eq[T](t: T) = ArgumentMatchers.eq(t)
  def any[T] = ArgumentMatchers.any[T]
  def anyBoolean = ArgumentMatchers.anyBoolean
  def anyString = ArgumentMatchers.anyString
  def same[T](value: T) = ArgumentMatchers.same(value)
  def verify[T](t: T, mode: VerificationMode = times(1)) = M.verify(t, mode)
  def times(num: Int) = M.times(num)
  def timeout(millis: Int) = M.timeout(millis.toLong)
  def atLeastOnce = M.atLeastOnce()
  def atLeast(num: Int) = M.atLeast(num)
  def atMost(num: Int) = M.atMost(num)
  def never = M.never()

  def inOrder(mocks: AnyRef*) = M.inOrder(mocks: _*)

  def noMoreInteractions(mocks: AnyRef*): Unit = {
    M.verifyNoMoreInteractions(mocks: _*)
  }

  def reset(mocks: AnyRef*): Unit = {
    M.reset(mocks: _*)
  }

  class MockAnswer[T](function: Array[AnyRef] => T) extends Answer[T] {
    def answer(invocation: InvocationOnMock): T = {
      function(invocation.getArguments)
    }
  }

  implicit class Stubbed[T](c: => T) {
    def returns(t: T, t2: T*): OngoingStubbing[T] = {
      if (t2.isEmpty) M.when(c).thenReturn(t)
      else t2.foldLeft(M.when(c).thenReturn(t)) { (res, cur) => res.thenReturn(cur) }
    }
    def answers(function: Array[AnyRef] => T) = M.when(c).thenAnswer(new MockAnswer(function))
    def throws[E <: Throwable](e: E*): OngoingStubbing[T] = {
      if (e.isEmpty) throw new java.lang.IllegalArgumentException("The parameter passed to throws must not be empty")
      e.drop(1).foldLeft(M.when(c).thenThrow(e.head)) { (res, cur) => res.thenThrow(cur) }
    }
  }
}

object Mockito extends Mockito 
Example 31
Source File: SonarFileSystemSpec.scala    From sonar-scala   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.mwz.sonar.scala
package util
package syntax

import java.nio.file.{Path, Paths}

import cats.instances.list._
import cats.instances.option._
import com.mwz.sonar.scala.util.syntax.SonarFileSystem._
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito._
import org.scalatest.OptionValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar
import org.sonar.api.batch.fs.FileSystem
import org.sonar.api.batch.fs.internal.DefaultFileSystem

class SonarFileSystemSpec extends AnyFlatSpec with Matchers with OptionValues with MockitoSugar {
  it should "attempt to resolve paths" in {
    val fs = new DefaultFileSystem(Paths.get("./"))

    val paths = List(Paths.get("path/1"), Paths.get("path/2"))
    fs.resolve(paths) shouldBe List(
      Paths.get("./").resolve("path/1").toAbsolutePath.normalize.toFile,
      Paths.get("./").resolve("path/2").toAbsolutePath.normalize.toFile
    )

    val path: Option[Path] = Some(Paths.get("another/path"))
    fs.resolve(path).value shouldBe
    Paths.get("./").resolve("another/path").toAbsolutePath.normalize.toFile
  }

  it should "handle exceptions gracefully" in {
    val fs = mock[FileSystem]
    val path = List(Paths.get("path"))

    when(fs.resolvePath(any())).thenThrow(new RuntimeException())

    fs.resolve(path) shouldBe empty
  }
} 
Example 32
Source File: mainContentHeaderSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package views.html.integration

import config.ConfigDecorator
import org.joda.time.DateTime
import org.scalatestplus.mockito.MockitoSugar
import util.BaseSpec
import views.html.ViewSpec

class mainContentHeaderSpec extends ViewSpec with MockitoSugar {

  implicit val configDecorator: ConfigDecorator = mock[ConfigDecorator]

  "Rendering mainContentHeader.scala.html" should {

    "show last logged in details with name when a name is present and a lastLogin is supplied" in {
      val millis = DateTime.parse("1982-04-30T00:00:00.000+01:00")
      val document = asDocument(
        views.html.integration
          .mainContentHeader(Some("Firstname"), Some(millis), Nil, false, None, None)
          .toString)
      document.select(".last-login > p").text shouldBe "Firstname, you last signed in 12:00am, Friday 30 April 1982"
    }

    "show last logged in details without name when no name is present and a lastLogin is supplied" in {
      val millis = DateTime.parse("1982-04-30T00:00:00.000+01:00")
      val document = asDocument(
        views.html.integration
          .mainContentHeader(None, Some(millis), Nil, false, None, None)
          .toString)
      document.select(".last-login > p").text shouldBe "You last signed in 12:00am, Friday 30 April 1982"
    }

    "not show last logged in details when lastLogin is not supplied" in {
      val document = asDocument(
        views.html.integration
          .mainContentHeader(None, None, Nil, false, None, None)
          .toString)
      document.select(".last-login").isEmpty shouldBe true
    }

    "show breadcrumb when one is passed" in {
      val document = asDocument(
        views.html.integration
          .mainContentHeader(None, None, List(("/url", "Link Text"), ("/url2", "Link Text 2")), true, None, None)
          .toString)
      val doc = asDocument(document.select("#global-breadcrumb").toString)

      doc.select("a").size() shouldBe 2
      document.select("#global-breadcrumb").isEmpty shouldBe false
    }

    "hide breadcrumb when none is passed" in {
      val document = asDocument(views.html.integration.mainContentHeader(None, None, Nil, true, None, None).toString)
      document.select("#global-breadcrumb").isEmpty shouldBe true
    }

    "show BETA banner showBetaBanner is true" in {
      val document = asDocument(views.html.integration.mainContentHeader(None, None, Nil, true, None, None).toString)
      document.select(".beta-banner .phase-tag").text shouldBe "BETA"
    }

    "hide BETA banner showBetaBanner is false" in {
      val document = asDocument(
        views.html.integration
          .mainContentHeader(None, None, Nil, false, None, None)
          .toString)
      document.select(".beta-banner .phase-tag").isEmpty shouldBe true
    }

    "show feedback link in BETA banner when passed deskProToken with PTA" in {
      val document = asDocument(
        views.html.integration
          .mainContentHeader(None, None, Nil, true, Some("PTA"), None)
          .toString)
      document
        .select(".beta-banner .feedback")
        .text shouldBe "This is a new service - your feedback will help us to improve it."
    }

    "hide feedback link in BETA banner when not passed any deskProToken" in {
      val document = asDocument(
        views.html.integration
          .mainContentHeader(None, None, Nil, false, None, None)
          .toString)
      document.select(".beta-banner .feedback").isEmpty shouldBe true
    }

  }
} 
Example 33
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 34
Source File: FormPartialServiceSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.codahale.metrics.Timer
import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.{Configuration, Environment}
import play.twirl.api.Html
import services.partials.FormPartialService
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.BaseSpec
import util.Fixtures._

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

class FormPartialServiceSpec extends BaseSpec {

  trait LocalSetup {
    val servicesConfig = app.injector.instanceOf[ServicesConfig]
    val timer = MockitoSugar.mock[Timer.Context]
    val formPartialService: FormPartialService = new FormPartialService(
      injected[Environment],
      injected[Configuration],
      MockitoSugar.mock[DefaultHttpClient],
      MockitoSugar.mock[Metrics],
      MockitoSugar.mock[ConfigDecorator],
      injected[SessionCookieCrypto],
      servicesConfig
    ) {
      override val metricsOperator: MetricsOperator = MockitoSugar.mock[MetricsOperator]
      when(metricsOperator.startTimer(any())) thenReturn timer
    }
  }

  "Calling FormPartialServiceSpec" should {

    "return form list for National insurance" in new LocalSetup {

      when(formPartialService.http.GET[HtmlPartial](any())(any(), any(), any())) thenReturn
        Future.successful[HtmlPartial](HtmlPartial.Success(Some("Title"), Html("<title/>")))

      formPartialService.getNationalInsurancePartial(buildFakeRequestWithAuth("GET")).map(p => p shouldBe "<title/>")
      verify(formPartialService.http, times(1)).GET[Html](any())(any(), any(), any())
    }

    "return form list for Self-assessment" in new LocalSetup {

      when(formPartialService.http.GET[HtmlPartial](any())(any(), any(), any())) thenReturn
        Future.successful[HtmlPartial](HtmlPartial.Success(Some("Title"), Html("<title/>")))

      formPartialService.getSelfAssessmentPartial(buildFakeRequestWithAuth("GET")).map(p => p shouldBe "<title/>")
      verify(formPartialService.http, times(1)).GET[Html](any())(any(), any(), any())
    }

  }

} 
Example 35
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 36
Source File: IdentityVerificationFrontendServiceSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.codahale.metrics.Timer
import com.kenshoo.play.metrics.Metrics
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status._
import play.api.libs.json.Json
import play.api.{Configuration, Environment}
import services.http.FakeSimpleHttp
import uk.gov.hmrc.http.HttpResponse
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import util.BaseSpec

class IdentityVerificationFrontendServiceSpec extends BaseSpec {

  trait SpecSetup {
    def httpResponse: HttpResponse
    def simulateIdentityVerificationFrontendIsDown: Boolean

    val anException = new RuntimeException("Any")
    val metricId = "get-iv-journey-status"

    lazy val (service, metrics, timer) = {
      val fakeSimpleHttp = {
        if (simulateIdentityVerificationFrontendIsDown) new FakeSimpleHttp(Right(anException))
        else new FakeSimpleHttp(Left(httpResponse))
      }

      val serviceConfig = app.injector.instanceOf[ServicesConfig]
      val timer = MockitoSugar.mock[Timer.Context]
      val identityVerificationFrontendService: IdentityVerificationFrontendService =
        new IdentityVerificationFrontendService(
          injected[Environment],
          injected[Configuration],
          fakeSimpleHttp,
          MockitoSugar.mock[Metrics],
          serviceConfig) {

          override val metricsOperator: MetricsOperator = MockitoSugar.mock[MetricsOperator]
          when(metricsOperator.startTimer(any())) thenReturn timer
        }

      (identityVerificationFrontendService, identityVerificationFrontendService.metricsOperator, timer)
    }
  }

  "Calling IdentityVerificationFrontend.getIVJourneyStatus" should {

    "return an IdentityVerificationSuccessResponse containing a journey status object when called with a journeyId" in new SpecSetup {
      override lazy val httpResponse = HttpResponse(OK, Some(Json.obj("token" -> "1234", "result" -> "LockedOut")))
      override lazy val simulateIdentityVerificationFrontendIsDown = false

      val r = service.getIVJourneyStatus("1234")

      await(r) shouldBe IdentityVerificationSuccessResponse("LockedOut")
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementSuccessCounter(metricId)
      verify(timer, times(1)).stop()
    }

    "return IdentityVerificationNotFoundResponse when called with a journeyId that causes a NOT FOUND response" in new SpecSetup {
      override lazy val httpResponse = HttpResponse(NOT_FOUND)
      override lazy val simulateIdentityVerificationFrontendIsDown = false

      val r = service.getIVJourneyStatus("4321")

      await(r) shouldBe IdentityVerificationNotFoundResponse
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementFailedCounter(metricId)
      verify(timer, times(1)).stop()
    }

    "return TaxCalculationUnexpectedResponse when an unexpected status is returned" in new SpecSetup {
      val seeOtherResponse = HttpResponse(SEE_OTHER)
      override lazy val httpResponse = seeOtherResponse
      override lazy val simulateIdentityVerificationFrontendIsDown = false

      val r = service.getIVJourneyStatus("1234")

      await(r) shouldBe IdentityVerificationUnexpectedResponse(seeOtherResponse)
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementFailedCounter(metricId)
      verify(timer, times(1)).stop()
    }

    "return IdentityVerificationErrorResponse when called and service is down" in new SpecSetup {
      override lazy val httpResponse = ???
      override lazy val simulateIdentityVerificationFrontendIsDown = true

      val r = service.getIVJourneyStatus("1234")

      await(r) shouldBe IdentityVerificationErrorResponse(anException)
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementFailedCounter(metricId)
      verify(timer, times(1)).stop()
    }

  }
} 
Example 37
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 38
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 39
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 40
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 41
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 42
Source File: EnrolmentsConnectorSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package connectors

import models._
import org.joda.time.DateTime
import org.mockito.Matchers.{any, eq => eqTo}
import org.mockito.Mockito.when
import org.scalatest.EitherValues
import org.scalatest.Inspectors.forAll
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status._
import play.api.libs.json.{JsObject, JsResultException, Json}
import uk.gov.hmrc.http.{HttpException, HttpResponse}
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import util.BaseSpec

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

class EnrolmentsConnectorSpec extends BaseSpec with MockitoSugar with ScalaFutures with EitherValues {

  val http = mock[DefaultHttpClient]
  val connector = new EnrolmentsConnector(http, config)
  val baseUrl = config.enrolmentStoreProxyUrl

  "getAssignedEnrolments" should {
    val utr = "1234500000"
    val url = s"$baseUrl/enrolment-store/enrolments/IR-SA~UTR~$utr/users"

    "Return the error message for a BAD_REQUEST response" in {
      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(BAD_REQUEST)))

      connector.getUserIdsWithEnrolments(utr).futureValue.left.value should include(BAD_REQUEST.toString)
    }

    "NO_CONTENT response should return no enrolments" in {
      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(NO_CONTENT)))

      connector.getUserIdsWithEnrolments(utr).futureValue.right.value shouldBe Seq.empty
    }

    "query users with no principal enrolment returns empty enrolments" in {
      val json = Json.parse("""
                              |{
                              |    "principalUserIds": [],
                              |     "delegatedUserIds": []
                              |}""".stripMargin)

      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(OK, Some(json))))

      connector.getUserIdsWithEnrolments(utr).futureValue.right.value shouldBe Seq.empty
    }

    "query users with assigned enrolment return two principleIds" in {
      val json = Json.parse("""
                              |{
                              |    "principalUserIds": [
                              |       "ABCEDEFGI1234567",
                              |       "ABCEDEFGI1234568"
                              |    ],
                              |    "delegatedUserIds": [
                              |     "dont care"
                              |    ]
                              |}""".stripMargin)

      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(OK, Some(json))))

      val expected = Seq("ABCEDEFGI1234567", "ABCEDEFGI1234568")

      connector.getUserIdsWithEnrolments(utr).futureValue.right.value shouldBe expected
    }
  }
} 
Example 43
Source File: PayApiConnectorSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package connectors

import models.{CreatePayment, PaymentRequest}
import org.mockito.Matchers.{any, eq => eqTo}
import org.mockito.Mockito.when
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status._
import play.api.libs.json.{JsResultException, Json}
import uk.gov.hmrc.http.HttpResponse
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import util.BaseSpec

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

class PayApiConnectorSpec extends BaseSpec with MockitoSugar with ScalaFutures {

  val http = mock[DefaultHttpClient]
  val connector = new PayApiConnector(http, config)
  val paymentRequest = PaymentRequest(config, "some utr")
  val postUrl = config.makeAPaymentUrl

  "createPayment" should {
    "parse the json load for a successful CREATED response" in {
      val json = Json.obj(
        "journeyId" -> "exampleJourneyId",
        "nextUrl"   -> "testNextUrl"
      )

      when(
        http.POST[PaymentRequest, HttpResponse](eqTo(postUrl), eqTo(paymentRequest), any())(any(), any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(CREATED, Some(json))))

      connector.createPayment(paymentRequest).futureValue shouldBe Some(
        CreatePayment("exampleJourneyId", "testNextUrl"))
    }

    "Returns a None when the status code is not CREATED" in {
      when(
        http.POST[PaymentRequest, HttpResponse](eqTo(postUrl), eqTo(paymentRequest), any())(any(), any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(BAD_REQUEST)))

      connector.createPayment(paymentRequest).futureValue shouldBe None
    }

    "Throws a JsResultException when given bad json" in {
      val badJson = Json.obj("abc" -> "invalidData")

      when(
        http.POST[PaymentRequest, HttpResponse](eqTo(postUrl), eqTo(paymentRequest), any())(any(), any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(CREATED, Some(badJson))))

      val f = connector.createPayment(paymentRequest)
      whenReady(f.failed) { e =>
        e shouldBe a[JsResultException]
      }
    }
  }
} 
Example 44
Source File: ScalastyleCheckerSpec.scala    From sonar-scala   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.mwz.sonar.scala
package scalastyle

import org.mockito.ArgumentMatchers._
import org.mockito.Mockito._
import org.scalastyle.{FileSpec, ScalastyleConfiguration, ScalastyleChecker => Checker}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.mockito.MockitoSugar

class ScalastyleCheckerSpec extends AnyFlatSpec with MockitoSugar {
  "ScalastyleChecker" should "checkFiles" in {
    val checker = mock[Checker[FileSpec]]
    when(checker.checkFiles(any(), any()))
      .thenReturn(List.empty)

    val config: ScalastyleConfiguration = new ScalastyleConfiguration(
      "SonarQube",
      commentFilter = true,
      List.empty
    )

    new ScalastyleChecker().checkFiles(checker, config, Seq.empty)

    verify(checker).checkFiles(any(), any())
  }
} 
Example 45
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 46
Source File: Mock.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.mocks

import org.mockito.{ArgumentMatchers => Matchers}
import org.mockito.Mockito
import org.mockito.stubbing.OngoingStubbing
import org.mockito.verification.VerificationMode
import org.scalatest.{BeforeAndAfterEach, Suite}
import org.scalatestplus.mockito.MockitoSugar

trait Mock extends MockitoSugar with BeforeAndAfterEach { _: Suite =>

  def any[T]() = Matchers.any[T]()
  def eqTo[T](t: T) = Matchers.eq[T](t)
  def when[T](t: T) = Mockito.when(t)
  def reset[T](t: T) = Mockito.reset(t)

  def verify[T](t: T): T = Mockito.verify(t)
  def verify[T](t: T, mode: VerificationMode): T = Mockito.verify(t, mode)
  def times(n: Int): VerificationMode = Mockito.times(n)
  def never: VerificationMode = Mockito.never()
  def once: VerificationMode = Mockito.times(1)

  implicit class stubbingOps[T](stubbing: OngoingStubbing[T]){
    def returns(t: T) = stubbing.thenReturn(t)
  }
} 
Example 47
Source File: OperationResponseSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema

import de.leanovate.swaggercheck.SwaggerChecks
import de.leanovate.swaggercheck.schema.model.{Definition, JsonPath, ValidationResult}
import de.leanovate.swaggercheck.shrinkable.{CheckJsString, CheckJsValue}
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito._
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.mockito.MockitoSugar

class OperationResponseSpec extends WordSpec with MustMatchers with MockitoSugar {
  "OperationResponse" should {
    "verify response body" in {
      val swaggerChecks = mock[SwaggerChecks]
      val bodySchema = mock[Definition]
      val response = OperationResponse(Some(bodySchema), Seq.empty)

      when(bodySchema.validate(any(), any(), any())(any())).thenReturn(ValidationResult.success)

      response.verify(swaggerChecks, Map.empty, "{}").isSuccess mustBe true

      verify(bodySchema).validate(swaggerChecks, JsonPath(), CheckJsValue.parse("{}"))(CheckJsValue.Adapter)
    }

    "verify response headers" in {
      val swaggerChecks = mock[SwaggerChecks]
      val headerSchema = mock[Definition]
      val response = OperationResponse(None, Seq("some header" -> headerSchema))

      when(headerSchema.validate(any(), any(), any())(any())).thenReturn(ValidationResult.success)

      response.verify(swaggerChecks, Map.empty, "{}").isSuccess mustBe true

      verifyZeroInteractions(headerSchema)

      response.verify(swaggerChecks, Map("some header" -> "something"), "{}").isSuccess mustBe true

      verify(headerSchema).validate[CheckJsValue](swaggerChecks, JsonPath(), CheckJsString.formatted("something"))(CheckJsValue.Adapter)
    }
  }
} 
Example 48
Source File: ArrayDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import org.mockito.Mockito._
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.mockito.MockitoSugar

class ArrayDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "ArrayDefinition" should {
    "accept any array if no item definition is set" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(array = Some(Seq(TestNode(), TestNode())))
      val schema = mock[Schema]

      val definition = ArrayDefinition(None, None, None)

      val result = definition.validate(schema, path, node)

      result mustBe ValidationSuccess
    }

    "succeed if item definition succeeds on all elements" in {
      val path = JsonPath("jsonpath")
      val item1 = TestNode()
      val item2 = TestNode()
      val node = TestNode(array = Some(Seq(item1, item2)))
      val schema = mock[Schema]
      val itemDefinition = mock[Definition]

      when(itemDefinition.validate(schema, path.index(0), item1)).thenReturn(ValidationSuccess)
      when(itemDefinition.validate(schema, path.index(1), item2)).thenReturn(ValidationSuccess)

      val definition = ArrayDefinition(None, None, Some(itemDefinition))

      definition.validate(schema, path, node) mustBe ValidationSuccess

      verify(itemDefinition).validate(schema, path.index(0), item1)
      verify(itemDefinition).validate(schema, path.index(1), item2)
    }

    "fail if item definition fails on one element" in {
      val path = JsonPath("jsonpath")
      val item1 = TestNode()
      val item2 = TestNode()
      val node = TestNode(array = Some(Seq(item1, item2)))
      val schema = mock[Schema]
      val itemDefinition = mock[Definition]

      when(itemDefinition.validate(schema, path.index(0), item1)).thenReturn(ValidationResult.error("error"))
      when(itemDefinition.validate(schema, path.index(1), item2)).thenReturn(ValidationSuccess)

      val definition = ArrayDefinition(None, None, Some(itemDefinition))

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head mustBe "error"
    }

    "fail if array has less then minItems" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(array = Some(Seq(TestNode(), TestNode())))
      val schema = mock[Schema]

      val definition = ArrayDefinition(Some(3), None, None)

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("should have at least 3 items in path jsonpath")
    }

    "fail if array has more then maxItems" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(array = Some(Seq(TestNode(), TestNode())))
      val schema = mock[Schema]

      val definition = ArrayDefinition(None, Some(1), None)

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("should have at least 1 items in path jsonpath")
    }

    "fail validation on everything that is not an array" in {
      val path = JsonPath("jsonpath")
      val node = TestNode()
      val schema = mock[Schema]

      val definition = ArrayDefinition(None, None, None)

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("should be an array in path jsonpath")
    }
  }
} 
Example 49
Source File: IntegerDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import de.leanovate.swaggercheck.schema.model.formats.ValueFormat
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}

class IntegerDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "IntegerDefinition" should {
    "accept any integer if no format or range is defined" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(integer = Some(BigInt(Long.MaxValue) + 12345))
      val schema = mock[Schema]

      val definition = IntegerDefinition(None, None, None)

      definition.validate(schema, path, node) mustBe ValidationSuccess
    }

    "accept values that match the defined format" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(integer = Some(BigInt(12345)))
      val schema = mock[Schema]
      val format = mock[ValueFormat[BigInt]]

      when(schema.findIntegerFormat("theformat")).thenReturn(Some(format))
      when(format.validate(path, BigInt(12345))).thenReturn(ValidationResult.success)

      val definition = IntegerDefinition(Some("theformat"), None, None)

      definition.validate(schema, path, node) mustBe ValidationSuccess

      verify(schema).findIntegerFormat("theformat")
      verify(format).validate(path, BigInt(12345))
    }

    "fail validation if value is less than minimum" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(integer = Some(BigInt(12345)))
      val schema = mock[Schema]

      val definition = IntegerDefinition(None, Some(BigInt(123456)), None)

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("has to be greater than 123456 in path jsonpath")
    }

    "fail validation if value is greater than maximum" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(integer = Some(BigInt(123456)))
      val schema = mock[Schema]

      val definition = IntegerDefinition(None, None, Some(BigInt(12345)))

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("has to be less than 12345 in path jsonpath")
    }

    "fail validation on everything that is not an integer" in {
      val path = JsonPath("jsonpath")
      val node = TestNode()
      val schema = mock[Schema]

      val definition = IntegerDefinition(None, None, None)

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("should be an integer in path jsonpath")
    }
  }
} 
Example 50
Source File: ReferenceDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import org.scalatest.{MustMatchers, WordSpec}
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar

class ReferenceDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "ReferenceDefinition" should {
    "delegate validation to referenced definition" in {
      val path = JsonPath("jsonpath")
      val node = TestNode()
      val schema = mock[Schema]
      val referencedDefinition = mock[Definition]

      when(schema.findByRef("reference")).thenReturn(Some(referencedDefinition))
      when(referencedDefinition.validate(schema, path, node)).thenReturn(ValidationResult.error("error1"))

      val definition = ReferenceDefinition("reference")

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head mustBe "error1"
    }

    "fail validation if referenced definition does not exists" in {
      val path = JsonPath("jsonpath")
      val node = TestNode()
      val schema = mock[Schema]

      when(schema.findByRef("reference")).thenReturn(None)

      val definition = ReferenceDefinition("reference")

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head mustBe "Referenced definition does not exists: reference"
    }
  }
} 
Example 51
Source File: NumberDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import de.leanovate.swaggercheck.schema.model.formats.ValueFormat
import org.mockito.Mockito._
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.mockito.MockitoSugar

class NumberDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "NumberDefinition" should {
    "accept any integer if no format or range is defined" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(number = Some(BigDecimal(Long.MaxValue) + 12345))
      val schema = mock[Schema]

      val definition = NumberDefinition(None, None, None)

      definition.validate(schema, path, node) mustBe ValidationSuccess
    }

    "accept values that match the defined format" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(number = Some(BigDecimal(12345.67)))
      val schema = mock[Schema]
      val format = mock[ValueFormat[BigDecimal]]

      when(schema.findNumberFormat("theformat")).thenReturn(Some(format))
      when(format.validate(path, BigDecimal(12345.67))).thenReturn(ValidationResult.success)

      val definition = NumberDefinition(Some("theformat"), None, None)

      definition.validate(schema, path, node) mustBe ValidationSuccess

      verify(schema).findNumberFormat("theformat")
      verify(format).validate(path, BigDecimal(12345.67))
    }

    "fail validation if value is less than minimum" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(number = Some(BigDecimal(12345.6)))
      val schema = mock[Schema]

      val definition = NumberDefinition(None, Some(BigDecimal(123456.7)), None)

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("has to be greater than 123456.7 in path jsonpath")
    }

    "fail validation if value is greater than maximum" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(number = Some(BigDecimal(123456.7)))
      val schema = mock[Schema]

      val definition = NumberDefinition(None, None, Some(BigDecimal(12345.6)))

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("has to be less than 12345.6 in path jsonpath")
    }

    "fail validation on everything that is not an integer" in {
      val path = JsonPath("jsonpath")
      val node = TestNode()
      val schema = mock[Schema]

      val definition = NumberDefinition(None, None, None)

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("should be a number in path jsonpath")
    }
  }
} 
Example 52
Source File: EmptyDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}

class EmptyDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "EmptyDefinition" should {
    "validate anything" in {
      val path = JsonPath("jsonpath")
      val node = TestNode()
      val schema = mock[Schema]

      val definition = EmptyDefinition

      definition.validate(schema, path, node) mustBe ValidationSuccess
    }
  }
} 
Example 53
Source File: OneOfDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}

class OneOfDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "OneOfDefinition" should {
    "succeed validation if one child succeed" in {
      val definition1 = mock[Definition]
      val definition2 = mock[Definition]
      val definition3 = mock[Definition]
      val schema = mock[Schema]
      val path = JsonPath("path")
      val node = TestNode()

      when(definition1.validate(schema, path, node)).thenReturn(ValidationResult.error("error1"))
      when(definition2.validate(schema, path, node)).thenReturn(ValidationResult.success)
      when(definition3.validate(schema, path, node)).thenReturn(ValidationResult.error("error2"))

      val definition = OneOfDefinition(Seq(definition1, definition2, definition3))

      definition.validate(schema, path, node) mustBe ValidationSuccess

      verify(definition1).validate(schema, path, node)
      verify(definition2).validate(schema, path, node)
      verify(definition3).validate(schema, path, node)
    }

    "fail validation if one child fails" in {
      val definition1 = mock[Definition]
      val definition2 = mock[Definition]
      val definition3 = mock[Definition]
      val schema = mock[Schema]
      val path = JsonPath("path")
      val node = TestNode()

      when(definition1.validate(schema, path, node)).thenReturn(ValidationResult.error("error1"))
      when(definition2.validate(schema, path, node)).thenReturn(ValidationResult.error("error2"))
      when(definition3.validate(schema, path, node)).thenReturn(ValidationResult.error("error3"))

      val definition = OneOfDefinition(Seq(definition1, definition2, definition3))

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result mustBe Seq("error1", "error2", "error3")
    }
  }
} 
Example 54
Source File: AllOfDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.mockito.Mockito._

class AllOfDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "AllOfDefinition" should {
    "succeed validation if all children succeed" in {
      val definition1 = mock[Definition]
      val definition2 = mock[Definition]
      val definition3 = mock[Definition]
      val schema = mock[Schema]
      val path = JsonPath("path")
      val node = TestNode()

      when(definition1.validate(schema, path, node)).thenReturn(ValidationResult.success)
      when(definition2.validate(schema, path, node)).thenReturn(ValidationResult.success)
      when(definition3.validate(schema, path, node)).thenReturn(ValidationResult.success)

      val definition = AllOfDefinition(Seq(definition1, definition2, definition3))

      definition.validate(schema, path, node) mustBe ValidationSuccess

      verify(definition1).validate(schema, path, node)
      verify(definition2).validate(schema, path, node)
      verify(definition3).validate(schema, path, node)
    }

    "fail validation if one child fails" in {
      val definition1 = mock[Definition]
      val definition2 = mock[Definition]
      val definition3 = mock[Definition]
      val schema = mock[Schema]
      val path = JsonPath("path")
      val node = TestNode()

      when(definition1.validate(schema, path, node)).thenReturn(ValidationResult.success)
      when(definition2.validate(schema, path, node)).thenReturn(ValidationResult.error("error"))
      when(definition3.validate(schema, path, node)).thenReturn(ValidationResult.success)

      val definition = AllOfDefinition(Seq(definition1, definition2, definition3))

      val result = definition.validate(schema, path, node)

      result mustBe ValidationResult.error("error")
    }
  }
} 
Example 55
Source File: BooleanDefinitionSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model

import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}

class BooleanDefinitionSpec extends WordSpec with MockitoSugar with MustMatchers {
  "BooleanDefinition" should {
    "succeed on any boolean value" in {
      val path = JsonPath("jsonpath")
      val node = TestNode(boolean = Some(true))
      val schema = mock[Schema]

      val definition = BooleanDefinition

      definition.validate(schema, path, node)  mustBe ValidationSuccess
    }

    "fail validation on everything that is not a boolean" in {
      val path = JsonPath("jsonpath")
      val node = TestNode()
      val schema = mock[Schema]

      val definition = BooleanDefinition

      val ValidationFailure(result) = definition.validate(schema, path, node)

      result must have size 1
      result.head must endWith("should be a boolean in path jsonpath")
    }
  }
} 
Example 56
Source File: ConsumerExtensionsSpec.scala    From embedded-kafka   with MIT License 5 votes vote down vote up
package net.manub.embeddedkafka

import net.manub.embeddedkafka.Codecs.stringValueCrDecoder
import net.manub.embeddedkafka.ConsumerExtensions._
import org.apache.kafka.clients.consumer.{
  ConsumerRecord,
  ConsumerRecords,
  KafkaConsumer
}
import org.apache.kafka.common.TopicPartition
import org.mockito.Mockito.{times, verify, when}
import org.scalatestplus.mockito.MockitoSugar

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

class ConsumerExtensionsSpec
    extends EmbeddedKafkaSpecSupport
    with MockitoSugar {

  "consumeLazily" should {
    "retry to get messages with the configured maximum number of attempts when poll fails" in {
      implicit val retryConf: ConsumerRetryConfig =
        ConsumerRetryConfig(2, 1.millis)

      val consumer = mock[KafkaConsumer[String, String]]
      val consumerRecords =
        new ConsumerRecords[String, String](
          Map
            .empty[TopicPartition, java.util.List[
              ConsumerRecord[String, String]
            ]]
            .asJava
        )

      when(consumer.poll(duration2JavaDuration(retryConf.poll)))
        .thenReturn(consumerRecords)

      consumer.consumeLazily[String]("topic")

      verify(consumer, times(retryConf.maximumAttempts))
        .poll(duration2JavaDuration(retryConf.poll))
    }

    "not retry to get messages with the configured maximum number of attempts when poll succeeds" in {
      implicit val retryConf: ConsumerRetryConfig =
        ConsumerRetryConfig(2, 1.millis)

      val consumer       = mock[KafkaConsumer[String, String]]
      val consumerRecord = mock[ConsumerRecord[String, String]]
      val consumerRecords = new ConsumerRecords[String, String](
        Map[TopicPartition, java.util.List[ConsumerRecord[String, String]]](
          new TopicPartition("topic", 1) -> List(consumerRecord).asJava
        ).asJava
      )

      when(consumer.poll(duration2JavaDuration(retryConf.poll)))
        .thenReturn(consumerRecords)

      consumer.consumeLazily[String]("topic")

      verify(consumer).poll(duration2JavaDuration(retryConf.poll))
    }

    "poll to get messages with the configured poll timeout" in {
      implicit val retryConf: ConsumerRetryConfig =
        ConsumerRetryConfig(1, 10.millis)

      val consumer = mock[KafkaConsumer[String, String]]
      val consumerRecords =
        new ConsumerRecords[String, String](
          Map
            .empty[TopicPartition, java.util.List[
              ConsumerRecord[String, String]
            ]]
            .asJava
        )

      when(consumer.poll(duration2JavaDuration(retryConf.poll)))
        .thenReturn(consumerRecords)

      consumer.consumeLazily[String]("topic")

      verify(consumer).poll(duration2JavaDuration(retryConf.poll))
    }
  }
} 
Example 57
Source File: ExasolRelationSuite.scala    From spark-exasol-connector   with Apache License 2.0 5 votes vote down vote up
package com.exasol.spark

import org.apache.spark.rdd.RDD
import org.apache.spark.sql.Row
import org.apache.spark.sql.sources._
import org.apache.spark.sql.types._

import com.exasol.spark.util.ExasolConnectionManager

import com.holdenkarau.spark.testing.DataFrameSuiteBase
import org.mockito.Mockito._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar

class ExasolRelationSuite
    extends AnyFunSuite
    with Matchers
    with MockitoSugar
    with DataFrameSuiteBase {

  test("buildScan returns RDD of empty Row-s when requiredColumns is empty (count pushdown)") {
    val query = "SELECT 1"
    val cntQuery = "SELECT COUNT(*) FROM (SELECT 1) A "
    val cnt = 5L

    val manager = mock[ExasolConnectionManager]
    when(manager.withCountQuery(cntQuery)).thenReturn(cnt)

    val relation = new ExasolRelation(spark.sqlContext, query, Option(new StructType), manager)
    val rdd = relation.buildScan()

    assert(rdd.isInstanceOf[RDD[Row]])
    assert(rdd.partitions.size === 4)
    assert(rdd.count === cnt)
    verify(manager, times(1)).withCountQuery(cntQuery)
  }

  test("unhandledFilters should keep non-pushed filters") {
    val schema: StructType = new StructType()
      .add("a", BooleanType)
      .add("b", StringType)
      .add("c", IntegerType)

    val filters = Array[Filter](
      LessThanOrEqual("c", "3"),
      EqualTo("b", "abc"),
      Not(EqualTo("a", false))
    )

    val nullFilters = Array(EqualNullSafe("b", "xyz"))

    val rel = new ExasolRelation(spark.sqlContext, "", Option(schema), null)

    assert(rel.unhandledFilters(filters) === Array.empty[Filter])
    assert(rel.unhandledFilters(filters ++ nullFilters) === nullFilters)
  }

} 
Example 58
Source File: ExasolRDDSuite.scala    From spark-exasol-connector   with Apache License 2.0 5 votes vote down vote up
package com.exasol.spark.rdd

import java.sql.Statement

import org.apache.spark.SparkContext
import org.apache.spark.sql.types.StructType

import com.exasol.jdbc.EXAConnection
import com.exasol.jdbc.EXAResultSet
import com.exasol.spark.util.ExasolConnectionManager

import org.mockito.Mockito._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar

class ExasolRDDSuite extends AnyFunSuite with Matchers with MockitoSugar {

  test("`getPartitions` returns correct set of partitions") {
    val sparkContext = mock[SparkContext]
    val mainConnection = mock[EXAConnection]
    val mainStatement = mock[Statement]
    val mainResultSet = mock[EXAResultSet]
    val manager = mock[ExasolConnectionManager]

    val handle: Int = 7

    when(manager.mainConnection).thenReturn(mainConnection)
    when(manager.subConnections(mainConnection)).thenReturn(Seq("url1", "url2"))
    when(mainConnection.createStatement()).thenReturn(mainStatement)
    when(mainStatement.executeQuery("")).thenReturn(mainResultSet)
    when(mainResultSet.GetHandle()).thenReturn(handle)

    val rdd = new ExasolRDD(sparkContext, "", StructType(Nil), manager)
    val partitions = rdd.getPartitions

    assert(partitions.size == 2)
    partitions.zipWithIndex.foreach {
      case (part, idx) =>
        assert(part.index === idx)
        assert(part.isInstanceOf[ExasolRDDPartition])
        assert(part.asInstanceOf[ExasolRDDPartition].handle === handle)
        assert(part.asInstanceOf[ExasolRDDPartition].connectionUrl === s"url${idx + 1}")
    }
    verify(manager, times(1)).mainConnection
    verify(manager, times(1)).subConnections(mainConnection)
  }

  test("`getPartitions` throws exceptions if main connection is null") {
    val sparkContext = mock[SparkContext]
    val manager = mock[ExasolConnectionManager]

    when(manager.mainConnection).thenReturn(null)

    val thrown = intercept[RuntimeException] {
      new ExasolRDD(sparkContext, "", StructType(Nil), manager).getPartitions
    }
    assert(thrown.getMessage === "Could not establish main connection to Exasol!")

    verify(manager, times(1)).mainConnection
  }

}