org.specs2.Specification Scala Examples

The following examples show how to use org.specs2.Specification. 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: TimeFunSpec.scala    From scalaz-reactive   with Apache License 2.0 5 votes vote down vote up
package scalaz.reactive

import org.scalacheck.Gen
import org.specs2.{ ScalaCheck, Specification }
import scalaz._
import scalaz.reactive.Time.T
import scalaz.reactive.TimeFun._
import scalaz.reactive.laws.ApplicativeLaws

class TimeFunSpec extends Specification with ScalaCheck with TimeFunInstances {

  def is = "TimeFunSpec".title ^ s2"""
   Generate a mix of K and Fun TimeFuns
      `TimeFun.ap` holds identity law. ${laws.apIdentityLaw}
      `TimeFun.ap` holds homomorphism law. ${laws.apHomomorphismLaw}
      `TimeFun.ap` holds interchange law. ${laws.apInterchangeLaw}
      `TimeFun.ap` holds derived map law. ${laws.apDerivedMapLaw}
    """

  // generate values for the a:A
  def aGen: Gen[Long] =
    Gen.choose(-100, 100)

  def faGen =
    for {
      v   <- aGen
      k   <- aGen
      fun <- Gen.oneOf(K(v), Fun(_.value * k * v))
    } yield fun

  def abGen: Gen[Long => Long] =
    for {
      k <- aGen
    } yield (l: Long) => l * k

  def fabGen: Gen[TimeFun[Long => Long]] =
    for {
      k <- aGen
    } yield K((l: Long) => l + k)

  def eqGen: Gen[TimeFun[Long] => Long] =
    for {
      l <- Gen.choose[Long](-100, 100)
      t = T(l)
    } yield (tf: TimeFun[Long]) => tf.apply(t)

  val laws =
    new ApplicativeLaws(Applicative[TimeFun], aGen, faGen, abGen, fabGen, eqGen)

} 
Example 2
Source File: CollectionsServiceSpec.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.api.services

import cats.data.OptionT
import cats.effect.IO
import cats.implicits._
import com.azavea.franklin.Generators
import com.azavea.franklin.api.{TestClient, TestServices}
import com.azavea.franklin.database.TestDatabaseSpec
import com.azavea.franklin.datamodel.CollectionsResponse
import com.azavea.stac4s.StacCollection
import com.azavea.stac4s.testing._
import org.http4s.circe.CirceEntityDecoder._
import org.http4s.{Method, Request, Uri}
import org.specs2.{ScalaCheck, Specification}

import java.net.URLEncoder
import java.nio.charset.StandardCharsets

class CollectionsServiceSpec
    extends Specification
    with ScalaCheck
    with TestDatabaseSpec
    with Generators {
  def is = s2"""
  This specification verifies that the collections service can run without crashing

  The collections service should:
    - create and delete collections $createDeleteCollectionExpectation
    - list collections              $listCollectionsExpectation
    - get collections by id         $getCollectionsExpectation
"""

  val testServices: TestServices[IO] = new TestServices[IO](transactor)

  val testClient: TestClient[IO] =
    new TestClient[IO](testServices.collectionsService, testServices.collectionItemsService)

  def listCollectionsExpectation = prop {
    (stacCollectionA: StacCollection, stacCollectionB: StacCollection) =>
      {
        val listIO = (
          testClient.getCollectionResource(stacCollectionA),
          testClient.getCollectionResource(stacCollectionB)
        ).tupled use { _ =>
          val request = Request[IO](method = Method.GET, Uri.unsafeFromString(s"/collections"))
          (for {
            resp    <- testServices.collectionsService.routes.run(request)
            decoded <- OptionT.liftF { resp.as[CollectionsResponse] }
          } yield decoded).value
        }

        val result = listIO.unsafeRunSync.get.collections map { _.id }

        (result must contain(stacCollectionA.id)) and (result must contain(stacCollectionB.id))
      }
  }

  def getCollectionsExpectation = prop { (stacCollection: StacCollection) =>
    val fetchIO =
      testClient.getCollectionResource(stacCollection) use { collection =>
        val encodedId = URLEncoder.encode(collection.id, StandardCharsets.UTF_8.toString)
        val request =
          Request[IO](method = Method.GET, Uri.unsafeFromString(s"/collections/$encodedId"))
        (for {
          resp    <- testServices.collectionsService.routes.run(request)
          decoded <- OptionT.liftF { resp.as[StacCollection] }
        } yield (decoded, collection)).value
      }

    val (fetched, inserted) = fetchIO.unsafeRunSync.get

    fetched must beTypedEqualTo(inserted)
  }

  // since creation / deletion is a part of the collection resource, and accurate creation is checked
  // in getCollectionsExpectation, this test just makes sure that if other tests are failing, it's
  // not because create/delete are broken
  def createDeleteCollectionExpectation = prop { (stacCollection: StacCollection) =>
    (testClient
      .getCollectionResource(stacCollection) use { _ => IO.unit }).unsafeRunSync must beTypedEqualTo(
      ()
    )
  }

} 
Example 3
Source File: SchemasSpec.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.api.schemas

import com.azavea.franklin.Generators
import com.azavea.franklin.datamodel.PaginationToken
import org.specs2.{ScalaCheck, Specification}
import sttp.tapir.Codec
import sttp.tapir.CodecFormat.TextPlain
import sttp.tapir.DecodeResult

class SchemasSpec extends Specification with ScalaCheck with Generators {

  def is = s2"""
  This specification verifies that the custom schemas pass basic round trip tests

  Custom schemas should round trip:
    - PaginationTokens         $paginationTokenExpectation
"""

  def paginationTokenExpectation = prop { (token: PaginationToken) =>
    val codec = implicitly[Codec[String, PaginationToken, TextPlain]]
    codec.decode(codec.encode(token)) ==== DecodeResult.Value(token)
  }
} 
Example 4
Source File: ValidationSpec.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.extensions.validation

import cats.implicits._
import com.azavea.stac4s.StacItem
import com.azavea.stac4s.syntax._
import com.azavea.stac4s.testing._
import eu.timepit.refined.types.string.NonEmptyString
import org.specs2.{ScalaCheck, Specification}

class ValidationSpec extends Specification with ScalaCheck {

  def is = s2"""
  This specification verifies that the Validation extension behaves sensibly

  The validation extension should:
    - report all the extensions it tries to validate   $validateSeveralExpectation
    - accumulate errors from checked extensions        $accumulateErrorsExpectation
"""

  def validateSeveralExpectation = prop { (item: StacItem) =>
    val validate = getItemValidator(List("label", "layer"))
    val test = validate(item)
      .getExtensionFields[ValidationExtension]
      .toEither
      .right
      .get
      .attemptedExtensions
      .toList
      .toSet
      .map { (s: NonEmptyString) => s.value }
    val expectation = Set(Label, Layer) map { _.repr }
    test should beTypedEqualTo(expectation)
  }

  def accumulateErrorsExpectation = prop { (item: StacItem) =>
    val validateLabel    = getItemValidator(List("label"))
    val validateLayer    = getItemValidator(List("layer"))
    val combinedValidate = getItemValidator(List("layer", "label"))

    val labelValidated    = validateLabel(item)
    val layerValidated    = validateLayer(item)
    val combinedValidated = combinedValidate(item)

    val test = (labelValidated.getExtensionFields[ValidationExtension] |+| layerValidated
      .getExtensionFields[ValidationExtension]).toEither.right.get.errors.toSet

    val expectation = combinedValidated
      .getExtensionFields[ValidationExtension]
      .toEither
      .right
      .get
      .errors
      .toSet

    test should beTypedEqualTo(expectation)
  }

} 
Example 5
Source File: ReadmeSpec.scala    From eff   with MIT License 5 votes vote down vote up
package org.atnos.example

import org.specs2.Specification
import org.atnos.eff._
import cats.syntax.all._
import cats.data._
import cats.Eval
import ReaderEffect._
import WriterEffect._
import EvalEffect._
import Eff._

class ReadmeSpec extends Specification { def is = s2"""

 run the first example $firstExample

"""

  def firstExample = {

    object StackEffects {
      type ReaderInt[A] = Reader[Int, A]
      type WriterString[A] = Writer[String, A]
      type Stack = Fx.fx3[ReaderInt, WriterString, Eval]
    }

    import StackEffects._

    // create an action
    val action: Eff[Stack, Int] = for {
    // get the configuration
      init <- ask[Stack, Int]

      // log the current configuration value
      _ <- tell[Stack, String]("START: the start value is "+init)

      // compute the nth power of 2
      a <- delay[Stack, Int](powerOfTwo(init))

      // log an end message
      _ <- tell[Stack, String]("END")
    } yield a

    // run the action with all the interpreters
    val result: (Int, List[String]) =
      run(runEval(runWriter(runReader(5)(action))))

    result === ((32, List("START: the start value is 5", "END")))
  }

  def powerOfTwo(n: Int): Int =
    math.pow(2, n.toDouble).toInt
} 
Example 6
Source File: OptionEffectSpec.scala    From eff   with MIT License 5 votes vote down vote up
package org.atnos.eff

import org.specs2.{ScalaCheck, Specification}
import org.scalacheck.Gen.posNum
import cats.syntax.all._
import cats.instances.all._
import cats.data._
import Eff._
import org.atnos.eff.all._
import org.atnos.eff.syntax.all._

class OptionEffectSpec extends Specification with ScalaCheck { def is = s2"""

 run the option monad                     $optionMonad
 run the option monad with nothing        $optionWithNothingMonad
 run the option monad with reader         $optionReader

 The Eff monad is stack safe with Option  $stacksafeOption

"""

  def optionMonad = {
    type S = Fx.fx1[Option]

    val option: Eff[S, String] =
      for {
        s1 <- OptionEffect.some("hello")
        s2 <- OptionEffect.some("world")
      } yield s1 + " " + s2

    option.runOption.run === Some("hello world")
  }

  def optionWithNothingMonad = {
    type S = Fx.fx1[Option]

    val option: Eff[S, String] =
      for {
        s1 <- OptionEffect.some[S, String]("hello")
        s2 <- OptionEffect.none[S, String]
      } yield s1 + " " + s2

    option.runOption.run === None
  }

  def optionReader = prop { (init: Int, someValue: Int) =>

    // define a Reader / Option stack
    type S = Fx.fx2[Option, ReaderInt]

    // create actions
    def readOption[R :_option :_readerInt]: Eff[R, Int] =
      for {
        j <- OptionEffect.some(someValue)
        i <- ask
      } yield i + j

    // run effects
    readOption[S].runOption.runReader(init).run must_== Some(init + someValue)
  }.setGens(posNum[Int], posNum[Int]).set(minTestsOk = 1)


  def stacksafeOption = {
    val list = (1 to 5000).toList
    val action = list.traverse(i => OptionEffect.some(i))

    action.runOption.run ==== Some(list)
  }

  type ReaderInt[A] = Reader[Int, A]

  type _readerInt[R] = ReaderInt |= R
} 
Example 7
Source File: IntoPolySpec.scala    From eff   with MIT License 5 votes vote down vote up
package org.atnos.eff

import cats.data._
import org.specs2.Specification
import org.specs2.matcher.ThrownExpectations
import syntax.all._

class IntoPolySpec extends Specification with ThrownExpectations { def is = s2"""

 The Into typeclass is used to inject the effects of one stack into another stack containing at least the same effects
   a stack can be injected into itself $into1
   a stack can be injected into another containing one prepended effect $into2

   more examples $more

 One stack can be injected into another if there is a Member implicit relating the 2 $memberInto

"""

  sealed trait OptionLike[A] { def a: A }
  case class Option1[A](a: A) extends OptionLike[A]
  case class Option2[A](a: A) extends OptionLike[A]
  case class Option3[A](a: A) extends OptionLike[A]
  case class Option4[A](a: A) extends OptionLike[A]
  case class Option5[A](a: A) extends OptionLike[A]
  case class Option6[A](a: A) extends OptionLike[A]
  case class Option7[A](a: A) extends OptionLike[A]

  type S1 = Fx.fx1[Option1]
  type S2 = Fx.fx2[Option1, Option2]
  type S3 = Fx.fx3[Option1, Option2, Option3]
  type S4 = Fx.fx4[Option1, Option2, Option3, Option4]
  type S5 = Fx.fx5[Option1, Option2, Option3, Option4, Option5]
  type S6 = Fx.fx6[Option1, Option2, Option3, Option4, Option5, Option6]
  type S7 = Fx.fx7[Option1, Option2, Option3, Option4, Option5, Option6, Option7]


  def into1 =
    Eff.send[Option1, Fx1[Option1], Int](Option1(1)).into[Fx1[Option1]].runOpt.run === 1

  def into2 = {
    Eff.send[Option1, Fx1[Option1], Int](Option1(1)).map(identity _).into[Fx2[Option1, Option2]].runOpt.runOpt.run === 1
    Eff.send[Option2, Fx1[Option2], Int](Option2(1)).map(identity _).into[Fx2[Option1, Option2]].runOpt.runOpt.run === 1
  }

  def more = {
    Eff.send[Option1, Fx2[Option2, Option1], Int](Option1(1)).map(identity _).into[Fx2[Option1, Option2]].runOpt.runOpt.run === 1

    Eff.send[Option1, Fx1[Option1], Int](Option1(1)).map(identity _).into[Fx3[Option1, Option2, Option3]].runOpt.runOpt.runOpt.run === 1
    Eff.send[Option2, Fx1[Option2], Int](Option2(1)).map(identity _).into[Fx3[Option1, Option2, Option3]].runOpt.runOpt.runOpt.run === 1
    Eff.send[Option3, Fx1[Option3], Int](Option3(1)).map(identity _).into[Fx3[Option1, Option2, Option3]].runOpt.runOpt.runOpt.run === 1

    Eff.send[Option1, Fx2[Option1, Option2], Int](Option1(1)).map(identity _).into[Fx3[Option1, Option2, Option3]].runOpt.runOpt.runOpt.run === 1

    // make sure that flatMap works
    Eff.send[Option1, Fx2[Option1, Option2], Int](Option1(1)).flatMap(i => Eff.send(Option2(i))).into[Fx3[Option1, Option2, Option3]].runOpt.runOpt.runOpt.run === 1
  }

  def memberInto = {
    def stopUnless[EO, E](cond: Eff[E, Boolean])(implicit m: Member.Aux[Option, EO, E]): Eff[EO, Unit] = {
      cond.into[EO].flatMap { c =>
        if (c) OptionEffect.some(())
        else   OptionEffect.none
      }
    }

    def isEven[E](n: Int): Eff[E, Boolean] =
      Eff.pure[E, Boolean](n % 2 == 0)

    def action[EO, E](implicit r: Reader[Int, *] |= EO, o: Member.Aux[Option, EO, E]): Eff[EO, String] =
      for {
        m <- reader.ask[EO, Int]
        _ <- stopUnless[EO, E](isEven(m + 1))
      } yield m.toString

    type S = Fx.fx1[Reader[Int, *]]
    action[Fx.prepend[Option, S], S].runOption.runReader(2).run must beNone
  }

  
  implicit class RunOptionOps[T[_] <: OptionLike[_], R, U](e: Eff[R, Int])(implicit m: Member.Aux[T, R, U]) {
    def runOpt: Eff[U, Int] = runOption(e)
  }

  def runOption[T[_] <: OptionLike[_], R, U](e: Eff[R, Int])(implicit m: Member.Aux[T, R, U]): Eff[U, Int] =
    e match {
      case Pure(a, _) => Eff.pure(a)
      case Impure(NoEffect(a), c, _) => runOption(c(a))
      case Impure(u: Union[_,_], c, _) =>
        m.project(u) match {
          case Right(oa) => runOption(c(oa.a))
          case Left(u1) => Impure[U, u1.X, Int](u1, Continuation.lift(x => runOption(c(x))))
        }
      case a@ImpureAp(_,_,_) => runOption(a.toMonadic)
    }
} 
Example 8
Source File: EvalEffectSpec.scala    From eff   with MIT License 5 votes vote down vote up
package org.atnos.eff

import org.specs2.Specification
import org.atnos.eff.all._
import org.atnos.eff.syntax.all._

import cats.syntax.all._
import cats.instances.all._
import cats.instances.all._
import cats.Eval

class EvalEffectSpec extends Specification { def is = s2"""

 run is stack safe with Eval               $stacksafeRun
 attempt is stack safe with Eval           $stacksafeAttempt
 recursion in Eval.defer is stack safe     $stacksafeRecursion

"""

  type E = Fx.fx1[Eval]

  val list = (1 to 5000).toList

  def stacksafeRun = {
    val action = list.traverse(i => EvalEffect.delay(i))
    action.runEval.run ==== list
  }

  def stacksafeAttempt = {
    val action = list.traverse(i => EvalEffect.delay(i))
    action.attemptEval.run ==== Right(list)
  }

  def stacksafeRecursion = {
    def loop(i: Int): Eval[Eff[Fx.fx1[Eval], Int]] =
      if (i == 0) {
        Eval.now(Eff.pure(1))
      } else {
        Eval.now(org.atnos.eff.eval.defer(loop(i - 1)).map(_  + 1))
      }

    loop(100000).value.runEval.run ==== 100001
  }
} 
Example 9
Source File: InferenceSpec.scala    From eff   with MIT License 5 votes vote down vote up
package org.atnos.eff

import all._
import syntax.all._
import cats.data._
import org.specs2.Specification

class InferenceSpec extends Specification { def is = s2"""

 All the examples should compile ok

"""
  def e1 = {
    import Example1._

    putAndTell[S](4).runState(0).runWriter.runReader("").run
    putAndTell[S](4).runReader("").runState(0).runWriter.run

    // in this case a type annotation is required on runWriter
    putAndTell[S](4).runReader("").runWriter[String].runState(0).run

    ok
  }
}

object Example1  {
  type RNG[R] = Member[State[Int, *], R]
  type Log[R] = Member[Writer[String, *], R]
  type Env[R] = Member[Reader[String, *], R]

  type S = Fx.fx3[State[Int, *], Writer[String, *], Reader[String, *]]

  def putAndTell[R : RNG : Log: Env](i: Int) =
    for {
      _ <- put(i)
      _ <- tell("stored " + i)
    } yield i

} 
Example 10
Source File: StreamingFormulaDemo2.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.spark.demo

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.ScalaCheck
import org.specs2.Specification
import org.specs2.matcher.ResultMatchers
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.Duration
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.dstream.DStream._

import scalaz.syntax.std.boolean._
    
import es.ucm.fdi.sscheck.spark.streaming.SharedStreamingContextBeforeAfterEach
import es.ucm.fdi.sscheck.prop.tl.{Formula,DStreamTLProperty}
import es.ucm.fdi.sscheck.prop.tl.Formula._
import es.ucm.fdi.sscheck.gen.{PDStreamGen,BatchGen}
import es.ucm.fdi.sscheck.gen.BatchGenConversions._
import es.ucm.fdi.sscheck.gen.PDStreamGenConversions._
import es.ucm.fdi.sscheck.matcher.specs2.RDDMatchers._

@RunWith(classOf[JUnitRunner])
class StreamingFormulaDemo2 
  extends Specification 
  with DStreamTLProperty
  with ResultMatchers
  with ScalaCheck {
  
  // Spark configuration
  override def sparkMaster : String = "local[*]"
  override def batchDuration = Duration(300)
  override def defaultParallelism = 3
  override def enableCheckpointing = true

  def is = 
    sequential ^ s2"""
    Check process to persistently detect and ban bad users
      - where a stateful implementation extracts the banned users correctly ${checkExtractBannedUsersList(listBannedUsers)}
      - where a trivial implementation ${checkExtractBannedUsersList(statelessListBannedUsers) must beFailing}
    """
  type UserId = Long
  
  def listBannedUsers(ds : DStream[(UserId, Boolean)]) : DStream[UserId] = 
    ds.updateStateByKey((flags : Seq[Boolean], maybeFlagged : Option[Unit]) =>
      maybeFlagged match {
        case Some(_) => maybeFlagged  
        case None => flags.contains(false) option {()}
      } 
    ).transform(_.keys)
      
  def statelessListBannedUsers(ds : DStream[(UserId, Boolean)]) : DStream[UserId] =
    ds.map(_._1)
    
  def checkExtractBannedUsersList(testSubject : DStream[(UserId, Boolean)] => DStream[UserId]) = {
    val batchSize = 20 
    val (headTimeout, tailTimeout, nestedTimeout) = (10, 10, 5) 
    val (badId, ids) = (15L, Gen.choose(1L, 50L))   
    val goodBatch = BatchGen.ofN(batchSize, ids.map((_, true)))
    val badBatch = goodBatch + BatchGen.ofN(1, (badId, false))
    val gen = BatchGen.until(goodBatch, badBatch, headTimeout) ++ 
               BatchGen.always(Gen.oneOf(goodBatch, badBatch), tailTimeout)
    
    type U = (RDD[(UserId, Boolean)], RDD[UserId])
    val (inBatch, outBatch) = ((_ : U)._1, (_ : U)._2)
    
    val formula = {
      val badInput = at(inBatch)(_ should existsRecord(_ == (badId, false)))
      val allGoodInputs = at(inBatch)(_ should foreachRecord(_._2 == true))
      val noIdBanned = at(outBatch)(_.isEmpty)
      val badIdBanned = at(outBatch)(_ should existsRecord(_ == badId))
      
      ( ( allGoodInputs and noIdBanned ) until badIdBanned on headTimeout ) and
      ( always { badInput ==> (always(badIdBanned) during nestedTimeout) } during tailTimeout )  
    }  
    
    forAllDStream(    
      gen)(
      testSubject)( 
      formula)
  }.set(minTestsOk = 10).verbose

} 
Example 11
Source File: DiffMatcherTest.scala    From diffx   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.diffx.specs2

import org.specs2.Specification

class DiffMatcherTest extends Specification with DiffMatcher {
  override def is = s2"""This is an empty specification"""

  val right: Foo = Foo(
    Bar("asdf", 5),
    List(123, 1234),
    Some(Bar("asdf", 5))
  )
  val left: Foo = Foo(
    Bar("asdf", 66),
    List(1234),
    Some(right)
  )

  def ignore = left must matchTo(right)
}
sealed trait Parent
case class Bar(s: String, i: Int) extends Parent
case class Foo(bar: Bar, b: List[Int], parent: Option[Parent]) extends Parent 
Example 12
Source File: RuleSpec.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.manage

import janstenpickle.vault.manage.Model.Rule
import org.scalacheck.{Gen, Prop}
import org.specs2.{ScalaCheck, Specification}
import uscala.result.specs2.ResultMatchers

class RuleSpec extends Specification with ScalaCheck with ResultMatchers {
  import RuleSpec._

  override def is =
    s2"""
      Can encode and decode policy strings $passes
      Cannot decode bad policy strings $fails
      """

  def passes = Prop.forAllNoShrink(Gen.listOf(ruleGen).suchThat(_.nonEmpty)) (rules =>
    Rule.decode(rules.map(_.encode).mkString("\n")) must beOk.like {
      case a => a must containAllOf(rules)
    }
  )

  def fails = Prop.forAllNoShrink(Gen.listOf(badRuleGen).suchThat(_.nonEmpty)) (rules =>
    Rule.decode(rules.mkString("\n")) must beFail
  )
}

object RuleSpec {
  val policyGen = Gen.option(Gen.oneOf("read", "write", "sudo", "deny"))
  val capabilitiesGen = Gen.option(
    Gen.listOf(Gen.oneOf("create", "read", "update", "delete", "list", "sudo", "deny")).
      suchThat(_.nonEmpty).
      map(_.distinct)
  )

  val ruleGen = for {
    path <- Gen.alphaStr.suchThat(_.nonEmpty)
    policy <- policyGen
    capabilities <- capabilitiesGen
  } yield Rule(path, capabilities, policy)

  val badRuleGen = for {
    path <- Gen.alphaStr.suchThat(_.nonEmpty)
    policy <- policyGen
    capabilities <- capabilitiesGen
  } yield
    s"""
       |path "$path"
       |   $policy cage
       |   $capabilities }""".stripMargin('|')
} 
Example 13
Source File: VaultSpec.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.core

import java.net.URL

import janstenpickle.scala.syntax.SyntaxRequest._
import janstenpickle.scala.syntax.ResponseSyntax._
import janstenpickle.scala.syntax.VaultConfigSyntax._
import org.scalacheck.Gen
import org.specs2.Specification
import org.specs2.specification.core.Fragments
import uscala.result.specs2.ResultMatchers

import scala.concurrent.ExecutionContext
import scala.io.Source


trait VaultSpec extends Specification with ResultMatchers {
  implicit val errConverter: Throwable => String = _.getMessage
  implicit val ec: ExecutionContext = ExecutionContext.global

  lazy val rootToken = Source.fromFile("/tmp/.root-token").mkString.trim
  lazy val roleId = Source.fromFile("/tmp/.role-id").mkString.trim
  lazy val secretId = Source.fromFile("/tmp/.secret-id").mkString.trim

  lazy val rootConfig: VaultConfig = VaultConfig(
    WSClient(new URL("http://localhost:8200")), rootToken
  )
  lazy val badTokenConfig = VaultConfig(
    rootConfig.wsClient,
    "face-off"
  )
  lazy val config = VaultConfig(
    rootConfig.wsClient,
    AppRole(roleId, secretId)
  )
  lazy val badServerConfig = VaultConfig(
    WSClient(new URL("http://nic-cage.xyz")),
    "con-air"
  )

  def check = config.token.attemptRun(_.getMessage) must beOk

  override def map(fs: => Fragments) =
    s2"""
      Can receive a token for an AppRole $check
    """ ^
    fs
}

object VaultSpec {
  val longerStrGen = Gen.alphaStr.suchThat(_.length >= 3)
  val strGen = Gen.alphaStr.suchThat(_.nonEmpty)
} 
Example 14
Source File: CatsInteropSpec.scala    From interop-cats   with Apache License 2.0 5 votes vote down vote up
package zio.interop

import cats.effect.{ Concurrent, Resource }
import org.specs2.Specification
import org.specs2.specification.AroundTimeout
import zio.{ Promise, Runtime, Task }
import zio.interop.catz._

class CatsInteropSpec extends Specification with AroundTimeout {

  def is = s2"""
      Resource
        cats fiber wrapped in Resource can be canceled $catsResourceInterruptible
      """

  def catsResourceInterruptible = {

    val io = for {
      p        <- Promise.make[Nothing, Int]
      resource = Resource.make(Concurrent[Task].start(p.succeed(1) *> Task.never))(_.cancel)
      _        <- resource.use(_ => p.await)
    } yield 0

    Runtime.default.unsafeRun(io) must be_===(0)
  }

} 
Example 15
Source File: LibisabelleSpec.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.tests

import java.nio.file.Paths

import scala.concurrent._
import scala.math.BigInt

import org.specs2.Specification
import org.specs2.specification.core.Env

import info.hupel.isabelle._
import info.hupel.isabelle.pure._

class PreloadedLibisabelleSpec(specs2Env: Env) extends LibisabelleSpec(specs2Env, "preloaded")
class UnloadedLibisabelleSpec(specs2Env: Env) extends LibisabelleSpec(specs2Env, "unloaded") {
  override def session = "Pure"
}

abstract class LibisabelleSpec(val specs2Env: Env, flavour: String) extends Specification
  with FullSetup
  with IsabelleMatchers { def is = s2"""

  Basic protocol interaction ($flavour)

  An Isabelle session
    can be started             ${system must exist.awaitFor(duration)}
    supports term parsing      ${parseCheck must beSuccess(Option.empty[String]).awaitFor(duration)}
    can parse terms            ${parsed must beSome.awaitFor(duration)}
    can't parse wrong terms    ${parseFailed must beNone.awaitFor(duration)}
    handles missing operations ${missingOperation must beFailure(contain("unknown command")).awaitFor(duration)}
    can load theories          ${loaded must beSuccess(()).awaitFor(duration)}
    handles operation errors   ${operationError must beFailure(contain("Invalid time")).awaitFor(duration)}
    handles load errors        ${loadedFailing must beFailure(be =~ """.*((Failed to finish proof)|(EXCURSION_FAIL)).*""".r).awaitFor(duration)}
    can cancel requests        ${cancelled.failed must beAnInstanceOf[CancellationException].awaitFor(duration)}"""


  // Pure operations

  val thy = Theory.get("Pure")
  val ctxt = Context.initGlobal(thy)

  val parseCheck = system.flatMap(sys => Term.parse(ctxt)("TERM x").check(sys, "Protocol_Pure"))

  val parsed = system.flatMap(_.run(Expr.fromString[Prop](ctxt, "TERM x"), "Protocol_Pure"))
  val parseFailed = system.flatMap(_.run(Expr.fromString[Prop](ctxt, "TERM"), "Protocol_Pure"))


  val AbsentOperation = Operation.implicitly[Unit, Unit]("absent_operation")

  val missingOperation = system.flatMap(_.invoke(AbsentOperation)(()))


  // Loading auxiliary files

  def load(name: String) = {
    val thy = resources.findTheory(Paths.get(s"tests/$name.thy")).get
    for {
      s <- system
      e <- isabelleEnv
      res <- s.invoke(Operation.UseThys)(List(e.isabellePath(thy)))
    }
    yield res
  }

  val loaded = load("Sleepy")
  val loadedFailing = load("Failing")

  val Sleepy = Operation.implicitly[BigInt, Unit]("sleepy")

  val operationError =
    for {
      s <- system
      _ <- loaded
      res <- s.invoke(Sleepy)(-1)
    }
    yield res

  val cancelled =
    for {
      s <- system
      _ <- loaded
      res <- { val future = s.invoke(Sleepy)(1); future.cancel(); future }
    }
    yield ()

} 
Example 16
Source File: EnvironmentSpec.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.tests

import java.nio.file.Files

import scala.util.control.NonFatal

import org.specs2.Specification
import org.specs2.specification.core.Env

import info.hupel.isabelle.api._
import info.hupel.isabelle.setup.Resolver

class EnvironmentSpec(val specs2Env: Env) extends Specification with BasicSetup with IsabelleMatchers { def is = s2"""

  Environment handling

  A low-level environment
    respects the USER_HOME setting                        ${settingsPrefix must beTrue.awaitFor(duration)}
    cleans up etc/components after failure                ${cleanedUp must beTrue.awaitFor(duration)}"""

  val classpath = Resolver.Default.resolve(platform, version)
  val user = Files.createTempDirectory("libisabelle_user")
  val context = Environment.Context(setup.home, user, Nil, Nil)

  val settingsPrefix = classpath.map { paths =>
    val env = Environment.instantiate(version, paths, context)
    val prefix = env.isabellePath(user.toAbsolutePath.toString)
    List("ISABELLE_BROWSER_INFO", "ISABELLE_HOME_USER").forall { setting =>
      env.isabelleSetting(setting).startsWith(prefix)
    }
  }

  val cleanedUp = classpath.map { paths =>
    try {
      val testContext = context.copy(
        home = Files.createTempDirectory("nonexistent_home"),
        components = List(Files.createTempDirectory("dummy_component"))
      )
      Environment.instantiate(version, paths, testContext)
    }
    catch {
      case NonFatal(ex) =>
    }

    !Files.exists(context.etcComponents(version))
  }

} 
Example 17
Source File: CodecSpec.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.tests

import scala.math.BigInt

import org.specs2.{ScalaCheck, Specification}
import org.specs2.specification.core.Env

import org.scalacheck._
import org.scalacheck.Prop.forAll

import info.hupel.isabelle._
import info.hupel.isabelle.api.XML

class CodecSpec(val specs2Env: Env) extends Specification with BasicSetup with ScalaCheck { def is = s2"""

  Round-trip property of Codecs

  Values can be converted
    of type Unit                      ${propCodec[Unit]}
    of type Boolean                   ${propCodec[Boolean]}
    of type BigInt                    ${propCodec[BigInt]}
    of type String                    ${propCodec[String]}
    of type (BigInt, BigInt)          ${propCodec[(BigInt, BigInt)]}
    of type (String, Unit)            ${propCodec[(String, Unit)]}
    of type List[Unit]                ${propCodec[List[Unit]]}
    of type List[BigInt]              ${propCodec[List[BigInt]]}
    of type List[String]              ${propCodec[List[String]]}
    of type List[List[String]]        ${propCodec[List[List[String]]]}
    of type List[(BigInt, BigInt)]    ${propCodec[List[(BigInt, BigInt)]]}
    of type (BigInt, List[BigInt])    ${propCodec[(BigInt, List[BigInt])]}
    of type Option[BigInt]            ${propCodec[Option[BigInt]]}
    of type Option[List[BigInt]]      ${propCodec[Option[List[BigInt]]]}
    of type List[Option[BigInt]]      ${propCodec[List[Option[BigInt]]]}
    of type Either[String, BigInt]    ${propCodec[Either[String, BigInt]]}
  """

  def propCodec[A : Codec : Arbitrary] = properties(new Properties("props") {
    property("encode/decode") = forAll { (a: A) =>
      Codec[A].decode(Codec[A].encode(a)) must beRight(a)
    }

    property("YXML") = forAll { (a: A) =>
      val encoded = Codec[A].encode(a)
      XML.fromYXML(encoded.toYXML) must be_===(encoded)
    }
  })

} 
Example 18
Source File: SetupSpec.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.tests

import java.nio.file.Files

import org.specs2.Specification
import org.specs2.specification.core.Env

import info.hupel.isabelle.Platform
import info.hupel.isabelle.setup._

class SetupSpec(val specs2Env: Env) extends Specification with DefaultSetup { def is = s2"""

  Isabelle setup

  Isabelle setup detection
    should handle absent setups      $absent
    should handle corrupted setups   $corrupted"""

  def absent = {
    val dir = Files.createTempDirectory("libisabelle_test")
    val platform = Platform.genericPlatform(dir)
    Files.createDirectories(platform.setupStorage)
    Setup.detect(platform, version, false) must beLeft(Setup.Absent)
  }

  def corrupted = {
    val dir = Files.createTempDirectory("libisabelle_test")
    val platform = Platform.genericPlatform(dir)
    Files.createDirectories(platform.setupStorage(version, true))
    Setup.detect(platform, version, false) must beLeft.like {
      case Setup.Corrupted(_) => true
    }
  }

} 
Example 19
Source File: OptimizeSpec.scala    From skeuomorph   with Apache License 2.0 5 votes vote down vote up
package higherkindness.skeuomorph.mu

import org.scalacheck.Prop
import org.specs2.{ScalaCheck, Specification}
import higherkindness.droste._
import higherkindness.droste.data._
import higherkindness.skeuomorph.mu.MuF.TCoproduct
import higherkindness.skeuomorph.mu.Optimize._

class OptimizeSpec extends Specification with ScalaCheck {

  import higherkindness.skeuomorph.instances._

  def is =
    s2"""
  mu Optimize

  It should convert a TCoproduct into a TOption. $convertCoproduct2Option

  It should convert a TCoproduct into a TEither. $convertCoproduct2Either
  """

  def convertCoproduct2Option: Prop =
    Prop.forAll(muCoproductWithTNullGen[Mu[MuF]]) { coproduct: TCoproduct[Mu[MuF]] =>
      val transformation: Mu[MuF] = knownCoproductTypesTrans[Mu[MuF]].algebra.run(coproduct)

      val test = scheme.hylo(checkOptionalValue, Project[MuF, Mu[MuF]].coalgebra)

      test(transformation)
    }

  def convertCoproduct2Either: Prop =
    Prop.forAll(muCoproductWithoutTNullGen[Mu[MuF]]) { coproduct: TCoproduct[Mu[MuF]] =>
      val transformation: Mu[MuF] = knownCoproductTypesTrans[Mu[MuF]].algebra.run(coproduct)

      val test = scheme.hylo(checkEitherValue, Project[MuF, Mu[MuF]].coalgebra)

      test(transformation)
    }

  def checkEitherValue: Algebra[MuF, Boolean] =
    Algebra[MuF, Boolean] {
      case MuF.TEither(_, _) => true
      case _                 => false
    }

  def checkOptionalValue: Algebra[MuF, Boolean] =
    Algebra[MuF, Boolean] {
      case MuF.TOption(_) => true
      case _              => false
    }
} 
Example 20
Source File: URIDecodingSpec.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi

import java.net.URI
import io.circe.syntax._
import org.specs2.Specification

class URIDecodingSpec extends Specification {
  override def is = s2"""
      Encode and decode an absolute URI $absoluteURI
      Encode and decode a relative URI $relativeURI
      """

  def absoluteURI = {
    val absoluteLink = "https://www.google.de/search?q=nyancat"

    val uri     = new URI(absoluteLink)
    val uriJson = uri.asJson
    val result  = uriJson.as[URI]

    result must beRight(uri)
  }

  def relativeURI = {
    val relativeLink = "/doggos?size=puppy"

    val uri     = new URI(relativeLink)
    val uriJson = uri.asJson
    val result  = uriJson.as[URI]

    result must beRight(uri)
  }
} 
Example 21
Source File: OAuthFailedSpec.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import io.circe.Json
import org.mdedetrich.webmodels.{FlowId, OAuth2Token, OAuth2TokenProvider}
import org.specs2.Specification
import org.specs2.concurrent.ExecutionEnv
import org.specs2.execute.Skipped
import org.specs2.matcher.FutureMatchers
import org.specs2.specification.core.SpecStructure
import org.zalando.kanadi.api.{Events, Subscriptions}
import org.zalando.kanadi.models._

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

class OAuthFailedSpec(implicit ec: ExecutionEnv) extends Specification with FutureMatchers with Config {

  val config = ConfigFactory.load()

  implicit val system       = ActorSystem()
  implicit val http         = Http()
  implicit val materializer = ActorMaterializer()
  val failingOauth2TokenProvider = Some(
    OAuth2TokenProvider(() => Future.successful(OAuth2Token("Failing token")))
  )

  val subscriptionsClient =
    Subscriptions(nakadiUri, failingOauth2TokenProvider)
  val eventsClient = Events(nakadiUri, failingOauth2TokenProvider)

  override def is: SpecStructure = s2"""
    Call to subscriptions list should fail with invalid token   $oAuthCallSubscriptions
    Call to publishEvents should fail with invalid token        $oAuthPublishEvents
  """

  def oAuthCallSubscriptions = Skipped("No way for current Nakadi docker image to detect \"wrong\" tokens")

  def oAuthPublishEvents = Skipped("No way for current Nakadi docker image to detect \"wrong\" tokens")
} 
Example 22
Source File: SubscriptionsSpec.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi

import java.util.UUID

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import org.mdedetrich.webmodels.FlowId
import org.specs2.Specification
import org.specs2.concurrent.ExecutionEnv
import org.specs2.specification.core.SpecStructure
import org.specs2.specification.{AfterAll, BeforeAll}
import org.zalando.kanadi.api.{Category, EventType, EventTypes, Events, Subscription, Subscriptions}
import org.zalando.kanadi.models.{EventTypeName, SubscriptionId}

import scala.collection.parallel.mutable
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

class SubscriptionsSpec(implicit ec: ExecutionEnv) extends Specification with Config with BeforeAll with AfterAll {
  override def is: SpecStructure = sequential ^ s2"""
      Create enough subscriptions to ensure that pagination is used $createEnoughSubscriptionsToUsePagination
    """

  val config = ConfigFactory.load()

  implicit val system       = ActorSystem()
  implicit val http         = Http()
  implicit val materializer = ActorMaterializer()

  val eventTypeName         = EventTypeName(s"Kanadi-Test-Event-${UUID.randomUUID().toString}")
  val OwningApplication     = "KANADI"
  val consumerGroup: String = UUID.randomUUID().toString
  val subscriptionsClient =
    Subscriptions(nakadiUri, None)
  val eventsClient = Events(nakadiUri, None)
  val eventsTypesClient =
    EventTypes(nakadiUri, None)
  val subscriptionIds: mutable.ParSet[SubscriptionId] = mutable.ParSet.empty

  eventTypeName.pp
  s"Consumer Group: $consumerGroup".pp

  def createEventType = eventsTypesClient.create(EventType(eventTypeName, OwningApplication, Category.Business))

  override def beforeAll =
    Await.result(createEventType, 10 seconds)

  override def afterAll = {
    Await.result(
      for {
        res1 <- Future.sequence(subscriptionIds.toList.map(s => subscriptionsClient.delete(s)))
        res2 <- eventsTypesClient.delete(eventTypeName)
      } yield (res1, res2),
      10 seconds
    )
    ()
  }

  def createEnoughSubscriptionsToUsePagination = (name: String) => {
    implicit val flowId: FlowId = Utils.randomFlowId()
    flowId.pp(name)

    val createdSubscriptions = Future.sequence(for {
      _ <- 1 to 22
      subscription = subscriptionsClient.create(
        Subscription(None, s"$OwningApplication-${UUID.randomUUID().toString}", Some(List(eventTypeName))))
    } yield {
      subscription.foreach { s =>
        subscriptionIds += s.id.get
      }
      subscription
    })

    val retrievedSubscriptions = (for {
      subscriptions <- createdSubscriptions
      retrievedSubscription = Future.sequence(subscriptions.map { subscription =>
        subscriptionsClient.createIfDoesntExist(subscription)
      })
    } yield retrievedSubscription).flatMap(a => a)

    Await.result(createdSubscriptions, 10 seconds) mustEqual Await.result(retrievedSubscriptions, 10 seconds)
  }

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

import io.circe.generic.auto._
import io.circe.syntax._
import java.nio.charset.StandardCharsets
import jawn.ast.JParser
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.{ScalaCheck, Specification}
import roc.postgresql.Null
import roc.types.failures.{ElementDecodingFailure, NullDecodedFailure}
import roc.types.{decoders => Decoders}

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

  Json Decoder
    must correctly decode Text representation                              $testValidText
    must throw a ElementDecodingFailure when Text decoding invalid Json    $testInvalidText
    must correctly decode Binary representation                            $testValidBinary
    must throw a ElementDecodingFailure when Binary decoding invalid Json  $testInvalidBinary
    must throw a NullDecodedFailure when Null decoding Json                $testNullDecoding

                                                                               """

  private val testValidText = forAll { x: JsonContainer =>
    Decoders.jsonElementDecoder.textDecoder(x.text) must_== x.json
  }

  private val testInvalidText = forAll { x: String =>
    Decoders.jsonElementDecoder.textDecoder(x) must throwA[ElementDecodingFailure]
  }

  private val testValidBinary = forAll { x: BinaryJsonContainer =>
    Decoders.jsonElementDecoder.binaryDecoder(x.binary) must_== x.json
  }

  private val testInvalidBinary = forAll { xs: Array[Byte] =>
    Decoders.jsonElementDecoder.binaryDecoder(xs) must throwA[ElementDecodingFailure]
  }

  private val testNullDecoding =
    Decoders.jsonElementDecoder.nullDecoder(Null('doesnotmatter, -71)) must throwA[NullDecodedFailure]

  case class JsonContainer(text: String, json: Json)
  private lazy val genJsonContainer: Gen[JsonContainer] = for {
    jObject <- arbitrary[JsonObject]
  } yield {
    val text = jObject.asJson.noSpaces
    val json = JParser.parseUnsafe(text)
    new JsonContainer(text, json)
  }
  private implicit lazy val arbitraryJsonContainer: Arbitrary[JsonContainer] = 
    Arbitrary(genJsonContainer)

  case class BinaryJsonContainer(binary: Array[Byte], json: Json)
  private lazy val genBinaryJsonContainer: Gen[BinaryJsonContainer] = for {
    jObject <- arbitrary[JsonObject]
  } yield {
    val text = jObject.asJson.noSpaces
    val json = JParser.parseUnsafe(text)
    val bytes = text.getBytes(StandardCharsets.UTF_8)
    new BinaryJsonContainer(bytes, json)
  }
  private implicit lazy val arbitraryBinaryJsonContainer: Arbitrary[BinaryJsonContainer] =
    Arbitrary(genBinaryJsonContainer)

  case class JsonObject(name: String, first_names: List[String])

  private lazy val genJsonObject: Gen[JsonObject] = for {
    name <- arbitrary[String]
    first_names <- arbitrary[List[String]]
  } yield new JsonObject(name, first_names)
  private implicit lazy val arbitraryJsonObject: Arbitrary[JsonObject] = 
    Arbitrary(genJsonObject)
} 
Example 24
Source File: QuerySpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package integrations

import com.twitter.util.Await
import org.specs2.Specification
import roc.postgresql.Request

final class QuerySpec extends Specification 
  with SqlReader
  with Client { def is = sequential ^ s2""" 

  Query
    must execute a CREATE command   $testCreate
    must execute an INSERT command  $testInsert
    must execute an UPDATE command  $testUpdate
    must execute a SELECT command   $testSelect
    must execute a DELETE command   $testDelete
    must execute a DROP command     $testDrop

                                                                        """

  def testCreate() = {
    val sql     = readSql("query/create.sql")
    val request = new Request(sql)
    val result  = Await.result(Postgres.query(request))
    result.completedCommand must_== "CREATE TABLE"
  }

  def testInsert() = {
    val sql     = readSql("query/insert.sql")
    val request = new Request(sql)
    val result  = Await.result(Postgres.query(request))
    result.completedCommand must_== "INSERT 0 1"
  }

  def testUpdate() = {
    val sql     = readSql("query/update.sql")
    val request = new Request(sql)
    val result  = Await.result(Postgres.query(request))
    result.completedCommand must_== "UPDATE 1"
  }

  def testSelect() = {
    val request = new Request("SELECT name FROM roc_tests WHERE id = 1")
    val result  = Await.result(Postgres.query(request))
    result.toList.length must_== 1
  }

  def testDelete() = {
    val request = new Request("DELETE FROM roc_tests WHERE id = 1;")
    val result  = Await.result(Postgres.query(request))
    result.completedCommand must_== "DELETE 1"
  }

  def testDrop() = {
    val request = new Request("DROP TABLE roc_tests;")
    val result = Await.result(Postgres.query(request))
    result.completedCommand must_== "DROP TABLE"
  }
} 
Example 25
Source File: PackageSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql

import java.nio.charset.StandardCharsets
import org.scalacheck.Prop.forAll
import org.specs2.{ScalaCheck, Specification}

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

  Postgresql Package
    should calculate length of C-Style String               $test0
    should calculate length of C-Style Strings              $test1
                                                                           """

  val test0 = forAll { (str: String) =>
    val bytes  = str.getBytes(StandardCharsets.UTF_8)
    val length = bytes.length + 1 // add 1 for null character
    lengthOfCStyleString(str) must_== length
  }

  val test1 = forAll { (xs: List[String]) =>
    val length = xs match {
      case h :: t => xs.map(lengthOfCStyleString).reduce(_ + _)
      case t      => 0
    }
    lengthOfCStyleStrings(xs) must_== length
  }
} 
Example 26
Source File: PacketSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql
package transport

import org.specs2.Specification

final class PacketSpec extends Specification { def is = s2"""

  Packets should
    encode a 'Message Type' byte                            $encodeMessageTypeByte
    encode the length                                       $encodeLength
    encode the body                                         $encodeBody
    encode a packet with no 'Message Type' byte             $encodeNoMessageTypeByte
                                                            """

  def encodeMessageTypeByte = {
    val buf       = Buffer.fromChannelBuffer(packet.toChannelBuffer)
    val bufReader = BufferReader(buf)

    bufReader.readByte must_== 'R'
  }

  def encodeLength = {
    val buf       = Buffer.fromChannelBuffer(packet.toChannelBuffer)
    val bufReader = BufferReader(buf)
    val _ = bufReader.readByte // tested in encodeMessageTypeByte

    bufReader.readInt must_== 8
  }
  
  def encodeBody = {
    val buf       = Buffer.fromChannelBuffer(packet.toChannelBuffer)
    val bufReader = BufferReader(buf)
    bufReader.readByte // tested in encodeMessageTypeByte
    bufReader.readInt  // tested in encodeLength

    bufReader.readInt must_== 0
  }

  def encodeNoMessageTypeByte = {
    val versionBytes      = Array[Byte](0x0, 0x3, 0x0, 0x0, 0x13)
    val userBytes         = Array[Byte](0x75, 0x73, 0x65, 0x72, 0x0)
    val testUserBytes     = Array[Byte](0x74, 0x65, 0x73, 0x74, 0x55, 0x73, 0x65, 0x72, 0x0)
    val databaseBytes     = Array[Byte](0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x0)
    val databaseNameBytes = Array[Byte](0x74, 0x65, 0x73, 0x74, 0x5F, 0x64, 0x61, 0x74, 0x61, 0x62,
      0x61, 0x73, 0x65, 0x0)
    val bs        = versionBytes ++ userBytes ++ testUserBytes ++ databaseBytes ++ databaseNameBytes
    val p         = Packet(None, Buffer(bs))
    val buf       = Buffer.fromChannelBuffer(p.toChannelBuffer)
    val bufReader = BufferReader(buf)

    val _ = bufReader.readInt
    bufReader.readInt must_== 196608
  }

  private val messageType = Some('R')
  private val bytes       = Array[Byte](0x0,0x0,0x0,0x0)
  private val packet      = Packet(messageType, Buffer(bytes))
} 
Example 27
Source File: BufferReaderSpec.scala    From roc   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package roc
package postgresql
package transport

import org.specs2.Specification
import org.specs2.specification.core._

final class BufferReaderSpec extends Specification { def is = s2"""

  BufferReader should
    read Bytes from an Array                                $readBytes
    read Shorts from an Array                               $readShorts
    read Int24s and remaining Short from an Array           $readInt24s
    read Ints from an Array                                 $readInts
    read Signed Int from an Array                           $readSignedInt
    read Long from an Array                                 $readLong
    read C-Style String from an Array                       $readNullTerminatedString
                                                            """

  def readBytes = {
    val br    = BufferReader(bytes)
    val exec1 = br.readByte must_== 0x11
    val exec2 = br.readByte must_== 0x22
    val exec3 = br.readByte must_== 0x33
    val exec4 = br.readByte must_== 0x44
    val exec5 = br.readByte must_== 0x55
    val exec6 = br.readByte must_== 0x66
    val exec7 = br.readByte must_== 0x77
    val exec8 = br.readByte must_== 0x78
    
    Fragments(ff.break, ff.example("read 1st byte".formatted("%19s"), exec1))
      .append(Fragments(ff.break, ff.example("read 2nd byte".formatted("%19s"), exec2)))
      .append(Fragments(ff.break, ff.example("read 3rd byte".formatted("%19s"), exec3)))
      .append(Fragments(ff.break, ff.example("read 4th byte".formatted("%19s"), exec4)))
      .append(Fragments(ff.break, ff.example("read 5th byte".formatted("%19s"), exec5)))
      .append(Fragments(ff.break, ff.example("read 6th byte".formatted("%19s"), exec6)))
      .append(Fragments(ff.break, ff.example("read 7th byte".formatted("%19s"), exec7)))
      .append(Fragments(ff.break, ff.example("read 8th byte".formatted("%19s"), exec8)))
  }

  def readShorts = {
    val br    = BufferReader(bytes)
    val exec1 = br.readShort must_== 0x1122
    val exec2 = br.readShort must_== 0x3344
    val exec3 = br.readShort must_== 0x5566
    val exec4 = br.readShort must_== 0x7778
    
    Fragments(ff.break, ff.example("read 1st short".formatted("%20s"), exec1))
      .append(Fragments(ff.break, ff.example("read 2nd short".formatted("%20s"), exec2)))
      .append(Fragments(ff.break, ff.example("read 3rd short".formatted("%20s"), exec3)))
      .append(Fragments(ff.break, ff.example("read 4th short".formatted("%20s"), exec4)))
  }

  def readInt24s = {
    val br    = BufferReader(bytes)
    val exec1 = br.readInt24 must_== 0x112233
    val exec2 = br.readInt24 must_== 0x445566
    val exec3 = br.readShort must_== 0x7778
   
    Fragments(ff.break, ff.example("read 1st Int24".formatted("%20s"), exec1))
      .append(Fragments(ff.break, ff.example("read 2nd Int24".formatted("%20s"), exec2)))
      .append(Fragments(ff.break, ff.example("read remaining Short".formatted("%26s"), exec3)))
  }

  def readInts = {
    val br    = BufferReader(bytes)
    val exec1 = br.readInt must_== 0x11223344
    val exec2 = br.readInt must_== 0x55667778

    Fragments(ff.break, ff.example("read 1st Int".formatted("%18s"), exec1))
      .append(Fragments(ff.break, ff.example("read 2nd Int".formatted("%18s"), exec2)))
  }

  def readSignedInt = {
    val n = 0xfff6ffff
    val br = BufferReader(Array[Byte](0xff.toByte, 0xf6.toByte, 0xff.toByte, 0xff.toByte))
    br.readInt must_== n 
  }

  def readLong = {
    val br = BufferReader(bytes)
    br.readLong must_== 0x1122334455667778L
  }

  def readNullTerminatedString = {
    val str = "Null Terminated String\u0000"
    val br = BufferReader(str.getBytes)
    br.readNullTerminatedString() must_== str.take(str.size-1)
  }

  private val bytes = Array[Byte](0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x78)
  override val ff = fragmentFactory
} 
Example 28
Source File: JsonSpec.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi
package api

import java.util.UUID

import cats.syntax.either._
import cats.instances.either._
import org.specs2.Specification
import org.specs2.specification.core.SpecStructure
import io.circe._
import io.circe.parser._
import io.circe.syntax._
import org.zalando.kanadi.models.{EventId, SpanCtx}
import java.time.OffsetDateTime

import io.circe.CursorOp.DownField

class JsonSpec extends Specification {
  override def is: SpecStructure = s2"""
    Parse business events         $businessEvent
    Parse data events             $dataEvent
    Parse undefined events        $undefinedEvent
    SpanCtx decoding example      $decodeSpnCtx
    SpanCtx encoding example      $encodeSpnCtx
    SpanCtx fail decoding example $badDecodeSpnCtx
    """

  val uuid      = UUID.randomUUID()
  val testEvent = SomeEvent("Bart", "Simpson", uuid)
  val now       = OffsetDateTime.now()
  val md        = Metadata(eid = EventId("4ae5011e-eb01-11e5-8b4a-1c6f65464fc6"), occurredAt = now)

  val coreEventJson = s"""
    "first_name": "Bart",
    "last_name": "Simpson",
    "uuid": "${uuid.toString}"
  """

  val metadata =
    s""""eid": "4ae5011e-eb01-11e5-8b4a-1c6f65464fc6", "occurred_at": ${now.asJson}"""

  val businessEventJson = s"""{
    "metadata": {$metadata},
    $coreEventJson
  }"""

  val dataEventJson = s"""{
    "metadata": {$metadata},
    "data_op": "C",
    "data": {$coreEventJson},
    "data_type": "blah"
  }"""

  val undefinedEventJson = s"{$coreEventJson}"

  def businessEvent =
    decode[Event[SomeEvent]](businessEventJson) must beRight(Event.Business(testEvent, md))

  def dataEvent =
    decode[Event[SomeEvent]](dataEventJson) must beRight(Event.DataChange(testEvent, "blah", DataOperation.Create, md))

  def undefinedEvent =
    decode[Event[SomeEvent]](undefinedEventJson) must beRight(Event.Undefined(testEvent))

  // Sample data is taken from official Nakadi source at https://github.com/zalando/nakadi/blob/effb2ed7e95bd329ab73ce06b2857aa57510e539/src/test/java/org/zalando/nakadi/validation/JSONSchemaValidationTest.java

  val spanCtxJson =
    """{"eid":"5678","occurred_at":"1992-08-03T10:00:00Z","span_ctx":{"ot-tracer-spanid":"b268f901d5f2b865","ot-tracer-traceid":"e9435c17dabe8238","ot-baggage-foo":"bar"}}"""

  val spanCtxBadJson =
    """{"eid":"5678","occurred_at":"1992-08-03T10:00:00Z","span_ctx":{"ot-tracer-spanid":"b268f901d5f2b865","ot-tracer-traceid":42,"ot-baggage-foo":"bar"}}"""

  val spanCtxEventMetadata = Metadata(
    eid = EventId("5678"),
    occurredAt = OffsetDateTime.parse("1992-08-03T10:00:00Z"),
    spanCtx = Some(
      SpanCtx(
        Map(
          "ot-tracer-spanid"  -> "b268f901d5f2b865",
          "ot-tracer-traceid" -> "e9435c17dabe8238",
          "ot-baggage-foo"    -> "bar"
        )))
  )

  def decodeSpnCtx =
    decode[Metadata](spanCtxJson) must beRight(spanCtxEventMetadata)

  def encodeSpnCtx =
    spanCtxEventMetadata.asJson.pretty(Printer.noSpaces.copy(dropNullValues = true)) mustEqual spanCtxJson

  def badDecodeSpnCtx =
    decode[Metadata](spanCtxBadJson) must beLeft(
      DecodingFailure("String", List(DownField("ot-tracer-traceid"), DownField("span_ctx"))))
} 
Example 29
Source File: OpenApiSchemaSpec.scala    From skeuomorph   with Apache License 2.0 5 votes vote down vote up
package higherkindness.skeuomorph.openapi

import higherkindness.skeuomorph.instances._
import org.typelevel.discipline.specs2.Discipline
import cats.laws.discipline._
import _root_.cats.implicits._
import org.specs2.{ScalaCheck, Specification}
import schema._
import org.scalacheck._
import _root_.io.circe._
import _root_.io.circe.testing._
import _root_.cats.kernel.CommutativeMonoid
import _root_.cats.laws.discipline.arbitrary._
import Spec._

class OpenApiSchemaSpec extends Specification with ScalaCheck with Discipline {

  implicit val miniIntMultiplication: CommutativeMonoid[MiniInt] = MiniInt.miniIntMultiplication

  def is = s2"""
      $shouldAbleCodecRoundTrip
      $shouldAbleToReadSpecExamples
      $functor
      $foldable
      $traverse
    """
  val traverse =
    checkAll(
      "Traverse[JsonSchemaF]",
      TraverseTests[JsonSchemaF].traverse[MiniInt, MiniInt, MiniInt, Set[MiniInt], Option, Option]
    )
  val functor  = checkAll("Functor[JsonSchemaF]", FunctorTests[JsonSchemaF].functor[MiniInt, MiniInt, String])
  val foldable = checkAll("Foldable[JsonSchemaF]", FoldableTests[JsonSchemaF].foldable[MiniInt, MiniInt])

  def shouldAbleCodecRoundTrip =
    Prop.forAll { (openApi: OpenApi[JsonSchemaF.Fixed]) =>
      import JsonEncoders._
      import JsonDecoders._

      CodecTests[OpenApi[JsonSchemaF.Fixed]].laws.codecRoundTrip(openApi)
    }

  def shouldAbleToReadSpecExamples =
    Prop.forAll { (format: Spec.Format) =>
      import JsonDecoders._
      import _root_.higherkindness.skeuomorph.openapi.yaml.{Decoder => YamlDecoder, _}
      format.fold(
        YamlDecoder[OpenApi[JsonSchemaF.Fixed]].apply(_).isRight,
        Decoder[OpenApi[JsonSchemaF.Fixed]].decodeJson(_).isRight
      )
    }
}

object Spec {
  type Yaml   = String
  type Format = Either[String, Json]

  private val examples =
    List("api-with-examples", "callback-example", "link-example", "petstore-expanded", "petstore", "uspto")

  private def fromResource(fileName: String): String =
    scala.io.Source
      .fromInputStream(getClass.getResourceAsStream(fileName))
      .getLines()
      .toList
      .mkString("\n")

  private def examplesArbitrary[A](f: String => String)(g: String => A): Gen[A] =
    Gen.oneOf(
      examples
        .map(x => g(fromResource(f(x))))
    )

  implicit val yamlArbitrary: Arbitrary[Format] =
    Arbitrary(
      eitherGen(
        examplesArbitrary(x => s"/openapi/yaml/$x.yaml")(identity),
        examplesArbitrary(x => s"/openapi/json/$x.json")(helpers.unsafeParse)
      )
    )

} 
Example 30
Source File: TaskInstancesSpecs.scala    From shims   with Apache License 2.0 5 votes vote down vote up
package shims.effect

import cats.Eq
import cats.laws.discipline.{ApplicativeTests, ParallelTests}

import cats.effect.{Async, IO}
import cats.effect.laws.discipline.{arbitrary, EffectTests}, arbitrary._
import cats.effect.laws.util.{TestContext, TestInstances}, TestInstances._

import cats.instances.either._
import cats.instances.int._
import cats.instances.tuple._
import cats.instances.unit._

import scalaz.Tag
import scalaz.concurrent.Task
import scalaz.concurrent.Task.ParallelTask

import org.specs2.Specification
import org.specs2.scalacheck.Parameters
import org.specs2.specification.core.Fragments

import org.typelevel.discipline.Laws
import org.typelevel.discipline.specs2.Discipline

import java.util.concurrent.RejectedExecutionException

import scala.concurrent.ExecutionContext

object TaskInstancesSpecs extends Specification with Discipline {
  import TaskArbitrary._
  import Task.taskParallelApplicativeInstance

  def is = br ^ taskEff ^ br ^ taskPar ^ br ^ parTaskApp ^ br ^ asyncShiftTask

  def taskEff = checkAllAsync("Effect[Task]",
    implicit ctx => EffectTests[Task].effect[Int, Int, Int])

  def taskPar = checkAllAsync("Parallel[Task]",
    implicit ctx => ParallelTests[Task].parallel[Int, Int])

  def parTaskApp = checkAllAsync("Parallel[Task]", { implicit ctx =>
    val tests = ApplicativeTests[ParallelTask]
    tests.applicative[Int, Int, Int]
  })

  def asyncShiftTask = {
    implicit val context: TestContext = TestContext()
    val boom = new RejectedExecutionException("Boom")
    val rejectingEc = new ExecutionContext {
      def execute(runnable: Runnable): Unit = throw boom
      def reportFailure(cause: Throwable): Unit = ()
    }

    "async.shift on rejecting execution context" ! {
      Eq[Task[Unit]].eqv(Async.shift[Task](rejectingEc), Task.fail(boom)) must beTrue
    }
  }

  def checkAllAsync(name: String, f: TestContext => Laws#RuleSet)(implicit p: Parameters) = {
    val context = TestContext()
    val ruleSet = f(context)

    Fragments.foreach(ruleSet.all.properties.toList) {
      case (id, prop) =>
        id ! check(prop, p, defaultFreqMapPretty) ^ br
    }
  }

  implicit def taskEq[A: Eq](implicit ctx: TestContext): Eq[Task[A]] =
    Eq.by(ta => IO.async[A](k => ta.unsafePerformAsync(e => k(e.toEither))))

  implicit def parallelTaskEq[A: Eq](implicit ctx: TestContext): Eq[ParallelTask[A]] =
    Tag.subst(taskEq[A])
} 
Example 31
Source File: MTLSpecs.scala    From shims   with Apache License 2.0 5 votes vote down vote up
package shims.effect

import cats.effect.{ContextShift, IO}
import cats.effect.laws.discipline.{arbitrary, AsyncTests, ConcurrentEffectTests, ConcurrentTests}, arbitrary._
import cats.effect.laws.util.{TestContext, TestInstances}, TestInstances._

import cats.{Eq, Functor, Monad}
import cats.instances.either._
import cats.instances.int._
import cats.instances.option._
import cats.instances.tuple._
import cats.instances.unit._
import cats.syntax.functor._

import scalaz.{EitherT, Kleisli, OptionT, StateT, WriterT}

import org.scalacheck.{Arbitrary, Prop}

import org.specs2.Specification
import org.specs2.scalacheck.Parameters
import org.specs2.specification.core.Fragments

import org.typelevel.discipline.Laws
import org.typelevel.discipline.specs2.Discipline

import scala.concurrent.ExecutionContext
import scala.util.control.NonFatal

import java.io.{ByteArrayOutputStream, PrintStream}

object MTLSpecs extends Specification with Discipline {

  def is =
    br ^ checkAllAsync("OptionT[IO, ?]", implicit ctx => ConcurrentTests[OptionT[IO, ?]].concurrent[Int, Int, Int]) ^
    br ^ checkAllAsync("Kleisli[IO, Int, ?]", implicit ctx => ConcurrentTests[Kleisli[IO, Int, ?]].concurrent[Int, Int, Int]) ^
    br ^ checkAllAsync("EitherT[IO, Throwable, ?]", implicit ctx => ConcurrentEffectTests[EitherT[IO, Throwable, ?]].concurrentEffect[Int, Int, Int]) ^
    br ^ checkAllAsync("StateT[IO, Int, ?]", implicit ctx => AsyncTests[StateT[IO, Int, ?]].async[Int, Int, Int]) ^
    br ^ checkAllAsync("WriterT[IO, Int, ?]", implicit ctx => ConcurrentEffectTests[WriterT[IO, Int, ?]].concurrentEffect[Int, Int, Int])

  def checkAllAsync(name: String, f: TestContext => Laws#RuleSet)(implicit p: Parameters) = {
    val context = TestContext()
    val ruleSet = f(context)

    Fragments.foreach(ruleSet.all.properties.toList) {
      case (id, prop) =>
        s"$name.$id" ! check(Prop(p => silenceSystemErr(prop(p))), p, defaultFreqMapPretty) ^ br
    }
  }

  implicit def iocsForEC(implicit ec: ExecutionContext): ContextShift[IO] =
    IO.contextShift(ec)

  implicit def optionTArbitrary[F[_], A](implicit arbFA: Arbitrary[F[Option[A]]]): Arbitrary[OptionT[F, A]] =
    Arbitrary(arbFA.arbitrary.map(OptionT.optionT(_)))

  implicit def kleisliArbitrary[F[_], R, A](implicit arbRFA: Arbitrary[R => F[A]]): Arbitrary[Kleisli[F, R, A]] =
    Arbitrary(arbRFA.arbitrary.map(Kleisli(_)))

  implicit def eitherTArbitrary[F[_]: Functor, L, A](implicit arbEA: Arbitrary[F[Either[L, A]]]): Arbitrary[EitherT[F, L, A]] =
    Arbitrary(arbEA.arbitrary.map(fe => EitherT.eitherT(fe.map(_.asScalaz))))

  implicit def stateTArbitrary[F[_]: Monad, S, A](implicit arbSFA: Arbitrary[S => F[(S, A)]]): Arbitrary[StateT[F, S, A]] =
    Arbitrary(arbSFA.arbitrary.map(StateT(_)))

  implicit def writerTArbitrary[F[_], L, A](implicit arbFLA: Arbitrary[F[(L, A)]]): Arbitrary[WriterT[F, L, A]] =
    Arbitrary(arbFLA.arbitrary.map(WriterT(_)))

  implicit def kleisliEq[F[_], A](implicit eqv: Eq[F[A]]): Eq[Kleisli[F, Int, A]] =
    Eq.by(_(42))   // totally random and comprehensive seed

  implicit def stateTEq[F[_]: Monad, S, A](implicit eqv: Eq[F[(Int, A)]]): Eq[StateT[F, Int, A]] =
    Eq.by(_.run(42))   // totally random and comprehensive seed

  // copied from cats-effect
  private def silenceSystemErr[A](thunk: => A): A = synchronized {
    // Silencing System.err
    val oldErr = System.err
    val outStream = new ByteArrayOutputStream()
    val fakeErr = new PrintStream(outStream)
    System.setErr(fakeErr)
    try {
      val result = thunk
      System.setErr(oldErr)
      result
    } catch {
      case NonFatal(e) =>
        System.setErr(oldErr)
        // In case of errors, print whatever was caught
        fakeErr.close()
        val out = outStream.toString("utf-8")
        if (out.nonEmpty) oldErr.println(out)
        throw e
    }
  }
} 
Example 32
Source File: ReaderOfMacroSpec.scala    From grafter   with MIT License 5 votes vote down vote up
package org.zalando.grafter.macros

import org.specs2.Specification
import org.specs2.matcher._
import org.specs2.execute._
import Typecheck._

class ReaderOfMacroSpec extends Specification with TypecheckMatchers { def is = s2"""

 the reader annotation can be used to declare a reader for a given config type $useAnnotation
 an annotation not placed on a class must not compile $compilationError

"""

  def useAnnotation = {
    R1.reader.apply(ApplicationConfig()).r3.r4.s ==== "hello"
  }

  def compilationError = {
    tc"""
       @readerOf[String]
       object O

    """ must failWith("the @readerOf annotation must annotate a class, found object O")
  }

}

object ReaderOfMacroTest {
  val r1: cats.data.Reader[ApplicationConfig, C] = C.reader
}

case class ApplicationConfig()

@readerOf[ApplicationConfig]
case class C()

//This will not compile because the type parameter is missing
//@reader
//case class CC()

@readerOf[ApplicationConfig]
case class R1(r2: R2, r3: R3, r4: R4) {
  private val field1 = "should not be used for the reader instance"
  println(field1)
}

@readerOf[ApplicationConfig]
case class R2()

@readerOf[ApplicationConfig]
case class R3(r4: R4)

case class R4(s: String)

object R4 {
  implicit def reader: cats.data.Reader[ApplicationConfig, R4] =
    cats.data.Reader(_ => R4("hello"))
} 
Example 33
Source File: ComponentsMatchersSpec.scala    From grafter   with MIT License 5 votes vote down vote up
package org.zalando.grafter

import org.specs2.Specification
import org.zalando.grafter.specs2.matcher._

class ComponentsMatchersSpec extends Specification with ComponentsMatchers { def is = s2"""

  A matcher can be used to check the contents of an application graph $useMatcher
  when there's a failure $showFailure

"""

  val application = Application()

  def useMatcher = {
    application must containInstances(
      classOf[Service1] -> 1,
      classOf[Service2] -> 1,
      classOf[Service3] -> 2
    )
  }

  def showFailure = {
    val result =
      application must containInstances(
        classOf[Service1] -> 1,
        classOf[Service4] -> 1,
        classOf[Service3] -> 1
      )

    result.message ====
      """|Application
         |is missing
         |  Service4 -> 1
         |doesn't have the right number of components for
         |  Service3 -> actual: 2, expected: 1""".stripMargin
  }
}

case class Application(service1: Service1 = Service1(), service2: Service2 = Service2())
case class Service1(service3: Service3 = Service3())
case class Service2(service3: Service3 = Service3())
case class Service3()
case class Service4() 
Example 34
Source File: SshClientSpec.scala    From scala-ssh   with Apache License 2.0 5 votes vote down vote up
package com.decodified.scalassh

import org.specs2.Specification
import java.io.File
import java.io.FileWriter
import io.Source
import Source.{ fromFile ⇒ open }
import org.specs2.execute.{ Failure, FailureException }

class SshClientSpec extends Specification {
  sequential

  def is =
    "The SshClient should be able to" ^
      "properly connect to the test host and fetch a directory listing" ! simpleTest ^
      "properly connect to the test host and execute three independent commands" ! threeCommandsTest ^
      "properly upload to the test host" ! fileUploadTest ^
      "properly download to the test host" ! fileDownloadTest

  def simpleTest = {
    SSH(testHostName) { client ⇒
      client.exec("ls -a").right.map { result ⇒
        result.stdOutAsString() + "|" + result.stdErrAsString()
      }
    }.right.get must startWith(".\n..\n")
  }

  def threeCommandsTest = {
    SSH(testHostName) { client ⇒
      client.exec("ls").right.flatMap { res1 ⇒
        println("OK 1")
        client.exec("dfssgsdg").right.flatMap { res2 ⇒
          println("OK 2")
          client.exec("uname").right.map { res3 ⇒
            println("OK 3")
            (res1.exitCode, res2.exitCode, res3.exitCode)
          }
        }
      }
    } mustEqual Right((Some(0), Some(127), Some(0)))
  }

  def fileUploadTest = {
    val testFile = make(new File(testFileName)) { file ⇒
      val writer = new FileWriter(file)
      writer.write(testText)
      writer.close()
    }

    SSH(testHostName) { client ⇒
      try client.upload(testFile.getAbsolutePath, testFileName).right.flatMap { _ ⇒
        client.exec("cat " + testFileName).right.map { result ⇒
          testFile.delete()
          result.stdOutAsString()
        }
      }
      finally client.close()
    } mustEqual Right(testText)
  }

  def fileDownloadTest = {
    SSH(testHostName) { client ⇒
      try client.download(testFileName, testFileName).right.map { _ ⇒
        make(open(testFileName).getLines.mkString) { _ ⇒
          new File(testFileName).delete()
        }
      }
      finally client.close()
    } mustEqual Right(testText)
  }

  lazy val testFileName = "testUpload.txt"
  lazy val testText = "Hello, Scala SSH!"

  lazy val testHostName = {
    val fileName = HostFileConfig.DefaultHostFileDir + File.separator + ".testhost"
    try {
      Source.fromFile(fileName).getLines().toList.head
    } catch {
      case e: Exception ⇒ throw FailureException(Failure(("Could not find file '%s', you need to create it holding " +
        "nothing but the name of the test host you would like to run your tests against!").format(fileName), e.toString))
    }
  }
} 
Example 35
Source File: StreamingFormulaDemo1.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.spark.demo

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.ScalaCheck
import org.specs2.Specification
import org.specs2.matcher.ResultMatchers
import org.scalacheck.Arbitrary.arbitrary

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.Duration
import org.apache.spark.streaming.dstream.DStream

import es.ucm.fdi.sscheck.spark.streaming.SharedStreamingContextBeforeAfterEach
import es.ucm.fdi.sscheck.prop.tl.{Formula,DStreamTLProperty}
import es.ucm.fdi.sscheck.prop.tl.Formula._
import es.ucm.fdi.sscheck.gen.{PDStreamGen,BatchGen}

@RunWith(classOf[JUnitRunner])
class StreamingFormulaDemo1 
  extends Specification 
  with DStreamTLProperty
  with ResultMatchers
  with ScalaCheck {
  
  // Spark configuration
  override def sparkMaster : String = "local[*]"
  override def batchDuration = Duration(150)
  override def defaultParallelism = 4  

  def is = 
    sequential ^ s2"""
    Simple demo Specs2 example for ScalaCheck properties with temporal
    formulas on Spark Streaming programs
      - where a simple property for DStream.count is a success ${countForallAlwaysProp(_.count)}     
      - where a faulty implementation of the DStream.count is detected ${countForallAlwaysProp(faultyCount) must beFailing}
    """
      
  def faultyCount(ds : DStream[Double]) : DStream[Long] = 
    ds.count.transform(_.map(_ - 1))
      
  def countForallAlwaysProp(testSubject : DStream[Double] => DStream[Long]) = {
    type U = (RDD[Double], RDD[Long])
    val (inBatch, transBatch) = ((_ : U)._1, (_ : U)._2)
    val numBatches = 10
    val formula : Formula[U] = always { (u : U) =>
      transBatch(u).count === 1 and
      inBatch(u).count === transBatch(u).first 
    } during numBatches

    val gen = BatchGen.always(BatchGen.ofNtoM(10, 50, arbitrary[Double]), numBatches)
    
    forAllDStream(
      gen)(
      testSubject)(
      formula)
  }.set(minTestsOk = 10).verbose  
  
}