org.scalactic.TypeCheckedTripleEquals Scala Examples

The following examples show how to use org.scalactic.TypeCheckedTripleEquals. 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: PostSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.home.scaladsl.persistence

//#unit-test
import scala.concurrent.Await
import scala.concurrent.duration._
import akka.Done
import akka.actor.ActorSystem
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.InvalidCommandException
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.lightbend.lagom.scaladsl.testkit.PersistentEntityTestDriver
import com.typesafe.config.ConfigFactory
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.BeforeAndAfterAll
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class PostSpec extends AnyWordSpecLike with Matchers with BeforeAndAfterAll with TypeCheckedTripleEquals {
  val system = ActorSystem("PostSpec", JsonSerializerRegistry.actorSystemSetupFor(BlogPostSerializerRegistry))

  override def afterAll(): Unit = {
    Await.ready(system.terminate, 10.seconds)
  }

  "Blog Post entity" must {
    "handle AddPost" in {
      val driver  = new PersistentEntityTestDriver(system, new Post, "post-1")
      val content = PostContent("Title", "Body")
      val outcome = driver.run(AddPost(content))
      outcome.events should ===(List(PostAdded("post-1", content)))
      outcome.state.published should ===(false)
      outcome.state.content should ===(Some(content))
      outcome.replies should ===(List(AddPostDone("post-1")))
      outcome.issues should be(Nil)
    }

    "validate title" in {
      val driver  = new PersistentEntityTestDriver(system, new Post, "post-1")
      val outcome = driver.run(AddPost(PostContent("", "Body")))
      outcome.replies.head.getClass should be(classOf[InvalidCommandException])
      outcome.events.size should ===(0)
      outcome.issues should be(Nil)
    }

    "handle ChangeBody" in {
      val driver = new PersistentEntityTestDriver(system, new Post, "post-1")
      driver.run(AddPost(PostContent("Title", "Body")))

      val outcome = driver.run(ChangeBody("New body 1"), ChangeBody("New body 2"))
      outcome.events should ===(List(BodyChanged("post-1", "New body 1"), BodyChanged("post-1", "New body 2")))
      outcome.state.published should ===(false)
      outcome.state.content.get.body should ===("New body 2")
      outcome.replies should ===(List(Done, Done))
      outcome.issues should be(Nil)
    }
  }
}
//#unit-test 
Example 2
Source File: EnforceAfterVersionRuleSpec.scala    From sbt-git-versioning   with MIT License 5 votes vote down vote up
package com.rallyhealth.sbt.semver.level.rule

import com.rallyhealth.sbt.semver.TestSnapshotVersion
import com.rallyhealth.sbt.versioning.SemVerReleaseType.Major
import com.rallyhealth.sbt.versioning.{ReleaseVersion, SemVerReleaseType, SemanticVersion}
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{Matchers, WordSpec}

class EnforceAfterVersionRuleSpec
  extends WordSpec
  with Matchers
  with TypeCheckedTripleEquals {

  case class Scenario(enforceAfter: Option[ReleaseVersion], majorAllowed: Seq[SemanticVersion] = Nil, noOpinion: Seq[SemanticVersion] = Nil)

  val scenarios = Seq(
    Scenario(
      enforceAfter = None,
      noOpinion = Seq(
        ReleaseVersion(0, 0, 0),
        ReleaseVersion(0, 0, 1),
        ReleaseVersion(0, 1, 1),
        ReleaseVersion(1, 0, 0),
        ReleaseVersion(1, 1, 1),
        TestSnapshotVersion(0, 0, 0),
        TestSnapshotVersion(0, 1, 1),
        TestSnapshotVersion(1, 0, 0),
        TestSnapshotVersion(1, 1, 1)
      )
    ),
    Scenario(
      enforceAfter = Some(ReleaseVersion(1, 0, 0)),
      majorAllowed = Seq(
        ReleaseVersion(0, 0, 0),
        ReleaseVersion(0, 0, 1),
        ReleaseVersion(0, 1, 1),
        ReleaseVersion(1, 0, 0),
        TestSnapshotVersion(0, 0, 0),
        TestSnapshotVersion(0, 1, 1),
        TestSnapshotVersion(1, 0, 0)
      ),
      noOpinion = Seq(
        ReleaseVersion(1, 1, 1),
        TestSnapshotVersion(1, 1, 1)
      )
    )
  )

  "maybeEnforceAfterVersion" when {

    for (Scenario(maybeEnforceAfter, majorAllowed, noOpinion) <- scenarios) {
      maybeEnforceAfter.toString should {

        def calcRelaseType(ver: SemanticVersion): Option[SemVerReleaseType] = {
          val maybeLevel = EnforceAfterVersionRule(ver, maybeEnforceAfter).calcLevel()
          maybeLevel.map(_.releaseType)
        }

        for (ver <- majorAllowed) {
          s"allow major changes for $ver" in {
            assert(calcRelaseType(ver) === Some(Major))
          }
        }

        for (ver <- noOpinion) {
          s"not have an opinion about $ver" in {
            assert(calcRelaseType(ver) === None)
          }
        }
      }
    }
  }
} 
Example 3
Source File: VersionDiffRuleSpec.scala    From sbt-git-versioning   with MIT License 5 votes vote down vote up
package com.rallyhealth.sbt.semver.level.rule

import com.rallyhealth.sbt.semver.TestSnapshotVersion
import com.rallyhealth.sbt.versioning.SemVerReleaseType.{Major, Minor, Patch}
import com.rallyhealth.sbt.versioning.{ReleaseVersion, SemVerReleaseType, SemanticVersion}
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{Matchers, WordSpec}

class VersionDiffRuleSpec
  extends WordSpec
  with Matchers
  with TypeCheckedTripleEquals {

  val releaseVersions = Seq(
    ReleaseVersion(0, 0, 0),
    ReleaseVersion(0, 0, 1),
    ReleaseVersion(0, 1, 1),
    ReleaseVersion(1, 0, 0),
    ReleaseVersion(1, 1, 1)
  )

  case class Scenario(
    prevRelease: Option[ReleaseVersion],
    shouldAllowForVersions: Map[SemVerReleaseType, Seq[SemanticVersion]]
  )

  val scenarios = Seq(
    Scenario(
      prevRelease = None,
      shouldAllowForVersions = Map(
        Major -> Seq(
          ReleaseVersion(0, 0, 0),
          ReleaseVersion(0, 0, 1),
          ReleaseVersion(0, 1, 1),
          ReleaseVersion(1, 0, 0),
          ReleaseVersion(1, 1, 1),
          TestSnapshotVersion(0, 0, 0),
          TestSnapshotVersion(0, 1, 1),
          TestSnapshotVersion(1, 0, 0),
          TestSnapshotVersion(1, 1, 1)
        )
      )
    ),
    Scenario(
      prevRelease = Some(ReleaseVersion(0, 0, 0)),
      shouldAllowForVersions = Map(
        Patch -> Seq(
          ReleaseVersion(0, 0, 1),
          ReleaseVersion(0, 0, 2)
        ),
        Minor -> Seq(
          ReleaseVersion(0, 1, 0),
          ReleaseVersion(0, 1, 1),
          TestSnapshotVersion(0, 0, 1), // because snapshots
          TestSnapshotVersion(0, 0, 2), // because snapshots
          TestSnapshotVersion(0, 1, 0),
          TestSnapshotVersion(0, 1, 1)
        ),
        Major -> Seq(
          ReleaseVersion(1, 0, 0),
          ReleaseVersion(1, 1, 1),
          TestSnapshotVersion(1, 0, 0),
          TestSnapshotVersion(1, 1, 1)
        )
      )
    )
  )

  for (scn <- scenarios) {
    s"prevRelease: ${scn.prevRelease}" should {
      for ((expected, versions) <- scn.shouldAllowForVersions) {
        s"allow $expected" when {
          for (ver <- versions) {
            s"current version: $ver" in {
              val maybeReleaseType = VersionDiffRule(ver, scn.prevRelease).calcLevel().map(_.releaseType)
              assert(maybeReleaseType === Some(expected))
            }
          }
        }
      }
    }
  }
} 
Example 4
Source File: InitialDevelopmentRuleSpec.scala    From sbt-git-versioning   with MIT License 5 votes vote down vote up
package com.rallyhealth.sbt.semver.level.rule

import com.rallyhealth.sbt.semver.TestSnapshotVersion
import com.rallyhealth.sbt.versioning.ReleaseVersion
import com.rallyhealth.sbt.versioning.SemVerReleaseType.Major
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{LoneElement, Matchers, WordSpec}

class InitialDevelopmentRuleSpec
  extends WordSpec
  with Matchers
  with LoneElement
  with TypeCheckedTripleEquals {

  val scenarios = Seq(
    ReleaseVersion(0, 0, 0) -> Some(Major),
    ReleaseVersion(0, 0, 1) -> Some(Major),
    ReleaseVersion(0, 1, 1) -> Some(Major),
    ReleaseVersion(1, 0, 0) -> None,
    ReleaseVersion(1, 1, 1) -> None,
    TestSnapshotVersion(0, 0, 0) -> Some(Major),
    TestSnapshotVersion(0, 1, 1) -> Some(Major),
    TestSnapshotVersion(1, 0, 0) -> None,
    TestSnapshotVersion(1, 1, 1) -> None
  )

  for ((version, expected) <- scenarios) {
    s"conclude ${version} is $expected" in {
      val maybeLevel = InitialDevelopmentRule(version).calcLevel()
      val maybeReleaseType = maybeLevel.map(_.releaseType)

      assert(maybeReleaseType === expected)
    }
  }
} 
Example 5
Source File: SemVerReleaseTypeSpec.scala    From sbt-git-versioning   with MIT License 5 votes vote down vote up
package com.rallyhealth.sbt.versioning

import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{Matchers, WordSpec}

class SemVerReleaseTypeSpec
  extends WordSpec
  with Matchers
  with TypeCheckedTripleEquals {

  "Major > Minor > Patch" in {
    assert(SemVerReleaseType.Major === SemVerReleaseType.Major)
    assert(SemVerReleaseType.Major > SemVerReleaseType.Minor)
    assert(SemVerReleaseType.Major > SemVerReleaseType.Patch)

    assert(SemVerReleaseType.Minor < SemVerReleaseType.Major)
    assert(SemVerReleaseType.Minor === SemVerReleaseType.Minor)
    assert(SemVerReleaseType.Minor > SemVerReleaseType.Patch)

    assert(SemVerReleaseType.Patch < SemVerReleaseType.Major)
    assert(SemVerReleaseType.Patch < SemVerReleaseType.Minor)
    assert(SemVerReleaseType.Patch === SemVerReleaseType.Patch)
  }

} 
Example 6
Source File: ReleaseableSemanticVersionSpec.scala    From sbt-git-versioning   with MIT License 5 votes vote down vote up
package com.rallyhealth.sbt.versioning

import com.rallyhealth.sbt.versioning.SemVerReleaseType.{Major, Minor, Patch, ReleaseableSemanticVersion}
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{FunSpec, Matchers}

class ReleaseableSemanticVersionSpec
  extends FunSpec
  with Matchers
  with TypeCheckedTripleEquals {

  private val testCases = Seq(
    TestCase(
      name = "Clean snapshots should be bumped, for everything but patch",
      version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false, "0123abc", 1),
      expectedReleases = Seq(
        Patch -> ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false),
        Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = false),
        Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = false)
      )
    ),
    TestCase(
      name = "Dirty snapshots should stay dirty",
      version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = true, "0123abc", 1),
      expectedReleases = Seq(
        Patch -> ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = true),
        Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = true),
        Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = true)
      )
    ),
    TestCase(
      name = "Snapshot identifiers should be stripped",
      version = SnapshotVersion(1, 2, 3, Seq("identifier"), isDirty = true, "0123abc", 1),
      expectedReleases = Seq(
        Patch -> ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = true),
        Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = true),
        Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = true)
      )
    ),
    TestCase(
      name = "Release versions should be bumped",
      version = ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false),
      expectedReleases = Seq(
        Patch -> ReleaseVersion(1, 2, 4, SemVerIdentifierList.empty, isDirty = false),
        Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = false),
        Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = false)
      )
    ),
    TestCase(
      name = "Release identifiers should be stripped",
      version = ReleaseVersion(1, 2, 3, Seq("identifier"), isDirty = false),
      expectedReleases = Seq(
        Patch -> ReleaseVersion(1, 2, 4, SemVerIdentifierList.empty, isDirty = false),
        Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = false),
        Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = false)
      )
    )
  )

  for (tc <- testCases) {
    describe(s"${tc.name} for ${tc.version.toString}") {
      for ((releaseType, expected) <- tc.expectedReleases) {
        it(s"$releaseType -> $expected") {
          val actual = tc.version.release(releaseType)
          assert(actual === expected)
        }
      }
    }
  }
}

case class TestCase(
  name: String,
  version: SemanticVersion,
  expectedReleases: Seq[(SemVerReleaseType, SemanticVersion)]
) 
Example 7
Source File: ConsulOpTests.scala    From helm   with Apache License 2.0 5 votes vote down vote up
package helm

import argonaut._, Argonaut._
import cats.effect.IO
import org.scalatest.{FlatSpec, Matchers}
import org.scalactic.TypeCheckedTripleEquals
import ConsulOp._

class ConsulOpTests extends FlatSpec with Matchers with TypeCheckedTripleEquals {
  val I = Interpreter.prepare[ConsulOp, IO]

  "getJson" should "return none right when get returns None" in {
    val interp = for {
      _ <- I.expectU[QueryResponse[Option[Array[Byte]]]] {
        case ConsulOp.KVGetRaw("foo", None, None) => IO.pure(QueryResponse(None, -1, true, -1))
      }
    } yield ()
    interp.run(kvGetJson[Json]("foo", None, None)).unsafeRunSync should equal(Right(QueryResponse(None, -1, true, -1)))
  }

  it should "return a value when get returns a decodeable value" in {
    val interp = for {
      _ <- I.expectU[QueryResponse[Option[Array[Byte]]]] {
        case ConsulOp.KVGetRaw("foo", None, None) => IO.pure(QueryResponse(Some("42".getBytes), -1, true, -1))
      }
    } yield ()
    interp.run(kvGetJson[Json]("foo", None, None)).unsafeRunSync should equal(Right(QueryResponse(Some(jNumber(42)), -1, true, -1)))
  }

  it should "return an error when get returns a non-decodeable value" in {
    val interp = for {
      _ <- I.expectU[QueryResponse[Option[Array[Byte]]]] {
        case ConsulOp.KVGetRaw("foo", None, None) => IO.pure(QueryResponse(Some("{".getBytes), -1, true, -1))
      }
    } yield ()
    interp.run(kvGetJson[Json]("foo", None, None)).unsafeRunSync should equal(Left("JSON terminates unexpectedly."))
  }
} 
Example 8
Source File: SimpleTransformationSpec.scala    From xml-lens   with MIT License 5 votes vote down vote up
package pl.msitko.xml.bench

import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{FlatSpec, Matchers}

class SimpleTransformationSpec extends FlatSpec with Matchers with TypeCheckedTripleEquals {
  import SimpleTransformation._

  "SimpleTransformation" should "work" in {
    val withLens = transformWith(SimpleTransformationLens)
    val withStd  = transformWith(SimpleTransformationStd).replace('\'', '"')

    withLens should === (example.output)
    withLens should === (withStd)
  }

  def transformWith(transformer: => SimpleTransformation): String = {
    transformer.transform(example.input)
  }
} 
Example 9
Source File: ActorSystemSpec.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.persistence

import akka.actor.ActorSystem
import akka.actor.setup.ActorSystemSetup
import akka.event.{ Logging, LoggingAdapter }
import akka.testkit.{ ImplicitSender, TestKit }
import com.typesafe.config.{ Config, ConfigFactory }
import org.scalactic.{ CanEqual, TypeCheckedTripleEquals }
import org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpecLike }

object ActorSystemSpec {
  def getCallerName(clazz: Class[_]): String = {
    val s = (Thread.currentThread.getStackTrace map (_.getClassName) drop 1)
      .dropWhile(_ matches "(java.lang.Thread|.*ActorSystemSpec.?$)")
    val reduced = s.lastIndexWhere(_ == clazz.getName) match {
      case -1 ⇒ s
      case z ⇒ s drop (z + 1)
    }
    reduced.head.replaceFirst(""".*\.""", "").replaceAll("[^a-zA-Z_0-9]", "_")
  }

}

abstract class ActorSystemSpec(system: ActorSystem) extends TestKit(system)
  with WordSpecLike with Matchers with BeforeAndAfterAll with TypeCheckedTripleEquals
  with ImplicitSender {

  def this(testName: String, config: Config) =
    this(ActorSystem(testName, config))

  def this(config: Config) = this(ActorSystemSpec.getCallerName(getClass), config)

  def this(setup: ActorSystemSetup) = this(ActorSystem(ActorSystemSpec.getCallerName(getClass), setup))

  def this() = this(ConfigFactory.empty())

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

  val log: LoggingAdapter = Logging(system, this.getClass)

  // for ScalaTest === compare of Class objects
  implicit def classEqualityConstraint[A, B]: CanEqual[Class[A], Class[B]] =
    new CanEqual[Class[A], Class[B]] {
      def areEqual(a: Class[A], b: Class[B]) = a == b
    }

} 
Example 10
Source File: ClusterMessageSerializerSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.cluster

import akka.actor.ActorSystem
import akka.actor.ExtendedActorSystem
import akka.testkit.ImplicitSender
import akka.testkit.TestKit
import com.lightbend.lagom.internal.cluster.ClusterDistribution.EnsureActive
import com.lightbend.lagom.internal.cluster.protobuf.msg.ClusterMessages.{ EnsureActive => ProtobufEnsureActive }
import com.typesafe.config.ConfigFactory
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.BeforeAndAfterAll
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

object ClusterMessageSerializerSpec {
  def actorSystem(): ActorSystem = {
    val config = ConfigFactory.defaultReference()
    ActorSystem(classOf[ClusterMessageSerializerSpec].getSimpleName, config)
  }
}

class ClusterMessageSerializerSpec
    extends TestKit(ClusterMessageSerializerSpec.actorSystem())
    with AnyWordSpecLike
    with Matchers
    with BeforeAndAfterAll
    with TypeCheckedTripleEquals
    with ImplicitSender {
  val clusterMessageSerializer = new ClusterMessageSerializer(system.asInstanceOf[ExtendedActorSystem])

  "ClusterMessageSerializer" must {
    "serialize EnsureActive" in {
      val ensureActive = EnsureActive("entity-1")
      val bytes        = clusterMessageSerializer.toBinary(ensureActive)
      ProtobufEnsureActive.parseFrom(bytes).getEntityId should be("entity-1")
    }

    "deserialize EnsureActive" in {
      val bytes        = ProtobufEnsureActive.newBuilder().setEntityId("entity-2").build().toByteArray
      val ensureActive = clusterMessageSerializer.fromBinary(bytes, "E").asInstanceOf[EnsureActive]
      ensureActive.entityId should be("entity-2")
    }

    "fail to serialize other types" in {
      assertThrows[IllegalArgumentException] {
        clusterMessageSerializer.toBinary("Strings are not supported")
      }
    }

    "fail to deserialize with the wrong manifest" in {
      assertThrows[IllegalArgumentException] {
        val bytes = ProtobufEnsureActive.newBuilder().setEntityId("entity-2").build().toByteArray
        clusterMessageSerializer.fromBinary(bytes, "WRONG-MANIFEST")
      }
    }
  }

  protected override def afterAll(): Unit = {
    shutdown()
    super.afterAll()
  }
} 
Example 11
Source File: ActorSystemSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.persistence

import java.lang.reflect.Modifier

import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import akka.actor.setup.ActorSystemSetup
import akka.event.Logging
import akka.event.LoggingAdapter
import akka.testkit.ImplicitSender
import akka.testkit.TestKit
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.scalactic.CanEqual
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.BeforeAndAfterAll
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

object ActorSystemSpec {
  // taken from akka-testkit's AkkaSpec
  private def testNameFromCallStack(classToStartFrom: Class[_]): String = {

    def isAbstractClass(className: String): Boolean = {
      try {
        Modifier.isAbstract(Class.forName(className).getModifiers)
      } catch {
        case _: Throwable => false // yes catch everything, best effort check
      }
    }

    val startFrom = classToStartFrom.getName
    val filteredStack = Thread.currentThread.getStackTrace.iterator
      .map(_.getClassName)
      // drop until we find the first occurrence of classToStartFrom
      .dropWhile(!_.startsWith(startFrom))
      // then continue to the next entry after classToStartFrom that makes sense
      .dropWhile {
        case `startFrom`                            => true
        case str if str.startsWith(startFrom + "$") => true // lambdas inside startFrom etc
        case str if isAbstractClass(str)            => true
        case _                                      => false
      }

    if (filteredStack.isEmpty)
      throw new IllegalArgumentException(s"Couldn't find [${classToStartFrom.getName}] in call stack")

    // sanitize for actor system name
    scrubActorSystemName(filteredStack.next())
  }

  // taken from akka-testkit's AkkaSpec
  
  private def scrubActorSystemName(name: String): String = {
    name
      .replaceFirst("""^.*\.""", "")  // drop package name
      .replaceAll("""\$\$?\w+""", "") // drop scala anonymous functions/classes
      .replaceAll("[^a-zA-Z_0-9]", "_")
  }
}

abstract class ActorSystemSpec(actorSystemFactory: () => ActorSystem)
    extends TestKit(actorSystemFactory())
    with AnyWordSpecLike
    with Matchers
    with BeforeAndAfterAll
    with TypeCheckedTripleEquals
    with ImplicitSender {

  def this(testName: String, config: Config) =
    this(() => ActorSystem(testName, config))

  def this(config: Config) = this(ActorSystemSpec.testNameFromCallStack(classOf[ActorSystemSpec]), config)

  def this(setup: ActorSystemSetup) =
    this(() => ActorSystem(ActorSystemSpec.testNameFromCallStack(classOf[ActorSystemSpec]), setup))

  def this() = this(ConfigFactory.empty())

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

  val log: LoggingAdapter                      = Logging(system, this.getClass)
  val coordinatedShutdown: CoordinatedShutdown = CoordinatedShutdown(system)

  // for ScalaTest === compare of Class objects
  implicit def classEqualityConstraint[A, B]: CanEqual[Class[A], Class[B]] =
    new CanEqual[Class[A], Class[B]] {
      def areEqual(a: Class[A], b: Class[B]) = a == b
    }
} 
Example 12
Source File: ActorServiceSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package docs.home.actor

import com.lightbend.lagom.docs.ServiceSupport
import scala.concurrent.duration._
import akka.actor.ActorSystem
import akka.testkit.ImplicitSender
import akka.testkit.TestKit
import com.typesafe.config.ConfigFactory
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.BeforeAndAfterAll
import akka.cluster.Cluster
import java.util.concurrent.TimeUnit

object ActorServiceSpec {
  def config = ConfigFactory.parseString("""
    akka.actor.provider = cluster
    akka.remote.artery.canonical.port = 0
    akka.remote.artery.canonical.hostname = 127.0.0.1
    """)
}

class ActorServiceSpec
    extends TestKit(ActorSystem("ActorServiceSpec", ActorServiceSpec.config))
    with ServiceSupport
    with BeforeAndAfterAll
    with TypeCheckedTripleEquals
    with ImplicitSender {
  val workerRoleConfig = ConfigFactory.parseString("akka.cluster.roles = [worker-node]")
  val node2            = ActorSystem("ActorServiceSpec", workerRoleConfig.withFallback(system.settings.config))
  val node3            = ActorSystem("ActorServiceSpec", workerRoleConfig.withFallback(system.settings.config))

  override def beforeAll {
    Cluster(system).join(Cluster(system).selfAddress)
    Cluster(node2).join(Cluster(system).selfAddress)
    Cluster(node3).join(Cluster(system).selfAddress)
    node2.actorOf(Worker.props(), "worker");
    node3.actorOf(Worker.props(), "worker");
    within(15.seconds) {
      awaitAssert {
        Cluster(system).state.members.size should ===(3)
      }
    }
  }

  override def afterAll {
    shutdown()
    shutdown(node2)
    shutdown(node3)
  }

  "Integration with actors" must {
    "work with for example clustered consistent hashing" in withServiceInstance[WorkerService](
      new WorkerServiceImpl(system)
    ).apply { app => client =>
      {
        val job = Job.of("123", "compute", "abc")

        // might take a while until cluster is formed and router knows about the nodes
        within(15.seconds) {
          awaitAssert {
            client.doWork().invoke(job).toCompletableFuture.get(3, TimeUnit.SECONDS) should ===(JobAccepted.of("123"))
          }
        }
      }
    }
  }
} 
Example 13
Source File: StreamingProducerSpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package coinyser

import java.sql.Timestamp

import coinyser.StreamingProducerSpec._
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{Matchers, WordSpec}

class StreamingProducerSpec extends WordSpec with Matchers with TypeCheckedTripleEquals {

  "StreamingProducer.deserializeWebsocketTransaction" should {
    "deserialize a valid String to a WebsocketTransaction" in {
      val str =
        """{"amount": 0.045318270000000001, "buy_order_id": 1969499130,
          |"sell_order_id": 1969495276, "amount_str": "0.04531827",
          |"price_str": "6339.73", "timestamp": "1533797395",
          |"price": 6339.7299999999996, "type": 0, "id": 71826763}""".stripMargin
      StreamingProducer.deserializeWebsocketTransaction(str) should
        ===(SampleWebsocketTransaction)
    }
  }

  "StreamingProducer.convertWsTransaction" should {
    "convert a WebSocketTransaction to a Transaction" in {
      StreamingProducer.convertWsTransaction(SampleWebsocketTransaction) should
        ===(SampleTransaction)
    }
  }

  "StreamingProducer.serializeTransaction" should {
    "serialize a Transaction to a String" in {
      StreamingProducer.serializeTransaction(SampleTransaction) should
        ===(SampleJsonTransaction)
    }
  }

  "StreamingProducer.subscribe" should {
    "register a callback that receives live trades" in {
      val pusher = new FakePusher(Vector("a", "b", "c"))
      var receivedTrades = Vector.empty[String]
      val io = StreamingProducer.subscribe(pusher) { trade => receivedTrades = receivedTrades :+ trade }
      io.unsafeRunSync()
      receivedTrades should ===(Vector("a", "b", "c"))
    }
  }
}

object StreamingProducerSpec {
  val SampleWebsocketTransaction = WebsocketTransaction(
    amount = 0.04531827, buy_order_id = 1969499130, sell_order_id = 1969495276,
    amount_str = "0.04531827", price_str = "6339.73", timestamp = "1533797395",
    price = 6339.73, `type` = 0, id = 71826763)

  val SampleTransaction = Transaction(
    timestamp = new Timestamp(1533797395000L), tid = 71826763,
    price = 6339.73, sell = false, amount = 0.04531827)

  val SampleJsonTransaction =
    """{"timestamp":"2018-08-09 06:49:55",
      |"date":"2018-08-09","tid":71826763,"price":6339.73,"sell":false,
      |"amount":0.04531827}""".stripMargin

} 
Example 14
Source File: Spec.scala    From drunk   with Apache License 2.0 5 votes vote down vote up
package com.github.jarlakxen.drunk

import org.scalactic.TypeCheckedTripleEquals
import org.scalatest._
import org.scalatest.concurrent.{Futures, ScalaFutures}
import org.scalatest.time._
import org.slf4j.LoggerFactory

trait Spec
    extends FlatSpec
    with Matchers
    with OptionValues
    with Inside
    with Retries
    with TryValues
    with Inspectors
    with TypeCheckedTripleEquals
    with Futures
    with ScalaFutures
    with RecoverMethods { self =>

  val log = LoggerFactory.getLogger(this.getClass)

  implicit val defaultPatience = PatienceConfig(timeout = Span(5, Seconds), interval = Span(5, Millis))

} 
Example 15
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 16
Source File: UUIDMacroSpec.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package macros

import java.util.UUID

import shapeless.test.{ typed, illTyped }

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalactic.TypeCheckedTripleEquals

class UUIDMacroSpec extends AnyFlatSpec with Matchers with TypeCheckedTripleEquals {

  def uuid: Nothing = sys.error("this should never be invoked")

  "UUID literal macro" should "work" in {
    val x = uuid"3a108ce3-9284-4883-a72c-71ced1f30e4c"
    typed[UUID] { x }
    x.variant should === (2)
    x.version should === (4)
    x should === (UUID.fromString("3a108ce3-9284-4883-a72c-71ced1f30e4c"))
  }

  it should "reject non-RFC-4122 UUIDs" in {
    val str = "00000000-0000-0001-0000-000000000002"
    val u = UUID.fromString(str)
    u.variant should !== (2)
    illTyped(
      """uuid"00000000-0000-0001-0000-000000000002"""",
      ".*not an RFC-4122 UUID.*"
    )
  }

  it should "reject syntactically invalid strings" in {
    illTyped(
      """uuid"abcd"""",
      ".*not a valid UUID.*"
    )
  }

  it should "only accept string literals" in {
    illTyped(
      """
        val v: String = "3a108ce3-9284-4883-a72c-71ced1f30e4c"
        StringContext(v).uuid()
      """,
      ".*not a string literal.*"
    )
  }
} 
Example 17
Source File: RetCalcSpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package retcalc

import org.scalactic.{Equality, TolerantNumerics, TypeCheckedTripleEquals}
import org.scalatest.{Matchers, WordSpec}

class RetCalcSpec extends WordSpec with Matchers with TypeCheckedTripleEquals {

  implicit val doubleEquality: Equality[Double] = TolerantNumerics.tolerantDoubleEquality(0.0001)

  "RetCalc.futureCapital" should {
    "calculate the amount of savings I will have in n months" in {
      // Excel =-FV(0.04/12,25*12,1000,10000,0)
      val actual = RetCalc.futureCapital(FixedReturns(0.04), nbOfMonths = 25 * 12,
        netIncome = 3000, currentExpenses = 2000, initialCapital = 10000)
      val expected = 541267.1990
      actual should ===(expected)
    }

    "calculate how much savings will be left after having taken a pension for n months" in {
      val actual = RetCalc.futureCapital(FixedReturns(0.04), nbOfMonths = 40 * 12,
        netIncome = 0, currentExpenses = 2000, initialCapital = 541267.198962)
      val expected = 309867.5316
      actual should ===(expected)
    }
  }

  val params = RetCalcParams(
    nbOfMonthsInRetirement = 40 * 12,
    netIncome = 3000,
    currentExpenses = 2000,
    initialCapital = 10000)

  "RetCalc.simulatePlan" should {
    "calculate the capital at retirement and the capital after death" in {
      val (capitalAtRetirement, capitalAfterDeath) = RetCalc.simulatePlan(
        returns = FixedReturns(0.04), params, nbOfMonthsSavings = 25 * 12)

      capitalAtRetirement should ===(541267.1990)
      capitalAfterDeath should ===(309867.5316)
    }

    "use different returns for capitalisation and drawdown" in {
      val nbOfMonthsSavings = 25 * 12
      val returns = VariableReturns(
        Vector.tabulate(nbOfMonthsSavings + params.nbOfMonthsInRetirement)(i =>
          if (i < nbOfMonthsSavings)
            VariableReturn(i.toString, 0.04 / 12)
          else
            VariableReturn(i.toString, 0.03 / 12)))
      val (capitalAtRetirement, capitalAfterDeath) =
        RetCalc.simulatePlan(returns, params, nbOfMonthsSavings)
      // Excel: =-FV(0.04/12, 25*12, 1000, 10000)
      capitalAtRetirement should ===(541267.1990)
      // Excel: =-FV(0.03/12, 40*12, -2000, 541267.20)
      capitalAfterDeath should ===(-57737.7227)
    }

  }


  "RetCalc.nbOfMonthsSaving" should {
    "calculate how long I need to save before I can retire" in {
      val actual = RetCalc.nbOfMonthsSaving(params, FixedReturns(0.04))
      val expected = 23 * 12 + 1
      actual should ===(expected)
    }

    "not crash if the resulting nbOfMonths is very high" in {
      val actual = RetCalc.nbOfMonthsSaving(
        params = RetCalcParams(
          nbOfMonthsInRetirement = 40 * 12,
          netIncome = 3000, currentExpenses = 2999, initialCapital = 0),
        returns = FixedReturns(0.01))
      val expected = 8280
      actual should ===(expected)
    }

    "not loop forever if I enter bad parameters" in {
      val actual = RetCalc.nbOfMonthsSaving(params.copy(netIncome = 1000), FixedReturns(0.04))
      actual should ===(Int.MaxValue)
    }
  }
} 
Example 18
Source File: ReturnsSpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package retcalc

import org.scalactic.{Equality, TolerantNumerics, TypeCheckedTripleEquals}
import org.scalatest.{Matchers, WordSpec}

class ReturnsSpec extends WordSpec with Matchers with TypeCheckedTripleEquals {

  implicit val doubleEquality: Equality[Double] =
    TolerantNumerics.tolerantDoubleEquality(0.0001)

  "Returns.monthlyReturn" should {
    "return a fixed rate for a FixedReturn" in {
      Returns.monthlyRate(FixedReturns(0.04), 0) should ===(0.04 / 12)
      Returns.monthlyRate(FixedReturns(0.04), 10) should ===(0.04 / 12)
    }

    val variableReturns = VariableReturns(
      Vector(VariableReturn("2000.01", 0.1), VariableReturn("2000.02", 0.2)))
    "return the nth rate for VariableReturn" in {
      Returns.monthlyRate(variableReturns, 0) should ===(0.1)
      Returns.monthlyRate(variableReturns, 1) should ===(0.2)
    }

    "roll over from the first rate if n > length" in {
      Returns.monthlyRate(variableReturns, 2) should ===(0.1)
      Returns.monthlyRate(variableReturns, 3) should ===(0.2)
      Returns.monthlyRate(variableReturns, 4) should ===(0.1)
    }

    "return the n+offset th rate for OffsetReturn" in {
      val returns = OffsetReturns(variableReturns, 1)
      Returns.monthlyRate(returns, 0) should ===(0.2)
      Returns.monthlyRate(returns, 1) should ===(0.1)
    }
  }


  "Returns.fromEquityAndInflationData" should {
    "compute real total returns from equity and inflation data" in {
      val equities = Vector(
        EquityData("2117.01", 100.0, 10.0),
        EquityData("2117.02", 101.0, 12.0),
        EquityData("2117.03", 102.0, 12.0))

      val inflations = Vector(
        InflationData("2117.01", 100.0),
        InflationData("2117.02", 102.0),
        InflationData("2117.03", 102.0))

      val returns = Returns.fromEquityAndInflationData(equities, inflations)
      returns should ===(VariableReturns(Vector(
        VariableReturn("2117.02", (101.0 + 12.0 / 12) / 100.0 - 102.0 / 100.0),
        VariableReturn("2117.03", (102.0 + 12.0 / 12) / 101.0 - 102.0 / 102.0))))
    }
  }

  "VariableReturns.fromUntil" should {
    "keep only a window of the returns" in {
      val variableReturns = VariableReturns(Vector.tabulate(12) { i =>
        val d = (i + 1).toDouble
        VariableReturn(f"2017.$d%02.0f", d)
      })

      variableReturns.fromUntil("2017.07", "2017.09").returns should ===(Vector(
        VariableReturn("2017.07", 7.0),
        VariableReturn("2017.08", 8.0)
      ))

      variableReturns.fromUntil("2017.10", "2018.01").returns should ===(Vector(
        VariableReturn("2017.10", 10.0),
        VariableReturn("2017.11", 11.0),
        VariableReturn("2017.12", 12.0)
      ))
    }
  }

  "Returns.annualizedTotalReturn" should {
    val returns = VariableReturns(Vector.tabulate(12)(i => VariableReturn(i.toString, i.toDouble / 100 / 12)))
    val avg = Returns.annualizedTotalReturn(returns)
    "compute a geometric mean of the returns" in {
      // Excel: GEOMEAN (see geomean.ods)
      avg should ===(0.0549505735)
    }

    "compute an average that can be used to calculate a futureCapital instead of using variable returns" in {
      // This calculation only works if the capital does not change over time
      // otherwise, the capital fluctuates as well as the interest rates, and we cannot use the mean
      val futCapVar = RetCalc.futureCapital(returns, 12, 0, 0, 500000)
      val futCapFix = RetCalc.futureCapital(FixedReturns(avg), 12, 0, 0, 500000)
      futCapVar should ===(futCapFix)
    }
  }

} 
Example 19
Source File: SimulatePlanAppIT.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package retcalc

import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{Matchers, WordSpec}

class SimulatePlanAppIT extends WordSpec with Matchers with TypeCheckedTripleEquals {
  "SimulatePlanApp.strMain" should {
    "simulate a retirement plan using market returns" in {
      val actualResult = SimulatePlanApp.strMain(
        Array("1952.09,2017.09", "25", "40", "3000", "2000", "10000"))

      val expectedResult =
        s"""
           |Capital after 25 years of savings:    468925
           |Capital after 40 years in retirement: 2958842
        """.stripMargin
      actualResult should === (expectedResult)
    }
  }
} 
Example 20
Source File: RetCalcIT.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package retcalc

import org.scalactic.{Equality, TolerantNumerics, TypeCheckedTripleEquals}
import org.scalatest.{Matchers, WordSpec}

class RetCalcIT extends WordSpec with Matchers with TypeCheckedTripleEquals {
  implicit val doubleEquality: Equality[Double] = TolerantNumerics.tolerantDoubleEquality(0.0001)

  val params = RetCalcParams(
    nbOfMonthsInRetirement = 40 * 12,
    netIncome = 3000,
    currentExpenses = 2000,
    initialCapital = 10000)


  "simulate a retirement plan with real market data" in {
    val returns = Returns.fromEquityAndInflationData(
      equities = EquityData.fromResource("sp500.tsv"),
      inflations = InflationData.fromResource("cpi.tsv")).fromUntil("1952.09", "2017.10")

    val (capitalAtRetirement, capitalAfterDeath) =
      RetCalc.simulatePlan(returns, params = params, nbOfMonthsSavings = 25 * 12)
    capitalAtRetirement should ===(468924.5522)
    capitalAfterDeath should ===(2958841.7675)
  }
} 
Example 21
Source File: ReturnsSpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package retcalc

import org.scalactic.{Equality, TolerantNumerics, TypeCheckedTripleEquals}
import org.scalatest.{EitherValues, Matchers, WordSpec}

class ReturnsSpec extends WordSpec with Matchers with TypeCheckedTripleEquals with EitherValues {

  implicit val doubleEquality: Equality[Double] =
    TolerantNumerics.tolerantDoubleEquality(0.0001)

  "Returns.monthlyReturn" should {
    "return a fixed rate for a FixedReturn" in {
      Returns.monthlyRate(FixedReturns(0.04), 0).right.value should ===(0.04 / 12)
      Returns.monthlyRate(FixedReturns(0.04), 10).right.value should ===(0.04 / 12)
    }

    val variableReturns = VariableReturns(Vector(
      VariableReturn("2000.01", 0.1),
      VariableReturn("2000.02", 0.2)))

    "return the nth rate for VariableReturn" in {
      Returns.monthlyRate(variableReturns, 0).right.value should ===(0.1)
      Returns.monthlyRate(variableReturns, 1).right.value should ===(0.2)
    }

    "return an error if n > length" in {
      Returns.monthlyRate(variableReturns, 2).left.value should ===(
        RetCalcError.ReturnMonthOutOfBounds(2, 1))
      Returns.monthlyRate(variableReturns, 3).left.value should ===(
        RetCalcError.ReturnMonthOutOfBounds(3, 1))
    }

    "return the n+offset th rate for OffsetReturn" in {
      val returns = OffsetReturns(variableReturns, 1)
      Returns.monthlyRate(returns, 0).right.value should ===(0.2)
    }
  }


  "Returns.fromEquityAndInflationData" should {
    "compute real total returns from equity and inflation data" in {
      val equities = Vector(
        EquityData("2117.01", 100.0, 10.0),
        EquityData("2117.02", 101.0, 12.0),
        EquityData("2117.03", 102.0, 12.0))

      val inflations = Vector(
        InflationData("2117.01", 100.0),
        InflationData("2117.02", 102.0),
        InflationData("2117.03", 102.0))

      val returns = Returns.fromEquityAndInflationData(equities, inflations)
      returns should ===(VariableReturns(Vector(
        VariableReturn("2117.02", (101.0 + 12.0 / 12) / 100.0 - 102.0 / 100.0),
        VariableReturn("2117.03", (102.0 + 12.0 / 12) / 101.0 - 102.0 / 102.0))))
    }
  }

  "VariableReturns.fromUntil" should {
    "keep only a window of the returns" in {
      val variableReturns = VariableReturns(Vector.tabulate(12) { i =>
        val d = (i + 1).toDouble
        VariableReturn(f"2017.$d%02.0f", d)
      })

      variableReturns.fromUntil("2017.07", "2017.09").returns should ===(Vector(
        VariableReturn("2017.07", 7.0),
        VariableReturn("2017.08", 8.0)
      ))

      variableReturns.fromUntil("2017.10", "2018.01").returns should ===(Vector(
        VariableReturn("2017.10", 10.0),
        VariableReturn("2017.11", 11.0),
        VariableReturn("2017.12", 12.0)
      ))
    }
  }

  "Returns.annualizedTotalReturn" should {
    val returns = VariableReturns(Vector.tabulate(12)(i => VariableReturn(i.toString, i.toDouble / 100 / 12)))
    val avg = Returns.annualizedTotalReturn(returns)
    "compute a geometric mean of the returns" in {
      // Excel: GEOMEAN (see geomean.ods)
      avg should ===(0.0549505735)
    }

    "compute an average that can be used to calculate a futureCapital instead of using variable returns" in {
      // This calculation only works if the capital does not change over time
      // otherwise, the capital fluctuates as well as the interest rates, and we cannot use the mean
      val futCapVar = RetCalc.futureCapital(returns, 12, 0, 0, 500000).right.value
      val futCapFix = RetCalc.futureCapital(FixedReturns(avg), 12, 0, 0, 500000).right.value
      futCapVar should ===(futCapFix)
    }
  }

} 
Example 22
Source File: SimulatePlanAppIT.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package retcalc

import cats.data.Validated.{Invalid, Valid}
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.{Matchers, WordSpec}

class SimulatePlanAppIT extends WordSpec with Matchers with TypeCheckedTripleEquals {
  "SimulatePlanApp.strMain" should {
    "simulate a retirement plan using market returns" in {
      val actualResult = SimulatePlanApp.strMain(
        Array("1952.09,2017.09", "25", "40", "3000", "2000", "10000"))

      val expectedResult =
        s"""
           |Capital after 25 years of savings:    468925
           |Capital after 40 years in retirement: 2958842
           |""".stripMargin
      actualResult should ===(Valid(expectedResult))
    }

    "return an error when the period exceeds the returns bounds" in {
      val actualResult = SimulatePlanApp.strMain(
        Array("1952.09,2017.09", "25", "60", "3000", "2000", "10000"))
      val expectedResult = "Cannot get the return for month 780. Accepted range: 0 to 779"
      actualResult should ===(Invalid(expectedResult))
    }

    "return an usage example when the number of arguments is incorrect" in {
      val result = SimulatePlanApp.strMain(
        Array("1952.09:2017.09", "25.0", "60", "3'000", "2000.0"))
      result should ===(Invalid(
        """Usage:
          |simulatePlan from,until nbOfYearsSaving nbOfYearsRetired netIncome currentExpenses initialCapital
          |
          |Example:
          |simulatePlan 1952.09,2017.09 25 40 3000 2000 10000
          |""".stripMargin))
    }

    "return several errors when several arguments are invalid" in {
      val result = SimulatePlanApp.strMain(
        Array("1952.09:2017.09", "25.0", "60", "3'000", "2000.0", "10000"))
      result should ===(Invalid(
        """Invalid format for fromUntil. Expected: from,until, actual: 1952.09:2017.09
          |Invalid number for nbOfYearsSaving: 25.0
          |Invalid number for netIncome: 3'000
          |Invalid number for currentExpenses: 2000.0""".stripMargin))
    }
  }
} 
Example 23
Source File: RetCalcIT.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package retcalc

import org.scalactic.{Equality, TolerantNumerics, TypeCheckedTripleEquals}
import org.scalatest.{EitherValues, Matchers, WordSpec}

class RetCalcIT extends WordSpec with Matchers with TypeCheckedTripleEquals with EitherValues {
  implicit val doubleEquality: Equality[Double] = TolerantNumerics.tolerantDoubleEquality(0.0001)

  val params = RetCalcParams(
    nbOfMonthsInRetirement = 40 * 12,
    netIncome = 3000,
    currentExpenses = 2000,
    initialCapital = 10000)


  "RetCalc.simulatePlan" should {
    "simulate a retirement plan with real market data" in {
      val returns = Returns.fromEquityAndInflationData(
        equities = EquityData.fromResource("sp500.tsv"),
        inflations = InflationData.fromResource("cpi.tsv")).fromUntil("1952.09", "2017.10")

      val (capitalAtRetirement, capitalAfterDeath) =
        RetCalc.simulatePlan(returns, params = params, nbOfMonthsSavings = 25 * 12).right.value
      capitalAtRetirement should ===(468924.5522)
      capitalAfterDeath should ===(2958841.7675)
    }
  }
} 
Example 24
Source File: EqualitySpec.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
import org.scalactic.{Equality, TolerantNumerics, TypeCheckedTripleEquals}
import org.scalatest.{Matchers, WordSpec}

class EqualitySpec extends WordSpec with Matchers with TypeCheckedTripleEquals{
  implicit val doubleEquality: Equality[Double] = TolerantNumerics.tolerantDoubleEquality(0.0001)

  implicit def vectorEquality[A](implicit eqA: Equality[A]): Equality[Vector[A]] = new Equality[Vector[A]] {
    override def areEqual(v1: Vector[A], b: Any): Boolean = b match {
      case v2: Vector[_] =>
        v1.size == v2.size &&
          v1.zip(v2).forall { case ((x, y)) => eqA.areEqual(x, y)}
      case _ => false
    }
  }

  "Equality" should {
    "allow to compare two Double with a tolerance" in {
      1.6 + 1.8 should ===(3.4)
    }

    "allow to compare two Vector[Double] with a tolerance" in {
      Vector(1.6 + 1.8, 0.0051) should === (Vector(3.4, 0.0052))
    }
  }
}