org.mockito.Mockito.verify Scala Examples
The following examples show how to use org.mockito.Mockito.verify.
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 |
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: TheFlashTweetsConsumerSpec.scala From KafkaPlayground with GNU General Public License v3.0 | 5 votes |
package com.github.pedrovgs.kafkaplayground.flash import com.github.pedrovgs.kafkaplayground.flash.elasticsearch.ElasticClient import com.github.pedrovgs.kafkaplayground.utils.EmbeddedKafkaServer import org.mockito.Mockito.verify import org.scalatest.concurrent.ScalaFutures import org.scalatest.mockito.MockitoSugar import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers} object TheFlashTweetsConsumerSpec { private val anyTopic = "topic" private val anyContent = "content" private val anyOtherContent = "anyOtherContent" } class TheFlashTweetsConsumerSpec extends FlatSpec with Matchers with EmbeddedKafkaServer with ScalaFutures with MockitoSugar with BeforeAndAfterEach { import TheFlashTweetsConsumerSpec._ private var elasticClient: ElasticClient = _ override protected def beforeEach(): Unit = { super.beforeEach() elasticClient = mock[ElasticClient] } "TheFlashTweetsConsumer" should "create a new document for the configured index using the messages polled from the kafka cluster" in { produceMessage(anyTopic, anyContent) givenAElasticConsumer().poll() val expectedId = s"topic_0_0" verify(elasticClient).insertOrUpdate(expectedId, anyContent) } it should "send more than a message to elasticsearch" in { produceMessage(anyTopic, anyContent) produceMessage(anyTopic, anyOtherContent) givenAElasticConsumer().poll() verify(elasticClient).insertOrUpdate("topic_0_0", anyContent) verify(elasticClient).insertOrUpdate("topic_0_1", anyOtherContent) } private def givenAElasticConsumer() = new TheFlashTweetsConsumer(kafkaServerAddress(), anyTopic, elasticClient) }
Example 3
Source File: StatusAndRouteCounterFilterSpec.scala From play-prometheus-filters with MIT License | 5 votes |
package com.github.stijndehaes.playprometheusfilters.filters import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults import com.github.stijndehaes.playprometheusfilters.mocks.MockController import io.prometheus.client.CollectorRegistry import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.verify import org.scalatest.mockito.MockitoSugar import org.scalatest.{MustMatchers, WordSpec} import org.scalatestplus.play.guice.GuiceOneAppPerSuite import play.api.Configuration import play.api.libs.typedmap.TypedMap import play.api.mvc.Results import play.api.routing.{HandlerDef, Router} import play.api.test.Helpers.stubControllerComponents import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits} import scala.concurrent.ExecutionContext.Implicits.global class StatusAndRouteCounterFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite { private implicit val mat = app.materializer private val configuration = mock[Configuration] "Filter constructor" should { "Add a histogram to the prometheus registry" in { val collectorRegistry = mock[CollectorRegistry] new StatusAndRouteLatencyFilter(collectorRegistry, configuration) verify(collectorRegistry).register(any()) } } "Apply method" should { "Measure the count" in { val filter = new StatusAndRouteCounterFilter(mock[CollectorRegistry], configuration) val rh = FakeRequest().withAttrs( TypedMap( Router.Attrs.HandlerDef -> HandlerDef(null, null, "testController", "test", null, "GET", "/path", null ,null) )) val action = new MockController(stubControllerComponents()).ok await(filter(action)(rh).run()) val metrics = filter.metrics(0).metric.collect() metrics must have size 1 val samples = metrics.get(0).samples //this is the count sample val countSample = samples.get(0) countSample.value mustBe 1.0 countSample.labelValues must have size 5 countSample.labelValues.get(0) mustBe "test" countSample.labelValues.get(1) mustBe "200" countSample.labelValues.get(2) mustBe "testController" countSample.labelValues.get(3) mustBe "/path" countSample.labelValues.get(4) mustBe "GET" } "Measure the count for an unmatched route" in { val filter = new StatusAndRouteCounterFilter(mock[CollectorRegistry], configuration) val rh = FakeRequest() val action = new MockController(stubControllerComponents()).error await(filter(action)(rh).run()) val metrics = filter.metrics(0).metric.collect() metrics must have size 1 val samples = metrics.get(0).samples //this is the count sample val countSample = samples.get(0) countSample.value mustBe 1.0 countSample.labelValues must have size 5 countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString countSample.labelValues.get(1) mustBe "404" countSample.labelValues.get(2) mustBe DefaultPlayUnmatchedDefaults.UnmatchedControllerString countSample.labelValues.get(3) mustBe DefaultPlayUnmatchedDefaults.UnmatchedPathString countSample.labelValues.get(4) mustBe DefaultPlayUnmatchedDefaults.UnmatchedVerbString } } }
Example 4
Source File: StatusAndRouteLatencyFilterSpec.scala From play-prometheus-filters with MIT License | 5 votes |
package com.github.stijndehaes.playprometheusfilters.filters import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults import com.github.stijndehaes.playprometheusfilters.mocks.MockController import io.prometheus.client.CollectorRegistry import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.verify import org.scalatest.mockito.MockitoSugar import org.scalatest.{MustMatchers, WordSpec} import org.scalatestplus.play.guice.GuiceOneAppPerSuite import play.api.Configuration import play.api.libs.typedmap.TypedMap import play.api.mvc.Results import play.api.routing.{HandlerDef, Router} import play.api.test.Helpers.stubControllerComponents import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits} import scala.concurrent.ExecutionContext.Implicits.global class StatusAndRouteLatencyFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite { private implicit val mat = app.materializer private val configuration = mock[Configuration] "Filter constructor" should { "Add a histogram to the prometheus registry" in { val collectorRegistry = mock[CollectorRegistry] new StatusAndRouteLatencyFilter(collectorRegistry, configuration) verify(collectorRegistry).register(any()) } } "Apply method" should { "Measure the latency" in { val filter = new StatusAndRouteLatencyFilter(mock[CollectorRegistry], configuration) val rh = FakeRequest().withAttrs( TypedMap( Router.Attrs.HandlerDef -> HandlerDef(null, null, "testController", "test", null, "GET", "/path", null ,null) )) val action = new MockController(stubControllerComponents()).ok await(filter(action)(rh).run()) val metrics = filter.metrics(0).metric.collect() metrics must have size 1 val samples = metrics.get(0).samples //this is the count sample val countSample = samples.get(samples.size() - 2) countSample.value mustBe 1.0 countSample.labelValues must have size 5 countSample.labelValues.get(0) mustBe "test" countSample.labelValues.get(1) mustBe "200" countSample.labelValues.get(2) mustBe "testController" countSample.labelValues.get(3) mustBe "/path" countSample.labelValues.get(4) mustBe "GET" } "Measure the latency for an unmatched route" in { val filter = new StatusAndRouteLatencyFilter(mock[CollectorRegistry], configuration) val rh = FakeRequest() val action = new MockController(stubControllerComponents()).error await(filter(action)(rh).run()) val metrics = filter.metrics(0).metric.collect() metrics must have size 1 val samples = metrics.get(0).samples //this is the count sample val countSample = samples.get(samples.size() - 2) countSample.value mustBe 1.0 countSample.labelValues must have size 5 countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString countSample.labelValues.get(1) mustBe "404" countSample.labelValues.get(2) mustBe DefaultPlayUnmatchedDefaults.UnmatchedControllerString countSample.labelValues.get(3) mustBe DefaultPlayUnmatchedDefaults.UnmatchedPathString countSample.labelValues.get(4) mustBe DefaultPlayUnmatchedDefaults.UnmatchedVerbString } } }
Example 5
Source File: StatusCounterFilterSpec.scala From play-prometheus-filters with MIT License | 5 votes |
package com.github.stijndehaes.playprometheusfilters.filters import com.github.stijndehaes.playprometheusfilters.mocks.MockController import io.prometheus.client.CollectorRegistry import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.verify import org.scalatest.mockito.MockitoSugar import org.scalatest.{MustMatchers, WordSpec} import org.scalatestplus.play.guice.GuiceOneAppPerSuite import play.api.Configuration import play.api.mvc.Results import play.api.test.Helpers.stubControllerComponents import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits} import scala.concurrent.ExecutionContext.Implicits.global class StatusCounterFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite { private implicit val mat = app.materializer private val configuration = mock[Configuration] "Filter constructor" should { "Add a counter to the prometheus registry" in { val collectorRegistry = mock[CollectorRegistry] new StatusCounterFilter(collectorRegistry, configuration) verify(collectorRegistry).register(any()) } } "Apply method" should { "Count the requests with status" in { val filter = new StatusCounterFilter(mock[CollectorRegistry], configuration) val rh = FakeRequest() val action = new MockController(stubControllerComponents()).ok await(filter(action)(rh).run()) val metrics = filter.metrics(0).metric.collect() metrics must have size 1 val samples = metrics.get(0).samples samples.get(0).value mustBe 1.0 samples.get(0).labelValues must have size 1 samples.get(0).labelValues.get(0) mustBe "200" } } }
Example 6
Source File: RouteLatencyFilterSpec.scala From play-prometheus-filters with MIT License | 5 votes |
package com.github.stijndehaes.playprometheusfilters.filters import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults import com.github.stijndehaes.playprometheusfilters.mocks.MockController import io.prometheus.client.CollectorRegistry import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.verify import org.scalatest.mockito.MockitoSugar import org.scalatest.{MustMatchers, WordSpec} import org.scalatestplus.play.guice.GuiceOneAppPerSuite import play.api.Configuration import play.api.libs.typedmap.TypedMap import play.api.mvc._ import play.api.routing.{HandlerDef, Router} import play.api.test.Helpers.stubControllerComponents import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits} import scala.concurrent.ExecutionContext.Implicits.global class RouteLatencyFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite { private implicit val mat = app.materializer private val configuration = mock[Configuration] "Filter constructor" should { "Add a histogram to the prometheus registry" in { val collectorRegistry = mock[CollectorRegistry] new RouteLatencyFilter(collectorRegistry, configuration) verify(collectorRegistry).register(any()) } } "Apply method" should { "Measure the latency" in { val filter = new RouteLatencyFilter(mock[CollectorRegistry], configuration) val rh = FakeRequest().withAttrs( TypedMap( Router.Attrs.HandlerDef -> HandlerDef(null, null, null, "test", null, null ,null ,null ,null) )) val action = new MockController(stubControllerComponents()).ok await(filter(action)(rh).run()) val metrics = filter.metrics(0).metric.collect() metrics must have size 1 val samples = metrics.get(0).samples //this is the count sample val countSample = samples.get(samples.size() - 2) countSample.value mustBe 1.0 countSample.labelValues must have size 1 countSample.labelValues.get(0) mustBe "test" } "Measure the latency for an unmatched route" in { val filter = new RouteLatencyFilter(mock[CollectorRegistry], configuration) val rh = FakeRequest() val action = new MockController(stubControllerComponents()).error await(filter(action)(rh).run()) val metrics = filter.metrics(0).metric.collect() metrics must have size 1 val samples = metrics.get(0).samples //this is the count sample val countSample = samples.get(samples.size() - 2) countSample.value mustBe 1.0 countSample.labelValues must have size 1 countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString } } }
Example 7
Source File: RecordIOOutputFormatTests.scala From sagemaker-spark with Apache License 2.0 | 5 votes |
package com.amazonaws.services.sagemaker.sparksdk.protobuf import java.io.ByteArrayOutputStream import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path} import org.apache.hadoop.io.{BytesWritable, NullWritable} import org.apache.hadoop.mapreduce.TaskAttemptContext import org.mockito.Matchers.any import org.mockito.Mockito.{verify, when} import org.scalatest.{BeforeAndAfter, FlatSpec} import org.scalatest.mock.MockitoSugar import com.amazonaws.services.sagemaker.sparksdk.protobuf.RecordIOOutputFormat.SageMakerProtobufRecordWriter class RecordIOOutputFormatTests extends FlatSpec with MockitoSugar with BeforeAndAfter { var sagemakerProtobufRecordWriter: SageMakerProtobufRecordWriter = _ var mockOutputStream : FSDataOutputStream = _ var byteArrayOutputStream: ByteArrayOutputStream = _ var mockTaskAttemptContext: TaskAttemptContext = _ var mockPath: Path = _ var mockFileSystem: FileSystem = _ before { byteArrayOutputStream = new ByteArrayOutputStream() mockOutputStream = mock[FSDataOutputStream] sagemakerProtobufRecordWriter = new SageMakerProtobufRecordWriter(mockOutputStream) mockTaskAttemptContext = mock[TaskAttemptContext] mockPath = mock[Path] mockFileSystem = mock[FileSystem] } it should "write an empty array of bytes" in { val bytesWritable = new BytesWritable(byteArrayOutputStream.toByteArray) val bytes = ProtobufConverter.byteArrayToRecordIOEncodedByteArray(bytesWritable.getBytes) sagemakerProtobufRecordWriter.write(NullWritable.get(), bytesWritable) verify(mockOutputStream).write(bytes, 0, bytes.length) } it should "write an array of bytes" in { val byteArray = Array[Byte](0, 0, 0, 0) byteArrayOutputStream.write(byteArray) val bytesWritable = new BytesWritable(byteArrayOutputStream.toByteArray) val bytes = ProtobufConverter.byteArrayToRecordIOEncodedByteArray(bytesWritable.getBytes) sagemakerProtobufRecordWriter.write(NullWritable.get(), bytesWritable) verify(mockOutputStream).write(bytes, 0, bytes.length) } it should "write an array of bytes, padding as necessary" in { byteArrayOutputStream.write(5) val bytesWritable = new BytesWritable(byteArrayOutputStream.toByteArray) val bytes = ProtobufConverter.byteArrayToRecordIOEncodedByteArray(bytesWritable.getBytes) sagemakerProtobufRecordWriter.write(NullWritable.get(), bytesWritable) verify(mockOutputStream).write(bytes, 0, bytes.length) } it should "write an array of bytes, padding only as much as necessary" in { byteArrayOutputStream.write(Array[Byte](0, 0, 0, 0, 0)) val bytesWritable = new BytesWritable(byteArrayOutputStream.toByteArray) val bytes = ProtobufConverter.byteArrayToRecordIOEncodedByteArray(bytesWritable.getBytes) sagemakerProtobufRecordWriter.write(NullWritable.get(), bytesWritable) verify(mockOutputStream).write(bytes, 0, bytes.length) } it should "create a record writer from a FSDataOutputStream created by the filesystem" in { val mockTaskAttemptContext = mock[TaskAttemptContext] val mockPath = mock[Path] val mockFileSystem = mock[FileSystem] when(mockPath.getFileSystem(any[Configuration])).thenReturn(mockFileSystem) new RecordIOOutputFormat() { override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = { mockPath } }.getRecordWriter(mockTaskAttemptContext) verify(mockFileSystem).create(mockPath, true) } }
Example 8
Source File: MasterWebUISuite.scala From Spark-2.3.1 with Apache License 2.0 | 5 votes |
package org.apache.spark.deploy.master.ui import java.io.DataOutputStream import java.net.{HttpURLConnection, URL} import java.nio.charset.StandardCharsets import java.util.Date import scala.collection.mutable.HashMap import org.mockito.Mockito.{mock, times, verify, when} import org.scalatest.BeforeAndAfterAll import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite} import org.apache.spark.deploy.DeployMessages.{KillDriverResponse, RequestKillDriver} import org.apache.spark.deploy.DeployTestUtils._ import org.apache.spark.deploy.master._ import org.apache.spark.rpc.{RpcEndpointRef, RpcEnv} class MasterWebUISuite extends SparkFunSuite with BeforeAndAfterAll { val conf = new SparkConf val securityMgr = new SecurityManager(conf) val rpcEnv = mock(classOf[RpcEnv]) val master = mock(classOf[Master]) val masterEndpointRef = mock(classOf[RpcEndpointRef]) when(master.securityMgr).thenReturn(securityMgr) when(master.conf).thenReturn(conf) when(master.rpcEnv).thenReturn(rpcEnv) when(master.self).thenReturn(masterEndpointRef) val masterWebUI = new MasterWebUI(master, 0) override def beforeAll() { super.beforeAll() masterWebUI.bind() } override def afterAll() { masterWebUI.stop() super.afterAll() } test("kill application") { val appDesc = createAppDesc() // use new start date so it isn't filtered by UI val activeApp = new ApplicationInfo( new Date().getTime, "app-0", appDesc, new Date(), null, Int.MaxValue) when(master.idToApp).thenReturn(HashMap[String, ApplicationInfo]((activeApp.id, activeApp))) val url = s"http://localhost:${masterWebUI.boundPort}/app/kill/" val body = convPostDataToString(Map(("id", activeApp.id), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify the master was called to remove the active app verify(master, times(1)).removeApplication(activeApp, ApplicationState.KILLED) } test("kill driver") { val activeDriverId = "driver-0" val url = s"http://localhost:${masterWebUI.boundPort}/driver/kill/" val body = convPostDataToString(Map(("id", activeDriverId), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify that master was asked to kill driver with the correct id verify(masterEndpointRef, times(1)).ask[KillDriverResponse](RequestKillDriver(activeDriverId)) } private def convPostDataToString(data: Map[String, String]): String = { (for ((name, value) <- data) yield s"$name=$value").mkString("&") } private def sendHttpRequest( url: String, method: String, body: String = ""): HttpURLConnection = { val conn = new URL(url).openConnection().asInstanceOf[HttpURLConnection] conn.setRequestMethod(method) if (body.nonEmpty) { conn.setDoOutput(true) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") conn.setRequestProperty("Content-Length", Integer.toString(body.length)) val out = new DataOutputStream(conn.getOutputStream) out.write(body.getBytes(StandardCharsets.UTF_8)) out.close() } conn } }
Example 9
Source File: ExecutionServiceSpec.scala From mist with Apache License 2.0 | 5 votes |
package io.hydrosphere.mist.master.execution import akka.actor.ActorSystem import akka.testkit.{TestKit, TestProbe} import io.hydrosphere.mist.core.{FunctionInfoData, MockitoSugar} import io.hydrosphere.mist.master.Messages.StatusMessages.UpdateStatusEvent import io.hydrosphere.mist.master.execution.status.StatusReporter import io.hydrosphere.mist.master.execution.workers.WorkerHub import io.hydrosphere.mist.master.models.JobStartRequest import io.hydrosphere.mist.master.store.JobRepository import io.hydrosphere.mist.master.{JobDetails, TestData, TestUtils} import org.scalatest._ import org.mockito.Mockito.verify import mist.api.data._ import mist.api.encoding.defaultEncoders._ import mist.api.encoding.JsSyntax._ import scala.concurrent.Await import scala.concurrent.duration.Duration class ExecutionServiceSpec extends TestKit(ActorSystem("testMasterService")) with FunSpecLike with Matchers with MockitoSugar with TestData { describe("jobs starting") { it("should start job") { val execution = TestProbe() val repo = mock[JobRepository] val hub = mock[WorkerHub] val reporter = mock[StatusReporter] when(repo.update(any[JobDetails])).thenSuccess(()) val service = new ExecutionService(execution.ref, hub, reporter, repo) val future = service.startJob( JobStartRequest( id = "id", function = FunctionInfoData("name", path="path", className="className", defaultContext="context"), context = TestUtils.contextSettings.default, parameters = JsMap("1" -> 2.js), source = JobDetails.Source.Http, externalId = None )) execution.expectMsgType[ContextEvent.RunJobCommand] execution.reply(ExecutionInfo(req = mkRunReq("id"))) val executionInfo = Await.result(future, Duration.Inf) executionInfo.request.id shouldBe "id" verify(reporter).reportPlain(any[UpdateStatusEvent]) } } describe("jobs stopping") { it("should stop job") { //TODO val contextsMaster = TestProbe() val repo = mock[JobRepository] val hub = mock[WorkerHub] val reporter = mock[StatusReporter] when(repo.get(any[String])) .thenSuccess(Some(mkDetails(JobDetails.Status.Started))) .thenSuccess(Some(mkDetails(JobDetails.Status.Canceled))) val service = new ExecutionService(contextsMaster.ref, hub, reporter, repo) val future = service.stopJob("id") contextsMaster.expectMsgType[ContextEvent.CancelJobCommand] contextsMaster.reply(ContextEvent.JobCancelledResponse("id", mkDetails(JobDetails.Status.Canceled))) val details = Await.result(future, Duration.Inf) details.get.status shouldBe JobDetails.Status.Canceled } } }
Example 10
Source File: LogStreamsSpec.scala From mist with Apache License 2.0 | 5 votes |
package io.hydrosphere.mist.master.logging import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.scaladsl.{Keep, Sink, Source} import akka.testkit.TestKit import io.hydrosphere.mist.core.MockitoSugar import io.hydrosphere.mist.core.logging.LogEvent import io.hydrosphere.mist.master.FilteredException import org.mockito.Mockito.verify import org.scalatest.{FunSpecLike, Matchers} import scala.concurrent.duration._ import scala.concurrent.{Await, Future} class LogStreamsSpec extends TestKit(ActorSystem("log-service-test")) with FunSpecLike with MockitoSugar with Matchers { implicit val materializer = ActorMaterializer() it("should store events") { val writer = mock[LogsWriter] when(writer.write(any[String], any[Seq[LogEvent]])) .thenReturn(Future.successful(LogUpdate("jobId", Seq.empty, 1))) val out = Source.single(LogEvent.mkDebug("id", "message")) .via(LogStreams.storeFlow(writer)) .take(1) .toMat(Sink.seq)(Keep.right).run() val updates = Await.result(out, Duration.Inf) updates.size shouldBe 1 verify(writer).write(any[String], any[Seq[LogEvent]]) } it("should ignore errors") { val event = LogEvent.mkDebug("id", "message") val writer = mock[LogsWriter] when(writer.write(any[String], any[Seq[LogEvent]])) .thenSuccess(LogUpdate("id", Seq(event), 1)) .thenFailure(FilteredException()) .thenSuccess(LogUpdate("id", Seq(event), 1)) .thenFailure(FilteredException()) .thenSuccess(LogUpdate("id", Seq(event), 1)) val in = (1 to 5).map(i => LogEvent.mkDebug(s"job-$i", "message")) val future = Source(in) .via(LogStreams.storeFlow(writer)) .take(3) .toMat(Sink.seq)(Keep.right).run() val updates = Await.result(future, Duration.Inf) updates.flatMap(_.events).size shouldBe 3 } }
Example 11
Source File: BatchChangeHandlerSpec.scala From vinyldns with Apache License 2.0 | 5 votes |
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 12
Source File: HeartbeatReceiverSuite.scala From iolap with Apache License 2.0 | 5 votes |
package org.apache.spark import scala.concurrent.duration._ import scala.language.postfixOps import org.apache.spark.executor.TaskMetrics import org.apache.spark.storage.BlockManagerId import org.mockito.Mockito.{mock, spy, verify, when} import org.mockito.Matchers import org.mockito.Matchers._ import org.apache.spark.scheduler.TaskScheduler import org.apache.spark.util.RpcUtils import org.scalatest.concurrent.Eventually._ class HeartbeatReceiverSuite extends SparkFunSuite with LocalSparkContext { test("HeartbeatReceiver") { sc = spy(new SparkContext("local[2]", "test")) val scheduler = mock(classOf[TaskScheduler]) when(scheduler.executorHeartbeatReceived(any(), any(), any())).thenReturn(true) when(sc.taskScheduler).thenReturn(scheduler) val heartbeatReceiver = new HeartbeatReceiver(sc) sc.env.rpcEnv.setupEndpoint("heartbeat", heartbeatReceiver).send(TaskSchedulerIsSet) eventually(timeout(5 seconds), interval(5 millis)) { assert(heartbeatReceiver.scheduler != null) } val receiverRef = RpcUtils.makeDriverRef("heartbeat", sc.conf, sc.env.rpcEnv) val metrics = new TaskMetrics val blockManagerId = BlockManagerId("executor-1", "localhost", 12345) val response = receiverRef.askWithRetry[HeartbeatResponse]( Heartbeat("executor-1", Array(1L -> metrics), blockManagerId)) verify(scheduler).executorHeartbeatReceived( Matchers.eq("executor-1"), Matchers.eq(Array(1L -> metrics)), Matchers.eq(blockManagerId)) assert(false === response.reregisterBlockManager) } test("HeartbeatReceiver re-register") { sc = spy(new SparkContext("local[2]", "test")) val scheduler = mock(classOf[TaskScheduler]) when(scheduler.executorHeartbeatReceived(any(), any(), any())).thenReturn(false) when(sc.taskScheduler).thenReturn(scheduler) val heartbeatReceiver = new HeartbeatReceiver(sc) sc.env.rpcEnv.setupEndpoint("heartbeat", heartbeatReceiver).send(TaskSchedulerIsSet) eventually(timeout(5 seconds), interval(5 millis)) { assert(heartbeatReceiver.scheduler != null) } val receiverRef = RpcUtils.makeDriverRef("heartbeat", sc.conf, sc.env.rpcEnv) val metrics = new TaskMetrics val blockManagerId = BlockManagerId("executor-1", "localhost", 12345) val response = receiverRef.askWithRetry[HeartbeatResponse]( Heartbeat("executor-1", Array(1L -> metrics), blockManagerId)) verify(scheduler).executorHeartbeatReceived( Matchers.eq("executor-1"), Matchers.eq(Array(1L -> metrics)), Matchers.eq(blockManagerId)) assert(true === response.reregisterBlockManager) } }
Example 13
Source File: MasterWebUISuite.scala From multi-tenancy-spark with Apache License 2.0 | 5 votes |
package org.apache.spark.deploy.master.ui import java.io.DataOutputStream import java.net.{HttpURLConnection, URL} import java.nio.charset.StandardCharsets import java.util.Date import scala.collection.mutable.HashMap import org.mockito.Mockito.{mock, times, verify, when} import org.scalatest.BeforeAndAfterAll import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite} import org.apache.spark.deploy.DeployMessages.{KillDriverResponse, RequestKillDriver} import org.apache.spark.deploy.DeployTestUtils._ import org.apache.spark.deploy.master._ import org.apache.spark.rpc.{RpcEndpointRef, RpcEnv} class MasterWebUISuite extends SparkFunSuite with BeforeAndAfterAll { val conf = new SparkConf val securityMgr = new SecurityManager(conf) val rpcEnv = mock(classOf[RpcEnv]) val master = mock(classOf[Master]) val masterEndpointRef = mock(classOf[RpcEndpointRef]) when(master.securityMgr).thenReturn(securityMgr) when(master.conf).thenReturn(conf) when(master.rpcEnv).thenReturn(rpcEnv) when(master.self).thenReturn(masterEndpointRef) val masterWebUI = new MasterWebUI(master, 0) override def beforeAll() { super.beforeAll() masterWebUI.bind() } override def afterAll() { masterWebUI.stop() super.afterAll() } test("kill application") { val appDesc = createAppDesc() // use new start date so it isn't filtered by UI val activeApp = new ApplicationInfo( new Date().getTime, "app-0", appDesc, new Date(), null, Int.MaxValue) when(master.idToApp).thenReturn(HashMap[String, ApplicationInfo]((activeApp.id, activeApp))) val url = s"http://localhost:${masterWebUI.boundPort}/app/kill/" val body = convPostDataToString(Map(("id", activeApp.id), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify the master was called to remove the active app verify(master, times(1)).removeApplication(activeApp, ApplicationState.KILLED) } test("kill driver") { val activeDriverId = "driver-0" val url = s"http://localhost:${masterWebUI.boundPort}/driver/kill/" val body = convPostDataToString(Map(("id", activeDriverId), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify that master was asked to kill driver with the correct id verify(masterEndpointRef, times(1)).ask[KillDriverResponse](RequestKillDriver(activeDriverId)) } private def convPostDataToString(data: Map[String, String]): String = { (for ((name, value) <- data) yield s"$name=$value").mkString("&") } private def sendHttpRequest( url: String, method: String, body: String = ""): HttpURLConnection = { val conn = new URL(url).openConnection().asInstanceOf[HttpURLConnection] conn.setRequestMethod(method) if (body.nonEmpty) { conn.setDoOutput(true) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") conn.setRequestProperty("Content-Length", Integer.toString(body.length)) val out = new DataOutputStream(conn.getOutputStream) out.write(body.getBytes(StandardCharsets.UTF_8)) out.close() } conn } }
Example 14
Source File: MultipleContainersSpec.scala From testcontainers-scala with MIT License | 5 votes |
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 15
Source File: SignalRefreshedTemplateSourceSpec.scala From cluster-broccoli with Apache License 2.0 | 5 votes |
package de.frosner.broccoli.templates import de.frosner.broccoli.signal.SignalManager import org.mockito.Mockito.{times, verify} import org.mockito.{ArgumentCaptor, Matchers} import org.specs2.mock.Mockito import org.specs2.mutable.Specification import sun.misc.{Signal, SignalHandler} class SignalRefreshedTemplateSourceSpec extends Specification with Mockito { "Receiving a SIGUSR2 signal" should { "update the cache" in { val signalManager = mock[SignalManager] val testTemplateSource = mock[CachedTemplateSource] val signalRefreshedTemplateSource = new SignalRefreshedTemplateSource(testTemplateSource, signalManager) val handler = ArgumentCaptor.forClass(classOf[SignalHandler]) there was one(signalManager).register(Matchers.eq(new Signal("USR2")), handler.capture()) there was no(testTemplateSource).refresh() there was no(testTemplateSource).loadTemplates() signalRefreshedTemplateSource.loadTemplates() there was no(testTemplateSource).refresh() there was one(testTemplateSource).loadTemplates() verify(testTemplateSource, times(1)).loadTemplates() handler.getValue.handle(new Signal("USR2")) there was one(testTemplateSource).refresh() there was one(testTemplateSource).loadTemplates() } } }
Example 16
Source File: MasterWebUISuite.scala From sparkoscope with Apache License 2.0 | 5 votes |
package org.apache.spark.deploy.master.ui import java.io.DataOutputStream import java.net.{HttpURLConnection, URL} import java.nio.charset.StandardCharsets import java.util.Date import scala.collection.mutable.HashMap import org.mockito.Mockito.{mock, times, verify, when} import org.scalatest.BeforeAndAfterAll import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite} import org.apache.spark.deploy.DeployMessages.{KillDriverResponse, RequestKillDriver} import org.apache.spark.deploy.DeployTestUtils._ import org.apache.spark.deploy.master._ import org.apache.spark.rpc.{RpcEndpointRef, RpcEnv} class MasterWebUISuite extends SparkFunSuite with BeforeAndAfterAll { val conf = new SparkConf val securityMgr = new SecurityManager(conf) val rpcEnv = mock(classOf[RpcEnv]) val master = mock(classOf[Master]) val masterEndpointRef = mock(classOf[RpcEndpointRef]) when(master.securityMgr).thenReturn(securityMgr) when(master.conf).thenReturn(conf) when(master.rpcEnv).thenReturn(rpcEnv) when(master.self).thenReturn(masterEndpointRef) val masterWebUI = new MasterWebUI(master, 0) override def beforeAll() { super.beforeAll() masterWebUI.bind() } override def afterAll() { masterWebUI.stop() super.afterAll() } test("kill application") { val appDesc = createAppDesc() // use new start date so it isn't filtered by UI val activeApp = new ApplicationInfo( new Date().getTime, "app-0", appDesc, new Date(), null, Int.MaxValue) when(master.idToApp).thenReturn(HashMap[String, ApplicationInfo]((activeApp.id, activeApp))) val url = s"http://localhost:${masterWebUI.boundPort}/app/kill/" val body = convPostDataToString(Map(("id", activeApp.id), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify the master was called to remove the active app verify(master, times(1)).removeApplication(activeApp, ApplicationState.KILLED) } test("kill driver") { val activeDriverId = "driver-0" val url = s"http://localhost:${masterWebUI.boundPort}/driver/kill/" val body = convPostDataToString(Map(("id", activeDriverId), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify that master was asked to kill driver with the correct id verify(masterEndpointRef, times(1)).ask[KillDriverResponse](RequestKillDriver(activeDriverId)) } private def convPostDataToString(data: Map[String, String]): String = { (for ((name, value) <- data) yield s"$name=$value").mkString("&") } private def sendHttpRequest( url: String, method: String, body: String = ""): HttpURLConnection = { val conn = new URL(url).openConnection().asInstanceOf[HttpURLConnection] conn.setRequestMethod(method) if (body.nonEmpty) { conn.setDoOutput(true) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") conn.setRequestProperty("Content-Length", Integer.toString(body.length)) val out = new DataOutputStream(conn.getOutputStream) out.write(body.getBytes(StandardCharsets.UTF_8)) out.close() } conn } }
Example 17
Source File: SessionHeartbeatSpec.scala From incubator-livy with Apache License 2.0 | 5 votes |
package org.apache.livy.server.interactive import scala.concurrent.duration._ import scala.concurrent.Future import scala.language.postfixOps import org.mockito.Mockito.{never, verify, when} import org.scalatest.{FunSpec, Matchers} import org.scalatest.concurrent.Eventually._ import org.scalatest.mock.MockitoSugar.mock import org.apache.livy.LivyConf import org.apache.livy.server.recovery.SessionStore import org.apache.livy.sessions.{Session, SessionManager} import org.apache.livy.sessions.Session.RecoveryMetadata class SessionHeartbeatSpec extends FunSpec with Matchers { describe("SessionHeartbeat") { class TestHeartbeat(override val heartbeatTimeout: FiniteDuration) extends SessionHeartbeat {} it("should not expire if heartbeat was never called.") { val t = new TestHeartbeat(Duration.Zero) t.heartbeatExpired shouldBe false } it("should expire if time has elapsed.") { val t = new TestHeartbeat(Duration.fromNanos(1)) t.heartbeat() eventually(timeout(2 nano), interval(1 nano)) { t.heartbeatExpired shouldBe true } } it("should not expire if time hasn't elapsed.") { val t = new TestHeartbeat(Duration.create(1, DAYS)) t.heartbeat() t.heartbeatExpired shouldBe false } } describe("SessionHeartbeatWatchdog") { abstract class TestSession extends Session(0, None, null, null) with SessionHeartbeat {} class TestWatchdog(conf: LivyConf) extends SessionManager[TestSession, RecoveryMetadata]( conf, { _ => assert(false).asInstanceOf[TestSession] }, mock[SessionStore], "test", Some(Seq.empty)) with SessionHeartbeatWatchdog[TestSession, RecoveryMetadata] {} it("should delete only expired sessions") { val expiredSession: TestSession = mock[TestSession] when(expiredSession.id).thenReturn(0) when(expiredSession.name).thenReturn(None) when(expiredSession.heartbeatExpired).thenReturn(true) when(expiredSession.stop()).thenReturn(Future.successful(())) when(expiredSession.lastActivity).thenReturn(System.nanoTime()) val nonExpiredSession: TestSession = mock[TestSession] when(nonExpiredSession.id).thenReturn(1) when(nonExpiredSession.name).thenReturn(None) when(nonExpiredSession.heartbeatExpired).thenReturn(false) when(nonExpiredSession.stop()).thenReturn(Future.successful(())) when(nonExpiredSession.lastActivity).thenReturn(System.nanoTime()) val n = new TestWatchdog(new LivyConf()) n.register(expiredSession) n.register(nonExpiredSession) n.deleteExpiredSessions() verify(expiredSession).stop() verify(nonExpiredSession, never).stop() } } }
Example 18
Source File: TransformTaskSpec.scala From incubator-retired-gearpump with Apache License 2.0 | 5 votes |
package org.apache.gearpump.streaming.dsl.task import java.time.Instant import org.apache.gearpump.Message import org.apache.gearpump.cluster.UserConfig import org.apache.gearpump.streaming.MockUtil import org.apache.gearpump.streaming.dsl.window.impl.{TimestampedValue, TriggeredOutputs, StreamingOperator} import org.mockito.Mockito.{verify, when} import org.scalacheck.Gen import org.scalatest.{Matchers, PropSpec} import org.scalatest.mock.MockitoSugar import org.scalatest.prop.PropertyChecks class TransformTaskSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar { property("MergeTask should trigger on watermark") { val longGen = Gen.chooseNum[Long](1L, 1000L) val watermarkGen = longGen.map(Instant.ofEpochMilli) forAll(watermarkGen) { (watermark: Instant) => val windowRunner = mock[StreamingOperator[Any, Any]] val context = MockUtil.mockTaskContext val config = UserConfig.empty val task = new TransformTask[Any, Any](windowRunner, context, config) val time = watermark.minusMillis(1L) val value: Any = time val message = Message(value, time) task.onNext(message) verify(windowRunner).foreach(TimestampedValue(value, time)) when(windowRunner.trigger(watermark)).thenReturn( TriggeredOutputs(Some(TimestampedValue(value, time)), watermark)) task.onWatermarkProgress(watermark) verify(context).output(message) verify(context).updateWatermark(watermark) } } }
Example 19
Source File: ConsumerExtensionsSpec.scala From embedded-kafka with MIT License | 5 votes |
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 20
Source File: JsonRequestSpec.scala From play-ws with Apache License 2.0 | 5 votes |
package play.api.libs.ws.ahc import java.nio.charset.StandardCharsets import akka.actor.ActorSystem import akka.stream.Materializer import akka.util.ByteString import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.Mockito.when import org.specs2.mock.Mockito import org.specs2.mutable.Specification import org.specs2.specification.AfterAll import play.api.libs.json.JsString import play.api.libs.json.JsValue import play.api.libs.json.Json import play.api.libs.ws.JsonBodyReadables import play.api.libs.ws.JsonBodyWritables import play.libs.ws.DefaultObjectMapper import play.shaded.ahc.org.asynchttpclient.Response import scala.io.Codec class JsonRequestSpec extends Specification with Mockito with AfterAll with JsonBodyWritables { sequential implicit val system = ActorSystem() implicit val materializer = Materializer.matFromSystem override def afterAll: Unit = { system.terminate() } "set a json node" in { val jsValue = Json.obj("k1" -> JsString("v1")) val client = mock[StandaloneAhcWSClient] val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null) .withBody(jsValue) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() req.getHeaders.get("Content-Type") must be_==("application/json") ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""") } "set a json node using the default object mapper" in { val objectMapper = DefaultObjectMapper.instance implicit val jsonReadable = body(objectMapper) val jsonNode = objectMapper.readTree("""{"k1":"v1"}""") val client = mock[StandaloneAhcWSClient] val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null) .withBody(jsonNode) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() req.getHeaders.get("Content-Type") must be_==("application/json") ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""") } "read an encoding of UTF-8" in { val json = io.Source.fromResource("test.json")(Codec.ISO8859).getLines.mkString val ahcResponse = mock[Response] val response = new StandaloneAhcWSResponse(ahcResponse) when(ahcResponse.getResponseBody(StandardCharsets.UTF_8)).thenReturn(json) when(ahcResponse.getContentType).thenReturn("application/json") val value: JsValue = JsonBodyReadables.readableAsJson.transform(response) verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.UTF_8) verify(ahcResponse, times(1)).getContentType value.toString must beEqualTo(json) } "read an encoding of ISO-8859-1" in { val json = io.Source.fromResource("test.json")(Codec.ISO8859).getLines.mkString val ahcResponse = mock[Response] val response = new StandaloneAhcWSResponse(ahcResponse) when(ahcResponse.getResponseBody(StandardCharsets.ISO_8859_1)).thenReturn(json) when(ahcResponse.getContentType).thenReturn("application/json;charset=iso-8859-1") val value: JsValue = JsonBodyReadables.readableAsJson.transform(response) verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.ISO_8859_1) verify(ahcResponse, times(1)).getContentType value.toString must beEqualTo(json) } }
Example 21
Source File: NispFrontendControllerSpec.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.controllers import org.slf4j.{Logger => Slf4JLogger} import org.mockito.Mockito.{verify, when} import org.mockito.ArgumentMatchers._ import org.scalatest.mock.MockitoSugar import org.scalatestplus.play.OneAppPerSuite import play.api.Logger import play.api.http.Status import play.api.mvc.Result import play.api.test.FakeRequest import uk.gov.hmrc.nisp.config.{ApplicationGlobal, ApplicationGlobalTrait} import uk.gov.hmrc.nisp.helpers.{MockApplicationGlobal, MockCachedStaticHtmlPartialRetriever} import uk.gov.hmrc.nisp.utils.MockTemplateRenderer import uk.gov.hmrc.play.test.UnitSpec import uk.gov.hmrc.renderer.TemplateRenderer class NispFrontendControllerSpec extends UnitSpec with MockitoSugar with OneAppPerSuite { val mockLogger: Slf4JLogger = mock[Slf4JLogger] when(mockLogger.isErrorEnabled).thenReturn(true) def controller = new NispFrontendController { override val logger = new Logger(mockLogger) val cachedStaticHtmlPartialRetriever = MockCachedStaticHtmlPartialRetriever override implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer override val applicationGlobal:ApplicationGlobalTrait = MockApplicationGlobal } implicit val request = FakeRequest() "onError" should { "should log error details" in { val result: Result = controller.onError(new Exception()) verify(mockLogger).error(anyString(), any[Exception]) } "should return an Internal Server Error (500)" in { val result: Result = controller.onError(new Exception()) status(result) shouldBe Status.INTERNAL_SERVER_ERROR } } }
Example 22
Source File: MasterWebUISuite.scala From drizzle-spark with Apache License 2.0 | 5 votes |
package org.apache.spark.deploy.master.ui import java.io.DataOutputStream import java.net.{HttpURLConnection, URL} import java.nio.charset.StandardCharsets import java.util.Date import scala.collection.mutable.HashMap import org.mockito.Mockito.{mock, times, verify, when} import org.scalatest.BeforeAndAfterAll import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite} import org.apache.spark.deploy.DeployMessages.{KillDriverResponse, RequestKillDriver} import org.apache.spark.deploy.DeployTestUtils._ import org.apache.spark.deploy.master._ import org.apache.spark.rpc.{RpcEndpointRef, RpcEnv} class MasterWebUISuite extends SparkFunSuite with BeforeAndAfterAll { val conf = new SparkConf val securityMgr = new SecurityManager(conf) val rpcEnv = mock(classOf[RpcEnv]) val master = mock(classOf[Master]) val masterEndpointRef = mock(classOf[RpcEndpointRef]) when(master.securityMgr).thenReturn(securityMgr) when(master.conf).thenReturn(conf) when(master.rpcEnv).thenReturn(rpcEnv) when(master.self).thenReturn(masterEndpointRef) val masterWebUI = new MasterWebUI(master, 0) override def beforeAll() { super.beforeAll() masterWebUI.bind() } override def afterAll() { masterWebUI.stop() super.afterAll() } test("kill application") { val appDesc = createAppDesc() // use new start date so it isn't filtered by UI val activeApp = new ApplicationInfo( new Date().getTime, "app-0", appDesc, new Date(), null, Int.MaxValue) when(master.idToApp).thenReturn(HashMap[String, ApplicationInfo]((activeApp.id, activeApp))) val url = s"http://localhost:${masterWebUI.boundPort}/app/kill/" val body = convPostDataToString(Map(("id", activeApp.id), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify the master was called to remove the active app verify(master, times(1)).removeApplication(activeApp, ApplicationState.KILLED) } test("kill driver") { val activeDriverId = "driver-0" val url = s"http://localhost:${masterWebUI.boundPort}/driver/kill/" val body = convPostDataToString(Map(("id", activeDriverId), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify that master was asked to kill driver with the correct id verify(masterEndpointRef, times(1)).ask[KillDriverResponse](RequestKillDriver(activeDriverId)) } private def convPostDataToString(data: Map[String, String]): String = { (for ((name, value) <- data) yield s"$name=$value").mkString("&") } private def sendHttpRequest( url: String, method: String, body: String = ""): HttpURLConnection = { val conn = new URL(url).openConnection().asInstanceOf[HttpURLConnection] conn.setRequestMethod(method) if (body.nonEmpty) { conn.setDoOutput(true) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") conn.setRequestProperty("Content-Length", Integer.toString(body.length)) val out = new DataOutputStream(conn.getOutputStream) out.write(body.getBytes(StandardCharsets.UTF_8)) out.close() } conn } }
Example 23
Source File: LogAppendingCommitStrategySpec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.validator import org.scalatest.mockito.MockitoSugar import org.scalatest.{AsyncWordSpec, Matchers} import TestHelper._ import com.daml.ledger.participant.state.kvutils.DamlKvutils.{DamlStateKey, DamlStateValue} import com.daml.ledger.participant.state.kvutils.Envelope import com.daml.ledger.validator.LedgerStateOperations.{Key, Value} import com.google.protobuf.ByteString import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers._ import org.mockito.Mockito.{times, verify, when} import scala.concurrent.Future class LogAppendingCommitStrategySpec extends AsyncWordSpec with Matchers with MockitoSugar { "commit" should { "return index from appendToLog" in { val mockLedgerStateOperations = mock[LedgerStateOperations[Long]] val expectedIndex = 1234L when(mockLedgerStateOperations.appendToLog(any[Key](), any[Value]())) .thenReturn(Future.successful(expectedIndex)) val instance = new LogAppendingCommitStrategy[Long]( mockLedgerStateOperations, DefaultStateKeySerializationStrategy) instance .commit(aParticipantId, "a correlation ID", aLogEntryId(), aLogEntry, Map.empty, Map.empty) .map { actualIndex => verify(mockLedgerStateOperations, times(1)).appendToLog(any[Key](), any[Value]()) verify(mockLedgerStateOperations, times(0)).writeState(any[Seq[(Key, Value)]]()) actualIndex should be(expectedIndex) } } "write keys serialized according to strategy" in { val mockLedgerStateOperations = mock[LedgerStateOperations[Long]] val actualOutputStateBytesCaptor = ArgumentCaptor .forClass(classOf[Seq[(Key, Value)]]) .asInstanceOf[ArgumentCaptor[Seq[(Key, Value)]]] when(mockLedgerStateOperations.writeState(actualOutputStateBytesCaptor.capture())) .thenReturn(Future.unit) when(mockLedgerStateOperations.appendToLog(any[Key](), any[Value]())) .thenReturn(Future.successful(0L)) val mockStateKeySerializationStrategy = mock[StateKeySerializationStrategy] val expectedStateKey = ByteString.copyFromUtf8("some key") when(mockStateKeySerializationStrategy.serializeStateKey(any[DamlStateKey]())) .thenReturn(expectedStateKey) val expectedOutputStateBytes = Seq((expectedStateKey, Envelope.enclose(aStateValue))) val instance = new LogAppendingCommitStrategy[Long]( mockLedgerStateOperations, mockStateKeySerializationStrategy) instance .commit( aParticipantId, "a correlation ID", aLogEntryId(), aLogEntry, Map.empty, Map(aStateKey -> aStateValue)) .map { _: Long => verify(mockStateKeySerializationStrategy, times(1)).serializeStateKey(aStateKey) verify(mockLedgerStateOperations, times(1)).writeState(any[Seq[(Key, Value)]]()) actualOutputStateBytesCaptor.getValue should be(expectedOutputStateBytes) } } } private val aStateKey: DamlStateKey = DamlStateKey .newBuilder() .setContractId(1.toString) .build private val aStateValue: DamlStateValue = DamlStateValue.getDefaultInstance }
Example 24
Source File: InMemoryLedgerReaderWriterSpec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.on.memory import com.codahale.metrics.MetricRegistry import com.daml.ledger.api.testing.utils.AkkaBeforeAndAfterAll import com.daml.ledger.participant.state.kvutils.api.CommitMetadata import com.daml.ledger.participant.state.v1.{ParticipantId, SubmissionResult} import com.daml.ledger.validator.{BatchedValidatingCommitter, LedgerStateOperations} import com.daml.lf.data.Ref import com.daml.metrics.Metrics import com.daml.platform.akkastreams.dispatcher.Dispatcher import com.google.protobuf.ByteString import org.mockito.ArgumentMatchers._ import org.mockito.Mockito.{times, verify, when} import org.scalatest.mockito.MockitoSugar import org.scalatest.{AsyncWordSpec, Matchers} import scala.concurrent.{ExecutionContext, Future} class InMemoryLedgerReaderWriterSpec extends AsyncWordSpec with AkkaBeforeAndAfterAll with Matchers with MockitoSugar { "commit" should { "not signal new head in case of failure" in { val mockDispatcher = mock[Dispatcher[Index]] val mockCommitter = mock[BatchedValidatingCommitter[Index]] when( mockCommitter.commit( anyString(), any[ByteString](), any[ParticipantId](), any[LedgerStateOperations[Index]])(any[ExecutionContext]())) .thenReturn( Future.successful(SubmissionResult.InternalError("Validation failed with an exception"))) val instance = new InMemoryLedgerReaderWriter( Ref.ParticipantId.assertFromString("participant ID"), "ledger ID", mockDispatcher, InMemoryState.empty, mockCommitter, new Metrics(new MetricRegistry) ) instance .commit("correlation ID", ByteString.copyFromUtf8("some bytes"), CommitMetadata.Empty) .map { actual => verify(mockDispatcher, times(0)).signalNewHead(anyInt()) actual should be(a[SubmissionResult.InternalError]) } } } }
Example 25
Source File: TaxCreditsChoiceControllerSpec.scala From pertax-frontend with Apache License 2.0 | 5 votes |
package controllers.address import models.dto.AddressPageVisitedDto import org.mockito.Matchers.any import org.mockito.Mockito.{times, verify} import play.api.http.Status.{BAD_REQUEST, OK, SEE_OTHER} import play.api.libs.json.Json import play.api.mvc.Request import play.api.test.FakeRequest import play.api.test.Helpers._ import uk.gov.hmrc.http.cache.client.CacheMap import views.html.personaldetails.TaxCreditsChoiceView class TaxCreditsChoiceControllerSpec extends AddressBaseSpec { trait LocalSetup extends AddressControllerSetup { def controller: TaxCreditsChoiceController = new TaxCreditsChoiceController( mockAuthJourney, withActiveTabAction, cc, addressJourneyCachingHelper, injected[TaxCreditsChoiceView], displayAddressInterstitialView ) def sessionCacheResponse: Option[CacheMap] = Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true))))) def currentRequest[A]: Request[A] = FakeRequest().asInstanceOf[Request[A]] } "onPageLoad" should { "return OK if there is an entry in the cache to say the user previously visited the 'personal details' page" in new LocalSetup { val result = controller.onPageLoad(currentRequest) status(result) shouldBe OK verify(mockLocalSessionCache, times(1)).fetch()(any(), any()) } "redirect back to the start of the journey if there is no entry in the cache to say the user previously visited the 'personal details' page" in new LocalSetup { override def sessionCacheResponse: Option[CacheMap] = None val result = controller.onPageLoad(currentRequest) status(result) shouldBe SEE_OTHER redirectLocation(result) shouldBe Some("/personal-account/personal-details") verify(mockLocalSessionCache, times(1)).fetch()(any(), any()) } } "onSubmit" should { "redirect to expected tax credits page when supplied with value = Yes (true)" in new LocalSetup { override def currentRequest[A]: Request[A] = FakeRequest("POST", "") .withFormUrlEncodedBody("taxCreditsChoice" -> "true") .asInstanceOf[Request[A]] val result = controller.onSubmit()(FakeRequest()) status(result) shouldBe SEE_OTHER redirectLocation(result) shouldBe Some("/tax-credits-service/personal/change-address") } "redirect to ResidencyChoice page when supplied with value = No (false)" in new LocalSetup { override def currentRequest[A]: Request[A] = FakeRequest("POST", "") .withFormUrlEncodedBody("taxCreditsChoice" -> "false") .asInstanceOf[Request[A]] val result = controller.onSubmit(FakeRequest()) status(result) shouldBe SEE_OTHER redirectLocation(result) shouldBe Some("/personal-account/your-address/residency-choice") } "return a bad request when supplied no value" in new LocalSetup { override def currentRequest[A]: Request[A] = FakeRequest("POST", "") .asInstanceOf[Request[A]] val result = controller.onSubmit(FakeRequest()) status(result) shouldBe BAD_REQUEST } } }