org.mockito.Mockito Scala Examples
The following examples show how to use org.mockito.Mockito.
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: TestOracleDataTypeConverter.scala From ohara with Apache License 2.0 | 7 votes |
package oharastream.ohara.connector.jdbc.datatype import java.sql.ResultSet import oharastream.ohara.client.configurator.InspectApi.RdbColumn import oharastream.ohara.common.rule.OharaTest import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.when import org.scalatest.matchers.should.Matchers._ class TestOracleDataTypeConverter extends OharaTest { @Test def testConverterCharValue(): Unit = { val resultSet: ResultSet = Mockito.mock(classOf[ResultSet]) when(resultSet.getString("column1")).thenReturn("value1") val column = RdbColumn("column1", "CHAR", false) val oracleDataTypeConverter = new OracleDataTypeConverter() val result = oracleDataTypeConverter.converterValue(resultSet, column) result shouldBe "value1" result.isInstanceOf[String] shouldBe true } @Test def testConverterRawValue(): Unit = { val resultSet: ResultSet = Mockito.mock(classOf[ResultSet]) when(resultSet.getBytes("column1")).thenReturn("aaaa".getBytes) val column = RdbColumn("column1", "RAW", false) val oracleDataTypeConverter = new OracleDataTypeConverter() val result = oracleDataTypeConverter.converterValue(resultSet, column) result.isInstanceOf[Array[Byte]] shouldBe true new String(result.asInstanceOf[Array[Byte]]) shouldBe "aaaa" } @Test def testConverterRawNullValue(): Unit = { val resultSet: ResultSet = Mockito.mock(classOf[ResultSet]) when(resultSet.getBytes("column1")).thenReturn(null) val column = RdbColumn("column1", "RAW", false) val oracleDataTypeConverter = new OracleDataTypeConverter() val result = oracleDataTypeConverter.converterValue(resultSet, column) result.isInstanceOf[Array[Byte]] shouldBe true result.asInstanceOf[Array[Byte]].length shouldBe 0 } @Test def testConverterSmallIntValue(): Unit = { val resultSet: ResultSet = Mockito.mock(classOf[ResultSet]) when(resultSet.getInt("column1")).thenReturn(111) val column = RdbColumn("column1", "INT", false) val oracleDataTypeConverter = new OracleDataTypeConverter() val result = oracleDataTypeConverter.converterValue(resultSet, column) result.isInstanceOf[Integer] shouldBe true result.asInstanceOf[Integer] shouldBe 111 } }
Example 2
Source File: IdentitiesRoutesSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.routes import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.headers.OAuth2BearerToken import akka.http.scaladsl.testkit.ScalatestRouteTest import ch.epfl.bluebrain.nexus.iam.acls.Acls import ch.epfl.bluebrain.nexus.iam.auth.{AccessToken, TokenRejection} import ch.epfl.bluebrain.nexus.iam.realms._ import ch.epfl.bluebrain.nexus.iam.testsyntax._ import ch.epfl.bluebrain.nexus.iam.types.Caller import ch.epfl.bluebrain.nexus.iam.types.IamError.InvalidAccessToken import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Authenticated, User} import ch.epfl.bluebrain.nexus.service.config.Settings import ch.epfl.bluebrain.nexus.service.marshallers.instances._ import ch.epfl.bluebrain.nexus.service.routes.Routes import ch.epfl.bluebrain.nexus.util.Resources import com.typesafe.config.{Config, ConfigFactory} import io.circe.Json import monix.eval.Task import org.mockito.matchers.MacroBasedMatchers import org.mockito.{IdiomaticMockito, Mockito} import org.scalatest.BeforeAndAfter import org.scalatest.concurrent.ScalaFutures import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import scala.concurrent.duration._ //noinspection TypeAnnotation class IdentitiesRoutesSpec extends AnyWordSpecLike with Matchers with ScalatestRouteTest with BeforeAndAfter with MacroBasedMatchers with Resources with ScalaFutures with IdiomaticMockito { implicit override def patienceConfig: PatienceConfig = PatienceConfig(3.seconds, 100.milliseconds) override def testConfig: Config = ConfigFactory.load("test.conf") private val config = Settings(system).serviceConfig implicit private val http = config.http private val realms: Realms[Task] = mock[Realms[Task]] private val acls: Acls[Task] = mock[Acls[Task]] before { Mockito.reset(realms, acls) } "The IdentitiesRoutes" should { val routes = Routes.wrap(new IdentitiesRoutes(acls, realms).routes) "return forbidden" in { val err = InvalidAccessToken(TokenRejection.InvalidAccessToken) realms.caller(any[AccessToken]) shouldReturn Task.raiseError(err) Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check { status shouldEqual StatusCodes.Unauthorized } } "return anonymous" in { realms.caller(any[AccessToken]) shouldReturn Task.pure(Caller.anonymous) Get("/identities") ~> routes ~> check { status shouldEqual StatusCodes.OK responseAs[Json].sort shouldEqual jsonContentOf("/identities/anonymous.json") } } "return all identities" in { val user = User("theuser", "therealm") val auth = Authenticated("therealm") val caller = Caller(user, Set(user, Anonymous, auth)) realms.caller(any[AccessToken]) shouldReturn Task.pure(caller) Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check { status shouldEqual StatusCodes.OK responseAs[Json].sort shouldEqual jsonContentOf("/identities/identities.json") } } } }
Example 3
Source File: KafkaJsonProducerSpec.scala From coral with Apache License 2.0 | 5 votes |
package io.coral.lib import java.util.Properties import io.coral.lib.KafkaJsonProducer.KafkaEncoder import kafka.utils.VerifiableProperties import org.json4s.JsonAST.{JObject, JValue} import org.scalatest.{Matchers, WordSpec} import org.json4s.jackson.JsonMethods._ import kafka.producer.{ProducerConfig, KeyedMessage, Producer} import org.mockito.{Mockito, ArgumentCaptor} import org.mockito.Mockito._ import scala.collection.mutable class KafkaJsonProducerSpec extends WordSpec with Matchers { "A KafkaJsonProducer" should { "create a KafkaJsonProducer with the JsonEncoder" in { val producer = KafkaJsonProducer() assert(producer.getClass == classOf[KafkaJsonProducer[JsonEncoder]]) } "create a KafkaJsonProducer with the specified Encoder" in { val producer = KafkaJsonProducer(classOf[MyEncoder]) assert(producer.getClass == classOf[KafkaJsonProducer[MyEncoder]]) } "create a sender" in { val producer = new MyKafkaJsonProducer producer.createSender("topic", new Properties) val serializer = producer.receivedProperties.get("serializer.class") assert(serializer == classOf[MyEncoder].getName) } } "A KafkaSender" should { "send the JSON provided without a key to Kafka" in { val messageJson = """{"key1": "value1", "key2": "value2"}""" val keyedMessage = sendMessage(None, messageJson) assert(keyedMessage.topic == "test") assert(keyedMessage.hasKey == false) assert(keyedMessage.message == parse(messageJson)) } "send the JSON provided with a key to Kafka" in { val messageJson = """{"key3": "value3", "key4": "value4"}""" val keyedMessage = sendMessage(Some("key"), messageJson) assert(keyedMessage.key == "key") assert(keyedMessage.topic == "test") assert(keyedMessage.message == parse(messageJson)) } } "A JsonEncoder" should { "encode the provided json" in { val json = """{"key1": "value1"}""" val encoder = new JsonEncoder(new VerifiableProperties) val result = encoder.toBytes(parse(json)) assert(parse(new String(result, "UTF-8")) == parse(json)) } } private def sendMessage(key: Option[String], messageJson: String): KeyedMessage[String, JValue] = { val producer = Mockito.mock(classOf[Producer[String, JValue]]) val sender = new KafkaSender("test", producer) sender.send(key, parse(messageJson).asInstanceOf[JObject]) val argumentCaptor = ArgumentCaptor.forClass(classOf[KeyedMessage[String, JValue]]) verify(producer).send(argumentCaptor.capture()) val keyedMessages = argumentCaptor.getAllValues assert(keyedMessages.size == 1) // The following construction is necessary because capturing of parameters // with Mockito, Scala type interference, and multiple arguments // don't work together without explicit casts. keyedMessages.get(0).asInstanceOf[mutable.WrappedArray.ofRef[KeyedMessage[String, JValue]]](0) } } class MyEncoder(verifiableProperties: VerifiableProperties) extends KafkaEncoder { override def toBytes(value: JValue): Array[Byte] = { Array() } } class MyKafkaJsonProducer extends KafkaJsonProducer(classOf[MyEncoder]) { var receivedProperties: Properties = _ override def createProducer(props: Properties): Producer[String, JValue] = { receivedProperties = props Mockito.mock(classOf[Producer[String, JValue]]) } }
Example 4
Source File: DeleteTeamMetricsApiSpec.scala From cave with MIT License | 5 votes |
import com.cave.metrics.data.Role import data.UserData import org.joda.time.DateTime import org.mockito.Matchers._ import org.mockito.{Matchers, Mockito} import org.mockito.Mockito._ import play.api.mvc.Results import play.api.test.{FakeRequest, FakeApplication, PlaySpecification} import scala.concurrent.{Future, ExecutionContext} import scala.Some import scala.util.Success class DeleteTeamMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData { val MetricName = "metric" val organization = GiltOrg val team = GiltTeam val user = SOME_USER "DELETE /organizations/:name/teams/:team/metric-names/:metric" should { "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true)) val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN)) status(result) must equalTo(NO_CONTENT) contentAsString(result) must equalTo("") } "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false)) val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN)) status(result) must equalTo(NOT_FOUND) } "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin))) when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true)) val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN)) status(result) must equalTo(NO_CONTENT) } "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member))) val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN)) status(result) must equalTo(FORBIDDEN) } } }
Example 5
Source File: DeleteTeamMetricsShortcutApiSpec.scala From cave with MIT License | 5 votes |
import com.cave.metrics.data.Role import data.UserData import org.joda.time.DateTime import org.mockito.Matchers._ import org.mockito.{Matchers, Mockito} import org.mockito.Mockito._ import play.api.mvc.Results import play.api.test.{FakeRequest, FakeApplication, PlaySpecification} import scala.concurrent.{Future, ExecutionContext} import scala.Some import scala.util.Success class DeleteTeamMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData { val MetricName = "metric" val organization = GiltOrg val team = GiltTeam val user = SOME_USER "DELETE /metric-names/:metric" should { "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true)) val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName"). withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl")) status(result) must equalTo(NO_CONTENT) contentAsString(result) must equalTo("") } "respond with 404 metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false)) val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName"). withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl")) status(result) must equalTo(NOT_FOUND) } "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true)) val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName"). withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl")) status(result) must equalTo(NO_CONTENT) } "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team))) when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member))) val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName"). withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl")) status(result) must equalTo(FORBIDDEN) } } }
Example 6
Source File: DeleteOrganizationMetricsShortcutApiSpec.scala From cave with MIT License | 5 votes |
import com.cave.metrics.data.Role import data.UserData import org.joda.time.DateTime import org.mockito.Matchers._ import org.mockito.{Matchers, Mockito} import org.mockito.Mockito._ import play.api.mvc.Results import play.api.test.{FakeRequest, FakeApplication, PlaySpecification} import scala.concurrent.{Future, ExecutionContext} import scala.Some import scala.util.Success class DeleteOrganizationMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData { val MetricName = "metric" val organization = GiltOrg val user = SOME_USER "DELETE /metric-names/:metric" should { "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true)) val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName"). withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl")) status(result) must equalTo(NO_CONTENT) contentAsString(result) must equalTo("") } "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false)) val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName"). withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl")) status(result) must equalTo(NOT_FOUND) } "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member))) val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName"). withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl")) status(result) must equalTo(FORBIDDEN) } } }
Example 7
Source File: DeleteOrganizationMetricsApiSpec.scala From cave with MIT License | 5 votes |
import com.cave.metrics.data.Role import data.UserData import org.joda.time.DateTime import org.mockito.Matchers._ import org.mockito.{Matchers, Mockito} import org.mockito.Mockito._ import play.api.mvc.Results import play.api.test.{FakeRequest, FakeApplication, PlaySpecification} import scala.concurrent.{Future, ExecutionContext} import scala.Some import scala.util.Success class DeleteOrganizationMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData { val MetricName = "metric" val organization = GiltOrg val user = SOME_USER "DELETE /organizations/:name/metric-names/:metric" should { "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true)) val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN)) status(result) must equalTo(NO_CONTENT) contentAsString(result) must equalTo("") } "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin))) when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext) when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false)) val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN)) status(result) must equalTo(NOT_FOUND) } "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) { Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory) when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user))) when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization))) when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member))) val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN)) status(result) must equalTo(FORBIDDEN) } } }
Example 8
Source File: RemoteDiskStorageOperationsSpec.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.storage import akka.http.scaladsl.model.ContentTypes._ import akka.http.scaladsl.model.Uri import cats.effect.IO import ch.epfl.bluebrain.nexus.commons.test.io.IOEitherValues import ch.epfl.bluebrain.nexus.commons.test.{ActorSystemFixture, Resources} import ch.epfl.bluebrain.nexus.iam.client.types.{AuthToken, Permission} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.file.File.{Digest, FileAttributes, FileDescription} import ch.epfl.bluebrain.nexus.kg.resources.Id import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.storage.Storage.RemoteDiskStorage import ch.epfl.bluebrain.nexus.storage.client.StorageClient import ch.epfl.bluebrain.nexus.storage.client.types.FileAttributes.{Digest => StorageDigest} import ch.epfl.bluebrain.nexus.storage.client.types.{FileAttributes => StorageFileAttributes} import org.mockito.{IdiomaticMockito, Mockito} import org.scalatest.BeforeAndAfter import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class RemoteDiskStorageOperationsSpec extends ActorSystemFixture("RemoteDiskStorageOperationsSpec") with AnyWordSpecLike with Matchers with BeforeAndAfter with IdiomaticMockito with IOEitherValues with Resources with TestHelper { private val endpoint = "http://nexus.example.com/v1" sealed trait Ctx { val cred = genString() implicit val token: Option[AuthToken] = Some(AuthToken(cred)) val path = Uri.Path(s"${genString()}/${genString()}") // format: off val storage = RemoteDiskStorage(ProjectRef(genUUID), genIri, 1L, false, false, "SHA-256", endpoint, Some(cred), genString(), Permission.unsafe(genString()), Permission.unsafe(genString()), 1024L) val attributes = FileAttributes(s"$endpoint/${storage.folder}/$path", path, s"${genString()}.json", `application/json`, 12L, Digest("SHA-256", genString())) // format: on } private val client = mock[StorageClient[IO]] before { Mockito.reset(client) } "RemoteDiskStorageOperations" should { "verify when storage exists" in new Ctx { client.exists(storage.folder) shouldReturn IO(true) val verify = new RemoteDiskStorageOperations.Verify[IO](storage, client) verify.apply.accepted } "verify when storage does not exists" in new Ctx { client.exists(storage.folder) shouldReturn IO(false) val verify = new RemoteDiskStorageOperations.Verify[IO](storage, client) verify.apply .rejected[String] shouldEqual s"Folder '${storage.folder}' does not exists on the endpoint '${storage.endpoint}'" } "fetch file" in new Ctx { val source = genSource client.getFile(storage.folder, path) shouldReturn IO(source) val fetch = new RemoteDiskStorageOperations.Fetch[IO](storage, client) val resultSource = fetch.apply(attributes).ioValue consume(resultSource) shouldEqual consume(source) } "link file" in new Ctx { val id = Id(storage.ref, genIri) val sourcePath = Uri.Path(s"${genString()}/${genString()}") val destRelativePath = Uri.Path(mangle(storage.ref, attributes.uuid, attributes.filename)) client.moveFile(storage.folder, sourcePath, destRelativePath) shouldReturn IO( StorageFileAttributes( attributes.location, attributes.bytes, StorageDigest(attributes.digest.algorithm, attributes.digest.value), attributes.mediaType ) ) val link = new RemoteDiskStorageOperations.Link[IO](storage, client) link .apply(id, FileDescription(attributes.uuid, attributes.filename, Some(attributes.mediaType)), sourcePath) .ioValue shouldEqual attributes.copy(path = destRelativePath) } } }
Example 9
Source File: TestResultLogWriterSpec.scala From mvn_scalafmt with Apache License 2.0 | 5 votes |
package org.antipathy.mvn_scalafmt.io import org.scalatest.GivenWhenThen import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.apache.maven.plugin.logging.Log import org.mockito.Mockito import org.antipathy.mvn_scalafmt.model.FormatResult import java.io.File class TestResultLogWriterSpec extends AnyFlatSpec with GivenWhenThen with Matchers { behavior of "TestResultLogWriter" it should "write details of unformatted sources to a log" in { val log = Mockito.mock(classOf[Log]) val writer = new TestResultLogWriter(log) val unformattedFile = Mockito.mock(classOf[File]) val formattedFile = Mockito.mock(classOf[File]) val unformatted = FormatResult( sourceFile = unformattedFile, originalSource = "unformatted", formattedSource = "formatted" ) val formatted = FormatResult( sourceFile = formattedFile, originalSource = "formatted", formattedSource = "formatted" ) val input = Seq(unformatted, formatted) Mockito.when(unformattedFile.getName).thenReturn("unformatted.scala") Mockito.when(formattedFile.getName).thenReturn("formatted.scala") val result = writer.write(input) result.totalFiles should be(input.length) result.unformattedFiles should be(1) result.fileDetails.length should be(input.length) result.fileDetails.filter(_.name == unformattedFile.getName).foreach { fd => fd.name should be(unformattedFile.getName) fd.details should be("Requires formatting") } result.fileDetails.filter(_.name == formattedFile.getName).foreach { fd => fd.name should be(formattedFile.getName) fd.details should be("Formatted") } } }
Example 10
Source File: ScalaFormatterSpec.scala From mvn_scalafmt with Apache License 2.0 | 5 votes |
package org.antipathy.mvn_scalafmt import java.io.File import org.antipathy.mvn_scalafmt.builder.Builder import org.antipathy.mvn_scalafmt.format.Formatter import org.antipathy.mvn_scalafmt.io.Writer import org.antipathy.mvn_scalafmt.model.{FormatResult, Summary} import org.mockito.{ArgumentMatchers, Mockito} import org.scalatest.GivenWhenThen import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.jdk.CollectionConverters._ class ScalaFormatterSpec extends AnyFlatSpec with GivenWhenThen with Matchers { behavior of "ScalaFormatter" it should "format scala files" in { val sourceBuilder = Mockito.mock(classOf[Builder[Seq[File], Seq[File]]]) val changedFilesBuilder = Mockito.mock(classOf[Builder[Seq[File], Seq[File]]]) val fileFormatter = Mockito.mock(classOf[Formatter[File, FormatResult]]) val writer = Mockito.mock(classOf[Writer[Seq[FormatResult], Summary]]) val formatter = new ScalaFormatter(sourceBuilder, changedFilesBuilder, fileFormatter, writer) val input = Seq(Mockito.mock(classOf[File])).asJava val sources = Mockito.mock(classOf[Seq[File]]) val sourceToFormat = Mockito.mock(classOf[File]) val sourcesToFormat = Seq(sourceToFormat) val formatResult = Mockito.mock(classOf[FormatResult]) val summary = Mockito.mock(classOf[Summary]) Mockito.when(sourceBuilder.build(ArgumentMatchers.any(classOf[Seq[File]]))).thenReturn(sources) Mockito.when(changedFilesBuilder.build(sources)).thenReturn(sourcesToFormat) Mockito.when(fileFormatter.format(sourceToFormat)).thenReturn(formatResult) Mockito.when(writer.write(Seq(formatResult))).thenReturn(summary) val result = formatter.format(input) result should be(summary) } }
Example 11
Source File: SparkPodInitContainerSuite.scala From Spark-2.3.1 with Apache License 2.0 | 5 votes |
package org.apache.spark.deploy.k8s import java.io.File import java.util.UUID import com.google.common.base.Charsets import com.google.common.io.Files import org.mockito.Mockito import org.scalatest.BeforeAndAfter import org.scalatest.mockito.MockitoSugar._ import org.apache.spark.{SparkConf, SparkFunSuite} import org.apache.spark.deploy.k8s.Config._ import org.apache.spark.util.Utils class SparkPodInitContainerSuite extends SparkFunSuite with BeforeAndAfter { private val DOWNLOAD_JARS_SECRET_LOCATION = createTempFile("txt") private val DOWNLOAD_FILES_SECRET_LOCATION = createTempFile("txt") private var downloadJarsDir: File = _ private var downloadFilesDir: File = _ private var downloadJarsSecretValue: String = _ private var downloadFilesSecretValue: String = _ private var fileFetcher: FileFetcher = _ override def beforeAll(): Unit = { downloadJarsSecretValue = Files.toString( new File(DOWNLOAD_JARS_SECRET_LOCATION), Charsets.UTF_8) downloadFilesSecretValue = Files.toString( new File(DOWNLOAD_FILES_SECRET_LOCATION), Charsets.UTF_8) } before { downloadJarsDir = Utils.createTempDir() downloadFilesDir = Utils.createTempDir() fileFetcher = mock[FileFetcher] } after { downloadJarsDir.delete() downloadFilesDir.delete() } test("Downloads from remote server should invoke the file fetcher") { val sparkConf = getSparkConfForRemoteFileDownloads val initContainerUnderTest = new SparkPodInitContainer(sparkConf, fileFetcher) initContainerUnderTest.run() Mockito.verify(fileFetcher).fetchFile("http://localhost:9000/jar1.jar", downloadJarsDir) Mockito.verify(fileFetcher).fetchFile("hdfs://localhost:9000/jar2.jar", downloadJarsDir) Mockito.verify(fileFetcher).fetchFile("http://localhost:9000/file.txt", downloadFilesDir) } private def getSparkConfForRemoteFileDownloads: SparkConf = { new SparkConf(true) .set(INIT_CONTAINER_REMOTE_JARS, "http://localhost:9000/jar1.jar,hdfs://localhost:9000/jar2.jar") .set(INIT_CONTAINER_REMOTE_FILES, "http://localhost:9000/file.txt") .set(JARS_DOWNLOAD_LOCATION, downloadJarsDir.getAbsolutePath) .set(FILES_DOWNLOAD_LOCATION, downloadFilesDir.getAbsolutePath) } private def createTempFile(extension: String): String = { val dir = Utils.createTempDir() val file = new File(dir, s"${UUID.randomUUID().toString}.$extension") Files.write(UUID.randomUUID().toString, file, Charsets.UTF_8) file.getAbsolutePath } }
Example 12
Source File: TaskSchedulerSpec.scala From vinyldns with Apache License 2.0 | 5 votes |
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 13
Source File: IdentitiesRoutesSpec.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.routes import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.headers.OAuth2BearerToken import akka.http.scaladsl.testkit.ScalatestRouteTest import ch.epfl.bluebrain.nexus.commons.test.Resources import ch.epfl.bluebrain.nexus.iam.auth.{AccessToken, TokenRejection} import ch.epfl.bluebrain.nexus.iam.config.{AppConfig, Settings} import ch.epfl.bluebrain.nexus.iam.marshallers.instances._ import ch.epfl.bluebrain.nexus.iam.realms._ import ch.epfl.bluebrain.nexus.iam.testsyntax._ import ch.epfl.bluebrain.nexus.iam.types.Caller import ch.epfl.bluebrain.nexus.iam.types.IamError.InvalidAccessToken import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Authenticated, User} import com.typesafe.config.{Config, ConfigFactory} import io.circe.Json import monix.eval.Task import org.mockito.matchers.MacroBasedMatchers import org.mockito.{IdiomaticMockito, Mockito} import org.scalatest.BeforeAndAfter import org.scalatest.concurrent.ScalaFutures import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import scala.concurrent.duration._ //noinspection TypeAnnotation class IdentitiesRoutesSpec extends AnyWordSpecLike with Matchers with ScalatestRouteTest with BeforeAndAfter with MacroBasedMatchers with Resources with ScalaFutures with IdiomaticMockito { override implicit def patienceConfig: PatienceConfig = PatienceConfig(3.seconds, 100.milliseconds) override def testConfig: Config = ConfigFactory.load("test.conf") private val appConfig: AppConfig = Settings(system).appConfig private implicit val http = appConfig.http private val realms: Realms[Task] = mock[Realms[Task]] before { Mockito.reset(realms) } "The IdentitiesRoutes" should { val routes = Routes.wrap(new IdentitiesRoutes(realms).routes) "return forbidden" in { val err = InvalidAccessToken(TokenRejection.InvalidAccessToken) realms.caller(any[AccessToken]) shouldReturn Task.raiseError(err) Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check { status shouldEqual StatusCodes.Unauthorized } } "return anonymous" in { realms.caller(any[AccessToken]) shouldReturn Task.pure(Caller.anonymous) Get("/identities") ~> routes ~> check { status shouldEqual StatusCodes.OK responseAs[Json].sort shouldEqual jsonContentOf("/identities/anonymous.json") } } "return all identities" in { val user = User("theuser", "therealm") val auth = Authenticated("therealm") val caller = Caller(user, Set(user, Anonymous, auth)) realms.caller(any[AccessToken]) shouldReturn Task.pure(caller) Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check { status shouldEqual StatusCodes.OK responseAs[Json].sort shouldEqual jsonContentOf("/identities/identities.json") } } } }
Example 14
Source File: RemoteDiskStorageOperationsSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.storage import akka.http.scaladsl.model.ContentTypes._ import akka.http.scaladsl.model.Uri import cats.effect.IO import ch.epfl.bluebrain.nexus.commons.test.io.IOEitherValues import ch.epfl.bluebrain.nexus.commons.test.{ActorSystemFixture, Resources} import ch.epfl.bluebrain.nexus.iam.auth.AccessToken import ch.epfl.bluebrain.nexus.iam.client.types.AuthToken import ch.epfl.bluebrain.nexus.iam.types.Permission import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.file.File.{Digest, FileAttributes, FileDescription} import ch.epfl.bluebrain.nexus.kg.resources.Id import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.storage.Storage.RemoteDiskStorage import ch.epfl.bluebrain.nexus.storage.client.StorageClient import ch.epfl.bluebrain.nexus.storage.client.types.FileAttributes.{Digest => StorageDigest} import ch.epfl.bluebrain.nexus.storage.client.types.{FileAttributes => StorageFileAttributes} import org.mockito.{IdiomaticMockito, Mockito} import org.scalatest.BeforeAndAfter import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class RemoteDiskStorageOperationsSpec extends ActorSystemFixture("RemoteDiskStorageOperationsSpec") with AnyWordSpecLike with Matchers with BeforeAndAfter with IdiomaticMockito with IOEitherValues with Resources with TestHelper { private val endpoint = "http://nexus.example.com/v1" // TODO: Remove when migrating ADMIN client implicit private def oldTokenConversion(implicit token: Option[AccessToken]): Option[AuthToken] = token.map(t => AuthToken(t.value)) sealed trait Ctx { val cred = genString() implicit val token: Option[AccessToken] = Some(AccessToken(cred)) val path = Uri.Path(s"${genString()}/${genString()}") // format: off val storage = RemoteDiskStorage(ProjectRef(genUUID), genIri, 1L, false, false, "SHA-256", endpoint, Some(cred), genString(), Permission.unsafe(genString()), Permission.unsafe(genString()), 1024L) val attributes = FileAttributes(s"$endpoint/${storage.folder}/$path", path, s"${genString()}.json", `application/json`, 12L, Digest("SHA-256", genString())) // format: on } private val client = mock[StorageClient[IO]] before { Mockito.reset(client) } "RemoteDiskStorageOperations" should { "verify when storage exists" in new Ctx { client.exists(storage.folder) shouldReturn IO(true) val verify = new RemoteDiskStorageOperations.Verify[IO](storage, client) verify.apply.accepted } "verify when storage does not exists" in new Ctx { client.exists(storage.folder) shouldReturn IO(false) val verify = new RemoteDiskStorageOperations.Verify[IO](storage, client) verify.apply .rejected[ String ] shouldEqual s"Folder '${storage.folder}' does not exists on the endpoint '${storage.endpoint}'" } "fetch file" in new Ctx { val source = genSource client.getFile(storage.folder, path) shouldReturn IO(source) val fetch = new RemoteDiskStorageOperations.Fetch[IO](storage, client) val resultSource = fetch.apply(attributes).ioValue consume(resultSource) shouldEqual consume(source) } "link file" in new Ctx { val id = Id(storage.ref, genIri) val sourcePath = Uri.Path(s"${genString()}/${genString()}") val destRelativePath = Uri.Path(mangle(storage.ref, attributes.uuid, attributes.filename)) client.moveFile(storage.folder, sourcePath, destRelativePath) shouldReturn IO( StorageFileAttributes( attributes.location, attributes.bytes, StorageDigest(attributes.digest.algorithm, attributes.digest.value), attributes.mediaType ) ) val link = new RemoteDiskStorageOperations.Link[IO](storage, client) link .apply(id, FileDescription(attributes.uuid, attributes.filename, Some(attributes.mediaType)), sourcePath) .ioValue shouldEqual attributes.copy(path = destRelativePath) } } }
Example 15
Source File: MongoObservableReactivePublisherTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package mongo.async import com.avsystem.commons.concurrent.RunNowEC import com.github.ghik.silencer.silent import com.mongodb.async.{client => mongo} import monix.execution.{Cancelable, Scheduler} import org.mockito.ArgumentMatchers.{eq => eqTo, _} import org.mockito.Mockito import org.mockito.Mockito._ import org.mongodb.scala.{Completed, Document, FindObservable, MongoCollection, SingleObservable} import org.scalactic.source.Position import org.scalatest.freespec.AnyFreeSpec import scala.concurrent.duration.Duration @silent("deprecated") class MongoObservableReactivePublisherTest extends AnyFreeSpec { abstract class MockedObservableTests(implicit position: Position) extends MongoObservableExtensions { def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit "should drop test collection" in { val collection = Mockito.mock(classOf[MongoCollection[Document]]) when(collection.drop()).thenReturn(SingleObservable(Completed())) val dropSubscriber = TestSubscriber[Completed]() subscribe(collection.drop(), dropSubscriber) dropSubscriber.assertNoTerminalEvent() dropSubscriber.requestMore(1) dropSubscriber.awaitTerminalEvent(Duration(100, "ms")) dropSubscriber.assertNoErrors() dropSubscriber.assertReceivedOnNext(Seq(Completed())) verify(collection).drop() verifyNoMoreInteractions(collection) } "should insert documents" in { val collection = Mockito.mock(classOf[MongoCollection[Document]]) val insertSubscriber = TestSubscriber[Completed]() when(collection.insertMany(any())).thenReturn(SingleObservable(Completed())) val documents: IndexedSeq[Document] = (1 to 100) map { i: Int => Document("_id" -> i) } subscribe(collection.insertMany(documents), insertSubscriber) insertSubscriber.requestMore(1) insertSubscriber.awaitTerminalEvent(Duration(100, "ms")) insertSubscriber.assertNoErrors() insertSubscriber.assertReceivedOnNext(Seq(Completed())) verify(collection).insertMany(eqTo(documents)) verifyNoMoreInteractions(collection) } "should find documents" in { val documents: IndexedSeq[Document] = (1 to 100) map { i: Int => Document("_id" -> i) } val original = Mockito.mock(classOf[FindObservable[Document]]) val findSubscriber = TestSubscriber[Document]() doNothing().when(original).subscribe(any()) subscribe(original, findSubscriber) findSubscriber.assertNoTerminalEvent() findSubscriber.requestMore(101) documents.foreach(findSubscriber.onNext) findSubscriber.onComplete() findSubscriber.awaitTerminalEvent(Duration(100, "ms")) findSubscriber.assertNoErrors() findSubscriber.assertReceivedOnNext(documents) verify(original).subscribe(any(classOf[mongo.Observer[_ >: Document]])) verifyNoMoreInteractions(original) } } "A Mongo-Reactive observable" - new MockedObservableTests { override def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit = obs.asReactive.subscribe(testSubscriber) } "A Mongo-Monix observable" - new MockedObservableTests { override def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit = obs.asMonix.subscribe( monix.reactive.observers.Subscriber.fromReactiveSubscriber(testSubscriber, Cancelable.empty)(Scheduler(RunNowEC)) ) } }
Example 16
Source File: Mock.scala From self-assessment-api with Apache License 2.0 | 5 votes |
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 17
Source File: MockUtil.scala From incubator-retired-gearpump with Apache License 2.0 | 5 votes |
package org.apache.gearpump.streaming import akka.actor.{Actor, ActorSystem} import akka.testkit.TestActorRef import org.apache.gearpump.cluster.TestUtil import org.apache.gearpump.streaming.task.{TaskContext, TaskId} import org.mockito.{ArgumentMatcher, Matchers, Mockito} object MockUtil { lazy val system: ActorSystem = ActorSystem("mockUtil", TestUtil.DEFAULT_CONFIG) def mockTaskContext: TaskContext = { val context = Mockito.mock(classOf[TaskContext]) Mockito.when(context.self).thenReturn(Mockito.mock(classOf[TestActorRef[Actor]])) Mockito.when(context.system).thenReturn(system) Mockito.when(context.parallelism).thenReturn(1) Mockito.when(context.taskId).thenReturn(TaskId(0, 0)) context } def argMatch[T](func: T => Boolean): T = { Matchers.argThat(new ArgumentMatcher[T] { override def matches(param: Any): Boolean = { val mesage = param.asInstanceOf[T] func(mesage) } }) } }
Example 18
Source File: ParquetWriterTaskSpec.scala From gearpump-examples with Apache License 2.0 | 5 votes |
package io.gearpump.examples.kafka_hdfs_pipeline import akka.actor.ActorSystem import org.apache.avro.Schema import io.gearpump.Message import io.gearpump.cluster.UserConfig import io.gearpump.streaming.MockUtil import org.apache.hadoop.fs.{FileSystem, Path} import org.apache.hadoop.yarn.conf.YarnConfiguration import org.apache.parquet.avro.{AvroParquetReader, AvroParquetWriter} import org.apache.parquet.hadoop.ParquetReader import org.apache.parquet.hadoop.api.ReadSupport import org.mockito.Mockito import org.mockito.Mockito._ import org.scalatest.prop.PropertyChecks import org.scalatest.{BeforeAndAfterAll, Matchers, PropSpec} class ParquetWriterTaskSpec extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll { implicit var system: ActorSystem = ActorSystem("PipeLineSpec") val context = MockUtil.mockTaskContext val appName = "KafkaHdfsPipeLine" when(context.appName).thenReturn(appName) val fs = FileSystem.get(new YarnConfiguration) val homeDir = fs.getHomeDirectory.toUri.getPath val parquetDir = new Path(homeDir, "gearpump") + "/parquet/" val parquetPath = parquetDir + appName + ".parquet" val parquetCrc = parquetDir + "." + appName + ".parquet.crc" val parquetWriter = Mockito.mock(classOf[AvroParquetWriter[SpaceShuttleRecord]]) val anomaly = 0.252 val now = System.currentTimeMillis val userConfig = UserConfig.empty.withString(ParquetWriterTask.PARQUET_OUTPUT_DIRECTORY, "/parquet") override def afterAll(): Unit = { List(parquetPath, parquetCrc, parquetDir).foreach(new java.io.File(_).delete) system.shutdown() } property("ParquetWriterTask should initialize with local parquet file opened for writing") { val parquetWriterTask = new ParquetWriterTask(context, userConfig) val path = parquetWriterTask.absolutePath.stripPrefix("file:") assert(parquetPath.equals(path)) parquetWriterTask.onStop } property("ParquetWriterTask should write records to a parquet file") { val message = Message(SpaceShuttleRecord(now, anomaly), now) val parquetWriterTask = new ParquetWriterTask(context, userConfig) parquetWriterTask.parquetWriter = parquetWriter parquetWriterTask.onNext(message) verify(parquetWriterTask.parquetWriter).write(message.msg.asInstanceOf[SpaceShuttleRecord]) parquetWriterTask.onStop } property("ParquetWriterTask should have verifiable written record") { val message = Message(SpaceShuttleRecord(now, anomaly), now) val parquetWriterTask = new ParquetWriterTask(context, userConfig) parquetWriterTask.onNext(message) parquetWriterTask.onStop val reader = new AvroParquetReader[SpaceShuttleRecord](new Path(parquetPath)) val record = reader.read() assert(message.msg.asInstanceOf[SpaceShuttleRecord].anomaly == record.anomaly) assert(message.msg.asInstanceOf[SpaceShuttleRecord].ts == record.ts) } }
Example 19
Source File: HandlerChainSpec.scala From money with Apache License 2.0 | 5 votes |
package com.comcast.money.core.handlers import com.comcast.money.api.SpanHandler import com.typesafe.config.ConfigFactory import org.mockito.Mockito import org.mockito.Mockito._ import org.scalatest.mockito.MockitoSugar import org.scalatest.{ Matchers, WordSpec } class HandlerChainSpec extends WordSpec with Matchers with MockitoSugar with TestData { "HandlerChain" should { "invoke all handlers in the chain in order" in { val handler1 = mock[SpanHandler] val handler2 = mock[SpanHandler] val handler3 = mock[SpanHandler] val ordered = Mockito.inOrder(handler1, handler2, handler3) val underTest = HandlerChain(Seq(handler1, handler2, handler3)) underTest.handle(testSpanInfo) ordered.verify(handler1).handle(testSpanInfo) ordered.verify(handler2).handle(testSpanInfo) ordered.verify(handler3).handle(testSpanInfo) } "continues invocation of chain if one of the handlers throws an exception" in { val handler1 = mock[SpanHandler] val handler2 = mock[SpanHandler] val handler3 = mock[SpanHandler] doThrow(classOf[RuntimeException]).when(handler1).handle(testSpanInfo) val ordered = Mockito.inOrder(handler1, handler2, handler3) val underTest = HandlerChain(Seq(handler1, handler2, handler3)) underTest.handle(testSpanInfo) ordered.verify(handler1).handle(testSpanInfo) ordered.verify(handler2).handle(testSpanInfo) ordered.verify(handler3).handle(testSpanInfo) } "create a sequence of handlers" in { val config = ConfigFactory.parseString( """ |{ | async = false | handlers = [ | { | class = "com.comcast.money.core.handlers.ConfiguredHandler" | }, | { | class = "com.comcast.money.core.handlers.ConfiguredHandler" | }, | { | class = "com.comcast.money.core.handlers.NonConfiguredHandler" | } | ] |} """.stripMargin) val result = HandlerChain(config) result shouldBe a[HandlerChain] result.asInstanceOf[HandlerChain].handlers should have size 3 } "wrap the handler chain in an async handler if async is set to true" in { val config = ConfigFactory.parseString( """ |{ | async = true | handlers = [ | { | class = "com.comcast.money.core.handlers.ConfiguredHandler" | }, | { | class = "com.comcast.money.core.handlers.ConfiguredHandler" | }, | { | class = "com.comcast.money.core.handlers.NonConfiguredHandler" | } | ] |} """.stripMargin) val result = HandlerChain(config) result shouldBe an[AsyncSpanHandler] result.asInstanceOf[AsyncSpanHandler] .wrapped.asInstanceOf[HandlerChain] .handlers should have size 3 } } }
Example 20
Source File: Mock.scala From vat-api with Apache License 2.0 | 5 votes |
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 21
Source File: TableFunctionRegistrySuite.scala From HANAVora-Extensions with Apache License 2.0 | 5 votes |
package org.apache.spark.sql.catalyst.analysis import org.mockito.Mockito import org.scalatest.FunSuite class TableFunctionRegistrySuite extends FunSuite { val tf1 = Mockito.mock(classOf[TableFunction]) val tf2 = Mockito.mock(classOf[TableFunction]) test("lookup of table functions") { val registry = new SimpleTableFunctionRegistry registry.registerFunction("test", tf1) assert(registry.lookupFunction("test") == Some(tf1)) assert(registry.lookupFunction("Test") == Some(tf1)) assert(registry.lookupFunction("TEST") == Some(tf1)) assert(registry.lookupFunction("notExisting").isEmpty) } test("overriding of table functions") { val registry = new SimpleTableFunctionRegistry registry.registerFunction("test", tf1) assert(registry.lookupFunction("test") == Some(tf1)) registry.registerFunction("test", tf2) assert(registry.lookupFunction("test") == Some(tf2)) } }
Example 22
Source File: SapSQLContextSuite.scala From HANAVora-Extensions with Apache License 2.0 | 5 votes |
package org.apache.spark.sql import java.io.{ByteArrayOutputStream, ObjectOutputStream} import org.apache.spark.sql.parser.SapParserException import org.apache.spark.util.DummyRelationUtils._ import org.mockito.Mockito import org.scalatest.FunSuite class SapSQLContextSuite extends FunSuite with GlobalSapSQLContext { test("SQL contexts do not support hive functions") { val rdd = sc.parallelize(Seq(Row("1"), Row("2"))) sqlc.createDataFrame(rdd, 'a.string, needsConversion = false) .registerTempTable("foo") intercept[AnalysisException] { sqlc.sql("SELECT int(a) FROM foo") } } test ("Check Spark Version"){ val sap_sqlc = sqlContext.asInstanceOf[CommonSapSQLContext] // current spark runtime version shall be supported sap_sqlc.checkSparkVersion(List(org.apache.spark.SPARK_VERSION)) // runtime exception for an unsupported version intercept[RuntimeException]{ sap_sqlc.checkSparkVersion(List("some.unsupported.version")) } } test("Slightly different versions") { val sap_sqlc = sqlContext.asInstanceOf[CommonSapSQLContext] val spy_sap_sqlc = Mockito.spy(sap_sqlc) Mockito.when(spy_sap_sqlc.getCurrentSparkVersion()) .thenReturn(org.apache.spark.SPARK_VERSION + "-CDH") // should not throw! spy_sap_sqlc.checkSparkVersion(spy_sap_sqlc.supportedVersions) Mockito.when(spy_sap_sqlc.getCurrentSparkVersion()) .thenReturn("something- " + org.apache.spark.SPARK_VERSION) // should not throw! spy_sap_sqlc.checkSparkVersion(spy_sap_sqlc.supportedVersions) } test("Ensure SapSQLContext stays serializable"){ // relevant for Bug 92818 // Remember that all class references in SapSQLContext must be serializable! val oos = new ObjectOutputStream(new ByteArrayOutputStream()) oos.writeObject(sqlContext) oos.close() } test("Rand function") { sqlContext.sql( s""" |CREATE TABLE test (name varchar(20), age integer) |USING com.sap.spark.dstest |OPTIONS ( |tableName "test" |) """.stripMargin) sqlContext.sql("SELECT * FROM test WHERE rand() < 0.1") } test("test version fields") { val sapSqlContext = sqlContext.asInstanceOf[CommonSapSQLContext] assert(sapSqlContext.EXTENSIONS_VERSION.isEmpty) assert(sapSqlContext.DATASOURCES_VERSION.isEmpty) } }
Example 23
Source File: MockedSidechainNodeViewHolderFixture.scala From Sidechains-SDK with MIT License | 5 votes |
package com.horizen.fixtures import akka.actor.{ActorRef, ActorSystem, Props} import com.horizen._ import org.mockito.Mockito import org.scalatest.mockito.MockitoSugar import scorex.core.settings.{NetworkSettings, ScorexSettings} class MockedSidechainNodeViewHolder(sidechainSettings: SidechainSettings, history: SidechainHistory, state: SidechainState, wallet: SidechainWallet, mempool: SidechainMemoryPool) extends SidechainNodeViewHolder(sidechainSettings, null, null, null, null, null, null, null, null, null, null, null, null) { override def restoreState(): Option[(HIS, MS, VL, MP)] = { Some(history, state, wallet, mempool) } } trait MockedSidechainNodeViewHolderFixture extends MockitoSugar { def getMockedSidechainNodeViewHolderRef(history: SidechainHistory, state: SidechainState, wallet: SidechainWallet, mempool: SidechainMemoryPool) (implicit actorSystem: ActorSystem): ActorRef = { val sidechainSettings = mock[SidechainSettings] val scorexSettings = mock[ScorexSettings] val networkSettings = mock[NetworkSettings] Mockito.when(sidechainSettings.scorexSettings) .thenAnswer(answer => { scorexSettings }) Mockito.when(scorexSettings.network) .thenAnswer(answer => { networkSettings }) Mockito.when(networkSettings.maxModifiersCacheSize) .thenAnswer(answer => { 10 }) actorSystem.actorOf(Props(new MockedSidechainNodeViewHolder(sidechainSettings, history, state, wallet, mempool))) } }
Example 24
Source File: TestResultSetDataConverter.scala From ohara with Apache License 2.0 | 4 votes |
package oharastream.ohara.connector.jdbc.source import java.sql.{ResultSet, Time, Timestamp} import oharastream.ohara.client.configurator.InspectApi.RdbColumn import oharastream.ohara.common.rule.OharaTest import oharastream.ohara.connector.jdbc.datatype.{MySQLDataTypeConverter, RDBDataTypeConverter} import oharastream.ohara.connector.jdbc.util.{ColumnInfo, DateTimeUtils} import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito._ import org.scalatest.matchers.should.Matchers._ class TestResultSetDataConverter extends OharaTest { private[this] val VARCHAR: String = "VARCHAR" private[this] val TIMESTAMP: String = "TIMESTAMP" private[this] val INT: String = "INT" private[this] val DATE: String = "DATE" private[this] val TIME: String = "TIME" @Test def testConverterRecord(): Unit = { val resultSet: ResultSet = Mockito.mock(classOf[ResultSet]) when(resultSet.getTimestamp("column1", DateTimeUtils.CALENDAR)).thenReturn(new Timestamp(0L)) when(resultSet.getString("column2")).thenReturn("aaa") when(resultSet.getInt("column3")).thenReturn(10) val columnList = Seq( RdbColumn("column1", TIMESTAMP, true), RdbColumn("column2", VARCHAR, false), RdbColumn("column3", INT, false) ) val dataTypeConverter: RDBDataTypeConverter = new MySQLDataTypeConverter() val result: Seq[ColumnInfo[_]] = ResultSetDataConverter.converterRecord(dataTypeConverter, resultSet, columnList) result.head.columnName shouldBe "column1" result.head.columnType shouldBe TIMESTAMP result.head.value.toString shouldBe "1970-01-01 08:00:00.0" result(1).columnName shouldBe "column2" result(1).columnType shouldBe VARCHAR result(1).value shouldBe "aaa" result(2).columnName shouldBe "column3" result(2).columnType shouldBe INT result(2).value shouldBe 10 } @Test def testNullValue(): Unit = { val resultSet: ResultSet = Mockito.mock(classOf[ResultSet]) when(resultSet.getTimestamp("column1", DateTimeUtils.CALENDAR)).thenReturn(new Timestamp(0L)) when(resultSet.getString("column2")).thenReturn(null) when(resultSet.getDate("column3")).thenReturn(null) when(resultSet.getTime("column4")).thenReturn(null) val columnList = Seq( RdbColumn("column1", TIMESTAMP, true), RdbColumn("column2", VARCHAR, false), RdbColumn("column3", DATE, false), RdbColumn("column4", TIME, false) ) val dataTypeConverter: RDBDataTypeConverter = new MySQLDataTypeConverter() val result: Seq[ColumnInfo[_]] = ResultSetDataConverter.converterRecord(dataTypeConverter, resultSet, columnList) result(1).columnName shouldBe "column2" result(1).columnType shouldBe VARCHAR result(1).value shouldBe "null" result(2).columnName shouldBe "column3" result(2).columnType shouldBe DATE result(2).value.toString shouldBe "1970-01-01" result(3).columnName shouldBe "column4" result(3).columnType shouldBe TIME result(3).value.toString shouldBe new Time(0).toString } }