org.scalatest.matchers.MatchResult Scala Examples

The following examples show how to use org.scalatest.matchers.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: ASTMatchers.scala    From Argus   with MIT License 5 votes vote down vote up
package argus.macros

import org.scalactic.Equality
import org.scalatest.matchers.{ MatchResult, Matcher }
import scala.tools.reflect.ToolBox


trait ASTMatchers {

  val runtimeUniverse = scala.reflect.runtime.universe
  import runtimeUniverse._
  import scala.reflect.runtime.currentMirror
  val toolbox = currentMirror.mkToolBox()

  // For testing equality between trees in tests
  implicit val treeEq = new Equality[Tree] {
    def areEqual(a: Tree, b: Any): Boolean =
      b match {
        // equalsStructure bug: https://github.com/scalamacros/paradise/issues/80
        case c: Tree => showRaw(a) == showRaw(c) //.equalsStructure(c)
        case _ => false
      }
  }

  implicit val valDefEq = new Equality[ValDef] {
    def areEqual(a: ValDef, b: Any): Boolean =
      b match {
        case c: ValDef => showRaw(a) == showRaw(c)
        case _ => false
      }
  }

  implicit val listTreeEq = new Equality[List[Tree]] {
    def areEqual(a: List[Tree], b: Any): Boolean =
      b match {
        case c: List[_] => a.size == c.size && a.zip(c).forall { case(x,y) => treeEq.areEqual(x,y) }
        case _ => false
      }
  }

  val extractCodecNameAndType: PartialFunction[Tree, (String, String)] = {
    case q"implicit val $name: $typ = $_" => (name.toString, typ.toString)
  }

} 
Example 2
Source File: MatchHelper.scala    From morpheus   with Apache License 2.0 5 votes vote down vote up
package org.opencypher.okapi.testing

import org.scalatest.matchers.{MatchResult, Matcher}

object MatchHelper {

  import AsCode._

  val success = MatchResult(true, "", "")

  // Returns a successful or the first failed match if there is one.
  def combine(m: MatchResult*): MatchResult = {
    m.foldLeft(success) {
      case (aggr, next) =>
        if (aggr.matches) next else aggr
    }
  }

  def addTrace(m: MatchResult, traceInfo: String): MatchResult = {
    if (m.matches) {
      m
    } else {
      MatchResult(false, m.rawFailureMessage + s"\nTRACE: $traceInfo", m.rawNegatedFailureMessage)
    }
  }

  
  case class referenceEqual(right: AnyRef) extends Matcher[AnyRef] {
    override def apply(left: AnyRef): MatchResult = {
      MatchResult(if (left == null) right == null else left.eq(right), s"$left was not the same instance as $right", "")
    }
  }


} 
Example 3
Source File: JsonMatchers.scala    From Vegas   with MIT License 5 votes vote down vote up
package vegas

import argus.json.JsonDiff
import org.scalactic.Equality
import io.circe._
import org.scalatest.matchers.{ MatchResult, Matcher }

// TODO This is copy-and-pasted from argus. Really needs to be put somewhere shared.
trait JsonMatchers {

  def beSameJsonAs(jrStr: String): Matcher[Json] = new Matcher[Json] {
    def apply(jl: Json) = {
      val jr = parser.parse(jrStr).right.get
      beSameJsonAs(jr)(jl)
    }
  }

  def beSameJsonAs(jr: Json): Matcher[Json] = new Matcher[Json] {
    def apply(jl: Json) = {
      val diff = JsonDiff.diff(jl, jr)
      MatchResult(diff.isEmpty, "Differences found in json: " + diff.mkString(","), "No differences found!")
    }
  }

  implicit val jsonEq = new Equality[Json] {
    def areEqual(a: Json, b: Any): Boolean =
      b match {
        case c: Json => JsonDiff.diff(a, c) == Nil
        case c: String => JsonDiff.diff(a, parser.parse(c).right.get) == Nil
        case _ => false
      }
  }

} 
Example 4
Source File: DiffMatcher.scala    From diffx   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.diffx.scalatest

import com.softwaremill.diffx.{ConsoleColorConfig, Diff, DiffResultDifferent}
import org.scalatest.matchers.{MatchResult, Matcher}

trait DiffMatcher {
  def matchTo[A: Diff](right: A)(implicit c: ConsoleColorConfig): Matcher[A] = { left =>
    Diff[A].apply(left, right) match {
      case c: DiffResultDifferent =>
        val diff = c.show.split('\n').mkString(Console.RESET, s"${Console.RESET}\n${Console.RESET}", Console.RESET)
        MatchResult(matches = false, s"Matching error:\n$diff", "")
      case _ => MatchResult(matches = true, "", "")
    }
  }
}

object DiffMatcher extends DiffMatcher 
Example 5
Source File: VersionSpec.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.utils

import org.scalatest.matchers.{BeMatcher, MatchResult}

import ai.deepsense.commons.{StandardSpec, UnitTestSupport}


class VersionSpec extends StandardSpec with UnitTestSupport {

  "Version" should {
    "be comparable with other version" in {
      val v = Version(1, 2, 3, "")
      v should be (compatibleWith(v))

      val versionPatchLower = v.copy(fix = v.fix - 1)
      val versionPatchHigher = v.copy(fix = v.fix + 1)
      v should be (compatibleWith(versionPatchLower))
      v should be (compatibleWith(versionPatchHigher))

      val versionMinorLower = v.copy(minor = v.minor - 1)
      val versionMinorHigher = v.copy(minor = v.minor + 1)
      v should be (incompatibleWith(versionMinorLower))
      v should be (incompatibleWith(versionMinorHigher))

      val versionMajorLower = v.copy(major = v.major - 1)
      val versionMajorHigher = v.copy(major = v.major + 1)
      v should be (incompatibleWith(versionMajorLower))
      v should be (incompatibleWith(versionMajorHigher))
    }

    "be parse strings" in {
      Version("1.2.3") shouldBe Version(1, 2, 3, "")
      Version("1.2.3.4") shouldBe Version(1, 2, 3, ".4")
      Version("1.2.3.a") shouldBe Version(1, 2, 3, ".a")
      Version("1.2.3-x") shouldBe Version(1, 2, 3, "-x")
      Version("1.2.3-numberhere:1") shouldBe Version(1, 2, 3, "-numberhere:1")

      a [VersionException] shouldBe thrownBy (Version("1"))
      a [VersionException] shouldBe thrownBy (Version("1."))
      a [VersionException] shouldBe thrownBy (Version("1.2"))
      a [VersionException] shouldBe thrownBy (Version("1.2."))
      a [VersionException] shouldBe thrownBy (Version("1.2.x"))
      a [VersionException] shouldBe thrownBy (Version("1x.2.3"))
      a [VersionException] shouldBe thrownBy (Version("1.2x.3"))
      a [VersionException] shouldBe thrownBy (Version("1x.2x.3"))
      a [VersionException] shouldBe thrownBy (Version("foo"))
    }
  }

  class VersionMatcher(right: Version) extends BeMatcher[Version] {
    def apply(left: Version): MatchResult = {
      MatchResult(left.compatibleWith(right),
        s"Version '${left.humanReadable}' was compatible with '${right.humanReadable}'",
        s"Version '${left.humanReadable}' was not compatible with '${right.humanReadable}'"
      )
    }
  }

  private def compatibleWith(version: Version) = new VersionMatcher(version)
  private def incompatibleWith(version: Version) = not(new VersionMatcher(version))
} 
Example 6
Source File: CatsHelpers.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api

import cats.effect._
import cats.implicits._
import vinyldns.api.domain.batch.BatchChangeInterfaces.ValidatedBatch
import vinyldns.api.domain.batch.BatchTransformations.ChangeForValidation

import scala.concurrent.duration._
import org.scalatest.Assertions._
import org.scalatest.matchers.{MatchResult, Matcher}

import scala.concurrent.ExecutionContext

trait CatsHelpers {
  private implicit val timer: Timer[IO] = IO.timer(ExecutionContext.global)
  private implicit val cs: ContextShift[IO] =
    IO.contextShift(scala.concurrent.ExecutionContext.global)

  def await[E, T](f: => IO[T], duration: FiniteDuration = 1.second): T = {
    val i: IO[Either[E, T]] = f.attempt.map {
      case Right(ok) => Right(ok.asInstanceOf[T])
      case Left(e) => Left(e.asInstanceOf[E])
    }
    awaitResultOf[E, T](i, duration).toOption.get
  }

  // Waits for the future to complete, then returns the value as an Either[Throwable, T]
  def awaitResultOf[E, T](
      f: => IO[Either[E, T]],
      duration: FiniteDuration = 1.second
  ): Either[E, T] = {
    val timeOut = IO.sleep(duration) *> IO(new RuntimeException("Timed out waiting for result"))
    IO.race(timeOut, f).unsafeRunSync().toOption.get
  }

  // Assumes that the result of the future operation will be successful, this will fail on a left disjunction
  def rightResultOf[E, T](f: => IO[Either[E, T]], duration: FiniteDuration = 1.second): T =
    rightValue(awaitResultOf[E, T](f, duration))

  // Assumes that the result of the future operation will fail, this will error on a right disjunction
  def leftResultOf[E, T](f: => IO[Either[E, T]], duration: FiniteDuration = 1.second): E =
    leftValue(awaitResultOf(f, duration))

  def leftValue[E, T](t: Either[E, T]): E = t match {
    case Right(x) => fail(s"expected left value, got right: $x")
    case Left(err) => err
  }

  def rightValue[E, T](t: Either[E, T]): T = t match {
    case Right(x) => x
    case Left(err) => fail(s"expected right value, got left: $err")
  }
}

object ValidatedBatchMatcherImprovements extends ValidatedBatchMatcherImprovements

trait ValidatedBatchMatcherImprovements {
  class ValidatedBatchContainsChangeForValidation(expectedChange: ChangeForValidation)
      extends Matcher[ValidatedBatch[ChangeForValidation]] {
    def apply(left: ValidatedBatch[ChangeForValidation]): MatchResult =
      MatchResult(
        left.contains(expectedChange.validNel),
        s"ValidatedBatch $left does not contain $expectedChange",
        s"ValidatedBatch $left contains $expectedChange"
      )
  }

  def containChangeForValidation(
      expectedChange: ChangeForValidation
  ): ValidatedBatchContainsChangeForValidation =
    new ValidatedBatchContainsChangeForValidation(expectedChange)
} 
Example 7
Source File: EitherMatchers.scala    From cats-scalatest   with Apache License 2.0 5 votes vote down vote up
package cats.scalatest

import org.scalatest.matchers.{BeMatcher, MatchResult, Matcher}

import scala.util.Either
import cats.syntax.either._

trait EitherMatchers {

  
final object EitherMatchers extends EitherMatchers

final private[scalatest] class BeCatsRightEitherMatcher[T](element: T) extends Matcher[_ Either T] {
  def apply(either: _ Either T): MatchResult =
    MatchResult(
      either.fold(_ => false, _ == element),
      s"'$either' did not contain an Right element matching '$element'.",
      s"'$either' contained an Right element matching '$element', but should not have."
    )
}

final private[scalatest] class BeCatsLeftEither[E](element: E) extends Matcher[E Either _] {
  def apply(either: E Either _): MatchResult =
    MatchResult(
      either.fold(_ == element, _ => false),
      s"'$either' did not contain an Left element matching '$element'.",
      s"'$either' contained an Left element matching '$element', but should not have."
    )
}

final private[scalatest] class IsCatsLeftEitherMatcher[E] extends BeMatcher[E Either _] {
  def apply(either: E Either _): MatchResult =
    MatchResult(
      either.isLeft,
      s"'$either' was not an Left, but should have been.",
      s"'$either' was an Left, but should *NOT* have been."
    )
}

final private[scalatest] class IsCatsRightEitherMatcher[T] extends BeMatcher[_ Either T] {
  def apply(either: _ Either T): MatchResult =
    MatchResult(
      either.isRight,
      s"'$either' was not an Right, but should have been.",
      s"'$either' was an Right, but should *NOT* have been."
    )
} 
Example 8
Source File: LogMatchers.scala    From stryker4s   with Apache License 2.0 5 votes vote down vote up
package stryker4s.scalatest

import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.LogEvent
import org.scalatest.BeforeAndAfterEach
import org.scalatest.matchers.{BeMatcher, MatchResult}
import stryker4s.testutil.{TestAppender}
import org.scalatest.Suite

trait LogMatchers extends BeforeAndAfterEach {
  // Will cause a compile error if LogMatchers is used outside of a ScalaTest Suite
  this: Suite =>

  def loggedAsDebug = new LogMatcherWithLevel(Level.DEBUG)
  def loggedAsInfo = new LogMatcherWithLevel(Level.INFO)
  def loggedAsWarning = new LogMatcherWithLevel(Level.WARN)
  def loggedAsError = new LogMatcherWithLevel(Level.ERROR)

  override def afterEach(): Unit = TestAppender.reset

  
  implicit private val threadName: String = Thread.currentThread().getName

  protected class LogMatcherWithLevel(expectedLogLevel: Level)(implicit threadName: String) extends BeMatcher[String] {
    def apply(expectedLogMessage: String): MatchResult = {
      getLoggingEventWithLogMessage(expectedLogMessage) match {
        case None =>
          MatchResult(
            matches = false,
            s"Log message '$expectedLogMessage' wasn't logged at any level.",
            s"Log message '$expectedLogMessage' was logged as $expectedLogLevel."
          )
        case Some(loggingEvent) =>
          val result = validateLogLevel(loggingEvent.getLevel, expectedLogLevel)

          MatchResult(
            result,
            s"Log message '$expectedLogMessage' was logged but not on correct log level, " +
              s"expected [$expectedLogLevel] actual [${loggingEvent.getLevel}].",
            s"Log message '$expectedLogMessage' was logged as $expectedLogLevel."
          )
      }
    }

    private def validateLogLevel(actualLogLevel: Level, expectedLogLevel: Level): Boolean = {
      expectedLogLevel.equals(actualLogLevel)
    }

    private def getLoggingEventWithLogMessage(expectedLogMessage: String): Option[LogEvent] = {
      TestAppender
        .events(threadName)
        .find(_.getMessage.getFormattedMessage.contains(expectedLogMessage))
    }
  }
} 
Example 9
Source File: SwaveSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core

import scala.concurrent.duration._
import org.scalatest.matchers.{MatchResult, Matcher}
import org.scalatest._
import swave.core.util._

abstract class SwaveSpec extends FreeSpec with StreamEnvShutdown {
  type Timeout = SwaveSpec.Timeout
  def Timeout = SwaveSpec.Timeout

  def produce[T](expected: T*)(implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] = produceSeq(expected)
  def produceSeq[T](expected: Seq[T])(implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] =
    equal(expected).matcher[Seq[T]].compose(_.drainTo(Drain.seq(100)).await(timeout.duration))
  def produceError[T](expected: Throwable)(implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] =
    equal(expected).matcher[Throwable].compose(_.drainTo(Drain.ignore).failed.await(timeout.duration))
  def produceErrorLike[T](pf: PartialFunction[Throwable, Unit])(
      implicit timeout: Timeout = Timeout()): Matcher[Spout[T]] =
    new Matcher[Spout[T]] {
      def apply(left: Spout[T]) = {
        val error = left.drainTo(Drain.ignore).failed.await(timeout.duration)
        inside(error)(pf)
        MatchResult(true, "", "")
      }
    }

  def timed[U](block: ⇒ U): FiniteDuration = {
    val start = System.nanoTime()
    block
    (System.nanoTime() - start).nanos
  }
}

object SwaveSpec {
  final case class Timeout(duration: FiniteDuration = Duration.Zero)
}

trait StreamEnvShutdown extends Matchers with Inside with BeforeAndAfterAll { this: Suite ⇒

  implicit val env: StreamEnv

  override val invokeBeforeAllAndAfterAllEvenIfNoTestsAreExpected = true

  override protected def afterAll(): Unit = {
    env.shutdown().awaitTermination(2.seconds)
    afterTermination()
  }

  protected def afterTermination(): Unit = ()
} 
Example 10
Source File: IOMatchers.scala    From skafka   with MIT License 5 votes vote down vote up
package com.evolutiongaming.skafka

import cats.effect.IO
import org.scalatest.matchers.{MatchResult, Matcher}

trait IOMatchers {
  class IOResultMatcher[-T](expected: T) extends Matcher[IO[T]] {
    def apply(left: IO[T]): MatchResult =
      MatchResult(
        matches = left.unsafeRunSync() == expected,
        rawFailureMessage = s"IO result didn't equal $expected",
        rawNegatedFailureMessage = s"IO result equals $expected"
      )
  }

  def produce[T](expected: T) = new IOResultMatcher[T](expected)

  def verify[T, U](job: IO[T])(check: T => U): U = {
    check(job.unsafeRunSync())
  }

}
object IOMatchers extends IOMatchers 
Example 11
Source File: JsonMatchers.scala    From Argus   with MIT License 5 votes vote down vote up
package argus.macros

import argus.json.JsonDiff
import org.scalactic.Equality
import cats.syntax.either._
import io.circe._
import org.scalatest.matchers.{ MatchResult, Matcher }

// TODO Should refactor this into somewhere generally useful.
trait JsonMatchers {

  def beSameJsonAs(jrStr: String): Matcher[Json] = new Matcher[Json] {
    def apply(jl: Json) = {
      val jr = parser.parse(jrStr).toOption.get
      beSameJsonAs(jr)(jl)
    }
  }

  def beSameJsonAs(jr: Json): Matcher[Json] = new Matcher[Json] {
    def apply(jl: Json) = {
      val diff = JsonDiff.diff(jl, jr)
      MatchResult(diff.isEmpty, "Differences found in json: " + diff.mkString(","), "No differences found!")
    }
  }

  implicit val jsonEq = new Equality[Json] {
    def areEqual(a: Json, b: Any): Boolean =
      b match {
        case c: Json => JsonDiff.diff(a, c) == Nil
        case c: String => JsonDiff.diff(a, parser.parse(c).toOption.get) == Nil
        case _ => false
      }
  }

} 
Example 12
Source File: ProduceError.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.common.state.diffs

import org.scalatest.matchers.{MatchResult, Matcher}

import scala.util.{Left, Right}

class ProduceError(errorMessage: String) extends Matcher[Either[_, _]] {
  override def apply(ei: Either[_, _]): MatchResult = {
    ei match {
      case r @ Right(_) => MatchResult(matches = false, "expecting Left(...{0}...) but got {1}", "got expected error", IndexedSeq(errorMessage, r))
      case l @ Left(_) =>
        MatchResult(matches = l.toString contains errorMessage,
                    "expecting Left(...{0}...) but got {1}",
                    "got expected error",
                    IndexedSeq(errorMessage, l))
    }
  }
}

object ProduceError {
  def produce(err: String): Matcher[Either[_, _]] = new ProduceError(err)
} 
Example 13
Source File: ValidationMatcher.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.transaction

import com.wavesplatform.transaction.assets.exchange.Validation
import org.scalatest.enablers.Containing
import org.scalatest.matchers.{BeMatcher, MatchResult}

trait ValidationMatcher {
  class ValidationMatcher extends BeMatcher[Validation] {
    def apply(left: Validation): MatchResult =
      MatchResult(
        left.status,
        left.toString + " was invalid",
        left.toString + " was valid"
      )
  }

  val valid = new ValidationMatcher

  implicit val containingNatureOfValidation: Containing[Validation] =
    new Containing[Validation] {
      def contains(v: Validation, ele: Any): Boolean =
        !v.status && v.labels.contains(ele.toString)

      def containsOneOf(v: Validation, elements: scala.collection.Seq[Any]): Boolean = {
        !v.status && elements.map(_.toString).map(v.labels.contains).reduce(_ || _)
      }

      def containsNoneOf(v: Validation, elements: scala.collection.Seq[Any]): Boolean = {
        v.status || elements.map(_.toString).map(v.labels.contains).reduce(!_ && !_)
      }
    }

} 
Example 14
Source File: DiffProduceError.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import com.wavesplatform.state.Diff
import org.scalatest.matchers.{MatchResult, Matcher}

class DiffProduceError(errorMessage: String, requireFailed: Boolean) extends Matcher[Either[_, _]] {
  override def apply(ei: Either[_, _]): MatchResult = {
    ei match {
      case r @ Right(diff: Diff) =>
        diff.scriptResults.values.find(_.error.exists(_.text.contains(errorMessage))) match {
          case Some(_) => MatchResult(matches = true, "", "", Vector.empty)
          case None    => MatchResult(matches = false, "expecting Left(...{0}...) but got {1}", "got expected error", IndexedSeq(errorMessage, r))
        }

      case r @ Right(_) => MatchResult(matches = false, "expecting Left(...{0}...) but got {1}", "got expected error", IndexedSeq(errorMessage, r))

      case l @ Left(_) =>
        MatchResult(
          matches = !requireFailed && (l.toString contains errorMessage),
          "expecting Left(...{0}...) but got {1}",
          "got expected error",
          IndexedSeq(errorMessage, l)
        )
    }
  }
} 
Example 15
Source File: ApiErrorMatchers.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.http

import akka.http.scaladsl.testkit.RouteTest
import com.wavesplatform.api.http.ApiError
import com.wavesplatform.http.ApiMarshallers._
import org.scalatest.Matchers
import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.libs.json._

trait ApiErrorMatchers extends Matchers { this: RouteTest =>
  class ProduceError(error: ApiError, matchMsg: Boolean) extends Matcher[RouteTestResult] {
    override def apply(left: RouteTestResult): MatchResult = left ~> check {
      if (response.status != error.code) {
        MatchResult(
          false,
          "got {0} while expecting {1}, response was {2}",
          "got expected status code {0}",
          IndexedSeq(response.status, error.code, response.entity)
        )
      } else {
        val responseJson     = responseAs[JsObject]
        val actualResponse   = responseJson - "trace" - "message"
        val actualMessage    = (responseJson \ "message").as[String]
        val expectedResponse = error.json - "message"
        val expectedMessage  = error.message
        MatchResult(
          actualResponse == expectedResponse && (if (matchMsg) actualMessage.matches(s".*$expectedMessage.*") else actualMessage == expectedMessage),
          "expected {0}, but instead got {1}",
          "expected not to get {0}, but instead did get it",
          IndexedSeq(error.json, responseJson)
        )
      }
    }
  }

  def produce(error: ApiError, matchMsg: Boolean = false): ProduceError = new ProduceError(error, matchMsg)
} 
Example 16
Source File: EitherMatchers.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform

import org.scalatest.matchers.{MatchResult, Matcher}

trait EitherMatchers {
  import EitherMatchers._
  def beRight: Matcher[Either[Any, Any]] = BeRight
  def beLeft: Matcher[Either[Any, Any]]  = BeLeft
}

object EitherMatchers extends EitherMatchers {
  private[EitherMatchers] abstract class EitherMatcher(side: String) extends Matcher[Either[Any, Any]] {
    protected def matches(valueToCheck: Either[Any, Any]): Boolean
    override def apply(valueToCheck: Either[Any, Any]): MatchResult = MatchResult(
      matches(valueToCheck),
      s"$valueToCheck was not $side",
      s"$valueToCheck was $side"
    )
  }

  private[EitherMatchers] object BeRight extends EitherMatcher("right") {
    override protected def matches(valueToCheck: Either[Any, Any]): Boolean = valueToCheck.isRight
  }

  private[EitherMatchers] object BeLeft extends EitherMatcher("left") {
    override protected def matches(valueToCheck: Either[Any, Any]): Boolean = valueToCheck.isLeft
  }
} 
Example 17
Source File: VersionSpec.scala    From seahorse-workflow-executor   with Apache License 2.0 5 votes vote down vote up
package io.deepsense.commons.utils

import org.scalatest.matchers.{BeMatcher, MatchResult}

import io.deepsense.commons.{StandardSpec, UnitTestSupport}


class VersionSpec extends StandardSpec with UnitTestSupport {

  "Version" should {
    "be comparable with other version" in {
      val v = Version(1, 2, 3, "")
      v should be (compatibleWith(v))

      val versionPatchLower = v.copy(fix = v.fix - 1)
      val versionPatchHigher = v.copy(fix = v.fix + 1)
      v should be (compatibleWith(versionPatchLower))
      v should be (compatibleWith(versionPatchHigher))

      val versionMinorLower = v.copy(minor = v.minor - 1)
      val versionMinorHigher = v.copy(minor = v.minor + 1)
      v should be (incompatibleWith(versionMinorLower))
      v should be (incompatibleWith(versionMinorHigher))

      val versionMajorLower = v.copy(major = v.major - 1)
      val versionMajorHigher = v.copy(major = v.major + 1)
      v should be (incompatibleWith(versionMajorLower))
      v should be (incompatibleWith(versionMajorHigher))
    }

    "be parse strings" in {
      Version("1.2.3") shouldBe Version(1, 2, 3, "")
      Version("1.2.3.4") shouldBe Version(1, 2, 3, ".4")
      Version("1.2.3.a") shouldBe Version(1, 2, 3, ".a")
      Version("1.2.3-x") shouldBe Version(1, 2, 3, "-x")
      Version("1.2.3-numberhere:1") shouldBe Version(1, 2, 3, "-numberhere:1")

      a [VersionException] shouldBe thrownBy (Version("1"))
      a [VersionException] shouldBe thrownBy (Version("1."))
      a [VersionException] shouldBe thrownBy (Version("1.2"))
      a [VersionException] shouldBe thrownBy (Version("1.2."))
      a [VersionException] shouldBe thrownBy (Version("1.2.x"))
      a [VersionException] shouldBe thrownBy (Version("1x.2.3"))
      a [VersionException] shouldBe thrownBy (Version("1.2x.3"))
      a [VersionException] shouldBe thrownBy (Version("1x.2x.3"))
      a [VersionException] shouldBe thrownBy (Version("foo"))
    }
  }

  class VersionMatcher(right: Version) extends BeMatcher[Version] {
    def apply(left: Version): MatchResult = {
      MatchResult(left.compatibleWith(right),
        s"Version '${left.humanReadable}' was compatible with '${right.humanReadable}'",
        s"Version '${left.humanReadable}' was not compatible with '${right.humanReadable}'"
      )
    }
  }

  private def compatibleWith(version: Version) = new VersionMatcher(version)
  private def incompatibleWith(version: Version) = not(new VersionMatcher(version))
} 
Example 18
Source File: ProduceError.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.test.matchers

import org.scalatest.matchers.{MatchResult, Matcher}

import scala.util.matching.Regex
import scala.util.{Left, Right}

object ProduceError {

  def produce(errorPattern: Regex): Matcher[Either[_, _]] = {
    case r @ Right(_) => MatchResult(matches = false, "expecting {0} to be Left and match: {1}", "got expected error", IndexedSeq(r, errorPattern))
    case Left(l) =>
      MatchResult(
        matches = errorPattern.findFirstIn(l.toString).isDefined,
        rawFailureMessage = "expecting {0} to match: {1}",
        rawNegatedFailureMessage = "got expected error",
        args = IndexedSeq(l, errorPattern)
      )
  }

  def produce(errorMessage: String): Matcher[Either[_, _]] = {
    case r @ Right(_) => MatchResult(matches = false, "expecting Left(...{0}...) but got {1}", "got expected error", IndexedSeq(errorMessage, r))
    case l @ Left(_) =>
      MatchResult(
        matches = l.toString contains errorMessage,
        rawFailureMessage = "expecting Left(...{0}...) but got {1}",
        rawNegatedFailureMessage = "got expected error",
        args = IndexedSeq(errorMessage, l)
      )
  }
} 
Example 19
Source File: ConfigReaderMatchers.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig

import java.net.URL

import com.typesafe.config.{ ConfigOrigin, ConfigOriginFactory }

import scala.reflect.ClassTag
import org.scalatest._
import org.scalatest.matchers.{ MatchResult, Matcher }
import pureconfig.error._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

trait ConfigReaderMatchers { this: AnyFlatSpec with Matchers =>

  def failWith(reason: FailureReason): Matcher[ConfigReader.Result[Any]] =
    matchPattern { case Left(ConfigReaderFailures(ConvertFailure(`reason`, _, _))) => }

  def failWith(
    reason: FailureReason,
    path: String,
    origin: Option[ConfigOrigin] = None): Matcher[ConfigReader.Result[Any]] =
    be(Left(ConfigReaderFailures(ConvertFailure(reason, origin, path))))

  def failWith(failure: ConfigReaderFailure): Matcher[ConfigReader.Result[Any]] =
    be(Left(ConfigReaderFailures(failure)))

  def failWithType[Reason <: FailureReason: ClassTag]: Matcher[ConfigReader.Result[Any]] =
    matchPattern { case Left(ConfigReaderFailures(ConvertFailure(_: Reason, _, _))) => }

  def failWithType[Failure <: ConfigReaderFailure: ClassTag](implicit dummy: DummyImplicit): Matcher[ConfigReader.Result[Any]] =
    matchPattern { case Left(ConfigReaderFailures(_: Failure)) => }

  def failLike(pf: PartialFunction[ConfigReaderFailure, MatchResult]) =
    new Matcher[ConfigReader.Result[Any]] with Inside with PartialFunctionValues {

      def apply(left: ConfigReader.Result[Any]): MatchResult = {
        inside(left) { case Left(ConfigReaderFailures(failure)) => pf.valueAt(failure) }
      }
    }

  def stringConfigOrigin(line: Int) =
    Some(ConfigOriginFactory.newSimple("String").withLineNumber(line))

  def urlConfigOrigin(url: URL, line: Int): Option[ConfigOrigin] =
    Some(ConfigOriginFactory.newURL(url).withLineNumber(line))

  val emptyConfigOrigin: Option[ConfigOrigin] =
    Some(ConfigOriginFactory.newSimple())
} 
Example 20
Source File: CirceEq.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.util

import _root_.io.circe._
import _root_.io.circe.syntax._
import org.scalatest.matchers.{MatchResult, Matcher}

trait CirceEq {
  implicit private val printer = Printer.noSpaces.copy(dropNullValues = true)

  def equalIgnoreArrayOrder(json: Json) = IgnoredArrayOrder(json)

  case class IgnoredArrayOrder(json: Json) extends Matcher[Json] {
    private def sortKeys(value: Json): Json = {
      def canonicalJson(json: Json): Json =
        json.arrayOrObject[Json](
          json,
          arr => Json.fromValues(arr.sortBy(_.hashCode()).map(canonicalJson)),
          obj => sorted(obj).asJson
        )

      def sorted(jObj: JsonObject): JsonObject =
        JsonObject.fromIterable(jObj.toVector.sortBy(_._1).map { case (k, v) => k -> canonicalJson(v) })

      canonicalJson(value)
    }

    override def apply(left: Json): MatchResult = {
      val leftSorted  = sortKeys(left)
      val rightSorted = sortKeys(json)
      MatchResult(
        leftSorted == rightSorted || printer.print(leftSorted) == printer.print(rightSorted),
        s"Both Json are not equal (ignoring array order)\n${printer.print(leftSorted)}\ndid not equal\n${printer.print(rightSorted)}",
        ""
      )
    }
  }

} 
Example 21
Source File: PDStream.scala    From sscheck   with Apache License 2.0 5 votes vote down vote up
package es.ucm.fdi.sscheck.gen

import org.scalatest.matchers.{Matcher, MatchResult}
import scala.language.implicitConversions

object PDStream {    
  def empty[A] : PDStream[A] = new PDStream(List():_*)
    
  implicit def batchSeq2dstream[A](batches : Seq[Batch[A]]) : PDStream[A] = PDStream(batches:_*)
  implicit def seqSeq2dstream[A](batches : Seq[Seq[A]]) : PDStream[A] = PDStream(batches.map(Batch(_:_*)):_*)
}


  def subsetOf(other : PDStream[A]) : Boolean = {
    batches
      .zip(other.batches)
      .map({case (thisBatch, otherBatch) =>
              thisBatch.forall(otherBatch.contains(_))
           })
      .forall(identity[Boolean])
  } 
}

trait DStreamMatchers {
  class DStreamSubsetOf[A](expectedSuperDStream : PDStream[A]) extends Matcher[PDStream[A]] {
    override def apply(observedDStream : PDStream[A]) : MatchResult = {      
      // FIXME reimplement with Inspector for better report
      MatchResult(observedDStream.subsetOf(expectedSuperDStream), 
      			s"""$observedDStream is not a pointwise subset of $expectedSuperDStream""", 
      			s"""$observedDStream is a pointwise subset of $expectedSuperDStream""")
    }
  }
  def beSubsetOf[A](expectedSuperDStream : PDStream[A]) = new DStreamSubsetOf(expectedSuperDStream)
}
object DStreamMatchers extends DStreamMatchers 
Example 22
Source File: SpanHandlerMatchers.scala    From money   with Apache License 2.0 5 votes vote down vote up
package com.comcast.money.akka

import akka.actor.ActorSystem
import com.comcast.money.core.handlers.HandlerChain
import org.scalatest.matchers.{ MatchResult, Matcher }

object SpanHandlerMatchers {
  def maybeCollectingSpanHandler(implicit actorSystem: ActorSystem) = maybeHandlerChain.map(_.asInstanceOf[CollectingSpanHandler])

  def clearHandlerChain(implicit actorSystem: ActorSystem) = maybeHandlerChain.foreach(_.asInstanceOf[CollectingSpanHandler].clear())

  def maybeHandlerChain(implicit actorSystem: ActorSystem) =
    MoneyExtension(actorSystem)
      .handler
      .asInstanceOf[HandlerChain]
      .handlers
      .headOption

  def checkNames(names: Seq[String], expectedNames: Seq[String]): Boolean =
    names
      .zip(expectedNames)
      .map { case (expectedName, actualName) => expectedName == actualName }
      .foldLeft(true) {
        case (_, acc) if acc == false => acc
        case (a, _) if a == false => a
        case (_, acc) => acc
      }

  def haveSomeSpanNames(expectedSpanNames: Seq[String], checkNames: (Seq[String], Seq[String]) => Boolean = checkNames) =
    Matcher {
      (maybeSpanHandler: Option[CollectingSpanHandler]) =>
        val maybeNames = maybeSpanHandler.map(_.spanInfoStack.map(_.name()))

        MatchResult(
          matches = {
            maybeNames match {
              case Some(spanNames) if spanNames.isEmpty => false
              case Some(spanNames) if spanNames.length != expectedSpanNames.length => false
              case Some(spanNames) => checkNames(spanNames, expectedSpanNames)
              case _ => false
            }
          },
          rawFailureMessage = s"Names: $maybeNames were not Some($expectedSpanNames)",
          rawNegatedFailureMessage = s"Names: $maybeNames were Some($expectedSpanNames)")
    }

  def haveSomeSpanName(expectedName: String) = haveSomeSpanNames(Seq(expectedName))

  def haveSomeSpanNamesInNoParticularOrder(expectedSpanNames: Seq[String]) = {
    def sortedCheckNames(names: Seq[String], expectedNames: Seq[String]) = checkNames(names.sortBy(_.hashCode), expectedNames.sortBy(_.hashCode))

    haveSomeSpanNames(expectedSpanNames, sortedCheckNames)
  }
} 
Example 23
Source File: MatchersTestSupport.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.drivers

import akka.http.scaladsl.model.headers.HttpCookiePair
import org.scalatest.matchers.should.Matchers._
import org.scalatest.matchers.{MatchResult, Matcher}

trait MatchersTestSupport {
  def failureMessageFor[T](matcher: Matcher[T], matchedOn: T): String =
    matcher.apply( matchedOn ).failureMessage
}

object CommonTestMatchers {

  def cookieWith(value: String): Matcher[HttpCookiePair] = be(value) compose { (_: HttpCookiePair).value }

  case class AlwaysMatcher[T]() extends Matcher[T] {
    def apply(left: T): MatchResult = MatchResult(matches = true, "", "")
  }
} 
Example 24
Source File: LoginHandlerSpec.scala    From gatling-imap   with GNU Affero General Public License v3.0 5 votes vote down vote up
package com.linagora.gatling.imap.protocol.command

import akka.actor.ActorSystem
import akka.testkit.TestProbe
import com.linagora.gatling.imap.Fixture.bart
import com.linagora.gatling.imap.protocol.{Command, Response, UserId}
import com.linagora.gatling.imap.{CyrusServer, ImapTestUtils, RunningServer}
import com.sun.mail.imap.protocol.IMAPResponse
import org.scalatest.matchers.{MatchResult, Matcher}
import org.scalatest.{BeforeAndAfterEach, Matchers, WordSpec}
import org.slf4j
import org.slf4j.LoggerFactory

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

class LoginHandlerSpec extends WordSpec with ImapTestUtils with BeforeAndAfterEach with Matchers {
  val logger: slf4j.Logger = LoggerFactory.getLogger(this.getClass.getCanonicalName)

  private val server: RunningServer = CyrusServer.start()

  override def beforeEach(): Unit = {
    server.addUser(bart)
  }

  override protected def afterEach(): Unit = {
    system.terminate()
    server.stop()
  }

  implicit lazy val system: ActorSystem = ActorSystem("LoginHandlerSpec")
  "Login handler" should {
    "send the response back when logged in" in {
      val probe = TestProbe()
      val sessionFuture = connect(server.mappedImapPort())
      sessionFuture.onComplete(session => {
        val handler = system.actorOf(LoginHandler.props(session.get))
        probe.send(handler, Command.Login(UserId(1), bart))
      })
      probe.expectMsgPF(1.minute) {
        case Response.LoggedIn(responses) => responses.isOk shouldBe true
      }
    }
  }

  object IMAPResponseMatchers {

    class HasTagMatcher(tag: String) extends Matcher[IMAPResponse] {
      def apply(left: IMAPResponse): MatchResult = {
        val name = left.getTag
        MatchResult(
          name == tag,
          s"""ImapResponse doesn't have tag "$tag"""",
          s"""ImapResponse has tag "$tag""""
        )
      }
    }

    class IsOkMatcher() extends Matcher[IMAPResponse] {
      def apply(left: IMAPResponse): MatchResult = {
        MatchResult(
          left.isOK,
          s"""ImapResponse isn't OK """,
          s"""ImapResponse is OK """
        )
      }
    }

    def isOk = new IsOkMatcher()

    def hasTag(tag: String) = new HasTagMatcher(tag)
  }

} 
Example 25
Source File: LoggingTest.scala    From incubator-retired-iota   with Apache License 2.0 5 votes vote down vote up

package org.apache.iota.fey

import ch.qos.logback.classic.{Level, Logger}
import org.scalatest.matchers.{MatchResult, Matcher}
import org.slf4j.helpers.SubstituteLogger
import org.slf4j.{LoggerFactory, Logger => SLF4JLogger}

trait LoggingTest{

  protected val logAppenderName = "inMemory"
  private val appender = findInMemoryAppender(logAppenderName)

  def beLoggedAt(logLevel: Level): Matcher[String] = new Matcher[String] {
    def apply(left: String) = {
      val containsAtLevel = appender.containsAtLevel(left, logLevel)
      MatchResult(containsAtLevel,
        s" '$left' was not found at log level",
        s" '$left' was found at log level")
    }
  }

  def resetCapturedLogs(): Unit = appender.reset()

  def dumpCapturedLogsToSysOut(): Unit = appender.dumpLogs()

  private def findInMemoryAppender(s: String): InMemoryAppender = {
    LoggerFactory.getLogger(SLF4JLogger.ROOT_LOGGER_NAME) match {
      case logger: Logger => logger.getAppender(s) match {
        case inMemoryAppender: InMemoryAppender => inMemoryAppender
        case _ => throw new IllegalStateException(s"Is the InMemoryAppender registered with logback in its configuration file with the name $s?")
      }
      case sub: SubstituteLogger => throw new IllegalStateException("SLF4J is probably still initializing. Is LoggingTest part of the outermost class wrapping your tests?")
      case _ => throw new IllegalStateException("Are you using LogBack logging?")
    }
  }
} 
Example 26
Source File: BaseJsonSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package circe

import io.circe._
import io.circe.syntax._
import org.scalatest.matchers.{ Matcher, MatchResult }
import scala.Vector

trait BaseJsonSpec extends tests.BaseSpec {

  def roundtripJson[A : Encoder : Decoder](a: A): A = {
    val json: Json = a.asJson
    json.as[A].fold(
      f => fail(f.toString),
      r => r
    )
  }

  def checkJson[A : Encoder : Decoder](a: A): A = {
    val res: A = roundtripJson(a)
    res should === (a)
    a should === (res)
    a.## should === (res.##)
    res
  }

  def checkJsonId[A <: AnyRef : Encoder : Decoder](a: A): A = {
    val res = checkJson(a)
    res shouldBe theSameInstanceAs (a)
    res
  }

  // TODO: also check cursor history
  def failWith(msg: String = ".*"): Matcher[Decoder.Result[Model]] = Matcher { res =>
    res.fold(
      failure => MatchResult(
        failure.message.matches(msg),
        "actual error message {0} does not match {1}",
        "actual error message {0} matches {1}", // FIXME
        args = Vector(failure.message, msg)
      ),
      success => MatchResult(
        false,
        "a decoding success (with result {0}) is not a failure with message {1}",
        "a decoding success (with result {0}) is a failure with message {1}", // FIXME
        args = Vector(success, msg)
      )
    )
  }
} 
Example 27
Source File: JsonMatchers.scala    From scalatest-json   with Apache License 2.0 5 votes vote down vote up
package com.stephenn.scalatest.jsonassert

import org.scalatest.matchers.MatchResult
import org.skyscreamer.jsonassert.{JSONCompare, JSONCompareMode}

import scala.util.{Failure, Success, Try}
import org.scalatest.matchers.Matcher

trait JsonMatchers {

  
  def matchJson(right: String): Matcher[String] =
    Matcher[String] { left =>
      Try(
        JSONCompare
          .compareJSON(right, left, JSONCompareMode.STRICT)
      ) match {
        case Failure(_) =>
          MatchResult(
            matches = false,
            rawFailureMessage = "Could not parse json {0} did not equal {1}",
            rawNegatedFailureMessage = "Json should not have matched {0} {1}",
            args = IndexedSeq(left.trim, right.trim)
          )
        case Success(jSONCompareResult) =>
          MatchResult(
            matches = jSONCompareResult.passed(),
            rawFailureMessage =
              "Json did not match {0} did not match {1}\n\nJson Diff:\n{2}",
            rawNegatedFailureMessage =
              "Json should not have matched {0} matched {1}\n\nJson Diff:\n{2}",
            args =
              IndexedSeq(left.trim, right.trim, jSONCompareResult.getMessage)
          )
      }
    }
}

object JsonMatchers extends JsonMatchers 
Example 28
Source File: JsonMatchers.scala    From scalatest-json   with Apache License 2.0 5 votes vote down vote up
package com.stephenn.scalatest.json4s

import org.scalatest.matchers.{MatchResult, Matcher}
import org.json4s._
import org.json4s.native.JsonMethods._

trait JsonMatchers {

  
  def matchJsonString(right: String): Matcher[JValue] = {
    Matcher[JValue] { left =>
      parseOpt(right) match {
        case None =>
          cantParseResult(compact(render(left)), right.trim)
        case Some(rightJson) =>
          matchJsonResult(compact(render(left)), right, left, rightJson)
      }
    }
  }

  private def matchJsonResult(left: String,
                              right: String,
                              leftJson: JValue,
                              rightJson: JValue) =
    MatchResult(
      matches = leftJson == rightJson,
      rawFailureMessage =
        "Json did not match {0} did not match {1}\n\nJson Diff:\n{2}",
      rawNegatedFailureMessage =
        "Json should not have matched {0} matched {1}\n\nJson Diff:\n{2}",
      args = IndexedSeq(left.trim, right.trim, diffMessage(leftJson, rightJson))
    )

  private def cantParseResult(left: String, right: String) = MatchResult(
    matches = false,
    rawFailureMessage = "Could not parse json {0} did not equal {1}",
    rawNegatedFailureMessage = "Json should not have matched {0} {1}",
    args = IndexedSeq(left.trim, right.trim)
  )

  private def diffMessage(left: JValue, right: JValue): String = {
    val Diff(c, a, d) = left diff right
    Seq(
      c.toSome.map(cc => s"Changed:\n${compact(render(cc))}"),
      a.toSome.map(aa => s"Added:\n${compact(render(aa))}"),
      d.toSome.map(dd => s"Removed:\n${compact(render(dd))}")
    ).flatten.mkString("\n")
  }
}

object JsonMatchers extends JsonMatchers 
Example 29
Source File: JsonMatchers.scala    From scalatest-json   with Apache License 2.0 5 votes vote down vote up
package com.stephenn.scalatest.playjson

import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.libs.json._

import scala.util.Try

trait JsonMatchers {

  
  def matchJsonString(right: String): Matcher[JsValue] = {
    Matcher[JsValue] { left =>
      Try(Json.parse(right)).toOption match {
        case None =>
          cantParseResult(Json.stringify(left), right.trim)
        case Some(rightJson) =>
          matchJsonResult(Json.stringify(left), right, left, rightJson)
      }
    }
  }

  private def matchJsonResult(left: String,
                              right: String,
                              leftJson: JsValue,
                              rightJson: JsValue) =
    MatchResult(
      matches = leftJson == rightJson,
      rawFailureMessage =
        "Json did not match {0} did not match {1}\n\nJson Diff:\n{2}",
      rawNegatedFailureMessage =
        "Json should not have matched {0} matched {1}\n\nJson Diff:\n{2}",
      args = IndexedSeq(left.trim, right.trim, diffMessage(leftJson, rightJson))
    )

  private def cantParseResult(left: String, right: String) = MatchResult(
    matches = false,
    rawFailureMessage = "Could not parse json {0} did not equal {1}",
    rawNegatedFailureMessage = "Json should not have matched {0} {1}",
    args = IndexedSeq(left.trim, right.trim)
  )

  private def diffMessage(left: JsValue, right: JsValue): String = {
    import diffson._
    import diffson.lcs._
    import diffson.playJson._
    import diffson.jsonpatch.lcsdiff._

    implicit val lcs = new Patience[JsValue]

    diff(left, right).toString
  }
}

object JsonMatchers extends JsonMatchers 
Example 30
Source File: TopicMatchers.scala    From kafka-configurator   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.sky.kafka.matchers

import com.sky.kafka.configurator.Topic
import org.scalatest.matchers.{ MatchResult, Matcher }
import org.scalatest.{ Matchers, Succeeded }

trait TopicMatchers extends Matchers {

  class TopicIsEquivalent(right: Topic) extends Matcher[Topic] {
    override def apply(left: Topic) = {
      val name = left.name == right.name
      val partitions = left.partitions == right.partitions
      val replication = left.replicationFactor == right.replicationFactor
      val config = (left.config should contain allElementsOf right.config).isInstanceOf[Succeeded.type]

      MatchResult(
        name && partitions && replication && config,
        s"$left is not equivalent to $right",
        s"$left is equivalent to $right"
      )
    }
  }

  def beEquivalentTo(topic: Topic) = new TopicIsEquivalent(topic)
} 
Example 31
Source File: FailureMatchers.scala    From dsentric   with Apache License 2.0 5 votes vote down vote up
package dsentric

import org.scalatest.matchers.{MatchResult, Matcher}

import dsentric._

trait FailureMatchers {
  val failWith = new FailWord
}

final class FailWord {

  def apply(right: String): Matcher[Any] =
    new Matcher[Any] {
      def apply(left: Any): MatchResult = {
        val result = left match {
          case f:Failures @unchecked =>
            f.exists(_._2 == right)
          case _ => false
        }
        val message =
          if (result) ""
          else left match {
            case f:Failures @unchecked =>
               "expected failure not found"
            case _ =>
              "expected failure"
          }

        MatchResult(
          result,
          message,
          "should not have failed with " + right
        )
      }
      override def toString: String = "failWith (" + right.toString + ")"
    }

  def apply(right: Path): Matcher[Any] =
    new Matcher[Any] {
      def apply(left: Any): MatchResult = {
        val result = left match {
          case f:Failures @unchecked  =>
            f.exists(_._1 == right)
          case _ => false
        }
        val message =
          if (result) ""
          else left match {
            case f:Failures @unchecked  =>
              "expected failure at path not found"
            case _ =>
              "expected failure"
          }

        MatchResult(
          result,
          message,
          "should not have failed at " + right
        )
      }
      override def toString: String = "failWith (" + right.toString + ")"
    }

  def apply(right: (Path, String)): Matcher[Any] =
    new Matcher[Any] {
      def apply(left: Any): MatchResult = {
        val result = left match {
          case f:Failures @unchecked =>
            f.contains(right)
          case _ => false
        }
        val message =
          if (result) ""
          else left match {
            case f:Failures @unchecked  =>
              "expected failure not found"
            case _ =>
              "expected failure"
          }

        MatchResult(
          result,
          message,
          "should not have failed with " + right
        )
      }
      override def toString: String = "failWith (" + right.toString + ")"
    }
} 
Example 32
Source File: FailWith.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.it.matchers

import com.wavesplatform.dex.it.api.responses.dex.MatcherError
import com.wavesplatform.dex.it.api.responses.dex.MatcherError.Params
import org.scalatest.matchers.{MatchResult, Matcher}

import scala.util.{Left, Right}

class FailWith(expectedErrorCode: Int, expectedMessagePart: Option[String] = None, expectedParams: Params = Params())
    extends Matcher[Either[MatcherError, Any]] {

  override def apply(input: Either[MatcherError, Any]): MatchResult = result(
    matches = input match {
      case Right(_) => false
      case Left(e) =>
        e.error == expectedErrorCode && expectedMessagePart.forall(e.message.contains) && (
          expectedParams.isEmpty || e.params.exists(Params.contains(_, expectedParams))
        )
    },
    input
  )

  private def result(matches: Boolean, r: Either[MatcherError, Any]): MatchResult =
    MatchResult(
      matches = matches,
      s"expecting Left(MatcherError(errorCode={0}, expectedMessagePart={1} params={2})) but got {3}",
      "got expected error",
      IndexedSeq(expectedErrorCode, expectedMessagePart, expectedParams, r)
    )
} 
Example 33
Source File: DiffMatcherWithImplicits.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.test.matchers

import com.softwaremill.diffx.{Derived, Diff, DiffResultDifferent, DiffResultValue, FieldPath, Identical}
import com.wavesplatform.dex.domain.account.PublicKey
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits.{DiffForMatcher, getDiff}
import org.scalatest.matchers.{MatchResult, Matcher}

trait DiffMatcherWithImplicits {

  implicit val derivedByteStrDiff: Derived[Diff[ByteStr]]     = Derived(getDiff[ByteStr](_.toString == _.toString))
  implicit val derivedPublicKeyDiff: Derived[Diff[PublicKey]] = Derived(derivedByteStrDiff.contramap[PublicKey](_.arr))

  def matchTo[A: Diff](left: A): DiffForMatcher[A] = DiffForMatcher(left)
}

object DiffMatcherWithImplicits {

  case class DiffForMatcher[A: Diff](right: A) extends Matcher[A] {
    override def apply(left: A): MatchResult = Diff[A].apply(left, right) match {
      case c: DiffResultDifferent =>
        val diff = c.show.split('\n').mkString(Console.RESET, s"${Console.RESET}\n${Console.RESET}", Console.RESET)
        MatchResult(matches = false, s"Matching error:\n$diff", "")
      case _ => MatchResult(matches = true, "", "")
    }
  }

  def getDiff[T](comparison: (T, T) => Boolean): Diff[T] = { (left: T, right: T, _: List[FieldPath]) =>
    if (comparison(left, right)) Identical(left) else DiffResultValue(left, right)
  }
}