org.specs2.specification.core.Fragments Scala Examples

The following examples show how to use org.specs2.specification.core.Fragments. 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: 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 2
Source File: Specs2Interface.scala    From jsonapi-scala   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package spray.testkit

import org.specs2.execute.{Failure, FailureException}
import org.specs2.specification.core.{Fragments, SpecificationStructure}
import org.specs2.specification.create.DefaultFragmentFactory

trait Specs2Interface extends TestFrameworkInterface with SpecificationStructure {

  def failTest(msg: String) = {
    val trace      = new Exception().getStackTrace.toList
    val fixedTrace = trace.drop(trace.indexWhere(_.getClassName.startsWith("org.specs2")) - 1)
    throw new FailureException(Failure(msg, stackTrace = fixedTrace))
  }

  override def map(fs: ⇒ Fragments) = super.map(fs).append(DefaultFragmentFactory.step(cleanUp()))
}

trait NoAutoHtmlLinkFragments extends org.specs2.specification.dsl.ReferenceDsl {
  override def linkFragment(alias: String) = super.linkFragment(alias)
  override def seeFragment(alias: String)  = super.seeFragment(alias)
} 
Example 3
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 4
Source File: Specs2RouteTest.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container

import akka.http.scaladsl.testkit.{RouteTest, TestFrameworkInterface}
import org.specs2.execute.{Failure, FailureException}
import org.specs2.specification.AfterAll
import org.specs2.specification.core.{Fragments, SpecificationStructure}
import org.specs2.specification.dsl.ActionDsl

trait Specs2Interface extends TestFrameworkInterface with SpecificationStructure with ActionDsl with AfterAll {

  def afterAll(): Unit = {
    cleanUp()
  }

  def failTest(msg: String) = {
    val trace = new Exception().getStackTrace.toList
    val fixedTrace = trace.drop(trace.indexWhere(_.getClassName.startsWith("org.specs2")) - 1)
    throw new FailureException(Failure(msg, stackTrace = fixedTrace))
  }

  override def map(fs: ⇒ Fragments) = super.map(fs).append(step(cleanUp()))
}

trait Specs2RouteTest extends RouteTest with Specs2Interface 
Example 5
Source File: TextUtilsSpec.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.util

import org.specs2.specification._
import org.specs2.specification.core.Fragments
import org.specs2.mutable._

import mimir.algebra._

object TextUtilsSpec
  extends Specification
{
  
  "TextUtils" should {

    "Parse Primitive Values" >> {

      Fragments.foreach(Seq(

        (TInt(),    "1",       IntPrimitive(1)),
        (TFloat(),  "1.0",     FloatPrimitive(1.0)),
        (TFloat(),  "1",       FloatPrimitive(1.0)),
        (TFloat(),  "1e-2",    FloatPrimitive(0.01)),
        (TBool(),   "YES",     BoolPrimitive(true)),
        (TBool(),   "yes",     BoolPrimitive(true)),
        (TBool(),   "True",    BoolPrimitive(true)),
        (TBool(),   "NO",      BoolPrimitive(false)),
        (TBool(),   "0",       BoolPrimitive(false)),
        (TType(),   "int",     TypePrimitive(TInt())),
        (TType(),   "zipcode", TypePrimitive(TUser("zipcode")))

      )) { case (t, str, v) =>
        s"CAST('$str' AS $t) == $v" >> {
          TextUtils.parsePrimitive(t, str) must be equalTo(v)
        }
      }
    }

    "Parse Dates" >> {

      TextUtils.parseDate("2017-02-12") must be equalTo(DatePrimitive(2017, 2, 12))

    }

    "Parse Timestamps" >> {

      TextUtils.parseTimestamp("2017-02-12 02:12:16") must be equalTo(TimestampPrimitive(2017, 2, 12, 2, 12, 16, 0))
      TextUtils.parseTimestamp("2013-10-07 08:23:19.120") must be equalTo(TimestampPrimitive(2013, 10, 7, 8, 23, 19, 120))
      TextUtils.parseTimestamp("2013-10-07 08:23:19.12") must be equalTo(TimestampPrimitive(2013, 10, 7, 8, 23, 19, 120))
      TextUtils.parseTimestamp("2013-10-07 08:23:19.1") must be equalTo(TimestampPrimitive(2013, 10, 7, 8, 23, 19, 100))
      TextUtils.parseTimestamp("2013-10-07 08:23:19.1201") must be equalTo(TimestampPrimitive(2013, 10, 7, 8, 23, 19, 120))

    }

  }

} 
Example 6
Source File: SerializationSpec.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.algebra;

import java.io._
import org.specs2.mutable._
import org.specs2.specification.core.{Fragment,Fragments}
import org.specs2.specification._

import mimir.util._
import mimir.test._
import mimir.serialization._
import mimir.parser.SQLStatement

object SqlFilesOnly extends FileFilter {

  def accept(f: File) =
  {
    f.getName().split("\\.").reverse.head.toLowerCase == "sql"
  }

}


object SerializationSpec extends SQLTestSpecification("SerializationTest") with BeforeAll {

  def beforeAll = {
    loadCSV(targetTable = "R", 
      sourceFile = "test/data/serial_r.csv"
    )
    loadCSV(targetTable = "S", 
      sourceFile = "test/data/serial_s.csv"
    )
    loadCSV(targetTable = "T", 
      sourceFile = "test/data/serial_t.csv"
    )
  }

  "The Algebra Serializer" should {
    val testDirectory = new File("test/sanity/simple")

    "Pass Simple Tests" >> {
      Fragments.foreach(
        testDirectory.
          listFiles(SqlFilesOnly)
      ) { case (file:File) =>
        file.getName().split("\\.").head in {
          var i = 0 
          stmts(file).map({
            case SQLStatement(s:sparsity.statement.Select) => {
              i = i + 1;
              // println(s"$file -> parsed: $s")
              val query = db.sqlToRA(s)
              // println(s"converted: $query")
              val serialized = Json.ofOperator(query)
              // println(s"serialized: $serialized")
              val deserialized = Json.toOperator(serialized)
              // println(s"deserialized: $deserialized")

              Some(deserialized must be equalTo query)
            }
 
            case stmt => throw new Exception("Simple test cases shouldn't have updates ($stmt)")
          }).flatten
        }
      }
    }

    "Co/Dec Special Cases" >> {
      Fragments.foreach(Seq[(String, (()=> Operator))](
        "Uniform Samples" -> { () => 
          db.table("T").sampleUniformly(0.1) 
        },
        "Stratified Samples" -> { () => 
          db.table("T").stratifiedSample(
            "C", TInt(), 
            Map(IntPrimitive(1) -> 0.1), 
            caveat = Some( (ID("stuff"), "a warning") )
          )
        }
      )) { case (title: String, gen:(() => Operator)) =>
        title in {
          val raw = gen()
          val serialized = Json.ofOperator(raw)
          val deserialized = Json.toOperator(serialized)

          Seq(deserialized must be equalTo raw)
        }
      }

    }
  }

} 
Example 7
Source File: TimeSeqScenarios.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.demo

import java.io._
import org.specs2.reporter.LineLogger
import org.specs2.specification.core.{Fragment,Fragments}

import mimir.test._
import mimir.util._
import mimir.algebra.ID

object TimeSeqScenarios
  extends SQLTestSpecification("TimeSeq")
{

  sequential

  "The Trivial Time Series" should {

    "Load correctly" >> {
      update("LOAD 'test/data/seq.csv'")
      ok
    }

    "run limit queries" >> {
      query("select T, A, B from seq limit 20"){ _.toSeq must have size(20) }
    }

    "run order-by limit queries" >> {
      query("select T, A, B from seq order by t limit 20"){ 
        _.toSeq.reverse.head(ID("T")).asLong must beEqualTo(20)
      }
      query("select T, A, B from seq order by t desc limit 20"){
        _.toSeq.reverse.head(ID("T")).asLong must beEqualTo(9980)
      }
    }

    "generate categories correctly" >> {
      query("""
        select T, A, B, 
          case when a is not null then 'A' 
               when b is not null then 'B' 
               else 'C' 
          end as cat from seq limit 20
      """) { _.map { _(3).asString }.toSet must contain("A", "B", "C") }
    }

  }

} 
Example 8
Source File: MissingValueSpec.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.lenses

import java.io._
import org.specs2.reporter.LineLogger
import org.specs2.specification.core.{Fragment,Fragments}

import mimir.test._
import mimir.util._
import LoggerUtils.trace
import mimir.ctables._
import mimir.algebra.{NullPrimitive,MissingVariable}

object MissingValueSpec  
extends SQLTestSpecification("MissingValueSpec")
{
  
  "The Missing Value Lens" should {
  
    loadCSV(
		  	sourceFile = "test/data/mv.csv", 
		  	targetTable = "mv", 
		  	inferTypes = true,
		  	detectHeaders = true
		  )
  
    "Create the Lens and query it" >> {
      update("""
          CREATE LENS MV1 
          AS SELECT * FROM mv 
          WITH MISSING_VALUE('B');
        """)
        
        query("SELECT * FROM MV1;") { _.toList.map(_.tuple.last) must be equalTo List(f(5.0), f(3.5), f(2.0), f(4.0),f(5.0), f(3.5), f(2.0), f(2.0)) }
      
      }
  
  }
} 
Example 9
Source File: LensManagerSpec.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.lenses

import java.io._
import org.specs2.specification.core.{Fragment,Fragments}

import mimir.algebra._
import mimir.util._
import mimir.ctables.InlineVGTerms
import mimir.optimizer.operator.InlineProjections
import mimir.test._
import mimir.models._

object LensManagerSpec extends SQLTestSpecification("LensTests") {

  sequential

  "The Lens Manager" should {

    "Be able to create and query missing value lenses" >> {
      loadCSV(
        targetTable = "R", 
        sourceFile = "test/r_test/r.csv",
        targetSchema = Seq("A", "B", "C")
      )
      queryOneColumn("SELECT B FROM R"){ _.toSeq should contain(NullPrimitive()) }
      update("CREATE LENS SANER AS SELECT * FROM R WITH MISSING_VALUE('B')")
      queryOneColumn("SELECT B FROM SANER"){ _.toSeq should not contain(NullPrimitive()) }
    }

    "Produce reasonable views" >> {
      db.loader.loadTable(targetTable = Some(ID("CPUSPEED")), sourceFile = "test/data/CPUSpeed.csv")
      val resolved1 = InlineProjections(db.views.resolve(db.table("CPUSPEED")))
      resolved1 must beAnInstanceOf[Project]
      val resolved2 = resolved1.asInstanceOf[Project]
      val coresColumnId = db.table("CPUSPEED").columnNames.indexOf(ID("CORES"))
      val coresModel = db.models.get(ID("MIMIR_TI_ATTR_CPUSPEED_TI"))

      // Make sure the model name is right.
      // Changes to the way the type inference lens assigns names will need to
      // be reflected above.  That's the only thing that should cause this test
      // to fail.
      coresModel must not be empty

      coresModel.reason(0, List(IntPrimitive(coresColumnId)), List()) must contain("I guessed that CPUSPEED.CORES was of type INT because all of the data fit")

      val coresGuess1 = coresModel.bestGuess(0, List(IntPrimitive(coresColumnId)), List())
      coresGuess1 must be equalTo(TypePrimitive(TInt()))

      val coresGuess2 = InlineVGTerms(VGTerm(coresModel.name, 0, List(IntPrimitive(coresColumnId)), List()), db)
      coresGuess2 must be equalTo(TypePrimitive(TInt()))


    }

    "Clean up after a DROP LENS" >> {

      val modelNamesBefore = db.models.associatedModels(ID("LENS:SANER"))
      modelNamesBefore must not beEmpty

      update("DROP LENS SANER");
      table("SANER") must throwA[Exception]

      val modelNamesAfter = db.models.associatedModels(ID("LENS:SANER"))
      modelNamesAfter must beEmpty
    }

  }  

} 
Example 10
Source File: RemoteSpecs.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema

import com.eclipsesource.schema.drafts.Version4
import com.eclipsesource.schema.test.{Assets, JsonSpec}
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import org.specs2.specification.core.Fragments
import org.specs2.specification.dsl.Online
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc.DefaultActionBuilder
import play.api.test.TestServer

class RemoteSpecs extends Specification with JsonSpec with Online with AfterAll {

  import Version4._

  implicit val validator: SchemaValidator = {
    SchemaValidator(Some(Version4)).addSchema(
      "http://localhost:1234/scope_foo.json",
      JsonSource.schemaFromString(
        """{
          |  "definitions": {
          |    "bar": { "type": "string" }
          |  }
          |}""".stripMargin
      ).get
    )
  }

  def createApp: Application = new GuiceApplicationBuilder()
    .appRoutes(app => {
      val Action = app.injector.instanceOf[DefaultActionBuilder]
      Assets.routes(Action)(getClass, "remotes/")
    })
    .build()

  lazy val server = TestServer(port = 1234, createApp)

  def afterAll: Unit = {
    server.stop
    Thread.sleep(1000)
  }

  def validateAjv(testName: String): Fragments = validate(testName, "ajv_tests")

  sequential

  "Validation from remote resources is possible" >> {
    {
      server.start
      Thread.sleep(1000)
    } must not(throwAn[Exception]) continueWith {
      validateMultiple(
        "ajv_tests" -> Seq(
          "5_adding_dependency_after",
          "5_recursive_references",
          "12_restoring_root_after_resolve",
          "13_root_ref_in_ref_in_remote_ref",
          "14_ref_in_remote_ref_with_id",
          "62_resolution_scope_change"
        ),
        "draft4" -> Seq("refRemote")
      )
    }
  }

  validateAjv("1_ids_in_refs")
} 
Example 11
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 12
Source File: SerializationTest.scala    From scala-serialization   with MIT License 5 votes vote down vote up
package com.komanov.serialization.converters

import java.io.ByteArrayOutputStream

import com.komanov.serialization.domain.SiteEventData
import org.apache.commons.io.HexDump
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope
import org.specs2.specification.core.Fragments

class SerializationTest extends SpecificationWithJUnit {

  sequential

  doTest("JSON", JsonConverter)
  doTest("ScalaPB", ScalaPbConverter)
  doTest("Java Protobuf", JavaPbConverter)
  doTest("Java Thrift", JavaThriftConverter)
  doTest("Scrooge", ScroogeConverter)
  doTest("Serializable", JavaSerializationConverter)
  doTest("Pickling", PicklingConverter)
  doTest("BooPickle", BoopickleConverter)
  doTest("Chill", ChillConverter)

  "ScalaPB and Java Protobuf" should {
    Fragments.foreach(TestData.sites) { case (name, site) =>
      s"be interoperable for site of $name" in new ctx {
        val javaMessage = JavaPbConverter.toByteArray(site)
        val scalaMessage = ScalaPbConverter.toByteArray(site)
        toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
      }
    }

    Fragments.foreach(TestData.events) { case (name, events) =>
      s"be interoperable events of $name" in new ctx {
        for (SiteEventData(_, event, _) <- events) {
          val javaMessage = JavaPbConverter.toByteArray(event)
          val scalaMessage = ScalaPbConverter.toByteArray(event)
          toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
        }
      }
    }
  }

  "Scrooge and Java Thrift" should {
    Fragments.foreach(TestData.sites) { case (name, site) =>
      s"be interoperable for site of $name" in new ctx {
        val javaMessage = JavaThriftConverter.toByteArray(site)
        val scalaMessage = ScroogeConverter.toByteArray(site)
        toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
      }
    }

    Fragments.foreach(TestData.events) { case (name, events) =>
      s"be interoperable events of $name" in new ctx {
        for (SiteEventData(_, event, _) <- events) {
          val javaMessage = JavaThriftConverter.toByteArray(event)
          val scalaMessage = ScroogeConverter.toByteArray(event)
          toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
        }
      }
    }
  }

  class ctx extends Scope

  def toHexDump(arr: Array[Byte]): String = {
    if (arr.isEmpty) {
      ""
    } else {
      val baos = new ByteArrayOutputStream
      HexDump.dump(arr, 0, baos, 0)
      new String(baos.toByteArray)
    }
  }

  def doTest(converterName: String, converter: MyConverter) = {
    converterName should {
      Fragments.foreach(TestData.sites) { case (name, site) =>
        s"serialize-parse site of $name" in new ctx {
          val bytes = converter.toByteArray(site)
          val parsed = converter.fromByteArray(bytes)
          parsed must be_===(site)
        }
      }

      Fragments.foreach(TestData.events) { case (name, events) =>
        s"serialize-parse site events of $name" in new ctx {
          for (SiteEventData(_, event, _) <- events) {
            val bytes = converter.toByteArray(event)
            val parsed = converter.siteEventFromByteArray(event.getClass, bytes)
            parsed must be_===(event)
          }
        }
      }
    }
  }

} 
Example 13
Source File: BeforeAfterAllStopOnError.scala    From docker-it-scala   with MIT License 5 votes vote down vote up
package com.whisk.docker.specs2

import org.specs2.specification.core.{Fragments, SpecificationStructure}
import org.specs2.specification.create.FragmentsFactory

trait BeforeAfterAllStopOnError extends SpecificationStructure with FragmentsFactory {

  def beforeAll()
  def afterAll()

  override def map(fs: => Fragments) =
    super
      .map(fs)
      .prepend(
        fragmentFactory.step(beforeAll()).stopOnError
      )
      .append(fragmentFactory.step(afterAll()))
} 
Example 14
Source File: scalaIdentifierSpec.scala    From tscfg   with Apache License 2.0 5 votes vote down vote up
package tscfg

import org.specs2.mutable.Specification
import org.specs2.specification.core.Fragments
import tscfg.generators.scala.ScalaUtil
import tscfg.generators.scala.ScalaUtil.scalaReservedWords

import scala.util.Random

object scalaIdentifierSpec extends Specification {

  """scalaIdentifier""" should {
    val scalaUtil: ScalaUtil = new ScalaUtil()
    import scalaUtil.scalaIdentifier


    List("foo", "bar_3", "$baz").foldLeft(Fragments.empty) { (res, id) =>
      res.append(s"""keep valid identifier "$id"""" in {
        scalaIdentifier(id) must_== id
      })
    }

    Random.shuffle(scalaReservedWords).take(3).foldLeft(Fragments.empty) { (res, w) =>
      val e = "`" +w + "`"
      res.append(s"""convert scala reserved word "$w" to "$e"""" in {
        scalaIdentifier(w) must_== e
      })
    }

    List("foo-bar", "foo:bar", "foo#bar").foldLeft(Fragments.empty) { (res, id) =>
      res.append(s"""replace non scala id character with '_': "$id" -> "foo_bar"""" in {
        scalaIdentifier(id) must_== "foo_bar"
      })
    }

    s"""prefix with '_' if first character is valid but not at first position: "21" -> "_21"""" in {
      scalaIdentifier("21") must_== "_21"
    }
  }

  """scalaIdentifier with useBackticks=true""" should {
    val scalaUtil: ScalaUtil = new ScalaUtil(useBackticks = true)
    import scalaUtil.scalaIdentifier

    List("foo-bar", "foo:bar", "foo#bar").foldLeft(Fragments.empty) { (res, id) =>
      res.append(s"""put non scala id with backticks: "$id" -> "`$id`"""" in {
        scalaIdentifier(id) must_== s"`$id`"
      })
    }

    List("0", "1", "3").foldLeft(Fragments.empty) { (res, id) =>
      res.append(s"""put literal number with backticks: "$id" -> "`$id`"""" in {
        scalaIdentifier(id) must_== s"`$id`"
      })
    }
  }
} 
Example 15
Source File: JavaIdentifierSpec.scala    From tscfg   with Apache License 2.0 5 votes vote down vote up
package tscfg

import org.specs2.mutable.Specification
import org.specs2.specification.core.Fragments
import tscfg.generators.java.javaUtil.{javaKeywords, javaIdentifier}
import scala.util.Random

object javaIdentifierSpec extends Specification {

  """javaIdentifier""" should {

    List("foo", "bar_3", "$baz").foldLeft(Fragments.empty) { (res, id) =>
      res.append(s"""keep valid identifier "$id"""" in {
        javaIdentifier(id) must_== id
      })
    }

    Random.shuffle(javaKeywords).take(3).foldLeft(Fragments.empty) { (res, kw) =>
      res.append(s"""convert java keyword "$kw" to "${kw}_"""" in {
        javaIdentifier(kw) must_== kw + "_"
      })
    }

    List("foo-bar", "foo:bar", "foo#bar").foldLeft(Fragments.empty) { (res, id) =>
      res.append(s"""replace non java id character with '_': "$id" -> "foo_bar"""" in {
        javaIdentifier(id) must_== "foo_bar"
      })
    }

    s"""prefix with '_' if first character is valid but not at first position: "21" -> "_21"""" in {
      javaIdentifier("21") must_== "_21"
    }
  }
} 
Example 16
Source File: ResourcesTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.model

import com.wix.bazel.migrator.model.ResourcesTest._
import com.wix.bazel.migrator.model.Target.Resources
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.core.Fragments

class ResourcesTest extends SpecificationWithJUnit {

  "Resources.applicablePackage" should {
    Fragments.foreach(packageRelativePathToApplicability) { case (packageRelativePath, isApplicable) =>
      s"return ${asString(isApplicable)} ($isApplicable) for $packageRelativePath" in {
        Resources.applicablePackage(packageRelativePath) ==== isApplicable
      }
    }
  }
  
  "Resources.apply" should {
    "return CodePurpose according to package relative path" in {
      Resources("foo", "src/main/scala").codePurpose must be_===(CodePurpose.Prod()) and
        (Resources("foo", "src/test/scala").codePurpose must be_===(CodePurpose.TestSupport))
    }
  }

  val packageRelativePathToApplicability = Seq(
    "/src/main/resources/" -> Applicable,
    "/src/main/java/" -> NotApplicable,
    "/src/foo/resources/" -> Applicable,
    "/src/main/java/com/wix/resources/"  -> NotApplicable
  ).map(prependModulePrefix)

  private def prependModulePrefix(path: (String, Boolean)) = (ModulePrefix + path._1, path._2)

  private def asString(isApplicable: Boolean) = if (isApplicable) "applicable" else "not applicable"
}

object ResourcesTest {
  private val Applicable = true
  private val NotApplicable = false
  private val ModulePrefix = "/some/module"
} 
Example 17
Source File: TestTypeTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.model

import com.wix.bazel.migrator.model.TestType._
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.core.Fragments

//Below is in comment due to https://github.com/etorreborre/specs2/issues/565
//class TestTypeTest extends SpecWithJUnit with TypedEqual with ExampleDsl with FragmentsDsl {
class TestTypeTest extends SpecificationWithJUnit {

  "TestType.from" should {
    Fragments.foreach(testPathToTestTypes) { case (fileName, testType) =>
      s"return $testType for $fileName" in {
        TestType.from(fileName) ==== testType
      }
    }
  }

  val testPathToTestTypes = Seq("SomeTest.scala" -> UT,
    "SomeIT.java" -> ITE2E,
    "SomeE2E.java" -> ITE2E,
    "ITSome.java" -> ITE2E,
    "E2ESome.java" -> ITE2E,
    "TestSome.java" -> UT,
    "ArbitraryFile.scala" -> TestType.None,
    "some/package/TestNotInRoot.scala" -> UT)


  "TestType.reduce" should {
    Fragments.foreach(testTypesMixesToCombinedTestType) { case (mixedTestTypes, testType) =>
      s"return $testType for $mixedTestTypes" in {
        TestType.reduce(mixedTestTypes) ==== testType
      }
    }
  }
  val testTypesMixesToCombinedTestType = Seq(Seq(UT, UT) -> UT,
    Seq(ITE2E, ITE2E) -> ITE2E,
    Seq(UT, ITE2E, UT) -> Mixed,
    Seq(ITE2E, UT, ITE2E) -> Mixed,
    Seq(ITE2E, UT, None) -> Mixed,
    Seq(None, UT) -> UT,
    Seq(None, ITE2E) -> ITE2E,
    Seq(UT, None) -> UT,
    Seq(ITE2E, None) -> ITE2E,
    Seq(None, None) -> None)
} 
Example 18
Source File: CodotaThinClientContract.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.codota


import org.specs2.mutable.{BeforeAfter, SpecificationWithJUnit}
import org.specs2.specification.core.Fragments

//noinspection TypeAnnotation
abstract class CodotaThinClientContract extends SpecificationWithJUnit {
  sequential

  def testData: CodotaThinClientTestData

  def client: CodotaThinClient = {
    val data = testData
    val validToken = data.validToken
    val codePack = data.codePack
    val url = data.codotaUrl
    new CodotaThinClient(validToken, codePack, url)
  }

  "client" should {
    "return path for given artifact name" in {
      client.pathFor(testData.validArtifact) must beSome(testData.matchingPath)
    }

    "throw MetaDataNotFound in case given artifact that was not found" in {
      client.pathFor("some.bad.artifact") must throwA[MetaDataOrArtifactNotFound]
    }

    "throw MetaDataNotFound in case given artifact without metadata" in {
      client.pathFor(testData.validArtifactWithoutMetaData) must throwA[MetaDataOrArtifactNotFound]
    }

    "throw NotAuthorizedException in case given invalid token" in {
      val badClient = new CodotaThinClient("someInvalidToken", testData.codePack, testData.codotaUrl)

      badClient.pathFor(testData.validArtifact) must throwA[NotAuthorizedException]
    }

    "throw CodePackNotFoundException in case given unknown codePack" in {
      val badClient = new CodotaThinClient(testData.validToken, "badCodePack", testData.codotaUrl)

      badClient.pathFor(testData.validArtifact) must throwA[CodePackNotFoundException]
    }

    "throw MissingCodePackException in case given empty codePack" in {
      val badClient = new CodotaThinClient(testData.validToken, "", baseURL = testData.codotaUrl)

      badClient.pathFor(testData.validArtifact) must throwA[MissingCodePackException]
    }

    stressTests
  }

  protected def stressTests: Fragments

  trait Ctx extends BeforeAfter {
    private val data = testData
    val artifactName = data.validArtifact
    val codePack = data.codePack
    val url = data.codotaUrl
    val matchingPath = data.matchingPath
    val validToken = data.validToken

    def client: CodotaThinClient = new CodotaThinClient(validToken, codePack, url)
  }

}

case class CodotaThinClientTestData(codotaUrl: String, validToken: String, codePack: String, validArtifact: String, matchingPath: String, validArtifactWithoutMetaData: String) 
Example 19
Source File: CodotaThinClientIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.codota

import java.net.SocketTimeoutException

import org.specs2.specification.BeforeAfterAll
import org.specs2.specification.core.Fragments


class CodotaThinClientIT extends CodotaThinClientContract with BeforeAfterAll {
  val codePack = "some_code_pack"
  val validToken = "someValidToken"
  val artifactName = "some.group.artifact-name"
  val validArtifactWithoutMetaData = "some.group.artifact-without-metadata"
  val matchingPath = "some/path/to/artifact"

  override def testData: CodotaThinClientTestData = {
    CodotaThinClientTestData(
      codotaUrl = codotaFakeServer.url,
      codePack = codePack,
      validToken = validToken,
      validArtifact = artifactName,
      matchingPath = matchingPath,
      validArtifactWithoutMetaData = validArtifactWithoutMetaData
    )
  }

  val artifactsToPaths = Map(artifactName -> Some(matchingPath), validArtifactWithoutMetaData -> None)
  val codotaFakeServer = new CodotaFakeServer(codePack, validToken, artifactsToPaths)

  override protected def stressTests: Fragments = {
    "retry in case of timeouts" in {
      codotaFakeServer.delayTheNextNCalls(n = 1)

      client.pathFor(artifactName) must beSome(testData.matchingPath)
    }

    "throw TimeoutException in case still getting timeout after given max retries" in {
      val fastToGiveUpClient = new CodotaThinClient(validToken, codePack, codotaFakeServer.url, maxRetries = 2)

      codotaFakeServer.delayTheNextNCalls(n = 3)
      fastToGiveUpClient.pathFor(artifactName) must throwA[SocketTimeoutException]
    }
  }

  override def beforeAll(): Unit = codotaFakeServer.start()

  override def afterAll(): Unit = codotaFakeServer.stop()
} 
Example 20
Source File: CodotaThinClientITReal.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.codota

import org.specs2.specification.core.Fragments

class CodotaThinClientITReal extends CodotaThinClientContract {
  override def testData: CodotaThinClientTestData = CodotaThinClientTestData(
    codotaUrl = CodotaThinClient.DefaultBaseURL,
    validToken = sys.env.getOrElse("codota.token", throw new RuntimeException("Missing codota.token from env")),
    codePack = "wix_enc",
    validArtifact = "com.wixpress.ci.domain",
    matchingPath = "@wix_ci//domain",
    validArtifactWithoutMetaData = "com.wixpress.proto.communities-blog-proto"
  )

  override protected def stressTests: Fragments = Fragments.empty // cannot affect real server
} 
Example 21
Source File: MavenScopeTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.maven

import com.wix.bazel.migrator.Persister
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope
import org.specs2.specification.core.{Fragment, Fragments}

class MavenScopeTest extends SpecificationWithJUnit {
  val ScopesToNames = List(
    ScopeToName(MavenScope.Compile,"compile"),
    ScopeToName(MavenScope.Test,"test"),
    ScopeToName(MavenScope.Runtime,"runtime"),
    ScopeToName(MavenScope.Provided,"provided"),
    ScopeToName(MavenScope.System,"system")
  )

  private def aNewInstanceOf(scope: MavenScope): MavenScope = {
    mapper.readValue(mapper.writeValueAsString(scope), classOf[MavenScope])
  }

  private def extractTest(scopeToName:ScopeToName):Fragment ={
    s"parse ${scopeToName.scope} from string '${scopeToName.name}'" in {
      MavenScope.of(scopeToName.name) mustEqual scopeToName.scope
    }

    s"have equals working on different instances(!) of the same ${scopeToName.scope} value " +
      "(different instances can be created by jackson deserialization)" in {
      val differentInstance = aNewInstanceOf(scopeToName.scope)
      differentInstance.eq(scopeToName.scope) must beFalse
      differentInstance mustEqual scopeToName.scope
    }

    s"have hash working on different instances(!) of the same ${scopeToName.scope} value " +
      "(different instances can be created by jackson deserialization)" in {
      val differentInstance = aNewInstanceOf(scopeToName.scope)
      differentInstance.eq(scopeToName.scope) must beFalse
      differentInstance.hashCode() mustEqual scopeToName.scope.hashCode()
    }
  }

  val mapper = Persister.objectMapper

  def allTests:Fragments = Fragments(ScopesToNames.map(extractTest): _*)

  "MavenScope" should {
    allTests
  }

  "equals" should {
    "return 'false' for two different scopes" in new Context {
      MavenScope.Compile mustNotEqual MavenScope.Provided
    }

    "return 'false' when comparing to an object which is not an instance of MavenScope" in new Context {
      MavenScope.System mustNotEqual 3
    }
  }

  "hashCode" should {
    "return different hash for differnt scopes" in new Context {
      MavenScope.Runtime.hashCode() mustNotEqual MavenScope.Test.hashCode()
    }
  }

  abstract class Context extends Scope {

  }
}

case class ScopeToName(scope:MavenScope, name:String) 
Example 22
Source File: EventProcessorTest.scala    From scala-serialization   with MIT License 5 votes vote down vote up
package com.komanov.serialization.domain

import com.komanov.serialization.converters.TestData
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.core.Fragments

class EventProcessorTest extends SpecificationWithJUnit {

  "apply/unapply" should {
    Fragments.foreach(TestData.sites) { case (name, site) =>
      s"serialize and deserialize a site [$name]" in {
        val parsed = EventProcessor.apply(EventProcessor.unapply(site))
        parsed must be_===(site)
      }
    }
  }

}