org.specs2.mock.Mockito Scala Examples

The following examples show how to use org.specs2.mock.Mockito. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SystemStatusSpec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.controllers

import com.mohiva.play.silhouette.test._
import org.hatdex.hat.api.HATTestContext
import org.hatdex.hat.api.json.HatJsonFormats
import org.hatdex.hat.api.models.{ HatStatus, StatusKind }
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.specification.BeforeAll
import play.api.Logger
import play.api.test.{ FakeRequest, PlaySpecification }

import scala.concurrent.Await
import scala.concurrent.duration._

class SystemStatusSpec(implicit ee: ExecutionEnv) extends PlaySpecification with Mockito with HATTestContext with BeforeAll with HatJsonFormats {

  val logger = Logger(this.getClass)

  sequential

  def beforeAll: Unit = {
    Await.result(databaseReady, 60.seconds)
  }

  "The `update` method" should {
    "Return success response after updating HAT database" in {
      val request = FakeRequest("GET", "http://hat.hubofallthings.net")

      val controller = application.injector.instanceOf[SystemStatus]
      val result = controller.update().apply(request)

      status(result) must equalTo(OK)
      (contentAsJson(result) \ "message").as[String] must be equalTo "Database updated"
    }
  }

  "The `status` method" should {
    "Return current utilisation" in {
      val request = FakeRequest("GET", "http://hat.hubofallthings.net")
        .withAuthenticator(owner.loginInfo)

      val controller = application.injector.instanceOf[SystemStatus]
      val result = controller.status().apply(request)

      status(result) must equalTo(OK)
      val stats = contentAsJson(result).as[List[HatStatus]]

      stats.length must be greaterThan 0
      stats.find(_.title == "Previous Login").get.kind must be equalTo StatusKind.Text("Never", None)
      stats.find(_.title == "Owner Email").get.kind must be equalTo StatusKind.Text("[email protected]", None)
      stats.find(_.title == "Database Storage").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "File Storage").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "Database Storage Used").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "File Storage Used").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "Database Storage Used Share").get.kind must haveClass[StatusKind.Numeric]
      stats.find(_.title == "File Storage Used Share").get.kind must haveClass[StatusKind.Numeric]
    }

    "Return last login information when present" in {
      val authRequest = FakeRequest("GET", "http://hat.hubofallthings.net")
        .withHeaders("username" -> "hatuser", "password" -> "pa55w0rd")

      val authController = application.injector.instanceOf[Authentication]

      val request = FakeRequest("GET", "http://hat.hubofallthings.net")
        .withAuthenticator(owner.loginInfo)

      val controller = application.injector.instanceOf[SystemStatus]

      val result = for {
        _ <- authController.accessToken().apply(authRequest)
        // login twice - the second login is considered "current", not previous
        _ <- authController.accessToken().apply(authRequest)
        r <- controller.status().apply(request)
      } yield r

      status(result) must equalTo(OK)
      val stats = contentAsJson(result).as[List[HatStatus]]

      stats.length must be greaterThan 0
      stats.find(_.title == "Previous Login").get.kind must be equalTo StatusKind.Text("moments ago", None)
    }
  }
} 
Example 2
Source File: BaseSpec.scala    From bean-validation-scala   with MIT License 5 votes vote down vote up
package com.tsukaby.bean_validation_scala

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification


trait BaseSpec extends Specification with Mockito {
  def targetClassName = {
    this.getClass.getSimpleName.replaceAll("Spec$", "")
  }

  def test(bean:Any, expected:Int) = {
    val validator = ScalaValidatorFactory.validator
    val violations = validator.validate(bean)
    violations.size must_=== expected
  }

} 
Example 3
Source File: TemplateSourceSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.templates

import de.frosner.broccoli.models.{ParameterInfo, ParameterType, Template}
import de.frosner.broccoli.templates.TemplateConfig.{Parameter, TemplateInfo}
import org.specs2.mutable.Specification
import org.mockito.Mockito._
import org.specs2.mock.Mockito

class TemplateSourceSpec extends Specification with Mockito {
  "loadTemplate" should {

    def templateRenderer(areValid: Boolean, paramNames: Seq[String]): TemplateRenderer = {
      val templateRenderer = mock[TemplateRenderer]
      when(templateRenderer.validateParameterName(anyString)).thenReturn(!areValid)
      paramNames.foreach(
        name => when(templateRenderer.validateParameterName(name)).thenReturn(areValid)
      )
      templateRenderer
    }
    // Always true when validating
    def defaultTemplateRenderer: TemplateRenderer = templateRenderer(false, Seq())

    def templateSource(renderer: TemplateRenderer): TemplateSource = new TemplateSource {
      val templateRenderer: TemplateRenderer = renderer
      override def loadTemplates(): Seq[Template] = Seq.empty
    }
    def defaultTemplateSource = templateSource(defaultTemplateRenderer)

    "work" in {
      val id = "templateId"
      val templateString = "Hello {{ id }}"
      val templateInfo = TemplateInfo(None, Map("id" -> Parameter(Some("id"), None, None, ParameterType.Raw, None)))
      val template =
        defaultTemplateSource.loadTemplate(id, templateString, templateInfo).get

      template.id === id and template.template === templateString and template.parameterInfos("id") === ParameterInfo
        .fromTemplateInfoParameter("id", templateInfo.parameters.get("id").get)
    }

    "require an 'id' parameter (no parameter)" in {
      val tryTemplate =
        defaultTemplateSource.loadTemplate("test", "Hallo", TemplateInfo(None, Map.empty))
      (tryTemplate.isFailure must beTrue) and (tryTemplate.failed.get.getMessage must beEqualTo(
        "requirement failed: There needs to be an 'id' field in the template for Broccoli to work. Parameters defined: Set()"))
    }

    "require an 'id' parameter (wrong parameter)" in {
      val tryTemplate =
        defaultTemplateSource.loadTemplate(
          "test",
          "Hallo {{bla}}",
          TemplateInfo(None, Map("bla" -> Parameter(Some("bla"), None, None, ParameterType.Raw, None)))
        )
      (tryTemplate.isFailure must beTrue) and (tryTemplate.failed.get.getMessage must beEqualTo(
        "requirement failed: There needs to be an 'id' field in the template for Broccoli to work. Parameters defined: Set(bla)"))
    }

    "should fail when template info contains an invalid parameter name" in {
      val tryTemplate =
        templateSource(templateRenderer(false, Seq("bla-bla"))).loadTemplate(
          "test",
          "Hallo {{bla-bla}}",
          TemplateInfo(None,
                       Map("id" -> Parameter(Some("id"), None, None, ParameterType.Raw, None),
                           "bla-bla" -> Parameter(Some("bla"), None, None, ParameterType.Raw, None)))
        )
      (tryTemplate.isFailure must beTrue) and (tryTemplate.failed.get.getMessage must beEqualTo(
        s"requirement failed: The following parameters are invalid: bla-bla"))
    }

    "not expose variables that are not defined in the template config" in {
      val tryTemplate =
        defaultTemplateSource.loadTemplate(
          "test",
          "{{id}} {{ global_var }} {% for x in [1 2 3] %}{{x}}{% endfor %}",
          TemplateInfo(None,
                       Map("id" -> Parameter(Some("id"), None, None, ParameterType.Raw, None),
                           "global_var" -> Parameter(Some("global_var"), None, None, ParameterType.Raw, None)))
        )
      (tryTemplate.isSuccess must beTrue) and (tryTemplate.get.parameters must not contain "x")
    }
  }
} 
Example 4
Source File: SignalRefreshedTemplateSourceSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.templates

import de.frosner.broccoli.signal.SignalManager
import org.mockito.Mockito.{times, verify}
import org.mockito.{ArgumentCaptor, Matchers}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import sun.misc.{Signal, SignalHandler}

class SignalRefreshedTemplateSourceSpec extends Specification with Mockito {
  "Receiving a SIGUSR2 signal" should {
    "update the cache" in {
      val signalManager = mock[SignalManager]
      val testTemplateSource = mock[CachedTemplateSource]
      val signalRefreshedTemplateSource = new SignalRefreshedTemplateSource(testTemplateSource, signalManager)
      val handler = ArgumentCaptor.forClass(classOf[SignalHandler])
      there was one(signalManager).register(Matchers.eq(new Signal("USR2")), handler.capture())

      there was no(testTemplateSource).refresh()
      there was no(testTemplateSource).loadTemplates()
      signalRefreshedTemplateSource.loadTemplates()

      there was no(testTemplateSource).refresh()
      there was one(testTemplateSource).loadTemplates()
      verify(testTemplateSource, times(1)).loadTemplates()

      handler.getValue.handle(new Signal("USR2"))
      there was one(testTemplateSource).refresh()
      there was one(testTemplateSource).loadTemplates()
    }
  }
} 
Example 5
Source File: SecurityServiceSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.services

import cats.data.OptionT
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.services.IdentityService
import com.mohiva.play.silhouette.api.util.Credentials
import com.mohiva.play.silhouette.impl.exceptions.InvalidPasswordException
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import de.frosner.broccoli.auth.{Account, AuthConfiguration, AuthMode, Role}
import org.mockito.Mock
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.mutable.ExecutionEnvironment

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

class SecurityServiceSpec extends Specification with Mockito with ExecutionEnvironment {

  def configWithAccounts(accounts: Seq[Account]): AuthConfiguration =
    AuthConfiguration(
      mode = AuthMode.Conf,
      session = AuthConfiguration.Session(timeout = Duration(1, "hour"), allowMultiLogin = true),
      cookie = AuthConfiguration.Cookie(secure = true),
      conf = AuthConfiguration.Conf(
        accounts = accounts
          .map(
            a =>
              AuthConfiguration.ConfAccount(
                a.name,
                "",
                a.instanceRegex,
                a.role
            ))
          .toList),
      allowedFailedLogins = 3
    )

  val identityService = mock[IdentityService[Account]]

  val account = Account("frank", "^test.*", Role.Administrator)

  override def is(implicit executionEnv: ExecutionEnv): Any =
    "An authentication check" should {

      "succeed if the credentials provider authenticates" in {
        val login = LoginInfo(CredentialsProvider.ID, account.name)
        val credentials = Credentials(account.name, "pass")

        val credentialsProvider = mock[CredentialsProvider]
        credentialsProvider.authenticate(credentials) returns Future.successful(login)

        SecurityService(configWithAccounts(List(account)), credentialsProvider, identityService)
          .authenticate(credentials) must beSome(login).await
      }

      "fail if the credentials provider fails to authenticate" in {
        val credentials = Credentials(account.name, "pass")

        val credentialsProvider = mock[CredentialsProvider]
        credentialsProvider.authenticate(credentials) returns Future.failed(new InvalidPasswordException("foo"))

        SecurityService(configWithAccounts(List(account)), credentialsProvider, identityService)
          .authenticate(credentials) must beNone.await
      }

      "succeed if the number of failed logins is equal to the allowed ones" in {
        val credentials = Credentials(account.name, "pass")
        val failedCredentials = credentials.copy(password = "foo")
        val login = LoginInfo(CredentialsProvider.ID, credentials.identifier)

        val credentialsProvider = mock[CredentialsProvider]
        credentialsProvider.authenticate(failedCredentials) returns Future.failed(new InvalidPasswordException("foo"))
        credentialsProvider.authenticate(credentials) returns Future.successful(login)

        val service = SecurityService(configWithAccounts(List(account)), credentialsProvider, identityService)
        val failedAttempts = for (attemptNo <- 1 to service.allowedFailedLogins) {
          service.authenticate(failedCredentials) must beNone.await
        }
        service.authenticate(credentials) must beSome(login).await
      }

      "fail if the number of failed logins is greater than the allowed number" in {
        val credentials = Credentials(account.name, "password")
        val failedCredentials = credentials.copy(password = "foo")
        val login = LoginInfo(CredentialsProvider.ID, credentials.identifier)

        val credentialsProvider = mock[CredentialsProvider]
        credentialsProvider.authenticate(failedCredentials) returns Future.failed(new InvalidPasswordException("foo"))
        credentialsProvider.authenticate(credentials) returns Future.successful(login)

        val service = SecurityService(configWithAccounts(List(account)), credentialsProvider, identityService)
        val failedAttempts = for (attemptNo <- 0 to service.allowedFailedLogins) {
          service.authenticate(failedCredentials) must beNone.await
        }
        service.authenticate(credentials) must beNone.await
      }

    }
} 
Example 6
Source File: LoggingSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli

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

import scala.util.matching.Regex

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

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

    def log(message: String): Unit
  }

  "logging the execution time" should {

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

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

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

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

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

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

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

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

} 
Example 7
Source File: HatDataStatsProcessorSpec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service.monitoring

import java.util.UUID

import akka.stream.Materializer
import com.google.inject.AbstractModule
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.models.{ EndpointData, Owner }
import org.hatdex.hat.api.service.applications.{ TestApplicationProvider, TrustedApplicationProvider }
import org.hatdex.hat.api.service.monitoring.HatDataEventBus.DataCreatedEvent
import org.hatdex.hat.authentication.models.HatUser
import org.hatdex.hat.dal.ModelTranslation
import org.hatdex.hat.resourceManagement.FakeHatConfiguration
import org.joda.time.DateTime
import org.specs2.mock.Mockito
import org.specs2.specification.Scope
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{ JsValue, Json }
import play.api.test.PlaySpecification
import play.api.{ Application, Logger }

class HatDataStatsProcessorSpec extends PlaySpecification with Mockito with HatDataStatsProcessorContext {

  val logger = Logger(this.getClass)

  sequential

  "The `computeInboundStats` method" should {
    "Correctly count numbers of values for simple objects" in {
      val service = application.injector.instanceOf[HatDataStatsProcessor]
      val stats = service.computeInboundStats(simpleDataCreatedEvent)

      import org.hatdex.hat.api.json.DataStatsFormat._
      logger.debug(s"Got back stats: ${Json.prettyPrint(Json.toJson(stats))}")

      stats.logEntry must be equalTo "test item"
      stats.statsType must be equalTo "inbound"
      stats.stats.length must be equalTo 1
      val endpointStats = stats.stats.head
      endpointStats.endpoint must be equalTo "testendpoint"

      endpointStats.propertyStats("field") must equalTo(1)
      endpointStats.propertyStats("date") must equalTo(1)
      endpointStats.propertyStats("date_iso") must equalTo(1)
      endpointStats.propertyStats("anotherField") must equalTo(1)
      endpointStats.propertyStats("object.objectField") must equalTo(1)
      endpointStats.propertyStats("object.objectFieldArray[]") must equalTo(3)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName") must equalTo(2)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName2") must equalTo(2)
    }
  }

}

trait HatDataStatsProcessorContext extends Scope {
  import scala.concurrent.ExecutionContext.Implicits.global
  // Setup default users for testing
  val owner = HatUser(UUID.randomUUID(), "hatuser", Some("pa55w0rd"), "hatuser", Seq(Owner()), enabled = true)

  class ExtrasModule extends AbstractModule with ScalaModule {
    override def configure(): Unit = {
      bind[TrustedApplicationProvider].toInstance(new TestApplicationProvider(Seq()))
    }
  }

  lazy val application: Application = new GuiceApplicationBuilder()
    .configure(FakeHatConfiguration.config)
    .overrides(new ExtrasModule)
    .build()

  implicit lazy val materializer: Materializer = application.materializer

  val simpleJson: JsValue = Json.parse(
    """
      | {
      |   "field": "value",
      |   "date": 1492699047,
      |   "date_iso": "2017-04-20T14:37:27+00:00",
      |   "anotherField": "anotherFieldValue",
      |   "object": {
      |     "objectField": "objectFieldValue",
      |     "objectFieldArray": ["objectFieldArray1", "objectFieldArray2", "objectFieldArray3"],
      |     "objectFieldObjectArray": [
      |       {"subObjectName": "subObject1", "subObjectName2": "subObject1-2"},
      |       {"subObjectName": "subObject2", "subObjectName2": "subObject2-2"}
      |     ]
      |   }
      | }
    """.stripMargin)

  val simpleDataCreatedEvent = DataCreatedEvent(
    "testhat.hubofallthings.net",
    ModelTranslation.fromInternalModel(owner).clean,
    DateTime.now(), "test item",
    Seq(
      EndpointData("testendpoint", Option(UUID.randomUUID()), None, None, simpleJson, None)))
} 
Example 8
Source File: FileManagerS3Spec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service

import org.hatdex.hat.api.HATTestContext
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import play.api.Logger
import play.api.test.PlaySpecification

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

class FileManagerS3Spec(implicit ee: ExecutionEnv) extends PlaySpecification with Mockito with FileManagerContext {

  val logger = Logger(this.getClass)

  sequential

  "The `getUploadUrl` method" should {
    "return a signed url for a provided key" in {
      val fileManager = application.injector.instanceOf[FileManager]
      val result: Future[String] = fileManager.getUploadUrl("testFile", None)

      result must startWith("https://hat-storage-test.s3.eu-west-1.amazonaws.com/hat.hubofallthings.net/testFile").await
    }
  }

  "The `getContentUrl` method" should {
    "return a signed url for a provided key" in {
      val fileManager = application.injector.instanceOf[FileManager]
      val result: Future[String] = fileManager.getContentUrl("testFile")

      result must startWith("https://hat-storage-test.s3.eu-west-1.amazonaws.com/hat.hubofallthings.net/testFile").await
    }
  }

  "The `deleteContents` method" should {
    "return quietly when deleting any file" in {
      val fileManager = application.injector.instanceOf[FileManager]
      val result: Future[Unit] = fileManager.deleteContents("deleteFile")

      result must not(throwAn[Exception]).await
      there was one(mockS3client).deleteObject("hat-storage-test", "hat.hubofallthings.net/deleteFile")
    }
  }

  "The `getFileSize` method" should {
    "return 0 for files that do not exist" in {
      val fileManager = application.injector.instanceOf[FileManager]
      val result: Future[Long] = fileManager.getFileSize("nonExistentFile")

      result must equalTo(0L).await(3, 10.seconds)
    }

    "extract file size for files that do exist" in {
      val fileManager = application.injector.instanceOf[FileManager]
      val result: Future[Long] = fileManager.getFileSize("testFile")

      result must equalTo(123456L).await
      there was one(mockS3client).getObjectMetadata("hat-storage-test", "hat.hubofallthings.net/testFile")
    }
  }
}

trait FileManagerContext extends HATTestContext {
  val mockS3client = fileManagerS3Mock.mockS3client
} 
Example 9
Source File: FileManagerS3Mock.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service

import com.amazonaws.auth.{ AWSStaticCredentialsProvider, BasicAWSCredentials }
import com.amazonaws.services.s3.model.ObjectMetadata
import com.amazonaws.services.s3.{ AmazonS3, AmazonS3ClientBuilder }
import org.specs2.mock.Mockito

import scala.concurrent.duration._

case class FileManagerS3Mock() extends Mockito {
  val s3Configuration = AwsS3Configuration("hat-storage-test", "testAwsAccessKey", "testAwsSecret", "eu-west-1", 5.minutes)
  private val awsCreds: BasicAWSCredentials = new BasicAWSCredentials(s3Configuration.accessKeyId, s3Configuration.secretKey)
  val mockS3client: AmazonS3 = spy(AmazonS3ClientBuilder.standard()
    .withRegion("eu-west-1")
    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
    .build())

  private val s3ObjectMetadata = new ObjectMetadata()
  s3ObjectMetadata.setContentLength(123456L)
  doReturn(s3ObjectMetadata).when(mockS3client).getObjectMetadata("hat-storage-test", "hat.hubofallthings.net/testFile")
  doNothing.when(mockS3client).deleteObject("hat-storage-test", "hat.hubofallthings.net/deleteFile")
} 
Example 10
Source File: DirectoryTemplateSourceSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.templates

import java.nio.file.{FileSystems, Files, Path}

import de.frosner.broccoli.models._
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.mockito.Mockito._

import scala.io.Source

class DirectoryTemplateSourceSpec extends Specification with TemporaryTemplatesContext with Mockito {
  "Loading templates from a directory" should {

    def templateRenderer: TemplateRenderer = {
      val templateRenderer = mock[TemplateRenderer]
      when(templateRenderer.validateParameterName(anyString)).thenReturn(true)
      templateRenderer
    }

    "fail if the passed directory is not directory" in {
      val directory = FileSystems.getDefault.getPath("not-a-directory")
      Files.exists(directory) must beFalse
      new DirectoryTemplateSource(directory.toString, mock[TemplateRenderer]).loadTemplates must throwA(
        new IllegalStateException(s"Templates directory ${directory.toAbsolutePath} is not a directory"))
    }

    "parse fully specified templates correctly" in { templatesDirectory: Path =>
      val templates =
        new DirectoryTemplateSource(templatesDirectory.toString, templateRenderer).loadTemplates()
      templates must contain(
        beEqualTo(Template(
          "curl",
          Source.fromFile(templatesDirectory.resolve("curl/template.json").toFile).mkString,
          "A periodic job that sends an HTTP GET request to a specified address every minute.",
          Map(
            "id" -> ParameterInfo("id", None, None, None, ParameterType.Raw, Some(0)),
            "URL" -> ParameterInfo("URL",
                                   None,
                                   Some(RawParameterValue("localhost:8000")),
                                   None,
                                   ParameterType.Raw,
                                   Some(1)),
            "enabled" -> ParameterInfo("enabled",
                                       None,
                                       Some(RawParameterValue("true")),
                                       None,
                                       ParameterType.Raw,
                                       Some(2))
          )
        ))).exactly(1)
    }

    "use a default template description if not provided" in { templatesDirectory: Path =>
      val templates =
        new DirectoryTemplateSource(templatesDirectory.toString, templateRenderer).loadTemplates()
      templates.map(_.description) must contain(beEqualTo("curl-without-decription template")).exactly(1)
    }

    "not contain templates that failed to parse" in { templatesDirectory: Path =>
      val templates =
        new DirectoryTemplateSource(templatesDirectory.toString, templateRenderer).loadTemplates()

      templates.map(_.id) must not contain beEqualTo("broken-template")
    }

  }
} 
Example 11
Source File: UserSyncTaskSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package tasks

import cats.effect.IO
import controllers.{Authenticator, UserAccountAccessor}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import vinyldns.core.domain.membership._

class UserSyncTaskSpec extends Specification with Mockito {
  val notAuthUser: User = User("not-authorized", "accessKey", "secretKey")
  val lockedNotAuthUser: User = notAuthUser.copy(lockStatus = LockStatus.Locked)
  val mockAuthenticator: Authenticator = {
    val mockObject = mock[Authenticator]
    mockObject.getUsersNotInLdap(List(notAuthUser)).returns(IO(List(notAuthUser)))
    mockObject
  }

  val mockUserAccountAccessor: UserAccountAccessor = {
    val mockObject = mock[UserAccountAccessor]
    mockObject.getAllUsers.returns(IO(List(notAuthUser)))
    mockObject
      .lockUsers(List(notAuthUser))
      .returns(IO(List(lockedNotAuthUser)))
    mockObject
  }

  "SyncUserTask" should {
    "successfully lock unauthorized, non-test users" in {
      new UserSyncTask(mockUserAccountAccessor, mockAuthenticator)
        .run()
        .unsafeRunSync() must beEqualTo(())

      there.was(one(mockUserAccountAccessor).lockUsers(List(notAuthUser)))
    }

    "successfully process if no users are found" in {
      val mockAuth: Authenticator = mock[Authenticator]
      mockAuth.getUsersNotInLdap(List(notAuthUser)).returns(IO(Nil))

      val mockUsers = mock[UserAccountAccessor]
      mockUsers
        .lockUsers(Nil)
        .returns(IO(Nil))

      mockUsers.getAllUsers.returns(IO(List(notAuthUser)))

      new UserSyncTask(mockUsers, mockAuth)
        .run()
        .unsafeRunSync() must beEqualTo(())
    }
  }
} 
Example 12
Source File: MetaSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package models
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import play.api.Configuration

class MetaSpec extends Specification with Mockito {
  "Meta" should {
    "load from config" in {
      val config = Map("vinyldns.version" -> "foo-bar")
      Meta(Configuration.from(config)).version must beEqualTo("foo-bar")
    }
    "default to false if shared-display-enabled is not found" in {
      val config = Map("vinyldns.version" -> "foo-bar")
      Meta(Configuration.from(config)).sharedDisplayEnabled must beFalse
    }
    "set to true if shared-display-enabled is true in config" in {
      val config = Map("shared-display-enabled" -> true)
      Meta(Configuration.from(config)).sharedDisplayEnabled must beTrue
    }
    "get the batch-change-limit value in config" in {
      val config = Map("batch-change-limit" -> 21)
      Meta(Configuration.from(config)).batchChangeLimit must beEqualTo(21)
    }
    "default to 1000 if batch-change-limit is not found" in {
      val config = Map("vinyldns.version" -> "foo-bar")
      Meta(Configuration.from(config)).batchChangeLimit must beEqualTo(1000)
    }
    "get the default-ttl value in config" in {
      val config = Map("default-ttl" -> 7210)
      Meta(Configuration.from(config)).defaultTtl must beEqualTo(7210)
    }
    "default to 7200 if default-ttl is not found" in {
      val config = Map("vinyldns.version" -> "foo-bar")
      Meta(Configuration.from(config)).defaultTtl must beEqualTo(7200)
    }
    "default to false if manual-batch-review-enabled is not found" in {
      val config = Map("vinyldns.version" -> "foo-bar")
      Meta(Configuration.from(config)).manualBatchChangeReviewEnabled must beFalse
    }
    "set to true if manual-batch-review-enabled is true in config" in {
      val config = Map("manual-batch-review-enabled" -> true)
      Meta(Configuration.from(config)).manualBatchChangeReviewEnabled must beTrue
    }
    "default to false if scheduled-batch-change-enabled is not found" in {
      val config = Map("vinyldns.version" -> "foo-bar")
      Meta(Configuration.from(config)).scheduledBatchChangesEnabled must beFalse
    }
    "set to true if scheduled-batch-change-enabled is true in config" in {
      val config = Map("scheduled-changes-enabled" -> true)
      Meta(Configuration.from(config)).scheduledBatchChangesEnabled must beTrue
    }
  }
} 
Example 13
Source File: CustomLinksSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package models

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import play.api.Configuration

class CustomLinksSpec extends Specification with Mockito {
  "CustomLinks" should {
    "load link from config" in {
      val linkOne = CustomLink(false, true, "title 1", "href 1", "icon 1")
      val config = Map(
        "links" -> List(
          Map(
            "displayOnSidebar" -> linkOne.displayOnSidebar,
            "displayOnLoginScreen" -> linkOne.displayOnLoginScreen,
            "title" -> linkOne.title,
            "href" -> linkOne.href,
            "icon" -> linkOne.icon
          )
        )
      )
      val customLinks = CustomLinks(Configuration.from(config))
      customLinks.links must beEqualTo(List[CustomLink](linkOne))
    }

    "load multiple links from config" in {
      val linkOne = CustomLink(false, true, "title 1", "href 1", "icon 1")
      val linkTwo = CustomLink(true, false, "title 2", "href 2", "icon 2")
      val config = Map(
        "links" -> List(
          Map(
            "displayOnSidebar" -> linkOne.displayOnSidebar,
            "displayOnLoginScreen" -> linkOne.displayOnLoginScreen,
            "title" -> linkOne.title,
            "href" -> linkOne.href,
            "icon" -> linkOne.icon
          ),
          Map(
            "displayOnSidebar" -> linkTwo.displayOnSidebar,
            "displayOnLoginScreen" -> linkTwo.displayOnLoginScreen,
            "title" -> linkTwo.title,
            "href" -> linkTwo.href,
            "icon" -> linkTwo.icon
          )
        )
      )
      val customLinks = CustomLinks(Configuration.from(config))
      customLinks.links must beEqualTo(List[CustomLink](linkOne, linkTwo))
    }

    "load empty list if no links in config" in {
      val customLinks = CustomLinks(Configuration.from(Map()))
      customLinks.links must beEqualTo(List[CustomLink]())
    }
  }
} 
Example 14
Source File: UserAccountAccessorSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package controllers

import cats.effect.IO
import org.joda.time.DateTime
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.BeforeEach
import vinyldns.core.domain.membership._

class UserAccountAccessorSpec extends Specification with Mockito with BeforeEach {

  private val user = User(
    "fbaggins",
    "key",
    "secret",
    Some("Frodo"),
    Some("Baggins"),
    Some("[email protected]"),
    DateTime.now,
    "frodo-uuid"
  )

  private val userLog = UserChange(
    "frodo-uuid",
    user,
    "fbaggins",
    DateTime.now,
    None,
    UserChangeType.Create
  ).toOption.get

  private val mockRepo = mock[UserRepository]
  private val mockChangeRepo = mock[UserChangeRepository]
  private val underTest = new UserAccountAccessor(mockRepo, mockChangeRepo)

  protected def before: Any =
    org.mockito.Mockito.reset(mockRepo, mockChangeRepo)

  "UserAccountAccessor" should {
    "return the user when storing a user that does not exist already" in {
      mockRepo.save(any[User]).returns(IO.pure(user))
      mockChangeRepo.save(any[UserChange]).returns(IO.pure(userLog))
      underTest.create(user).unsafeRunSync() must beEqualTo(user)
      there.was(one(mockChangeRepo).save(any[UserChange]))
    }

    "return the new user when storing a user that already exists in the store" in {
      val newUser = user.copy(accessKey = "new-key", secretKey = "new-secret")
      mockRepo.save(any[User]).returns(IO.pure(newUser))
      mockChangeRepo.save(any[UserChange]).returns(IO.pure(userLog))
      underTest.update(newUser, user).unsafeRunSync() must beEqualTo(newUser)
      there.was(one(mockChangeRepo).save(any[UserChange]))
    }

    "return the user when retrieving a user that exists by name" in {
      mockRepo.getUserByName(user.userName).returns(IO.pure(Some(user)))
      mockRepo.getUser(user.userName).returns(IO.pure(None))
      underTest.get("fbaggins").unsafeRunSync() must beSome(user)
    }

    "return the user when retrieving a user that exists by user ID" in {
      mockRepo.getUserByName(user.id).returns(IO.pure(None))
      mockRepo.getUser(user.id).returns(IO.pure(Some(user)))
      underTest.get(user.id).unsafeRunSync() must beSome(user)
    }

    "return None when the user to be retrieved does not exist" in {
      mockRepo.getUserByName(any[String]).returns(IO.pure(None))
      mockRepo.getUser(any[String]).returns(IO.pure(None))
      underTest.get("fbaggins").unsafeRunSync() must beNone
    }

    "return the user by access key" in {
      mockRepo.getUserByAccessKey(user.id).returns(IO.pure(Some(user)))
      underTest.getUserByKey(user.id).unsafeRunSync() must beSome(user)
    }

    "return all users" in {
      val userList = List(user, user.copy(id = "user2", userName = "user2"))
      mockRepo.getAllUsers.returns(IO.pure(userList))
      underTest.getAllUsers.unsafeRunSync() must beEqualTo(userList)
    }

    "lock specified users" in {
      val lockedUser = user.copy(lockStatus = LockStatus.Locked)
      val lockedUserChange = UserChange.UpdateUser(
        user.copy(lockStatus = LockStatus.Locked),
        "system",
        DateTime.now,
        user
      )
      mockRepo.save(List(lockedUser)).returns(IO(List(lockedUser)))
      mockChangeRepo.save(any[UserChange]).returns(IO(lockedUserChange))
      underTest.lockUsers(List(user)).unsafeRunSync() must beEqualTo(List(lockedUser))
    }
  }
} 
Example 15
Source File: DogStatsDReporterSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.metrics.reporting

import java.util.concurrent.TimeUnit

import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support
import com.typesafe.config.ConfigFactory
import org.coursera.metrics.datadog.transport.Transport
import org.specs2.mock.Mockito
import org.specs2.mutable.SpecificationLike

import scala.concurrent.duration.{FiniteDuration, _}

class DogStatsDReporterSpec extends AkkaTestkitSpecs2Support with SpecificationLike with Mockito {

  "The DatadogReporter reporter" should {

    "report metrics when triggered by the scheduler" in {

      implicit val conf = ConfigFactory.parseString(
        """
         {
          enabled=on
          host="localhost"
          port=8125
          reporting-interval=10ms
          metric-prefix = "pref"
          tags = ["boo", "hoo"]
          api-key = "abc123"
        }
        """)

      val dogStatsDReporter = spy(new DogStatsDReporter)

      val transport = mock[Transport]
      dogStatsDReporter.getTransport returns transport

      val rptr = mock[org.coursera.metrics.datadog.DatadogReporter]
      dogStatsDReporter.getReporter returns rptr

      dogStatsDReporter.start(FiniteDuration(2, TimeUnit.MILLISECONDS))
      there was after(100.millisecond).atLeastOne(dogStatsDReporter).report()

      dogStatsDReporter.tags must containAllOf(Seq("boo", "hoo", "app:container-service", "version:1.0.0.N/A"))
      dogStatsDReporter.prefix must be equalTo "pref"

      dogStatsDReporter.stop
      there was one(transport).close()
    }
  }

} 
Example 16
Source File: StatsDReporterSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.metrics.reporting

import java.util.concurrent.TimeUnit

import com.github.jjagged.metrics.reporting.statsd.StatsD
import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support
import com.typesafe.config.ConfigFactory
import org.specs2.mock.Mockito
import org.specs2.mutable.SpecificationLike

import scala.concurrent.duration._


class StatsDReporterSpec extends AkkaTestkitSpecs2Support with SpecificationLike with Mockito {

  "The StatsDReporter reporter" should {

    "report metrics when triggered by the scheduler" in {

      implicit val conf = ConfigFactory.parseString(
        """
         {
          enabled=on
          reporting-interval=10ms
          host="localhost"
          port=9092
          metric-prefix = "pref"
        }
        """)

      val statsdReporter = spy(new StatsDReporter)
      val statsD = mock[StatsD]
      statsdReporter.getStatsD returns statsD

      val rptr = mock[com.github.jjagged.metrics.reporting.StatsDReporter]
      statsdReporter.getReporter returns rptr

      statsdReporter.start(FiniteDuration(2, TimeUnit.MILLISECONDS))
      there was after(100.millisecond).atLeastOne(statsdReporter).report()

      statsdReporter.stop
      there was one(statsD).close()
    }
  }

} 
Example 17
Source File: ConfigurationDetectorSpec.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.util

import com.typesafe.config.{Config, ConfigException}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

class ConfigurationDetectorSpec extends Specification with Mockito {

  val myConfigFromEnvVar = "my-configuration-from-env-var"
  val myConfigFromFile = "my-configuration-from-file"

  abstract class ConfigurationDetectorSpecContext extends Scope {
    def config = mock[Config]

    val variableName = "MY-CONFIG"
    val configName = "my.config"
  }

  trait NoEnvVariable extends ConfigurationDetector {
    override protected def environmentVariable(name: String) = None
  }

  trait WithEnvVariable extends ConfigurationDetector {
    override protected def environmentVariable(name: String) = Some(myConfigFromEnvVar)
  }

  trait NoConfigFromFile extends ConfigurationDetector {
    override protected def configuration(path: String) = throw new ConfigException.Missing(path)
  }

  trait WithConfigFromFile extends ConfigurationDetector {
    override protected def configuration(path: String) = myConfigFromFile
  }

  "ConfigurationDetector" should {

    "if environment variable exists" in {

      "if configuration from file does not exists" in {
        "detect the configuration from the environment variable" in
          new ConfigurationDetectorSpecContext with WithEnvVariable with NoConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromEnvVar
          }
      }

      "if configuration from file exists" in {
        "detect the configuration from the environment variable" in
          new ConfigurationDetectorSpecContext with WithEnvVariable with WithConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromEnvVar
          }
      }
    }

    "if environment variable does not exist" in {

      "if configuration from file exists" in {
        "detect the configuration from the configuration file" in
          new ConfigurationDetectorSpecContext with NoEnvVariable with WithConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromFile
          }
      }

      "if configuration from file does not exist" in {
        "throw an exception" in
          new ConfigurationDetectorSpecContext with NoEnvVariable with NoConfigFromFile {
            envVarOrConfig(variableName, configName) must throwA[RuntimeException]
          }
      }
    }
  }
} 
Example 18
Source File: FlickrClientSpec.scala    From scalando   with MIT License 5 votes vote down vote up
package com.jcranky.flickr

import com.jcranky.flickr.FlickrClient.ClientError
import com.jcranky.flickr.HttpClient.{GetError, GetResponse}
import com.jcranky.flickr.model.Foto
import com.typesafe.config.{ConfigException, ConfigFactory}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

class FlickrClientSpec extends Specification with Mockito {
  "FlickrClient.fromConfig" should {
    "work with valid configuration" in {
      val client = FlickrClient.fromConfig(ConfigFactory.load("app-test.conf"))
      client !=== null
    }

    "fail if some configuration is missing" in {
      FlickrClient.fromConfig(ConfigFactory.load("acre.conf")) should throwAn[ConfigException]
    }
  }

  "FlickrClient.buscaFotos" should {
    "ask the httpclient for the photos and pass the response to the response parser" in {
      val fotos = List(Foto("1", "jcranky", "123", "321", 1, "my pic", true, false, false))
      val resp = buscaFotos(
        Right(GetResponse(200, "fotos-xml-here")),
        Right(fotos)
      )

      resp should beRight(fotos)
    }

    "return a client error if the parser returns a FlickrError" in {
      val error = FlickrKnownError(100, "Invalid API Key (Key has invalid format)")
      val resp = buscaFotos(
        Right(GetResponse(200, "error-xml-here")),
        Left(error)
      )

      resp should beLeft(ClientError(error.toString))
    }
  }

  
  def buscaFotos(httpResp: Either[GetError, GetResponse], parsed: Either[FlickrError, Seq[Foto]]): Either[ClientError, Seq[Foto]] = {
    val httpClient = mock[HttpClient]
    val parser = mock[ResponseParser]

    httpClient.get(any[String]) returns httpResp
    parser.parse(any[String]) returns parsed

    val client = new FlickrClient("api-key", "base-url", httpClient, parser)
    val resp = client.buscaFotos(List("scala"))

    there was one(httpClient).get(anyString)

    resp
  }
} 
Example 19
Source File: BroccoliMessageHandlerSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.websocket

import cats.data.EitherT
import cats.instances.future._
import de.frosner.broccoli.auth.Account
import de.frosner.broccoli.instances.NomadInstances
import de.frosner.broccoli.models._
import de.frosner.broccoli.nomad
import de.frosner.broccoli.services.InstanceService
import org.scalacheck.Gen
import org.specs2.ScalaCheck
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

import scala.concurrent.Future

class BroccoliMessageHandlerSpec
    extends Specification
    with ScalaCheck
    with Mockito
    with nomad.ModelArbitraries
    with ModelArbitraries {

  "The Broccoli Message Handler" should {
    "send back instance tasks" in { implicit ee: ExecutionEnv =>
      prop {
        (account: Account,
         id: String,
         tasks: List[AllocatedTask],
         periodicRunTasks: Map[String, List[AllocatedTask]]) =>
          val instances = mock[NomadInstances]
          val instanceTasks = InstanceTasks(id, tasks, periodicRunTasks)
          instances.getInstanceTasks(account)(id) returns EitherT.pure[Future, InstanceError](instanceTasks)

          val outgoingMessage = new BroccoliMessageHandler(instances, mock[InstanceService])
            .processMessage(account)(IncomingMessage.GetInstanceTasks(id))

          outgoingMessage must beEqualTo(OutgoingMessage.GetInstanceTasksSuccess(instanceTasks)).await
      }.setGen2(Gen.identifier)
    }

    "send back an error if instance tasks failed" in { implicit ee: ExecutionEnv =>
      prop { (account: Account, id: String, error: InstanceError) =>
        val instances = mock[NomadInstances]
        instances.getInstanceTasks(account)(id) returns EitherT.leftT[Future, InstanceTasks](error)

        val outgoingMessage = new BroccoliMessageHandler(instances, mock[InstanceService])
          .processMessage(account)(IncomingMessage.GetInstanceTasks(id))

        outgoingMessage must beEqualTo(OutgoingMessage.GetInstanceTasksError(id, error)).await
      }.setGen2(Gen.identifier)
    }
  }
} 
Example 20
Source File: PrettyPrinterSpec.scala    From random-data-generator   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.randomdatagenerator.utils

import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.specification.Scope
import scala.collection.mutable.ListBuffer

class PrettyPrinterSpec extends SpecificationLike with Mockito {

  abstract class PrettyPrinterSpecContext extends Scope {
    val logs: ListBuffer[String] = new ListBuffer
    private def append(log: String): Unit = synchronized { logs += log; () }

    val printer = {
      val mockPrintF = (log: String) => append(log)
      new PrettyPrinter(mockPrintF)
    }
  }

  "PrettyPrinter" should {

    "print an info message" in new PrettyPrinterSpecContext {
      val msg = "This is my info message"
      printer.info(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[info] [RandomDataGenerator] $msg")
    }

    "print an warning message" in new PrettyPrinterSpecContext {
      val msg = "This is my warning message"
      printer.warning(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[warn] [RandomDataGenerator] $msg")
    }

    "print an error message" in new PrettyPrinterSpecContext {
      val msg = "This is my error message"
      printer.error(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[error] [RandomDataGenerator] $msg")
    }

    "print an debug message" in new PrettyPrinterSpecContext {
      val msg = "This is my debug message"
      printer.debug(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[debug] [RandomDataGenerator] $msg")
    }
  }

} 
Example 21
Source File: SeedDetectorSpec.scala    From random-data-generator   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.randomdatagenerator.utils

import org.scalacheck.rng.Seed
import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.specification.Scope

class SeedDetectorSpec extends SpecificationLike with Mockito {

  abstract class SeedDetectorSpecContext extends Scope {
    val myRandomLong = scala.util.Random.nextLong

    def buildSeedDetector(myEnvVariable: Option[String]) = new SeedDetector {
      override protected lazy val envVariable = myEnvVariable
      override protected def randomLong = myRandomLong
    }
  }

  "SeedDetector" should {

    "when RANDOM_DATA_GENERATOR_SEED is not defined" should {
      "randomly select a seed value" in new SeedDetectorSpecContext {
        val seedDetector = buildSeedDetector(myEnvVariable = None)
        seedDetector.seed === Seed(myRandomLong)
      }
    }

    "when RANDOM_DATA_GENERATOR_SEED is defined" should {
      "set seed to the variable value" in new SeedDetectorSpecContext {
        val mySeed = "1234567"
        val seedDetector = buildSeedDetector(myEnvVariable = Some(mySeed))
        seedDetector.seed === Seed(mySeed.toLong)
      }

      "throw exception if the variable value is not numeric" in new SeedDetectorSpecContext {
        val mySeed = "not-a-valid-value"
        val seedDetector = buildSeedDetector(myEnvVariable = Some(mySeed))
        seedDetector.seed should throwA[RuntimeException]
      }
    }
  }

} 
Example 22
Source File: ResultsSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._
import org.specs2.mock.Mockito
import roc.postgresql.failures.ElementNotFoundFailure

final class ResultsSpec extends Specification with ScalaCheck with Mockito { def is = s2"""

  Row
    get(column) must throw ElementNotFound failure for unknown column name  $columnNotFound
                                                                           """

  val columnNotFound = forAll { sym: Symbol =>
    val row = new Row(List.empty[Element])
    row.get(sym) must throwA[ElementNotFoundFailure]
  }

  lazy val genSymbol: Gen[Symbol] = for {
    str <-  arbitrary[String]
  } yield Symbol(str)
  implicit lazy val arbitrarySymbol: Arbitrary[Symbol] =
    Arbitrary(genSymbol)
} 
Example 23
Source File: JavaPSourceFileTracerTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.analyze.jdk

import java.nio.file.{FileSystem, Files, Path}

import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder
import com.wix.bazel.migrator.model.SourceModule
import com.wix.bazel.migrator.model.makers.ModuleMaker._
import org.specs2.matcher.Scope
import org.specs2.mock.Mockito
import org.specs2.mutable.SpecificationWithJUnit
import com.wix.bazel.migrator.analyze.CodePath

class JavaPSourceFileTracerTest extends SpecificationWithJUnit with Mockito {
  "JavaPSourceFileTracerTest" should {
    "return the location of source file given it exists on filesystem" in new ctx{
      override def relativeSourcePath: String = "src/main/java"

      private val file: Path = fullPathToSourceFile
      Files.createDirectories(file.getParent)
      Files.createFile(file)

      processRunner.run(repoRoot,"javap",List("-cp",pathToClasses,fqn)) returns RunResult(
        exitCode = 0,
        stdOut = s"""Compiled from "${className}.$fileType"
                   |dontcare
                   |dontcare
                   |""".stripMargin,
        stdErr = ""
      )
      val res = tracer.traceSourceFile(module,fqn = fqn,pathToClasses = pathToClasses, testClass = false)

      res mustEqual CodePath(module,relativeSourcePath,filePath)
    }
  }

  trait ctx extends Scope{
    val fileSystem: FileSystem = MemoryFileSystemBuilder.newLinux().build()
    val repoRoot: Path = fileSystem.getPath("/")
    val moduleName = "foo"
    val module: SourceModule = aModule(moduleName)
    def relativeSourcePath:String
    val javaPackage = "com.wix.example"
    val className = "Example"
    val fileType = "java"
    val filePath = javaPackage.replace('.','/') + s"/$className.$fileType"
    def fullPathToSourceFile: Path = repoRoot.resolve(module.relativePathFromMonoRepoRoot).resolve(relativeSourcePath).resolve(filePath)
    val processRunner: ProcessRunner = mock[ProcessRunner]
    val tracer = new JavaPSourceFileTracer(repoRoot,processRunner,fileSystem)
    val pathToClasses: String = moduleName + "target/classes"
    val fqn = s"$javaPackage.$className"

  }

} 
Example 24
Source File: JsonRequestSpec.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws.ahc

import java.nio.charset.StandardCharsets

import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.util.ByteString
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.when
import org.specs2.mock.Mockito

import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.api.libs.json.JsString
import play.api.libs.json.JsValue
import play.api.libs.json.Json
import play.api.libs.ws.JsonBodyReadables
import play.api.libs.ws.JsonBodyWritables
import play.libs.ws.DefaultObjectMapper
import play.shaded.ahc.org.asynchttpclient.Response

import scala.io.Codec


class JsonRequestSpec extends Specification with Mockito with AfterAll with JsonBodyWritables {
  sequential

  implicit val system       = ActorSystem()
  implicit val materializer = Materializer.matFromSystem

  override def afterAll: Unit = {
    system.terminate()
  }

  "set a json node" in {
    val jsValue = Json.obj("k1" -> JsString("v1"))
    val client  = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(jsValue)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("application/json")
    ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
  }

  "set a json node using the default object mapper" in {
    val objectMapper = DefaultObjectMapper.instance

    implicit val jsonReadable = body(objectMapper)
    val jsonNode              = objectMapper.readTree("""{"k1":"v1"}""")
    val client                = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(jsonNode)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("application/json")
    ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
  }

  "read an encoding of UTF-8" in {
    val json = io.Source.fromResource("test.json")(Codec.ISO8859).getLines.mkString

    val ahcResponse = mock[Response]
    val response    = new StandaloneAhcWSResponse(ahcResponse)

    when(ahcResponse.getResponseBody(StandardCharsets.UTF_8)).thenReturn(json)
    when(ahcResponse.getContentType).thenReturn("application/json")

    val value: JsValue = JsonBodyReadables.readableAsJson.transform(response)
    verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.UTF_8)
    verify(ahcResponse, times(1)).getContentType
    value.toString must beEqualTo(json)
  }

  "read an encoding of ISO-8859-1" in {
    val json = io.Source.fromResource("test.json")(Codec.ISO8859).getLines.mkString

    val ahcResponse = mock[Response]
    val response    = new StandaloneAhcWSResponse(ahcResponse)

    when(ahcResponse.getResponseBody(StandardCharsets.ISO_8859_1)).thenReturn(json)
    when(ahcResponse.getContentType).thenReturn("application/json;charset=iso-8859-1")

    val value: JsValue = JsonBodyReadables.readableAsJson.transform(response)
    verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.ISO_8859_1)
    verify(ahcResponse, times(1)).getContentType
    value.toString must beEqualTo(json)
  }
} 
Example 25
Source File: CachingSpec.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws.ahc.cache

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Route
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.FutureMatchers
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.AkkaServerProvider
import play.api.libs.ws.ahc._
import play.shaded.ahc.org.asynchttpclient._

import scala.concurrent.Future

class CachingSpec(implicit val executionEnv: ExecutionEnv)
    extends Specification
    with AkkaServerProvider
    with AfterAll
    with FutureMatchers
    with Mockito {

  val asyncHttpClient: AsyncHttpClient = {
    val config                           = AhcWSClientConfigFactory.forClientConfig()
    val ahcConfig: AsyncHttpClientConfig = new AhcConfigBuilder(config).build()
    new DefaultAsyncHttpClient(ahcConfig)
  }

  override val routes: Route = {
    import akka.http.scaladsl.server.Directives._
    path("hello") {
      respondWithHeader(RawHeader("Cache-Control", "public")) {
        val httpEntity = HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>")
        complete(httpEntity)
      }
    }
  }

  override def afterAll = {
    super.afterAll()
    asyncHttpClient.close()
  }

  "GET" should {

    "work once" in {
      val cache = mock[Cache]
      cache.get(any[EffectiveURIKey]()).returns(Future.successful(None))

      val cachingAsyncHttpClient = new CachingAsyncHttpClient(asyncHttpClient, new AhcHttpCache(cache))
      val ws                     = new StandaloneAhcWSClient(cachingAsyncHttpClient)

      ws.url(s"http://localhost:$testServerPort/hello")
        .get()
        .map { response =>
          response.body must be_==("<h1>Say hello to akka-http</h1>")
        }
        .await

      there.was(one(cache).get(EffectiveURIKey("GET", new java.net.URI(s"http://localhost:$testServerPort/hello"))))
    }
  }
} 
Example 26
Source File: AhcWSResponseSpec.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.libs.ws.ahc

import org.specs2.mock.Mockito
import org.specs2.mutable._
import play.libs.ws._
import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders
import play.shaded.ahc.org.asynchttpclient.Response

import scala.collection.JavaConverters._
import scala.compat.java8.OptionConverters._

class AhcWSResponseSpec extends Specification with Mockito with DefaultBodyReadables with DefaultBodyWritables {

  "getUnderlying" should {

    "return the underlying response" in {
      val srcResponse = mock[Response]
      val response    = new StandaloneAhcWSResponse(srcResponse)
      response.getUnderlying must_== srcResponse
    }

  }

  "get headers" should {

    "get headers map which retrieves headers case insensitively" in {
      val srcResponse = mock[Response]
      val srcHeaders = new DefaultHttpHeaders()
        .add("Foo", "a")
        .add("foo", "b")
        .add("FOO", "b")
        .add("Bar", "baz")
      srcResponse.getHeaders.returns(srcHeaders)
      val response = new StandaloneAhcWSResponse(srcResponse)
      val headers  = response.getHeaders
      headers.get("foo").asScala must_== Seq("a", "b", "b")
      headers.get("BAR").asScala must_== Seq("baz")
    }

    "get a single header" in {
      val srcResponse = mock[Response]
      val srcHeaders = new DefaultHttpHeaders()
        .add("Foo", "a")
        .add("foo", "b")
        .add("FOO", "b")
        .add("Bar", "baz")
      srcResponse.getHeaders.returns(srcHeaders)
      val response = new StandaloneAhcWSResponse(srcResponse)

      response.getSingleHeader("Foo").asScala must beSome("a")
      response.getSingleHeader("Bar").asScala must beSome("baz")
    }

    "get an empty optional when header is not present" in {
      val srcResponse = mock[Response]
      val srcHeaders = new DefaultHttpHeaders()
        .add("Foo", "a")
        .add("foo", "b")
        .add("FOO", "b")
        .add("Bar", "baz")
      srcResponse.getHeaders.returns(srcHeaders)
      val response = new StandaloneAhcWSResponse(srcResponse)

      response.getSingleHeader("Non").asScala must beNone
    }

    "get all values for a header" in {
      val srcResponse = mock[Response]
      val srcHeaders = new DefaultHttpHeaders()
        .add("Foo", "a")
        .add("foo", "b")
        .add("FOO", "b")
        .add("Bar", "baz")
      srcResponse.getHeaders.returns(srcHeaders)
      val response = new StandaloneAhcWSResponse(srcResponse)

      response.getHeaderValues("Foo").asScala must containTheSameElementsAs(Seq("a", "b", "b"))
    }
  }

  

} 
Example 27
Source File: OpenTsdbWSMock.scala    From prometheus-opentsdb-exporter   with Apache License 2.0 5 votes vote down vote up
package tools

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

import play.api.http.{HeaderNames, Writeable}
import play.api.libs.ws._
import play.api.libs.json._
import play.api.http.Status._

import org.specs2.mock.Mockito


abstract class OpenTsdbWSMock extends Mockito with WSClient {
  private val request = mock[WSRequest]
  private val response = mock[WSResponse]

  private var metrics: List[String] = List.empty

  private val urls:collection.mutable.Buffer[String] = new collection.mutable.ArrayBuffer[String]()

  request.withRequestTimeout(any[Duration]) returns request
  request.withFollowRedirects(any[Boolean]) returns request

  response.status returns OK
  response.header(HeaderNames.CONTENT_TYPE) returns Some("application/json;charset=UTF-8")
  response.json answers { _ => this.synchronized {
    val payload = responsePayload(metrics.head)
    metrics = metrics.tail
    payload
  }}

  request.post(anyString)(any[Writeable[String]]) answers { args => this.synchronized {
    val payload = args.asInstanceOf[Array[Object]](0).asInstanceOf[JsValue]
    val metric = (payload \ "queries") (0) \ "metric" match {
      case JsDefined(m) => m.toString.replace("\"", "")
      case _ => ""
    }

    metrics = metrics ++ List(metric)

    Future.successful(response)
  }}

  def url(url: String): WSRequest = {
    urls += url
    request
  }

  def underlying[T]: T = this.asInstanceOf[T]

  protected def responsePayload: Map[String, JsValue]

  override def close(): Unit = ()
} 
Example 28
Source File: CredentialsSpec.scala    From codacy-analysis-cli   with GNU Affero General Public License v3.0 5 votes vote down vote up
package com.codacy.analysis.cli.clients

import com.codacy.analysis.cli.command.APIOptions
import com.codacy.analysis.cli.configuration.Environment
import com.codacy.analysis.core.clients._
import org.specs2.control.NoLanguageFeatures
import org.specs2.matcher.FutureMatchers
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

class CredentialsSpec extends Specification with NoLanguageFeatures with Mockito with FutureMatchers {

  private val environment = new Environment(Map.empty)
  private val apiTokenStr = "RandomApiToken"
  private val projectTokenStr = "RandomProjectToken"
  private val username = "some_user"
  private val project = "some_project"

  "Credentials" should {

    "Initialize credentials" in {
      "with API Token" in {
        "with user and project name" in {
          val apiOptions = APIOptions(
            apiToken = Option(apiTokenStr),
            username = Option(UserName(username)),
            project = Option(ProjectName(project)),
            codacyApiBaseUrl = Option("codacy.com"))
          val credentials: Option[Credentials] = Credentials.get(environment, apiOptions)

          credentials must beSome[Credentials]
          credentials must beLike { case Some(token) => token must beAnInstanceOf[APIToken] }
        }

        "without user and project name" in {
          val apiOptions = APIOptions(
            apiToken = Option(apiTokenStr),
            username = None,
            project = None,
            codacyApiBaseUrl = Option("codacy.com"))
          val credentials = Credentials.get(environment, apiOptions)

          credentials must beNone
        }
      }

      "with Project Token" in {

        val apiOptions = APIOptions(projectToken = Option(projectTokenStr), codacyApiBaseUrl = Option("codacy.com"))
        val credentials = Credentials.get(environment, apiOptions)

        credentials must beSome[Credentials]
        credentials must beLike { case Some(token) => token must beAnInstanceOf[ProjectToken] }
      }
    }
  }

} 
Example 29
Source File: ThingsControllerSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

import dal.ThingsRepository
import de.leanovate.swaggercheck.playhelper._
import de.leanovate.swaggercheck.schema.model.ValidationSuccess
import models.{Thing, ThingType}
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.ScalaCheck
import org.specs2.mock.Mockito
import play.api.Application
import play.api.inject.bind
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test._
import support.{Arbitraries, ThingApi}

import scala.concurrent.Future

class ThingsControllerSpec extends PlaySpecification with ScalaCheck with ThingApi with Mockito with Arbitraries{

  "ThingController" should {
    "support all /things routes" in {
      implicit val arbitraryRequest = Arbitrary[PlayOperationVerifier](swaggerCheck.operationVerifier())
      val app = testApp()

      prop { requestVerifier: PlayOperationVerifier =>
        val Some(result) = route(app, requestVerifier.request)

        status(result) must between(200, 300)

        requestVerifier.responseVerifier.verify(result) must be equalTo ValidationSuccess
      }
    }
  }

  def testApp(): Application = {
    val mockThingsRepository = mock[ThingsRepository]

    mockThingsRepository.getPage(any[Option[ThingType.Value]], any[Int], any[Int]) answers { _ => Future.successful(Gen.nonEmptyListOf(Arbitrary.arbitrary[Thing]).sample.getOrElse(Seq.empty)) }
    mockThingsRepository.getById(any[UUID]) answers { _ => Future.successful(Arbitrary.arbitrary[Thing].sample)}

    new GuiceApplicationBuilder()
      .overrides(bind[ThingsRepository].toInstance(mockThingsRepository))
      .build()
  }
} 
Example 30
Source File: SecurityRulesRepositorySpec.scala    From play-zhewbacca   with MIT License 5 votes vote down vote up
package org.zalando.zhewbacca

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import play.api.Configuration
import play.api.test.FakeRequest

import scala.concurrent.ExecutionContext

class SecurityRulesRepositorySpec extends Specification with Mockito {

  "SecurityRulesRepository" should {

    "load rules from default file" in {
      val provider = mock[AuthProvider]
      val repository = new SecurityRulesRepository(Configuration(), provider)
      val expectedRule = ValidateTokenRule(provider, "GET", "/foo", Scope(Set("uid", "entity.read")))

      repository.get(FakeRequest("GET", "/foo")) must beSome(expectedRule)
    }

    "load rules from custom file" in {
      val provider = mock[AuthProvider]
      val config = Configuration("authorisation.rules.file" -> "security_custom-security.conf")
      val repository = new SecurityRulesRepository(config, provider)
      val expectedRule = ValidateTokenRule(provider, "POST", "/bar.*", Scope(Set("uid")))

      repository.get(FakeRequest("POST", "/bar.*")) must beSome(expectedRule)
    }

    "raise an error when custom file is not available" in {
      val authProvider = mock[AuthProvider]
      val config = Configuration("authorisation.rules.file" -> "this-file-does-not-exist.conf")

      new SecurityRulesRepository(config, authProvider) must
        throwA[RuntimeException]("configuration file this-file-does-not-exist.conf for security rules not found")
    }

    "allow comments in security rules configuration file" in {
      val provider = mock[AuthProvider]
      val config = Configuration("authorisation.rules.file" -> "security_commented.conf")
      val repository = new SecurityRulesRepository(config, provider)
      val expectedRule = ValidateTokenRule(provider, "OPTIONS", "/", Scope(Set("app.resource.read")))

      repository.get(FakeRequest("OPTIONS", "/")) must beSome(expectedRule)
    }

    "raise an error when it cannot parse a configuration file" in {
      val authProvider = mock[AuthProvider]
        def config(fileName: String): Configuration = Configuration("authorisation.rules.file" -> fileName)

      new SecurityRulesRepository(config("security_unknown-http-method.conf"), authProvider) must throwA[RuntimeException]
      new SecurityRulesRepository(config("security_no-scopes.conf"), authProvider) must throwA[RuntimeException]
    }

    "return None if there is no configured rules for given request" in {
      val authProvider = mock[AuthProvider]
      val repository = new SecurityRulesRepository(Configuration(), authProvider)

      repository.get(FakeRequest("GET", "/unknown-uri")) must beNone
    }

    "allow explicitly to pass-through or deny a request for a specific URI" in {
      val authProvider = mock[AuthProvider]
      val configuration = Configuration("authorisation.rules.file" -> "security_pass-through.conf")
      val repository = new SecurityRulesRepository(configuration, authProvider)

      repository.get(FakeRequest("GET", "/foo")).get must beAnInstanceOf[ExplicitlyAllowedRule]
      repository.get(FakeRequest("GET", "/bar")).get must beAnInstanceOf[ExplicitlyDeniedRule]
    }

  }

} 
Example 31
Source File: MarshallerTestSupport.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.drivers

import com.wix.e2e.http.api.Marshaller
import org.specs2.matcher.ThrownExpectations
import org.specs2.mock.Mockito

trait MarshallerTestSupport extends Mockito with ThrownExpectations {
  val marshaller: Marshaller = mock[Marshaller]

  def givenUnmarshallerWith[T : Manifest](someEntity: T, forContent: String): Unit =
    marshaller.unmarshall[T](forContent) returns someEntity

  def givenBadlyBehavingUnmarshallerFor[T : Manifest](withContent: String): Unit =
    marshaller.unmarshall[T](withContent) throws new RuntimeException
}

trait CustomMarshallerProvider {
  def marshaller: Marshaller
  implicit def customMarshaller: Marshaller = marshaller
} 
Example 32
Source File: NetworkSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk

import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

import scala.concurrent.duration._

class NetworkSpec(implicit ee: ExecutionEnv) extends Specification with ArbitraryInput with Mockito {

  "test network" should {
    "identify itself" >> {
      TestNetwork.passphrase mustEqual "Test SDF Network ; September 2015"
      BigInt(1, TestNetwork.networkId).toString(16).toUpperCase mustEqual
        "CEE0302D59844D32BDCA915C8203DD44B33FBB7EDC19051EA37ABEDF28ECD472"
    }

    "provide network info" >> {
      TestNetwork.info() must not(throwAn[Exception]).awaitFor(10.seconds)
    }
  }

  "public network" should {
    "identify itself" >> {
      PublicNetwork.passphrase mustEqual "Public Global Stellar Network ; September 2015"
      BigInt(1, PublicNetwork.networkId).toString(16).toUpperCase mustEqual
        "7AC33997544E3175D266BD022439B22CDB16508C01163F26E5CB2A3E1045A979"
    }
  }

  "any network" should {
    "provide access to the master account" >> {
      val networkAccountId = "GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H"
      TestNetwork.masterAccount.accountId mustEqual networkAccountId
      KeyPair.fromSecretSeed(TestNetwork.masterAccount.secretSeed).accountId  mustEqual networkAccountId
    }
  }
} 
Example 33
Source File: UnixSignalManagerIntegrationSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.signal

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import sun.misc.{Signal, SignalHandler}

class UnixSignalManagerIntegrationSpec extends Specification with Mockito {
  "Registering new signal" should {
    "trigger the handler when the signal is raised" in {
      val manager = new UnixSignalManager()
      val signal = new Signal("USR2")
      val handler = mock[SignalHandler]
      manager.register(signal, handler)
      Signal.raise(signal)
      Thread.sleep(1000)
      there was one(handler).handle(signal)
    }
  }
} 
Example 34
Source File: UnixSignalManagerSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.signal

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import sun.misc.{Signal, SignalHandler}

class UnixSignalManagerSpec extends Specification with Mockito {
  "Registering new signal" should {
    "fail if the signal is reserved by the JVM" in {
      val manager = new UnixSignalManager()
      manager.register(new Signal("USR1"), mock[SignalHandler]) must throwA(
        new IllegalArgumentException("Signal already used by VM or OS: SIGUSR1"))
    }

    "fail if the signal is already registered" in {
      val manager = new UnixSignalManager()
      val handler = mock[SignalHandler]
      manager.register(new Signal("USR2"), handler)
      manager.register(new Signal("USR2"), handler) must throwA(
        new IllegalArgumentException(s"Signal ${new Signal("USR2")} is already registered"))
    }
  }
} 
Example 35
Source File: CachedTemplateSourceSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.templates

import org.specs2.mutable.Specification
import org.mockito.Mockito._
import org.specs2.mock.Mockito

class CachedTemplateSourceSpec extends Specification with Mockito {
  "Loading templates from cache " should {
    "load the templates from the underlying source into cache on the first run" in {
      val testTemplateSource = mock[TemplateSource]
      val cachedTemplateSource = new CachedTemplateSource(testTemplateSource)

      verify(testTemplateSource, times(0)).loadTemplates()
      val templates = cachedTemplateSource.loadTemplates()

      verify(testTemplateSource, times(1)).loadTemplates()
      templates must beEqualTo(testTemplateSource.loadTemplates())
    }

    "return cached results on subsequent runs" in {
      val testTemplateSource = mock[TemplateSource]
      val cachedTemplateSource = new CachedTemplateSource(testTemplateSource)

      val templates1 = cachedTemplateSource.loadTemplates()
      val templates2 = cachedTemplateSource.loadTemplates()

      verify(testTemplateSource, times(1)).loadTemplates()
      templates1 must beEqualTo(templates2)
    }
  }
} 
Example 36
Source File: AbstractRestTest.scala    From slick-akka-http-oauth2   with Apache License 2.0 4 votes vote down vote up
package rest

import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatest.{Matchers, WordSpec}
import org.specs2.mock.Mockito
import persistence.dals._
import persitence.handlers.OAuth2DataHandler
import utils.{ActorModule, ConfigurationModuleImpl, PersistenceModule}

trait AbstractRestTest  extends WordSpec with Matchers with ScalatestRouteTest with Mockito{

  trait Modules extends ConfigurationModuleImpl with ActorModule with PersistenceModule {
    val system = AbstractRestTest.this.system

    override val accountsDal =  mock[AccountsDal]
    override val oauthAuthorizationCodesDal = mock[OAuthAuthorizationCodesDal]
    override val oauthClientsDal = mock[OAuthClientsDal]
    override val oauthAccessTokensDal = mock[OAuthAccessTokensDal]
    override val oauth2DataHandler = new OAuth2DataHandler(this)
    override def config = getConfig.withFallback(super.config)
  }

  def getConfig: Config = ConfigFactory.empty();


}