org.specs2.matcher.MatchResult Scala Examples

The following examples show how to use org.specs2.matcher.MatchResult. 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: SimplestExampleSpec.scala    From parserz   with Apache License 2.0 5 votes vote down vote up
package org.spartanz.parserz

import org.specs2.matcher.MatchResult
import org.specs2.mutable.Specification

class SimplestExampleSpec extends Specification {

  object Syntax {
    sealed trait Expression
    case class Constant(value: Int)                extends Expression
    case class Sum(e1: Expression, e2: Expression) extends Expression
  }

  object Example {

    object Parser extends ParsersModule {
      override type Input = String
    }

    type S = Unit
    type E = String

    import Parser.Grammar._
    import Parser.Expr._
    import Parser._
    import Syntax._

    val char: Grammar[Any, Nothing, E, Char] = consumeOption("expected: char")(
      s => s.headOption.map(s.drop(1) -> _),
      { case (s, c) => Some(s + c.toString) }
    )

    val digit: Grammar[Any, Nothing, E, Char]        = char.filter("expected: digit")(cond(_.isDigit))
    val plus: Grammar[Any, Nothing, E, Char]         = char.filter("expected: '+'")(cond(_ == '+'))
    val integer: Grammar[Any, Nothing, E, Int]       = digit ∘ (_.toString.toInt, _.toString.head)
    val constant: Grammar[Any, Nothing, E, Constant] = integer ∘ (Constant, _.value)

    val expr1: Grammar[Any, Nothing, E, Expression] = constant.mapPartial("expected: Constant")(
      { case c               => c },
      { case c @ Constant(_) => c }
    )

    val expr2: Grammar[Any, Nothing, E, Expression] = (expr1 ~ (plus ~ expr1).rep).foldLeft(
      { case (e1, (_, e2)) => Sum(e1, e2) },
      { case Sum(e1, e2)   => (e1, ('+', e2)) }
    )

    val parser: (S, Input) => (S, E \/ (Input, Expression))  = Parser.parser[S, E, Expression](expr2)
    val printer: (S, (Input, Expression)) => (S, E \/ Input) = Parser.printer[S, E, Expression](expr2)
  }

  import Syntax._

  private def parse(s: String)  = Example.parser((), s)._2
  private def parse0(s: String) = parse(s).toOption.get._2

  private def print(e: Expression)  = Example.printer((), ("", e))._2
  private def print0(e: Expression) = print(e).toOption.get

  private def loop0(s: String, e: Expression): MatchResult[Any] = {
    val parsed  = parse0(s)
    val printed = print0(parsed)
    (parsed must_=== e).and(printed must_=== s)
  }

  "empty" in {
    parse("") must_=== Left("expected: char")
  }
  "single letter" in {
    parse("A") must_=== Left("expected: digit")
  }
  "single digit" in {
    loop0("1", Constant(1))
  }
  "several digits" in {
    parse("12") must_=== Right(("2", Constant(1)))
  }
  "just the plus" in {
    parse("+") must_=== Left("expected: digit")
  }
  "sum of two" in {
    loop0("1+2", Sum(Constant(1), Constant(2)))
  }
  "sum of three" in {
    loop0("1+2+3", Sum(Sum(Constant(1), Constant(2)), Constant(3)))
  }
  "sum of four" in {
    loop0("1+2+3+4", Sum(Sum(Sum(Constant(1), Constant(2)), Constant(3)), Constant(4)))
  }
  "incorrect composed sum of three" in {
    print(Sum(Constant(1), Sum(Constant(2), Constant(3)))) must_=== Left("expected: Constant")
  }
} 
Example 2
Source File: ChatStateSpec.scala    From http4s-chatserver   with Apache License 2.0 5 votes vote down vote up
package com.martinsnyder.chatserver

import org.specs2.matcher.MatchResult

class ChatStateSpec extends org.specs2.mutable.Specification {
  "ChatState" >> {
    "initializes empty" >> {
      noUsers && noRooms
    }
    "welcomes new users (only)" >> {
      welcomeNewUser && noWelcomeOldUser
    }
  }

  private[this] def noUsers(): MatchResult[Map[_,_]] =
    ChatState().userRooms must beEqualTo(Map.empty)

  private[this] def noRooms(): MatchResult[Map[_,_]] =
    ChatState().roomMembers must beEqualTo(Map.empty)

  private[this] def welcomeNewUser(): MatchResult[OutputMessage] =
    ChatState().process(EnterRoom("testUser", "room"))._2.head must beEqualTo(WelcomeUser("testUser"))

  private[this] def noWelcomeOldUser(): MatchResult[Seq[OutputMessage]] = {
    val initState = ChatState().process(EnterRoom("testUser", "room"))._1
    initState.process(EnterRoom("testUser", "room"))._2 must beEqualTo(Seq(SendToUser("testUser", "You are already in that room!")))
  }
} 
Example 3
Source File: TestUtils.scala    From codacy-analysis-cli   with GNU Affero General Public License v3.0 5 votes vote down vote up
package com.codacy.analysis.core.utils

import java.nio.file.attribute.PosixFilePermission
import java.nio.file.{Path, Paths}

import better.files.File
import com.codacy.plugins.api.results
import io.circe.Decoder
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.MatchResult

import scala.sys.process.Process

object TestUtils {

  implicit val categoryDecoder: Decoder[results.Pattern.Category.Value] =
    Decoder.decodeEnumeration(results.Pattern.Category)

  implicit val levelDecoder: Decoder[results.Result.Level.Value] =
    Decoder.decodeEnumeration(results.Result.Level)
  implicit val fileDecoder: Decoder[Path] = Decoder[String].map(Paths.get(_))
  implicit val executionEnv: ExecutionEnv = ExecutionEnv.fromGlobalExecutionContext

  def withClonedRepo[T](gitUrl: String, commitUUid: String)(block: (File, File) => MatchResult[T]): MatchResult[T] =
    (for {
      directory <- File.temporaryDirectory()
      file <- File.temporaryFile()
    } yield {
      directory
        .addPermission(PosixFilePermission.OWNER_READ)
        .addPermission(PosixFilePermission.GROUP_READ)
        .addPermission(PosixFilePermission.OTHERS_READ)
        .addPermission(PosixFilePermission.OWNER_EXECUTE)
        .addPermission(PosixFilePermission.GROUP_EXECUTE)
        .addPermission(PosixFilePermission.OTHERS_EXECUTE)
      Process(Seq("git", "clone", gitUrl, directory.pathAsString)).!
      Process(Seq("git", "reset", "--hard", commitUUid), directory.toJava).!
      block(file, directory)
    }).get()

  def withTemporaryGitRepo[T](fn: File => MatchResult[T]): MatchResult[T] = {
    (for {
      temporaryDirectory <- File.temporaryDirectory()
    } yield {
      Process(Seq("git", "init"), temporaryDirectory.toJava).!
      Process(Seq("git", "commit", "--allow-empty", "-m", "initial commit"), temporaryDirectory.toJava).!
      fn(temporaryDirectory)
    }).get

  }
} 
Example 4
Source File: package.scala    From temperature-machine   with Apache License 2.0 5 votes vote down vote up
package bad.robot.temperature

import cats.effect.IO
import org.http4s.{Header, Response, Status}
import org.specs2.matcher.{Expectable, MatchResult, Matcher}

package object test {

  def haveStatus(status: Status) = new Matcher[Response[IO]] {
    def apply[S <: Response[IO]](e: Expectable[S]): MatchResult[S] = result(
      e.value.status == status,
      s"""Status of [${e.value.status}]
          |
          |is
          |
          |$status""".stripMargin,
      s"""Status of
          |[${e.value.status}]
          |
          |is not
          |
          |[$status]
          |
          |(${e.value.as[String]})""".stripMargin,
      e)
  }

  def containsHeader(name: String, value: String) = new Matcher[Response[IO]] {
    def apply[S <: Response[IO]](e: Expectable[S]): MatchResult[S] = result(
      e.value.headers.toList.map(_.toRaw) contains Header(name, value),
      s"""${e.value.headers}
          |
          |contains
          |
          |$name""".stripMargin,
      s"""The response headers '${e.value.headers.toList.mkString("\n")}'
          |
          |do not contain
          |
          |[$name: $value]
          |""".stripMargin,
      e)
  }
} 
Example 5
Source File: CouchDbSpec.scala    From couchdb-scala   with Apache License 2.0 5 votes vote down vote up
package com.ibm.couchdb

import com.ibm.couchdb.api.{Design, Documents}
import com.ibm.couchdb.spec.{CouchDbSpecification, SpecConfig}
import org.http4s.Status
import org.specs2.matcher.MatchResult

class CouchDbSpec extends CouchDbSpecification {

  val couch = CouchDb(SpecConfig.couchDbHost, SpecConfig.couchDbPort)

  val db1 = "couchdb-scala-couchdb-spec1"
  val db2 = "couchdb-scala-couchdb-spec2"

  "User interface" >> {

    "Get info about the DB instance" >> {
      awaitRight(couch.server.info).couchdb mustEqual "Welcome"
    }

    "Create and query 2 DBs" >> {
      def testDb(dbName: String): MatchResult[Seq[CouchKeyVal[String, String]]] = {
        await(couch.dbs.delete(dbName))
        val error = awaitLeft(couch.dbs.delete(dbName))
        error.error mustEqual "not_found"
        error.reason mustEqual "missing"
        error.status mustEqual Status.NotFound
        error.request must contain("DELETE")
        error.request must contain(dbName)
        error.requestBody must beEmpty

        awaitOk(couch.dbs.create(dbName))
        couch.db(dbName, typeMapping).name mustEqual dbName
        couch.db(dbName, typeMapping).docs must beAnInstanceOf[Documents]
        couch.db(dbName, typeMapping).design must beAnInstanceOf[Design]

        val db = couch.db(dbName, typeMapping)
        db must beTheSameAs(couch.db(dbName, typeMapping))
        awaitDocOk(db.docs.create(fixAlice))
        awaitDocOk(db.design.create(fixDesign))

        val docs = awaitRight(
          db.query.view[String, String](fixDesign.name, FixViews.names).get.build.query)
        docs.rows must haveLength(1)
      }
      testDb(db1)
      testDb(db2)
    }
  }
} 
Example 6
Source File: AuthUtils.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import de.frosner.broccoli.auth.{Account, Role}
import de.frosner.broccoli.services.SecurityService
import jp.t2v.lab.play2.auth.test.Helpers._
import org.mockito.Mockito._
import org.specs2.matcher.MatchResult
import org.specs2.matcher.MatchersImplicits._
import play.api.cache.CacheApi
import play.api.mvc.{Action, AnyContentAsEmpty, Result}
import play.api.test.Helpers._
import play.api.test._
import play.api.{Application, Environment}

import scala.concurrent.Future

trait AuthUtils extends ServiceMocks {

  def playEnv(implicit app: Application): Environment = app.injector.instanceOf[Environment]

  def cacheApi(implicit app: Application): CacheApi = app.injector.instanceOf[CacheApi]

  def testWithAllAuths[T <: AuthConfigImpl, B](account: Account)(controller: SecurityService => T)(
      action: T => Action[B])(requestModifier: FakeRequest[AnyContentAsEmpty.type] => FakeRequest[B])(
      matcher: (T, Future[Result]) => MatchResult[_]): MatchResult[_] = {
    val confAuthController = controller(withAuthConf(mock[SecurityService], List(account)))
    val confAuthRequest = requestModifier(FakeRequest().withLoggedIn(confAuthController)(account.name))
    val confAuthResult = action(confAuthController).apply(confAuthRequest)
    val confAuthMatcher = matcher(confAuthController, confAuthResult)

    val noAuthController = controller(withAuthNone(mock[SecurityService]))
    val noAuthRequest = requestModifier(FakeRequest())
    val confAuthNoLoginResult = action(confAuthController).apply(noAuthRequest)
    val confAuthNoLoginMatcher = status(confAuthNoLoginResult) === 403

    confAuthMatcher and confAuthNoLoginMatcher
  }

  def testWithAllAuths[T <: AuthConfigImpl, B](controller: SecurityService => T)(action: T => Action[B])(
      requestModifier: FakeRequest[AnyContentAsEmpty.type] => FakeRequest[B])(
      matcher: (T, Future[Result]) => MatchResult[_]): MatchResult[_] = {
    val account = Account("user", ".*", Role.Administrator)
    val noAuthController = controller(withAuthNone(mock[SecurityService]))
    val noAuthRequest = requestModifier(FakeRequest())
    val noAuthResult = action(noAuthController).apply(noAuthRequest)
    val noAuthMatcher = matcher(noAuthController, noAuthResult)

    val authMatchers = testWithAllAuths(account)(controller)(action)(requestModifier)(matcher)

    noAuthMatcher and authMatchers
  }

} 
Example 7
Source File: ApplicativeLaws.scala    From scalaz-reactive   with Apache License 2.0 5 votes vote down vote up
package scalaz.reactive.laws
import org.scalacheck.{ Gen, Prop }
import org.scalacheck.Prop.forAll
import org.specs2.matcher.{ MatchResult, MustMatchers }
import scalaz.Applicative

class ApplicativeLaws[F[_], A](
  applicative: Applicative[F],
  aGen: Gen[A],
  faGen: Gen[F[A]],
  abGen: Gen[A => A],
  fabGen: Gen[F[A => A]],
  valueForEqGen: Gen[F[A] => A]
)(implicit
  pa: MatchResult[A] => Prop,
  pfa: MatchResult[F[A]] => Prop)
    extends MustMatchers {

  implicit class Equalable(v: F[A]) {
    def valueForEq(f: F[A] => A) = f(v)
  }

  // ap(fa)(point(_)) == fa
  def apIdentityLaw = forAll(faGen, valueForEqGen) { (fa, v) =>
    applicative
      .ap(fa)(applicative.point(identity[A](_)))
      .valueForEq(v) must beEqualTo(fa.valueForEq(v))
  }

  // ap(point(a))(point(ab)) == point(ab(a))
  def apHomomorphismLaw = forAll(aGen, abGen) { (a, ab) =>
    applicative
      .ap(applicative.point(a))(applicative.point(ab)) must
      beEqualTo(applicative.point(ab(a)))
  }

  // ap(point(a))(fab) == ap(fab)(point(_.apply(a)))
  def apInterchangeLaw = forAll(aGen, fabGen) { (a, fab) =>
    applicative.ap(applicative.point(a))(fab) must
      beEqualTo(
        applicative.ap(fab)(applicative.point((x: A => A) => x.apply(a)))
      )
  }

  //map(fa)(ab) == ap(fa)(point(ab))
  def apDerivedMapLaw = forAll(faGen, abGen, valueForEqGen) { (fa, ab, v) =>
    applicative.map(fa)(ab).valueForEq(v) must
      beEqualTo(applicative.ap(fa)(applicative.point(ab)).valueForEq(v))
  }
} 
Example 8
Source File: DiffMatcher.scala    From diffx   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.diffx.specs2

import com.softwaremill.diffx.{ConsoleColorConfig, Diff, DiffResultDifferent}
import org.specs2.matcher.{Expectable, MatchResult, Matcher}

trait DiffMatcher {
  def matchTo[A: Diff](left: A)(implicit c: ConsoleColorConfig): DiffForMatcher[A] = DiffForMatcher(left)

  case class DiffForMatcher[A: Diff](right: A) extends Matcher[A] {
    override def apply[S <: A](left: Expectable[S]): MatchResult[S] = {
      val diff = Diff[A]
      result(
        test = {
          diff.apply(left.value, right).isIdentical
        },
        okMessage = "",
        koMessage = diff.apply(left.value, right) match {
          case c: DiffResultDifferent =>
            c.show
          case _ =>
            ""
        },
        left
      )
    }
  }
}

object DiffMatcher extends DiffMatcher 
Example 9
Source File: UserPassIT.scala    From scala-vault   with MIT License 5 votes vote down vote up
package janstenpickle.vault.auth

import janstenpickle.vault.core.VaultSpec
import janstenpickle.vault.manage.Auth
import org.scalacheck.{Gen, Prop}
import org.specs2.ScalaCheck
import org.specs2.matcher.MatchResult

class UserPassIT extends VaultSpec with ScalaCheck {
  import VaultSpec._

  override def is =
    s2"""
      Can authenticate a user against a specific "client" path $authPass
      Fails to authenticate a user $end
        against a bad "client" path $badClient
        with a non-existent username $badUser
        with a bad password $badPassword
    """

  lazy val underTest = UserPass(config.wsClient)
  lazy val authAdmin = Auth(config)
  lazy val userAdmin = janstenpickle.vault.manage.UserPass(config)

  def setupClient(client: String) = authAdmin.enable("userpass", Some(client))
    .attemptRun(_.getMessage()) must beOk

  def setupUser(username: String, password: String, client: String) =
    userAdmin.create(username, password, 30, None, client)
    .attemptRun(_.getMessage())

  def removeClient(client: String) =
    authAdmin.disable(client).attemptRun(_.getMessage()) must beOk

  def authPass = test((username, password, client, ttl) =>
                        setupClient(client) and
    (setupUser(username, password, client) must beOk) and
    (underTest.authenticate(username, password, ttl, client)
    .attemptRun(_.getMessage()) must beOk) and
    removeClient(client)
  )

  // TODO: test below may fail rarely (e.g. client is same as badClientName)

  def badClient = test{ (username, password, client, ttl) =>
    val badClientName = "nic-kim-cage-client"
    setupClient(badClientName) and
    (setupUser(username, password, client) must beFail) and
    (underTest.authenticate(username, password, ttl, client)
    .attemptRun(_.getMessage()) must beFail) and
    removeClient(badClientName)
  }

  def badUser = test{ (username, password, client, ttl) =>
    val badUserName = "nic-kim-cage-user"
    setupClient(client) and
    (setupUser(username, password, client) must beOk) and
    (underTest.authenticate(badUserName, password, ttl, client)
    .attemptRun(_.getMessage()) must beFail) and
    removeClient(client)
  }

  def badPassword = test{ (username, password, client, ttl) =>
    val badPasswordValue = "nic-kim-cage-password"
    setupClient(client) and
    (setupUser(username, password, client) must beOk) and
    (underTest.authenticate(username, badPasswordValue, ttl, client)
    .attemptRun(_.getMessage()) must beFail) and
    removeClient(client)
  }

  def test(op: (String, String, String, Int) => MatchResult[Any]) =
    Prop.forAllNoShrink(
      longerStrGen,
      longerStrGen,
      Gen.numStr.suchThat(_.nonEmpty), Gen.posNum[Int]
    )(op)
}