org.scalamock.scalatest.MockFactory Scala Examples

The following examples show how to use org.scalamock.scalatest.MockFactory. 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: WaveformSpec.scala    From scala-audio-file   with MIT License 5 votes vote down vote up
package me.mziccard.audio

import org.scalatest.{FlatSpec, MustMatchers}
import org.scalamock.scalatest.MockFactory

class WaveformSpec extends FlatSpec with MockFactory {

  "Waveform" should "get track info" in {
      val mockFile = mock[AudioFile]
      (mockFile.lengthInSeconds _).expects().returning(60L)
      (mockFile.numFrames _).expects().returning(3600)
      (mockFile.numChannels _).expects().returning(2)
      Waveform(mockFile)
  }
  
  "Waveform" should "read track frames" in {
      val mockFile = mock[AudioFile]
      (mockFile.lengthInSeconds _).expects().returning(60L)
      (mockFile.numFrames _).expects().returning(1024)
      (mockFile.numChannels _).expects().returning(2)
      (mockFile.readNormalizedFrames(_ : Array[Double], _ : Int)).expects(*, 2)
      Waveform(mockFile).getWaveform(512)
      
  }
  
  "Waveform" should "read enough frames" in {
      val mockFile = mock[AudioFile]
      (mockFile.lengthInSeconds _).expects().returning(60L)
      (mockFile.numFrames _).expects().returning(1024)
      (mockFile.numChannels _).expects().returning(2)
      var readFrames = 0
      (mockFile.readNormalizedFrames(_ : Array[Double], _ : Int)) expects(*, 2) onCall { 
        (buffer : Array[Double], numFramesToRead : Int) => {
          if (readFrames < 1024) {
            for(i <- 0 until numFramesToRead)
              buffer(i) = i.toFloat/numFramesToRead
            readFrames = readFrames + numFramesToRead
            2
          } else {
            0
          }
        }
      } repeat(513)
      Waveform(mockFile).getWaveform(512)
  }
  
  "Waveform" should "be of requested size" in {
      val mockFile = mock[AudioFile]
      (mockFile.lengthInSeconds _).expects().returning(60L)
      (mockFile.numFrames _).expects().returning(1024)
      (mockFile.numChannels _).expects().returning(2)
      var readFrames = 0
      (mockFile.readNormalizedFrames(_ : Array[Double], _ : Int)) expects(*, 2) onCall { 
        (buffer : Array[Double], numFramesToRead : Int) => {
          if (readFrames < 1024) {
            for(i <- 0 until numFramesToRead)
              buffer(i) = i.toFloat/numFramesToRead
            readFrames = readFrames + numFramesToRead
            2
          } else {
            0
          }
        }
      } repeat(513)
      val waveform = Waveform(mockFile).getWaveform(512)
      assert(waveform.length >= 512)
  }
  
  "Waveform" should "be the maximum of each frame block" in {
      val mockFile = mock[AudioFile]
      (mockFile.lengthInSeconds _).expects().returning(60L)
      (mockFile.numFrames _).expects().returning(1024)
      (mockFile.numChannels _).expects().returning(2)
      var readFrames = 0
      (mockFile.readNormalizedFrames(_ : Array[Double], _ : Int)) expects(*, 2) onCall { 
        (buffer : Array[Double], numFramesToRead : Int) => {
          if (readFrames < 1024) {
            for(i <- 0 until numFramesToRead)
              buffer(i) = i.toFloat/numFramesToRead
            readFrames = readFrames + numFramesToRead
            2
          } else {
            0
          }
        }
      } repeat(513)
      val waveform = Waveform(mockFile).getWaveform(512)
      waveform.foreach(x => assert(x == 1.toFloat/2))
  }
} 
Example 2
Source File: ArtifactS3SaverTest.scala    From marvin-engine-executor   with Apache License 2.0 5 votes vote down vote up
package org.marvin.artifact.manager

import java.io.File

import akka.Done
import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit}
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.model.GetObjectRequest
import com.typesafe.config.ConfigFactory
import org.apache.hadoop.fs.Path
import org.marvin.artifact.manager.ArtifactSaver.{SaveToLocal, SaveToRemote}
import org.marvin.fixtures.MetadataMock
import org.marvin.model.EngineMetadata
import org.scalamock.scalatest.MockFactory
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}


class ArtifactS3SaverTest extends TestKit(
  ActorSystem("ArtifactS3SaverTest", ConfigFactory.parseString("""akka.loggers = ["akka.testkit.TestEventListener"]""")))
  with ImplicitSender with WordSpecLike with Matchers with BeforeAndAfterAll with MockFactory {

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "s3 saver" should {
    "receive SaveToLocal message" in {
      val metadata = MetadataMock.simpleMockedMetadata()
      val _s3Client = mock[AmazonS3]
      val actor = system.actorOf(Props(new ArtifactS3SaverMock(metadata, _s3Client, true)))

      val protocol = "protocol"
      val artifactName = "model"

      (_s3Client.getObject(_ : GetObjectRequest, _ : File)).expects(*, *).once()

      actor ! SaveToLocal(artifactName, protocol)

      expectMsg(Done)
    }

    "receive SaveToRemote message" in {
      val metadata = MetadataMock.simpleMockedMetadata()
      val _s3Client = mock[AmazonS3]
      val actor = system.actorOf(Props(new ArtifactS3SaverMock(metadata, _s3Client, true)))

      val protocol = "protocol"
      val artifactName = "model"

      (_s3Client.putObject(_ : String, _: String, _ : File)).expects(metadata.s3BucketName, *, *).once()

      actor ! SaveToRemote(artifactName, protocol)

      expectMsg(Done)
    }
  }

    "call preStart method wth success" in {
      val metadata = MetadataMock.simpleMockedMetadata()
      try{
        system.actorOf(Props(new ArtifactS3Saver(metadata)))
        assert(true)
      }catch {
        case _: Throwable =>
          assert(false)
      }
    }

  class ArtifactS3SaverMock(metadata: EngineMetadata, _s3Client: AmazonS3, _isRemote: Boolean) extends ArtifactS3Saver(metadata) {
    def _preStart(): Unit = super.preStart()
    override def preStart(): Unit = {
      s3Client = _s3Client
    }

    override def validatePath(path: Path, isRemote: Boolean): Boolean = {
      if (_isRemote) true
      else false
    }
  }
} 
Example 3
Source File: MockServerSpec.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.server

import org.scalamock.scalatest.MockFactory
import polynote.env.ops.Enrich
import polynote.kernel.{BaseEnv, CellEnv, GlobalEnv, Kernel}
import polynote.kernel.Kernel.Factory
import polynote.kernel.environment.NotebookUpdates
import polynote.testing.ZIOSpec
import polynote.testing.kernel.{MockEnv, MockKernelEnv}
import zio.{RIO, ZIO}

trait MockServerSpec extends MockFactory with ZIOSpec {
  import runtime.unsafeRun
  private val kernel          = mock[Kernel]
  private val kernelFactory   = new Factory.Service {
    def apply(): RIO[BaseEnv with GlobalEnv with CellEnv with NotebookUpdates, Kernel] = ZIO.succeed(kernel)
  }

  val testEnv: MockKernelEnv = unsafeRun(MockKernelEnv(kernelFactory))

  implicit class ResolvedEnvIORunOps[A](val self: ZIO[MockEnv.Env, Throwable, A]) {
    def runIO: A = self.provideSomeLayer[Environment](testEnv.baseLayer).runIO()
  }
} 
Example 4
Source File: ServerHostTest.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.server

import java.net.{HttpURLConnection, InetAddress, InetSocketAddress, URL}

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}
import polynote.app.{App, Args, Environment, MainArgs}
import polynote.config._
import polynote.kernel.{BaseEnv, Kernel}
import polynote.kernel.environment.Config
import polynote.kernel.environment.Env.LayerOps
import polynote.kernel.interpreter.Interpreter
import polynote.kernel.logging.Logging
import polynote.server.auth.IdentityProvider
import polynote.server.repository.NotebookRepository
import polynote.server.repository.fs.FileSystems
import polynote.testing.{ConfiguredZIOSpec, ZIOSpec}
import zio.{RIO, Task, ZIO, ZLayer}
import zio.blocking.effectBlocking

class ServerHostTest extends FreeSpec with Matchers with ConfiguredZIOSpec with MockFactory {
  override val config: PolynoteConfig = PolynoteConfig(
    listen = Listen(host = "0.0.0.0", port = 0)
  )

  val configLayer: ZLayer[BaseEnv, Nothing, Config] = ZLayer.succeed(config)

  private def request(uri: String) = effectBlocking {
    val conn = new URL(uri).openConnection().asInstanceOf[HttpURLConnection]
    conn.setConnectTimeout(500)
    conn.connect()
    val responseCode = conn.getResponseCode
    responseCode shouldEqual 200
  }

  "Server" - {

    "listens on all interfaces when given listen=0.0.0.0" ignore {
      val kernel        = mock[Kernel]
      val kernelFactory = Kernel.Factory.const(kernel)
      val server        = new Server

      val serverEnv: ZLayer[BaseEnv, Throwable, server.MainEnv with MainArgs] =
        (configLayer andThen IdentityProvider.layer) ++
          Interpreter.Factories.load ++ ZLayer.succeed(kernelFactory) ++ ZLayer.succeed(Args(watchUI = true)) ++
          (configLayer ++ FileSystems.live >>> NotebookRepository.live)

      val run = server.server("TESTKEY").provideSomeLayer[BaseEnv](serverEnv).use {
        server =>
          for {
            localAddress <- effectBlocking(InetAddress.getLocalHost.getCanonicalHostName)
            _            <- server.awaitUp
            port         <- server.localAddress.map(_.asInstanceOf[InetSocketAddress].getPort)
            _            <- request(s"http://$localAddress:$port/")
            _            <- request(s"http://127.0.0.1:$port/")
            _            <- server.shutdown()
          } yield ()
      }

      run.runIO()
    }

  }

} 
Example 5
Source File: MicroBlockSpecification.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.lagonaki.unit

import com.wavesplatform.account.KeyPair
import com.wavesplatform.block.{Block, MicroBlock}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.mining.Miner
import com.wavesplatform.state.diffs.produce
import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves}
import com.wavesplatform.transaction._
import com.wavesplatform.transaction.transfer._
import org.scalamock.scalatest.MockFactory
import org.scalatest.words.ShouldVerb
import org.scalatest.{FunSuite, Matchers}

import scala.util.Random

class MicroBlockSpecification extends FunSuite with Matchers with MockFactory with ShouldVerb {

  val prevResBlockSig  = ByteStr(Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte))
  val totalResBlockSig = ByteStr(Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte))
  val reference        = Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte)
  val sender           = KeyPair(reference.dropRight(2))
  val gen              = KeyPair(reference)

  test("MicroBlock with txs bytes/parse roundtrip") {

    val ts                       = System.currentTimeMillis() - 5000
    val tr: TransferTransaction  = TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 2, ByteStr.empty,  ts + 1).explicitGet()
    val assetId                  = IssuedAsset(ByteStr(Array.fill(AssetIdLength)(Random.nextInt(100).toByte)))
    val tr2: TransferTransaction = TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, assetId, 5, Waves, 2, ByteStr.empty,  ts + 2).explicitGet()

    val transactions = Seq(tr, tr2)

    val microBlock  = MicroBlock.buildAndSign(3.toByte, sender, transactions, prevResBlockSig, totalResBlockSig).explicitGet()
    val parsedBlock = MicroBlock.parseBytes(microBlock.bytes()).get

    assert(microBlock.signaturesValid().isRight)
    assert(parsedBlock.signaturesValid().isRight)

    assert(microBlock.signature == parsedBlock.signature)
    assert(microBlock.sender == parsedBlock.sender)
    assert(microBlock.totalResBlockSig == parsedBlock.totalResBlockSig)
    assert(microBlock.reference == parsedBlock.reference)
    assert(microBlock.transactionData == parsedBlock.transactionData)
    assert(microBlock == parsedBlock)
  }

  test("MicroBlock cannot be created with zero transactions") {

    val transactions       = Seq.empty[TransferTransaction]
    val eitherBlockOrError = MicroBlock.buildAndSign(3.toByte, sender, transactions, prevResBlockSig, totalResBlockSig)

    eitherBlockOrError should produce("cannot create empty MicroBlock")
  }

  test("MicroBlock cannot contain more than Miner.MaxTransactionsPerMicroblock") {

    val transaction =
      TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 1000, ByteStr.empty,  System.currentTimeMillis()).explicitGet()
    val transactions = Seq.fill(Miner.MaxTransactionsPerMicroblock + 1)(transaction)

    val eitherBlockOrError = MicroBlock.buildAndSign(3.toByte, sender, transactions, prevResBlockSig, totalResBlockSig)
    eitherBlockOrError should produce("too many txs in MicroBlock")
  }
} 
Example 6
Source File: ClientSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import java.util.concurrent.ConcurrentHashMap

import com.wavesplatform.{TransactionGen, Version}
import io.netty.buffer.{ByteBuf, Unpooled}
import io.netty.channel.Channel
import io.netty.channel.embedded.EmbeddedChannel
import io.netty.channel.group.ChannelGroup
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}

import scala.concurrent.duration.DurationInt
import scala.util.Random

class ClientSpec extends FreeSpec with Matchers with MockFactory with TransactionGen {

  private val clientHandshake = new Handshake(
    applicationName = "wavesI",
    applicationVersion = Version.VersionTuple,
    nodeName = "test",
    nodeNonce = Random.nextInt(),
    declaredAddress = None
  )

  private val serverHandshake = clientHandshake.copy(nodeNonce = Random.nextInt())

  "should send only a local handshake on connection" in {
    val channel = createEmbeddedChannel(mock[ChannelGroup])

    val sentClientHandshakeBuff = channel.readOutbound[ByteBuf]()
    Handshake.decode(sentClientHandshakeBuff) shouldBe clientHandshake
    channel.outboundMessages() shouldBe empty
  }

  "should add a server's channel to all channels after the handshake only" in {
    var channelWasAdded = false
    val allChannels     = mock[ChannelGroup]
    (allChannels.add _).expects(*).onCall { _: Channel =>
      channelWasAdded = true
      true
    }

    val channel = createEmbeddedChannel(allChannels)

    // skip the client's handshake
    channel.readOutbound[ByteBuf]()
    channelWasAdded shouldBe false

    val replyServerHandshakeBuff = Unpooled.buffer()
    serverHandshake.encode(replyServerHandshakeBuff)
    channel.writeInbound(replyServerHandshakeBuff)
    channelWasAdded shouldBe true
  }

  private def createEmbeddedChannel(allChannels: ChannelGroup) = new EmbeddedChannel(
    new HandshakeDecoder(PeerDatabase.NoOp),
    new HandshakeTimeoutHandler(1.minute),
    new HandshakeHandler.Client(
      handshake = clientHandshake,
      establishedConnections = new ConcurrentHashMap(),
      peerConnections = new ConcurrentHashMap(),
      peerDatabase = PeerDatabase.NoOp,
      allChannels = allChannels
    )
  )

} 
Example 7
Source File: HandshakeDecoderSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import java.nio.charset.StandardCharsets

import com.google.common.primitives.{Ints, Longs}
import com.wavesplatform.{NoShrink, TransactionGen}
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
import org.scalacheck.{Arbitrary, Gen}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class HandshakeDecoderSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen with NoShrink {

  "should read a handshake and remove itself from the pipeline" in {
    var mayBeDecodedHandshake: Option[Handshake] = None

    val channel = new EmbeddedChannel(
      new HandshakeDecoder(PeerDatabase.NoOp),
      new ChannelInboundHandlerAdapter {
        override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = msg match {
          case x: Handshake => mayBeDecodedHandshake = Some(x)
          case _            =>
        }
      }
    )

    val origHandshake = new Handshake(
      applicationName = "wavesI",
      applicationVersion = (1, 2, 3),
      nodeName = "test",
      nodeNonce = 4,
      declaredAddress = None
    )

    val buff = Unpooled.buffer
    origHandshake.encode(buff)
    buff.writeCharSequence("foo", StandardCharsets.UTF_8)

    channel.writeInbound(buff)

    mayBeDecodedHandshake should contain(origHandshake)
  }

  private val invalidHandshakeBytes: Gen[Array[Byte]] = {
    // To bypass situations where the appNameLength > whole buffer and HandshakeDecoder waits for next bytes
    val appName  = "x" * Byte.MaxValue
    val nodeName = "y" * Byte.MaxValue

    val appNameBytes   = appName.getBytes(StandardCharsets.UTF_8)
    val versionBytes   = Array(1, 2, 3).flatMap(Ints.toByteArray)
    val nodeNameBytes  = nodeName.getBytes(StandardCharsets.UTF_8)
    val nonceBytes     = Longs.toByteArray(1)
    val timestampBytes = Longs.toByteArray(System.currentTimeMillis() / 1000)

    val validDeclaredAddressLen = Set(0, 8, 20)
    val invalidBytesGen = Gen.listOfN(3, Arbitrary.arbByte.arbitrary).filter {
      case List(appNameLen, nodeNameLen, declaredAddressLen) =>
        !(appNameLen == appNameBytes.size || nodeNameLen == nodeNameBytes.size ||
          validDeclaredAddressLen.contains(declaredAddressLen))
      case _ =>
        false
    }

    invalidBytesGen.map {
      case List(appNameLen, nodeNameLen, declaredAddressLen) =>
        Array(appNameLen) ++
          appNameBytes ++
          versionBytes ++
          Array(nodeNameLen) ++
          nodeNameBytes ++
          nonceBytes ++
          Array(declaredAddressLen) ++
          timestampBytes
    }
  }

  "should blacklist a node sends an invalid handshake" in forAll(invalidHandshakeBytes) { bytes: Array[Byte] =>
    val decoder = new SpiedHandshakeDecoder
    val channel = new EmbeddedChannel(decoder)

    val buff = Unpooled.buffer
    buff.writeBytes(bytes)

    channel.writeInbound(buff)
    decoder.blockCalls shouldBe >(0)
  }

  private class SpiedHandshakeDecoder extends HandshakeDecoder(PeerDatabase.NoOp) {
    var blockCalls = 0

    override protected def block(ctx: ChannelHandlerContext, e: Throwable): Unit = {
      blockCalls += 1
    }
  }

} 
Example 8
Source File: MessageCodecSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import java.nio.charset.StandardCharsets

import com.wavesplatform.TransactionGen
import com.wavesplatform.transaction.assets.IssueTransaction
import com.wavesplatform.transaction.{ProvenTransaction, Transaction}
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.embedded.EmbeddedChannel
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class MessageCodecSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen {

  "should block a sender of invalid messages" in {
    val codec = new SpiedMessageCodec
    val ch    = new EmbeddedChannel(codec)

    ch.writeInbound(RawBytes(TransactionSpec.messageCode, "foo".getBytes(StandardCharsets.UTF_8)))
    ch.readInbound[IssueTransaction]()

    codec.blockCalls shouldBe 1
  }

  "should not block a sender of valid messages" in forAll(randomTransactionGen) { origTx: ProvenTransaction =>
    val codec = new SpiedMessageCodec
    val ch    = new EmbeddedChannel(codec)

    ch.writeInbound(RawBytes.fromTransaction(origTx))
    val decodedTx = ch.readInbound[Transaction]()

    decodedTx shouldBe origTx
    codec.blockCalls shouldBe 0
  }

  private class SpiedMessageCodec extends MessageCodec(PeerDatabase.NoOp) {
    var blockCalls = 0

    override def block(ctx: ChannelHandlerContext, e: Throwable): Unit = {
      blockCalls += 1
    }
  }

} 
Example 9
Source File: BrokenConnectionDetectorSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import com.wavesplatform.TransactionGen
import io.netty.channel.embedded.EmbeddedChannel
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

import scala.concurrent.duration.DurationInt

class BrokenConnectionDetectorSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen {

  "should not close an active connection until the timeout" in {
    val handler = new BrokenConnectionDetector(400.millis)
    val ch      = new EmbeddedChannel(handler)

    ch.writeInbound("foo")
    Thread.sleep(200)
    ch.runPendingTasks()
    ch.isActive shouldBe true
  }

  "should not close a connection when messages are keep going" in {
    val handler = new BrokenConnectionDetector(100.millis)
    val ch      = new EmbeddedChannel(handler)

    (1 to 3).foreach { _ =>
      ch.writeInbound("bar")
      Thread.sleep(50)
      ch.runPendingTasks()
    }

    ch.isActive shouldBe true
  }

  "should close a broken connection" in {
    val handler = new BrokenConnectionDetector(200.millis)
    val ch      = new EmbeddedChannel(handler)

    ch.writeInbound("bar")
    Thread.sleep(250)
    ch.runPendingTasks()
    ch.isActive shouldBe false
  }

} 
Example 10
Source File: ChannelGroupExtSpec.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import java.util.concurrent.ConcurrentHashMap

import io.netty.channel._
import io.netty.channel.embedded.EmbeddedChannel
import io.netty.channel.group.DefaultChannelGroup
import io.netty.util.concurrent.GlobalEventExecutor
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}

import scala.jdk.CollectionConverters._
import scala.util.Random

class ChannelGroupExtSpec extends FreeSpec with Matchers with MockFactory {
  "broadcast" - {
    "should not send a message to the excluded channels" in {
      val message = "test"

      val channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE)
      val received     = ConcurrentHashMap.newKeySet[Int]()

      def receiver(id: Int): Channel = new EmbeddedChannel(
        new ChannelId {
          override def asShortText(): String        = asLongText()
          override def asLongText(): String         = id.toString
          override def compareTo(o: ChannelId): Int = o.asLongText().toInt - id
        },
        new ChannelOutboundHandlerAdapter {
          override def write(ctx: ChannelHandlerContext, msg: scala.Any, promise: ChannelPromise): Unit = {
            received.add(id)
            super.write(ctx, msg, promise)
          }
        }
      )

      val allIds      = (0 to 5).toSet
      val allChannels = allIds.map(receiver)

      val excludedChannels = allChannels.filter(_ => Random.nextBoolean)
      val excludedIds      = excludedChannels.map(_.id.asLongText().toInt)

      allChannels.foreach(channelGroup.add)
      channelGroup.broadcast(message, excludedChannels).syncUninterruptibly()

      received.asScala shouldBe (allIds -- excludedIds)
    }
  }
} 
Example 11
Source File: FeatureProviderTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.features

import com.wavesplatform.block.Block
import com.wavesplatform.settings.{BlockchainSettings, FunctionalitySettings, GenesisSettings, RewardsSettings}
import com.wavesplatform.state.Blockchain
import org.scalacheck.Gen
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class FeatureProviderTest extends FlatSpec with Matchers with ScalaCheckPropertyChecks with MockFactory {
  "blockVersionAt" should "return valid version" in {
    val fs                 = FunctionalitySettings.MAINNET
    val v3ActivationHeight = fs.blockVersion3AfterHeight
    val v4ActivationHeight = 1740000
    val v5ActivationHeight = 2000000

    val genesisAt = 1
    val plainAt   = (2 to fs.blockVersion3AfterHeight + 1).toSet
    val ngAt      = (v3ActivationHeight + 2 to v4ActivationHeight).toSet
    val rewardAt  = (v4ActivationHeight + 1 until v5ActivationHeight).toSet

    val features = Map(
      BlockchainFeatures.BlockReward.id -> v4ActivationHeight,
      BlockchainFeatures.BlockV5.id     -> v5ActivationHeight
    )

    val blockchain = mock[Blockchain]
    (blockchain.activatedFeatures _).expects().anyNumberOfTimes().returning(features)
    (blockchain.settings _).expects().anyNumberOfTimes().returning(BlockchainSettings('W', fs, GenesisSettings.MAINNET, RewardsSettings.MAINNET))

    forAll(Gen.choose(1, v5ActivationHeight * 2)) { h =>
      if (h == genesisAt) blockchain.blockVersionAt(h) shouldBe Block.GenesisBlockVersion
      else if (plainAt contains h) blockchain.blockVersionAt(h) shouldBe Block.PlainBlockVersion
      else if (ngAt contains h) blockchain.blockVersionAt(h) shouldBe Block.NgBlockVersion
      else if (rewardAt contains h) blockchain.blockVersionAt(h) shouldBe Block.RewardBlockVersion
      else blockchain.blockVersionAt(h) shouldBe Block.ProtoBlockVersion
    }

    blockchain.blockVersionAt(v3ActivationHeight) shouldBe Block.PlainBlockVersion
    blockchain.blockVersionAt(v3ActivationHeight + 1) shouldBe Block.PlainBlockVersion
    blockchain.blockVersionAt(v3ActivationHeight + 2) shouldBe Block.NgBlockVersion

    blockchain.blockVersionAt(v4ActivationHeight) shouldBe Block.NgBlockVersion
    blockchain.blockVersionAt(v4ActivationHeight + 1) shouldBe Block.RewardBlockVersion

    blockchain.blockVersionAt(v5ActivationHeight) shouldBe Block.ProtoBlockVersion
  }
} 
Example 12
Source File: ObservedLoadingCacheSpecification.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.utils

import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong

import com.google.common.base.Ticker
import com.google.common.cache.{CacheBuilder, CacheLoader, LoadingCache}
import com.wavesplatform.utils.ObservedLoadingCacheSpecification.FakeTicker
import monix.execution.Ack
import monix.reactive.Observer
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FreeSpec, Matchers}

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

class ObservedLoadingCacheSpecification extends FreeSpec with Matchers with MockFactory {
  private val ExpiringTime = 10.minutes

  "notifies" - {
    "on refresh" in test { (loadingCache, changes, _) =>
      (changes.onNext _).expects("foo").returning(Future.successful(Ack.Continue)).once()

      loadingCache.refresh("foo")
    }

    "on put" in test { (loadingCache, changes, _) =>
      (changes.onNext _).expects("foo").returning(Future.successful(Ack.Continue)).once()

      loadingCache.put("foo", 10)
    }

    "on putAll" in test { (loadingCache, changes, _) =>
      (changes.onNext _).expects("foo").returning(Future.successful(Ack.Continue)).once()
      (changes.onNext _).expects("bar").returning(Future.successful(Ack.Continue)).once()

      loadingCache.putAll(Map[String, Integer]("foo" -> 10, "bar" -> 11).asJava)
    }

    "on invalidate" in test { (loadingCache, changes, _) =>
      (changes.onNext _).expects("foo").returning(Future.successful(Ack.Continue)).once()

      loadingCache.invalidate("foo")
    }

    "on invalidateAll" in test { (loadingCache, changes, _) =>
      (changes.onNext _).expects("foo").returning(Future.successful(Ack.Continue)).once()
      (changes.onNext _).expects("bar").returning(Future.successful(Ack.Continue)).once()

      loadingCache.invalidateAll(Seq("foo", "bar").asJava)
    }
  }

  "don't notify" - {
    "on cache expiration" in test { (loadingCache, changes, ticker) =>
      (changes.onNext _).expects("foo").returning(Future.successful(Ack.Continue)).once()
      loadingCache.put("foo", 1)
      ticker.advance(ExpiringTime.toMillis + 100, TimeUnit.MILLISECONDS)
    }
  }

  private def test(f: (LoadingCache[String, Integer], Observer[String], FakeTicker) => Unit): Unit = {
    val changes = mock[Observer[String]]
    val ticker  = new FakeTicker()

    val delegate = CacheBuilder
      .newBuilder()
      .expireAfterWrite(ExpiringTime.toMillis, TimeUnit.MILLISECONDS)
      .ticker(ticker)
      .build(new CacheLoader[String, Integer] {
        override def load(key: String): Integer = key.length
      })

    val loadingCache = new ObservedLoadingCache(delegate, changes)
    f(loadingCache, changes, ticker)
  }
}

private object ObservedLoadingCacheSpecification {

  // see https://github.com/google/guava/blob/master/guava-testlib/src/com/google/common/testing/FakeTicker.java
  class FakeTicker extends Ticker {
    private val nanos                  = new AtomicLong()
    private var autoIncrementStepNanos = 0L

    def advance(time: Long, timeUnit: TimeUnit): FakeTicker = advance(timeUnit.toNanos(time))
    def advance(nanoseconds: Long): FakeTicker = {
      nanos.addAndGet(nanoseconds)
      this
    }

    def setAutoIncrementStep(autoIncrementStep: Long, timeUnit: TimeUnit): FakeTicker = {
      require(autoIncrementStep >= 0, "May not auto-increment by a negative amount")
      this.autoIncrementStepNanos = timeUnit.toNanos(autoIncrementStep)
      this
    }

    override def read: Long = nanos.getAndAdd(autoIncrementStepNanos)
  }
} 
Example 13
Source File: BlockRewardSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.ledger

import io.iohk.ethereum.blockchain.sync.EphemBlockchainTestSetup
import io.iohk.ethereum.domain._
import io.iohk.ethereum.utils.Config.SyncConfig
import io.iohk.ethereum.utils.{BlockchainConfig, Config}
import io.iohk.ethereum.{Fixtures, Mocks}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class BlockRewardSpec extends FlatSpec with Matchers with MockFactory {

  val blockchainConfig = BlockchainConfig(Config.config)
  val syncConfig = SyncConfig(Config.config)

  val blockchain = mock[BlockchainImpl]

  val ledger = new LedgerImpl(new Mocks.MockVM(), blockchain, blockchainConfig, syncConfig, Mocks.MockValidatorsAlwaysSucceed)

  "Reward Calculation" should "pay to the miner if no ommers included" in new TestSetup {
    val block = sampleBlock(validAccountAddress, Seq(validAccountAddress2, validAccountAddress3))
    val afterRewardWorldState: InMemoryWorldStateProxy = ledger.payBlockReward(block, worldState)
    val beforeExecutionBalance: BigInt = worldState.getGuaranteedAccount(Address(block.header.beneficiary)).balance
    afterRewardWorldState.getGuaranteedAccount(Address(block.header.beneficiary)).balance shouldEqual (beforeExecutionBalance + minerTwoOmmersReward)
  }

  "Reward" should "be paid to the miner even if the account doesn't exist" in new TestSetup {
    val block = sampleBlock(Address(0xdeadbeef))
    val afterRewardWorldState: InMemoryWorldStateProxy = ledger.payBlockReward(block, worldState)
    val expectedReward = UInt256(ledger.blockRewardCalculator.calcBlockMinerReward(block.header.number, 0))
    afterRewardWorldState.getGuaranteedAccount(Address(block.header.beneficiary)).balance shouldEqual expectedReward
  }

  "Reward Calculation" should "be paid if ommers are included in block" in new TestSetup {
    val block = sampleBlock(validAccountAddress, Seq(validAccountAddress2, validAccountAddress3))
    val afterRewardWorldState: InMemoryWorldStateProxy = ledger.payBlockReward(block, worldState)
    val beforeExecutionBalance1: BigInt = worldState.getGuaranteedAccount(Address(block.header.beneficiary)).balance
    val beforeExecutionBalance2: BigInt = worldState.getGuaranteedAccount(Address(block.body.uncleNodesList.head.beneficiary)).balance
    val beforeExecutionBalance3: BigInt = worldState.getGuaranteedAccount(Address(block.body.uncleNodesList(1).beneficiary)).balance
    afterRewardWorldState.getGuaranteedAccount(Address(block.header.beneficiary)).balance shouldEqual (beforeExecutionBalance1 + minerTwoOmmersReward)
    afterRewardWorldState.getGuaranteedAccount(Address(block.body.uncleNodesList.head.beneficiary)).balance shouldEqual (beforeExecutionBalance2 + ommerFiveBlocksDifferenceReward)
    afterRewardWorldState.getGuaranteedAccount(Address(block.body.uncleNodesList(1).beneficiary)).balance shouldEqual (beforeExecutionBalance3 + ommerFiveBlocksDifferenceReward)
  }

  "Reward" should "be paid if ommers are included in block even if accounts don't exist" in new TestSetup {
    val block = sampleBlock(Address(0xdeadbeef), Seq(Address(0x1111), Address(0x2222)))
    val afterRewardWorldState: InMemoryWorldStateProxy = ledger.payBlockReward(block, worldState)
    afterRewardWorldState.getGuaranteedAccount(Address(block.header.beneficiary)).balance shouldEqual minerTwoOmmersReward
    afterRewardWorldState.getGuaranteedAccount(Address(block.body.uncleNodesList.head.beneficiary)).balance shouldEqual ommerFiveBlocksDifferenceReward
    afterRewardWorldState.getGuaranteedAccount(Address(block.body.uncleNodesList(1).beneficiary)).balance shouldEqual ommerFiveBlocksDifferenceReward
  }


  trait TestSetup extends EphemBlockchainTestSetup {

    val validAccountAddress = Address(0xababab)
    val validAccountAddress2 = Address(0xcdcdcd)
    val validAccountAddress3 = Address(0xefefef)

    val minerTwoOmmersReward = BigInt("5312500000000000000")
    val ommerFiveBlocksDifferenceReward = BigInt("1875000000000000000")

    val worldState: InMemoryWorldStateProxy = BlockchainImpl(storagesInstance.storages).getWorldStateProxy(-1, UInt256.Zero, None)
      .saveAccount(validAccountAddress, Account(balance = 10))
      .saveAccount(validAccountAddress2, Account(balance = 20))
      .saveAccount(validAccountAddress3, Account(balance = 30))

    // We don't care for this tests if block is not valid
    def sampleBlock(minerAddress: Address, ommerMiners: Seq[Address] = Nil): Block = {
      Block(
        header = Fixtures.Blocks.Genesis.header.copy(beneficiary = minerAddress.bytes, number = 10),
        body = Fixtures.Blocks.Genesis.body.copy(
          uncleNodesList = ommerMiners.map(a => Fixtures.Blocks.Genesis.header.copy(beneficiary = a.bytes, number = 5))
        )
      )
    }
  }
} 
Example 14
Source File: DeleteAccountsSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.ledger

import io.iohk.ethereum.utils.{BlockchainConfig, Config}
import io.iohk.ethereum.Mocks
import io.iohk.ethereum.blockchain.sync.EphemBlockchainTestSetup
import io.iohk.ethereum.domain.{Account, Address, BlockchainImpl, UInt256}
import io.iohk.ethereum.utils.Config.SyncConfig
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class DeleteAccountsSpec extends FlatSpec with Matchers with MockFactory {

  val blockchainConfig = BlockchainConfig(Config.config)
  val syncConfig = SyncConfig(Config.config)

  val blockchain = mock[BlockchainImpl]

  val ledger = new LedgerImpl(new Mocks.MockVM(), blockchain, blockchainConfig, syncConfig, Mocks.MockValidatorsAlwaysSucceed)

  it should "delete no accounts when none of them should be deleted" in new TestSetup {
    val newWorld = InMemoryWorldStateProxy.persistState(ledger.deleteAccounts(Set.empty)(worldState))
    accountAddresses.foreach{ a => assert(newWorld.getAccount(a).isDefined) }
    newWorld.stateRootHash shouldBe worldState.stateRootHash
  }

  it should "delete the accounts listed for deletion" in new TestSetup {
    val newWorld = ledger.deleteAccounts(accountAddresses.tail)(worldState)
    accountAddresses.tail.foreach{ a => assert(newWorld.getAccount(a).isEmpty) }
    assert(newWorld.getAccount(accountAddresses.head).isDefined)
  }

  it should "delete all the accounts if they are all listed for deletion" in new TestSetup {
    val newWorld = InMemoryWorldStateProxy.persistState(ledger.deleteAccounts(accountAddresses)(worldState))
    accountAddresses.foreach{ a => assert(newWorld.getAccount(a).isEmpty) }
    newWorld.stateRootHash shouldBe Account.EmptyStorageRootHash
  }

  it should "delete account that had storage updated before" in new TestSetup {
    val worldStateWithStorage = worldState.saveStorage(
      validAccountAddress,
      worldState.getStorage(validAccountAddress).store(1, 123))

    val updatedWorldState = ledger.deleteAccounts(accountAddresses)(worldStateWithStorage)

    val newWorld = InMemoryWorldStateProxy.persistState(updatedWorldState)
    newWorld.getAccount(validAccountAddress) shouldBe 'empty
  }

  trait TestSetup extends EphemBlockchainTestSetup {

    val validAccountAddress = Address(0xababab)
    val validAccountAddress2 = Address(0xcdcdcd)
    val validAccountAddress3 = Address(0xefefef)

    val accountAddresses = Set(validAccountAddress, validAccountAddress2, validAccountAddress3)

    val worldStateWithoutPersist: InMemoryWorldStateProxy =
      BlockchainImpl(storagesInstance.storages).getWorldStateProxy(-1, UInt256.Zero, None)
        .saveAccount(validAccountAddress, Account(balance = 10))
        .saveAccount(validAccountAddress2, Account(balance = 20))
        .saveAccount(validAccountAddress3, Account(balance = 30))
    val worldState = InMemoryWorldStateProxy.persistState(worldStateWithoutPersist)
  }

} 
Example 15
Source File: OmmersPoolSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.ommers

import akka.actor.ActorSystem
import akka.testkit.TestProbe
import akka.util.ByteString
import io.iohk.ethereum.Fixtures.Blocks.Block3125369
import io.iohk.ethereum.Timeouts
import io.iohk.ethereum.domain.{Address, BlockchainImpl}
import io.iohk.ethereum.ommers.OmmersPool.{AddOmmers, GetOmmers, RemoveOmmers}
import io.iohk.ethereum.utils.MiningConfig
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration._

class OmmersPoolSpec extends FlatSpec with Matchers with MockFactory {

  "OmmersPool" should "accept ommers" in new TestSetup {
    //just return header
    (blockchain.getBlockHeaderByHash _).expects(*).returns(Some(Block3125369.header))

    ommersPool ! AddOmmers(Block3125369.header)
    ommersPool.!(GetOmmers(Block3125369.header.number + 1))(testProbe.ref)

    testProbe.expectMsg(Timeouts.normalTimeout, OmmersPool.Ommers(Seq(Block3125369.header)))
  }

  "OmmersPool" should "removes ommers ommers" in new TestSetup {
    //just return header
    (blockchain.getBlockHeaderByHash _).expects(*).returns(Some(Block3125369.header))

    ommersPool ! AddOmmers(Block3125369.header)
    ommersPool ! AddOmmers(Block3125369.header.copy(number = 2))
    ommersPool ! RemoveOmmers(Block3125369.header)

    ommersPool.!(GetOmmers(3))(testProbe.ref)

    testProbe.expectMsg(Timeouts.normalTimeout, OmmersPool.Ommers(Seq(Block3125369.header.copy(number = 2))))
  }

  "OmmersPool" should "returns ommers when out of pool siez" in new TestSetup {
    //just return header
    (blockchain.getBlockHeaderByHash _).expects(*).returns(Some(Block3125369.header))

    ommersPool ! AddOmmers(Block3125369.header.copy(number = 4))
    ommersPool ! AddOmmers(Block3125369.header.copy(number = 20))
    ommersPool ! AddOmmers(Block3125369.header.copy(number = 30))
    ommersPool ! AddOmmers(Block3125369.header.copy(number = 40))
    ommersPool ! AddOmmers(Block3125369.header.copy(number = 5))
    ommersPool.!(GetOmmers(6))(testProbe.ref)

    testProbe.expectMsg(Timeouts.normalTimeout, OmmersPool.Ommers(Seq(Block3125369.header.copy(number = 5))))
  }

  trait TestSetup extends MockFactory {
    implicit val system = ActorSystem("OmmersPoolSpec_System")

    val miningConfig = new MiningConfig {
      override val ommersPoolSize: Int = 3
      override val coinbase: Address = Address(2)
      override val ommerPoolQueryTimeout: FiniteDuration = Timeouts.normalTimeout
      override val blockCacheSize: Int = 4
      override val activeTimeout: FiniteDuration = Timeouts.normalTimeout
      override val headerExtraData: ByteString = ByteString.empty
      override val miningEnabled: Boolean = false
      override val ethashDir: String = "~/.ethash"
      override val mineRounds: Int = 100000
    }

    val testProbe = TestProbe()

    val blockchain = mock[BlockchainImpl]
    val ommersPool = system.actorOf(OmmersPool.props(blockchain, miningConfig))
  }
} 
Example 16
Source File: GitHubSpec.scala    From akka-api-gateway-example   with MIT License 5 votes vote down vote up
package jp.co.dzl.example.akka.api.service

import akka.actor.ActorSystem
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.{ HttpMethods, HttpRequest, HttpResponse }
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ Flow, Source }
import akka.stream.testkit.scaladsl.TestSink
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ BeforeAndAfterAll, FlatSpec, Matchers }

import scala.concurrent.Await
import scala.concurrent.duration.Duration

class GitHubSpec extends FlatSpec with Matchers with ScalaFutures with BeforeAndAfterAll with MockFactory {
  implicit val system = ActorSystem("github-spec")
  implicit val executor = system.dispatcher
  implicit val materializer = ActorMaterializer()

  override protected def afterAll: Unit = {
    Await.result(system.terminate(), Duration.Inf)
  }

  "#from" should "merge original headers to github request" in {
    val github = new GitHubImpl("127.0.0.1", 8000, 5, mock[HttpClient])
    val request = HttpRequest(HttpMethods.GET, "/")
      .addHeader(RawHeader("host", "dummy"))
      .addHeader(RawHeader("timeout-access", "dummy"))

    val result = Source.single(HttpRequest(HttpMethods.GET, "/v1/github/users/xxxxxx"))
      .via(github.from(request))
      .runWith(TestSink.probe[HttpRequest])
      .request(1)
      .expectNext()

    result.headers.filter(_.lowercaseName() == "host") shouldBe empty
    result.headers.filter(_.lowercaseName() == "timeout-access") shouldBe empty
    result.headers.filter(_.lowercaseName() == "x-forwarded-host") shouldNot be(empty)
  }

  "#send" should "connect using http client" in {
    val httpResponse = HttpResponse()
    val httpClient = mock[HttpClient]
    (httpClient.connectionHttps _).expects(*, *, *).returning(Flow[HttpRequest].map(_ => httpResponse))

    val github = new GitHubImpl("127.0.0.1", 8000, 5, httpClient)
    val result = Source.single(HttpRequest(HttpMethods.GET, "/"))
      .via(github.send)
      .runWith(TestSink.probe[HttpResponse])
      .request(1)
      .expectNext()

    result shouldBe httpResponse
  }
} 
Example 17
Source File: RowDecoderSpec.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres.generic

import com.twitter.finagle.postgres.Row
import com.twitter.finagle.postgres.values.ValueDecoder
import org.scalamock.scalatest.MockFactory
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class RowDecoderSpec extends AnyFlatSpec with Matchers with MockFactory {

  val row = mock[Row]

  "Row decoder" should "decode non-nullables" in {
    case class Foo(int: Int, string: String, numeric: BigDecimal)
    val decoder = RowDecoder[Foo]

    (row.get(_: String)(_: ValueDecoder[Int])) expects ("int", ValueDecoder.int4) returning 10
    (row.get(_: String)(_: ValueDecoder[String])) expects ("string", ValueDecoder.string) returning "ten"
    (row.get(_: String)(_: ValueDecoder[BigDecimal])) expects ("numeric", ValueDecoder.bigDecimal) returning BigDecimal(10.0)

    decoder(row) shouldEqual Foo(10, "ten", 10.0)
  }

  it should "decode nullables" in {
    case class FooWithNulls(int: Int, string: Option[String], numeric: BigDecimal)
    val decoder = RowDecoder[FooWithNulls]

    (row.get(_: String)(_: ValueDecoder[Int])) expects ("int", ValueDecoder.int4) returning 10
    (row.getOption(_: String)(_: ValueDecoder[String])) expects ("string", ValueDecoder.string) returning None
    (row.get(_: String)(_: ValueDecoder[BigDecimal])) expects ("numeric", ValueDecoder.bigDecimal) returning BigDecimal(10.0)

    decoder(row) shouldEqual FooWithNulls(10, None, 10.0)
  }

  it should "decode join results" in {
    case class A(int: Int, string: String)
    case class B(int: Int, bool: Boolean)
    val decoder = RowDecoder[(A, B)]

    (row.get(_: String)(_: ValueDecoder[Int])) expects ("_1.int", ValueDecoder.int4) returning 10
    (row.get(_: String)(_: ValueDecoder[String])) expects ("_1.string", ValueDecoder.string) returning "ten"
    (row.get(_: String)(_: ValueDecoder[Int])) expects ("_2.int", ValueDecoder.int4) returning 20
    (row.get(_: String)(_: ValueDecoder[Boolean])) expects ("_2.bool", ValueDecoder.boolean) returning true

    decoder(row) shouldEqual (A(10, "ten"), B(20, true))
  }
} 
Example 18
Source File: ServiceBrokerSpec.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client

import akka.actor.{ ActorRef, ActorSystem }
import akka.actor.Status.Failure
import akka.testkit.{ ImplicitSender, TestKit }
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ BeforeAndAfterAll, FlatSpecLike, Matchers }
import stormlantern.consul.client.dao.ConsulHttpClient
import stormlantern.consul.client.discovery.ConnectionHolder
import stormlantern.consul.client.helpers.CallingThreadExecutionContext
import stormlantern.consul.client.loadbalancers.LoadBalancerActor
import stormlantern.consul.client.util.Logging

import scala.concurrent.Future

class ServiceBrokerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FlatSpecLike
    with Matchers with ScalaFutures with BeforeAndAfterAll with MockFactory with Logging {

  implicit val ec = CallingThreadExecutionContext()
  def this() = this(ActorSystem("ServiceBrokerSpec"))

  override def afterAll() {
    TestKit.shutdownActorSystem(system)
  }

  trait TestScope {
    val connectionHolder: ConnectionHolder = mock[ConnectionHolder]
    val httpClient: ConsulHttpClient = mock[ConsulHttpClient]
    val loadBalancer: ActorRef = self
  }

  "The ServiceBroker" should "return a service connection when requested" in new TestScope {
    (connectionHolder.connection _).expects().returns(Future.successful(true))
    (connectionHolder.loadBalancer _).expects().returns(loadBalancer)
    val sut = new ServiceBroker(self, httpClient)
    val result: Future[Boolean] = sut.withService("service1") { service: Boolean ⇒
      Future.successful(service)
    }
    expectMsgPF() {
      case ServiceBrokerActor.GetServiceConnection("service1") ⇒
        lastSender ! connectionHolder
        result.map(_ shouldEqual true).futureValue
    }
    expectMsg(LoadBalancerActor.ReturnConnection(connectionHolder))
  }

  it should "return the connection when an error occurs" in new TestScope {
    (connectionHolder.connection _).expects().returns(Future.successful(true))
    (connectionHolder.loadBalancer _).expects().returns(loadBalancer)
    val sut = new ServiceBroker(self, httpClient)
    val result: Future[Boolean] = sut.withService[Boolean, Boolean]("service1") { service: Boolean ⇒
      throw new RuntimeException()
    }
    expectMsgPF() {
      case ServiceBrokerActor.GetServiceConnection("service1") ⇒
        lastSender ! connectionHolder
        an[RuntimeException] should be thrownBy result.futureValue
    }
    expectMsg(LoadBalancerActor.ReturnConnection(connectionHolder))
  }

  it should "throw an error when an excpetion is returned" in new TestScope {
    val sut = new ServiceBroker(self, httpClient)
    val result: Future[Boolean] = sut.withService("service1") { service: Boolean ⇒
      Future.successful(service)
    }
    expectMsgPF() {
      case ServiceBrokerActor.GetServiceConnection("service1") ⇒
        lastSender ! Failure(new RuntimeException())
        an[RuntimeException] should be thrownBy result.futureValue
    }
  }
} 
Example 19
Source File: ServiceAvailabilityActorSpec.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.discovery

import akka.actor.ActorSystem
import akka.testkit.{ ImplicitSender, TestActorRef, TestKit }
import org.scalamock.scalatest.MockFactory
import org.scalatest.{ BeforeAndAfterAll, FlatSpecLike, Matchers }
import stormlantern.consul.client.dao.{ ConsulHttpClient, IndexedServiceInstances }
import stormlantern.consul.client.discovery.ServiceAvailabilityActor.Start
import stormlantern.consul.client.helpers.ModelHelpers
import stormlantern.consul.client.util.Logging

import scala.concurrent.Future
import scala.concurrent.duration._

class ServiceAvailabilityActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FlatSpecLike
    with Matchers with BeforeAndAfterAll with MockFactory with Logging {

  def this() = this(ActorSystem("ServiceAvailabilityActorSpec"))

  override def afterAll() {
    TestKit.shutdownActorSystem(system)
  }

  "The ServiceAvailabilityActor" should "receive one service update when there are no changes" in {
    val httpClient: ConsulHttpClient = mock[ConsulHttpClient]
    val sut = TestActorRef(ServiceAvailabilityActor.props(httpClient, ServiceDefinition("bogus123", "bogus"), self))
    (httpClient.getService _).expects("bogus", None, Some(0L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(1, Set.empty)))
    (httpClient.getService _).expects("bogus", None, Some(1L), Some("1s"), None).onCall { p ⇒
      sut.stop()
      Future.successful(IndexedServiceInstances(1, Set.empty))
    }
    sut ! Start
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123"))
    expectMsg(1.second, ServiceAvailabilityActor.Started)
    expectNoMsg(1.second)
  }

  it should "receive two service updates when there is a change" in {
    val httpClient: ConsulHttpClient = mock[ConsulHttpClient]
    lazy val sut = TestActorRef(ServiceAvailabilityActor.props(httpClient, ServiceDefinition("bogus123", "bogus"), self))
    val service = ModelHelpers.createService("bogus123", "bogus")
    (httpClient.getService _).expects("bogus", None, Some(0L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(1, Set.empty)))
    (httpClient.getService _).expects("bogus", None, Some(1L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(2, Set(service))))
    (httpClient.getService _).expects("bogus", None, Some(2L), Some("1s"), None).onCall { p ⇒
      sut.stop()
      Future.successful(IndexedServiceInstances(2, Set(service)))
    }
    sut ! Start
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123"))
    expectMsg(1.second, ServiceAvailabilityActor.Started)
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123", Set(service), Set.empty))
    expectNoMsg(1.second)
  }

  it should "receive one service update when there are two with different tags" in {
    val httpClient: ConsulHttpClient = mock[ConsulHttpClient]
    lazy val sut = TestActorRef(ServiceAvailabilityActor.props(httpClient, ServiceDefinition("bogus123", "bogus", Set("one", "two")), self))
    val nonMatchingservice = ModelHelpers.createService("bogus123", "bogus", tags = Set("one"))
    val matchingService = nonMatchingservice.copy(serviceTags = Set("one", "two"))
    (httpClient.getService _).expects("bogus", Some("one"), Some(0L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(1, Set.empty)))
    (httpClient.getService _).expects("bogus", Some("one"), Some(1L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(2, Set(nonMatchingservice, matchingService))))
    (httpClient.getService _).expects("bogus", Some("one"), Some(2L), Some("1s"), None).onCall { p ⇒
      sut.stop()
      Future.successful(IndexedServiceInstances(2, Set(nonMatchingservice, matchingService)))
    }
    sut ! Start
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123"))
    expectMsg(1.second, ServiceAvailabilityActor.Started)
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123", Set(matchingService), Set.empty))
    expectNoMsg(1.second)
  }
} 
Example 20
Source File: LeaderFollowerActorSpec.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.election

import java.util
import java.util.UUID

import akka.actor.ActorSystem
import akka.testkit.{ TestActorRef, ImplicitSender, TestKit }
import org.scalamock.scalatest.MockFactory
import org.scalatest.{ BeforeAndAfterAll, Matchers, FlatSpecLike }
import stormlantern.consul.client.dao.{ BinaryData, KeyData, AcquireSession, ConsulHttpClient }
import stormlantern.consul.client.election.LeaderFollowerActor.Participate

import scala.concurrent.Future

class LeaderFollowerActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FlatSpecLike
    with Matchers with BeforeAndAfterAll with MockFactory {

  def this() = this(ActorSystem("LeaderFollowerActorSpec"))

  override def afterAll() {
    TestKit.shutdownActorSystem(system)
  }

  trait TestScope {
    val sessionId: UUID = UUID.fromString("9A3BB9C-E2E7-43DF-BFD5-845417146552")
    val key = "path/to/our/key"
    val host = "myhost.mynetwork.net"
    val port = 1337
    val consulHttpClient: ConsulHttpClient = mock[ConsulHttpClient]
    val leaderInfoBytes: Array[Byte] = s"""{"host":"$host","port":$port}""".getBytes("UTF-8")
  }

  "The LeaderFollowerActor" should "participate in an election, win, watch for changes and participate again when session is lost" in new TestScope {
    val sut = TestActorRef(LeaderFollowerActor.props(consulHttpClient, sessionId, key, host, port))
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).returns(Future.successful(true))
    (consulHttpClient.getKeyValuePair _).expects(key, Some(0L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 1, 1, 0, BinaryData(leaderInfoBytes), Some(sessionId))))
    }
    (consulHttpClient.getKeyValuePair _).expects(key, Some(1L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 2, 1, 0, BinaryData(leaderInfoBytes), None)))
    }
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).onCall { p ⇒
      sut.stop()
      Future.successful(false)
    }
    sut ! Participate
  }

  it should "participate in an election, lose, watch for changes and participate again when session is lost" in new TestScope {
    val otherSessionId: UUID = UUID.fromString("9A3BB9C-E2E7-43DF-BFD5-845417146553")
    val sut = TestActorRef(LeaderFollowerActor.props(consulHttpClient, sessionId, key, host, port))
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).returns(Future.successful(false))
    (consulHttpClient.getKeyValuePair _).expects(key, Some(0L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 1, 1, 0, BinaryData(leaderInfoBytes), Some(otherSessionId))))
    }
    (consulHttpClient.getKeyValuePair _).expects(key, Some(1L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 2, 1, 0, BinaryData(leaderInfoBytes), None)))
    }
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).onCall { p ⇒
      sut.stop()
      Future.successful(true)
    }
    sut ! Participate
  }
} 
Example 21
Source File: MockWsClient.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks
import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import play.api.libs.ws.{BodyWritable, WSClient, WSRequest, WSResponse}

import scala.concurrent.Future
import scala.concurrent.duration.Duration

trait MockWsClient extends MockFactory {

  val mockWsClient: WSClient = mock[WSClient]
  val mockWsRequest: WSRequest = mock[WSRequest]

  object MockWsClient {

    def url(url: String): CallHandler[WSRequest] = {
      (mockWsClient.url(_: String))
        .expects(url)
    }
  }

  object MockWsRequest {

    def withHttpHeaders(headers: Seq[(String, String)]): CallHandler[WSRequest] = {
      (mockWsRequest.withHttpHeaders _ ).expects(*)
    }

    def withRequestTimeout(timeout: Duration): CallHandler[WSRequest] = {
      (mockWsRequest.withRequestTimeout(_: Duration))
        .expects(timeout)
    }

    def post[I: BodyWritable](body: I): CallHandler[Future[WSResponse]] = {
      (mockWsRequest.post(_: I)(_: BodyWritable[I]))
        .expects(body, *)
    }
  }

} 
Example 22
Source File: MockObligationService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import utils.EndpointLogContext
import v1.models.request.obligations.ObligationsRequest
import v1.models.response.obligations.ObligationsResponse
import v1.services.{ObligationsService, ServiceOutcome}

import scala.concurrent.{ExecutionContext, Future}

trait MockObligationService extends MockFactory{

  val mockObligationsService: ObligationsService = mock[ObligationsService]

  object MockObligationService {

    def receiveObligations(request: ObligationsRequest): CallHandler[Future[ServiceOutcome[ObligationsResponse]]] = {
      (mockObligationsService
        .retrieveObligations(_ : ObligationsRequest)(_: HeaderCarrier, _: ExecutionContext, _: EndpointLogContext))
        .expects(request, *, *, *)
    }
  }

} 
Example 23
Source File: MockNrsService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.joda.time.DateTime
import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import v1.controllers.UserRequest
import v1.models.errors.ErrorWrapper
import v1.models.nrs.response.NrsResponse
import v1.models.request.submit.SubmitRequest
import v1.services.NrsService

import scala.concurrent.{ExecutionContext, Future}

trait MockNrsService extends MockFactory {

  val mockNrsService: NrsService = mock[NrsService]

  object MockNrsService {

    def submitNrs(request: SubmitRequest, dateTime: DateTime): CallHandler[Future[Either[ErrorWrapper, NrsResponse]]] = {
      (mockNrsService
        .submitNrs(_ : SubmitRequest, _: DateTime)(_: UserRequest[_], _: HeaderCarrier, _: ExecutionContext))
        .expects(request, *, *, *, *)
    }
  }

} 
Example 24
Source File: MockEnrolmentsAuthService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.auth.core.authorise.Predicate
import uk.gov.hmrc.http.HeaderCarrier
import v1.models.auth.UserDetails
import v1.models.outcomes.AuthOutcome
import v1.services.EnrolmentsAuthService

import scala.concurrent.{ExecutionContext, Future}

trait MockEnrolmentsAuthService extends MockFactory {

  val mockEnrolmentsAuthService: EnrolmentsAuthService = mock[EnrolmentsAuthService]

  object MockEnrolmentsAuthService {

    def authoriseUser(): Unit = {
      (mockEnrolmentsAuthService.authorised(_: Predicate, _: Boolean)(_: HeaderCarrier, _: ExecutionContext))
        .expects(*, *, *, *)
        .returns(Future.successful(Right(UserDetails("Individual", None, "client-Id"))))
    }

    def authorised(predicate: Predicate): CallHandler[Future[AuthOutcome]] = {
      (mockEnrolmentsAuthService.authorised(_: Predicate, _: Boolean)(_: HeaderCarrier, _: ExecutionContext))
        .expects(predicate, *, *, *)
    }
  }

} 
Example 25
Source File: MockLiabilitiesService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import utils.EndpointLogContext
import v1.models.request.liabilities.LiabilitiesRequest
import v1.models.response.liabilities.LiabilitiesResponse
import v1.services.{LiabilitiesService, ServiceOutcome}

import scala.concurrent.{ExecutionContext, Future}

trait MockLiabilitiesService extends MockFactory {

  val mockRetrieveLiabilitiesService: LiabilitiesService = mock[LiabilitiesService]

  object MockRetrieveLiabilitiesService {

    def retrieveLiabilities(request: LiabilitiesRequest): CallHandler[Future[ServiceOutcome[LiabilitiesResponse]]] = {
      (mockRetrieveLiabilitiesService
        .retrieveLiabilities(_ : LiabilitiesRequest)(_: HeaderCarrier, _: ExecutionContext, _: EndpointLogContext))
        .expects(request, *, *, *)
    }
  }

} 
Example 26
Source File: MockViewReturnService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import utils.EndpointLogContext
import v1.models.request.viewReturn.ViewRequest
import v1.models.response.viewReturn.ViewReturnResponse
import v1.services.{ServiceOutcome, ViewReturnService}

import scala.concurrent.{ExecutionContext, Future}

trait MockViewReturnService extends MockFactory {

  val mockViewReturnService: ViewReturnService = mock[ViewReturnService]

  object MockViewReturnService {

    def viewReturn(request: ViewRequest): CallHandler[Future[ServiceOutcome[ViewReturnResponse]]] = {
      (mockViewReturnService
        .viewReturn(_ : ViewRequest)(_: HeaderCarrier, _: ExecutionContext, _: EndpointLogContext))
        .expects(request, *, *, *)
    }
  }

} 
Example 27
Source File: MockSubmitReturnService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import utils.EndpointLogContext
import v1.models.request.submit.SubmitRequest
import v1.models.response.submit.SubmitResponse
import v1.services.{ServiceOutcome, SubmitReturnService}

import scala.concurrent.{ExecutionContext, Future}

trait MockSubmitReturnService extends MockFactory {

  val mockSubmitReturnService: SubmitReturnService = mock[SubmitReturnService]

  object MockSubmitReturnService {

    def submitReturn(request: SubmitRequest): CallHandler[Future[ServiceOutcome[SubmitResponse]]] = {
      (mockSubmitReturnService
        .submitReturn(_ : SubmitRequest)(_: HeaderCarrier, _: ExecutionContext, _: EndpointLogContext))
        .expects(request, *, *, *)
    }
  }

} 
Example 28
Source File: MockPaymentsService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import utils.EndpointLogContext
import v1.models.request.payments.PaymentsRequest
import v1.models.response.payments.PaymentsResponse
import v1.services.{PaymentsService, ServiceOutcome}

import scala.concurrent.{ExecutionContext, Future}

trait MockPaymentsService extends MockFactory {

  val mockPaymentsService: PaymentsService = mock[PaymentsService]

  object MockPaymentsService {

    def retrievePayments(request: PaymentsRequest): CallHandler[Future[ServiceOutcome[PaymentsResponse]]] = {
      (mockPaymentsService
        .retrievePayments(_: PaymentsRequest)(_: HeaderCarrier, _: ExecutionContext, _: EndpointLogContext))
        .expects(request, *, *, *)
    }
  }

} 
Example 29
Source File: MockAuditService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.services

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import play.api.libs.json.Writes
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.audit.http.connector.AuditResult
import v1.models.audit.AuditEvent
import v1.services.AuditService

import scala.concurrent.{ExecutionContext, Future}

trait MockAuditService extends MockFactory {

  val mockAuditService: AuditService = stub[AuditService]

  object MockedAuditService {
    def verifyAuditEvent[T](event: AuditEvent[T]): CallHandler[Future[AuditResult]] = {
      (mockAuditService.auditEvent(_: AuditEvent[T])(_: HeaderCarrier, _: ExecutionContext, _: Writes[T]))
        .verify(event, *, *, *)
        .returning(Future.successful(AuditResult.Success))
    }
  }

} 
Example 30
Source File: MockObligationsValidator.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.validators

import org.scalamock.handlers.CallHandler1
import org.scalamock.scalatest.MockFactory
import v1.controllers.requestParsers.validators.ObligationsValidator
import v1.models.errors.MtdError
import v1.models.request.obligations.ObligationsRawData

class MockObligationsValidator extends MockFactory{

  val mockValidator: ObligationsValidator = mock[ObligationsValidator]

  object MockVrnValidator {

    def validate(data: ObligationsRawData): CallHandler1[ObligationsRawData, List[MtdError]] = {
      (mockValidator
        .validate(_: ObligationsRawData))
        .expects(data)
    }
  }
} 
Example 31
Source File: MockLiabilitiesValidator.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.validators

import org.scalamock.handlers.CallHandler1
import org.scalamock.scalatest.MockFactory
import v1.controllers.requestParsers.validators.LiabilitiesValidator
import v1.models.errors.MtdError
import v1.models.request.liabilities.LiabilitiesRawData

class MockLiabilitiesValidator extends MockFactory {

  val mockValidator: LiabilitiesValidator = mock[LiabilitiesValidator]

  object MockVrnValidator {

    def validate(data: LiabilitiesRawData): CallHandler1[LiabilitiesRawData, List[MtdError]] = {
      (mockValidator
        .validate(_: LiabilitiesRawData))
        .expects(data)
    }
  }
} 
Example 32
Source File: MockPaymentsValidator.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.validators

import org.scalamock.handlers.CallHandler1
import org.scalamock.scalatest.MockFactory
import v1.controllers.requestParsers.validators.PaymentsValidator
import v1.models.errors.MtdError
import v1.models.request.payments.PaymentsRawData

class MockPaymentsValidator extends MockFactory {
    val mockValidator: PaymentsValidator = mock[PaymentsValidator]

    object MockVrnValidator {

      def validate(data: PaymentsRawData): CallHandler1[PaymentsRawData, List[MtdError]] = {
        (mockValidator
          .validate(_: PaymentsRawData))
          .expects(data)
      }
    }
} 
Example 33
Source File: MockSubmitReturnValidator.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.validators

import org.scalamock.handlers.CallHandler1
import org.scalamock.scalatest.MockFactory
import v1.controllers.requestParsers.validators.SubmitReturnValidator
import v1.models.errors.MtdError
import v1.models.request.submit.SubmitRawData

class MockSubmitReturnValidator extends MockFactory {

  val mockValidator: SubmitReturnValidator = mock[SubmitReturnValidator]

  object MockSubmitReturnsValidator {

    def validate(data: SubmitRawData): CallHandler1[SubmitRawData, List[MtdError]] = {
      (mockValidator
        .validate(_: SubmitRawData))
        .expects(data)
    }
  }
} 
Example 34
Source File: MockViewReturnValidator.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.validators

import org.scalamock.handlers.CallHandler1
import org.scalamock.scalatest.MockFactory
import v1.controllers.requestParsers.validators.ViewReturnValidator
import v1.models.errors.MtdError
import v1.models.request.viewReturn.ViewRawData

class MockViewReturnValidator extends MockFactory {

  val mockValidator: ViewReturnValidator = mock[ViewReturnValidator]

  object MockViewReturnValidator {

    def validate(data: ViewRawData): CallHandler1[ViewRawData, List[MtdError]] = {
      (mockValidator
        .validate(_: ViewRawData))
        .expects(data)
    }
  }
} 
Example 35
Source File: MockHttpClient.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import play.api.libs.json.Writes
import uk.gov.hmrc.http.{HeaderCarrier, HttpReads}
import uk.gov.hmrc.play.bootstrap.http.HttpClient

import scala.concurrent.{ExecutionContext, Future}

trait MockHttpClient extends MockFactory {

  val mockHttpClient: HttpClient = mock[HttpClient]

  object MockedHttpClient {

    def get[T](url: String, requiredHeaders: (String, String)*): CallHandler[Future[T]] = {
      (mockHttpClient
        .GET(_: String)(_: HttpReads[T], _: HeaderCarrier, _: ExecutionContext))
        .expects(where { (actualUrl, _, hc, _) =>
          url == actualUrl && requiredHeaders.forall(h => hc.headers.contains(h))
        })
    }

    def get[T](url: String, queryParams: Seq[(String, String)], requiredHeaders: (String, String)*): CallHandler[Future[T]] = {
      (mockHttpClient
        .GET(_: String, _: Seq[(String, String)])(_: HttpReads[T], _: HeaderCarrier, _: ExecutionContext))
        .expects(where { (actualUrl, params,  _, hc, _) =>
          url == actualUrl && requiredHeaders.forall(h => hc.headers.contains(h)) && params == queryParams
        })
    }

    def post[I, T](url: String, body: I, requiredHeaders: (String, String)*): CallHandler[Future[T]] = {
      (mockHttpClient
        .POST[I, T](_: String, _: I, _: Seq[(String, String)])(_: Writes[I], _: HttpReads[T], _: HeaderCarrier, _: ExecutionContext))
        .expects(where { (actualUrl, actualBody, _, _, _, hc, _) =>
          url == actualUrl && body == actualBody && requiredHeaders.forall(h => hc.headers.contains(h))
        })
    }
  }

} 
Example 36
Source File: MockViewReturnConnector.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.connectors

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import v1.connectors.{DesOutcome, ViewReturnConnector}
import v1.models.request.viewReturn.ViewRequest
import v1.models.response.viewReturn.ViewReturnResponse

import scala.concurrent.{ExecutionContext, Future}

trait MockViewReturnConnector extends MockFactory {

  val mockViewReturnConnector: ViewReturnConnector = mock[ViewReturnConnector]

  object MockViewReturnConnector {

    def viewReturn(requestData: ViewRequest): CallHandler[Future[DesOutcome[ViewReturnResponse]]] = {
      (mockViewReturnConnector
        .viewReturn(_: ViewRequest)(_: HeaderCarrier, _: ExecutionContext))
        .expects(requestData, *, *)
    }
  }

} 
Example 37
Source File: MockLiabilitiesConnector.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.connectors

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import v1.connectors.{DesOutcome, LiabilitiesConnector}
import v1.models.request.liabilities.LiabilitiesRequest
import v1.models.response.liabilities.LiabilitiesResponse

import scala.concurrent.{ExecutionContext, Future}

trait MockLiabilitiesConnector extends MockFactory {

  val mockRetrieveLiabilitiesConnector: LiabilitiesConnector = mock[LiabilitiesConnector]

  object MockRetrieveLiabilitiesConnector {

    def retrieveLiabilities(requestData: LiabilitiesRequest): CallHandler[Future[DesOutcome[LiabilitiesResponse]]] = {
      (mockRetrieveLiabilitiesConnector
        .retrieveLiabilities(_: LiabilitiesRequest)(_: HeaderCarrier, _: ExecutionContext))
        .expects(requestData, *, *)
    }
  }

} 
Example 38
Source File: MockNrsConnector.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.connectors

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import v1.connectors.{NrsConnector, NrsOutcome}
import v1.models.nrs.request.NrsSubmission
import v1.models.nrs.response.NrsResponse

import scala.concurrent.{ExecutionContext, Future}

trait MockNrsConnector extends MockFactory {

  val mockNrsConnector: NrsConnector = mock[NrsConnector]

  object MockNrsConnector {

    def submitNrs(body: NrsSubmission): CallHandler[Future[NrsOutcome[NrsResponse]]] = {
      (mockNrsConnector
        .submitNrs(_: NrsSubmission)(_: HeaderCarrier, _: ExecutionContext))
        .expects(body, *, *)
    }
  }

} 
Example 39
Source File: MockObligationsConnector.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.connectors

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import v1.connectors.{DesOutcome, ObligationsConnector}
import v1.models.request.obligations.ObligationsRequest
import v1.models.response.obligations.ObligationsResponse

import scala.concurrent.{ExecutionContext, Future}

trait MockObligationsConnector extends MockFactory {

  val mockObligationsConnector: ObligationsConnector = mock[ObligationsConnector]

  object MockObligationsConnector {

    def retrieveObligations(requestData: ObligationsRequest): CallHandler[Future[DesOutcome[ObligationsResponse]]] = {
      (mockObligationsConnector
        .retrieveObligations(_: ObligationsRequest)(_: HeaderCarrier, _: ExecutionContext))
        .expects(requestData, *, *)
    }
  }

} 
Example 40
Source File: MockSubmitReturnConnector.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.connectors

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import v1.connectors.{DesOutcome, SubmitReturnConnector}
import v1.models.request.submit.SubmitRequest
import v1.models.response.submit.SubmitResponse

import scala.concurrent.{ExecutionContext, Future}

trait MockSubmitReturnConnector extends MockFactory {

  val mockSubmitReturnConnector: SubmitReturnConnector = mock[SubmitReturnConnector]

  object MockSubmitReturnConnector {

    def submitReturn(requestData: SubmitRequest): CallHandler[Future[DesOutcome[SubmitResponse]]] = {
      (mockSubmitReturnConnector
        .submitReturn(_: SubmitRequest)(_: HeaderCarrier, _: ExecutionContext))
        .expects(requestData, *, *)
    }
  }

} 
Example 41
Source File: MockPaymentsConnector.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.mocks.connectors

import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import uk.gov.hmrc.http.HeaderCarrier
import v1.connectors.{DesOutcome, PaymentsConnector}
import v1.models.request.payments.PaymentsRequest
import v1.models.response.payments.PaymentsResponse

import scala.concurrent.{ExecutionContext, Future}

trait MockPaymentsConnector extends MockFactory {

  val mockRetrievePaymentsConnector: PaymentsConnector = mock[PaymentsConnector]

  object MockRetrievePaymentsConnector {

    def retrievePayments(requestData: PaymentsRequest): CallHandler[Future[DesOutcome[PaymentsResponse]]] = {
      (mockRetrievePaymentsConnector
        .retrievePayments(_: PaymentsRequest)(_: HeaderCarrier, _: ExecutionContext))
        .expects(requestData, *, *)
    }
  }

} 
Example 42
Source File: MockAppConfig.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package mocks

import config.AppConfig
import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import play.api.Configuration

import scala.concurrent.duration.Duration

trait MockAppConfig extends MockFactory {

  val mockAppConfig: AppConfig = mock[AppConfig]

  object MockedAppConfig {
    def desBaseUrl: CallHandler[String] = (mockAppConfig.desBaseUrl _: () => String).expects()
    def desToken: CallHandler[String] = (mockAppConfig.desToken _).expects()
    def desEnvironment: CallHandler[String] = (mockAppConfig.desEnv _).expects()
    def featureSwitch: CallHandler[Option[Configuration]] = (mockAppConfig.featureSwitch _: () => Option[Configuration]).expects()
    def apiGatewayContext: CallHandler[String]            = (mockAppConfig.apiGatewayContext _: () => String).expects()
    def apiStatus: CallHandler[String] = (mockAppConfig.apiStatus: String => String).expects("1.0")
    def endpointsEnabled: CallHandler[Boolean] = (mockAppConfig.endpointsEnabled: String => Boolean).expects("1.0")

    // NRS config items
    def nrsApiKey: CallHandler[String] = (mockAppConfig.nrsApiKey _).expects()
    def nrsMaxTimeout: CallHandler[Duration] = (mockAppConfig.nrsMaxTimeout _).expects()
    def appName: CallHandler[String] = (mockAppConfig.appName _).expects()
    def nrsBaseUrl: CallHandler[String] = (mockAppConfig.nrsBaseUrl _).expects()
  }
} 
Example 43
Source File: TestApplication.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi

import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock._
import com.github.tomakehurst.wiremock.core.WireMockConfiguration._
import com.github.tomakehurst.wiremock.stubbing.StubMapping
import org.scalamock.scalatest.MockFactory
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach}
import play.api.http.Status._

import scala.concurrent.duration._
import scala.language.postfixOps

trait TestApplication
  extends UnitSpec
    with BeforeAndAfterEach
    with BeforeAndAfterAll
    with MockFactory {

  override implicit val timeout: FiniteDuration = 100 seconds

  val mockPort = 22222
  val mockHost = "localhost"

  protected val wiremockBaseUrl: String = s"http://$mockHost:$mockHost"
  private val wireMockServer = new WireMockServer(wireMockConfig().port(mockPort))

  protected def baseBeforeAll(): StubMapping = {
    wireMockServer.stop()
    wireMockServer.start()
    WireMock.configureFor(mockHost, mockPort)
    // the below stub is here so that the application finds the registration endpoint which is called on startup
    stubFor(post(urlPathEqualTo("/registration")).willReturn(aResponse().withStatus(OK)))
  }

  override def beforeAll(): Unit = {
    super.beforeAll()
    baseBeforeAll()
  }

  override def afterAll(): Unit = {
    super.afterAll()
    wireMockServer.stop()
  }

  override def beforeEach(): Unit = {
    super.beforeEach()
    WireMock.reset()
  }

} 
Example 44
Source File: NRSServiceSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.services

import org.joda.time.DateTime
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.test.FakeRequest
import uk.gov.hmrc.domain.Vrn
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.vatapi.UnitSpec
import uk.gov.hmrc.vatapi.assets.TestConstants.Auth.orgAuthContextWithNrsData
import uk.gov.hmrc.vatapi.assets.TestConstants.NRSResponse._
import uk.gov.hmrc.vatapi.assets.TestConstants.VatReturn._
import uk.gov.hmrc.vatapi.httpparsers.NrsError
import uk.gov.hmrc.vatapi.httpparsers.NrsSubmissionHttpParser.NrsSubmissionOutcome
import uk.gov.hmrc.vatapi.mocks.connectors.MockNRSConnector
import uk.gov.hmrc.vatapi.models.VatReturnDeclaration
import uk.gov.hmrc.vatapi.resources.AuthRequest

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

class NRSServiceSpec extends UnitSpec with GuiceOneAppPerSuite with MockFactory with ScalaFutures with MockNRSConnector {

  val testNRSService = new NRSService(mockNRSConnector)

  implicit val hc: HeaderCarrier = HeaderCarrier()
  implicit val req: AuthRequest[_] = new AuthRequest(orgAuthContextWithNrsData, FakeRequest().withHeaders(("Authorization", "Bearer test-bearer-token")))

  val testDateTime: DateTime = DateTime.now()

  "NRSService.submit" when {

    lazy val testVrn: Vrn = Vrn("123456789")
    def result(declaration: VatReturnDeclaration): Future[NrsSubmissionOutcome] = {
      val submission = testNRSService.convertToNrsSubmission(testVrn, declaration)
      testNRSService.submit(testVrn, submission)
    }

    "successful responses are returned from the connector" should {
      "return the correctly formatted NRS Data model" in {
        setupNrsSubmission(testVrn, nrsSubmission)(Right(nrsClientData))
        extractAwait(result(vatReturnDeclaration)) shouldBe Right(nrsClientData)
      }
    }

    "error responses are returned from the connector" should {
      "return an NRS Error model" in {
        setupNrsSubmission(testVrn, nrsSubmission)(Left(NrsError))
        extractAwait(result(vatReturnDeclaration)) shouldBe Left(NrsError)
      }
    }
  }
} 
Example 45
Source File: VatReturnsServiceSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.services

import org.joda.time.DateTime
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.http.Status.{BAD_REQUEST, OK}
import play.api.libs.json.Json
import uk.gov.hmrc.domain.Vrn
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.vatapi.UnitSpec
import uk.gov.hmrc.vatapi.assets.TestConstants.NRSResponse._
import uk.gov.hmrc.vatapi.assets.TestConstants.VatReturn._
import uk.gov.hmrc.vatapi.mocks.connectors.MockVatReturnsConnector
import uk.gov.hmrc.vatapi.models.des
import uk.gov.hmrc.vatapi.models.des.{DesError, DesErrorCode}
import uk.gov.hmrc.vatapi.resources.wrappers.VatReturnResponse

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

class VatReturnsServiceSpec extends UnitSpec with GuiceOneAppPerSuite with MockFactory with ScalaFutures with MockVatReturnsConnector {

  val testVatReturnsService = new VatReturnsService(mockVatReturnsConnector)

  implicit val hc: HeaderCarrier = HeaderCarrier()
  val testDateTime: DateTime = DateTime.now()

  val successResponse = VatReturnResponse(HttpResponse(OK, responseJson = Some(Json.toJson(vatReturnsDes))))
  val invalidPayloadResponse =
    VatReturnResponse(HttpResponse(
      BAD_REQUEST,
      responseJson = Some(Json.toJson(DesError(DesErrorCode.INVALID_PAYLOAD, "Submission has not passed validation. Invalid parameter Payload.")))
    ))


  "VatReturnsService.submit" when {

    lazy val testVrn: Vrn = Vrn("123456789")
    def result(submission: des.VatReturnDeclaration): Future[VatReturnResponse] = testVatReturnsService.submit(testVrn, submission)

    "successful responses are returned from the connector" should {
      "return the correctly formatted VatReturnsDes Data model" in {
        setupVatReturnSubmission(testVrn, desVatReturnDeclaration(timestamp))(successResponse)
        await(result(desVatReturnDeclaration(timestamp))) shouldBe successResponse
      }
    }

    "error responses are returned from the connector" should {
      "return a Des Error model" in {
        setupVatReturnSubmission(testVrn, desVatReturnDeclaration(timestamp))(invalidPayloadResponse)
        await(result(desVatReturnDeclaration(timestamp))) shouldBe invalidPayloadResponse
      }
    }
  }
} 
Example 46
Source File: RichRowSuite.scala    From spark-excel   with Apache License 2.0 5 votes vote down vote up
package com.crealytics.spark.excel

import org.apache.poi.ss.usermodel.{Cell, Row}
import org.scalacheck.Gen
import org.scalacheck.Prop.BooleanOperators
import org.scalamock.scalatest.MockFactory

import scala.util.Try
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalatest.funsuite.AnyFunSuite

trait RowGenerator extends MockFactory {
  private val MAX_WIDTH = 100

  protected case class GeneratedRow(start: Int, end: Int, lastCellNum: Int, row: Row)

  protected val rowGen: Gen[GeneratedRow] = for {
    startColumn <- Gen.choose(0, MAX_WIDTH - 1)
    endColumn <- Gen.choose(0, MAX_WIDTH - 1)
    lastCellNum <- Gen.choose(0, MAX_WIDTH - 1)
    row = stub[Row]
    _ = (row.getCell(_: Int)).when(*) returns stub[Cell]
    _ = row.getLastCellNum _ when () returns lastCellNum.toShort
  } yield GeneratedRow(startColumn, endColumn, lastCellNum, row)
}

class RichRowSuite extends AnyFunSuite with ScalaCheckPropertyChecks with RowGenerator {
  test("Invalid cell range should throw an error") {
    forAll(rowGen) { g =>
      (g.start > g.end) ==> Try {
        g.row.eachCellIterator(g.start, g.end).next()
      }.isFailure
    }
  }

  test("Valid cell range should iterate through all non-empty cells") {
    forAll(rowGen) { g =>
      (g.start <= g.end && g.start < g.lastCellNum) ==> {
        val count = g.row.eachCellIterator(g.start, g.end).size
        count === Math.min(g.end, g.lastCellNum - 1) - g.start + 1
      }
    }
  }

  test("Valid cell range should should not iterate through non-empty cells") {
    forAll(rowGen) { g =>
      (g.start <= g.end && g.start >= g.lastCellNum) ==> {
        g.row.eachCellIterator(g.start, g.end).size === 0
      }
    }
  }
} 
Example 47
Source File: KustoSourceTests.scala    From azure-kusto-spark   with Apache License 2.0 5 votes vote down vote up
package com.microsoft.kusto.spark

import com.microsoft.kusto.spark.datasource.KustoSourceOptions
import com.microsoft.kusto.spark.utils.{KustoDataSourceUtils => KDSU}
import org.apache.spark.SparkContext
import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}
import org.apache.spark.sql.{SQLContext, SparkSession}
import org.junit.runner.RunWith
import org.scalamock.scalatest.MockFactory
import org.scalatest.junit.JUnitRunner
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

@RunWith(classOf[JUnitRunner])
class KustoSourceTests extends FlatSpec with MockFactory with Matchers with BeforeAndAfterAll {
  private val loggingLevel: Option[String] = Option(System.getProperty("logLevel"))
  if (loggingLevel.isDefined) KDSU.setLoggingLevel(loggingLevel.get)

  private val nofExecutors = 4
  private val spark: SparkSession = SparkSession.builder()
    .appName("KustoSource")
    .master(f"local[$nofExecutors]")
    .getOrCreate()

  private var sc: SparkContext = _
  private var sqlContext: SQLContext = _
  private val cluster: String = "KustoCluster"
  private val database: String = "KustoDatabase"
  private val query: String = "KustoTable"
  private val appId: String = "KustoSinkTestApplication"
  private val appKey: String = "KustoSinkTestKey"
  private val appAuthorityId: String = "KustoSinkAuthorityId"

  override def beforeAll(): Unit = {
    super.beforeAll()

    sc = spark.sparkContext
    sqlContext = spark.sqlContext
  }

  override def afterAll(): Unit = {
    super.afterAll()

    sc.stop()
  }

  "KustoDataSource" should "recognize Kusto and get the correct schema" in {
    val spark: SparkSession = SparkSession.builder()
      .appName("KustoSource")
      .master(f"local[$nofExecutors]")
      .getOrCreate()

    val customSchema = "colA STRING, colB INT"

    val df = spark.sqlContext
      .read
      .format("com.microsoft.kusto.spark.datasource")
      .option(KustoSourceOptions.KUSTO_CLUSTER, cluster)
      .option(KustoSourceOptions.KUSTO_DATABASE, database)
      .option(KustoSourceOptions.KUSTO_QUERY, query)
      .option(KustoSourceOptions.KUSTO_AAD_APP_ID, appId)
      .option(KustoSourceOptions.KUSTO_AAD_APP_SECRET, appKey)
      .option(KustoSourceOptions.KUSTO_AAD_AUTHORITY_ID, appAuthorityId)
      .option(KustoSourceOptions.KUSTO_CUSTOM_DATAFRAME_COLUMN_TYPES, customSchema)
      .load("src/test/resources/")

    val expected = StructType(Array(StructField("colA", StringType, nullable = true),StructField("colB", IntegerType, nullable = true)))
    assert(df.schema.equals(expected))
  }
} 
Example 48
Source File: ControllerActorTest.scala    From sparta   with Apache License 2.0 5 votes vote down vote up
package com.stratio.sparta.serving.api.actor

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit}
import com.stratio.sparta.driver.service.StreamingContextService
import com.stratio.sparta.serving.core.actor.{RequestActor, FragmentActor, StatusActor}
import com.stratio.sparta.serving.core.config.SpartaConfig
import com.stratio.sparta.serving.core.constants.AkkaConstant
import org.apache.curator.framework.CuratorFramework
import org.junit.runner.RunWith
import org.scalamock.scalatest.MockFactory
import org.scalatest._
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class ControllerActorTest(_system: ActorSystem) extends TestKit(_system)
  with ImplicitSender
  with WordSpecLike
  with Matchers
  with BeforeAndAfterAll
  with MockFactory {

  SpartaConfig.initMainConfig()
  SpartaConfig.initApiConfig()

  val curatorFramework = mock[CuratorFramework]
  val statusActor = _system.actorOf(Props(new StatusActor(curatorFramework)))
  val executionActor = _system.actorOf(Props(new RequestActor(curatorFramework)))
  val streamingContextService = new StreamingContextService(curatorFramework)
  val fragmentActor = _system.actorOf(Props(new FragmentActor(curatorFramework)))
  val policyActor = _system.actorOf(Props(new PolicyActor(curatorFramework, statusActor)))
  val sparkStreamingContextActor = _system.actorOf(
    Props(new LauncherActor(streamingContextService, curatorFramework)))
  val pluginActor = _system.actorOf(Props(new PluginActor()))
  val configActor = _system.actorOf(Props(new ConfigActor()))

  def this() =
    this(ActorSystem("ControllerActorSpec", SpartaConfig.daemonicAkkaConfig))

  implicit val actors = Map(
    AkkaConstant.StatusActorName -> statusActor,
    AkkaConstant.FragmentActorName -> fragmentActor,
    AkkaConstant.PolicyActorName -> policyActor,
    AkkaConstant.LauncherActorName -> sparkStreamingContextActor,
    AkkaConstant.PluginActorName -> pluginActor,
    AkkaConstant.ExecutionActorName -> executionActor,
    AkkaConstant.ConfigActorName -> configActor
  )

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "ControllerActor" should {
    "set up the controller actor that contains all sparta's routes without any error" in {
      _system.actorOf(Props(new ControllerActor(actors, curatorFramework)))
    }
  }
} 
Example 49
Source File: AppStatusHttpServiceTest.scala    From sparta   with Apache License 2.0 5 votes vote down vote up
package com.stratio.sparta.serving.api.service.http

import akka.actor.ActorRef
import com.stratio.sparta.serving.api.constants.HttpConstant
import org.apache.curator.framework.CuratorFramework
import org.junit.runner.RunWith
import org.scalamock.scalatest.MockFactory
import org.scalatest.WordSpec
import org.scalatest.junit.JUnitRunner
import spray.http.StatusCodes

@RunWith(classOf[JUnitRunner])
class AppStatusHttpServiceTest extends WordSpec
                              with AppStatusHttpService
                              with HttpServiceBaseTest
with MockFactory {

  override implicit val actors: Map[String, ActorRef] = Map()
  override val supervisor: ActorRef = testProbe.ref
  override val curatorInstance = mock[CuratorFramework]

  "AppStatusHttpService" should {
    "check the status of the server" in {
      Get(s"/${HttpConstant.AppStatus}") ~> routes() ~> check {
        status should be (StatusCodes.InternalServerError)
      }
    }
  }
} 
Example 50
Source File: Build.scala    From sbt-lighter   with Apache License 2.0 5 votes vote down vote up
import com.amazonaws.services.elasticmapreduce._
import com.amazonaws.services.elasticmapreduce.model._
import com.amazonaws.services.s3._
import com.amazonaws.services.s3.model._
import org.scalamock.scalatest.MockFactory

object Build extends MockFactory {
  val emr = stub[AmazonElasticMapReduce]

  inSequence {
    (emr
      .listClusters(_: ListClustersRequest))
      .when(*)
      .returns(new ListClustersResult())
    (emr
      .runJobFlow(_: RunJobFlowRequest))
      .when(*)
      .returns(
        new RunJobFlowResult().withJobFlowId("j-xxxlighterxxx")
      )
    (emr
      .listClusters(_: ListClustersRequest))
      .when(*)
      .anyNumberOfTimes()
      .returns(
        new ListClustersResult().withClusters(
          new ClusterSummary().withId("j-xxxlighterxxx")
        )
      )
  }

  (emr
    .addJobFlowSteps(_: AddJobFlowStepsRequest))
    .when(*)
    .returns(new AddJobFlowStepsResult())

  (emr
    .terminateJobFlows(_: TerminateJobFlowsRequest))
    .when(*)
    .returns(new TerminateJobFlowsResult())

  val s3 = stub[AmazonS3]

  (s3
    .putObject(_: PutObjectRequest))
    .when(*)
    .returns(new PutObjectResult())
} 
Example 51
Source File: MessagesSuite.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
package com.bot4s.telegram.api

import cats.instances.future._
import com.bot4s.telegram.api.declarative._
import com.bot4s.telegram.models.{Message, Update}
import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpec

import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.Future

class MessagesSuite extends FlatSpec with MockFactory with TestUtils {

  trait Fixture {
    val handler = mockFunction[Message, Future[Unit]]
    val bot = new TestBot with Messages[Future]
  }

  "A message filter " should "accept matches" in new Fixture {
    val helloMsg = textMessage("hello")
    handler.expects(helloMsg).returning(Future.successful(())).once()
    when[Future, Message](bot.onMessage, _.text.contains("hello"))(handler)
    bot.receiveMessage(helloMsg).get
  }

  it should "ignore non-matches" in new Fixture {
    handler.expects(*).never()
    when[Future, Message](bot.onMessage, _.text.contains("hello"))(handler)
    bot.receiveMessage(textMessage("abc"))
  }

  "onMessage" should "catch all messages" in new Fixture {
    val msgs = (0 until 100).map (t => textMessage(t.toString))
    for (m <- msgs)
      handler.expects(m).returning(Future.successful(())).once()
    bot.onMessage(handler)
    val r = Future.traverse(msgs) { m => bot.receiveUpdate(Update(123, Some(m)), None) }
    r.get
  }

  "editedMessage filter " should "accept matches" in new Fixture {
    val helloMsg = textMessage("hello")
    handler.expects(helloMsg).returning(Future.successful(())).once()
    when[Future, Message](bot.onEditedMessage, _.text.contains("hello"))(handler)
    bot.receiveEditedMessage(helloMsg).get
  }

  it should "ignore non-matches" in new Fixture {
    handler.expects(*).never()
    when[Future, Message](bot.onEditedMessage, _.text.contains("hello"))(handler)
    bot.receiveEditedMessage(textMessage("abc"))
  }

  "onEditedMessage" should "catch all messages" in new Fixture {
    val msgs = (0 until 100).map (t => textMessage(t.toString))
    for (m <- msgs)
      handler.expects(m).returning(Future.successful(())).once()
    bot.onEditedMessage(handler)
    val r = Future.traverse(msgs) { m => bot.receiveUpdate(Update(123, editedMessage = Some(m)), None) }
    r.get
  }
} 
Example 52
Source File: InlineQueriesSuite.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
package com.bot4s.telegram.api

import cats.instances.future._
import com.bot4s.telegram.api.declarative._
import com.bot4s.telegram.models.{InlineQuery, Update}
import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpec

import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.Future

class InlineQueriesSuite extends FlatSpec with MockFactory with TestUtils {

  trait Fixture {
    val handler = mockFunction[InlineQuery, Future[Unit]]
    val bot = new TestBot with InlineQueries[Future] with RegexCommands[Future]
  }

  "Inline query filter" should "accept matches" in new Fixture {
    val q = inlineQuery("hello")
    handler.expects(q).returning(Future.successful(())).once()
    when[Future, InlineQuery](bot.onInlineQuery, _.query == "hello")(handler)
    bot.receiveInlineQuery(q).get
  }

  it should "ignore non-matches" in new Fixture {
    handler.expects(*).never()
    when[Future, InlineQuery](bot.onInlineQuery, _.query == "hello")(handler)
    bot.receiveInlineQuery(inlineQuery("abc"))
  }

  "onInlineQuery" should "catch all messages" in new Fixture {
    val queries = (0 until 100).map (t => inlineQuery(t.toString))
    for (q <- queries)
      handler.expects(q).returning(Future.successful(())).once()
    bot.onInlineQuery(handler)
    val r = Future.traverse(queries) { q => bot.receiveUpdate(Update(123, inlineQuery = Some(q)), None) }
    r.get
  }

  "onRegexInline" should "pass matched groups" in new Fixture {
    val argsHandler = mockFunction[InlineQuery, Seq[String], Future[Unit]]
    argsHandler.expects(*, Seq("1234")).returning(Future.successful(())).once()
    bot.onRegexInline("""/cmd ([0-9]+)""".r)(argsHandler.curried)
    bot.receiveInlineQuery(inlineQuery("/cmd 1234")).get
  }
} 
Example 53
Source File: RegexCommandsSuite.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
package com.bot4s.telegram.api

import com.bot4s.telegram.api.declarative.RegexCommands
import com.bot4s.telegram.models.Message
import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpec

import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.Future

class RegexCommandsSuite extends FlatSpec with MockFactory with TestUtils {

  trait Fixture {
    val handler = mockFunction[Message, Seq[String], Future[Unit]]
    val bot = new TestBot with RegexCommands[Future]
  }

  behavior of "RegexCommands"

  it should "match simple regex" in new Fixture {
    handler.expects(*, Seq("/pepe")).returning(Future.successful(())).once()
    handler.expects(*, Seq("/cojo")).returning(Future.successful(())).once()

    bot.onRegex("""(/pepe|/cojo)""".r)(handler.curried)

    (for {
      // Invalid
      _ <- bot.receiveMessage(textMessage("/cocou"))
      _ <- bot.receiveMessage(textMessage("/pepecojo"))
      _ <- bot.receiveMessage(textMessage("/cojopepe"))

      // Valid
      _ <- bot.receiveMessage(textMessage("  /pepe  "))
      _ <- bot.receiveMessage(textMessage("/cojo"))
    } yield ()).get
  }

  it should "pass regex groups" in new Fixture {
    handler.expects(*, List("1234")).returning(Future.successful(())).once
    bot.onRegex("""/cmd ([0-9]+)""".r)(handler.curried)
    bot.receiveMessage(textMessage("/cmd 1234")).get
  }
} 
Example 54
Source File: MarshallingSuite.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
package com.bot4s.telegram.marshalling

import com.bot4s.telegram.api.TestUtils
import com.bot4s.telegram.models.CountryCode.CountryCode
import com.bot4s.telegram.models.Currency.Currency
import com.bot4s.telegram.models.MaskPositionType.MaskPositionType
import com.bot4s.telegram.models.MessageEntityType.MessageEntityType
import com.bot4s.telegram.models.{ChatId, MaskPositionType, _}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class MarshallingSuite extends FlatSpec with MockFactory with Matchers with TestUtils {

  behavior of "Circe JSON marshalling"

  it should "correctly parse Invoice" in {
    val i = Invoice("A", "B", "C", Currency.USD, 1234)
    i should ===(fromJson[Invoice](toJson(i)))
  }

  it should "correctly parse Country (Chile)" in {
    val parsedCountry = fromJson[CountryCode](""" "CL" """)
    parsedCountry should ===(CountryCode.CL)
    parsedCountry.englishName should ===(CountryCode.CL.englishName)
  }

  it should "correctly parse Currency (USD)" in {
    val parsedCurrency = fromJson[Currency](""" "USD" """)
    parsedCurrency should ===(Currency.USD)
    parsedCurrency.symbol === (Currency.USD.symbol)
  }

  it should "correctly parse ChatId" in {
    val channel = fromJson[ChatId](""" "my_channel" """)
    val chat = fromJson[ChatId](""" 123456 """)
    channel should ===(ChatId.Channel("my_channel"))
    chat should ===(ChatId.Chat(123456))
  }

  it should "correctly serialize ChatId" in {
    toJson[ChatId](ChatId.Channel("my_channel")) === (""""my_channel"""")
    toJson[ChatId](ChatId.Chat(123456)) === ("""123456""")
  }

  it should "correctly parse Either[Boolean, Message]" in {
    fromJson[Either[Boolean, Message]]("true") === (true)
    val msg = textMessage("Hello world")
    val msgJson = toJson[Message](msg)
    fromJson[Either[Boolean, Message]](msgJson) === (msg)
  }

  it should "correctly de/serialize MessageEntityType" in {
    fromJson[MessageEntityType](""""phone_nuber"""") === (MessageEntityType.PhoneNumber)
    // MessageEntityType fallback to Unknown
    fromJson[MessageEntityType](""""not_a_message_entity"""") === (MessageEntityType.Unknown)
    toJson(MessageEntityType.PhoneNumber) === ("phone_number")
  }

  it should "correctly de/serialize MaskPositionType" in {
    fromJson[MaskPositionType](""""chin"""") === (MaskPositionType.Chin)
    toJson(MaskPositionType.Mouth) === ("mouth")
  }

  it should "correctly de/serialize Message.migrateToChatId" in {
    fromJson[Message](
      """{
        |"message_id": 1,
        |"date": 1,
        |"chat": {"id": 123, "type": "private"},
        |"migrate_to_chat_id": 12345678901234567
        |}""".stripMargin)
      .migrateToChatId === 12345678901234567L
  }

  it should "correctly parse User" in {
    fromJson[User](
      """{
        |"id": 123,
        |"is_bot": true,
        |"first_name": "Pepe"
        |}""".stripMargin)
      .isBot === User(id = 1, isBot=true, firstName="Pepe")
  }
} 
Example 55
Source File: SparkApplicationTester.scala    From TopNotch   with Apache License 2.0 5 votes vote down vote up
package com.bfm.topnotch

import org.scalatest.OneInstancePerTest
import org.apache.hadoop.hbase.CellUtil
import org.apache.hadoop.hbase.client.{HConnection, HTableInterface, Put}
import org.apache.spark._
import org.apache.spark.sql.SparkSession
import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpec
import com.typesafe.scalalogging.StrictLogging

/**
 * This class handles some of the boilerplate of testing SparkApplications with HBase writers
 */
abstract class SparkApplicationTester extends FlatSpec with OneInstancePerTest with MockFactory with StrictLogging
  with SharedSparkContext {
  protected val hconn = mock[HConnection]
  lazy val spark = SparkSession
    .builder()
    .appName(getClass.getName)
    .master("local")
    .config("spark.sql.shuffle.partitions", "4")
    //setting this to false to emulate HiveQL's case insensitivity for column names
    .config("spark.sql.caseSensitive", "false")
    .getOrCreate()

  /**
   * Verify that the next HTable will receive the correct puts. Call this once per HTable that is supposed to be created and written to.
   * Note: All HBase tests for a SparkApplication object must be run sequentially in order for us to keep track of HTableInterface mocks
   * @param tests The test's expected name for the HTable and expected values for the Put objects placed in the HTable
   * @param acceptAnyPut Tells the mock to accept any put value. This is useful for tests using the mock and but not
   *                     testing what is put inside it.
   */
  def setHBaseMock(tests: HTableParams, acceptAnyPut: Boolean = false): Unit = {
    val table = mock[HTableInterface]
    inSequence {
      (hconn.getTable(_: String)).expects(tests.tableName).returning(table)
      inAnyOrder {
        for (correctPut <- tests.puts) {
          if (acceptAnyPut) {
            (table.put(_: Put)).expects(*)
          }
          else {
            (table.put(_: Put)).expects(where {
              (actualPut: Put) =>
                val actualValue = CellUtil.cloneValue(actualPut.get(correctPut.columnFamily, correctPut.columnQualifier).get(0))
                correctPut.valueTest(actualValue)
                // just return true, as if issues, will have exception thrown by value test
                true
            })
          }
        }
      }
      (table.close _).expects().returns()
    }
  }

  /**
    * Set the next HTable will accept anything accept anything. This is useful if testing a thing that needs an hbase
    * table, but the specific test isn't testing the hbase functionality.
    *
    * @param tableName the name of the table that will be accessed.
    */
  def allowAnyHBaseActions(tableName: String): Unit ={
    setHBaseMock(new HTableParams(tableName, Seq(null)), true)
  }

  /**
   * The set of parameters defining what values should be used to create the HTable
   * @param tableName The name of the table the test expects to be created
   * @param puts The list of parameters for the puts that the test expects to be placed in the table
   */
  case class HTableParams(
                           tableName: String,
                           puts: Seq[HPutParams]
                           )

  /**
   * The list of values that the test expects to be in a put.
   * @param row The name of the row to put into HBase
   * @param columnFamily The cell's column family
   * @param columnQualifier The cell's column qualifier
   * @param correctString A string representing the correct value or an error message
   * @param valueTest The method for checking if the value in the cell is correct. Done as the actual and intended values
   *                  in a cell may be equal even if they don't have the expression as an array of bytes.
    *                 This should throw an exception on failure, using a call like shouldBe
   */
  case class HPutParams(
                         row: Array[Byte],
                         columnFamily: Array[Byte],
                         columnQualifier: Array[Byte],
                         correctString: String,
                         valueTest: Array[Byte] => Unit
                         )
} 
Example 56
Source File: NotificationSenderTest.scala    From teamcity-slack   with MIT License 5 votes vote down vote up
package com.fpd.teamcity.slack

import com.fpd.teamcity.slack.ConfigManager.BuildSettingFlag.BuildSettingFlag
import com.fpd.teamcity.slack.ConfigManager.{BuildSetting, BuildSettingFlag, Config}
import com.fpd.teamcity.slack.SlackGateway.SlackAttachment
import jetbrains.buildServer.messages.Status
import jetbrains.buildServer.serverSide.{Branch, SBuild}
import jetbrains.buildServer.vcs.SVcsModification
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

import scala.collection.JavaConverters._

class NotificationSenderTest extends FlatSpec with MockFactory with Matchers {
  import NotificationSenderTest._

  "NotificationSender.prepareSettings" should "return setting if build success" in new Context {
    def settingFlags = Set(BuildSettingFlag.success)

    sender.prepareSettings(build, Set(BuildSettingFlag.success)).toSet shouldEqual Set(setting)
  }

  "NotificationSender.prepareSettings" should "not return setting if build success" in new Context {
    def settingFlags = Set(BuildSettingFlag.success, BuildSettingFlag.failureToSuccess)

    sender.prepareSettings(build, Set(BuildSettingFlag.success)).toSet shouldEqual Set.empty[BuildSetting]
  }

  "NotificationSender.prepareSettings" should "not return setting if build fails" in new Context {
    def settingFlags = Set(BuildSettingFlag.failure, BuildSettingFlag.successToFailure)

    sender.prepareSettings(build, Set(BuildSettingFlag.failure)).toSet shouldEqual Set.empty[BuildSetting]
  }

  "NotificationSender.prepareSettings" should "return setting if build fails" in new Context {
    def settingFlags = Set(BuildSettingFlag.failure)

    sender.prepareSettings(build, Set(BuildSettingFlag.failure)).toSet shouldEqual Set(setting)
  }

  "NotificationSender.shouldSendPersonal" should "return true" in new Context {
    def settingFlags = Set(BuildSettingFlag.failure)
    manager.setConfig(manager.config.get.copy(personalEnabled = Some(true)))
    build.getBuildStatus _ when() returns Status.FAILURE

    sender.shouldSendPersonal(build) shouldEqual true
  }

  "NotificationSender.shouldSendPersonal" should "return false when personalEnabled is false" in new Context {
    def settingFlags = Set(BuildSettingFlag.failure)
    manager.setConfig(manager.config.get.copy(personalEnabled = Some(false)))
    build.getBuildStatus _ when() returns Status.FAILURE

    sender.shouldSendPersonal(build) shouldEqual false
  }

  "NotificationSender.shouldSendPersonal" should "return false when build is success" in new Context {
    def settingFlags = Set(BuildSettingFlag.failure)
    build.getBuildStatus _ when() returns Status.NORMAL

    sender.shouldSendPersonal(build) shouldEqual false
  }
}

object NotificationSenderTest {

  class NotificationSenderStub(val configManager: ConfigManager,
                               val gateway: SlackGateway,
                               val messageBuilderFactory: MessageBuilderFactory
                              ) extends NotificationSender {
  }

  trait Context extends CommonMocks {
    val gateway: SlackGateway = stub[SlackGateway]
    val messageBuilderFactory: MessageBuilderFactory = stub[MessageBuilderFactory]

    private val builder = stub[SBuildMessageBuilder]
    builder.compile _ when(*, *) returns SlackAttachment("", "", "")
    (messageBuilderFactory.createForBuild(_: SBuild)) when * returns builder

    val sender = new NotificationSenderStub(manager, gateway, messageBuilderFactory)

    def settingFlags: Set[BuildSettingFlag]
    val channelName = "general"
    val setting = BuildSetting("buildTypeId", "my-branch", channelName, "", settingFlags)
    val build: SBuild = stub[SBuild]
    val branch: Branch = stub[Branch]

    manager.setConfig(Config("", Map("some-key" → setting)))

    branch.getDisplayName _ when() returns setting.branchMask
    build.getBuildTypeId _ when() returns setting.buildTypeId
    build.getBranch _ when() returns branch
    build.getContainingChanges _ when() returns List.empty[SVcsModification].asJava
  }
} 
Example 57
Source File: SlackServerAdapterTest.scala    From teamcity-slack   with MIT License 5 votes vote down vote up
package com.fpd.teamcity.slack

import com.fpd.teamcity.slack.ConfigManager.BuildSettingFlag
import com.fpd.teamcity.slack.ConfigManager.BuildSettingFlag.BuildSettingFlag
import com.fpd.teamcity.slack.SlackServerAdapter._
import jetbrains.buildServer.messages.Status
import org.scalamock.scalatest.MockFactory
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.scalatest.{FlatSpec, Matchers}

class SlackServerAdapterTest extends FlatSpec with MockFactory with Matchers {
  "SlackServerAdapter.statusChanged" should "work properly" in {
    forAll(data) { (previous: Status, current: Status, changed: Boolean) ⇒
      statusChanged(previous, current) shouldEqual changed
    }

    def data =
      Table(
        ("previous", "current", "changed"), // First tuple defines column names
        // Subsequent tuples define the data
        (Status.FAILURE, Status.NORMAL, true),
        (Status.ERROR, Status.NORMAL, true),
        (Status.NORMAL, Status.FAILURE, true),
        (Status.NORMAL, Status.ERROR, true),
        (Status.UNKNOWN, Status.FAILURE, false),
        (Status.UNKNOWN, Status.NORMAL, false),
        (Status.NORMAL, Status.UNKNOWN, false),
        (Status.FAILURE, Status.UNKNOWN, false),
        (Status.FAILURE, Status.FAILURE, false),
        (Status.NORMAL, Status.NORMAL, false),
        (Status.ERROR, Status.ERROR, false),
        (Status.UNKNOWN, Status.UNKNOWN, false)
      )
  }

  "SlackServerAdapter.calculateFlags" should "work properly" in {
    forAll(data) { (previous: Status, current: Status, flags: Set[BuildSettingFlag]) ⇒
      calculateFlags(previous, current) shouldEqual flags
    }

    import BuildSettingFlag._
    def data =
      Table(
        ("previous", "current", "flags"), // First tuple defines column names
        // Subsequent tuples define the data
        (Status.FAILURE, Status.NORMAL, Set(success, failureToSuccess)),
        (Status.ERROR, Status.NORMAL, Set(success, failureToSuccess)),
        (Status.NORMAL, Status.FAILURE, Set(failure, successToFailure)),
        (Status.NORMAL, Status.ERROR, Set(failure, successToFailure)),
        (Status.UNKNOWN, Status.FAILURE, Set(failure)),
        (Status.UNKNOWN, Status.ERROR, Set(failure)),
        (Status.UNKNOWN, Status.NORMAL, Set(success))
      )
  }
} 
Example 58
Source File: BuildSettingsTryTest.scala    From teamcity-slack   with MIT License 5 votes vote down vote up
package com.fpd.teamcity.slack.controllers

import com.fpd.teamcity.slack.ConfigManager.BuildSetting
import com.fpd.teamcity.slack.SlackGateway.{Destination, SlackChannel, SlackUser}
import jetbrains.buildServer.serverSide.{Branch, BuildHistory, SFinishedBuild}
import jetbrains.buildServer.users.SUser
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
import org.scalatest.prop.TableDrivenPropertyChecks._

import scala.collection.JavaConverters._

class BuildSettingsTryTest extends FlatSpec with MockFactory with Matchers {
  "BuildSettingsTry.findPreviousBuild" should "work" in {
    val buildTypeId = "MyBuildTypeId"

    // Branches
    val branchMaster = stub[Branch]
    branchMaster.getDisplayName _ when() returns "master"

    val branchDefault = stub[Branch]
    branchDefault.getDisplayName _ when() returns "default"

    // Builds
    val buildWithoutBranch = stub[SFinishedBuild]
    buildWithoutBranch.getBranch _ when() returns null
    buildWithoutBranch.getBuildTypeId _ when() returns buildTypeId

    val buildDefault = stub[SFinishedBuild]
    buildDefault.getBranch _ when() returns branchDefault
    buildDefault.getBuildTypeId _ when() returns buildTypeId

    val buildMaster = stub[SFinishedBuild]
    buildMaster.getBranch _ when() returns branchMaster
    buildMaster.getBuildTypeId _ when() returns buildTypeId

    // Build histories
    val emptyBuildHistory = stub[BuildHistory]
    emptyBuildHistory.getEntries _ when * returns Seq[SFinishedBuild]().asJava

    val buildHistoryWithMatch = stub[BuildHistory]
    buildHistoryWithMatch.getEntries _ when * returns Seq(buildWithoutBranch).asJava

    val buildHistoryWithMatch2 = stub[BuildHistory]
    buildHistoryWithMatch2.getEntries _ when * returns Seq(buildDefault).asJava

    val buildHistoryWithoutMatch = stub[BuildHistory]
    buildHistoryWithoutMatch.getEntries _ when * returns Seq(buildMaster).asJava

    // settings
    val settingMatchAll = BuildSetting(buildTypeId, ".*", "", "")
    val settingMatchDefault = BuildSetting(buildTypeId, "default", "", "")

    // Assertion
    forAll(data) { (buildHistory: BuildHistory, buildSetting: BuildSetting, found: Option[SFinishedBuild]) ⇒
      BuildSettingsTry.findPreviousBuild(buildHistory, buildSetting) shouldEqual found
    }

    def data =
      Table(
        ("buildHistory", "buildSetting", "found"), // First tuple defines column names
        // Subsequent tuples define the data
        (emptyBuildHistory, settingMatchAll, None),
        (buildHistoryWithMatch, settingMatchAll, Some(buildWithoutBranch)),
        (buildHistoryWithoutMatch, settingMatchDefault, None),
        (buildHistoryWithMatch2, settingMatchDefault, Some(buildDefault))
      )
  }

  "BuildSettingsTry.detectDestination" should "work" in {
    forAll(data) { (setting: BuildSetting, user: SUser, expected: Option[Destination]) ⇒
      BuildSettingsTry.detectDestination(setting, user) shouldEqual expected
    }

    def data = {
      val buildTypeId = "MyBuildTypeId"
      val email = "[email protected]"
      val channelName = "general"
      val branchName = "default"

      val user = stub[SUser]
      user.getEmail _ when() returns email

      Table(
        ("setting", "user", "expected"), // First tuple defines column names
        // Subsequent tuples define the data
        (BuildSetting(buildTypeId, branchName, "", ""), user, None),
        (BuildSetting(buildTypeId, branchName, channelName, ""), user, Some(SlackChannel(channelName))),
        (BuildSetting(buildTypeId, branchName, "", "", notifyCommitter = true), user, Some(SlackUser(email)))
      )
    }
  }
} 
Example 59
Source File: ConfigManagerTest.scala    From teamcity-slack   with MIT License 5 votes vote down vote up
package com.fpd.teamcity.slack

import com.fpd.teamcity.slack.ConfigManager.BuildSetting
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class ConfigManagerTest extends FlatSpec with MockFactory with Matchers {
  "updateBuildSetting" should "preserve build settings when changing API key" in new CommonMocks {
    val key = "SomeKey"
    manager.update(key, "", personalEnabled = true, enabled = true, "", sendAsAttachment = true)
    manager.oauthKey shouldEqual Some(key)

    val buildSetting = BuildSetting("", "", "", "{name}", Set.empty)
    manager.updateBuildSetting(buildSetting, None)
    manager.oauthKey shouldEqual Some(key)
    manager.allBuildSettingList.values.toSet shouldEqual Set(buildSetting)
  }
} 
Example 60
Source File: CheckpointTrackerActorSpec.scala    From kinesis-stream   with MIT License 5 votes vote down vote up
package px.kinesis.stream.consumer.checkpoint

import akka.actor.Status.Failure
import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{ImplicitSender, TestKit}
import org.scalamock.scalatest.MockFactory
import org.scalatest.funspec.AnyFunSpecLike
import org.scalatest.BeforeAndAfterAll
import org.scalatest.matchers.must.Matchers
import px.kinesis.stream.consumer.checkpoint.CheckpointTrackerActor._
import px.kinesis.stream.consumer.checkpoint.{ShardCheckpointTrackerActor => shard}
import software.amazon.kinesis.retrieval.kpl.ExtendedSequenceNumber

import scala.collection.immutable.Seq

class CheckpointTrackerActorSpec
    extends TestKit(ActorSystem("CheckpointTrackerActorSpec"))
    with ImplicitSender
    with AnyFunSpecLike
    with Matchers
    with BeforeAndAfterAll
    with MockFactory {
  override def afterAll: Unit = {
    TestKit.shutdownActorSystem(system)
  }

  val workerId = "123"

  def toSequenceNum(i: Int): ExtendedSequenceNumber =
    new ExtendedSequenceNumber(i.toString)

  def createTracker(): ActorRef =
    system.actorOf(
      CheckpointTrackerActor
        .props(workerId, 10, 10))

  describe("track") {
    it("should track successfully after creation of tracker") {
      val tracker = createTracker()
      val shardId = "01"
      tracker ! Command.Create(shardId)
      expectMsg(Response.Ack)

      tracker ! Command.Track(shardId, Seq(1).map(toSequenceNum))
      expectMsg(shard.Response.Ack)
    }

    it("should fail if tracker is not active") {
      val tracker = createTracker()
      val shardId = "01"
      // shard tracker for 01 does not exist
      tracker ! Command.Track(shardId, Seq(1).map(toSequenceNum))
      expectMsgPF() {
        case Failure(_) => true
      }
    }
  }

  describe("process") {
    it("should process successfully after creation of tracker") {
      val tracker = createTracker()
      val shardId = "01"
      tracker ! Command.Create(shardId)
      expectMsg(Response.Ack)

      tracker ! Command.Process(shardId, toSequenceNum(1))
      expectMsg(shard.Response.Ack)
    }

    it("should process successfully even after shard tracker is shutdown") {
      val tracker = createTracker()
      val shardId = "01"
      tracker ! Command.Create(shardId)
      expectMsg(Response.Ack)

      tracker ! Command.Process(shardId, toSequenceNum(1))
      expectMsg(shard.Response.Ack)

      tracker ! Command.ShutdownShard(shardId)
      expectMsg(Response.Ack)

      tracker ! Command.Process(shardId, toSequenceNum(2))
      expectMsg(shard.Response.Ack)

    }

  }
} 
Example 61
Source File: ModelsSpec.scala    From remora   with MIT License 5 votes vote down vote up
import models.RegistryKafkaMetric
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class ModelsSpec extends FlatSpec with Matchers with MockFactory {

  "RegistryKafkaMetric" should "be encoded as a string as expected with partition" in {
    val metric = RegistryKafkaMetric("gauge","topic", Some("partition"), "group","lag")
    RegistryKafkaMetric.encode(metric) should be("gauge.topic.partition.group.lag")
  }

  it should "be decoded from string without partition" in {
    val stringMetric = "gauge.topic.group.lag"
    RegistryKafkaMetric.decode(stringMetric) should be(Some(RegistryKafkaMetric("gauge","topic", None,"group","lag")))
  }

  it should "be encoded as a string as expected without partition" in {
    val metric = RegistryKafkaMetric("gauge","topic", None, "group","lag")
    RegistryKafkaMetric.encode(metric) should be("gauge.topic.group.lag")
  }

  it should "be decoded from string with partition" in {
    val stringMetric = "gauge.topic.partition.group.lag"
    RegistryKafkaMetric.decode(stringMetric) should be(Some(RegistryKafkaMetric("gauge","topic", Some("partition"),"group","lag")))
  }



  it should "return None if metric name is not standard" in {
    val stringMetric = "gauge.faulty"
    RegistryKafkaMetric.decode(stringMetric) should be(None)
  }


} 
Example 62
Source File: RemoraDatadogReporterSpec.scala    From remora   with MIT License 5 votes vote down vote up
package reporter


import com.codahale.metrics.{Metric, MetricFilter, MetricRegistry}
import config.DataDog
import org.coursera.metrics.datadog.MetricNameFormatter
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers, PrivateMethodTester}

class RemoraDatadogReporterSpec extends FlatSpec with Matchers with PrivateMethodTester with MockFactory {

  private val metricRegistry: MetricRegistry = new MetricRegistry
  private val metric: Metric = mock[Metric]
  private val config = DataDog(enabled = true, "test", 1, "localhost", 8125, List.empty, removeTagsFromMetricName = false)
  private val configRemoveTags = DataDog(enabled = true, "test", 1, "localhost", 8125, List.empty, removeTagsFromMetricName = true)

  "Metrics filter" should "match any metric when no filter is given" in {
    val filter = buildMetricFilter(List.empty)

    filter.matches("any_metrics_name", metric) should be(true)
  }

  it should "match metric containing consumer group name" in {
    val kafkaConsumerGroupName = "test-consumer1"
    val filter = buildMetricFilter(List(kafkaConsumerGroupName))

    filter.matches(s"metric-name-$kafkaConsumerGroupName", metric) should be(true)
  }

  it should "not match metric containing consumer group name" in {
    val filter = buildMetricFilter(List("test-consumer1"))

    filter.matches("some-metrics", metric) should be(false)
  }

  "Metric name formatter" should "add tag information if metric is well formatted" in {
    val formatter = getMetricNameFormatter(config)

    formatter.format(s"${config.name}.gauge.test.1.test-consumer.lag") should be(s"${config.name}.gauge.test.1.test-consumer.lag[topic:test,group:test-consumer,partition:1]")
  }

  it should "not add partition tag information if no partition" in {
    val formatter = getMetricNameFormatter(config)

    formatter.format(s"${config.name}.gauge.test-topic.test-consumer.totalLag") should be(s"${config.name}.gauge.test-topic.test-consumer.totalLag[topic:test-topic,group:test-consumer]")
  }

  it should "not add tag information otherwise" in {
    val formatter = getMetricNameFormatter(config)

    formatter.format(s"${config.name}.gauge.test_1_faulty_test-consumer__lag") should be(s"${config.name}.gauge.test_1_faulty_test-consumer__lag")
  }

  "Metric name formatter without tags" should "add tag information if metric is well formatted" in {
    val formatter = getMetricNameFormatter(configRemoveTags)

    formatter.format(s"${configRemoveTags.name}.gauge.test.1.test-consumer.lag") should be(s"${configRemoveTags.name}.gauge.lag[topic:test,group:test-consumer,partition:1]")
  }

  it should "not add partition tag information if no partition" in {
    val formatter = getMetricNameFormatter(configRemoveTags)

    formatter.format(s"${configRemoveTags.name}.gauge.test-topic.test-consumer.totalLag") should be(s"${configRemoveTags.name}.gauge.totalLag[topic:test-topic,group:test-consumer]")
  }

  private def buildMetricFilter(kafkaConsumerList: List[String], removeTags: Boolean = false): MetricFilter = {
    val config = DataDog(enabled = true, "test", 1, "localhost", 8125, kafkaConsumerList, removeTags)
    val reporter = new RemoraDatadogReporter(metricRegistry, config)
    reporter invokePrivate PrivateMethod[MetricFilter]('kafkaConsumerGroupFilter)()
  }

  private def getMetricNameFormatter(config: DataDog): MetricNameFormatter = {
    val reporter = new RemoraDatadogReporter(metricRegistry, config)
    reporter invokePrivate PrivateMethod[MetricNameFormatter]('metricNameFormatter)(config.removeTagsFromMetricName)
  }
} 
Example 63
Source File: ConsumerPropertiesTest.scala    From reactive-nakadi   with MIT License 5 votes vote down vote up
package org.zalando.react.nakadi.properties

import java.util.UUID

import org.zalando.react.nakadi.commit.handlers.BaseCommitManager
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration._


class ConsumerPropertiesTest extends FlatSpec with Matchers with MockFactory {

  def uuid() = UUID.randomUUID().toString
  def token = "random_token"
  val server = "some.server.zalando.net"
  val eventType = uuid()
  val groupId = uuid()
  val partition = uuid()
  val commitHandler = mock[BaseCommitManager]
  val serverProperties = ServerProperties(host = server, port = 8080, isConnectionSSL = false)

  "ConsumerProperties" should "handle simple case" in {
    val props = ConsumerProperties(
      serverProperties = serverProperties,
      tokenProvider = Option(() => token),
      groupId = groupId,
      partition = partition,
      commitHandler = commitHandler,
      eventType = eventType
    )
    props.serverProperties should === (serverProperties)
    props.tokenProvider.get.apply should === (token)
    props.eventType should === (eventType)
    props.groupId should === (groupId)
    props.partition should === (partition)
    props.commitHandler should === (commitHandler)
    props.offset should === (None)
    props.commitInterval should === (30.seconds)
    props.batchLimit should === (0)
    props.batchFlushTimeoutInSeconds should === (30.seconds)
    props.streamLimit should === (0)
    props.streamTimeoutInSeconds should === (0.seconds)
    props.streamKeepAliveLimit should === (0)
    props.pollParallelism should === (0)
  }

  it should "also be able to set read from end of stream and commitInterval" in {
    val props = ConsumerProperties(
      serverProperties = serverProperties,
      tokenProvider = Option(() => token),
      groupId = groupId,
      partition = partition,
      commitHandler = commitHandler,
      eventType = eventType
    ).commitInterval(10.seconds)
      .readFromStartOfStream()

    props.serverProperties should === (serverProperties)
    props.tokenProvider.get.apply should === (token)
    props.eventType should === (eventType)
    props.groupId should === (groupId)
    props.partition should === (partition)
    props.commitHandler should === (commitHandler)
    props.offset.get.toString should === ("BEGIN")
    props.commitInterval should === (10.seconds)
    props.batchLimit should === (0)
    props.batchFlushTimeoutInSeconds should === (30.seconds)
    props.streamLimit should === (0)
    props.streamTimeoutInSeconds should === (0.seconds)
    props.streamKeepAliveLimit should === (0)
    props.pollParallelism should === (0)
  }

} 
Example 64
Source File: EmbeddedKsqlEngine.scala    From ksql-jdbc-driver   with Apache License 2.0 5 votes vote down vote up
package com.github.mmolimar.ksql.jdbc.embedded

import java.io.IOException

import com.github.mmolimar.ksql.jdbc.utils.TestUtils
import io.confluent.ksql.rest.server.{KsqlRestApplication, KsqlRestConfig}
import io.confluent.ksql.version.metrics.VersionCheckerAgent
import io.confluent.rest.RestConfig
import kafka.utils.Logging
import org.apache.kafka.clients.producer.ProducerConfig
import org.scalamock.scalatest.MockFactory
import io.confluent.ksql.util.KsqlConfig

import scala.collection.JavaConverters._

class EmbeddedKsqlEngine(port: Int = TestUtils.getAvailablePort, brokerList: String, connectUrl: String) extends Logging with MockFactory {

  private val config = new KsqlRestConfig(Map(
    RestConfig.LISTENERS_CONFIG -> s"http://localhost:$port",
    ProducerConfig.BOOTSTRAP_SERVERS_CONFIG -> brokerList,
    KsqlConfig.CONNECT_URL_PROPERTY -> connectUrl,
    "ksql.service.id" -> "ksql-jdbc",
    "ksql.streams.auto.offset.reset" -> "latest",
    "ksql.command.topic.suffix" -> "commands"
  ).asJava)

  lazy val ksqlEngine: KsqlRestApplication = {
    import io.confluent.ksql.rest.server.mock.ksqlRestApplication

    val versionCheckerAgent = mock[VersionCheckerAgent]
    (versionCheckerAgent.start _).expects(*, *).returns((): Unit).anyNumberOfTimes
    (versionCheckerAgent.updateLastRequestTime _).expects().returns((): Unit).anyNumberOfTimes
    ksqlRestApplication(config, versionCheckerAgent)
  }

  @throws[IOException]
  def startup(): Unit = {
    info("Starting up embedded KSQL engine")

    ksqlEngine.start()

    info("Started embedded Zookeeper: " + getConnection)
  }

  def shutdown(): Unit = {
    info("Shutting down embedded KSQL engine")

    TestUtils.swallow(ksqlEngine.stop())

    info("Stopped embedded KSQL engine")
  }

  def getPort: Int = port

  def getConnection: String = "localhost:" + getPort

  override def toString: String = {
    val sb: StringBuilder = new StringBuilder("KSQL{")
    sb.append("connection=").append(getConnection)
    sb.append('}')

    sb.toString
  }

} 
Example 65
Source File: KsqlConnectionSpec.scala    From ksql-jdbc-driver   with Apache License 2.0 5 votes vote down vote up
package com.github.mmolimar.ksql.jdbc

import java.sql.{Connection, SQLException, SQLFeatureNotSupportedException}
import java.util.{Collections, Properties}

import com.github.mmolimar.ksql.jdbc.utils.TestUtils._
import io.confluent.ksql.rest.client.{KsqlRestClient, MockableKsqlRestClient, RestResponse}
import io.confluent.ksql.rest.entity._
import org.eclipse.jetty.http.HttpStatus.Code
import org.scalamock.scalatest.MockFactory
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class KsqlConnectionSpec extends AnyWordSpec with Matchers with MockFactory {

  "A KsqlConnection" when {

    "validating specs" should {
      val values = KsqlConnectionValues("localhost", 8080, None, None, Map.empty[String, String])
      val mockKsqlRestClient = mock[MockableKsqlRestClient]
      val ksqlConnection = new KsqlConnection(values, new Properties) {
        override def init: KsqlRestClient = mockKsqlRestClient
      }

      "throw not supported exception if not supported" in {
        val methods = implementedMethods[KsqlConnection]
        reflectMethods[KsqlConnection](methods = methods, implemented = false, obj = ksqlConnection)
          .foreach(method => {
            assertThrows[SQLFeatureNotSupportedException] {
              method()
            }
          })
      }

      "work if implemented" in {
        assertThrows[SQLException] {
          ksqlConnection.isClosed
        }
        ksqlConnection.getTransactionIsolation should be(Connection.TRANSACTION_NONE)
        ksqlConnection.setClientInfo(new Properties)

        (mockKsqlRestClient.makeKsqlRequest(_: String)).expects(*)
          .returns(RestResponse.successful[KsqlEntityList](Code.OK, new KsqlEntityList))
        ksqlConnection.setClientInfo("", "")
        assertThrows[SQLException] {
          (mockKsqlRestClient.makeKsqlRequest(_: String)).expects(*)
            .returns(RestResponse.erroneous(Code.INTERNAL_SERVER_ERROR, new KsqlErrorMessage(-1, "", Collections.emptyList[String])))
          ksqlConnection.setClientInfo("", "")
        }

        ksqlConnection.isReadOnly should be(false)

        (mockKsqlRestClient.makeStatusRequest _: () => RestResponse[CommandStatuses]).expects
          .returns(RestResponse.successful[CommandStatuses]
            (Code.OK, new CommandStatuses(Collections.emptyMap[CommandId, CommandStatus.Status])))
        ksqlConnection.isValid(0) should be(true)

        Option(ksqlConnection.getMetaData) should not be None

        Option(ksqlConnection.createStatement) should not be None
        assertThrows[SQLFeatureNotSupportedException] {
          ksqlConnection.createStatement(-1, -1)
        }
        ksqlConnection.setAutoCommit(true)
        ksqlConnection.setAutoCommit(false)
        ksqlConnection.getAutoCommit should be(false)
        ksqlConnection.getSchema should be(None.orNull)
        ksqlConnection.getWarnings should be(None.orNull)
        ksqlConnection.getCatalog should be(None.orNull)
        ksqlConnection.setCatalog("test")
        ksqlConnection.getCatalog should be(None.orNull)

        (mockKsqlRestClient.close _).expects
        ksqlConnection.close()
        ksqlConnection.isClosed should be(true)
        ksqlConnection.commit()
      }
    }
  }

  "A ConnectionNotSupported" when {

    "validating specs" should {

      "throw not supported exception if not supported" in {

        val resultSet = new ConnectionNotSupported
        reflectMethods[ConnectionNotSupported](methods = Seq.empty, implemented = false, obj = resultSet)
          .foreach(method => {
            assertThrows[SQLFeatureNotSupportedException] {
              method()
            }
          })
      }
    }
  }

} 
Example 66
Source File: SourcepathCommandIntegrationSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.tool.commands

import java.nio.file.Paths

import org.scaladebugger.test.helpers.FixedParallelSuite
import org.scaladebugger.tool.Repl
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.Eventually
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import test.{ToolConstants, ToolTestUtilities, ToolFixtures}

class SourcepathCommandIntegrationSpec extends FunSpec with Matchers
  with ParallelTestExecution with ToolFixtures with MockFactory
  with ToolTestUtilities with Eventually with FixedParallelSuite
{
  implicit override val patienceConfig = PatienceConfig(
    timeout = scaled(ToolConstants.EventuallyTimeout),
    interval = scaled(ToolConstants.EventuallyInterval)
  )

  describe("SourcepathCommand") {
    it("should add the provided path to the current list and load sources") {
      val vt = newVirtualTerminal()
      val repl = Repl.newInstance(newTerminal = (_,_) => vt)
      repl.start()

      val q = "\""
      val s = java.io.File.separator

      // Set some paths to be displayed
      repl.stateManager.updateSourcePaths(Seq(
        Paths.get("a"),
        Paths.get("b"),
        Paths.get("c")
      ))

      // Add '.' as sourcepath
      vt.newInputLine("sourcepath \".\"")

      // Verify that we have finished loading our source files
      eventually {
        validateNextLine(vt, """Loaded \d+ source files""",
          success = (text, line) => line should startWith regex text)
      }

      eventually {
        val state = repl.stateManager.state
        state.sourcePaths.last.getFileName.toString should contain ('.')
      }
    }

    it("should list all current source paths if no argument provided") {
      val vt = newVirtualTerminal()
      val repl = Repl.newInstance(newTerminal = (_,_) => vt)
      repl.start()

      // Set some paths to be displayed
      repl.stateManager.updateSourcePaths(Seq(
        Paths.get("a"),
        Paths.get("b"),
        Paths.get("c")
      ))

      // Display the source paths
      vt.newInputLine("sourcepath")

      val line = vt.nextOutputLine(
        waitTime = ToolConstants.NextOutputLineTimeout.millisPart
      )
      val s = java.io.File.pathSeparator
      line.get should be (s"Source paths: a${s}b${s}c\n")
    }
  }
} 
Example 67
Source File: GrabInfoDSLWrapperSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.dsl.info

import com.sun.jdi.ThreadReference
import org.scaladebugger.api.profiles.traits.info.{GrabInfoProfile, ThreadInfo}
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

import scala.util.Success

class GrabInfoDSLWrapperSpec extends ParallelMockFunSpec
{
  private val mockGrabInfoProfile = mock[GrabInfoProfile]

  describe("GrabInfoDSLWrapper") {
    describe("#forThread(ThreadReference)") {
      it("should invoke the underlying profile method") {
        import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL

        val threadReference = mock[ThreadReference]
        val returnValue = Success(mock[ThreadInfo])

        (mockGrabInfoProfile.tryThread(_: ThreadReference))
          .expects(threadReference)
          .returning(returnValue).once()

        mockGrabInfoProfile.forThread(threadReference) should be (returnValue)
      }
    }

    describe("#forUnsafeThread(ThreadReference)") {
      it("should invoke the underlying profile method") {
        import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL

        val threadReference = mock[ThreadReference]
        val returnValue = mock[ThreadInfo]

        (mockGrabInfoProfile.thread(_: ThreadReference))
          .expects(threadReference)
          .returning(returnValue).once()

        mockGrabInfoProfile.forUnsafeThread(threadReference) should be (returnValue)
      }
    }

    describe("#forThread(Long)") {
      it("should invoke the underlying profile method") {
        import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL

        val threadId = 999L
        val returnValue = Success(mock[ThreadInfo])

        (mockGrabInfoProfile.tryThread(_: Long))
          .expects(threadId)
          .returning(returnValue).once()

        mockGrabInfoProfile.forThread(threadId) should be (returnValue)
      }
    }

    describe("#forUnsafeThread(Long)") {
      it("should invoke the underlying profile method") {
        import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL

        val threadId = 999L
        val returnValue = mock[ThreadInfo]

        (mockGrabInfoProfile.thread(_: Long))
          .expects(threadId)
          .returning(returnValue).once()

        mockGrabInfoProfile.forUnsafeThread(threadId) should be (returnValue)
      }
    }
  }
} 
Example 68
Source File: ScalaVirtualMachineSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.virtualmachines

import com.sun.jdi.VirtualMachine
import org.scaladebugger.api.profiles.traits.DebugProfile
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.ManagerContainer
import org.scaladebugger.api.profiles.ProfileManager
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class ScalaVirtualMachineSpec extends ParallelMockFunSpec
{
  private class TestManagerContainer extends ManagerContainer(
    null, null, null, null, null, null, null, null, null, null, null, null,
    null, null, null, null, null, null, null
  )

  private def newScalaVirtualMachine(
    scalaVirtualMachineManager: ScalaVirtualMachineManager,
    managerContainer: ManagerContainer,
    _profileManager: ProfileManager
  ) =
    new Object with ScalaVirtualMachine {
      override val cache: ObjectCache = null
      override val lowlevel: ManagerContainer = managerContainer
      override val manager: ScalaVirtualMachineManager = scalaVirtualMachineManager
      override def startProcessingEvents(): Unit = {}
      override def isInitialized: Boolean = false
      override def isProcessingEvents: Boolean = false
      override def suspend(): Unit = {}
      override def stopProcessingEvents(): Unit = {}
      override def resume(): Unit = {}
      override def initialize(
        defaultProfile: String,
        startProcessingEvents: Boolean
      ): Unit = {}
      override val underlyingVirtualMachine: VirtualMachine = null
      override def isStarted: Boolean = false
      override val uniqueId: String = ""
      override protected val profileManager: ProfileManager = _profileManager
      override def register(name: String, profile: DebugProfile): Option[DebugProfile] = None
      override def retrieve(name: String): Option[DebugProfile] = None
      override def unregister(name: String): Option[DebugProfile] = None
    }

  private val mockManagerContainerProcessPendingRequests =
    mockFunction[ManagerContainer, Unit]
  private val mockProfileManager = mock[ProfileManager]
  private val scalaVirtualMachine = newScalaVirtualMachine(
    ScalaVirtualMachineManager.GlobalInstance,
    new TestManagerContainer {
      override def processPendingRequests(
        managerContainer: ManagerContainer
      ): Unit = mockManagerContainerProcessPendingRequests(managerContainer)
    },
    mockProfileManager
  )

  describe("ScalaVirtualMachine") {
    describe("#processPendingRequests") {
      it("should process the other VM's pending requests using its low-level managers") {
        val otherManagerContainer = new TestManagerContainer
        val otherScalaVirtualMachine = newScalaVirtualMachine(
          null, otherManagerContainer, null
        )

        mockManagerContainerProcessPendingRequests.expects(otherManagerContainer).once()

        scalaVirtualMachine.processPendingRequests(otherScalaVirtualMachine)
      }
    }
  }
} 
Example 69
Source File: DummyVMDeathManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.vm

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyVMDeathManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val vmDeathManager = new DummyVMDeathManager

  describe("DummyVMDeathManager") {
    describe("#vmDeathRequestList") {
      it("should return an empty list") {
        vmDeathManager.vmDeathRequestList should be (empty)
      }
    }

    describe("#createVMDeathRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = vmDeathManager.createVMDeathRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasVMDeathRequest") {
      it("should return false") {
        val expected = false

        val actual = vmDeathManager.hasVMDeathRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getVMDeathRequest") {
      it("should return None") {
        val expected = None

        val actual = vmDeathManager.getVMDeathRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getVMDeathRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = vmDeathManager.getVMDeathRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeVMDeathRequest") {
      it("should return false") {
        val expected = false

        val actual = vmDeathManager.removeVMDeathRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 70
Source File: VMDeathManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.vm

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestVMDeathManager

import scala.util.Success

class VMDeathManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockVMDeathManager = mock[VMDeathManager]
  private val testVMDeathManager = new TestVMDeathManager(
    mockVMDeathManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("VMDeathManager") {
    describe("#createVMDeathRequest") {
      it("should invoke createVMDeathRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockVMDeathManager.createVMDeathRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testVMDeathManager.createVMDeathRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createVMDeathRequestFromInfo") {
      it("should invoke createVMDeathRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockVMDeathManager.createVMDeathRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = VMDeathRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testVMDeathManager.createVMDeathRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 71
Source File: AccessWatchpointManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.watchpoints

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestAccessWatchpointManager

import scala.util.Success

class AccessWatchpointManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockAccessWatchpointManager = mock[AccessWatchpointManager]
  private val testAccessWatchpointManager = new TestAccessWatchpointManager(
    mockAccessWatchpointManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("AccessWatchpointManager") {
    describe("#createAccessWatchpointRequest") {
      it("should invoke createAccessWatchpointRequestWithId") {
        val expected = Success(TestRequestId)
        val testClassName = "some.class.name"
        val testFieldName = "someFieldName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockAccessWatchpointManager.createAccessWatchpointRequestWithId _)
          .expects(TestRequestId, testClassName, testFieldName, testExtraArguments)
          .returning(expected).once()

        val actual = testAccessWatchpointManager.createAccessWatchpointRequest(
          testClassName,
          testFieldName,
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createAccessWatchpointRequestFromInfo") {
      it("should invoke createAccessWatchpointRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testClassName = "some.class.name"
        val testFieldName = "someFieldName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockAccessWatchpointManager.createAccessWatchpointRequestWithId _)
          .expects(TestRequestId, testClassName, testFieldName, testExtraArguments)
          .returning(expected).once()

        val info = AccessWatchpointRequestInfo(
          TestRequestId,
          testIsPending,
          testClassName,
          testFieldName,
          testExtraArguments
        )
        val actual = testAccessWatchpointManager.createAccessWatchpointRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 72
Source File: ModificationWatchpointManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.watchpoints

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestModificationWatchpointManager

import scala.util.Success

class ModificationWatchpointManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockModificationWatchpointManager = mock[ModificationWatchpointManager]
  private val testModificationWatchpointManager = new TestModificationWatchpointManager(
    mockModificationWatchpointManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("ModificationWatchpointManager") {
    describe("#createModificationWatchpointRequest") {
      it("should invoke createModificationWatchpointRequestWithId") {
        val expected = Success(TestRequestId)
        val testClassName = "some.class.name"
        val testFieldName = "someFieldName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockModificationWatchpointManager.createModificationWatchpointRequestWithId _)
          .expects(TestRequestId, testClassName, testFieldName, testExtraArguments)
          .returning(expected).once()

        val actual = testModificationWatchpointManager.createModificationWatchpointRequest(
          testClassName,
          testFieldName,
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createModificationWatchpointRequestFromInfo") {
      it("should invoke createModificationWatchpointRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testClassName = "some.class.name"
        val testFieldName = "someFieldName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockModificationWatchpointManager.createModificationWatchpointRequestWithId _)
          .expects(TestRequestId, testClassName, testFieldName, testExtraArguments)
          .returning(expected).once()

        val info = ModificationWatchpointRequestInfo(
          TestRequestId,
          testIsPending,
          testClassName,
          testFieldName,
          testExtraArguments
        )
        val actual = testModificationWatchpointManager.createModificationWatchpointRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 73
Source File: MethodEntryManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.methods

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestMethodEntryManager

import scala.util.Success

class MethodEntryManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockMethodEntryManager = mock[MethodEntryManager]
  private val testMethodEntryManager = new TestMethodEntryManager(
    mockMethodEntryManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("MethodEntryManager") {
    describe("#createMethodEntryRequest") {
      it("should invoke createMethodEntryRequestWithId") {
        val expected = Success(TestRequestId)
        val testClassName = "some.class.name"
        val testMethodName = "someMethodName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMethodEntryManager.createMethodEntryRequestWithId _)
          .expects(TestRequestId, testClassName, testMethodName, testExtraArguments)
          .returning(expected).once()

        val actual = testMethodEntryManager.createMethodEntryRequest(
          testClassName,
          testMethodName,
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createMethodEntryRequestFromInfo") {
      it("should invoke createMethodEntryRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testClassName = "some.class.name"
        val testMethodName = "someMethodName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMethodEntryManager.createMethodEntryRequestWithId _)
          .expects(TestRequestId, testClassName, testMethodName, testExtraArguments)
          .returning(expected).once()

        val info = MethodEntryRequestInfo(
          TestRequestId,
          testIsPending,
          testClassName,
          testMethodName,
          testExtraArguments
        )
        val actual = testMethodEntryManager.createMethodEntryRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 74
Source File: MethodExitManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.methods

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestMethodExitManager

import scala.util.Success

class MethodExitManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockMethodExitManager = mock[MethodExitManager]
  private val testMethodExitManager = new TestMethodExitManager(
    mockMethodExitManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("MethodExitManager") {
    describe("#createMethodExitRequest") {
      it("should invoke createMethodExitRequestWithId") {
        val expected = Success(TestRequestId)
        val testClassName = "some.class.name"
        val testMethodName = "someMethodName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMethodExitManager.createMethodExitRequestWithId _)
          .expects(TestRequestId, testClassName, testMethodName, testExtraArguments)
          .returning(expected).once()

        val actual = testMethodExitManager.createMethodExitRequest(
          testClassName,
          testMethodName,
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createMethodExitRequestFromInfo") {
      it("should invoke createMethodExitRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testClassName = "some.class.name"
        val testMethodName = "someMethodName"
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMethodExitManager.createMethodExitRequestWithId _)
          .expects(TestRequestId, testClassName, testMethodName, testExtraArguments)
          .returning(expected).once()

        val info = MethodExitRequestInfo(
          TestRequestId,
          testIsPending,
          testClassName,
          testMethodName,
          testExtraArguments
        )
        val actual = testMethodExitManager.createMethodExitRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 75
Source File: JDIArgumentGroupSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.utils

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.JDIArgument
import org.scaladebugger.api.lowlevel.events.JDIEventArgument
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class JDIArgumentGroupSpec extends ParallelMockFunSpec
{
  describe("JDIArgumentGroup") {
    describe("#apply") {
      it("should place any request args in the request field of the group") {
        val expected = Seq(mock[JDIRequestArgument], mock[JDIRequestArgument])

        val JDIArgumentGroup(rArgs, _, _) = JDIArgumentGroup(expected: _*)

        val actual = rArgs

        actual should contain theSameElementsAs (expected)
      }

      it("should place any event args in the event field of the group") {
        val expected = Seq(mock[JDIEventArgument], mock[JDIEventArgument])

        val JDIArgumentGroup(_, eArgs, _) = JDIArgumentGroup(expected: _*)

        val actual = eArgs

        actual should contain theSameElementsAs (expected)
      }

      it("should place any other args in the other field of the group") {
        val expected = Seq(mock[JDIArgument], mock[JDIArgument])

        val JDIArgumentGroup(_, _, oArgs) = JDIArgumentGroup(expected: _*)

        val actual = oArgs

        actual should contain theSameElementsAs (expected)
      }

      it("should support grouping all types of arguments when mixed together") {
        val expectedRequestArgs = Seq(
          mock[JDIRequestArgument],
          mock[JDIRequestArgument]
        )
        val expectedEventArgs = Seq(
          mock[JDIEventArgument],
          mock[JDIEventArgument]
        )
        val expectedOtherArgs = Seq(
          mock[JDIArgument],
          mock[JDIArgument]
        )

        val JDIArgumentGroup(rArgs, eArgs, oArgs) = JDIArgumentGroup(
          expectedOtherArgs ++ expectedRequestArgs ++ expectedEventArgs: _*
        )

        rArgs should contain theSameElementsAs (expectedRequestArgs)
        eArgs should contain theSameElementsAs (expectedEventArgs)
        oArgs should contain theSameElementsAs (expectedOtherArgs)
      }
    }
  }
} 
Example 76
Source File: BreakpointManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.breakpoints

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestBreakpointManager

import scala.util.Success

class BreakpointManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockBreakpointManager = mock[BreakpointManager]
  private val testBreakpointManager = new TestBreakpointManager(
    mockBreakpointManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("BreakpointManager") {
    describe("#createBreakpointRequest") {
      it("should invoke createBreakpointRequestWithId") {
        val expected = Success(TestRequestId)
        val testFileName = "some/file/name"
        val testLineNumber = 999
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockBreakpointManager.createBreakpointRequestWithId _)
          .expects(TestRequestId, testFileName, testLineNumber, testExtraArguments)
          .returning(expected).once()

        val actual = testBreakpointManager.createBreakpointRequest(
          testFileName,
          testLineNumber,
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createBreakpointRequestFromInfo") {
      it("should invoke createBreakpointRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testFileName = "some/file/name"
        val testLineNumber = 999
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockBreakpointManager.createBreakpointRequestWithId _)
          .expects(TestRequestId, testFileName, testLineNumber, testExtraArguments)
          .returning(expected).once()

        val info = BreakpointRequestInfo(
          TestRequestId,
          testIsPending,
          testFileName,
          testLineNumber,
          testExtraArguments
        )
        val actual = testBreakpointManager.createBreakpointRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 77
Source File: MonitorContendedEnteredManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestMonitorContendedEnteredManager

import scala.util.Success

class MonitorContendedEnteredManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockMonitorContendedEnteredManager = mock[MonitorContendedEnteredManager]
  private val testMonitorContendedEnteredManager = new TestMonitorContendedEnteredManager(
    mockMonitorContendedEnteredManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("MonitorContendedEnteredManager") {
    describe("#createMonitorContendedEnteredRequest") {
      it("should invoke createMonitorContendedEnteredRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorContendedEnteredManager.createMonitorContendedEnteredRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testMonitorContendedEnteredManager.createMonitorContendedEnteredRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createMonitorContendedEnteredRequestFromInfo") {
      it("should invoke createMonitorContendedEnteredRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorContendedEnteredManager.createMonitorContendedEnteredRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = MonitorContendedEnteredRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testMonitorContendedEnteredManager.createMonitorContendedEnteredRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 78
Source File: DummyMonitorWaitManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyMonitorWaitManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val monitorWaitManager = new DummyMonitorWaitManager

  describe("DummyMonitorWaitManager") {
    describe("#monitorWaitRequestList") {
      it("should return an empty list") {
        monitorWaitManager.monitorWaitRequestList should be (empty)
      }
    }

    describe("#createMonitorWaitRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = monitorWaitManager.createMonitorWaitRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasMonitorWaitRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorWaitManager.hasMonitorWaitRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorWaitRequest") {
      it("should return None") {
        val expected = None

        val actual = monitorWaitManager.getMonitorWaitRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorWaitRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = monitorWaitManager.getMonitorWaitRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeMonitorWaitRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorWaitManager.removeMonitorWaitRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 79
Source File: MonitorWaitedManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestMonitorWaitedManager

import scala.util.Success

class MonitorWaitedManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockMonitorWaitedManager = mock[MonitorWaitedManager]
  private val testMonitorWaitedManager = new TestMonitorWaitedManager(
    mockMonitorWaitedManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("MonitorWaitedManager") {
    describe("#createMonitorWaitedRequest") {
      it("should invoke createMonitorWaitedRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorWaitedManager.createMonitorWaitedRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testMonitorWaitedManager.createMonitorWaitedRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createMonitorWaitedRequestFromInfo") {
      it("should invoke createMonitorWaitedRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorWaitedManager.createMonitorWaitedRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = MonitorWaitedRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testMonitorWaitedManager.createMonitorWaitedRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 80
Source File: MonitorWaitManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestMonitorWaitManager

import scala.util.Success

class MonitorWaitManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockMonitorWaitManager = mock[MonitorWaitManager]
  private val testMonitorWaitManager = new TestMonitorWaitManager(
    mockMonitorWaitManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("MonitorWaitManager") {
    describe("#createMonitorWaitRequest") {
      it("should invoke createMonitorWaitRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorWaitManager.createMonitorWaitRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testMonitorWaitManager.createMonitorWaitRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createMonitorWaitRequestFromInfo") {
      it("should invoke createMonitorWaitRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorWaitManager.createMonitorWaitRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = MonitorWaitRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testMonitorWaitManager.createMonitorWaitRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 81
Source File: DummyMonitorWaitedManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyMonitorWaitedManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val monitorWaitedManager = new DummyMonitorWaitedManager

  describe("DummyMonitorWaitedManager") {
    describe("#monitorWaitedRequestList") {
      it("should return an empty list") {
        monitorWaitedManager.monitorWaitedRequestList should be (empty)
      }
    }

    describe("#createMonitorWaitedRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = monitorWaitedManager.createMonitorWaitedRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasMonitorWaitedRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorWaitedManager.hasMonitorWaitedRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorWaitedRequest") {
      it("should return None") {
        val expected = None

        val actual = monitorWaitedManager.getMonitorWaitedRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorWaitedRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = monitorWaitedManager.getMonitorWaitedRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeMonitorWaitedRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorWaitedManager.removeMonitorWaitedRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 82
Source File: DummyMonitorContendedEnterManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyMonitorContendedEnterManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val monitorContendedEnterManager = new DummyMonitorContendedEnterManager

  describe("DummyMonitorContendedEnterManager") {
    describe("#monitorContendedEnterRequestList") {
      it("should return an empty list") {
        monitorContendedEnterManager.monitorContendedEnterRequestList should be (empty)
      }
    }

    describe("#createMonitorContendedEnterRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = monitorContendedEnterManager.createMonitorContendedEnterRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasMonitorContendedEnterRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorContendedEnterManager.hasMonitorContendedEnterRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorContendedEnterRequest") {
      it("should return None") {
        val expected = None

        val actual = monitorContendedEnterManager.getMonitorContendedEnterRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorContendedEnterRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = monitorContendedEnterManager.getMonitorContendedEnterRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeMonitorContendedEnterRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorContendedEnterManager.removeMonitorContendedEnterRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 83
Source File: MonitorContendedEnterManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestMonitorContendedEnterManager

import scala.util.Success

class MonitorContendedEnterManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockMonitorContendedEnterManager = mock[MonitorContendedEnterManager]
  private val testMonitorContendedEnterManager = new TestMonitorContendedEnterManager(
    mockMonitorContendedEnterManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("MonitorContendedEnterManager") {
    describe("#createMonitorContendedEnterRequest") {
      it("should invoke createMonitorContendedEnterRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorContendedEnterManager.createMonitorContendedEnterRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testMonitorContendedEnterManager.createMonitorContendedEnterRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createMonitorContendedEnterRequestFromInfo") {
      it("should invoke createMonitorContendedEnterRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockMonitorContendedEnterManager.createMonitorContendedEnterRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = MonitorContendedEnterRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testMonitorContendedEnterManager.createMonitorContendedEnterRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 84
Source File: DummyMonitorContendedEnteredManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.monitors

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyMonitorContendedEnteredManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val monitorContendedEnteredManager = new DummyMonitorContendedEnteredManager

  describe("DummyMonitorContendedEnteredManager") {
    describe("#monitorContendedEnteredRequestList") {
      it("should return an empty list") {
        monitorContendedEnteredManager.monitorContendedEnteredRequestList should be (empty)
      }
    }

    describe("#createMonitorContendedEnteredRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = monitorContendedEnteredManager.createMonitorContendedEnteredRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasMonitorContendedEnteredRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorContendedEnteredManager.hasMonitorContendedEnteredRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorContendedEnteredRequest") {
      it("should return None") {
        val expected = None

        val actual = monitorContendedEnteredManager.getMonitorContendedEnteredRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getMonitorContendedEnteredRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = monitorContendedEnteredManager.getMonitorContendedEnteredRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeMonitorContendedEnteredRequest") {
      it("should return false") {
        val expected = false

        val actual = monitorContendedEnteredManager.removeMonitorContendedEnteredRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 85
Source File: DummyEventManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.EventManager.EventHandler
import org.scaladebugger.api.lowlevel.events.EventType.EventType
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyEventManagerSpec extends ParallelMockFunSpec
{
  private val TestHandlerId = java.util.UUID.randomUUID().toString
  private val eventManager = new DummyEventManager

  describe("DummyEventManager") {
    describe("#addEventHandlerWithId") {
      it("should return the provided id") {
        val expected = TestHandlerId

        val actual = eventManager.addEventHandlerWithId(
          expected,
          mock[EventType],
          mock[EventHandler]
        )

        actual should be (expected)
      }
    }

    describe("#getHandlersForEventType") {
      it("should return an empty list") {
        val expected = Nil

        val actual = eventManager.getHandlersForEventType(mock[EventType])

        actual should be (expected)
      }
    }

    describe("#getHandlerIdsForEventType") {
      it("should return an empty list") {
        val expected = Nil

        val actual = eventManager.getHandlerIdsForEventType(mock[EventType])

        actual should be (expected)
      }
    }

    describe("#getEventHandler") {
      it("should return None") {
        val expected = None

        val actual = eventManager.getEventHandler(TestHandlerId)

        actual should be (expected)
      }
    }

    describe("#getAllEventHandlerInfo") {
      it("should return an empty list") {
        val expected = Nil

        val actual = eventManager.getAllEventHandlerInfo

        actual should be (expected)
      }
    }

    describe("#removeEventHandler") {
      it("should return None") {
        val expected = None

        val actual = eventManager.removeEventHandler(TestHandlerId)

        actual should be (expected)
      }
    }

    describe("#start") {
      it("should do nothing") {
        eventManager.start()
      }
    }

    describe("#stop") {
      it("should do nothing") {
        eventManager.stop()
      }
    }
  }
} 
Example 86
Source File: CustomPropertyDataRequestProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.data.processors

import com.sun.jdi.event.Event
import com.sun.jdi.request.EventRequest
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.data.requests.CustomPropertyDataRequest
import org.scaladebugger.api.lowlevel.events.data.results.CustomPropertyDataResult
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class CustomPropertyDataRequestProcessorSpec extends ParallelMockFunSpec
{
  private val testKey = "some key"
  private val testValue = "some value"
  private val customPropertyDataRequest =
    CustomPropertyDataRequest(key = testKey)
  private val customPropertyDataProcessor =
    new CustomPropertyDataRequestProcessor(customPropertyDataRequest)

  describe("CustomPropertyDataRequestProcessor") {
    describe("#process") {
      it ("should return a result object if the property is found") {
        val expected = CustomPropertyDataResult(
          key = testKey,
          value = testValue
        )

        val mockRequest = mock[EventRequest]
        val mockEvent = mock[Event]

        // Retrieval of the property should return our test value, meaning that
        // there is a property
        (mockEvent.request _).expects().returning(mockRequest).once()
        (mockRequest.getProperty _).expects(testKey).returning(testValue).once()

        val actual = customPropertyDataProcessor.process(mockEvent)
        actual should contain only (expected)
      }

      it("should return an empty collection if the property is not found") {
        val expected = CustomPropertyDataResult(
          key = testKey,
          value = testValue
        )

        val mockRequest = mock[EventRequest]
        val mockEvent = mock[Event]

        // Retrieval of the property should return null, meaning there is no
        // valid property
        (mockEvent.request _).expects().returning(mockRequest).once()
        (mockRequest.getProperty _).expects(testKey).returning(null).once()

        val actual = customPropertyDataProcessor.process(mockEvent)
        actual should be (empty)
      }
    }
  }
} 
Example 87
Source File: CustomPropertyDataRequestSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.data.requests

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class CustomPropertyDataRequestSpec extends ParallelMockFunSpec
{
  private val testKey = "some key"
  private val customPropertyDataRequest =
    CustomPropertyDataRequest(key = testKey)

  describe("CustomPropertyDataRequest") {
    describe("#toProcessor") {
      it("should return a processor containing the custom property data request") {
        customPropertyDataRequest.toProcessor.argument should
          be (customPropertyDataRequest)
      }
    }
  }
} 
Example 88
Source File: YesResumeSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.misc

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class YesResumeSpec extends ParallelMockFunSpec
{
  describe("YesResume") {
    describe("#value") {
      it("should return true") {
        val expected = true
        val actual = YesResume.value
        actual should be (expected)
      }
    }

    describe("#toProcessor") {
      it("should return a processor containing YesResume") {
        YesResume.toProcessor.argument should be (YesResume)
      }
    }
  }
} 
Example 89
Source File: NoResumeSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.misc

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class NoResumeSpec extends ParallelMockFunSpec
{
  describe("NoResume") {
    describe("#value") {
      it("should return false") {
        val expected = false
        val actual = NoResume.value
        actual should be (expected)
      }
    }

    describe("#toProcessor") {
      it("should return a processor containing NoResume") {
        NoResume.toProcessor.argument should be (NoResume)
      }
    }
  }
} 
Example 90
Source File: ResumeProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.misc.processors

import com.sun.jdi.event.Event
import org.scaladebugger.api.lowlevel.events.misc.{NoResume, YesResume}
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class ResumeProcessorSpec extends ParallelMockFunSpec
{
  describe("ResumeProcessor") {
    describe("#process") {
      it("should return false if created from NoResume") {
        val expected = false
        val actual = NoResume.toProcessor.process(mock[Event])
        actual should be (expected)
      }

      it("should return true if created from YesResume") {
        val expected = true
        val actual = YesResume.toProcessor.process(mock[Event])
        actual should be (expected)
      }
    }
  }
} 
Example 91
Source File: AndFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class AndFilterSpec extends ParallelMockFunSpec
{
  private val andFilter = AndFilter()

  describe("AndFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the and filter") {
        andFilter.toProcessor.argument should be (andFilter)
      }
    }
  }
} 
Example 92
Source File: MinTriggerFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class MinTriggerFilterSpec extends ParallelMockFunSpec
{
  private val testCount = 3
  private val minTriggerFilter = MinTriggerFilter(count = testCount)

  describe("MinTriggerFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the min trigger filter") {
        minTriggerFilter.toProcessor.argument should be (minTriggerFilter)
      }
    }
  }
} 
Example 93
Source File: NotFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class NotFilterSpec extends ParallelMockFunSpec
{
  private val notFilter = NotFilter(mock[JDIEventFilter])

  describe("NotFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the or filter") {
        notFilter.toProcessor.argument should be (notFilter)
      }
    }
  }
} 
Example 94
Source File: AndFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters.processors

import com.sun.jdi.event.Event
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.filters.{AndFilter, JDIEventFilter, JDIEventFilterProcessor}
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class AndFilterProcessorSpec extends ParallelMockFunSpec
{
  describe("AndFilterProcessor") {
    describe("#process") {
      it ("should return false if any internal filter returns false") {
        val expected = false

        val andProcessor = new AndFilterProcessor(AndFilter(
          newMockFilter(result = true),
          newMockFilter(result = false)
        ))

        val actual = andProcessor.process(mock[Event])

        actual should be (expected)
      }

      it("should return true if all internal filters return true") {
        val expected = true

        val andProcessor = new AndFilterProcessor(AndFilter(
          newMockFilter(result = true),
          newMockFilter(result = true)
        ))

        val actual = andProcessor.process(mock[Event])

        actual should be (expected)
      }

      it("should return true if there are no internal filters") {
        val expected = true

        val andProcessor = new AndFilterProcessor(AndFilter())

        val actual = andProcessor.process(mock[Event])

        actual should be (expected)
      }
    }
  }

  private def newMockFilter(result: Boolean): JDIEventFilter = {
    val mockFilter = mock[JDIEventFilter]
    val mockProcessor = mock[JDIEventFilterProcessor]

    (mockFilter.toProcessor _).expects().returning(mockProcessor).once()
    (mockProcessor.process _).expects(*).returning(result).once()

    mockFilter
  }
} 
Example 95
Source File: NotFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters.processors

import com.sun.jdi.event.Event
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.filters.{JDIEventFilter, JDIEventFilterProcessor, NotFilter}
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class NotFilterProcessorSpec extends ParallelMockFunSpec
{
  describe("NotFilterProcessor") {
    describe("#process") {
      it ("should return false if any internal filter returns false") {
        val expected = false

        val notProcessor = new NotFilterProcessor(NotFilter(
          newMockFilter(result = true)
        ))

        val actual = notProcessor.process(mock[Event])

        actual should be (expected)
      }

      it("should return true if the internal filter returns false") {
        val expected = true

        val notProcessor = new NotFilterProcessor(NotFilter(
          newMockFilter(result = false)
        ))

        val actual = notProcessor.process(mock[Event])

        actual should be (expected)
      }
    }
  }

  private def newMockFilter(result: Boolean): JDIEventFilter = {
    val mockFilter = mock[JDIEventFilter]
    val mockProcessor = mock[JDIEventFilterProcessor]

    (mockFilter.toProcessor _).expects().returning(mockProcessor).once()
    (mockProcessor.process _).expects(*).returning(result).once()

    mockFilter
  }
} 
Example 96
Source File: MinTriggerFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters.processors

import com.sun.jdi.event.Event
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.filters.MinTriggerFilter
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class MinTriggerFilterProcessorSpec extends ParallelMockFunSpec
{
  private val testCount = 3
  private val minTriggerFilter = MinTriggerFilter(count = testCount)
  private val minTriggerProcessor =
    new MinTriggerFilterProcessor(minTriggerFilter)

  describe("MinTriggerFilterProcessor") {
    describe("#process") {
      it ("should return false if the total already processed has not reached the min count") {
        // Verify that the processor is false for the first N processes
        for (i <- 1 to testCount) {
          minTriggerProcessor.process(mock[Event]) should be (false)
        }
      }

      it("should return true if the total already processed has reached the min count") {
        for (i <- 1 to testCount) {
          minTriggerProcessor.process(mock[Event])
        }

        // Verify that the processor is true after the first N processes
        minTriggerProcessor.process(mock[Event]) should be (true)
      }
    }

    describe("#reset") {
      it("should reset the internal counter to zero") {
        for (i <- 1 to testCount) {
          minTriggerProcessor.process(mock[Event])
        }

        minTriggerProcessor.reset()

        // Verify that the processor is false even after the first N processes
        minTriggerProcessor.process(mock[Event]) should be (false)
      }
    }
  }
} 
Example 97
Source File: MaxTriggerFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters.processors

import com.sun.jdi.event.Event
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.filters.MaxTriggerFilter
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class MaxTriggerFilterProcessorSpec extends ParallelMockFunSpec
{
  private val testCount = 3
  private val maxTriggerFilter = MaxTriggerFilter(count = testCount)
  private val maxTriggerProcessor =
    new MaxTriggerFilterProcessor(maxTriggerFilter)

  describe("MaxTriggerFilterProcessor") {
    describe("#process") {
      it ("should return true if the total processed has not exceeded the max count") {
        // Verify that the processor is true for the first N processes
        for (i <- 1 to testCount) {
          maxTriggerProcessor.process(mock[Event]) should be (true)
        }
      }

      it("should return false if the total processed has exceeded the max count") {
        for (i <- 1 to testCount) {
          maxTriggerProcessor.process(mock[Event])
        }

        // Verify that the processor is false after the first N processes
        maxTriggerProcessor.process(mock[Event]) should be (false)
      }
    }

    describe("#reset") {
      it("should reset the internal counter to zero") {
        for (i <- 1 to testCount) {
          maxTriggerProcessor.process(mock[Event])
        }

        maxTriggerProcessor.reset()

        // Verify that the processor is true even after the first N processes
        maxTriggerProcessor.process(mock[Event]) should be (true)
      }
    }
  }
} 
Example 98
Source File: OrFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters.processors

import com.sun.jdi.event.Event
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.filters.{JDIEventFilter, JDIEventFilterProcessor, OrFilter}
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class OrFilterProcessorSpec extends ParallelMockFunSpec
{
  describe("OrFilterProcessor") {
    describe("#process") {
      it ("should return false if all internal filters return false") {
        val expected = false

        val orProcessor = new OrFilterProcessor(OrFilter(
          newMockFilter(result = false),
          newMockFilter(result = false)
        ))

        val actual = orProcessor.process(mock[Event])

        actual should be (expected)
      }

      it("should return true if any internal filter returns true") {
        val expected = true

        val orProcessor = new OrFilterProcessor(OrFilter(
          newMockFilter(result = true),
          newMockFilter(result = false)
        ))

        val actual = orProcessor.process(mock[Event])

        actual should be (expected)
      }

      it("should return true if there are no internal filters") {
        val expected = true

        val orProcessor = new OrFilterProcessor(OrFilter())

        val actual = orProcessor.process(mock[Event])

        actual should be (expected)
      }
    }
  }

  private def newMockFilter(result: Boolean): JDIEventFilter = {
    val mockFilter = mock[JDIEventFilter]
    val mockProcessor = mock[JDIEventFilterProcessor]

    (mockFilter.toProcessor _).expects().returning(mockProcessor).once()
    (mockProcessor.process _).expects(*).returning(result).once()

    mockFilter
  }
} 
Example 99
Source File: CustomPropertyFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters.processors

import com.sun.jdi.event.Event
import com.sun.jdi.request.EventRequest
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.filters.CustomPropertyFilter
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class CustomPropertyFilterProcessorSpec extends ParallelMockFunSpec
{
  private val testKey = "some key"
  private val testValue = "some value"
  private val customPropertyFilter = CustomPropertyFilter(
    key = testKey,
    value = testValue
  )
  private val customPropertyProcessor =
    new CustomPropertyFilterProcessor(customPropertyFilter)

  describe("CustomPropertyFilterProcessor") {
    describe("#process") {
      it("should return false if the property is not found") {
        val expected = false

        val mockEvent = mock[Event]
        val mockRequest = mock[EventRequest]

        // Request's property is null if not found
        inSequence {
          (mockEvent.request _).expects().returning(mockRequest).once()
          (mockRequest.getProperty _).expects(testKey).returning(null).once()
        }

        val actual = customPropertyProcessor.process(mockEvent)
        actual should be (expected)
      }

      it ("should return false if the property does not match") {
        val expected = false

        val mockEvent = mock[Event]
        val mockRequest = mock[EventRequest]

        // Request's property is different
        inSequence {
          (mockEvent.request _).expects().returning(mockRequest).once()
          (mockRequest.getProperty _).expects(testKey)
            .returning(testValue+1).once()
        }

        val actual = customPropertyProcessor.process(mockEvent)
        actual should be (expected)
      }

      it("should return true if the property matches") {
        val expected = true

        val mockEvent = mock[Event]
        val mockRequest = mock[EventRequest]

        // Request's property is same
        inSequence {
          (mockEvent.request _).expects().returning(mockRequest).once()
          (mockRequest.getProperty _).expects(testKey)
            .returning(testValue).once()
        }

        val actual = customPropertyProcessor.process(mockEvent)
        actual should be (expected)
      }
    }
  }
} 
Example 100
Source File: MethodNameFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class MethodNameFilterSpec extends ParallelMockFunSpec
{
  private val testName = "some name"
  private val methodNameFilter = MethodNameFilter(name = testName)

  describe("MethodNameFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the method name filter") {
        methodNameFilter.toProcessor.argument should be (methodNameFilter)
      }
    }
  }
} 
Example 101
Source File: UniqueIdPropertyFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.filters.processors.CustomPropertyFilterProcessor
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class UniqueIdPropertyFilterSpec extends ParallelMockFunSpec
{
  private val testId = java.util.UUID.randomUUID().toString
  private val uniqueIdPropertyFilter = UniqueIdPropertyFilter(id = testId)

  describe("UniqueIdPropertyFilter") {
    describe("constructor") {
      it("should set the custom property filter key to \"_id\"") {
        uniqueIdPropertyFilter.key should be ("_id")
      }

      it("should set the custom property filter value to the id") {
        uniqueIdPropertyFilter.value should be (testId)
      }
    }
    describe("#toProcessor") {
      it("should return a custom property filter processor") {
        uniqueIdPropertyFilter.toProcessor shouldBe
          a [CustomPropertyFilterProcessor]
      }

      it("should return a processor containing the unique id property filter") {
        uniqueIdPropertyFilter.toProcessor.argument should
          be (uniqueIdPropertyFilter)
      }
    }
  }
} 
Example 102
Source File: CustomPropertyFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class CustomPropertyFilterSpec extends ParallelMockFunSpec
{
  private val testKey = "some key"
  private val testValue = "some value"
  private val customPropertyFilter = CustomPropertyFilter(
    key = testKey,
    value = testValue
  )

  describe("CustomPropertyFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the custom property filter") {
        customPropertyFilter.toProcessor.argument should
          be (customPropertyFilter)
      }
    }
  }
} 
Example 103
Source File: MaxTriggerFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class MaxTriggerFilterSpec extends ParallelMockFunSpec
{
  private val testCount = 3
  private val maxTriggerFilter = MaxTriggerFilter(count = testCount)

  describe("MaxTriggerFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the max trigger filter") {
        maxTriggerFilter.toProcessor.argument should be (maxTriggerFilter)
      }
    }
  }
} 
Example 104
Source File: WildcardPatternFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class WildcardPatternFilterSpec extends ParallelMockFunSpec
{
  private val testPattern = "some*pattern"
  private val wildcardPatternFilter = WildcardPatternFilter(
    pattern = testPattern
  )

  describe("WildcardPatternFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the wildcard pattern filter") {
        wildcardPatternFilter.toProcessor.argument should be (wildcardPatternFilter)
      }
    }
  }
} 
Example 105
Source File: OrFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.events.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class OrFilterSpec extends ParallelMockFunSpec
{
  private val orFilter = OrFilter()

  describe("OrFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the or filter") {
        orFilter.toProcessor.argument should be (orFilter)
      }
    }
  }
} 
Example 106
Source File: ClassPrepareManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.classes

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestClassPrepareManager

import scala.util.Success

class ClassPrepareManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockClassPrepareManager = mock[ClassPrepareManager]
  private val testClassPrepareManager = new TestClassPrepareManager(
    mockClassPrepareManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("ClassPrepareManager") {
    describe("#createClassPrepareRequest") {
      it("should invoke createClassPrepareRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockClassPrepareManager.createClassPrepareRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testClassPrepareManager.createClassPrepareRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createClassPrepareRequestFromInfo") {
      it("should invoke createClassPrepareRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockClassPrepareManager.createClassPrepareRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = ClassPrepareRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testClassPrepareManager.createClassPrepareRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 107
Source File: DummyClassUnloadManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.classes

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyClassUnloadManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val classUnloadManager = new DummyClassUnloadManager

  describe("DummyClassUnloadManager") {
    describe("#classUnloadRequestList") {
      it("should return an empty list") {
        classUnloadManager.classUnloadRequestList should be (empty)
      }
    }

    describe("#createClassUnloadRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = classUnloadManager.createClassUnloadRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasClassUnloadRequest") {
      it("should return false") {
        val expected = false

        val actual = classUnloadManager.hasClassUnloadRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getClassUnloadRequest") {
      it("should return None") {
        val expected = None

        val actual = classUnloadManager.getClassUnloadRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getClassUnloadRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = classUnloadManager.getClassUnloadRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeClassUnloadRequest") {
      it("should return false") {
        val expected = false

        val actual = classUnloadManager.removeClassUnloadRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 108
Source File: ClassUnloadManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.classes

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestClassUnloadManager

import scala.util.Success

class ClassUnloadManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockClassUnloadManager = mock[ClassUnloadManager]
  private val testClassUnloadManager = new TestClassUnloadManager(
    mockClassUnloadManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("ClassUnloadManager") {
    describe("#createClassUnloadRequest") {
      it("should invoke createClassUnloadRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockClassUnloadManager.createClassUnloadRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testClassUnloadManager.createClassUnloadRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createClassUnloadRequestFromInfo") {
      it("should invoke createClassUnloadRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockClassUnloadManager.createClassUnloadRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = ClassUnloadRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testClassUnloadManager.createClassUnloadRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 109
Source File: DummyClassPrepareManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.classes

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyClassPrepareManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val classPrepareManager = new DummyClassPrepareManager

  describe("DummyClassPrepareManager") {
    describe("#classPrepareRequestList") {
      it("should return an empty list") {
        classPrepareManager.classPrepareRequestList should be (empty)
      }
    }

    describe("#createClassPrepareRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = classPrepareManager.createClassPrepareRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasClassPrepareRequest") {
      it("should return false") {
        val expected = false

        val actual = classPrepareManager.hasClassPrepareRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getClassPrepareRequest") {
      it("should return None") {
        val expected = None

        val actual = classPrepareManager.getClassPrepareRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getClassPrepareRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = classPrepareManager.getClassPrepareRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeClassPrepareRequest") {
      it("should return false") {
        val expected = false

        val actual = classPrepareManager.removeClassPrepareRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 110
Source File: JDIRequestArgumentProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests

import com.sun.jdi.request.EventRequest
import com.sun.jdi.{ObjectReference, ReferenceType, ThreadReference}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.filters._
import org.scaladebugger.api.lowlevel.requests.properties.{CustomProperty, EnabledProperty, SuspendPolicyProperty}
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class JDIRequestArgumentProcessorSpec extends ParallelMockFunSpec
{
  // Create three mock filters to provide to the main filter processor
  private val mockArgumentsAndProcessors = Seq(
    newMockArgumentAndProcessor(),
    newMockArgumentAndProcessor(),
    newMockArgumentAndProcessor()
  )

  private val jdiRequestArgumentProcessor =
    new JDIRequestArgumentProcessor(mockArgumentsAndProcessors .map(_._1): _*)

  describe("JDIRequestArgumentProcessor") {
    describe("#process") {
      it("should execute every provided filter-to-processor on the request") {
        val mockEventRequest = mock[EventRequest]

        // Expect each processor to have its process method invoked once
        val mockProcessors = mockArgumentsAndProcessors.map(_._2)
        mockProcessors.foreach(mockProcessor =>
          (mockProcessor.process _).expects(mockEventRequest)
            .returning(mockEventRequest).once()
        )

        jdiRequestArgumentProcessor.process(mockEventRequest)
      }

      it("should return the updated request instance") {
        // Creating a stub request because we don't care what gets invoked
        // on the request itself
        val stubEventRequest = stub[EventRequest]

        val jdiRequestArgumentProcessor = new JDIRequestArgumentProcessor(
          ClassExclusionFilter(classPattern = ""),
          ClassInclusionFilter(classPattern = ""),
          ClassReferenceFilter(referenceType = mock[ReferenceType]),
          CountFilter(count = 3),
          InstanceFilter(objectReference = mock[ObjectReference]),
          SourceNameFilter(sourceNamePattern = ""),
          ThreadFilter(threadReference = mock[ThreadReference]),
          CustomProperty(key = "key", value = "value"),
          EnabledProperty(value = true),
          SuspendPolicyProperty.AllThreads
        )

        val result = jdiRequestArgumentProcessor.process(stubEventRequest)

        result should be (stubEventRequest)
      }
    }
  }

  
  private def newMockArgumentAndProcessor(): (JDIRequestArgument, JDIRequestProcessor) = {
    val mockArgument = mock[JDIRequestArgument]
    val mockProcessor = mock[JDIRequestProcessor]

    // Allow any number of times for arbitrary usage of function
    (mockArgument.toProcessor _).expects()
      .returning(mockProcessor).anyNumberOfTimes()

    (mockArgument, mockProcessor)
  }
} 
Example 111
Source File: EnabledPropertySpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.properties

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class EnabledPropertySpec extends ParallelMockFunSpec
{
  private val testValue = false
  private val enabledProperty = EnabledProperty(value = testValue)

  describe("EnabledProperty") {
    describe("#toProcessor") {
      it("should return a processor containing the enabled property") {
        enabledProperty.toProcessor.argument should be (enabledProperty)
      }
    }
  }
} 
Example 112
Source File: EnabledPropertyProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.properties.processors

import com.sun.jdi.request._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.properties.EnabledProperty
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class EnabledPropertyProcessorSpec extends ParallelMockFunSpec
{
  private val testValue = false
  private val enabledProperty = EnabledProperty(value = testValue)
  private val enabledProcessor = new EnabledPropertyProcessor(enabledProperty)

  describe("EnabledPropertyProcessor") {
    describe("#process") {
      it("should set the enabled status of the event request") {
        val mockEventRequest = mock[EventRequest]

        (mockEventRequest.setEnabled _).expects(testValue).once()

        enabledProcessor.process(mockEventRequest)
      }
    }
  }
} 
Example 113
Source File: CustomPropertyProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.properties.processors

import com.sun.jdi.request._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.properties.CustomProperty
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class CustomPropertyProcessorSpec extends ParallelMockFunSpec
{
  private val mockKey = mock[AnyRef]
  private val mockValue = mock[AnyRef]
  private val customProperty = CustomProperty(
    key = mockKey,
    value = mockValue
  )
  private val customPropertyProcessor =
    new CustomPropertyProcessor(customProperty)

  describe("CustomPropertyProcessor") {
    describe("#process") {
      it("should add the property to the event request") {
        val mockEventRequest = mock[EventRequest]

        (mockEventRequest.putProperty _).expects(mockKey, mockValue).once()

        customPropertyProcessor.process(mockEventRequest)
      }
    }
  }
} 
Example 114
Source File: SuspendPolicyPropertyProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.properties.processors

import com.sun.jdi.request._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.properties.SuspendPolicyProperty
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class SuspendPolicyPropertyProcessorSpec extends ParallelMockFunSpec
{
  private val testPolicy = 0
  private val suspendPolicyProperty = SuspendPolicyProperty(policy = testPolicy)
  private val suspendPolicyProcessor =
    new SuspendPolicyPropertyProcessor(suspendPolicyProperty)

  describe("SuspendPolicyPropertyProcessor") {
    describe("#process") {
      it("should set the suspend policy of the event request") {
        val mockEventRequest = mock[EventRequest]

        (mockEventRequest.setSuspendPolicy _).expects(testPolicy).once()

        suspendPolicyProcessor.process(mockEventRequest)
      }
    }
  }
} 
Example 115
Source File: SuspendPolicyPropertySpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.properties

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class SuspendPolicyPropertySpec extends ParallelMockFunSpec
{
  private val testPolicy = 0
  private val suspendPolicyProperty = SuspendPolicyProperty(policy = testPolicy)

  describe("SuspendPolicyProperty") {
    describe("#toProcessor") {
      it("should return a processor containing the suspend policy property") {
        suspendPolicyProperty.toProcessor.argument should
          be (suspendPolicyProperty)
      }
    }
  }
} 
Example 116
Source File: CustomPropertySpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.properties

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class CustomPropertySpec extends ParallelMockFunSpec
{
  private val mockKey = mock[AnyRef]
  private val mockValue = mock[AnyRef]
  private val customProperty = CustomProperty(key = mockKey, value = mockValue)

  describe("CustomProperty") {
    describe("#toProcessor") {
      it("should return a processor containing the custom property") {
        customProperty.toProcessor.argument should be (customProperty)
      }
    }
  }
} 
Example 117
Source File: UniqueIdPropertySpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.properties

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.properties.processors.CustomPropertyProcessor
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class UniqueIdPropertySpec extends ParallelMockFunSpec
{
  private val testId = java.util.UUID.randomUUID().toString
  private val uniqueIdProperty = UniqueIdProperty(id = testId)

  describe("UniqueIdProperty") {
    describe("constructor") {
      it("should set the custom property key to \"_id\"") {
        uniqueIdProperty.key should be ("_id")
      }

      it("should set the custom property value to the id") {
        uniqueIdProperty.value should be (testId)
      }
    }
    describe("#toProcessor") {
      it("should return a custom property processor") {
        uniqueIdProperty.toProcessor shouldBe a [CustomPropertyProcessor]
      }

      it("should return a processor containing the unique id property") {
        uniqueIdProperty.toProcessor.argument should be (uniqueIdProperty)
      }
    }
  }
} 
Example 118
Source File: SourceNameFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class SourceNameFilterSpec extends ParallelMockFunSpec
{
  private val testPattern = "some pattern"
  private val sourceNameFilter = SourceNameFilter(
    sourceNamePattern = testPattern
  )

  describe("SourceNameFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the source name filter") {
        sourceNameFilter.toProcessor.argument should be (sourceNameFilter)
      }
    }
  }
} 
Example 119
Source File: ClassExclusionFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class ClassExclusionFilterSpec extends ParallelMockFunSpec
{
  private val testPattern = "some pattern"
  private val classExclusionFilter = ClassExclusionFilter(
    classPattern = testPattern
  )

  describe("ClassExclusionFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the class exclusion filter") {
        classExclusionFilter.toProcessor.argument should be (classExclusionFilter)
      }
    }
  }
} 
Example 120
Source File: ClassReferenceFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters

import com.sun.jdi.ReferenceType
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class ClassReferenceFilterSpec extends ParallelMockFunSpec
{
  private val mockReferenceType = mock[ReferenceType]
  private val classReferenceFilter = ClassReferenceFilter(
    referenceType = mockReferenceType
  )

  describe("ClassReferenceFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the class reference filter") {
        classReferenceFilter.toProcessor.argument should be (classReferenceFilter)
      }
    }
  }
} 
Example 121
Source File: ThreadFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters

import com.sun.jdi.ThreadReference
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class ThreadFilterSpec extends ParallelMockFunSpec
{
  private val mockThreadReference = mock[ThreadReference]
  private val threadFilter = ThreadFilter(threadReference = mockThreadReference)

  describe("ThreadFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the thread filter") {
        threadFilter.toProcessor.argument should be (threadFilter)
      }
    }
  }
} 
Example 122
Source File: SourceNameFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters.processors

import com.sun.jdi.request._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.filters.SourceNameFilter
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class SourceNameFilterProcessorSpec extends ParallelMockFunSpec
{
  private val testSourceNamePattern = "some pattern"
  private val sourceNameFilter = SourceNameFilter(
    sourceNamePattern = testSourceNamePattern
  )
  private val sourceNameProcessor =
    new SourceNameFilterProcessor(sourceNameFilter)

  describe("SourceNameFilterProcessor") {
    describe("#process") {
      it("should add the source name for class prepare requests") {
        val mockClassPrepareRequest = mock[ClassPrepareRequest]

        (mockClassPrepareRequest.addSourceNameFilter _)
          .expects(testSourceNamePattern)

        sourceNameProcessor.process(mockClassPrepareRequest)
      }

      it("should not add the source name for any other request") {
        val mockEventRequest = mock[EventRequest]

        // TODO: Since there is no method for this generic event, what do we
        //       really test here?
        //(mockEventRequest.addSourceNameFilter _).expects(mockSourceNameReference).never()

        sourceNameProcessor.process(mockEventRequest)
      }
    }
  }
} 
Example 123
Source File: CountFilterProcessorSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters.processors

import com.sun.jdi.request._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.filters.CountFilter
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class CountFilterProcessorSpec extends ParallelMockFunSpec
{
  private val testCount = 3
  private val countFilter = CountFilter(count = testCount)
  private val countProcessor = new CountFilterProcessor(countFilter)

  describe("CountFilterProcessor") {
    describe("#process") {
      it("should add the count for all requests") {
        val mockEventRequest = mock[EventRequest]

        (mockEventRequest.addCountFilter _).expects(testCount)

        countProcessor.process(mockEventRequest)
      }
    }
  }
} 
Example 124
Source File: InstanceFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters

import com.sun.jdi.ObjectReference
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class InstanceFilterSpec extends ParallelMockFunSpec
{
  private val mockObjectReference = mock[ObjectReference]
  private val instanceFilter = InstanceFilter(
    objectReference = mockObjectReference
  )

  describe("InstanceFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the instance filter") {
        instanceFilter.toProcessor.argument should be (instanceFilter)
      }
    }
  }
} 
Example 125
Source File: CountFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class CountFilterSpec extends ParallelMockFunSpec
{
  private val testCount = 3
  private val countFilter = CountFilter(count = testCount)

  describe("CountFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the count filter") {
        countFilter.toProcessor.argument should be (countFilter)
      }
    }
  }
} 
Example 126
Source File: ClassInclusionFilterSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.requests.filters

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class ClassInclusionFilterSpec extends ParallelMockFunSpec
{
  private val testPattern = "some pattern"
  private val classInclusionFilter = ClassInclusionFilter(
    classPattern = testPattern
  )

  describe("ClassInclusionFilter") {
    describe("#toProcessor") {
      it("should return a processor containing the class inclusion filter") {
        classInclusionFilter.toProcessor.argument should be (classInclusionFilter)
      }
    }
  }
} 
Example 127
Source File: ThreadDeathManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.threads

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestThreadDeathManager

import scala.util.Success

class ThreadDeathManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockThreadDeathManager = mock[ThreadDeathManager]
  private val testThreadDeathManager = new TestThreadDeathManager(
    mockThreadDeathManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("ThreadDeathManager") {
    describe("#createThreadDeathRequest") {
      it("should invoke createThreadDeathRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockThreadDeathManager.createThreadDeathRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testThreadDeathManager.createThreadDeathRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createThreadDeathRequestFromInfo") {
      it("should invoke createThreadDeathRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockThreadDeathManager.createThreadDeathRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = ThreadDeathRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testThreadDeathManager.createThreadDeathRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 128
Source File: ThreadStartManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.threads

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.TestThreadStartManager

import scala.util.Success

class ThreadStartManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockThreadStartManager = mock[ThreadStartManager]
  private val testThreadStartManager = new TestThreadStartManager(
    mockThreadStartManager
  ) {
    override protected def newRequestId(): String = TestRequestId
  }

  describe("ThreadStartManager") {
    describe("#createThreadStartRequest") {
      it("should invoke createThreadStartRequestWithId") {
        val expected = Success(TestRequestId)
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockThreadStartManager.createThreadStartRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val actual = testThreadStartManager.createThreadStartRequest(
          testExtraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#createThreadStartRequestFromInfo") {
      it("should invoke createThreadStartRequestWithId") {
        val expected = Success(TestRequestId)
        val testIsPending = false
        val testExtraArguments = Seq(stub[JDIRequestArgument])

        (mockThreadStartManager.createThreadStartRequestWithId _)
          .expects(TestRequestId, testExtraArguments)
          .returning(expected).once()

        val info = ThreadStartRequestInfo(
          TestRequestId,
          testIsPending,
          testExtraArguments
        )
        val actual = testThreadStartManager.createThreadStartRequestFromInfo(info)

        actual should be(expected)
      }
    }
  }
} 
Example 129
Source File: DummyThreadStartManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.threads

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyThreadStartManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val threadStartManager = new DummyThreadStartManager

  describe("DummyThreadStartManager") {
    describe("#threadStartRequestList") {
      it("should return an empty list") {
        threadStartManager.threadStartRequestList should be (empty)
      }
    }

    describe("#createThreadStartRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = threadStartManager.createThreadStartRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasThreadStartRequest") {
      it("should return false") {
        val expected = false

        val actual = threadStartManager.hasThreadStartRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getThreadStartRequest") {
      it("should return None") {
        val expected = None

        val actual = threadStartManager.getThreadStartRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getThreadStartRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = threadStartManager.getThreadStartRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeThreadStartRequest") {
      it("should return false") {
        val expected = false

        val actual = threadStartManager.removeThreadStartRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 130
Source File: DummyThreadDeathManagerSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.lowlevel.threads

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.DummyOperationException
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyThreadDeathManagerSpec extends ParallelMockFunSpec
{
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val threadDeathManager = new DummyThreadDeathManager

  describe("DummyThreadDeathManager") {
    describe("#threadDeathRequestList") {
      it("should return an empty list") {
        threadDeathManager.threadDeathRequestList should be (empty)
      }
    }

    describe("#createThreadDeathRequestWithId") {
      it("should return a failure of dummy operation") {
        val result = threadDeathManager.createThreadDeathRequestWithId(
          TestRequestId
        )

        result.isFailure should be (true)
        result.failed.get shouldBe a [DummyOperationException]
      }
    }

    describe("#hasThreadDeathRequest") {
      it("should return false") {
        val expected = false

        val actual = threadDeathManager.hasThreadDeathRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getThreadDeathRequest") {
      it("should return None") {
        val expected = None

        val actual = threadDeathManager.getThreadDeathRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#getThreadDeathRequestInfo") {
      it("should return None") {
        val expected = None

        val actual = threadDeathManager.getThreadDeathRequestInfo(
          TestRequestId
        )

        actual should be (expected)
      }
    }

    describe("#removeThreadDeathRequest") {
      it("should return false") {
        val expected = false

        val actual = threadDeathManager.removeThreadDeathRequest(
          TestRequestId
        )

        actual should be (expected)
      }
    }
  }
} 
Example 131
Source File: JavaStringInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.java.info

import com.sun.jdi._
import org.scaladebugger.api.profiles.traits.info.{InfoProducer, StringInfo, TypeInfo}
import org.scaladebugger.api.virtualmachines.ScalaVirtualMachine
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class JavaStringInfoSpec extends ParallelMockFunSpec
{
  private val mockNewTypeProfile = mockFunction[Type, TypeInfo]
  private val mockScalaVirtualMachine = mock[ScalaVirtualMachine]
  private val mockInfoProducerProfile = mock[InfoProducer]
  private val mockVirtualMachine = mock[VirtualMachine]
  private val mockReferenceType = mock[ReferenceType]
  private val mockStringReference = mock[StringReference]
  private val javaStringInfoProfile = new JavaStringInfo(
    mockScalaVirtualMachine, mockInfoProducerProfile, mockStringReference
  )(
    _virtualMachine = mockVirtualMachine,
    _referenceType = mockReferenceType
  ) {
    override protected def newTypeProfile(_type: Type): TypeInfo =
      mockNewTypeProfile(_type)
  }

  describe("JavaStringInfo") {
    describe("#toJavaInfo") {
      it("should return a new instance of the Java profile representation") {
        val expected = mock[StringInfo]

        // Get Java version of info producer
        (mockInfoProducerProfile.toJavaInfo _).expects()
          .returning(mockInfoProducerProfile).once()

        // Create new info profile using Java version of info producer
        // NOTE: Cannot validate second set of args because they are
        //       call-by-name, which ScalaMock does not support presently
        (mockInfoProducerProfile.newStringInfo(
          _: ScalaVirtualMachine,
          _: StringReference
        )(
          _: VirtualMachine,
          _: ReferenceType
        )).expects(
          mockScalaVirtualMachine,
          mockStringReference,
          *, *
        ).returning(expected).once()

        val actual = javaStringInfoProfile.toJavaInfo

        actual should be (expected)
      }
    }

    describe("#isJavaInfo") {
      it("should return true") {
        val expected = true

        val actual = javaStringInfoProfile.isJavaInfo

        actual should be (expected)
      }
    }

    describe("#toJdiInstance") {
      it("should return the JDI instance this profile instance represents") {
        val expected = mockStringReference

        val actual = javaStringInfoProfile.toJdiInstance

        actual should be (expected)
      }
    }
  }
} 
Example 132
Source File: JavaClassObjectInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.java.info

import com.sun.jdi._
import org.scaladebugger.api.lowlevel.{InvokeNonVirtualArgument, InvokeSingleThreadedArgument, JDIArgument}
import org.scaladebugger.api.profiles.traits.info._
import org.scaladebugger.api.virtualmachines.ScalaVirtualMachine
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class JavaClassObjectInfoSpec extends ParallelMockFunSpec
{
  private val mockNewTypeProfile = mockFunction[Type, TypeInfo]
  private val mockScalaVirtualMachine = mock[ScalaVirtualMachine]
  private val mockInfoProducerProfile = mock[InfoProducer]
  private val mockVirtualMachine = mock[VirtualMachine]
  private val mockReferenceType = mock[ReferenceType]
  private val mockClassObjectReference = mock[ClassObjectReference]
  private val javaClassObjectInfoProfile = new JavaClassObjectInfo(
    mockScalaVirtualMachine, mockInfoProducerProfile, mockClassObjectReference
  )(
    _virtualMachine = mockVirtualMachine,
    _referenceType = mockReferenceType
  ) {
    override protected def newTypeProfile(_type: Type): TypeInfo =
      mockNewTypeProfile(_type)
  }

  describe("JavaClassObjectInfo") {
    describe("#toJavaInfo") {
      it("should return a new instance of the Java profile representation") {
        val expected = mock[ClassObjectInfo]

        // Get Java version of info producer
        (mockInfoProducerProfile.toJavaInfo _).expects()
          .returning(mockInfoProducerProfile).once()

        // Create new info profile using Java version of info producer
        // NOTE: Cannot validate second set of args because they are
        //       call-by-name, which ScalaMock does not support presently
        (mockInfoProducerProfile.newClassObjectInfo(
          _: ScalaVirtualMachine,
          _: ClassObjectReference
        )(
          _: VirtualMachine,
          _: ReferenceType
        )).expects(
          mockScalaVirtualMachine,
          mockClassObjectReference,
          *, *
        ).returning(expected).once()

        val actual = javaClassObjectInfoProfile.toJavaInfo

        actual should be (expected)
      }
    }

    describe("#isJavaInfo") {
      it("should return true") {
        val expected = true

        val actual = javaClassObjectInfoProfile.isJavaInfo

        actual should be (expected)
      }
    }

    describe("#toJdiInstance") {
      it("should return the JDI instance this profile instance represents") {
        val expected = mockClassObjectReference

        val actual = javaClassObjectInfoProfile.toJdiInstance

        actual should be (expected)
      }
    }

    describe("#reflectedType") {
      it("should return a profile wrapper around the reference type represented by the class") {
        val expected = mock[ReferenceTypeInfo]
        val referenceType = mock[ReferenceType]

        (mockClassObjectReference.reflectedType _).expects()
          .returning(referenceType).once()

        val mockTypeInfoProfile = mock[TypeInfo]
        mockNewTypeProfile.expects(referenceType)
          .returning(mockTypeInfoProfile).once()

        (mockTypeInfoProfile.toReferenceType _).expects()
          .returning(expected).once()

        val actual = javaClassObjectInfoProfile.reflectedType

        actual should be (expected)
      }
    }
  }
} 
Example 133
Source File: MethodInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.traits.info

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import test.InfoTestClasses.TestMethodInfo

import scala.util.{Failure, Success, Try}

class MethodInfoSpec extends ParallelMockFunSpec
{
  describe("MethodInfo") {
    describe("#toPrettyString") {
      it("should display the name, type parameters, and return type of the method") {
        val expected = "def methodName(type1,type2): returnType"

        val methodInfoProfile = new TestMethodInfo {
          override def name: String = "methodName"
          override def tryParameterTypeNames: Try[Seq[String]] =
            Success(Seq("type1", "type2"))
          override def tryReturnTypeName: Try[String] = Success("returnType")
        }

        val actual = methodInfoProfile.toPrettyString

        actual should be (expected)
      }

      it("should display ??? for the type parameters if unavailable") {
        val expected = "def methodName(???): returnType"

        val methodInfoProfile = new TestMethodInfo {
          override def name: String = "methodName"
          override def tryParameterTypeNames: Try[Seq[String]] =
            Failure(new Throwable)
          override def tryReturnTypeName: Try[String] = Success("returnType")
        }

        val actual = methodInfoProfile.toPrettyString

        actual should be (expected)      }

      it("should display ??? for the return type if unavailable") {
        val expected = "def methodName(type1,type2): ???"

        val methodInfoProfile = new TestMethodInfo {
          override def name: String = "methodName"
          override def tryParameterTypeNames: Try[Seq[String]] =
            Success(Seq("type1", "type2"))
          override def tryReturnTypeName: Try[String] =
            Failure(new Throwable)
        }

        val actual = methodInfoProfile.toPrettyString

        actual should be (expected)      }
    }

    describe("#tryReturnTypeName") {
      it("should wrap the unsafe call in a Try") {
        val mockUnsafeMethod = mockFunction[String]

        val methodInfoProfile = new TestMethodInfo {
          override def returnTypeName: String = mockUnsafeMethod()
        }

        val r = "some.return.type"
        mockUnsafeMethod.expects().returning(r).once()
        methodInfoProfile.tryReturnTypeName.get should be (r)
      }
    }

    describe("#tryParameterTypeNames") {
      it("should wrap the unsafe call in a Try") {
        val mockUnsafeMethod = mockFunction[Seq[String]]

        val methodInfoProfile = new TestMethodInfo {
          override def parameterTypeNames: Seq[String] = mockUnsafeMethod()
        }

        val r = Seq("some.param.type")
        mockUnsafeMethod.expects().returning(r).once()
        methodInfoProfile.tryParameterTypeNames.get should be (r)
      }
    }
  }
} 
Example 134
Source File: ThreadGroupInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.traits.info

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import test.InfoTestClasses.TestThreadGroupInfo

import scala.util.{Success, Try}

class ThreadGroupInfoSpec extends ParallelMockFunSpec
{
  describe("ThreadGroupInfo") {
    describe("#toPrettyString") {
      it("should display the thread name and unique id as a hex code") {
        val expected = "Thread Group threadGroupName (0xABCDE)"

        val threadInfoProfile = new TestThreadGroupInfo {
          override def uniqueId: Long = Integer.parseInt("ABCDE", 16)
          override def name: String = "threadGroupName"
        }

        val actual = threadInfoProfile.toPrettyString

        actual should be(expected)
      }
    }
  }
} 
Example 135
Source File: PrimitiveInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.traits.info

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import test.InfoTestClasses.TestPrimitiveInfo

class PrimitiveInfoSpec extends ParallelMockFunSpec
{
  describe("PrimitiveInfo") {
    describe("#tryToLocalValue") {
      it("should wrap the unsafe call in a Try") {
        val mockUnsafeMethod = mockFunction[AnyVal]

        val primitiveInfoProfile = new TestPrimitiveInfo {
          override def toLocalValue: AnyVal = mockUnsafeMethod()
        }

        val r = 3
        mockUnsafeMethod.expects().returning(r).once()
        primitiveInfoProfile.tryToLocalValue.get should be (r)
      }
    }

    describe("#toPrettyString") {
      it("should display the value as a string") {
        val expected = "333"

        val primitiveInfoProfile = new TestPrimitiveInfo {
          override def isChar: Boolean = false
          override def toLocalValue: AnyVal = 333
        }

        val actual = primitiveInfoProfile.toPrettyString

        actual should be(expected)
      }

      it("should wrap a character value in single quotes") {
        val expected = "'a'"

        val primitiveInfoProfile = new TestPrimitiveInfo {
          override def isChar: Boolean = true
          override def toLocalValue: AnyVal = 'a'
        }

        val actual = primitiveInfoProfile.toPrettyString

        actual should be(expected)
      }

      it("should return <ERROR> if unable to get the value") {
        val expected = "<ERROR>"

        val primitiveInfoProfile = new TestPrimitiveInfo {
          override def isChar: Boolean = false
          override def toLocalValue: AnyVal = throw new Throwable
        }

        val actual = primitiveInfoProfile.toPrettyString

        actual should be(expected)
      }
    }
  }
} 
Example 136
Source File: LocationInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.traits.info

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import test.InfoTestClasses.TestLocationInfo

import scala.util.{Failure, Success, Try}

class LocationInfoSpec extends ParallelMockFunSpec
{
  describe("LocationInfo") {
    describe("#toPrettyString") {
      it("should include the source path if available") {
        val expected = "path/to/file.scala : 999"

        val locationInfoProfile = new TestLocationInfo {
          override def trySourcePath: Try[String] =
            Success("path/to/file.scala")
          override def lineNumber: Int = 999
        }

        val actual = locationInfoProfile.toPrettyString

        actual should be (expected)
      }

      it("should use ??? for the source path if unavailable") {
        val expected = "??? : 999"

        val locationInfoProfile = new TestLocationInfo {
          override def trySourcePath: Try[String] = Failure(new Throwable)
          override def lineNumber: Int = 999
        }

        val actual = locationInfoProfile.toPrettyString

        actual should be (expected)
      }
    }

    describe("#codeIndexOption") {
      it("should return Some(code position) if position is 0 or greater") {
        val expected = Some(999)

        val locationInfoProfile = new TestLocationInfo {
          override def codeIndex: Long = expected.get
        }

        val actual = locationInfoProfile.codeIndexOption

        actual should be (expected)
      }

      it("should return None if position is less than 0") {
        val expected = None

        val locationInfoProfile = new TestLocationInfo {
          override def codeIndex: Long = -1
        }

        val actual = locationInfoProfile.codeIndexOption

        actual should be (expected)
      }
    }

    describe("#lineNumberOption") {
      it("should return Some(line number) if line is 0 or greater") {
        val expected = Some(999)

        val locationInfoProfile = new TestLocationInfo {
          override def lineNumber: Int = expected.get
        }

        val actual = locationInfoProfile.lineNumberOption

        actual should be (expected)
      }

      it("should return None if line is less than 0") {
        val expected = None

        val locationInfoProfile = new TestLocationInfo {
          override def lineNumber: Int = -1
        }

        val actual = locationInfoProfile.lineNumberOption

        actual should be (expected)
      }
    }
  }
} 
Example 137
Source File: StringInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.traits.info

import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import test.InfoTestClasses.TestStringInfo

class StringInfoSpec extends ParallelMockFunSpec
{
  describe("StringInfo") {
    describe("#toPrettyString") {
      it("should return the local string value wrapped in double quotes") {
        val q = '"'
        val expected = s"${q}TEST${q}"

        val stringInfoProfile = new TestStringInfo {
          override def toLocalValue: Any = "TEST"
        }

        val actual = stringInfoProfile.toPrettyString

        actual should be(expected)
      }
    }
  }
} 
Example 138
Source File: SwappableCreateInfoSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.swappable.info

import org.scaladebugger.api.profiles.ProfileManager
import org.scaladebugger.api.profiles.swappable.SwappableDebugProfile
import org.scaladebugger.api.profiles.traits.DebugProfile
import org.scaladebugger.api.profiles.traits.info.ValueInfo
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}

class SwappableCreateInfoSpec extends ParallelMockFunSpec
{
  private val mockDebugProfile = mock[DebugProfile]
  private val mockProfileManager = mock[ProfileManager]

  private val swappableDebugProfile = new Object with SwappableDebugProfile {
    override protected val profileManager: ProfileManager = mockProfileManager
  }

  describe("SwappableMiscInfo") {
    describe("#createRemotely(AnyVal)") {
      it("should invoke the method on the underlying profile") {
        val expected = mock[ValueInfo]
        val value: AnyVal = 33

        (mockProfileManager.retrieve _).expects(*)
          .returning(Some(mockDebugProfile)).once()

        (mockDebugProfile.createRemotely(_: AnyVal)).expects(value)
          .returning(expected).once()

        val actual = swappableDebugProfile.createRemotely(value)

        actual should be (expected)
      }

      it("should throw an exception if there is no underlying profile") {
        val value = "some string"

        (mockProfileManager.retrieve _).expects(*).returning(None).once()

        intercept[AssertionError] {
          swappableDebugProfile.createRemotely(value)
        }
      }
    }

    describe("#createRemotely(String)") {
      it("should invoke the method on the underlying profile") {
        val expected = mock[ValueInfo]
        val value = "some string"

        (mockProfileManager.retrieve _).expects(*)
          .returning(Some(mockDebugProfile)).once()

        (mockDebugProfile.createRemotely(_: String)).expects(value)
          .returning(expected).once()

        val actual = swappableDebugProfile.createRemotely(value)

        actual should be (expected)
      }

      it("should throw an exception if there is no underlying profile") {
        val value = "some string"

        (mockProfileManager.retrieve _).expects(*).returning(None).once()

        intercept[AssertionError] {
          swappableDebugProfile.createRemotely(value)
        }
      }
    }
  }
} 
Example 139
Source File: SwappableDebugProfileManagementSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.swappable

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.JDIArgument
import org.scaladebugger.api.lowlevel.events.EventType.EventType
import org.scaladebugger.api.profiles.ProfileManager
import org.scaladebugger.api.profiles.traits.DebugProfile
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class SwappableDebugProfileManagementSpec extends ParallelMockFunSpec
{
  private val mockDebugProfile = mock[DebugProfile]
  private val mockProfileManager = mock[ProfileManager]

  private val swappableDebugProfile = new Object with SwappableDebugProfile {
    override protected val profileManager: ProfileManager = mockProfileManager
  }

  describe("SwappableDebugProfileManagement") {
    describe("#use") {
      it("should set the current underlying profile") {
        val expected = mockDebugProfile
        val name = "some name"

        (mockProfileManager.retrieve _).expects(name)
          .returning(Some(expected)).once()

        swappableDebugProfile.use(name)

        val actual = swappableDebugProfile.withCurrentProfile

        actual should be (expected)
      }
    }

    describe("#withCurrentProfile") {
      it("should return the currently-active profile") {
        val expected = mockDebugProfile
        val name = "some name"

        (mockProfileManager.retrieve _).expects(name)
          .returning(Some(expected)).once()

        swappableDebugProfile.use(name)

        val actual = swappableDebugProfile.withCurrentProfile

        actual should be (expected)
      }

      it("should throw an exception if the profile is not found") {
        val name = "some name"

        (mockProfileManager.retrieve _).expects(name).returning(None).once()

        swappableDebugProfile.use(name)

        intercept[AssertionError] {
          swappableDebugProfile.withCurrentProfile
        }
      }
    }

    describe("#withProfile") {
      it("should return the profile with the specified name") {
        val expected = mockDebugProfile
        val name = "some name"

        (mockProfileManager.retrieve _).expects(name)
          .returning(Some(expected)).once()

        val actual = swappableDebugProfile.withProfile(name)

        actual should be (expected)
      }

      it("should throw an exception if the profile is not found") {
        val name = "some name"

        (mockProfileManager.retrieve _).expects(name).returning(None).once()

        intercept[AssertionError] {
          swappableDebugProfile.withProfile(name)
        }
      }
    }
  }
} 
Example 140
Source File: SwappableVMStartRequestSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.swappable.requests.vm

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.JDIArgument
import org.scaladebugger.api.profiles.ProfileManager
import org.scaladebugger.api.profiles.swappable.SwappableDebugProfile
import org.scaladebugger.api.profiles.traits.DebugProfile
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class SwappableVMStartRequestSpec extends ParallelMockFunSpec
{
  private val mockDebugProfile = mock[DebugProfile]
  private val mockProfileManager = mock[ProfileManager]

  private val swappableDebugProfile = new Object with SwappableDebugProfile {
    override protected val profileManager: ProfileManager = mockProfileManager
  }

  describe("SwappableVMStartRequest") {
    describe("#tryGetOrCreateVMStartRequestWithData") {
      it("should invoke the method on the underlying profile") {
        val arguments = Seq(mock[JDIArgument])

        (mockProfileManager.retrieve _).expects(*)
          .returning(Some(mockDebugProfile)).once()

        // NOTE: Forced to use onCall with product due to issues with ScalaMock
        //       casting and inability to work with varargs directly
        (mockDebugProfile.tryGetOrCreateVMStartRequestWithData _).expects(*)
          .onCall((t: Product) => {
            val args = t.productElement(0).asInstanceOf[Seq[JDIArgument]]
            args should be(arguments)
            null
          })

        swappableDebugProfile.tryGetOrCreateVMStartRequestWithData(arguments: _*)
      }

      it("should throw an exception if there is no underlying profile") {
        val arguments = Seq(mock[JDIArgument])

        (mockProfileManager.retrieve _).expects(*).returning(None).once()

        intercept[AssertionError] {
          swappableDebugProfile.tryGetOrCreateVMStartRequestWithData(arguments: _*)
        }
      }
    }
  }
} 
Example 141
Source File: SwappableVMDisconnectRequestSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.swappable.requests.vm

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.JDIArgument
import org.scaladebugger.api.profiles.ProfileManager
import org.scaladebugger.api.profiles.swappable.SwappableDebugProfile
import org.scaladebugger.api.profiles.traits.DebugProfile
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class SwappableVMDisconnectRequestSpec extends ParallelMockFunSpec
{
  private val mockDebugProfile = mock[DebugProfile]
  private val mockProfileManager = mock[ProfileManager]

  private val swappableDebugProfile = new Object with SwappableDebugProfile {
    override protected val profileManager: ProfileManager = mockProfileManager
  }

  describe("SwappableVMDisconnectRequest") {
    describe("#tryGetOrCreateVMDisconnectRequestWithData") {
      it("should invoke the method on the underlying profile") {
        val arguments = Seq(mock[JDIArgument])

        (mockProfileManager.retrieve _).expects(*)
          .returning(Some(mockDebugProfile)).once()

        // NOTE: Forced to use onCall with product due to issues with ScalaMock
        //       casting and inability to work with varargs directly
        (mockDebugProfile.tryGetOrCreateVMDisconnectRequestWithData _).expects(*)
          .onCall((t: Product) => {
            val args = t.productElement(0).asInstanceOf[Seq[JDIArgument]]
            args should be(arguments)
            null
          })

        swappableDebugProfile.tryGetOrCreateVMDisconnectRequestWithData(arguments: _*)
      }

      it("should throw an exception if there is no underlying profile") {
        val arguments = Seq(mock[JDIArgument])

        (mockProfileManager.retrieve _).expects(*).returning(None).once()

        intercept[AssertionError] {
          swappableDebugProfile.tryGetOrCreateVMDisconnectRequestWithData(arguments: _*)
        }
      }
    }
  }
} 
Example 142
Source File: SwappableEventListenerRequestSpec.scala    From scala-debugger   with Apache License 2.0 5 votes vote down vote up
package org.scaladebugger.api.profiles.swappable.requests.events

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.JDIArgument
import org.scaladebugger.api.lowlevel.events.EventType.EventType
import org.scaladebugger.api.profiles.ProfileManager
import org.scaladebugger.api.profiles.swappable.SwappableDebugProfile
import org.scaladebugger.api.profiles.traits.DebugProfile
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class SwappableEventListenerRequestSpec extends ParallelMockFunSpec
{
  private val mockDebugProfile = mock[DebugProfile]
  private val mockProfileManager = mock[ProfileManager]

  private val swappableDebugProfile = new Object with SwappableDebugProfile {
    override protected val profileManager: ProfileManager = mockProfileManager
  }

  describe("SwappableEventListenerRequest") {
    describe("#eventHandlers") {
      it("should invoke the method on the underlying profile") {
        (mockProfileManager.retrieve _).expects(*)
          .returning(Some(mockDebugProfile)).once()

        (mockDebugProfile.eventHandlers _).expects().once()

        swappableDebugProfile.eventHandlers
      }

      it("should throw an exception if there is no underlying profile") {
        (mockProfileManager.retrieve _).expects(*).returning(None).once()

        intercept[AssertionError] {
          swappableDebugProfile.eventHandlers
        }
      }
    }

    describe("#tryCreateEventListenerWithData") {
      // TODO: ScalaMock is causing a stack overflow exception
      ignore("should invoke the method on the underlying profile") {
        val eventType = mock[EventType]
        val arguments = Seq(mock[JDIArgument])

        (mockProfileManager.retrieve _).expects(*)
          .returning(Some(mockDebugProfile)).once()

        (mockDebugProfile.tryCreateEventListenerWithData _)
          .expects(eventType, arguments).once()

        swappableDebugProfile.tryCreateEventListenerWithData(eventType, arguments: _*)
      }

      it("should throw an exception if there is no underlying profile") {
        val eventType = mock[EventType]
        val arguments = Seq(mock[JDIArgument])

        (mockProfileManager.retrieve _).expects(*).returning(None).once()

        intercept[AssertionError] {
          swappableDebugProfile.tryCreateEventListenerWithData(eventType, arguments: _*)
        }
      }
    }
  }
} 
Example 143
Source File: AnomalyDetectorTest.scala    From deequ   with Apache License 2.0 5 votes vote down vote up
package com.amazon.deequ.anomalydetection

import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, PrivateMethodTester, WordSpec}


class AnomalyDetectorTest extends WordSpec with Matchers with MockFactory with PrivateMethodTester {
  private val fakeAnomalyDetector = stub[AnomalyDetectionStrategy]

  val aD = AnomalyDetector(fakeAnomalyDetector)
  val data = Seq((0L, -1.0), (1L, 2.0), (2L, 3.0), (3L, 0.5)).map { case (t, v) =>
    DataPoint[Double](t, Option(v))
  }

  "Anomaly Detector" should {

    "ignore missing values" in {
      val data = Seq(DataPoint[Double](0L, Option(1.0)), DataPoint[Double](1L, Option(2.0)),
        DataPoint[Double](2L, None), DataPoint[Double](3L, Option(1.0)))

      (fakeAnomalyDetector.detect _ when(Vector(1.0, 2.0, 1.0), (0, 3)))
        .returns(Seq((1, Anomaly(Option(2.0), 1.0))))

      val anomalyResult = aD.detectAnomaliesInHistory(data, (0L, 4L))

      assert(anomalyResult == DetectionResult(Seq((1L, Anomaly(Option(2.0), 1.0)))))
    }

    "only detect values in range" in {
      (fakeAnomalyDetector.detect _ when(Vector(-1.0, 2.0, 3.0, 0.5), (2, 4)))
        .returns(Seq((2, Anomaly(Option(3.0), 1.0))))

      val anomalyResult = aD.detectAnomaliesInHistory(data, (2L, 4L))

      assert(anomalyResult == DetectionResult(Seq((2L, Anomaly(Option(3.0), 1.0)))))
    }

    "throw an error when intervals are not ordered" in {
      intercept[IllegalArgumentException] {
        aD.detectAnomaliesInHistory(data, (4, 2))
      }
    }

    "treat ordered values with time gaps correctly" in {
      val data = (for (i <- 1 to 10) yield {
        (i.toLong * 200L) -> 5.0
      }).map { case (t, v) =>
        DataPoint[Double](t, Option(v))
      }

      (fakeAnomalyDetector.detect _ when(data.map(_.metricValue.get).toVector, (0, 2)))
        .returns (Seq((0, Anomaly(Option(5.0), 1.0)), (1, Anomaly(Option(5.0), 1.0))))

      val anomalyResult = aD.detectAnomaliesInHistory(data, (200L, 401L))

      assert(anomalyResult == DetectionResult(Seq((200L, Anomaly(Option(5.0), 1.0)),
        (400L, Anomaly(Option(5.0), 1.0)))))
    }

    "treat unordered values with time gaps correctly" in {
      val data = Seq((10L, -1.0), (25L, 2.0), (11L, 3.0), (0L, 0.5)).map { case (t, v) =>
        DataPoint[Double](t, Option(v))
      }
      val tS = AnomalyDetector(SimpleThresholdStrategy(lowerBound = -0.5, upperBound = 1.0))

      (fakeAnomalyDetector.detect _ when(Vector(0.5, -1.0, 3.0, 2.0), (0, 4)))
        .returns(Seq((1, Anomaly(Option(-1.0), 1.0)), (2, Anomaly(Option(3.0), 1.0)),
          (3, Anomaly(Option(2.0), 1.0))))

      val anomalyResult = aD.detectAnomaliesInHistory(data)

      assert(anomalyResult == DetectionResult(Seq((10L, Anomaly(Option(-1.0), 1.0)),
        (11L, Anomaly(Option(3.0), 1.0)), (25L, Anomaly(Option(2.0), 1.0)))))
    }

    "treat unordered values without time gaps correctly" in {
      val data = Seq((1L, -1.0), (3L, 2.0), (2L, 3.0), (0L, 0.5)).map { case (t, v) =>
        DataPoint[Double](t, Option(v))
      }

      (fakeAnomalyDetector.detect _ when(Vector(0.5, -1.0, 3.0, 2.0), (0, 4)))
        .returns(Seq((1, Anomaly(Option(-1.0), 1.0)), (2, Anomaly(Option(3.0), 1.0)),
          (3, Anomaly(Option(2.0), 1.0))))

      val anomalyResult = aD.detectAnomaliesInHistory(data)

      assert(anomalyResult == DetectionResult(Seq((1L, Anomaly(Option(-1.0), 1.0)),
        (2L, Anomaly(Option(3.0), 1.0)), (3L, Anomaly(Option(2.0), 1.0)))))
    }

  }
} 
Example 144
Source File: PrometheusResponseTimeRecorderSpec.scala    From prometheus-akka-http   with MIT License 5 votes vote down vote up
package com.lonelyplanet.prometheus

import io.prometheus.client.{Collector, CollectorRegistry}
import org.scalamock.scalatest.MockFactory
import com.lonelyplanet.prometheus.Utils._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration
import scala.concurrent.duration.FiniteDuration
import scala.util.Random

class PrometheusResponseTimeRecorderSpec extends AnyFlatSpec with Matchers with MockFactory {

  "PrometheusLatencyRecorder" should "register a histogram and record request latencies" in {
    val registry = new CollectorRegistry()
    val randomMetricName = generateRandomString
    val randomMetricHelp = generateRandomString
    val randomLabelName = generateRandomString
    val randomEndpointName = generateRandomString
    val randomLatency = Math.abs(Random.nextInt(10000))

    // our random value will end up in the second bucket
    val buckets = List((randomLatency - 1).toDouble, (randomLatency + 1).toDouble)

    val recorder = new PrometheusResponseTimeRecorder(
      randomMetricName,
      randomMetricHelp,
      buckets,
      randomLabelName,
      registry,
      duration.MILLISECONDS)

    recorder.recordResponseTime(randomEndpointName, FiniteDuration(randomLatency, duration.MILLISECONDS))

    val first = getBucketValue(registry, randomMetricName, List(randomLabelName), List(randomEndpointName), buckets.head)
    val second = getBucketValue(registry, randomMetricName, List(randomLabelName), List(randomEndpointName), buckets.last)
    val positiveInf = getBucketValue(registry, randomMetricName, List(randomLabelName), List(randomEndpointName), Double.PositiveInfinity)

    first shouldBe 0
    second shouldBe 1
    positiveInf shouldBe 1
  }

  private def getBucketValue(registry: CollectorRegistry, metricName: String, labelNames: List[String], labelValues: List[String], bucket: Double) = {
    val name = metricName + "_bucket"

    // 'le' should be the first label in the list
    val allLabelNames = (Array("le") ++ labelNames).reverse
    val allLabelValues = (Array(Collector.doubleToGoString(bucket)) ++ labelValues).reverse
    registry.getSampleValue(name, allLabelNames, allLabelValues).intValue()
  }

} 
Example 145
Source File: package.scala    From featherbed   with Apache License 2.0 4 votes vote down vote up
package featherbed

import java.net.URL

import com.twitter.finagle.{Filter, Http}
import com.twitter.finagle.http.{Request, Response}
import org.scalamock.matchers.Matcher
import org.scalamock.scalatest.MockFactory

package object fixture {
  private[fixture] class MockClient (
    baseUrl: URL,
    filter: Filter[Request, Response, Request, Response]
  ) extends Client(baseUrl) {
    override def clientTransform(c: Http.Client) = c.filtered(filter)
  }

  trait ClientTest { self: MockFactory =>
    class TransportRequestMatcher(f: Request => Unit) extends Matcher[Any] {
      override def canEqual(x: Any) = x match {
        case x: Request => true
        case _ => false
      }
      override def safeEquals(that: Any): Boolean = that match {
        case x: Request => f(x); true
        case _ => false
      }
    }

    def request(f: Request => Unit): TransportRequestMatcher = new TransportRequestMatcher(f)

    def mockClient(url: String, filter: Filter[Request, Response, Request, Response]): Client =
      new MockClient(new URL(url), filter)
  }
}