org.scalatest.Inside Scala Examples

The following examples show how to use org.scalatest.Inside. 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: QuerySpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.http

import edu.neu.coe.csye7200.model.{GoogleQuery, YQLQuery}
import org.scalatest.{Inside, Matchers, WordSpecLike}


class QuerySpec extends WordSpecLike with Matchers with Inside {

  "YQL tech query" in {
    val symbols = List("YHOO", "AAPL", "GOOG", "MSFT")
    val uri = YQLQuery("json", diagnostics = true).createQuery(symbols)
    println(uri.toString)
    uri.toString shouldEqual "https://query.yahooapis.com/v1/public/yql?format=json&callback=&q=select+*+from+yahoo.finance.quotes+where+symbol+in+(%22YHOO%22,%22AAPL%22,%22GOOG%22,%22MSFT%22)&diagnostics=true&env=http://datatables.org/alltables.env"
  }

  "Google tech query" in {
    val symbols = List("AAPL", "YHOO")
    val uri = GoogleQuery("NASDAQ").createQuery(symbols)
    println(uri.toString)
    // TODO this is actually incorrect (and so is code being tested)--fix it
    uri.toString shouldEqual "https://finance.google.com/finance/info?q=NASDAQ:AAPL,YHOO&client=ig"
  }

} 
Example 2
Source File: MetronomeITBase.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome.integrationtest

import java.util.UUID

import com.mesosphere.utils.AkkaUnitTest
import com.mesosphere.utils.http.RestResultMatchers
import com.mesosphere.utils.mesos.MesosClusterTest
import com.typesafe.scalalogging.StrictLogging
import dcos.metronome.integrationtest.utils.{MetronomeFacade, MetronomeFramework}
import org.apache.mesos.v1.Protos.FrameworkID
import org.scalatest.Inside

import scala.concurrent.duration._

class MetronomeITBase
    extends AkkaUnitTest
    with MesosClusterTest
    with Inside
    with RestResultMatchers
    with StrictLogging {

  override lazy implicit val patienceConfig = PatienceConfig(180.seconds, interval = 1.second)

  def withFixture(frameworkId: Option[FrameworkID.Builder] = None)(fn: Fixture => Unit): Unit = {
    val f = new Fixture(frameworkId)
    try fn(f)
    finally {
      f.metronomeFramework.stop()
    }
  }

  class Fixture(existingFrameworkId: Option[FrameworkID.Builder] = None) extends StrictLogging {
    logger.info("Create Fixture with new Metronome...")

    val zkUrl = s"zk://${zkserver.connectUrl}/metronome_${UUID.randomUUID()}"
    val masterUrl = mesosFacade.url.getHost + ":" + mesosFacade.url.getPort

    val currentITName = MetronomeITBase.this.getClass.getSimpleName

    val metronomeFramework = MetronomeFramework.LocalMetronome(currentITName, masterUrl, zkUrl)

    logger.info("Starting metronome...")
    metronomeFramework.start().futureValue

    logger.info(s"Metronome started, reachable on: ${metronomeFramework.url}")
    lazy val metronome: MetronomeFacade = metronomeFramework.facade
  }

} 
Example 3
Source File: ConcordanceSpec.scala    From CSYE7200   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.concordance

import org.scalatest.{ FlatSpec, Matchers, Inside }


class ConcordanceSpec extends FlatSpec with Matchers with Inside {
  
  def parse(s: String) = {
    val p = new ConcordanceParser
    p.parseAll(p.sentence,s) match {
      case p.Success(ws,_) => ws
      case p.Failure(e,_) => println(e); List()
      case p.Error(e,_) => println(e); List()
    }
  }

  "Concordance" should "read Hello World!" in {
    val r = parse("Hello World!")
    r should matchPattern { case h::tail => }
    r.head should matchPattern { case PositionalString("Hello") => }
    inside(r.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (1)
    }
    r.tail.head should matchPattern { case PositionalString("World!") => }
    inside(r.tail.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (7)
    }
  }
    it should "read Hello<newline>World!" in {
    val r = parse("Hello\nWorld!")
    r should matchPattern { case h::tail => }
    r.head should matchPattern { case PositionalString("Hello") => }
    inside(r.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (1)
    }
    r.tail.head should matchPattern { case PositionalString("World!") => }
    inside(r.tail.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (2)
        p.pos.column shouldBe (1)
    }
  }
} 
Example 4
Source File: MiniDatabaseSpec2.scala    From CSYE7200   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.minidatabase2

import org.scalatest.{FlatSpec, Inside, Matchers}

import scala.util._


class MiniDatabaseSpec2 extends FlatSpec with Inside with Matchers {

  "map2" should "succeed for two Success values" in {
    val t1 = Success(1)
    val t2 = Success(2)
    val t3 = MiniDatabase2.map2(t1, t2) { case (x, y) => x + y }
    t3 should matchPattern { case Success(3) => }
  }
  it should "fail if any Failures" in {
    val t0 = Failure[Int](new IllegalArgumentException)
    val t1 = Success(1)
    val t2 = Success(2)
    MiniDatabase2.map2(t0, t2) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t0, t1) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t2, t0) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
  }
  "map3" should "succeed for two Some values" in {
    val t1 = Some(1)
    val t2 = Some(2)
    val t3 = Some(3)
    MiniDatabase2.map3(t1, t2, t3) { case (x, y, z) => x + y + z } should matchPattern { case Some(6) => }
  }
  it should "fail if any None values" in {
    val t1 = Some(1)
    val t2 = None
    val t3 = Some(3)
    MiniDatabase2.map3(t1, t2, t3) { case (x, y, z) => x + y + z } should matchPattern { case None => }
  }
  it should "fail if any Failures" in {
    val t0 = Failure[Int](new IllegalArgumentException)
    val t1 = Success(1)
    val t2 = Success(2)
    MiniDatabase2.map2(t0, t2) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t0, t1) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t2, t0) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
  }
  "Height" should "succeed 6 ft 5 in" in {
    Height.parse("6 ft 5 in") should matchPattern { case Success(_) => }
  }
  it should "fail 6 ft five in" in {
    Height.parse("6 ft five in") should matchPattern { case Failure(_) => }
  }
  it should """succeed 6' 5"""" in {
    Height.parse("""6' 5"""") should matchPattern { case Success(_) => }
  }
  it should """fail to parse 6'""" in {
    Height.parse("""6'""") should matchPattern { case Failure(_) => }
  }
  it should "succeed: equal 77 inches and be considered tall" in {
    val height = Height.parse("6 ft 5 in")
    inside(height) {
      case Success(h) => h should matchPattern { case Height(6, 5) => }
    }
    inside(height) {
      case Success(h) => h.inches shouldEqual 77
    }
    inside(height) {
      case Success(h) => MiniDatabase2.measure(h) should be("tall")
    }
  }

  "Name" should "succeed: Tom Brady" in {
    Name.parse("Tom Brady") should matchPattern { case Success(_) => }
  }

  it should """succeed: Thomas E. P. "Tom" Brady""" in {
    Name.parse("""Thomas E. P. "Tom" Brady""") should matchPattern { case Success(_) => }
  }

  "Entry" should """succeed: Thomas E. P. "Tom" Brady, etc.""" in {
    Entry.parse("""Thomas E. P. "Tom" Brady, 078-05-1120, Aug 3rd 1977, 6 ft 4 in, 225""".split(",")) should matchPattern { case Success(_) => }
  }

  it should """fail: Thomas E. P. "Tom" Brady""" in {
    Entry.parse("""Brady, 123-45-6789""".split(",")) should matchPattern { case Failure(_) => }
  }
} 
Example 5
Source File: RenderableSpec.scala    From CSYE7200   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200

import org.scalatest.{FlatSpec, Inside, Matchers}

import scala.util.Try

case class Scalar(s: String) extends Renderable {
  def render: String = s.toUpperCase()
}


class RenderableSpec extends FlatSpec with Matchers with Inside {
  behavior of "Renderable"
  it should "render simple values like toString" in {
    Scalar("x").render shouldBe "X"
  }
  it should "render list values with indentation" in {
    val list = Seq(Scalar("x"), Scalar("y"), Scalar("z"))
    list.render shouldBe "(\nX,\nY,\nZ\n)"
  }
  it should "render list values with double indentation" in {
    val list = Seq(Seq(Scalar("x0"), Scalar("x1")), Seq(Scalar("y0"), Scalar("y1")), Seq(Scalar("z0"), Scalar("z1")))
    list.render shouldBe "(\n(\nX0,\nX1\n),\n(\nY0,\nY1\n),\n(\nZ0,\nZ1\n)\n)"
  }
  it should "render option values" in {
    val xo = Option(Scalar("x"))
    xo.render shouldBe "Some(X)"
  }
  it should "render try values" in {
    val xy = Try(Scalar("x"))
    xy.render shouldBe "Success(X)"
  }
  it should "render either values" in {
    val e = Left(Scalar("x"))
    e.render shouldBe "Left(X)"
  }
} 
Example 6
Source File: SparkLauncherErrorHandlingTest.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.sessionmanager

import scalaz.Failure

import com.google.inject.Guice
import org.scalatest.Inside
import org.scalatest.concurrent.Futures
import org.scalatest.time.{Second, Seconds, Span}

import ai.deepsense.commons.StandardSpec
import ai.deepsense.sessionmanager.service.sessionspawner.sparklauncher.clusters.SeahorseSparkLauncher
import ai.deepsense.sessionmanager.service.sessionspawner.sparklauncher.spark.SparkArgumentParser.UnknownOption
import ai.deepsense.sessionmanager.service.sessionspawner.sparklauncher.{SparkLauncherConfig, SparkLauncherError}

class SparkLauncherErrorHandlingTest extends StandardSpec with Futures with Inside {

  import ai.deepsense.sessionmanager.service.TestData._

  private implicit val patience = PatienceConfig(Span(10, Seconds), Span(1, Second))
  private val sparkLauncherConfig = {
    val injector = Guice.createInjector(new SessionManagerAppModule())
    injector.getInstance(classOf[SparkLauncherConfig])
  }

  "Unknown opt handling (pre spark launcher)" in {
    val clusterDetails = someClusterDetails.copy (
      params = Some("--non-existing-parameter some-value")
    )
    val creating = SeahorseSparkLauncher(Nil, sparkLauncherConfig, clusterDetails)
    inside(creating) { case Failure(error) =>
      error shouldBe an [UnknownOption]
    }
  }

  "Unknown illegal conf key in params" in {
    val clusterDetails = someClusterDetails.copy (
      params = Some("--conf not-spark.executor.extraJavaOptions=-XX:+PrintGCDetails")
    )
    val creating = SeahorseSparkLauncher(Nil, sparkLauncherConfig, clusterDetails)
    inside(creating) { case Failure(error) =>
      error shouldBe an [SparkLauncherError]
      error.getMessage should include ("'key' must start with 'spark.'")
    }

  }

} 
Example 7
Source File: EpisodeParserSpec.scala    From scalalaz-gen   with Apache License 2.0 5 votes vote down vote up
package ru.scalalaz.gen.parsing

import java.time.LocalDate

import cats.data.Validated.Valid
import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.Inside

class EpisodeParserSpec extends AnyFlatSpec with Matchers with Inside {

  val episodeStr = """
      |title=Episode#1
      |page=http://scalalaz.ru/series-01.html
      |date=2016-11-28
      |audio.url=https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3
      |audio.length=6
      |----
      |### Yoyoyo!
      |it is a new episode!""".stripMargin

  it should "parse from string" in {
    val result = EpisodeParser.fromString(episodeStr)
    inside(result) {
      case Valid(episode) =>
        episode.content shouldBe "### Yoyoyo!\nit is a new episode!"

        val rss = episode.settings
        rss.title shouldBe "Episode#1"
        rss.page shouldBe "http://scalalaz.ru/series-01.html"

        rss.date shouldBe LocalDate.of(2016, 11, 28)

        rss.audio.url shouldBe "https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3"
        rss.audio.length shouldBe 6
    }
  }

} 
Example 8
Source File: FormatParserSpec.scala    From scalalaz-gen   with Apache License 2.0 5 votes vote down vote up
package ru.scalalaz.gen.parsing

import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.Inside

class FormatParserSpec extends AnyFlatSpec with Matchers with Inside {

  val raw = """title=value
      |key2=value2
      |----
      |### Yoyoyo!
      |it is a new episode!""".stripMargin

  it should "parse from string" in {
    val result = FormatParser.parseContent(raw)
    inside(result) {
      case Right(parsed) =>
        parsed.header shouldBe Map("title" -> Some("value"), "key2" -> Some("value2"))
        parsed.otherData shouldBe "### Yoyoyo!\nit is a new episode!"
    }
  }

  val raw2 =
    """
      |title=Выпуск 01
      |enc.url=https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3
      |enc.length=63337733
      |page=http://scalalaz.ru/series-01.html
      |date=2016-08-07
      |----
      |### Выпуск 01
      |
      |@:audioControls "https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3".
      |
      |Темы:
      |
      |- [Релиз-кандидат Akka](http://akka.io/news/2016/08/02/akka-…4.9-RC1-released.html)
      |- [Релиз Spark](https://exit.sc/?url=http%3A%2F%2Fspark.apache.org%2Freleases%2Fspark-release-2-0-0.html)
      |- [Релиз Spark](https://exit.sc/?url=http%3A%2F%2Fspark.apache.org%2Freleases%2Fspark-release-2-0-0.html)
      |- [Релиз Spark](https://exit.sc/?url=http%3A%2F%2Fspark.apache.org%2Freleases%2Fspark-release-2-0-0.html)
      |- [Pants](http://www.pantsbuild.org/)""".stripMargin

  it should "parse more complicated case" in {
    val result = FormatParser.parseContent(raw2)
    inside(result) {
      case Right(parsed) =>
    }
  }
} 
Example 9
Source File: ConcordanceSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.concordance

import org.scalatest.{ FlatSpec, Matchers, Inside }


class ConcordanceSpec extends FlatSpec with Matchers with Inside {
  
  def parse(s: String) = {
    val p = new ConcordanceParser
    p.parseAll(p.sentence,s) match {
      case p.Success(ws,_) => ws
      case p.Failure(e,_) => println(e); List()
      case p.Error(e,_) => println(e); List()
    }
  }

  "Concordance" should "read Hello World!" in {
    val r = parse("Hello World!")
    r should matchPattern { case h::tail => }
    r.head should matchPattern { case PositionalString("Hello") => }
    inside(r.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (1)
    }
    r.tail.head should matchPattern { case PositionalString("World!") => }
    inside(r.tail.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (7)
    }
  }
    it should "read Hello<newline>World!" in {
    val r = parse("Hello\nWorld!")
    r should matchPattern { case h::tail => }
    r.head should matchPattern { case PositionalString("Hello") => }
    inside(r.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (1)
    }
    r.tail.head should matchPattern { case PositionalString("World!") => }
    inside(r.tail.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (2)
        p.pos.column shouldBe (1)
    }
  }
} 
Example 10
Source File: TestUtils.scala    From sigmastate-interpreter   with MIT License 5 votes vote down vote up
package scalan

import scalan.util.FileUtil
import org.scalactic.TripleEquals
import org.scalatest.{Inside, Matchers, TestSuite}


  def isCI = sys.env.get("CI").flatMap(toBoolean).getOrElse(false)
  private def toBoolean(s: String): Option[Boolean] =
    scala.util.Try(s.toBoolean).toOption
  def pendingOnCI(): Unit = if (isCI) { pending }

  private val _currentTestName = new ThreadLocal[String]

  override def withFixture(test: NoArgTest) = {
    _currentTestName.set(test.name)
    val outcome = super.withFixture(test)
    _currentTestName.set(null)
    outcome
  }

  protected def currentTestName: String = {
    val testName = _currentTestName.get()
    assert(testName != null, "currentTestName called outside a test")
    testName
  }

  protected def currentTestNameAsFileName: String = FileUtil.cleanFileName(currentTestName)
} 
Example 11
Source File: PortfolioSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.portfolio

import akka.actor.{ActorRef, ActorSystem, Props, actorRef2Scala}
import akka.testkit._
import com.typesafe.config.ConfigFactory
import edu.neu.coe.csye7200.HedgeFund
import edu.neu.coe.csye7200.actors._
import edu.neu.coe.csye7200.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow
import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}

import scala.concurrent.duration._
import scala.util.Success


class PortfolioSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("MockPortfolioBlackboard"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "read portfolio" taggedAs Slow in {
    val config = ConfigFactory.load
    val portfolio = HedgeFund.getPortfolio(config)
    portfolio should matchPattern { case Some(_) => }
    portfolio.get.name shouldEqual "Test Portfolio"
    println(s"portfolio: $portfolio")
  }

  "send back" taggedAs Slow in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockPortfolioBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", put = true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234"))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, m, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(m, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockPortfolioBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[PortfolioUpdate] -> "updateLogger", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive: PartialFunction[Any, Unit] = {
    case msg: Confirmation => testActor forward msg
    case msg: QueryResponse => testActor forward msg
    //      case msg: CandidateOption => testActor forward msg
    case msg => super.receive(msg)
  }
} 
Example 12
Source File: PredicateSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.oldrules

import org.scalatest.{Inside, Matchers, WordSpecLike}

import scala.util.{Failure, Success}


class PredicateSpec extends WordSpecLike with Matchers with Inside {

  "Simple Predicate and Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    predicate(MapCandidate("test", Map("x" -> "2"))) should matchPattern {
      case Success(true) =>
    }
    predicate(MapCandidate("test", Map("x" -> "4"))) should matchPattern {
      case Success(false) =>
    }
  }

  "Simple Predicate, bad Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    inside(predicate(MapCandidate("test", Map("y" -> "2")))) {
      case Failure(x) => println(x)
    }
    inside(predicate(MapCandidate("test", Map("x" -> "y")))) {
      case Failure(x) => println(x)
    }
  }

  "String Predicate" in {
    val predicate = Predicate("x < 3")
    predicate should matchPattern {
      case NumberPredicate("x", LessThan(), 3) =>
    }
    predicate shouldEqual NumberPredicate("x", "<", 3)
  }

  "Text Predicate" in {
    val predicate = Predicate("x == Hello")
    predicate(MapCandidate("test", Map("x" -> "Hello"))) should matchPattern {
      case Success(true) =>
    }
  }
} 
Example 13
Source File: SimpleRuleSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.oldrules

import org.scalatest.{Inside, Matchers, WordSpecLike}

import scala.util.{Failure, Success}


class SimpleRuleSpec extends WordSpecLike with Matchers with Inside {

  "Simple Predicate and Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    val rule = SimpleRule(predicate)
    rule(MapCandidate("test", Map("x" -> "2"))) should matchPattern {
      case Success(true) =>
    }
    rule(MapCandidate("test", Map("x" -> "4"))) should matchPattern {
      case Success(false) =>
    }
  }

  "Simple Predicate, bad Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    val rule = SimpleRule(predicate)
    inside(rule(MapCandidate("test", Map("y" -> "2")))) {
      case Failure(x) => println(x)
    }
    inside(rule(MapCandidate("test", Map("x" -> "y")))) {
      case Failure(x) => println(x)
    }
  }

  "Simple Rule" in {
    val predicate = SimpleRule("x < 3")
    predicate should matchPattern {
      case NumberPredicate("x", LessThan(), 3) =>
    }
  }
  "Parenthesized Rule" in {
    val predicate = SimpleRule("(x < 3)")
    predicate should matchPattern {
      case NumberPredicate("x", LessThan(), 3) =>
    }
  }
  "Compound Rule" in {
    val predicate = SimpleRule("(x < 3) & (y > 1)")
    predicate should matchPattern {
      case ComposedPredicate(NumberPredicate("x", LessThan(), 3), NumberPredicate("y", GreaterThan(), 1), Predicate.and) =>
    }
  }

  // FIXME: reimplement rules in terms of Rule class

  //  "Nested Rule" in {
  //    val predicate = SimpleRule("(x < 3) & ((y > 1) | (z = 0))")
  //    predicate should matchPattern {
  //      case
  //      ComposedPredicate(NumberPredicate("x", LessThan(), 3), ComposedPredicate (
  //      NumberPredicate("y", GreaterThan(), 1),
  //      NumberPredicate("z", Equals(), 0), Predicate.or), Predicate.and) =>
  //    }
  //  }
} 
Example 14
Source File: OptionAnalyzerSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.actors

import akka.actor.{ActorRef, ActorSystem, Props, actorRef2Scala}
import akka.testkit._
import edu.neu.coe.csye7200.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow
import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}

import scala.concurrent.duration._


class OptionAnalyzerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("OptionAnalyzerSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "send back" taggedAs Slow in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockAnalyzerBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", put = true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, m, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(m, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockAnalyzerBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive: PartialFunction[Any, Unit] = {
    case msg: Confirmation => testActor forward msg
    case msg: QueryResponse => testActor forward msg
    case msg => super.receive(msg)
  }
} 
Example 15
Source File: PredicateSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.rules

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import spray.http._


class PredicateSpec extends WordSpecLike with Matchers with Inside {

  "Simple Predicate and Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    predicate.apply(MapCandidate("test", Map("x" -> "2"))) should matchPattern {
      case Right(true) =>
    }
    predicate.apply(MapCandidate("test", Map("x" -> "4"))) should matchPattern {
      case Right(false) =>
    }
  }

  "Simple Predicate, bad Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    inside(predicate.apply(MapCandidate("test", Map("y" -> "2")))) {
      case Left(x) => println(x)
    }
    inside(predicate.apply(MapCandidate("test", Map("x" -> "y")))) {
      case Left(x) => println(x)
    }
  }

  "String Predicate" in {
    val predicate = Predicate("x < 3")
    predicate should matchPattern {
      case NumberPredicate("x", LessThan(), 3) =>
    }
    predicate shouldEqual NumberPredicate("x", "<", 3)
  }

  "Text Predicate" in {
    val predicate = Predicate("x == Hello")
    predicate.apply(MapCandidate("test", Map("x" -> "Hello"))) should matchPattern {
      case Right(true) =>
    }
  }
} 
Example 16
Source File: RuleSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.rules

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import spray.http._


class RuleSpec extends WordSpecLike with Matchers with Inside {

  "Simple Predicate and Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    val rule = Rule(predicate)
    rule.apply(MapCandidate("test", Map("x" -> "2"))) should matchPattern {
      case Right(true) =>
    }
    rule.apply(MapCandidate("test", Map("x" -> "4"))) should matchPattern {
      case Right(false) =>
    }
  }

  "Simple Predicate, bad Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    val rule = Rule(predicate)
    inside(rule.apply(MapCandidate("test", Map("y" -> "2")))) {
      case Left(x) => println(x)
    }
    inside(rule.apply(MapCandidate("test", Map("x" -> "y")))) {
      case Left(x) => println(x)
    }
  }

  "Simple Rule" in {
    val predicate = Rule("x < 3")
    predicate should matchPattern {
      case NumberPredicate("x", LessThan(), 3) =>
    }
  }
  "Compound Rule" in {
    val predicate = Rule("(x < 3) & (y > 1)")
    predicate should matchPattern {
      case And(NumberPredicate("x", LessThan(), 3), NumberPredicate("y", GreaterThan(), 1)) =>
    }
  }
  "Nested Rule" in {
    val predicate = Rule("(x < 3) & ((y > 1) | (z = 0))")
    predicate should matchPattern {
      case And(
        NumberPredicate("x", LessThan(), 3),
        Or(
          NumberPredicate("y", GreaterThan(), 1),
          NumberPredicate("z", Equals(), 0))) =>
    }
  }
} 
Example 17
Source File: QuerySpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.http

import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}
import edu.neu.coe.csye7200.hedge_fund.model.{GoogleQuery, YQLQuery}


class QuerySpec extends WordSpecLike with Matchers with Inside {

  "YQL tech query" in {
    val symbols = List("YHOO", "AAPL", "GOOG", "MSFT")
    val uri = YQLQuery("json", true).createQuery(symbols)
    println(uri.toString)
    uri.toString shouldEqual "https://query.yahooapis.com/v1/public/yql?format=json&callback=&q=select+*+from+yahoo.finance.quotes+where+symbol+in+(%22YHOO%22,%22AAPL%22,%22GOOG%22,%22MSFT%22)&diagnostics=true&env=http://datatables.org/alltables.env"
  }

  "Google tech query" in {
    val symbols = List("AAPL", "YHOO")
    val uri = GoogleQuery("NASDAQ").createQuery(symbols)
    println(uri.toString)
    // TODO this is actually incorrect (and so is code being tested)--fix it
    uri.toString shouldEqual "https://finance.google.com/finance/info?q=NASDAQ:AAPL,YHOO&client=ig"
  }

} 
Example 18
Source File: PortfolioSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.portfolio

import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit._

import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import com.typesafe.config.ConfigFactory
import edu.neu.coe.csye7200.hedge_fund.HedgeFund
import edu.neu.coe.csye7200.hedge_fund.actors._
import edu.neu.coe.csye7200.hedge_fund.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow


class PortfolioSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("MockPortfolioBlackboard"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }
  
  "read portfolio" taggedAs(Slow) in {
    val config = ConfigFactory.load
    val portfolio = HedgeFund.getPortfolio(config)
    portfolio.name shouldEqual "Test Portfolio"
    println(s"portfolio: $portfolio")
  }

  "send back" taggedAs(Slow) in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockPortfolioBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234"))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockPortfolioBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[PortfolioUpdate] -> "updateLogger", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponse => testActor forward msg
//      case msg: CandidateOption => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 19
Source File: ServiceClientSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos

import _root_.io.circe.Json
import com.mesosphere.cosmos.http.Authorization
import com.mesosphere.cosmos.http.RequestSession
import com.mesosphere.cosmos.test.TestUtil
import com.mesosphere.http.OriginHostScheme
import io.lemonlabs.uri.Uri
import com.twitter.finagle.http.Request
import org.scalatest.FreeSpec
import org.scalatest.Inside

final class ServiceClientSpec extends FreeSpec with Inside {

  import ServiceClientSpec._

  "A ServiceClient" - {
    "supports an optional AuthorizationHeaderName request header" - {
      "so that Cosmos can interact with security-enabled AdminRouters" - {
        val testClient = new AuthorizationTestClient()
        "header not provided" - {

          implicit val session = TestUtil.Anonymous

          "with baseRequestBuilder()" in {
            val requestBuilder = testClient.baseRequestBuilder(Uri.parse("/foo/bar/baz"))
            assert(!requestBuilder.buildGet.headerMap.contains(AuthorizationHeaderName))
          }
          "with get()" in {
            assert(!testClient.testGet.headerMap.contains(AuthorizationHeaderName))
          }
          "with post()" in {
            assert(!testClient.testPost.headerMap.contains(AuthorizationHeaderName))
          }
          "with postForm()" in {
            assert(!testClient.testPostForm.headerMap.contains(AuthorizationHeaderName))
          }
          "with delete()" in {
            assert(!testClient.testDelete.headerMap.contains(AuthorizationHeaderName))
          }
        }

        "header provided" - {

          implicit val session = RequestSession(
            Some(Authorization("credentials")),
            OriginHostScheme("localhost", OriginHostScheme.Scheme.http)
          )

          "with baseRequestBuilder()" in {
            val requestBuilder = testClient.baseRequestBuilder(Uri.parse("/foo/bar/baz"))
            val headerOpt = requestBuilder.buildDelete.headerMap.get(AuthorizationHeaderName)
            inside(headerOpt) { case Some(header) => assertResult("credentials")(header) }
          }
          "with get()" in {
            val headerOpt = testClient.testGet.headerMap.get(AuthorizationHeaderName)
            inside (headerOpt) { case Some(header) => assertResult("credentials")(header) }
          }
          "with post()" in {
            val headerOpt = testClient.testPost.headerMap.get(AuthorizationHeaderName)
            inside (headerOpt) { case Some(header) => assertResult("credentials")(header) }
          }
          "with postForm()" in {
            val headerOpt = testClient.testPostForm.headerMap.get(AuthorizationHeaderName)
            inside (headerOpt) { case Some(header) => assertResult("credentials")(header) }
          }
          "with delete()" in {
            val headerOpt = testClient.testDelete.headerMap.get(AuthorizationHeaderName)
            inside (headerOpt) { case Some(header) => assertResult("credentials")(header) }
          }
        }
      }
    }
  }

}

object ServiceClientSpec {
  private[cosmos] val PathUri: Uri = Uri.parse("/foo/bar/baz")
  private val AuthorizationHeaderName: String = "Authorization"
}

private final class AuthorizationTestClient
  extends ServiceClient(Uri.parse("http://example.com")) {

  def testGet(implicit session: RequestSession): Request = get(ServiceClientSpec.PathUri)
  def testPost(implicit session: RequestSession): Request = post(ServiceClientSpec.PathUri, Json.Null)
  def testPostForm(implicit session: RequestSession): Request = postForm(ServiceClientSpec.PathUri, "")
  def testDelete(implicit session: RequestSession): Request = delete(ServiceClientSpec.PathUri)

} 
Example 20
Source File: MutantRunResultMapperTest.scala    From stryker4s   with Apache License 2.0 5 votes vote down vote up
package stryker4s.report.mapper
import java.nio.file.Path

import better.files.File
import mutationtesting._
import org.scalatest.Inside
import stryker4s.config.{Config, Thresholds => ConfigThresholds}
import stryker4s.extension.FileExtensions._
import stryker4s.extension.ImplicitMutationConversion._
import stryker4s.extension.mutationtype._
import stryker4s.model.{Killed, Mutant, Survived}
import stryker4s.scalatest.FileUtil
import stryker4s.testutil.Stryker4sSuite

import scala.meta.{Lit, Term}

class MutantRunResultMapperTest extends Stryker4sSuite with Inside {
  describe("mapper") {
    it("should map 4 files to valid MutationTestReport") {
      val sut = new MutantRunResultMapper {}
      implicit val config: Config = Config(thresholds = ConfigThresholds(high = 60, low = 40))

      val path = FileUtil.getResource("scalaFiles/ExampleClass.scala").relativePath
      val mutantRunResult = Killed(
        toMutant(0, EqualTo, NotEqualTo, path),
        path
      )
      val mutantRunResult2 = Survived(
        toMutant(1, Lit.String("Hugo"), EmptyString, path),
        path
      )
      val path3 = FileUtil.getResource("scalaFiles/simpleFile.scala").relativePath
      val mutantRunResult3 = Killed(
        toMutant(0, GreaterThan, LesserThan, path3),
        path3
      )

      val mutationRunResults = List(mutantRunResult, mutantRunResult2, mutantRunResult3)

      val result = sut.toReport(mutationRunResults)
      inside(result) {
        case MutationTestReport(_, _, thresholds, files) =>
          thresholds should equal(Thresholds(high = 60, low = 40))
          files should have size 2
          val firstResult = files.find(_._1.endsWith("scalaFiles/ExampleClass.scala")).value
          files.find(_._1.endsWith("scalaFiles/simpleFile.scala")).value
          inside(firstResult._2) {
            case MutationTestResult(source, mutants, language) =>
              language should equal("scala")
              mutants should (
                contain.only(
                  MutantResult(
                    "0",
                    "EqualityOperator",
                    "!=",
                    Location(Position(4, 27), Position(4, 29)),
                    MutantStatus.Killed
                  ),
                  MutantResult(
                    "1",
                    "StringLiteral",
                    "\"\"",
                    Location(Position(6, 31), Position(6, 37)),
                    MutantStatus.Survived
                  )
                )
              )
              source should equal(FileUtil.getResource("scalaFiles/ExampleClass.scala").contentAsString)
          }
      }
    }
  }

  
  private def toMutant(id: Int, original: Term, category: SubstitutionMutation[_ <: Term], file: Path) = {
    import stryker4s.extension.TreeExtensions.FindExtension

    import scala.meta._
    val parsed = File(file).contentAsString.parse[Source]
    val foundOrig = parsed.get.find(original).value
    Mutant(id, foundOrig, category.tree, category)
  }
} 
Example 21
Source File: AkkaCompatSpec.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.compat.akka

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._

import scala.concurrent.duration._
import org.scalatest.{BeforeAndAfterAll, FreeSpec, Inside, Matchers}
import swave.core._
import swave.core.util._

class AkkaCompatSpec extends FreeSpec with Matchers with Inside with BeforeAndAfterAll {

  implicit val env          = StreamEnv()
  implicit val system       = ActorSystem()
  implicit val materializer = ActorMaterializer()

  "Akka compatibility should work as expected" - {

    "Source.toSpout" in {
      Source(1 to 10).toSpout.drainToList(100).await() shouldEqual (1 to 10)
    }

    "Spout.toAkkaSource" in {
      Spout(1 to 10).toAkkaSource.runWith(Sink.seq).await() shouldEqual (1 to 10)
    }

    "Flow.toPipe" in {
      val flow = Flow[Int].map(_ * -1)
      Spout(1 to 10).via(flow.toPipe).drainToList(100).await() shouldEqual (-1 to -10 by -1)
    }

    "Pipe.toAkkaFlow" in {
      val pipe = Pipe[Int].map(_ * -1)
      Source(1 to 10).via(pipe.toAkkaFlow).runWith(Sink.seq).await() shouldEqual (-1 to -10 by -1)
    }

    "Sink.toDrain" in {
      val sink = Sink.seq[Int]
      Spout(1 to 10).drainTo(sink.toDrain).await() shouldEqual (1 to 10)
    }

    "Drain.toAkkaSink" in {
      val drain = Drain.seq[Int](100)
      Source(1 to 10).runWith(drain.toAkkaSink).await() shouldEqual (1 to 10)
    }
  }

  override val invokeBeforeAllAndAfterAllEvenIfNoTestsAreExpected = true

  override protected def afterAll(): Unit = {
    val envTermination = env.shutdown()
    system.terminate().await(2.seconds)
    envTermination.awaitTermination(2.seconds)
  }
} 
Example 22
Source File: SmartConstructorTest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.lang

import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.lang.v1.compiler.Terms
import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CONST_STRING}
import org.scalatest.{Inside, Matchers, PropSpec}

class SmartConstructorTest extends PropSpec with Matchers with Inside {
  property("CONST_BYTESTR size limit") {
    val allowedBytes = ByteStr.fill(Terms.DataEntryValueMax)(1)
    inside(CONST_BYTESTR(allowedBytes)) {
      case Right(CONST_BYTESTR(bytes)) => bytes shouldBe allowedBytes
    }

    val illegalBytes = ByteStr.fill(Terms.DataEntryValueMax + 1)(1)
    CONST_BYTESTR(illegalBytes) shouldBe Symbol("left")
  }

  property("CONST_STRING size limit") {
    val allowedString = "ё" * (Terms.DataEntryValueMax / 2)
    inside(CONST_STRING(allowedString)) {
      case Right(CONST_STRING(str)) =>
        str shouldBe allowedString
        str.getBytes("UTF-8").length shouldBe Terms.DataEntryValueMax - 1
    }

    val illegalString = "ё" * (Terms.DataEntryValueMax / 2 + 1)
    CONST_STRING(illegalString) shouldBe Symbol("left")
  }
} 
Example 23
Source File: AccountOrAliasTests.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.account

import com.wavesplatform.EitherMatchers
import com.wavesplatform.common.utils.EitherExt2
import org.scalatest.{Inside, Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class AccountOrAliasTests extends PropSpec with PropertyChecks with Matchers with EitherMatchers with Inside {

  property("Account should get parsed correctly") {
    AddressOrAlias.fromString("3My3KZgFQ3CrVHgz6vGRt8687sH4oAA1qp8").explicitGet() shouldBe an[Address]
    AddressOrAlias.fromString("address:3My3KZgFQ3CrVHgz6vGRt8687sH4oAA1qp8").explicitGet() shouldBe an[Address]
  }

  property("Alias should get parsed correctly") {
    inside(AddressOrAlias.fromString("alias:T:sasha").explicitGet()) {
      case alias: Alias =>
        alias.name shouldBe "sasha"
        alias.chainId shouldBe 'T'
    }

    val alias2 = Alias.fromString("alias:T:sasha").explicitGet()
    alias2.name shouldBe "sasha"
    alias2.chainId shouldBe 'T'
  }

  property("Alias can be from other network") {
    AddressOrAlias.fromString("alias:Q:sasha") shouldBe Alias.createWithChainId("sasha", 'Q'.toByte)
  }

  property("Malformed aliases cannot be reconstructed") {
    AddressOrAlias.fromString("alias::sasha") should beLeft
    AddressOrAlias.fromString("alias:T: sasha") should beLeft
    AddressOrAlias.fromString("alias:T:sasha\nivanov") should beLeft
    AddressOrAlias.fromString("alias:T:s") should beLeft
    AddressOrAlias.fromString("alias:TTT:sasha") should beLeft

    Alias.fromString("alias:T: sasha") should beLeft
    Alias.fromString("alias:T:sasha\nivanov") should beLeft
    Alias.fromString("alias::sasha") should beLeft
    Alias.fromString("alias:T:s") should beLeft
    Alias.fromString("alias:TTT:sasha") should beLeft

    Alias.fromString("aliaaas:W:sasha") should beLeft
  }

  property("Unknown address schemes cannot be parsed") {
    AddressOrAlias.fromString("postcode:119072") should beLeft
  }
} 
Example 24
Source File: ConsumerRecordsSpec.scala    From scala-kafka-client   with MIT License 5 votes vote down vote up
package cakesolutions.kafka.akka

import cakesolutions.kafka.KafkaTopicPartition
import org.scalatest.{FlatSpecLike, Inside, Matchers}

class ConsumerRecordsSpec extends FlatSpecLike with Matchers with Inside {

  val partition = KafkaTopicPartition("sometopic", 0)
  val knownInput: ConsumerRecords[String, Int] = ConsumerRecords.fromPairs(partition, Seq(Some("foo") -> 1))
  val partiallyKnownInput: ConsumerRecords[_, _] = knownInput
  val anyInput: Any = knownInput

  "ConsumerRecords" should "match types correctly" in {
    partiallyKnownInput.hasType[ConsumerRecords[String, Int]] shouldEqual true
    partiallyKnownInput.hasType[ConsumerRecords[Int, String]] shouldEqual false
  }

  it should "cast to only correct types" in {
    val success = partiallyKnownInput.cast[ConsumerRecords[String, Int]]
    val failure = partiallyKnownInput.cast[ConsumerRecords[Int, String]]

    success shouldEqual Some(knownInput)
    failure shouldEqual None
  }

  it should "extract values correctly" in {
    val correctExt = ConsumerRecords.extractor[String, Int]
    val incorrectExt = ConsumerRecords.extractor[Int, String]

    anyInput should not matchPattern {
      case incorrectExt(_) =>
    }

    inside(anyInput) {
      case correctExt(kvs) =>
        kvs shouldEqual knownInput
    }
  }
} 
Example 25
Source File: MiniDatabaseSpec2.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package edu.neu.coe.csye._7200.minidatabase2

import org.scalatest.{FlatSpec, Inside, Matchers}

import scala.util._


class MiniDatabase2Spec extends FlatSpec with Inside with Matchers {
  
  "map2" should "succeed for two Success values" in {
    val t1 = Success(1)
    val t2 = Success(2)
    val t3 = MiniDatabase2.map2(t1,t2){case (x,y) => x+y}
    t3 should matchPattern { case Success(3) => }
  }
  it should "fail if any Failures" in {
    val t0 = Failure[Int](new IllegalArgumentException)
    val t1 = Success(1)
    val t2 = Success(2)
    MiniDatabase2.map2(t0,t2){case (x,y) => x+y} should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t0,t1){case (x,y) => x+y} should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t2,t0){case (x,y) => x+y} should matchPattern { case Failure(_) => }
  }
  "map3" should "succeed for two Some values" in {
    val t1 = Some(1)
    val t2 = Some(2)
    val t3 = Some(3)
    MiniDatabase2.map3(t1,t2,t3){case (x,y,z) => x+y+z} should matchPattern { case Some(6) => }
  }
  it should "fail if any None values" in {
    val t1 = Some(1)
    val t2 = None
    val t3 = Some(3)
    MiniDatabase2.map3(t1,t2,t3){case (x,y,z) => x+y+z} should matchPattern { case None => }
  }
  it should "fail if any Failures" in {
    val t0 = Failure[Int](new IllegalArgumentException)
    val t1 = Success(1)
    val t2 = Success(2)
    MiniDatabase2.map2(t0,t2){case (x,y) => x+y} should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t0,t1){case (x,y) => x+y} should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t2,t0){case (x,y) => x+y} should matchPattern { case Failure(_) => }
  }
  "Height" should "succeed 6 ft 5 in" in {
    Height.parse("6 ft 5 in") should matchPattern { case Success(h) => }
  }
  it should "fail 6 ft five in" in {
    Height.parse("6 ft five in") should matchPattern { case Failure(x) => }
  }
  it should """succeed 6' 5"""" in {
    Height.parse("""6' 5"""") should matchPattern { case Success(h) => }
  }
  it should """fail to parse 6'""" in {
    Height.parse("""6'""") should matchPattern { case Failure(x) => }
  }
  it should "succeed: equal 77 inches and be considered tall" in {
    val height = Height.parse("6 ft 5 in")    
    inside(height) {
      case Success(h) => h should matchPattern { case Height(6,5) => }
    }
    inside(height) {
      case Success(h) => h.inches shouldEqual (77)
    }
    inside(height) {
      case Success(h) => MiniDatabase2.measure(h) should be ("tall")
    }
  }

  "Name" should "succeed: Tom Brady" in {
    Name.parse("Tom Brady") should matchPattern { case Success(h) => }
  }
  
  it should """succeed: Thomas E. P. "Tom" Brady""" in {
    Name.parse("""Thomas E. P. "Tom" Brady""") should matchPattern { case Success(h) => }
  }
  
  "Entry" should """succeed: Thomas E. P. "Tom" Brady, etc.""" in {
    Entry.parse("""Thomas E. P. "Tom" Brady, 078-05-1120, Aug 3rd 1977, 6 ft 4 in, 225""".split(",")) should matchPattern { case Success(h) => }
  }
  
  it should """fail: Thomas E. P. "Tom" Brady""" in {
    Entry.parse("""Brady, 123-45-6789""".split(",")) should matchPattern { case Failure(x) => }
  }
} 
Example 26
Source File: JsonYQLParserSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.actors

import akka.actor.{ ActorSystem, Actor, Props, ActorRef }
import akka.testkit._
import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll }
import scala.io.Source
import scala.concurrent.duration._
import spray.http._
import spray.http.MediaTypes._
import org.scalatest.Inside
import scala.language.postfixOps
import spray.http.ContentType.apply


class JsonYQLParserSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("JsonYQLParserSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  import scala.language.postfixOps
  val json = Source.fromFile("src/test/resources/yqlExample.json") mkString

  "json conversion" in {
    val body = HttpEntity(MediaTypes.`application/json`, json.getBytes())
    val ok = JsonYQLParser.decode(body) match {
      case Right(x) =>
        val count = x.query.count
        count should equal(4)
        x.query.results.quote.length should equal(count)
        x.query.results.get(count - 1, "symbol") should matchPattern { case Some("MSFT") => }

      case Left(x) =>
        fail("decoding error: " + x)
    }
  }

  "send back" in {
    val blackboard = system.actorOf(Props.create(classOf[MockYQLBlackboard], testActor), "blackboard")
    val entityParser = _system.actorOf(Props.create(classOf[EntityParser], blackboard), "entityParser")
    val entity = HttpEntity(MediaTypes.`application/json`, json.getBytes())
    entityParser ! EntityMessage("json:YQL", entity)
    val msg = expectMsgClass(3.seconds, classOf[QueryResponseValid])
    println("msg received: " + msg)
    msg should matchPattern {
      case QueryResponseValid("MSFT", _) =>
    }
    inside(msg) {
      case QueryResponseValid(symbol, attributes) => attributes.get("Ask") should matchPattern { case Some("46.17") => }
    }
  }

}

import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.Await
import com.phasmid.hedge_fund.model.Model

class MockYQLUpdateLogger(blackboard: ActorRef) extends UpdateLogger(blackboard) {
  override def processStock(identifier: String, model: Model) = {
    model.getKey("price") match {
      case Some(p) => {
        // sender is the MarketData actor
        val future = sender ? SymbolQuery(identifier, List(p))
        val result = Await.result(future, timeout.duration).asInstanceOf[QueryResponseValid]
        result.attributes map {
          case (k, v) =>
            log.info(s"$identifier attribute $k has been updated to: $v")
            blackboard ! result
        }
      }
      case None => log.warning(s"'price' not defined in model")
    }
  }
}

class MockYQLBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[MockYQLUpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => msg match {
        // Cut down on the volume of messages
        case Confirmation("MSFT", _, _) => super.receive(msg)
        case _ =>
      }
      case msg: QueryResponseValid => testActor forward msg

      case msg => super.receive(msg)
    }
} 
Example 27
Source File: OptionAnalyzerSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.actors

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import akka.actor.{ ActorSystem, Actor, Props, ActorRef }
import akka.testkit._
import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import com.phasmid.hedge_fund.model._


class OptionAnalyzerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("OptionAnalyzerSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "send back" in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockAnalyzerBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "54.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45, "EV" -> "37.132B", "EBITDA" -> "3.046B"))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponseValid])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponseValid(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockAnalyzerBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponseValid => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 28
Source File: PortfolioSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.portfolio

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import akka.actor.{ ActorSystem, Actor, Props, ActorRef }
import akka.testkit._
import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import com.phasmid.hedge_fund.HedgeFund
import com.phasmid.hedge_fund.actors._
import com.typesafe.config.ConfigFactory
import com.phasmid.hedge_fund.model.GoogleOptionModel


class PortfolioSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("MockPortfolioBlackboard"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }
  
  "read portfolio" in {
    val config = ConfigFactory.load
    val portfolio = HedgeFund.getPortfolio(config)
    portfolio.name shouldEqual "Test Portfolio"
    println(s"portfolio: $portfolio")
  }

  "send back" in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockPortfolioBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45, "EV" -> 37132000000.0, "EBITDA" -> 3046000000.0))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponseValid(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockPortfolioBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[PortfolioUpdate] -> "updateLogger", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponse => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 29
Source File: QuerySpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.http

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import spray.http._
import com.phasmid.hedge_fund.model.GoogleQuery
import com.phasmid.hedge_fund.model.YQLQuery


class QuerySpec extends WordSpecLike with Matchers with Inside {

  "YQL tech query" in {
    val symbols = List("YHOO", "AAPL", "GOOG", "MSFT")
    val uri = YQLQuery("json", true).createQuery(symbols)
    println(uri.toString)
    uri.toString shouldEqual "https://query.yahooapis.com/v1/public/yql?format=json&callback=&q=select+*+from+yahoo.finance.quotes+where+symbol+in+(%22YHOO%22,%22AAPL%22,%22GOOG%22,%22MSFT%22)&diagnostics=true&env=http://datatables.org/alltables.env"
  }

  "Google tech query" in {
    val symbols = List("AAPL", "YHOO")
    val uri = GoogleQuery("NASDAQ").createQuery(symbols)
    println(uri.toString)
    // TODO this is actually incorrect (and so is code being tested)--fix it
    uri.toString shouldEqual "https://finance.google.com/finance/info?q=NASDAQ:AAPL,YHOO&client=ig"
  }

} 
Example 30
Source File: RuleSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.rules

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import spray.http._


class RuleSpec extends WordSpecLike with Matchers with Inside {

  "Simple Predicate and Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    val rule = Rule(predicate)
    rule.apply(MapCandidate("test", Map("x" -> "2"))) should matchPattern {
      case Right(true) =>
    }
    rule.apply(MapCandidate("test", Map("x" -> "4"))) should matchPattern {
      case Right(false) =>
    }
  }

  "Simple Predicate, bad Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    val rule = Rule(predicate)
    inside(rule.apply(MapCandidate("test", Map("y" -> "2")))) {
      case Left(x) =>
    }
    inside(rule.apply(MapCandidate("test", Map("x" -> "y")))) {
      case Left(x) =>
    }
  }

  "Simple Rule" in {
    val predicate = Rule("x < 3")
    predicate should matchPattern {
      case NumberPredicate("x", LessThan(), 3) =>
    }
  }
  "Compound Rule" in {
    val predicate = Rule("(x < 3) & (y > 1)")
    predicate should matchPattern {
      case And(NumberPredicate("x", LessThan(), 3), NumberPredicate("y", GreaterThan(), 1)) =>
    }
  }
  "Nested Rule" in {
    val predicate = Rule("(x < 3) & ((y > 1) | (z = 0))")
    predicate should matchPattern {
      case And(
        NumberPredicate("x", LessThan(), 3),
        Or(
          NumberPredicate("y", GreaterThan(), 1),
          NumberPredicate("z", Equals(), 0))) =>
    }
  }
} 
Example 31
Source File: PredicateSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.rules

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import spray.http._


class PredicateSpec extends WordSpecLike with Matchers with Inside {

  "Simple Predicate and Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    predicate.apply(MapCandidate("test", Map("x" -> "2"))) should matchPattern {
      case Right(true) =>
    }
    predicate.apply(MapCandidate("test", Map("x" -> "4"))) should matchPattern {
      case Right(false) =>
    }
  }

  "Simple Predicate, bad Candidate" in {
    val predicate = NumberPredicate("x", "<", 3)
    inside(predicate.apply(MapCandidate("test", Map("y" -> "2")))) {
      case Left(x) =>
    }
    inside(predicate.apply(MapCandidate("test", Map("x" -> "y")))) {
      case Left(x) =>
    }
  }

  "String Predicate" in {
    val predicate = Predicate("x < 3")
    predicate should matchPattern {
      case NumberPredicate("x", LessThan(), 3) =>
    }
    predicate shouldEqual NumberPredicate("x", "<", 3)
  }

  "Text Predicate" in {
    val predicate = Predicate("x == Hello")
    predicate.apply(MapCandidate("test", Map("x" -> "Hello"))) should matchPattern {
      case Right(true) =>
    }
  }
} 
Example 32
Source File: ConcordanceSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.concordance

import org.scalatest.{ FlatSpec, Matchers, Inside }


class ConcordanceSpec extends FlatSpec with Matchers with Inside {
  
  def parse(s: String) = {
    val p = new ConcordanceParser
    p.parseAll(p.sentence,s) match {
      case p.Success(ws,_) => ws
      case p.Failure(e,_) => println(e); List()
      case p.Error(e,_) => println(e); List()
    }
  }

  "Concordance" should "read Hello World!" in {
    val r = parse("Hello World!")
    r should matchPattern { case h::tail => }
    r.head should matchPattern { case PositionalString("Hello") => }
    inside(r.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (1)
    }
    r.tail.head should matchPattern { case PositionalString("World!") => }
    inside(r.tail.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (7)
    }
  }
    it should "read Hello<newline>World!" in {
    val r = parse("Hello\nWorld!")
    r should matchPattern { case h::tail => }
    r.head should matchPattern { case PositionalString("Hello") => }
    inside(r.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (1)
        p.pos.column shouldBe (1)
    }
    r.tail.head should matchPattern { case PositionalString("World!") => }
    inside(r.tail.head) { case p @ PositionalString(_) =>
        p.pos.line shouldBe (2)
        p.pos.column shouldBe (1)
    }
  }
} 
Example 33
Source File: IntellijPluginResolverTestBase.scala    From sbt-idea-plugin   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.sbtidea.download.plugin

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

import org.jetbrains.sbtidea.Keys._
import org.jetbrains.sbtidea.download.plugin.PluginDescriptor.Dependency
import org.jetbrains.sbtidea.{Keys, download, pathToPathExt}
import org.scalatest.Inside
import sbt._

import scala.language.implicitConversions

abstract class IntellijPluginResolverTestBase extends IntellijPluginInstallerTestBase with Inside {

  protected val pluginA: PluginDescriptor = PluginDescriptor("org.A", "A - bundled", "0", "", "")
  protected val pluginB: PluginDescriptor = PluginDescriptor("org.B", "B - remote", "0", "", "")
  protected val pluginC: PluginDescriptor = PluginDescriptor("org.C", "C - remote", "0", "", "",
    Seq(Dependency("org.A", optional = true), Dependency("org.B", optional = false)))
  protected val pluginD: PluginDescriptor = PluginDescriptor("org.D", "D - remote cyclic", "0", "", "",
    Seq(Dependency("org.E", optional = false), Dependency("org.A", optional = true)))
  protected val pluginE: PluginDescriptor = PluginDescriptor("org.E", "C - remote cyclic", "0", "", "",
    Seq(Dependency("org.D", optional = false), Dependency("org.C", optional = true)))

  protected val descriptorMap: Map[String, PluginDescriptor] =
    Seq(pluginA, pluginB, pluginC, pluginD, pluginE).map(p => p.id -> p).toMap

  protected implicit def descriptor2Plugin(descriptor: PluginDescriptor): PluginDependency =
      PluginDependency(Keys.IntellijPlugin.Id(descriptor.id, None, None),
        IDEA_BUILDINFO,
        descriptor.dependsOn.map(p => plugin2PluginDep(p.id.toPlugin)))

  override protected implicit val localRegistry: LocalPluginRegistryApi = new LocalPluginRegistryApi {
    override def getPluginDescriptor(ideaPlugin: Keys.IntellijPlugin): Either[String, PluginDescriptor] = ideaPlugin match {
      case IntellijPlugin.Url(_) =>
        throw new IllegalArgumentException("url plugin not supported")
      case IntellijPlugin.Id(id, _, _) =>
        descriptorMap.get(id).filterNot(_.name.contains("remote")).toRight("plugin is remote")
      case IntellijPlugin.BundledFolder(name) =>
        descriptorMap.get(name).filterNot(_.name.contains("remote")).toRight("plugin is remote")
    }
    override def isPluginInstalled(ideaPlugin: Keys.IntellijPlugin): Boolean = ideaPlugin match {
      case IntellijPlugin.Url(_) => false
      case IntellijPlugin.Id(id, _, _) =>
        descriptorMap.get(id).exists(_.name.contains("bundled"))
      case IntellijPlugin.BundledFolder(name) =>
        descriptorMap.get(name).exists(_.name.contains("bundled"))
    }

    override def getAllDescriptors: Seq[PluginDescriptor] = descriptorMap.values.toSeq
    override def markPluginInstalled(ideaPlugin: Keys.IntellijPlugin, to: Path): Unit = ()
    override def getInstalledPluginRoot(ideaPlugin: Keys.IntellijPlugin): Path =
      Paths.get("INVALID")
  }

  override protected implicit val repoAPI: PluginRepoApi = new PluginRepoApi {
    override def getRemotePluginXmlDescriptor(idea: download.BuildInfo, pluginId: String, channel: Option[String]): Either[Throwable, PluginDescriptor] =
      descriptorMap.get(pluginId).filter(_.name.contains("remote")).toRight(null)
    override def getPluginDownloadURL(idea: download.BuildInfo, pluginInfo: Keys.IntellijPlugin.Id): URL =
      new URL("file:INVALID")
    override def getLatestPluginVersion(idea: download.BuildInfo, pluginId: String, channel: Option[String]): Either[Throwable, String] =
      throw new IllegalArgumentException
  }

} 
Example 34
Source File: BaseSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package tests

import org.scalatest.matchers.should.Matchers
import org.scalatest.freespec.AnyFreeSpecLike
import org.scalatest.Inside
import org.scalactic.TypeCheckedTripleEquals

trait BaseSpec
  extends AnyFreeSpecLike
  with Matchers
  with Inside
  with TypeCheckedTripleEquals
  with laws.Serialization {

  final val notFound =
    "could not find implicit value for parameter compat:.*"

  def checkEqHash[A](a: A, b: A): Unit = {
    a should === (b)
    b should === (a)
    a.## should === (b.##)
    a.hashCode should === (b.hashCode)
  }

  def checkEqHashCompat(a: Model, b: Model): Unit = {
    checkEqHash(a, b)
    checkCompatible(a, b)
  }

  def checkCompatible(a: Model, b: Model): Unit = {
    if (!a.compatible(b)) {
      fail(s"${a} wasn't compatible with ${b} (it should)")
    }
    if (!b.compatible(a)) {
      fail(s"${b} wasn't compatible with ${a} (it should)")
    } else {
      if (a !== b) {
        a.## should !== (b.##)
        a.hashCode should !== (b.hashCode)
      }
    }
  }

  def checkNotEqHash[A](a: A, b: A): Unit = {
    a should !== (b)
    a.## should !== (b.##)
    a.hashCode should !== (b.hashCode)
  }

  def checkNotEqHashCompat(a: Model, b: Model): Unit = {
    checkNotEqHash(a, b)
    checkNotCompatible(a, b)
  }

  def checkNotCompatible(a: Model, b: Model): Unit = {
    if (a.compatible(b)) {
      fail(s"${a} was compatible with ${b} (it shouldn't)")
    }
    if (b.compatible(a)) {
      fail(s"${b} was compatible with ${a} (it shouldn't)")
    } else {
      a.## should !== (b.##)
      a.hashCode should !== (b.hashCode)
    }
  }

  def checkSer[A <: AnyRef](a: A): A = {
    val res = roundtripSer(a)
    res should === (a)
    a should === (res)
    a.## should === (res.##)
    res
  }

  def checkId[A <: AnyRef](a: A): A = {
    val res = checkSer(a)
    res shouldBe theSameInstanceAs (a)
    res
  }

  def roundtripStr[A](a: A)(implicit A: Atomic[A]): A =
    A.fromString(A.stringRepr(a)).fold(err => fail(err.msg), a => a)

  def roundtripBin[A](a: A)(implicit A: Atomic[A]): A = {
    val (a2, r) = A.fromBinary(A.binaryRepr(a)).fold(err => fail(err.msg), ar => ar)
    r.length should === (0L)
    a2
  }
} 
Example 35
Source File: CachingDamlLedgerStateReaderSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.validator.caching

import com.daml.caching.WeightedCache
import com.daml.ledger.participant.state.kvutils.DamlKvutils.{DamlStateKey, DamlStateValue}
import com.daml.ledger.participant.state.kvutils.caching.`Message Weight`
import com.daml.ledger.validator.{DamlLedgerStateReader, DefaultStateKeySerializationStrategy}
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{AsyncWordSpec, Inside, Matchers}

import scala.concurrent.{ExecutionContext, Future}

class CachingDamlLedgerStateReaderSpec
    extends AsyncWordSpec
    with Matchers
    with Inside
    with MockitoSugar {

  private val keySerializationStrategy = DefaultStateKeySerializationStrategy

  "readState" should {
    "record read keys" in {
      val mockReader = mock[DamlLedgerStateReader]
      when(mockReader.readState(argThat((keys: Seq[DamlStateKey]) => keys.size == 1)))
        .thenReturn(Future.successful(Seq(Some(aDamlStateValue()))))
      val instance = newInstance(mockReader, shouldCache = false)

      instance.readState(Seq(aDamlStateKey)).map { actual =>
        actual should have size 1
        instance.getReadSet should be(
          Set(keySerializationStrategy.serializeStateKey(aDamlStateKey)))
      }
    }

    "update cache upon read if policy allows" in {
      val mockReader = mock[DamlLedgerStateReader]
      when(mockReader.readState(argThat((keys: Seq[DamlStateKey]) => keys.size == 1)))
        .thenReturn(Future.successful(Seq(Some(aDamlStateValue()))))
      val instance = newInstance(mockReader, shouldCache = true)

      instance.readState(Seq(aDamlStateKey)).map { _ =>
        instance.cache.getIfPresent(aDamlStateKey) shouldBe defined
      }
    }

    "do not update cache upon read if policy does not allow" in {
      val mockReader = mock[DamlLedgerStateReader]
      when(mockReader.readState(argThat((keys: Seq[DamlStateKey]) => keys.size == 1)))
        .thenReturn(Future.successful(Seq(Some(aDamlStateValue()))))
      val instance = newInstance(mockReader, shouldCache = false)

      instance.readState(Seq(aDamlStateKey)).map { _ =>
        instance.cache.getIfPresent(aDamlStateKey) should not be defined
      }
    }

    "serve request from cache for seen key (if policy allows)" in {
      val mockReader = mock[DamlLedgerStateReader]
      when(mockReader.readState(any[Seq[DamlStateKey]]())).thenReturn(Future.successful(Seq(None)))
      val instance = newInstance(mockReader, shouldCache = true)

      for {
        originalReadState <- instance.readState(Seq(aDamlStateKey))
        readAgain <- instance.readState(Seq(aDamlStateKey))
      } yield {
        verify(mockReader, times(1)).readState(_)
        readAgain shouldEqual originalReadState
      }
    }
  }

  private lazy val aDamlStateKey = DamlStateKey.newBuilder
    .setContractId("aContractId")
    .build

  private def aDamlStateValue(): DamlStateValue = DamlStateValue.getDefaultInstance

  private def newInstance(damlLedgerStateReader: DamlLedgerStateReader, shouldCache: Boolean)(
      implicit executionContext: ExecutionContext): CachingDamlLedgerStateReader = {
    val cache = WeightedCache.from[DamlStateKey, DamlStateValue](WeightedCache.Configuration(1024))
    new CachingDamlLedgerStateReader(
      cache,
      _ => shouldCache,
      keySerializationStrategy,
      damlLedgerStateReader)
  }
} 
Example 36
Source File: IndexedSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.validator.batch

import org.scalatest.{AsyncWordSpec, Inside, Matchers}
import org.scalatest.mockito.MockitoSugar

import scala.concurrent.Future

class IndexedSpec extends AsyncWordSpec with Matchers with Inside with MockitoSugar {

  "indexed" should {

    "map over value" in {
      val indexed = Indexed(50, 0L)
      val indexed2 = indexed.map(_ + 1)
      indexed2.index should be(0L)
      indexed2.value should be(51)
    }

    "mapFuture over value" in {
      val indexed = Indexed(50, 0L)
      indexed
        .mapFuture(v => Future { v + 1 })
        .map { newIndexed =>
          newIndexed.index should be(0L)
          newIndexed.value should be(51)
        }
    }

    "fromSeq works" in {
      val seq = Seq(1, 2, 3)
      val indexedSeq = Indexed.fromSeq(seq)
      indexedSeq should have size (3)
      seq.zipWithIndex.foreach {
        case (x, i) =>
          indexedSeq(i).value should be(x)
          indexedSeq(i).index should be(i)
      }
      succeed
    }
  }
} 
Example 37
Source File: TemplateSubscriptionSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.extractor

import java.io.File

import com.daml.bazeltools.BazelRunfiles._
import com.daml.lf.data.Ref.Party
import com.daml.extractor.config.{ExtractorConfig, TemplateConfig}
import com.daml.extractor.services.ExtractorFixtureAroundAll
import com.daml.ledger.api.testing.utils.SuiteResourceManagementAroundAll
import com.daml.testing.postgresql.PostgresAroundAll
import org.scalatest.{FlatSpec, Inside, Matchers, Suite}
import scalaz.OneAnd

class TemplateSubscriptionSpec
    extends FlatSpec
    with Suite
    with PostgresAroundAll
    with SuiteResourceManagementAroundAll
    with ExtractorFixtureAroundAll
    with Matchers
    with Inside {

  override protected def darFile = new File(rlocation("extractor/TransactionExample.dar"))

  override def scenario: Option[String] = Some("TransactionExample:templateFilterTest")

  override def configureExtractor(ec: ExtractorConfig): ExtractorConfig = {
    val ec2 = super.configureExtractor(ec)
    ec2.copy(
      parties = OneAnd(Party assertFromString "Bob", Nil),
      templateConfigs = Set(TemplateConfig("TransactionExample", "RightOfUseAgreement")))
  }

  "Transactions" should "be extracted" in {
    getTransactions should have length 1
  }

  "Exercises" should "be extracted" in {
    getExercises should have length 0
  }

  "Contracts" should "be extracted" in {
    inside(getContracts) {
      case List(contract) =>
        contract.template should ===("TransactionExample:RightOfUseAgreement")
    }
  }
} 
Example 38
Source File: MultiPartyTemplateSubscriptionSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.extractor

import java.io.File

import com.daml.bazeltools.BazelRunfiles._
import com.daml.lf.data.Ref.Party
import com.daml.extractor.config.{ExtractorConfig, TemplateConfig}
import com.daml.extractor.services.ExtractorFixtureAroundAll
import com.daml.ledger.api.testing.utils.SuiteResourceManagementAroundAll
import com.daml.testing.postgresql.PostgresAroundAll
import org.scalatest.{FlatSpec, Inside, Matchers, Suite}
import scalaz.OneAnd

class MultiPartyTemplateSubscriptionSpec
    extends FlatSpec
    with Suite
    with PostgresAroundAll
    with SuiteResourceManagementAroundAll
    with ExtractorFixtureAroundAll
    with Matchers
    with Inside {

  override protected def darFile = new File(rlocation("extractor/TransactionExample.dar"))

  override def scenario: Option[String] = Some("TransactionExample:templateFilterTest")

  private final val alice = Party assertFromString "Alice"
  private final val bob = Party assertFromString "Bob"

  override def configureExtractor(ec: ExtractorConfig): ExtractorConfig = {
    val ec2 = super.configureExtractor(ec)
    ec2.copy(
      parties = OneAnd(alice, List(bob)),
      templateConfigs = Set(
        TemplateConfig("TransactionExample", "RightOfUseOffer"),
        TemplateConfig("TransactionExample", "RightOfUseAgreement"))
    )
  }

  "Transactions" should "be extracted" in {
    getTransactions should have length 2
  }

  "Exercises" should "be extracted" in {
    inside(getExercises) {
      case List(e) =>
        e.template should ===("TransactionExample:RightOfUseOffer")
        e.choice should ===("Accept")
    }
  }

  "Contracts" should "be extracted" in {
    inside(getContracts) {
      case List(a1, a2) =>
        a1.template should ===("TransactionExample:RightOfUseOffer")
        a2.template should ===("TransactionExample:RightOfUseAgreement")
    }
  }
} 
Example 39
Source File: EnumSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.extractor

import java.io.File

import com.daml.bazeltools.BazelRunfiles.rlocation
import com.daml.extractor.services.{CustomMatchers, ExtractorFixtureAroundAll}
import com.daml.ledger.api.testing.utils.SuiteResourceManagementAroundAll
import com.daml.testing.postgresql.PostgresAroundAll
import io.circe.parser._
import org.scalatest.{FlatSpec, Inside, Matchers, Suite}
import scalaz.Scalaz._

class EnumSpec
    extends FlatSpec
    with Suite
    with PostgresAroundAll
    with SuiteResourceManagementAroundAll
    with ExtractorFixtureAroundAll
    with Inside
    with Matchers
    with CustomMatchers {

  override protected def darFile = new File(rlocation("daml-lf/encoder/test-1.8.dar"))

  override def scenario: Option[String] = Some("EnumMod:createContracts")

  "Enum" should "be extracted" in {
    getContracts should have length 3
  }

  it should "contain the correct JSON data" in {

    val contractsJson = getContracts.map(_.create_arguments)

    val expected = List(
      """{
      "x" : "Red",
      "party" : "Bob"
      }""",
      """{
      "x" : "Green",
      "party" : "Bob"
      }""",
      """{
      "x" : "Blue",
      "party" : "Bob"
      }"""
    ).traverseU(parse)

    expected should be('right) // That should only fail if this JSON^^ is ill-formatted

    contractsJson should contain theSameElementsAs expected.right.get
  }

} 
Example 40
Source File: TlsTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http

import HttpServiceTestFixture.UseTls
import akka.http.scaladsl.model.{StatusCodes, Uri}
import org.scalatest.{Assertion, AsyncFreeSpec, Inside, Matchers}
import spray.json.{JsArray, JsObject}

import scala.concurrent.Future

@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements"))
class TlsTest
    extends AsyncFreeSpec
    with Matchers
    with Inside
    with AbstractHttpServiceIntegrationTestFuns {

  override def jdbcConfig = None

  override def staticContentConfig = None

  override def useTls = UseTls.Tls

  "connect normally with tls on" in withHttpService { (uri: Uri, _, _) =>
    getRequest(uri = uri.withPath(Uri.Path("/v1/query")))
      .flatMap {
        case (status, output) =>
          status shouldBe StatusCodes.OK
          assertStatus(output, StatusCodes.OK)
          inside(output) {
            case JsObject(fields) =>
              inside(fields.get("result")) {
                case Some(JsArray(vector)) => vector should have size 0L
              }
          }
      }: Future[Assertion]
  }
} 
Example 41
Source File: DarManifestReaderTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.archive

import java.io.{ByteArrayInputStream, InputStream}
import java.nio.charset.Charset

import com.daml.lf.archive.DarManifestReader.DarManifestReaderException
import org.scalatest.{Inside, Matchers, WordSpec}

import scala.util.{Failure, Success}

class DarManifestReaderTest extends WordSpec with Matchers with Inside {

  private val unicode = Charset.forName("UTF-8")

  "should read dalf names from manifest, real scenario with Dalfs line split" in {
    val manifest = """Manifest-Version: 1.0
      |Created-By: Digital Asset packager (DAML-GHC)
      |Main-Dalf: com.daml.lf.archive:DarReaderTest:0.1.dalf
      |Dalfs: com.daml.lf.archive:DarReaderTest:0.1.dalf, daml-pri
      | m.dalf
      |Format: daml-lf
      |Encryption: non-encrypted""".stripMargin

    val inputStream: InputStream = new ByteArrayInputStream(manifest.getBytes(unicode))
    val actual = DarManifestReader.dalfNames(inputStream)

    actual shouldBe Success(
      Dar("com.daml.lf.archive:DarReaderTest:0.1.dalf", List("daml-prim.dalf")))

    inputStream.close()
  }

  "should read dalf names from manifest, Main-Dalf returned in the head" in {
    val manifest = """Main-Dalf: A.dalf
                     |Dalfs: B.dalf, C.dalf, A.dalf, E.dalf
                     |Format: daml-lf
                     |Encryption: non-encrypted""".stripMargin

    val inputStream: InputStream = new ByteArrayInputStream(manifest.getBytes(unicode))
    val actual = DarManifestReader.dalfNames(inputStream)

    actual shouldBe Success(Dar("A.dalf", List("B.dalf", "C.dalf", "E.dalf")))

    inputStream.close()
  }

  "should read dalf names from manifest, can handle one Dalf per manifest" in {
    val manifest = """Main-Dalf: A.dalf
                     |Dalfs: A.dalf
                     |Format: daml-lf
                     |Encryption: non-encrypted""".stripMargin

    val inputStream: InputStream = new ByteArrayInputStream(manifest.getBytes(unicode))
    val actual = DarManifestReader.dalfNames(inputStream)

    actual shouldBe Success(Dar("A.dalf", List.empty))

    inputStream.close()
  }

  "should return failure if Format is not daml-lf" in {
    val manifest = """Main-Dalf: A.dalf
                     |Dalfs: B.dalf, C.dalf, A.dalf, E.dalf
                     |Format: anything-different-from-daml-lf
                     |Encryption: non-encrypted""".stripMargin

    val inputStream: InputStream = new ByteArrayInputStream(manifest.getBytes(unicode))
    val actual = DarManifestReader.dalfNames(inputStream)

    inside(actual) {
      case Failure(DarManifestReaderException(msg)) =>
        msg shouldBe "Unsupported format: anything-different-from-daml-lf"
    }

    inputStream.close()
  }
} 
Example 42
Source File: LawlessTraversalsSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.data

import ImmArray.ImmArraySeq

import org.scalatest.{Inside, Matchers, WordSpec}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

class LawlessTraversalsSpec
    extends WordSpec
    with Matchers
    with Inside
    with GeneratorDrivenPropertyChecks {
  import LawlessTraversals._

  "traverseEitherStrictly" should {
    "satisfy identity, elementwise" in forAll { xs: Seq[Int] =>
      xs traverseEitherStrictly (Right(_)) should ===(Right(xs))
    }

    "preserve class if the implementation bothered to set it up" in {
      val classySeqs = Seq[Seq[Int]](List(1), Vector(2), ImmArraySeq(3))
      // we need to use patmat, not == or shouldBe, because patmat is stricter
      inside(classySeqs map (_ traverseEitherStrictly (Right(_)))) {
        case Seq(_, Right(List(_)), _) => fail("lists are not vectors")
        case Seq(Right(List(1)), Right(Vector(2)), Right(ImmArraySeq(3))) =>
      }
    }
  }
} 
Example 43
Source File: GeneratedCommandsUT.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.codegen

import com.daml.sample.MyMain.SimpleListExample
import com.daml.ledger.api.v1.{commands => rpccmd}
import com.daml.ledger.client.binding.{Primitive => P}

import org.scalatest.{Inside, Matchers, WordSpec}

class GeneratedCommandsUT extends WordSpec with Matchers with Inside {
  private val alice = P.Party("Alice")
  private val contract = SimpleListExample(alice, List(42))

  "create" should {
    "make a create command" in {
      inside(contract.create.command.command) {
        case rpccmd.Command.Command.Create(rpccmd.CreateCommand(_, _)) => ()
      }
    }
  }

  "createAnd" should {
    "make a create-and-exercise command" in {
      inside(contract.createAnd.exerciseGo(alice).command.command) {
        case rpccmd.Command.Command
              .CreateAndExercise(rpccmd.CreateAndExerciseCommand(_, _, _, _)) =>
          ()
      }
    }
  }
} 
Example 44
Source File: NamespaceSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.codegen.types

import org.scalatest.{WordSpec, Matchers, Inside}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

import scalaz.std.anyVal._
import scalaz.std.tuple._
import scalaz.std.vector._
import scalaz.syntax.bifunctor._

class NamespaceSpec extends WordSpec with Matchers with Inside with GeneratorDrivenPropertyChecks {
  "fromHierarchy" should {
    "be lossless for keysets" in forAll { m: Map[List[Int], Int] =>
      NamespaceSpec
        .paths(Namespace.fromHierarchy(m))
        .collect { case (ns, Some(a)) => (ns, a) }
        .toMap shouldBe m
    }
  }
}

object NamespaceSpec {
  import com.daml.codegen.lf.HierarchicalOutput.`scalaz ==>> future`

  def paths[K, A](n: Namespace[K, A]): Vector[(List[K], A)] =
    n.foldTreeStrict[Vector[(List[K], A)]] { (a, kVecs) =>
      kVecs.foldMapWithKey { (k, vec) =>
        vec.map(_ leftMap (k :: _))
      } :+ ((List(), a))
    }
} 
Example 45
Source File: PortFilesSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ports

import java.nio.file.{Path, Paths}
import java.util.UUID

import com.daml.ports.PortFiles.FileAlreadyExists
import org.scalatest.{FreeSpec, Inside, Matchers}
import scalaz.{-\/, \/-}

class PortFilesSpec extends FreeSpec with Matchers with Inside {

  "Can create a port file with a unique file name" in {
    val path = uniquePath()
    inside(PortFiles.write(path, Port(1024))) {
      case \/-(()) =>
    }
    path.toFile.exists() shouldBe true
  }

  "Cannot create a port file with a nonunique file name" in {
    val path = uniquePath()
    inside(PortFiles.write(path, Port(1024))) {
      case \/-(()) =>
    }
    inside(PortFiles.write(path, Port(1024))) {
      case -\/(FileAlreadyExists(p)) =>
        p shouldBe path
    }
  }

  private def uniquePath(): Path = {
    val fileName = s"${this.getClass.getSimpleName}-${UUID.randomUUID().toString}.dummy"
    Paths.get(fileName)
  }
} 
Example 46
Source File: PathGroupTest.scala    From docless   with MIT License 5 votes vote down vote up
package com.timeout.docless.swagger

import org.scalatest.{FreeSpec, Inside, Matchers}
import cats.data.NonEmptyList
import cats.data.Validated
import SchemaError._
import com.timeout.docless.schema.JsonSchema
import com.timeout.docless.schema.JsonSchema._
import com.timeout.docless.swagger.Method._

class PathGroupTest extends FreeSpec with Matchers {
  "PathGroup" - {
    val petstore = PetstoreSchema()
    val pet      = PetstoreSchema.Schemas.pet

    val paths     = Path("/example") :: petstore.paths.get.toList
    val defs      = petstore.definitions.get.toList
    val defsNoPet = defs.filterNot(_.id === pet.id)
    val params    = petstore.parameters.get.toList

    val group1          = PathGroup(paths, defs, params)
    val group2          = PathGroup(List(Path("/extra")), Nil, Nil)
    val groupMissingErr = PathGroup(paths, defsNoPet, params)

    def err(path: String, m: Method, f: Definition => Ref): SchemaError =
      missingDefinition(RefWithContext.response(f(pet.definition), m, path))

    "aggregate" - {
      "when some top level definitions are missing" - {
        "returns the missing refs" in {
          PathGroup.aggregate(petstore.info, List(groupMissingErr)) should ===(
            Validated.invalid[NonEmptyList[SchemaError], APISchema](
              NonEmptyList.of(
                err("/pets", Get, ArrayRef.apply),
                err("/pets", Post, TypeRef.apply),
                err("/pets/{id}", Get, TypeRef.apply),
                err("/pets/{id}", Delete, TypeRef.apply)
              )
            )
          )
        }
      }
      "when some nested definitions are missing" - {
        val info = Info("example")
        case class Nested(name: String)
        case class TopLevel(nested: Nested)

        val schema = JsonSchema.deriveFor[TopLevel]
        val nested = schema.relatedDefinitions.head

        val paths = List(
          "/example".Post(
            Operation('_, "...")
              .withParams(BodyParameter(schema = Some(schema.asRef)))
          )
        )

        val withNested    = PathGroup(paths, schema.definitions.toList, Nil)
        val withoutNested = PathGroup(paths, List(schema.definition), Nil)

        "returns the missing refs" in {
          PathGroup.aggregate(info, List(withNested)).isValid shouldBe true
          PathGroup.aggregate(info, List(withoutNested)) should ===(
            Validated.invalid[NonEmptyList[SchemaError], APISchema](
              NonEmptyList.of(
                MissingDefinition(
                  RefWithContext.definition(nested.asRef, schema.definition)
                )
              )
            )
          )
        }
      }
      "when no definition is missing" - {
        "returns a valid api schema" in new Inside {
          inside(PathGroup.aggregate(petstore.info, List(group1, group2))) {
            case Validated.Valid(schema) =>
              schema.info should ===(petstore.info)
              schema.paths.get should ===(group1.paths ++ group2.paths)
              schema.definitions.get should ===(
                group1.definitions ++ group2.definitions
              )
              schema.parameters.get should ===(group1.params ++ group2.params)
          }
        }
      }
    }
  }
} 
Example 47
Source File: IncompatibleClientSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package com.example.lib

import cats.effect.IO

import org.scalatest.Inside
import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpec

import fs2.{ Stream, Chunk }

import scodec.bits._
import scodec.stream.StreamEncoder

import dev.tauri.seals.scodec.StreamCodecs
import dev.tauri.seals.scodec.StreamCodecs._

import Protocol.v2
import Protocol.v1.Seed

class IncompatibleClientSpec
    extends AnyFlatSpec
    with Matchers
    with Inside
    with TcpTest {

  protected override def ec = scala.concurrent.ExecutionContext.global

  val reqCodec: StreamEncoder[v2.Request] = streamEncoderFromReified[v2.Request]

  override def afterAll(): Unit = {
    super.afterAll()
  }

  "Client with incompatible schema" should "be rejected" ignore { // TODO
    val resp: Either[Throwable, Vector[v2.Response]] = Server.serveAddr(0, sockGroup).flatMap { localAddr =>
      incompatibleClient(localAddr.getPort)
    }.take(1L).compile.toVector.attempt.unsafeRunSync()

    inside(resp) {
      case Left(ex) => ex.getMessage should include ("incompatible models")
    }
  }

  def incompatibleClient(port: Int): Stream[IO, v2.Response] = {
    Stream.resource(sockGroup.client[IO](Server.addr(port))).flatMap { socket =>
      val bvs: Stream[IO, BitVector] = reqCodec.encode[IO](Stream(Seed(42): v2.Request))
      val bs: Stream[IO, Byte] = bvs.flatMap { bv =>
        Stream.chunk(Chunk.bytes(bv.bytes.toArray))
      }
      val read = bs.through(socket.writes(Server.timeout)).drain.onFinalize(socket.endOfOutput) ++
        socket.reads(Server.bufferSize, Server.timeout).chunks.map(ch => BitVector.view(ch.toArray))
      read.through(StreamCodecs.pipe[IO, v2.Response])
    }
  }
} 
Example 48
Source File: AtomicSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package tests

import java.util.UUID

import org.scalatest.Inside
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

import cats.implicits._

import laws.MyUUID
import laws.TestArbInstances.arbUuid
import laws.TestInstances.atomic._
import laws.TestTypes.{ CaseClass, Whatever }

class AtomicSpec extends BaseSpec with ScalaCheckDrivenPropertyChecks with Inside {

  val atomic = Atomic[MyUUID]
  val whatever = Atomic[Whatever.type]

  "Automatic Model derivation" in {
    atomic.description should === ("MyUUID")
    atomic.uuid should === (uuid"85a168db-6ce3-47e7-b8aa-e45aa075d523")
  }

  "equals + hashCode" in {
    checkEqHash(atomic, atomic)
    checkNotEqHash(atomic, whatever)
    checkNotEqHash(atomic, Atomic[String])
  }

  "Serializable" in {
    checkSer(atomic)
    checkSer(whatever)
  }

  "stringRepr/fromString and binaryRepr/fromBinary" in {
    forAll { u: MyUUID =>
      roundtripStr(u)(atomic) should === (u)
      roundtripBin(u)(atomic) should === (u)
    }
  }

  "custom Atomic has higher priority than built-in" in {
    import laws.TestInstances.atomic.bad._
    Model.Atom.atom[Int].uuid should === (laws.TestInstances.atomic.bad.atomicInt.uuid)
  }

  "have higher priority than generic Reified" in {
    // derived instance:
    val r1 = Reified[CaseClass]

    // define an atomic:
    val constUuid = uuid"3ba1f17e-c0cd-4b17-8cca-771e90b60498"
    val r2 = {
      object ACC extends Atomic[CaseClass] with Atomic.FallbackBinary[CaseClass] {

        def description: String = "CaseClass"

        def fromString(s: String): Either[Atomic.Error, CaseClass] = {
          try {
            Either.right(CaseClass(s.toLong))
          } catch {
            case ex: IllegalArgumentException => Either.left(Atomic.Error(ex.getMessage))
          }
        }

        def stringRepr(a: CaseClass): String = a.n.toString

        val uuid: UUID = constUuid
      }

      implicit val atomicCaseClass: Atomic[CaseClass] = ACC

      // now this should take priority over the derived instance:
      Reified[CaseClass]
    }

    r1.model should !== (r2.model)

    inside (r1.model) {
      case _: core.Model.Atom =>
        fail("not expected an Atom")
      case _ =>
        // OK
    }

    inside (r2.model) {
      case a: core.Model.Atom =>
        a.uuid should === (constUuid)
    }
  }
} 
Example 49
Source File: LedgerClientIT.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client

import com.daml.ledger.api.testing.utils.{AkkaBeforeAndAfterAll, SuiteResourceManagementAroundEach}
import com.daml.ledger.client.configuration.{
  CommandClientConfiguration,
  LedgerClientConfiguration,
  LedgerIdRequirement
}
import com.daml.platform.sandboxnext.SandboxNextFixture
import io.grpc.ManagedChannel
import org.scalatest.{AsyncWordSpec, Inside, Matchers}

final class LedgerClientIT
    extends AsyncWordSpec
    with Matchers
    with Inside
    with AkkaBeforeAndAfterAll
    with SuiteResourceManagementAroundEach
    with SandboxNextFixture {
  "the ledger client" should {
    "shut down the channel when closed" in {
      val clientConfig = LedgerClientConfiguration(
        applicationId = classOf[LedgerClientIT].getSimpleName,
        ledgerIdRequirement = LedgerIdRequirement.none,
        commandClient = CommandClientConfiguration.default,
        sslContext = None,
        token = None,
      )

      for {
        client <- LedgerClient(channel, clientConfig)
      } yield {
        inside(channel) {
          case channel: ManagedChannel =>
            channel.isShutdown should be(false)
            channel.isTerminated should be(false)

            client.close()

            channel.isShutdown should be(true)
            channel.isTerminated should be(true)
        }
      }
    }
  }
} 
Example 50
Source File: MapSetMarshallingTest.scala    From ncdbg   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.programmaticallyspeaking.ncd.nashorn.java9

import com.programmaticallyspeaking.ncd.host.{MapNode, SetNode}
import com.programmaticallyspeaking.ncd.nashorn.RealMarshallerTestFixture
import org.scalatest.Inside

class MapSetMarshallingTest extends RealMarshallerTestFixture with Inside with RunningJava9 {

  "Marshalling to MapNode works for" - {
    "Map" in {
      evaluateExpression("new Map([['a',42]])") { (_, actual) =>
        inside(actual) {
          case MapNode(1, false, _) =>
        }
      }
    }

    "WeakMap" in {
      evaluateExpression("new WeakMap([[{},42]])") { (_, actual) =>
        inside(actual) {
          case MapNode(-1, true, _) =>
        }
      }
    }

    "Set" in {
      evaluateExpression("new Set(['a'])") { (_, actual) =>
        inside(actual) {
          case SetNode(1, false, _) =>
        }
      }
    }

    "WeakSet" in {
      evaluateExpression("new WeakSet([{}])") { (_, actual) =>
        inside(actual) {
          case SetNode(-1, true, _) =>
        }
      }
    }
  }
} 
Example 51
Source File: JsonGoogleOptionParserSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.actors

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit._
import edu.neu.coe.csye7200.hedge_fund.model.Model
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.io.Source
import scala.concurrent.duration._
import spray.http._
import spray.http.MediaTypes._
import org.scalatest.Inside
import org.scalatest.tagobjects.Slow

import scala.language.postfixOps
import spray.json.pimpString


class JsonGoogleOptionParserSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("JsonGoogleParserSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  import scala.language.postfixOps
  val json = Source.fromFile(getClass.getResource("/googleOptionExample.json").getPath) mkString

  "json read" in {
    import spray.json._
    val obj = JsonGoogleOptionParser.fix(json).parseJson
  }

  "json conversion" in {
    val contentType = ContentType(MediaTypes.`application/json`, HttpCharsets.`UTF-8`)
    val entity = HttpEntity(contentType, json.getBytes())
    val ok = JsonGoogleOptionParser.decode(entity) match {
      case Right(x) =>
        x.puts.length should equal(20)
        val puts = x.puts
        puts(0).get("s") should matchPattern { case Some("MSFT150731P00042500") => }

      case Left(x) =>
        fail("decoding error: " + x)
    }
  }

  "send back" taggedAs(Slow) in {
    val blackboard = system.actorOf(Props.create(classOf[MockGoogleOptionBlackboard], testActor), "blackboard")
    val entityParser = _system.actorOf(Props.create(classOf[EntityParser], blackboard))
    val contentType = ContentType(MediaTypes.`application/json`, HttpCharsets.`UTF-8`)
    val entity = HttpEntity(contentType, json.getBytes()) 
    entityParser ! EntityMessage("json:GO", entity)
    val msg = expectMsgClass(3.seconds, classOf[QueryResponse])
    println("msg received: " + msg)
    msg should matchPattern {
      case QueryResponse(_, _) =>
    }
  }
}

import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.Await


class MockGoogleOptionUpdateLogger(blackboard: ActorRef) extends UpdateLogger(blackboard) {
  override def processOption(identifier: String, model: Model, attributes: Map[String, Any]) = {
    val keys = model mapKeys (List("underlying", "strikePrice", "expiry"))
    println(s"$keys")
    val future = blackboard ? OptionQuery(identifier, keys)
    val result = Await.result(future, timeout.duration).asInstanceOf[QueryResponse]
    blackboard ! result
  }
}

class MockGoogleOptionBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[MockGoogleOptionUpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => msg match {
        // Cut down on the volume of messages
        case Confirmation("MSFT150731P00045000", _, _) => super.receive(msg)
        case _ =>
      }
      case msg: QueryResponse => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 52
Source File: OptionAnalyzerSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.actors

import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit._

import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import edu.neu.coe.csye7200.hedge_fund.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow


class OptionAnalyzerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("OptionAnalyzerSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "send back" taggedAs(Slow) in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockAnalyzerBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockAnalyzerBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponse => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 53
Source File: JsonYQLParserSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.actors

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit._
import edu.neu.coe.csye7200.hedge_fund.model.Model
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.io.Source
import scala.concurrent.duration._
import spray.http._
import org.scalatest.Inside

import scala.language.postfixOps
import spray.http.ContentType.apply


class JsonYQLParserSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("JsonYQLParserSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  import scala.language.postfixOps
  val json = Source.fromFile(getClass.getResource("/yqlExample.json").getPath) mkString

  "json conversion" in {
    val body = HttpEntity(MediaTypes.`application/json`, json.getBytes())
    val ok = JsonYQLParser.decode(body) match {
      case Right(x) =>
        val count = x.query.count
        count should equal(4)
        x.query.results.quote.length should equal(count)
        x.query.results.get(count - 1, "symbol") should matchPattern { case Some("MSFT") => }

      case Left(x) =>
        fail("decoding error: " + x)
    }
  }

  "send back" in {
    val blackboard = system.actorOf(Props.create(classOf[MockYQLBlackboard], testActor), "blackboard")
    val entityParser = _system.actorOf(Props.create(classOf[EntityParser], blackboard), "entityParser")
    val entity = HttpEntity(MediaTypes.`application/json`, json.getBytes())
    entityParser ! EntityMessage("json:YQL", entity)
    val msg = expectMsgClass(3.seconds, classOf[QueryResponse])
    println("msg received: " + msg)
    msg should matchPattern {
      case QueryResponse("MSFT", _) =>
    }
    inside(msg) {
      case QueryResponse(symbol, attributes) => attributes.get("Ask") should matchPattern { case Some("46.17") => }
    }
  }

}

import akka.pattern.ask
import scala.concurrent.Await

class MockYQLUpdateLogger(blackboard: ActorRef) extends UpdateLogger(blackboard) {
  override def processStock(identifier: String, model: Model) = {
    model.getKey("price") match {
      case Some(p) => {
        // sender is the MarketData actor
        val future = sender ? SymbolQuery(identifier, List(p))
        val result = Await.result(future, timeout.duration).asInstanceOf[QueryResponse]
        result.attributes map {
          case (k, v) =>
            log.info(s"$identifier attribute $k has been updated to: $v")
            blackboard ! result
        }
      }
      case None => log.warning(s"'price' not defined in model")
    }
  }
}

class MockYQLBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[MockYQLUpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => msg match {
        // Cut down on the volume of messages
        case Confirmation("MSFT", _, _) => super.receive(msg)
        case _ =>
      }
      case msg: QueryResponse => testActor forward msg

      case msg => super.receive(msg)
    }
} 
Example 54
Source File: MiniDatabaseSpec2.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.minidatabase2

import org.scalatest.{FlatSpec, Inside, Matchers}

import scala.util._


class MiniDatabaseSpec2 extends FlatSpec with Inside with Matchers {

  "map2" should "succeed for two Success values" in {
    val t1 = Success(1)
    val t2 = Success(2)
    val t3 = MiniDatabase2.map2(t1, t2) { case (x, y) => x + y }
    t3 should matchPattern { case Success(3) => }
  }
  it should "fail if any Failures" in {
    val t0 = Failure[Int](new IllegalArgumentException)
    val t1 = Success(1)
    val t2 = Success(2)
    MiniDatabase2.map2(t0, t2) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t0, t1) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t2, t0) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
  }
  "map3" should "succeed for two Some values" in {
    val t1 = Some(1)
    val t2 = Some(2)
    val t3 = Some(3)
    MiniDatabase2.map3(t1, t2, t3) { case (x, y, z) => x + y + z } should matchPattern { case Some(6) => }
  }
  it should "fail if any None values" in {
    val t1 = Some(1)
    val t2 = None
    val t3 = Some(3)
    MiniDatabase2.map3(t1, t2, t3) { case (x, y, z) => x + y + z } should matchPattern { case None => }
  }
  it should "fail if any Failures" in {
    val t0 = Failure[Int](new IllegalArgumentException)
    val t1 = Success(1)
    val t2 = Success(2)
    MiniDatabase2.map2(t0, t2) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t0, t1) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
    MiniDatabase2.map2(t2, t0) { case (x, y) => x + y } should matchPattern { case Failure(_) => }
  }
  "Height" should "succeed 6 ft 5 in" in {
    Height.parse("6 ft 5 in") should matchPattern { case Success(_) => }
  }
  it should "fail 6 ft five in" in {
    Height.parse("6 ft five in") should matchPattern { case Failure(_) => }
  }
  it should """succeed 6' 5"""" in {
    Height.parse("""6' 5"""") should matchPattern { case Success(_) => }
  }
  it should """fail to parse 6'""" in {
    Height.parse("""6'""") should matchPattern { case Failure(_) => }
  }
  it should "succeed: equal 77 inches and be considered tall" in {
    val height = Height.parse("6 ft 5 in")
    inside(height) {
      case Success(h) => h should matchPattern { case Height(6, 5) => }
    }
    inside(height) {
      case Success(h) => h.inches shouldEqual 77
    }
    inside(height) {
      case Success(h) => MiniDatabase2.measure(h) should be("tall")
    }
  }

  "Name" should "succeed: Tom Brady" in {
    Name.parse("Tom Brady") should matchPattern { case Success(_) => }
  }

  it should """succeed: Thomas E. P. "Tom" Brady""" in {
    Name.parse("""Thomas E. P. "Tom" Brady""") should matchPattern { case Success(_) => }
  }

  "Entry" should """succeed: Thomas E. P. "Tom" Brady, etc.""" in {
    Entry.parse("""Thomas E. P. "Tom" Brady, 078-05-1120, Aug 3rd 1977, 6 ft 4 in, 225""".split(",")) should matchPattern { case Success(_) => }
  }

  it should """fail: Thomas E. P. "Tom" Brady""" in {
    Entry.parse("""Brady, 123-45-6789""".split(",")) should matchPattern { case Failure(_) => }
  }
} 
Example 55
Source File: RenderableSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200

import org.scalatest.{FlatSpec, Inside, Matchers}

import scala.util.Try

case class Scalar(s: String) extends Renderable {
  def render: String = s.toUpperCase()
}


class RenderableSpec extends FlatSpec with Matchers with Inside {
  behavior of "Renderable"
  it should "render simple values like toString" in {
    Scalar("x").render shouldBe "X"
  }
  it should "render list values with indentation" in {
    val list = Seq(Scalar("x"), Scalar("y"), Scalar("z"))
    list.render shouldBe "(\nX,\nY,\nZ\n)"
  }
  it should "render list values with double indentation" in {
    val list = Seq(Seq(Scalar("x0"), Scalar("x1")), Seq(Scalar("y0"), Scalar("y1")), Seq(Scalar("z0"), Scalar("z1")))
    list.render shouldBe "(\n(\nX0,\nX1\n),\n(\nY0,\nY1\n),\n(\nZ0,\nZ1\n)\n)"
  }
  it should "render option values" in {
    val xo = Option(Scalar("x"))
    xo.render shouldBe "Some(X)"
  }
  it should "render try values" in {
    val xy = Try(Scalar("x"))
    xy.render shouldBe "Success(X)"
  }
  it should "render either values" in {
    val e = Left(Scalar("x"))
    e.render shouldBe "Left(X)"
  }
} 
Example 56
Source File: ProfilerTest.scala    From ncdbg   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.programmaticallyspeaking.ncd.chrome.domains

import com.programmaticallyspeaking.ncd.host.{ProfilingData, Sample, SampleType}
import com.programmaticallyspeaking.ncd.testing.UnitTest
import org.mockito.Mockito._
import org.scalatest.Inside

import scala.concurrent.duration._

class ProfilerTest extends UnitTest with DomainActorTesting with ProfilerTesting with Inside {

  "Profiler" - {
    "setSamplingInterval" - {
      "should be accepted" in {
        val profiler = newActorInstance[Profiler]
        requestAndReceiveResponse(profiler, "1", Domain.enable)
        val r = requestAndReceiveResponse(profiler, "2", Profiler.setSamplingInterval(1000))
        r should be (Accepted)
      }
    }

    "start" - {
      "should use the sampling interval in calling the host" in {
        val profiler = newActorInstance[Profiler]
        requestAndReceiveResponse(profiler, "1", Domain.enable)
        requestAndReceiveResponse(profiler, "2", Profiler.setSamplingInterval(1500))
        requestAndReceiveResponse(profiler, "3", Profiler.start)

        verify(currentScriptHost).startProfiling(1500.micros)
      }

      "should reject profile start without sampling interval" in {
        val profiler = newActorInstance[Profiler]
        requestAndReceiveResponse(profiler, "1", Domain.enable)
        val ex = intercept[ResponseException](requestAndReceiveResponse(profiler, "2", Profiler.start))
        ex.getMessage should include ("Sampling interval")
      }

      "should support changing the sampling interval" in {
        val profiler = newActorInstance[Profiler]
        requestAndReceiveResponse(profiler, "1", Domain.enable)
        requestAndReceiveResponse(profiler, "2", Profiler.setSamplingInterval(1500))
        requestAndReceiveResponse(profiler, "3", Profiler.setSamplingInterval(500))
        requestAndReceiveResponse(profiler, "4", Profiler.start)

        verify(currentScriptHost).startProfiling(500.micros)
      }
    }

    "stop" - {
      val stackFrame = createStackFrame("a", "file:///some/script.js", "myFun", 1, 1)
      val sample = Sample(2000L, Seq(stackFrame), SampleType.Script)
      val input = ProfilingData(Seq(sample), 1000, 5000)

      "should use the sampling interval in calling the host" in {
        when(currentScriptHost.stopProfiling()).thenReturn(input)

        val profiler = newActorInstance[Profiler]
        requestAndReceiveResponse(profiler, "1", Domain.enable)
        requestAndReceiveResponse(profiler, "2", Profiler.setSamplingInterval(1500))
        requestAndReceiveResponse(profiler, "3", Profiler.start)
        val response = requestAndReceiveResponse(profiler, "4", Profiler.stop)

        inside(response) {
          case Profiler.ProfileResult(profile) =>
            profile.samples should have size (1)
        }
      }

    }
  }
} 
Example 57
Source File: TaskRepositoryOnRDBSpec.scala    From ddd-on-scala   with MIT License 5 votes vote down vote up
package crossroad0201.dddonscala.infrastructure.task

import crossroad0201.dddonscala.adapter.infrastructure.rdb.ScalikeJdbcSessionHolder
import crossroad0201.dddonscala.adapter.infrastructure.rdb.task.TaskRepositoryOnRDB
import crossroad0201.dddonscala.domain.UnitOfWork
import crossroad0201.dddonscala.domain.task._
import crossroad0201.dddonscala.domain.user.UserId
import org.scalatest.{BeforeAndAfterAll, GivenWhenThen, Inside, Matchers}
import org.scalatest.fixture.WordSpec
import scalikejdbc.scalatest.AutoRollback
import scalikejdbc._
import scalikejdbc.config.DBs

import scala.util.{Failure, Success}

class TaskRepositoryOnRDBSpec
    extends WordSpec
    with GivenWhenThen
    with Matchers
    with Inside
    with BeforeAndAfterAll
    with AutoRollback {

  override protected def beforeAll() = DBs.setupAll

  override protected def afterAll() = DBs.closeAll

  override def fixture(implicit session: DBSession) {
    sql"""INSERT INTO tasks VALUES ('TESTTASK001', 'テストタスク1', 'OPENED', 'USER001', NULL, 1)""".update.apply

    sql"""INSERT INTO tasks VALUES ('TESTTASK002', 'テストタスク2', 'CLOSED', 'USER001', 'USER002', 1)""".update.apply
    sql"""INSERT INTO task_comments VALUES (1, 'TESTTASK002', 'ひとつめのコメント', 'USER001')""".update.apply
    sql"""INSERT INTO task_comments VALUES (2, 'TESTTASK002', 'ふたつめのコメント', 'USER002')""".update.apply
  }

  "get" when {
    "タスクが存在する" should {
      "タスクが返される" in { implicit dbs =>
        new WithFixture {
          Given("存在するタスクID")
          val taskId = "TESTTASK002"

          Then("タスクを取得する")
          val actual = get(TaskId(taskId))
          println(s"Actual: $actual")

          When("タスクが返される")
          inside(actual) {
            case (Success(Some(aTask))) =>
              aTask.id should be(TaskId("TESTTASK002"))
              aTask.name should be(TaskName("テストタスク2"))
              aTask.state should be(TaskState.Closed)
              aTask.authorId should be(UserId("USER001"))
              aTask.assignment should be(Assigned(UserId("USER002")))
          }
        }
      }
    }
  }

  trait WithFixture extends TaskRepositoryOnRDB {
    implicit def dbSessionAsUnitOfWork(implicit dbs: DBSession): UnitOfWork =
      new UnitOfWork with ScalikeJdbcSessionHolder {
        override val dbSession = dbs
      }
  }

} 
Example 58
Source File: TemplateLiteralTest.scala    From ncdbg   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.programmaticallyspeaking.ncd.nashorn.java9

import com.programmaticallyspeaking.ncd.host.SimpleValue
import com.programmaticallyspeaking.ncd.nashorn.RealMarshallerTestFixture
import org.scalatest.Inside

class TemplateLiteralTest extends RealMarshallerTestFixture with RunningJava9 with Inside {
  "Marshalling of template literals" - {

    "works for a plain one" in {
      evaluateExpression("`foo`") { (_, actual) =>
        actual should be (SimpleValue("foo"))
      }
    }

    "works for one with an embedded string" in {
      evaluateExpression("(function (x) { return `foo${x}`; })(42)") { (_, actual) =>
        actual should be (SimpleValue("foo42"))
      }
    }

    "works for a multiline lstring" in {
      evaluateExpression("`foo\nbar`") { (_, actual) =>
        actual should be (SimpleValue("foo\nbar"))
      }
    }
  }
} 
Example 59
Source File: SymbolMarshallingTest.scala    From ncdbg   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.programmaticallyspeaking.ncd.nashorn.java9

import com.programmaticallyspeaking.ncd.host.SymbolNode
import com.programmaticallyspeaking.ncd.nashorn.RealMarshallerTestFixture
import org.scalatest.Inside

class SymbolMarshallingTest extends RealMarshallerTestFixture with Inside with RunningJava9 {

  "Marshalling to ValueNode works for" - {
    "local Symbol" in {
      evaluateExpression("Symbol('foo')") { (_, actual) =>
        inside(actual) {
          case SymbolNode(desc, _) => desc should be ("Symbol(foo)")
        }
      }
    }

    "global Symbol" in {
      evaluateExpression("Symbol.for('foo')") { (_, actual) =>
        inside(actual) {
          case SymbolNode(desc, _) => desc should be ("Symbol(foo)")
        }
      }
    }

  }
} 
Example 60
Source File: ConfigReaderFailureOriginSuite.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.{ ConfigFactory, ConfigValueType }
import org.scalatest.{ EitherValues, Inside }
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig.error._
import pureconfig.generic.auto._


class ConfigReaderFailureOriginSuite extends BaseSuite with EitherValues with Inside {
  "Loading configuration from files" should "show proper error locations when loading a single file" in {
    import pureconfig.syntax._
    case class Conf(a: Int, b: String, c: Int)

    val workingDir = getClass.getResource("/").getFile
    val file = "conf/configFailureOrigin/single/a.conf"
    val conf = ConfigFactory.load(file).root()

    inside(conf.get("conf").to[Conf].left.value.toList) {
      case List(
        ConvertFailure(
          KeyNotFound("a", _),
          Some(origin1),
          ""),
        ConvertFailure(
          WrongType(ConfigValueType.STRING, valueTypes),
          Some(origin2),
          "c")
        ) =>
        origin1.filename() should endWith(file)
        origin1.url() shouldBe new URL("file", "", workingDir + file)
        origin1.lineNumber() shouldBe 1

        origin2.filename() should endWith(file)
        origin2.url() shouldBe new URL("file", "", workingDir + file)
        origin2.lineNumber() shouldBe 3
        valueTypes should contain only ConfigValueType.NUMBER

    }

    inside(conf.get("other-conf").to[Conf].left.value.toList) {
      case List(
        ConvertFailure(
          KeyNotFound("a", _),
          Some(origin1),
          ""),
        ConvertFailure(
          KeyNotFound("b", _),
          Some(origin2),
          ""),
        ConvertFailure(
          WrongType(ConfigValueType.STRING, valueTypes2),
          Some(origin3),
          "c")
        ) =>
        origin1.filename() should endWith(file)
        origin1.url shouldBe new URL("file", "", workingDir + file)
        origin1.lineNumber shouldBe 7

        origin2.filename() should endWith(file)
        origin2.url shouldBe new URL("file", "", workingDir + file)
        origin2.lineNumber shouldBe 7

        origin3.filename() should endWith(file)
        origin3.url shouldBe new URL("file", "", workingDir + file)
        origin3.lineNumber shouldBe 9
        valueTypes2 should contain only ConfigValueType.NUMBER
    }
  }

  it should "show proper error location when loading from multiple files" in {
    import pureconfig.syntax._
    case class Conf(a: Int, b: String, c: Int)

    val workingDir = getClass.getResource("/").getFile
    val file1 = "conf/configFailureOrigin/multiple/a.conf"
    val file2 = "conf/configFailureOrigin/multiple/b.conf"
    val conf = ConfigFactory.load(file1).withFallback(ConfigFactory.load(file2)).root()

    inside(conf.get("conf").to[Conf].left.value.toList) {
      case List(ConvertFailure(
        WrongType(ConfigValueType.STRING, valueTypes),
        Some(origin),
        "a")) =>
        valueTypes should contain only ConfigValueType.NUMBER
        origin.url() shouldBe new URL("file", "", workingDir + file2)
        origin.lineNumber() shouldBe 2

    }
  }
} 
Example 61
Source File: TopologicalSortSpec.scala    From algorithmaday   with GNU General Public License v3.0 5 votes vote down vote up
package org.pfcoperez.dailyalgorithm.applications

import org.scalatest.{ FlatSpec, Matchers, Inside }

class TopologicalSortSpec extends FlatSpec with Matchers with Inside {
  import TopologicalSort._

  "TopologicalSort algorithm implementation" should "order elements by their dependency tree" in {

    val dm: DependencyMatrix[Char] = Map(
      'A' -> Set('E'),
      'B' -> Set('F'),
      'C' -> Set('G'),
      'D' -> Set('G'),
      'E' -> Set('H'),
      'F' -> Set('H', 'I'),
      'G' -> Set('I'),
      'H' -> Set('J'),
      'I' -> Set('H'),
      'J' -> Set())

    inside(topologicalSort(dm)) {
      case Some(order) =>
        val node2index = order.zipWithIndex.toMap

        node2index('J') shouldBe 0
        node2index('H') shouldBe 1
        node2index('E') should be < node2index('A')
        node2index('F') should be < node2index('B')
        node2index('I') should be < node2index('G')
        node2index('G') should be < node2index('C')
        node2index('G') should be < node2index('D')

    }

  }

  it should "fail to create an order when there are cyclic dependencies" in {

    val dm: DependencyMatrix[Char] = Map(
      'A' -> Set('B'),
      'B' -> Set('C'),
      'C' -> Set('A'))

    topologicalSort(dm) shouldBe empty

  }

  it should "serve to make a plan to develop interstellar travel" in {

    val technologicalDependencies: DependencyMatrix[String] = Map(
      "Interstellar Travel" -> Set("Safe cabins", "Warp drive"),
      "Quantum computing" -> Set(),
      "Magnetic shields" -> Set("Quantum computing"),
      "Dark matter confinement" -> Set("Quantum computing"),
      "Safe cabins" -> Set("Magnetic shields"),
      "Warp drive" -> Set("Dark matter confinement"))

    inside(topologicalSort(technologicalDependencies)) {
      case Some(plan) =>

        plan.head shouldBe "Quantum computing"
        plan.last shouldBe "Interstellar Travel"

        val planIndexes: Map[String, Int] = plan.zipWithIndex.toMap

        planIndexes("Dark matter confinement") should be < planIndexes("Warp drive")
        planIndexes("Magnetic shields") should be < planIndexes("Safe cabins")

    }

  }

} 
Example 62
Source File: ScriptManagerTest.scala    From codepropertygraph   with Apache License 2.0 5 votes vote down vote up
package io.shiftleft.console.scripting

import better.files.File
import cats.effect.IO
import org.scalatest.{Inside, Matchers, WordSpec}

import io.shiftleft.codepropertygraph.Cpg
import io.shiftleft.console.scripting.ScriptManager.{ScriptCollections, ScriptDescription, ScriptDescriptions}

import java.nio.file.{FileSystemNotFoundException, NoSuchFileException, Path}

import scala.io.Source
import scala.util.Try

class ScriptManagerTest extends WordSpec with Matchers with Inside {

  private object TestScriptExecutor extends AmmoniteExecutor {
    override protected def predef: String = ""
    override def runScript(scriptPath: Path, parameters: Map[String, String], cpg: Cpg): IO[Any] = IO.fromTry(
      Try {
        val source = Source.fromFile(scriptPath.toFile)
        val result = source.getLines.mkString(System.lineSeparator())
        source.close()
        result
      }
    )
  }

  private object TestScriptManager extends ScriptManager(TestScriptExecutor)

  protected val DEFAULT_CPG_NAME: String = {
    if (File(".").name == "console") {
      (File("..") / "resources" / "testcode" / "cpgs" / "method" / "cpg.bin.zip").pathAsString
    } else {
      (File("resources") / "testcode" / "cpgs" / "method" / "cpg.bin.zip").pathAsString
    }
  }

  def withScriptManager(f: ScriptManager => Unit): Unit = {
    f(TestScriptManager)
  }

  "listing scripts" should {
    "be correct" in withScriptManager { scriptManager =>
      val scripts = scriptManager.scripts()
      val expected = List(
        ScriptCollections("general",
                          ScriptDescriptions(
                            "A collection of general purpose scripts.",
                            List(ScriptDescription("list-funcs.sc", "Lists all functions."))
                          )),
        ScriptCollections("java",
                          ScriptDescriptions(
                            "A collection of java-specific scripts.",
                            List(ScriptDescription("list-sl-ns.sc", "Lists all shiftleft namespaces."))
                          )),
        ScriptCollections("general/general_plus",
                          ScriptDescriptions(
                            "Even more general purpose scripts.",
                            List.empty
                          ))
      )

      scripts should contain theSameElementsAs expected
    }
  }

  "running scripts" should {
    "be correct when explicitly specifying a CPG" in withScriptManager { scriptManager =>
      val expected =
        """|@main def main() = {
           |  cpg.method.name.l
           |}""".stripMargin

      scriptManager.runScript("general/list-funcs.sc", Map.empty, Cpg.emptyCpg) shouldBe expected
    }

    "be correct when specifying a CPG filename" in withScriptManager { scriptManager =>
      val expected =
        """|@main def main() = {
           |  cpg.method.name.l
           |}""".stripMargin

      scriptManager.runScript("general/list-funcs.sc", Map.empty, DEFAULT_CPG_NAME) shouldBe expected
    }

    "throw an exception if the specified CPG can not be found" in withScriptManager { scriptManager =>
      intercept[FileSystemNotFoundException] {
        scriptManager.runScript("general/list-funcs.sc", Map.empty, "cake.bin.zip")
      }
    }

    "throw an exception if the specified script can not be found" in withScriptManager { scriptManager =>
      intercept[NoSuchFileException] {
        scriptManager.runScript("list-funcs.sc", Map.empty, Cpg.emptyCpg)
      }
    }
  }

} 
Example 63
Source File: ScalaSupportSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.api

import org.scalatest.Inside
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class ScalaSupportSpec extends AnyWordSpec with Matchers with Inside {
  "scala support" should {
    "resolve a function" in {
      val method: ScalaServiceSupport.ScalaMethodCall[String] = testMethod _
      method.method.getDeclaringClass should ===(this.getClass)
      method.method.getName should ===("testMethod")
    }
  }

  def testMethod(s: String): String = s
} 
Example 64
Source File: ServiceSupport.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.it

import java.util.Collections
import java.util.function.{ Function => JFunction }

import akka.stream.Materializer
import akka.stream.scaladsl.Source
import org.scalatest.Inside
import play.api.Application
import play.api.Configuration
import play.api.Environment
import play.inject.guice.GuiceApplicationBuilder

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.reflect.ClassTag
import akka.japi.function.Procedure
import com.google.inject.Binder
import com.google.inject.Module
import com.google.inject.TypeLiteral
import com.lightbend.lagom.javadsl.testkit.ServiceTest
import com.lightbend.lagom.javadsl.testkit.ServiceTest.TestServer
import play.api.routing.Router
import java.util

import com.lightbend.lagom.internal.testkit.EmptyAdditionalRoutersModule
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

sealed trait HttpBackend {
  final val provider: String = s"play.core.server.${codeName}ServerProvider"
  val codeName: String
}

case object AkkaHttp extends HttpBackend {
  val codeName = "AkkaHttp"
}

case object Netty extends HttpBackend {
  val codeName = "Netty"
}

trait ServiceSupport extends AnyWordSpecLike with Matchers with Inside {
  def withServer(
      configureBuilder: GuiceApplicationBuilder => GuiceApplicationBuilder
  )(block: Application => Unit)(implicit httpBackend: HttpBackend): Unit = {
    val jConfigureBuilder = new JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder] {
      override def apply(b: GuiceApplicationBuilder): GuiceApplicationBuilder = {
        configureBuilder(b)
          .overrides(EmptyAdditionalRoutersModule)
          .configure("play.server.provider", httpBackend.provider)
      }
    }
    val jBlock = new Procedure[TestServer] {
      override def apply(server: TestServer): Unit = {
        block(server.app.asScala())
      }
    }
    val setup = ServiceTest.defaultSetup.configureBuilder(jConfigureBuilder).withCluster(false)
    ServiceTest.withServer(setup, jBlock)
  }

  def withClient[T: ClassTag](
      configureBuilder: GuiceApplicationBuilder => GuiceApplicationBuilder
  )(block: Application => T => Unit)(implicit httpBackend: HttpBackend): Unit = {
    withServer(configureBuilder) { application =>
      val client = application.injector.instanceOf[T]
      block(application)(client)
    }
  }

  implicit def materializer(implicit app: Application): Materializer = app.materializer

  def consume[T](source: Source[T, _])(implicit mat: Materializer): List[T] = {
    Await.result(source.runFold(List.empty[T])((list, t) => t :: list), 10.seconds).reverse
  }
} 
Example 65
Source File: ResponseFormatsTest.scala    From daml   with Apache License 2.0 4 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.http.json

import com.daml.http.util.Collections._

import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.stream.scaladsl.Source
import akka.util.ByteString
import org.scalacheck.Gen
import org.scalatest.compatible.Assertion
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FreeSpec, Inside, Matchers}
import scalaz.syntax.show._
import scalaz.{Show, \/}
import spray.json._

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}

class ResponseFormatsTest
    extends FreeSpec
    with Matchers
    with Inside
    with GeneratorDrivenPropertyChecks {

  implicit val asys: ActorSystem = ActorSystem(this.getClass.getSimpleName)
  implicit val mat: Materializer = Materializer(asys)
  implicit val ec: ExecutionContext = asys.dispatcher

  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 100)

  "resultJsObject should serialize Source of Errors and JsValues" in forAll(
    Gen.listOf(errorOrJsNumber),
    Gen.option(Gen.nonEmptyListOf(Gen.identifier))) { (input, warnings) =>
    import spray.json.DefaultJsonProtocol._

    val jsValWarnings: Option[JsValue] = warnings.map(_.toJson)
    val (failures, successes): (Vector[JsString], Vector[JsValue]) =
      input.toVector.partitionMap(_.leftMap(e => JsString(e.shows)))

    val jsValSource = Source[DummyError \/ JsValue](input)

    val responseF: Future[ByteString] =
      ResponseFormats
        .resultJsObject(jsValSource, jsValWarnings)
        .runFold(ByteString.empty)((b, a) => b ++ a)

    val resultF: Future[Assertion] = responseF.map { str =>
      JsonParser(str.utf8String) shouldBe expectedResult(failures, successes, jsValWarnings)
    }

    Await.result(resultF, 10.seconds)
  }

  private def expectedResult(
      failures: Vector[JsValue],
      successes: Vector[JsValue],
      warnings: Option[JsValue]): JsObject = {

    val map1: Map[String, JsValue] = warnings match {
      case Some(x) => Map("warnings" -> x)
      case None => Map.empty
    }

    val map2 =
      if (failures.isEmpty)
        Map[String, JsValue]("result" -> JsArray(successes), "status" -> JsNumber("200"))
      else
        Map[String, JsValue](
          "result" -> JsArray(successes),
          "errors" -> JsArray(failures),
          "status" -> JsNumber("501"))

    JsObject(map1 ++ map2)
  }

  private lazy val errorOrJsNumber: Gen[DummyError \/ JsNumber] = Gen.frequency(
    1 -> dummyErrorGen.map(\/.left),
    5 -> jsNumberGen.map(\/.right)
  )

  private lazy val dummyErrorGen: Gen[DummyError] = Gen.identifier.map(DummyError.apply)

  private lazy val jsNumberGen: Gen[JsNumber] = Gen.posNum[Long].map(JsNumber.apply)
}

final case class DummyError(message: String)

object DummyError {
  implicit val ShowInstance: Show[DummyError] = Show shows { e =>
    s"DummyError(${e.message})"
  }
} 
Example 66
Source File: ConfigParserSpec.scala    From daml   with Apache License 2.0 4 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.extractor.config

import com.daml.extractor.config.Generators._
import com.daml.extractor.targets.Target
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FlatSpec, Inside, Matchers}
import scalaz.OneAnd
import scalaz.Scalaz._
import scalaz.scalacheck.ScalazArbitrary._

class ConfigParserSpec
    extends FlatSpec
    with Matchers
    with Inside
    with GeneratorDrivenPropertyChecks {

  behavior of ConfigParser.getClass.getSimpleName

  val requiredArgs = Vector("--party", "Bob")

  it should "parse template configuration" in forAll {
    templateConfigs: OneAnd[List, TemplateConfig] =>
      val args = requiredArgs ++ Vector("--templates", templateConfigUserInput(templateConfigs))
      inside(ConfigParser.parse(args)) {
        case Some((config, _)) =>
          config.templateConfigs should ===(templateConfigs.toSet)
      }
  }

  it should "fail parsing when duplicate template configurations" in forAll {
    templateConfigs: OneAnd[List, TemplateConfig] =>
      val duplicate = templateConfigs.head

      val args = requiredArgs ++ Vector(
        "--templates",
        templateConfigUserInput(duplicate :: templateConfigs.toList))

      // scopt prints errors into STD Error stream
      val capturedStdErr = new java.io.ByteArrayOutputStream()
      val result: Option[(ExtractorConfig, Target)] = Console.withErr(capturedStdErr) {
        ConfigParser.parse(args)
      }
      capturedStdErr.flush()
      capturedStdErr.close()
      result should ===(None)
      val firstLine = capturedStdErr.toString.replaceAllLiterally("\r", "").split('\n')(0)
      firstLine should ===("Error: The list of templates must contain unique elements")
  }
}