org.mockito.Matchers Scala Examples

The following examples show how to use org.mockito.Matchers. 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: Utils.scala    From drizzle-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.scheduler.cluster.mesos

import java.util.Collections

import scala.collection.JavaConverters._

import org.apache.mesos.Protos._
import org.apache.mesos.Protos.Value.{Range => MesosRange, Ranges, Scalar}
import org.apache.mesos.SchedulerDriver
import org.mockito.{ArgumentCaptor, Matchers}
import org.mockito.Mockito._

object Utils {
  def createOffer(
      offerId: String,
      slaveId: String,
      mem: Int,
      cpus: Int,
      ports: Option[(Long, Long)] = None,
      gpus: Int = 0): Offer = {
    val builder = Offer.newBuilder()
    builder.addResourcesBuilder()
      .setName("mem")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(mem))
    builder.addResourcesBuilder()
      .setName("cpus")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(cpus))
    ports.foreach { resourcePorts =>
      builder.addResourcesBuilder()
        .setName("ports")
        .setType(Value.Type.RANGES)
        .setRanges(Ranges.newBuilder().addRange(MesosRange.newBuilder()
          .setBegin(resourcePorts._1).setEnd(resourcePorts._2).build()))
    }
    if (gpus > 0) {
      builder.addResourcesBuilder()
        .setName("gpus")
        .setType(Value.Type.SCALAR)
        .setScalar(Scalar.newBuilder().setValue(gpus))
    }
    builder.setId(createOfferId(offerId))
      .setFrameworkId(FrameworkID.newBuilder()
        .setValue("f1"))
      .setSlaveId(SlaveID.newBuilder().setValue(slaveId))
      .setHostname(s"host${slaveId}")
      .build()
  }

  def verifyTaskLaunched(driver: SchedulerDriver, offerId: String): List[TaskInfo] = {
    val captor = ArgumentCaptor.forClass(classOf[java.util.Collection[TaskInfo]])
    verify(driver, times(1)).launchTasks(
      Matchers.eq(Collections.singleton(createOfferId(offerId))),
      captor.capture())
    captor.getValue.asScala.toList
  }

  def createOfferId(offerId: String): OfferID = {
    OfferID.newBuilder().setValue(offerId).build()
  }

  def createSlaveId(slaveId: String): SlaveID = {
    SlaveID.newBuilder().setValue(slaveId).build()
  }

  def createExecutorId(executorId: String): ExecutorID = {
    ExecutorID.newBuilder().setValue(executorId).build()
  }

  def createTaskId(taskId: String): TaskID = {
    TaskID.newBuilder().setValue(taskId).build()
  }
} 
Example 2
Source File: PartiallyUnrolledIteratorSuite.scala    From drizzle-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.storage

import org.mockito.Matchers
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar

import org.apache.spark.SparkFunSuite
import org.apache.spark.memory.MemoryMode.ON_HEAP
import org.apache.spark.storage.memory.{MemoryStore, PartiallyUnrolledIterator}

class PartiallyUnrolledIteratorSuite extends SparkFunSuite with MockitoSugar {
  test("join two iterators") {
    val unrollSize = 1000
    val unroll = (0 until unrollSize).iterator
    val restSize = 500
    val rest = (unrollSize until restSize + unrollSize).iterator

    val memoryStore = mock[MemoryStore]
    val joinIterator = new PartiallyUnrolledIterator(memoryStore, ON_HEAP, unrollSize, unroll, rest)

    // Firstly iterate over unrolling memory iterator
    (0 until unrollSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.hasNext
    joinIterator.hasNext
    verify(memoryStore, times(1))
      .releaseUnrollMemoryForThisTask(Matchers.eq(ON_HEAP), Matchers.eq(unrollSize.toLong))

    // Secondly, iterate over rest iterator
    (unrollSize until unrollSize + restSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.close()
    // MemoryMode.releaseUnrollMemoryForThisTask is called only once
    verifyNoMoreInteractions(memoryStore)
  }
} 
Example 3
Source File: MockUtil.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
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 4
Source File: Utils.scala    From sparkoscope   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.scheduler.cluster.mesos

import java.util.Collections

import scala.collection.JavaConverters._

import org.apache.mesos.Protos._
import org.apache.mesos.Protos.Value.{Range => MesosRange, Ranges, Scalar}
import org.apache.mesos.SchedulerDriver
import org.mockito.{ArgumentCaptor, Matchers}
import org.mockito.Mockito._

object Utils {
  def createOffer(
      offerId: String,
      slaveId: String,
      mem: Int,
      cpus: Int,
      ports: Option[(Long, Long)] = None,
      gpus: Int = 0): Offer = {
    val builder = Offer.newBuilder()
    builder.addResourcesBuilder()
      .setName("mem")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(mem))
    builder.addResourcesBuilder()
      .setName("cpus")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(cpus))
    ports.foreach { resourcePorts =>
      builder.addResourcesBuilder()
        .setName("ports")
        .setType(Value.Type.RANGES)
        .setRanges(Ranges.newBuilder().addRange(MesosRange.newBuilder()
          .setBegin(resourcePorts._1).setEnd(resourcePorts._2).build()))
    }
    if (gpus > 0) {
      builder.addResourcesBuilder()
        .setName("gpus")
        .setType(Value.Type.SCALAR)
        .setScalar(Scalar.newBuilder().setValue(gpus))
    }
    builder.setId(createOfferId(offerId))
      .setFrameworkId(FrameworkID.newBuilder()
        .setValue("f1"))
      .setSlaveId(SlaveID.newBuilder().setValue(slaveId))
      .setHostname(s"host${slaveId}")
      .build()
  }

  def verifyTaskLaunched(driver: SchedulerDriver, offerId: String): List[TaskInfo] = {
    val captor = ArgumentCaptor.forClass(classOf[java.util.Collection[TaskInfo]])
    verify(driver, times(1)).launchTasks(
      Matchers.eq(Collections.singleton(createOfferId(offerId))),
      captor.capture())
    captor.getValue.asScala.toList
  }

  def createOfferId(offerId: String): OfferID = {
    OfferID.newBuilder().setValue(offerId).build()
  }

  def createSlaveId(slaveId: String): SlaveID = {
    SlaveID.newBuilder().setValue(slaveId).build()
  }

  def createExecutorId(executorId: String): ExecutorID = {
    ExecutorID.newBuilder().setValue(executorId).build()
  }

  def createTaskId(taskId: String): TaskID = {
    TaskID.newBuilder().setValue(taskId).build()
  }
} 
Example 5
Source File: PartiallyUnrolledIteratorSuite.scala    From sparkoscope   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.storage

import org.mockito.Matchers
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar

import org.apache.spark.SparkFunSuite
import org.apache.spark.memory.MemoryMode.ON_HEAP
import org.apache.spark.storage.memory.{MemoryStore, PartiallyUnrolledIterator}

class PartiallyUnrolledIteratorSuite extends SparkFunSuite with MockitoSugar {
  test("join two iterators") {
    val unrollSize = 1000
    val unroll = (0 until unrollSize).iterator
    val restSize = 500
    val rest = (unrollSize until restSize + unrollSize).iterator

    val memoryStore = mock[MemoryStore]
    val joinIterator = new PartiallyUnrolledIterator(memoryStore, ON_HEAP, unrollSize, unroll, rest)

    // Firstly iterate over unrolling memory iterator
    (0 until unrollSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.hasNext
    joinIterator.hasNext
    verify(memoryStore, times(1))
      .releaseUnrollMemoryForThisTask(Matchers.eq(ON_HEAP), Matchers.eq(unrollSize.toLong))

    // Secondly, iterate over rest iterator
    (unrollSize until unrollSize + restSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.close()
    // MemoryMode.releaseUnrollMemoryForThisTask is called only once
    verifyNoMoreInteractions(memoryStore)
  }
} 
Example 6
Source File: SignalRefreshedTemplateSourceSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
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 7
Source File: LoggingSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli

import org.mockito.{ArgumentCaptor, Matchers}
import org.scalacheck.Gen
import org.specs2.ScalaCheck
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

import scala.util.matching.Regex

class LoggingSpec extends Specification with Mockito with ScalaCheck {
  import logging._

  trait F[T] {
    def body(): T

    def log(message: String): Unit
  }

  "logging the execution time" should {

    "execute the block just once" in {
      val f = mock[F[Unit]]

      logExecutionTime("foo") {
        f.body()
      }(Function.const(()))

      there was one(f).body()
      there was no(f).log(Matchers.any[String]())
    }

    "invokes the log function" in prop { label: String =>
      val f = mock[F[Int]]

      logExecutionTime(label) {
        42
      }(f.log(_))

      val message = ArgumentCaptor.forClass(classOf[String])
      there was one(f).log(message.capture())
      message.getValue must beMatching(s"${Regex.quote(label)} took \\d+ ms")

      there was no(f).body()
    }.setGen(Gen.identifier.label("label"))

    "returns the result of the body" in prop { ret: Int =>
      logExecutionTime("foo") {
        ret
      }(Function.const(())) === ret
    }
  }

} 
Example 8
Source File: Utils.scala    From multi-tenancy-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.scheduler.cluster.mesos

import java.util.Collections

import scala.collection.JavaConverters._

import org.apache.mesos.Protos._
import org.apache.mesos.Protos.Value.{Range => MesosRange, Ranges, Scalar}
import org.apache.mesos.SchedulerDriver
import org.mockito.{ArgumentCaptor, Matchers}
import org.mockito.Mockito._

object Utils {
  def createOffer(
      offerId: String,
      slaveId: String,
      mem: Int,
      cpus: Int,
      ports: Option[(Long, Long)] = None,
      gpus: Int = 0): Offer = {
    val builder = Offer.newBuilder()
    builder.addResourcesBuilder()
      .setName("mem")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(mem))
    builder.addResourcesBuilder()
      .setName("cpus")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(cpus))
    ports.foreach { resourcePorts =>
      builder.addResourcesBuilder()
        .setName("ports")
        .setType(Value.Type.RANGES)
        .setRanges(Ranges.newBuilder().addRange(MesosRange.newBuilder()
          .setBegin(resourcePorts._1).setEnd(resourcePorts._2).build()))
    }
    if (gpus > 0) {
      builder.addResourcesBuilder()
        .setName("gpus")
        .setType(Value.Type.SCALAR)
        .setScalar(Scalar.newBuilder().setValue(gpus))
    }
    builder.setId(createOfferId(offerId))
      .setFrameworkId(FrameworkID.newBuilder()
        .setValue("f1"))
      .setSlaveId(SlaveID.newBuilder().setValue(slaveId))
      .setHostname(s"host${slaveId}")
      .build()
  }

  def verifyTaskLaunched(driver: SchedulerDriver, offerId: String): List[TaskInfo] = {
    val captor = ArgumentCaptor.forClass(classOf[java.util.Collection[TaskInfo]])
    verify(driver, times(1)).launchTasks(
      Matchers.eq(Collections.singleton(createOfferId(offerId))),
      captor.capture())
    captor.getValue.asScala.toList
  }

  def createOfferId(offerId: String): OfferID = {
    OfferID.newBuilder().setValue(offerId).build()
  }

  def createSlaveId(slaveId: String): SlaveID = {
    SlaveID.newBuilder().setValue(slaveId).build()
  }

  def createExecutorId(executorId: String): ExecutorID = {
    ExecutorID.newBuilder().setValue(executorId).build()
  }

  def createTaskId(taskId: String): TaskID = {
    TaskID.newBuilder().setValue(taskId).build()
  }
} 
Example 9
Source File: PartiallyUnrolledIteratorSuite.scala    From multi-tenancy-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.storage

import org.mockito.Matchers
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar

import org.apache.spark.SparkFunSuite
import org.apache.spark.memory.MemoryMode.ON_HEAP
import org.apache.spark.storage.memory.{MemoryStore, PartiallyUnrolledIterator}

class PartiallyUnrolledIteratorSuite extends SparkFunSuite with MockitoSugar {
  test("join two iterators") {
    val unrollSize = 1000
    val unroll = (0 until unrollSize).iterator
    val restSize = 500
    val rest = (unrollSize until restSize + unrollSize).iterator

    val memoryStore = mock[MemoryStore]
    val joinIterator = new PartiallyUnrolledIterator(memoryStore, ON_HEAP, unrollSize, unroll, rest)

    // Firstly iterate over unrolling memory iterator
    (0 until unrollSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.hasNext
    joinIterator.hasNext
    verify(memoryStore, times(1))
      .releaseUnrollMemoryForThisTask(Matchers.eq(ON_HEAP), Matchers.eq(unrollSize.toLong))

    // Secondly, iterate over rest iterator
    (unrollSize until unrollSize + restSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.close()
    // MemoryMode.releaseUnrollMemoryForThisTask is called only once
    verifyNoMoreInteractions(memoryStore)
  }
} 
Example 10
Source File: HeartbeatReceiverSuite.scala    From iolap   with Apache License 2.0 5 votes vote down vote up
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 11
Source File: PartiallyUnrolledIteratorSuite.scala    From Spark-2.3.1   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.storage

import org.mockito.Matchers
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar

import org.apache.spark.SparkFunSuite
import org.apache.spark.memory.MemoryMode.ON_HEAP
import org.apache.spark.storage.memory.{MemoryStore, PartiallyUnrolledIterator}

class PartiallyUnrolledIteratorSuite extends SparkFunSuite with MockitoSugar {
  test("join two iterators") {
    val unrollSize = 1000
    val unroll = (0 until unrollSize).iterator
    val restSize = 500
    val rest = (unrollSize until restSize + unrollSize).iterator

    val memoryStore = mock[MemoryStore]
    val joinIterator = new PartiallyUnrolledIterator(memoryStore, ON_HEAP, unrollSize, unroll, rest)

    // Firstly iterate over unrolling memory iterator
    (0 until unrollSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.hasNext
    joinIterator.hasNext
    verify(memoryStore, times(1))
      .releaseUnrollMemoryForThisTask(Matchers.eq(ON_HEAP), Matchers.eq(unrollSize.toLong))

    // Secondly, iterate over rest iterator
    (unrollSize until unrollSize + restSize).foreach { value =>
      assert(joinIterator.hasNext)
      assert(joinIterator.hasNext)
      assert(joinIterator.next() == value)
    }

    joinIterator.close()
    // MemoryMode.releaseUnrollMemoryForThisTask is called only once
    verifyNoMoreInteractions(memoryStore)
  }
} 
Example 12
Source File: DeleteOrganizationMetricsApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteOrganizationMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

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

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

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

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

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

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

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

class DeleteOrganizationMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

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

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

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

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

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

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

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

class DeleteTeamMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

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

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

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

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

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

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

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

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

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

class DeleteTeamMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

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

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

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

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

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

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

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

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

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