org.scalatest.TryValues Scala Examples

The following examples show how to use org.scalatest.TryValues. 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: DomainMethodArgumentFactoryTest.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.chrome.net.Protocol
import com.programmaticallyspeaking.ncd.testing.UnitTest
import org.scalatest.TryValues

class DomainMethodArgumentFactoryTest extends UnitTest {

  val factory = DomainMethodArgumentFactory

  "DomainMethodArgumentFactory.create" - {
    "with a message with a malformed method" - {
      "should signal the error" in {
        val msg = Protocol.IncomingMessage(1, "Foobar", null)
        val ex = intercept[IllegalArgumentException](factory.create(msg))
        ex.getMessage should include ("Malformed method")
      }
    }

    "with a message that targets a custom 'enable' method that takes parameters" in {
      val msg = Protocol.IncomingMessage(1, "Network.enable", Map.empty)
      val result = factory.create(msg)
      result should be (Network.enable())
    }

    "with a message without parameters" - {

      "should create a domain-generic 'enable' case object" in {
        // Access Domain.enable first to force-initialize the instance
        val expected = Domain.enable
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.enable", null)
        val result = factory.create(msg)
        result shouldBe theSameInstanceAs (expected)
      }

      "should create a case object" in {
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.bar", null)
        val result = factory.create(msg)
        result shouldBe theSameInstanceAs (FooTestDomain.bar)
      }

      "should create a case class if possible" in {
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.barArgs", null)
        val result = factory.create(msg)
        result should be (FooTestDomain.barArgs())
      }
    }

    "with a message with empty parameters" - {

      "should not create a case object" in {
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.bar", Map.empty)
        val ex = intercept[IllegalArgumentException](factory.create(msg))
        ex.getMessage should include ("there are arguments")
      }

      "should create a case class" in {
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.barcase", Map.empty)
        val result = factory.create(msg)
        result should be (FooTestDomain.barcase(None))
      }

    }

    "with a message with parameters" - {
      "should create a case class" in {
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.baz", Map("a" -> "data", "b" -> 42))
        val result = factory.create(msg)
        result should be (FooTestDomain.baz("data", 42))
      }

      "should refuse to create a case object" in {
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.bar", Map("a" -> "data", "b" -> 42))
        val ex = intercept[IllegalArgumentException](factory.create(msg))
        ex.getMessage should include ("there are arguments")
      }
    }

    "with an unknown domain and/or method" - {
      "should signal the error" in {
        val msg = Protocol.IncomingMessage(1, "FooTestDomain.xyz", null)
        val ex = intercept[IllegalArgumentException](factory.create(msg))
        ex.getMessage should include ("are unknown")
      }
    }
  }
} 
Example 2
Source File: VersionNumberCalculatorSpec.scala    From releaser   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.releaser

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

class VersionNumberCalculatorSpec extends WordSpec with Matchers with TryValues {

  import VersionNumberCalculator._

  "VersionNumberCalculator" should {
    "calculate 0.8.2 given a release candidate of 0.8.1-4-ge733d26 and release type of HOTFIX" in {
      calculateTarget(ReleaseCandidateVersion("0.8.1-4-ge733d26"), ReleaseType.HOTFIX).success.value.value shouldBe "0.8.2"
    }

    "calculate 0.9.0 given a release candidate of 0.8.1-4-ge733d26 and release type of MINOR" in {
      calculateTarget(ReleaseCandidateVersion("0.8.1-4-ge733d26"), ReleaseType.MINOR).success.value.value shouldBe "0.9.0"
    }

    "calculate 1.0.0 given a release candidate of 0.8.1-4-ge733d26 and release type of MAJOR" in {
      calculateTarget(ReleaseCandidateVersion("0.8.1-4-ge733d26"), ReleaseType.MAJOR).success.value.value shouldBe "1.0.0"
    }

    "calculate 11.12.20 given a release candidate of 11.12.19-4-ge733d26 and release type of MAJOR" in {
      calculateTarget(ReleaseCandidateVersion("11.12.19-4-ge733d26"), ReleaseType.HOTFIX).success.value.value shouldBe "11.12.20"
    }

    "return a failure given an invalid release number of 0.0.1-SNAPSHOT and release type of PATCH" in {
      calculateTarget(ReleaseCandidateVersion("0.0.1-SNAPSHOT"), ReleaseType.HOTFIX).failure.exception.getMessage should include("SNAPSHOT")
    }
  }
} 
Example 3
Source File: ArtefactMetaDataProviderSpecs.scala    From releaser   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.releaser

import java.nio.file.Paths

import org.scalatest.{Matchers, TryValues, WordSpec}
import uk.gov.hmrc.releaser.github.GithubConnector

import scala.util.Failure

class ArtefactMetaDataProviderSpecs extends WordSpec with Matchers with TryValues {

  "ArtefactMetaData" should {
    "build instance from file" in {
      val md = new ArtefactMetaDataProvider().fromJarFile(Paths.get(this.getClass.getResource("/sbt-bobby/uk.gov.hmrc/sbt-bobby/scala_2.10/sbt_0.13/0.8.1-4-ge733d26/jars/sbt-bobby.jar").toURI))  match {
        case Failure(e) => fail(e)
        case s => s
      }

      md.success.value.commitAuthor shouldBe "Charles Kubicek"
      md.success.value.sha  shouldBe "e733d26fa504c040f2c95ecd25a3a55399a00883"
      md.success.value.commitDate shouldBe GithubConnector.githubDateTimeFormatter.parseDateTime("2015-04-09T10:18:12.000Z")
    }
  }
} 
Example 4
Source File: KryoSerializerInitSpec.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.serializers

import java.nio.file.Paths

import akka.actor.ActorSystem
import akka.serialization.SerializationExtension
import akka.testkit.TestKit
import ch.epfl.bluebrain.nexus.kg.TestHelper
import io.altoo.akka.serialization.kryo.KryoSerializer
import org.scalatest.TryValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class KryoSerializerInitSpec
    extends TestKit(ActorSystem("KryoSerializerInitSpec"))
    with AnyWordSpecLike
    with Matchers
    with TryValues
    with TestHelper {
  private val serialization = SerializationExtension(system)

  "A Path Kryo serialization" should {
    "succeed" in {
      val path = Paths.get("resources/application.conf")

      // Find the Serializer for it
      val serializer = serialization.findSerializerFor(path)
      serializer.getClass.equals(classOf[KryoSerializer]) shouldEqual true

      // Check serialization/deserialization
      val serialized = serialization.serialize(path)
      serialized.isSuccess shouldEqual true

      val deserialized = serialization.deserialize(serialized.get, path.getClass)
      deserialized.isSuccess shouldEqual true
      deserialized.success.value shouldEqual path
    }
  }

} 
Example 5
Source File: StorageCacheSpec.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.cache

import java.nio.file.Paths
import java.time.Clock

import akka.testkit._
import ch.epfl.bluebrain.nexus.commons.test.ActorSystemFixture
import ch.epfl.bluebrain.nexus.kg.TestHelper
import ch.epfl.bluebrain.nexus.kg.config.AppConfig._
import ch.epfl.bluebrain.nexus.kg.config.{AppConfig, Settings}
import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.{ProjectRef}
import ch.epfl.bluebrain.nexus.kg.storage.Storage.DiskStorage
import ch.epfl.bluebrain.nexus.rdf.implicits._
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.{Inspectors, TryValues}

import scala.concurrent.duration._

//noinspection NameBooleanParameters
class StorageCacheSpec
    extends ActorSystemFixture("StorageCacheSpec", true)
    with Matchers
    with Inspectors
    with ScalaFutures
    with TryValues
    with TestHelper {

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(3.seconds.dilated, 5.milliseconds)

  private implicit val clock: Clock         = Clock.systemUTC
  private implicit val appConfig: AppConfig = Settings(system).appConfig

  val ref1 = ProjectRef(genUUID)
  val ref2 = ProjectRef(genUUID)

  val time   = clock.instant()
  val lastId = url"http://example.com/lastA"
  // initialInstant.minusSeconds(1L + genInt().toLong)

  val tempStorage = DiskStorage(ref1, genIri, 1L, false, true, "alg", Paths.get("/tmp"), read, write, 1024L)

  val lastStorageProj1 = tempStorage.copy(id = lastId)
  val lastStorageProj2 = tempStorage.copy(ref = ref2, id = lastId)

  val storagesProj1: List[DiskStorage] = List.fill(5)(tempStorage.copy(id = genIri)) :+ lastStorageProj1
  val storagesProj2: List[DiskStorage] = List.fill(5)(tempStorage.copy(ref = ref2, id = genIri)) :+ lastStorageProj2

  private val cache = StorageCache[Task]

  "StorageCache" should {

    "index storages" in {
      forAll((storagesProj1 ++ storagesProj2).zipWithIndex) {
        case (storage, index) =>
          implicit val instant = time.plusSeconds(index.toLong)
          cache.put(storage).runToFuture.futureValue
          cache.get(storage.ref, storage.id).runToFuture.futureValue shouldEqual Some(storage)
      }
    }

    "get latest default storage" in {
      cache.getDefault(ref1).runToFuture.futureValue shouldEqual Some(lastStorageProj1)
      cache.getDefault(ref2).runToFuture.futureValue shouldEqual Some(lastStorageProj2)
      cache.getDefault(ProjectRef(genUUID)).runToFuture.futureValue shouldEqual None
    }

    "list storages" in {
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs storagesProj1
      cache.get(ref2).runToFuture.futureValue should contain theSameElementsAs storagesProj2
    }

    "deprecate storage" in {
      val storage          = storagesProj1.head
      implicit val instant = time.plusSeconds(30L)
      cache.put(storage.copy(deprecated = true, rev = 2L)).runToFuture.futureValue
      cache.get(storage.ref, storage.id).runToFuture.futureValue shouldEqual None
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs storagesProj1.filterNot(_ == storage)
    }
  }
} 
Example 6
Source File: ResolverCacheSpec.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.cache

import akka.actor.ExtendedActorSystem
import akka.serialization.Serialization
import akka.testkit._
import ch.epfl.bluebrain.nexus.commons.test.ActorSystemFixture
import ch.epfl.bluebrain.nexus.iam.client.types.Identity.Anonymous
import ch.epfl.bluebrain.nexus.kg.TestHelper
import ch.epfl.bluebrain.nexus.kg.config.AppConfig._
import ch.epfl.bluebrain.nexus.kg.config.{AppConfig, Settings}
import ch.epfl.bluebrain.nexus.kg.resolve.Resolver._
import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.{ProjectLabel, ProjectRef}
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.{Inspectors, TryValues}

import scala.concurrent.duration._

//noinspection NameBooleanParameters
class ResolverCacheSpec
    extends ActorSystemFixture("ResolverCacheSpec", true)
    with Matchers
    with Inspectors
    with ScalaFutures
    with TryValues
    with TestHelper {

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(3.seconds.dilated, 5.milliseconds)

  private implicit val appConfig: AppConfig = Settings(system).appConfig

  val ref1 = ProjectRef(genUUID)
  val ref2 = ProjectRef(genUUID)

  val label1 = ProjectLabel(genString(), genString())
  val label2 = ProjectLabel(genString(), genString())

  val resolver: InProjectResolver = InProjectResolver(ref1, genIri, 1L, false, 10)
  val crossRefs: CrossProjectResolver =
    CrossProjectResolver(Set(genIri), List(ref1, ref2), Set(Anonymous), ref1, genIri, 0L, false, 1)
  val crossLabels: CrossProjectResolver =
    CrossProjectResolver(Set(genIri), List(label1, label2), Set(Anonymous), ref1, genIri, 0L, false, 1)

  val resolverProj1: Set[InProjectResolver] = List.fill(5)(resolver.copy(id = genIri)).toSet
  val resolverProj2: Set[InProjectResolver] = List.fill(5)(resolver.copy(id = genIri, ref = ref2)).toSet

  private val cache = ResolverCache[Task]

  "ResolverCache" should {

    "index resolvers" in {
      val list = (resolverProj1 ++ resolverProj2).toList
      forAll(list) { resolver =>
        cache.put(resolver).runToFuture.futureValue
        cache.get(resolver.ref, resolver.id).runToFuture.futureValue shouldEqual Some(resolver)
      }
    }

    "list resolvers" in {
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs resolverProj1
      cache.get(ref2).runToFuture.futureValue should contain theSameElementsAs resolverProj2
    }

    "deprecate resolver" in {
      val resolver = resolverProj1.head
      cache.put(resolver.copy(deprecated = true, rev = 2L)).runToFuture.futureValue
      cache.get(resolver.ref, resolver.id).runToFuture.futureValue shouldEqual None
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs resolverProj1.filterNot(_ == resolver)
    }

    "serialize cross project resolver" when {
      val serialization = new Serialization(system.asInstanceOf[ExtendedActorSystem])
      "parameterized with ProjectRef" in {
        val bytes = serialization.serialize(crossRefs).success.value
        val out   = serialization.deserialize(bytes, classOf[CrossProjectResolver]).success.value
        out shouldEqual crossRefs
      }
      "parameterized with ProjectLabel" in {
        val bytes = serialization.serialize(crossLabels).success.value
        val out   = serialization.deserialize(bytes, classOf[CrossProjectResolver]).success.value
        out shouldEqual crossLabels
      }
    }
  }
} 
Example 7
Source File: CompositeResolutionSpec.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.resolve

import java.time.Clock
import java.util.UUID
import java.util.regex.Pattern.quote

import cats.instances.try_._
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.commons.test.Resources
import ch.epfl.bluebrain.nexus.kg.resources.Ref
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.implicits._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{OptionValues, TryValues}

import scala.util.Try

class CompositeResolutionSpec extends AnyWordSpecLike with Resources with Matchers with TryValues with OptionValues {

  "CompositeResolution" should {

    implicit val clock = Clock.systemUTC

    val resource1Uri: AbsoluteIri = url"http://nexus.example.com/resources/static/${UUID.randomUUID().toString}"
    val resource2Uri: AbsoluteIri = url"http://nexus.example.com/resources/static/${UUID.randomUUID().toString}"
    val staticResolution1 = StaticResolution[Try](
      Map(
        resource1Uri -> jsonContentOf(
          "/resolve/simple-resource.json",
          Map(quote("{id}") -> resource1Uri.show, quote("{random}") -> UUID.randomUUID().toString)
        )
      )
    )
    val staticResolution2 = StaticResolution[Try](
      Map(
        resource2Uri -> jsonContentOf(
          "/resolve/simple-resource.json",
          Map(quote("{id}") -> resource2Uri.show, quote("{random}") -> UUID.randomUUID().toString)
        )
      )
    )
    val staticResolution3 = StaticResolution[Try](
      Map(
        resource1Uri -> jsonContentOf(
          "/resolve/simple-resource.json",
          Map(quote("{id}") -> resource1Uri.show, quote("{random}") -> UUID.randomUUID().toString)
        )
      )
    )

    val compositeResolution = CompositeResolution[Try](List(staticResolution1, staticResolution2, staticResolution3))

    "return the resource from the first resolver which returns the resource" in {

      compositeResolution.resolve(Ref(resource1Uri)).success.value.value shouldEqual staticResolution1
        .resolve(Ref(resource1Uri))
        .success
        .value
        .value
      compositeResolution.resolve(Ref(resource2Uri)).success.value.value shouldEqual staticResolution2
        .resolve(Ref(resource2Uri))
        .success
        .value
        .value
    }
  }

} 
Example 8
Source File: StreamletDefinitionSpec.scala    From cloudflow   with Apache License 2.0 5 votes vote down vote up
package cloudflow.streamlets

import com.typesafe.config.ConfigFactory
import org.scalatest.{ MustMatchers, OptionValues, TryValues, WordSpec }

class StreamletDefinitionSpec extends WordSpec with MustMatchers with TryValues with OptionValues {

  "A valid StreamletConfig" should {
    val config          = ConfigFactory.load("config-map-sample.json")
    val streamletConfig = StreamletDefinition.read(config).get

    "the loaded instances must contain class, instance and port information" in {
      val expectedStreamlet = ("sensor-data", "cloudflow.examples.sensordata.SensorDataIngress$")
      streamletConfig.streamletRef must be(expectedStreamlet._1)
      streamletConfig.streamletClass must be(expectedStreamlet._2)
    }

    "a loaded instance must have port configuration" in {
      val ports = streamletConfig.portMappings
      val expectedPorts = Map(
        "accepted" -> Topic("accepted"),
        "rejected" -> Topic("rejected")
      )
      ports.foreach(portMapping ⇒ expectedPorts(portMapping.port) must be(portMapping.topic))
    }

    "a loaded instance must have its own configuration" in {
      val config = streamletConfig.config
      config.getInt("cloudflow.internal.server.container-port") must be(2049)
    }

    "a loaded instance must have the common configuration" in {
      config.getString("cloudflow.common.attribute") must be("value")
      config.getString("cloudflow.kafka.bootstrap-servers") must be("cloudflow-kafka.lightbend:9092")
    }

    "a loaded instance must not have runner configuration" in {
      val config = streamletConfig.config
      config.hasPath("runner") must be(false)
    }
  }
} 
Example 9
Source File: ClassOpsSpec.scala    From cloudflow   with Apache License 2.0 5 votes vote down vote up
package cloudflow.streamlets

import org.scalatest.{ MustMatchers, TryValues, WordSpec }

// Definitions for test purposes
class Foo
class Bar extends Foo

class ClassWithArgsConstructor(arg: Int) extends Bar {
  def args = arg
}
class ClassWithNoArgsConstructor() extends Bar

object BarObject extends Bar

class ClassWithCompanionObject
object ClassWithCompanionObject

class ClassWithArgsAndCompanionObject(arg: Int) {
  def args = arg
}
object ClassWithArgsAndCompanionObject

class ClassOpsSpec extends WordSpec with MustMatchers with TryValues {

  import ClassOps._

  "nameOf" should {
    "return the fully qualified class name of the specified type" in {
      nameOf[Foo] mustBe "cloudflow.streamlets.Foo"
    }
    "return the fully qualified class name of the specified instance" in {
      nameOf(BarObject) mustBe "cloudflow.streamlets.BarObject"
    }
  }

  "instanceOf" should {
    import ClassOps._
    "create a new instance of a class" in {
      instanceOf("cloudflow.streamlets.Bar").success.value mustBe a[Bar]
    }

    "reuse the object instance of a singleton Object" in {
      instanceOf("cloudflow.streamlets.BarObject").success.value mustBe (BarObject)
    }

    "reuse the object instance of a singleton Object with name passed with a $" in {
      instanceOf("cloudflow.streamlets.BarObject$").success.value mustBe (BarObject)
    }

    "fail to create an instance for a class without a no-args constructor" in {
      instanceOf("cloudflow.streamlets.ClassWithArgsConstructor").failure.exception mustBe a[InstantiationException]
    }

    "create a new instance of a class with a no-arg constructor and a companion object" in {
      instanceOf("cloudflow.streamlets.ClassWithCompanionObject").success.value mustBe a[ClassWithCompanionObject]
    }

    "reuse the object instance when we have a class with no no-arg constructor along with a companion Object" in {
      instanceOf("cloudflow.streamlets.ClassWithArgsAndCompanionObject").success.value mustBe (ClassWithArgsAndCompanionObject)
    }
  }
} 
Example 10
Source File: CodecsSpec.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc
import akka.grpc.internal.{ Codecs, Gzip, Identity }
import akka.grpc.scaladsl.headers
import akka.http.scaladsl.model.HttpRequest
import io.grpc.Status
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.TryValues

import scala.collection.immutable

class CodecsSpec extends AnyWordSpec with Matchers with TryValues {

  private def accept(encodings: String*): HttpRequest =
    HttpRequest(headers = immutable.Seq(headers.`Message-Accept-Encoding`(encodings.mkString(","))))

  private def enc(encodings: String*): HttpRequest =
    HttpRequest(headers = immutable.Seq(headers.`Message-Encoding`(encodings.mkString(","))))

  "Negotiating message encoding with remote client" should {

    "default to Identity if no encoding provided" in {
      Codecs.negotiate(HttpRequest()) should be(Identity)
    }

    "accept explicit Identity" in {
      Codecs.negotiate(accept(Identity.name)) should be(Identity)
    }

    "accept explicit Gzip" in {
      Codecs.negotiate(accept(Gzip.name)) should be(Gzip)
    }

    "use client preference with multiple known encodings" in {
      Codecs.negotiate(accept(Gzip.name, Identity.name)) should be(Gzip)
      Codecs.negotiate(accept(Identity.name, Gzip.name)) should be(Identity)
    }

    "use first known encoding" in {
      Codecs.negotiate(accept("xxxxx", Gzip.name, Identity.name)) should be(Gzip)
    }

    "use default encoding if unknown encodings specified" in {
      Codecs.negotiate(accept("xxxxx")) should be(Identity)
    }

  }

  "Detecting message encoding from remote" should {

    "default to Identity if not specified" in {
      Codecs.detect(HttpRequest()).success.value should be(Identity)
    }

    "accept explicit Identity" in {
      Codecs.detect(enc(Identity.name)).success.value should be(Identity)
    }

    "accept explicit Gzip" in {
      Codecs.detect(enc(Gzip.name)).success.value should be(Gzip)
    }

    "fail with unknown encoding" in {
      val detected = Codecs.detect(enc("xxxxxxx"))
      detected.failure.exception shouldBe a[GrpcServiceException]
      detected.failure.exception.asInstanceOf[GrpcServiceException].status.getCode should be(
        Status.UNIMPLEMENTED.getCode)
    }
  }

} 
Example 11
Source File: JWKSetSerializerSpec.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.io

import akka.actor.{ActorSystem, ExtendedActorSystem}
import akka.serialization.Serialization
import akka.testkit.TestKit
import com.nimbusds.jose.jwk.JWKSet
import com.typesafe.config.ConfigFactory
import org.scalatest.TryValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class JWKSetSerializerSpec
    extends TestKit(ActorSystem("JWKSetSerializerSpec", ConfigFactory.load("akka-test.conf")))
    with AnyWordSpecLike
    with Matchers
    with TryValues {

  private val serialization = new Serialization(system.asInstanceOf[ExtendedActorSystem])

  private val json =
    """
      |{
      |  "keys": [
      |    {
      |      "kid": "-JoF9COvvt7UhyhJMC-YlTF6piRlZgQKRQks5sPMKxw",
      |      "kty": "RSA",
      |      "alg": "RS256",
      |      "use": "sig",
      |      "n": "iEk11wBlv0I4pawBSY6ZYCLvwVslfCvjwvg5tIAg9n",
      |      "e": "AQAB"
      |    }
      |  ]
      |}
    """.stripMargin

  private val jwks = JWKSet.parse(json)

  "A JWKSetSerializer" should {

    "serialize and deserialize" in {
      val bytes = serialization.serialize(jwks).success.value
      val obj   = serialization.deserialize(bytes, classOf[JWKSet]).success.value
      jwks.toJSONObject shouldEqual obj.toJSONObject // JWKSet doesn't have a proper equals method
    }
  }
} 
Example 12
Source File: FileInfotonTests.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package cmwell.it

import java.nio.charset.StandardCharsets

import com.typesafe.scalalogging.LazyLogging
import org.scalatest.{AsyncFunSpec, Matchers, TryValues}
import play.api.libs.json._

import scala.concurrent.duration.DurationInt
import scala.io.Source

class FileInfotonTests extends AsyncFunSpec with Matchers with TryValues with Helpers with LazyLogging {
  describe("file infoton") {
    val path = cmt / "InfoFile4"
    val fileStr = Source.fromURL(this.getClass.getResource("/article.txt")).mkString
    val j = Json.obj("Offcourse" -> Seq("I can do it"),"I'm" -> Seq("a spellbinder"))

    val f0 = Http.post(path, fileStr, Some("text/plain;charset=UTF-8"), Nil, ("X-CM-WELL-TYPE" -> "FILE") :: tokenHeader).map { res =>
      withClue(res){
        Json.parse(res.payload) should be(jsonSuccess)
      }
    }
    val f1 = f0.flatMap {_ => spinCheck(100.millis, true)(Http.get(path)){res =>
      new String(res.payload, StandardCharsets.UTF_8) == fileStr && res.contentType.takeWhile(_ != ';') == "text/plain"}
      .map { res =>
        withClue(res) {
          new String(res.payload, StandardCharsets.UTF_8) should be(fileStr)
          res.contentType.takeWhile(_ != ';') should be("text/plain")
        }
      }}
    val f2 = f1.flatMap(_ => Http.post(path, Json.stringify(j), None, Nil, ("X-CM-WELL-TYPE" -> "FILE_MD") :: tokenHeader)).map {res =>
      withClue(res) {
        Json.parse(res.payload) should be(jsonSuccess)
      }
    }
    val f3 = f2.flatMap(_ => spinCheck(100.millis, true)(Http.get(path, List("format" -> "json"))){
      res =>
        val jsonResult = Json.parse(res.payload).transform(fieldsSorter andThen (__ \ 'fields).json.pick)
        jsonResult match {
          case JsSuccess(value, _) => value == j
          case JsError(_) => false
        }
    }.map{ res =>
        withClue(res) {
          Json
            .parse(res.payload)
            .transform(fieldsSorter andThen (__ \ 'fields).json.pick)
            .get shouldEqual j
        }
      }
    )
    val f4 = f3.flatMap(_ => Http.delete(uri = path, headers = tokenHeader).map { res =>
       withClue(res) {
         Json.parse(res.payload) should be(jsonSuccess)
       }
    })
    val lenna = cmt / "lenna"
    val f5 = {
      val lennaInputStream = this.getClass.getResource("/Lenna.png").openStream()
      Http.post(lenna / "Lenna.png", () => lennaInputStream, Some("image/png"), Nil, ("X-CM-WELL-TYPE" -> "FILE") :: tokenHeader).transform { res =>
        // first, close the stream
        lennaInputStream.close()
        withClue(res)(res.map { r =>
          Json.parse(r.payload) should be(jsonSuccess)
        })
      }
    }
    val f6 = spinCheck(100.millis,true,1.minute)(Http.get(lenna,List("op" -> "search","qp" -> "content.mimeType:image/png", "format" -> "json"))){ res =>
        res.status match {
          case 503 => Recoverable
          case 200 => {
            val j = Json.parse(res.payload) \ "results"
            (j \ "total": @unchecked) match {
              case JsDefined(JsNumber(n)) => n.intValue == 1
            }
          }
          case _ => UnRecoverable
        }
      }.map { res =>
      withClue(res) {
        val j = Json.parse(res.payload) \ "results"
        (j \ "infotons": @unchecked) match {
          case JsDefined(JsArray(arr)) => (arr.head \ "system" \ "path": @unchecked) match {
            case JsDefined(JsString(lennaPath)) =>
              lennaPath shouldEqual "/cmt/cm/test/lenna/Lenna.png"
          }
        }
      }
    }

    it("should put File infoton")(f0)
    it("should get previously inserted file with text/plain mimetype")(f1)
    it("should put file infoton metadata")(f2)
    it("should get file infoton metadata")(f3)
    it("should delete file infoton")(f4)
    it("should upload Lenna.png image")(f5)
    it("should search by content.mimeType")(f6)
  }
} 
Example 13
Source File: ZipBombDetectionSpec.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.FileInputStream
import java.util.zip.ZipInputStream

import com.daml.bazeltools.BazelRunfiles
import org.scalatest.{FlatSpec, Matchers, TryValues}

final class ZipBombDetectionSpec extends FlatSpec with Matchers with TryValues {

  private def bomb: ZipInputStream =
    new ZipInputStream(
      new FileInputStream(BazelRunfiles.rlocation("daml-lf/archive/DarReaderTest.dar"))
    )

  "DarReader" should "reject a zip bomb with the proper error" in {
    DarReader()
      .readArchive("t", bomb, entrySizeThreshold = 1024)
      .failure
      .exception shouldBe a[Errors.ZipBomb]
  }

  "UniversalArchiveReader" should "reject a zip bomb with the proper error" in {
    UniversalArchiveReader(entrySizeThreshold = 1024)
      .readDarStream("t", bomb)
      .failure
      .exception shouldBe a[Errors.ZipBomb]
  }

} 
Example 14
Source File: JWKSetSerializerSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.io

import akka.actor.{ActorSystem, ExtendedActorSystem}
import akka.serialization.Serialization
import akka.testkit.TestKit
import com.nimbusds.jose.jwk.JWKSet
import com.typesafe.config.ConfigFactory
import org.scalatest.TryValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class JWKSetSerializerSpec
    extends TestKit(ActorSystem("JWKSetSerializerSpec", ConfigFactory.load("test.conf")))
    with AnyWordSpecLike
    with Matchers
    with TryValues {

  private val serialization = new Serialization(system.asInstanceOf[ExtendedActorSystem])

  private val json =
    """
      |{
      |  "keys": [
      |    {
      |      "kid": "-JoF9COvvt7UhyhJMC-YlTF6piRlZgQKRQks5sPMKxw",
      |      "kty": "RSA",
      |      "alg": "RS256",
      |      "use": "sig",
      |      "n": "iEk11wBlv0I4pawBSY6ZYCLvwVslfCvjwvg5tIAg9n",
      |      "e": "AQAB"
      |    }
      |  ]
      |}
    """.stripMargin

  private val jwks = JWKSet.parse(json)

  "A JWKSetSerializer" should {

    "serialize and deserialize" in {
      val bytes = serialization.serialize(jwks).success.value
      val obj   = serialization.deserialize(bytes, classOf[JWKSet]).success.value
      jwks.toJSONObject shouldEqual obj.toJSONObject // JWKSet doesn't have a proper equals method
    }
  }
} 
Example 15
Source File: KryoSerializerInitSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.serializers

import java.nio.file.Paths

import akka.actor.ActorSystem
import akka.serialization.SerializationExtension
import akka.testkit.TestKit
import ch.epfl.bluebrain.nexus.kg.TestHelper
import io.altoo.akka.serialization.kryo.KryoSerializer
import org.scalatest.TryValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class KryoSerializerInitSpec
    extends TestKit(ActorSystem("KryoSerializerInitSpec"))
    with AnyWordSpecLike
    with Matchers
    with TryValues
    with TestHelper {
  private val serialization = SerializationExtension(system)

  "A Path Kryo serialization" should {
    "succeed" in {
      val path = Paths.get("resources/application.conf")

      // Find the Serializer for it
      val serializer = serialization.findSerializerFor(path)
      serializer.getClass.equals(classOf[KryoSerializer]) shouldEqual true

      // Check serialization/deserialization
      val serialized = serialization.serialize(path)
      serialized.isSuccess shouldEqual true

      val deserialized = serialization.deserialize(serialized.get, path.getClass)
      deserialized.isSuccess shouldEqual true
      deserialized.success.value shouldEqual path
    }
  }

} 
Example 16
Source File: StorageCacheSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.cache

import java.nio.file.Paths
import java.time.Clock

import akka.testkit._
import ch.epfl.bluebrain.nexus.commons.test.ActorSystemFixture
import ch.epfl.bluebrain.nexus.kg.TestHelper
import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef
import ch.epfl.bluebrain.nexus.kg.storage.Storage.DiskStorage
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.{ServiceConfig, Settings}
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.{Inspectors, TryValues}

import scala.concurrent.duration._

//noinspection NameBooleanParameters
class StorageCacheSpec
    extends ActorSystemFixture("StorageCacheSpec", true)
    with Matchers
    with Inspectors
    with ScalaFutures
    with TryValues
    with TestHelper {

  implicit override def patienceConfig: PatienceConfig = PatienceConfig(3.seconds.dilated, 5.milliseconds)

  implicit private val clock: Clock             = Clock.systemUTC
  implicit private val appConfig: ServiceConfig = Settings(system).serviceConfig
  implicit private val keyValueStoreCfg         = appConfig.kg.keyValueStore.keyValueStoreConfig

  val ref1 = ProjectRef(genUUID)
  val ref2 = ProjectRef(genUUID)

  val time   = clock.instant()
  val lastId = url"http://example.com/lastA"
  // initialInstant.minusSeconds(1L + genInt().toLong)

  val tempStorage = DiskStorage(ref1, genIri, 1L, false, true, "alg", Paths.get("/tmp"), read, write, 1024L)

  val lastStorageProj1 = tempStorage.copy(id = lastId)
  val lastStorageProj2 = tempStorage.copy(ref = ref2, id = lastId)

  val storagesProj1: List[DiskStorage] = List.fill(5)(tempStorage.copy(id = genIri)) :+ lastStorageProj1
  val storagesProj2: List[DiskStorage] = List.fill(5)(tempStorage.copy(ref = ref2, id = genIri)) :+ lastStorageProj2

  private val cache = StorageCache[Task]

  "StorageCache" should {

    "index storages" in {
      forAll((storagesProj1 ++ storagesProj2).zipWithIndex) {
        case (storage, index) =>
          implicit val instant = time.plusSeconds(index.toLong)
          cache.put(storage).runToFuture.futureValue
          cache.get(storage.ref, storage.id).runToFuture.futureValue shouldEqual Some(storage)
      }
    }

    "get latest default storage" in {
      cache.getDefault(ref1).runToFuture.futureValue shouldEqual Some(lastStorageProj1)
      cache.getDefault(ref2).runToFuture.futureValue shouldEqual Some(lastStorageProj2)
      cache.getDefault(ProjectRef(genUUID)).runToFuture.futureValue shouldEqual None
    }

    "list storages" in {
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs storagesProj1
      cache.get(ref2).runToFuture.futureValue should contain theSameElementsAs storagesProj2
    }

    "deprecate storage" in {
      val storage          = storagesProj1.head
      implicit val instant = time.plusSeconds(30L)
      cache.put(storage.copy(deprecated = true, rev = 2L)).runToFuture.futureValue
      cache.get(storage.ref, storage.id).runToFuture.futureValue shouldEqual None
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs storagesProj1.filterNot(_ == storage)
    }
  }
} 
Example 17
Source File: ResolverCacheSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.cache

import akka.actor.ExtendedActorSystem
import akka.serialization.Serialization
import akka.testkit._
import ch.epfl.bluebrain.nexus.commons.test.ActorSystemFixture
import ch.epfl.bluebrain.nexus.iam.types.Identity.Anonymous
import ch.epfl.bluebrain.nexus.kg.TestHelper
import ch.epfl.bluebrain.nexus.kg.config.KgConfig._
import ch.epfl.bluebrain.nexus.kg.resolve.Resolver._
import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.{ProjectLabel, ProjectRef}
import ch.epfl.bluebrain.nexus.service.config.{ServiceConfig, Settings}
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.{Inspectors, TryValues}

import scala.concurrent.duration._

//noinspection NameBooleanParameters
class ResolverCacheSpec
    extends ActorSystemFixture("ResolverCacheSpec", true)
    with Matchers
    with Inspectors
    with ScalaFutures
    with TryValues
    with TestHelper {

  implicit override def patienceConfig: PatienceConfig = PatienceConfig(3.seconds.dilated, 5.milliseconds)

  implicit private val appConfig: ServiceConfig = Settings(system).serviceConfig
  implicit private val keyValueStoreCfg         = appConfig.kg.keyValueStore.keyValueStoreConfig

  val ref1 = ProjectRef(genUUID)
  val ref2 = ProjectRef(genUUID)

  val label1 = ProjectLabel(genString(), genString())
  val label2 = ProjectLabel(genString(), genString())

  val resolver: InProjectResolver       = InProjectResolver(ref1, genIri, 1L, false, 10)
  val crossRefs: CrossProjectResolver   =
    CrossProjectResolver(Set(genIri), List(ref1, ref2), Set(Anonymous), ref1, genIri, 0L, false, 1)
  val crossLabels: CrossProjectResolver =
    CrossProjectResolver(Set(genIri), List(label1, label2), Set(Anonymous), ref1, genIri, 0L, false, 1)

  val resolverProj1: Set[InProjectResolver] = List.fill(5)(resolver.copy(id = genIri)).toSet
  val resolverProj2: Set[InProjectResolver] = List.fill(5)(resolver.copy(id = genIri, ref = ref2)).toSet

  private val cache = ResolverCache[Task]

  "ResolverCache" should {

    "index resolvers" in {
      val list = (resolverProj1 ++ resolverProj2).toList
      forAll(list) { resolver =>
        cache.put(resolver).runToFuture.futureValue
        cache.get(resolver.ref, resolver.id).runToFuture.futureValue shouldEqual Some(resolver)
      }
    }

    "list resolvers" in {
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs resolverProj1
      cache.get(ref2).runToFuture.futureValue should contain theSameElementsAs resolverProj2
    }

    "deprecate resolver" in {
      val resolver = resolverProj1.head
      cache.put(resolver.copy(deprecated = true, rev = 2L)).runToFuture.futureValue
      cache.get(resolver.ref, resolver.id).runToFuture.futureValue shouldEqual None
      cache.get(ref1).runToFuture.futureValue should contain theSameElementsAs resolverProj1.filterNot(_ == resolver)
    }

    "serialize cross project resolver" when {
      val serialization = new Serialization(system.asInstanceOf[ExtendedActorSystem])
      "parameterized with ProjectRef" in {
        val bytes = serialization.serialize(crossRefs).success.value
        val out   = serialization.deserialize(bytes, classOf[CrossProjectResolver]).success.value
        out shouldEqual crossRefs
      }
      "parameterized with ProjectLabel" in {
        val bytes = serialization.serialize(crossLabels).success.value
        val out   = serialization.deserialize(bytes, classOf[CrossProjectResolver]).success.value
        out shouldEqual crossLabels
      }
    }
  }
} 
Example 18
Source File: CompositeResolutionSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.resolve

import java.time.Clock
import java.util.UUID
import java.util.regex.Pattern.quote

import cats.instances.try_._
import cats.syntax.show._
import ch.epfl.bluebrain.nexus.commons.test.Resources
import ch.epfl.bluebrain.nexus.kg.resources.Ref
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.implicits._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{OptionValues, TryValues}

import scala.util.Try

class CompositeResolutionSpec extends AnyWordSpecLike with Resources with Matchers with TryValues with OptionValues {

  "CompositeResolution" should {

    implicit val clock = Clock.systemUTC

    val resource1Uri: AbsoluteIri = url"http://nexus.example.com/resources/static/${UUID.randomUUID().toString}"
    val resource2Uri: AbsoluteIri = url"http://nexus.example.com/resources/static/${UUID.randomUUID().toString}"
    val staticResolution1         = StaticResolution[Try](
      Map(
        resource1Uri -> jsonContentOf(
          "/resolve/simple-resource.json",
          Map(quote("{id}") -> resource1Uri.show, quote("{random}") -> UUID.randomUUID().toString)
        )
      )
    )
    val staticResolution2         = StaticResolution[Try](
      Map(
        resource2Uri -> jsonContentOf(
          "/resolve/simple-resource.json",
          Map(quote("{id}") -> resource2Uri.show, quote("{random}") -> UUID.randomUUID().toString)
        )
      )
    )
    val staticResolution3         = StaticResolution[Try](
      Map(
        resource1Uri -> jsonContentOf(
          "/resolve/simple-resource.json",
          Map(quote("{id}") -> resource1Uri.show, quote("{random}") -> UUID.randomUUID().toString)
        )
      )
    )

    val compositeResolution = CompositeResolution[Try](List(staticResolution1, staticResolution2, staticResolution3))

    "return the resource from the first resolver which returns the resource" in {

      compositeResolution.resolve(Ref(resource1Uri)).success.value.value shouldEqual staticResolution1
        .resolve(Ref(resource1Uri))
        .success
        .value
        .value
      compositeResolution.resolve(Ref(resource2Uri)).success.value.value shouldEqual staticResolution2
        .resolve(Ref(resource2Uri))
        .success
        .value
        .value
    }
  }

} 
Example 19
Source File: SourcingSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.sourcing

import org.scalactic.source
import org.scalatest.{Inspectors, OptionValues, TryValues}
import org.scalatest.exceptions.{StackDepthException, TestFailedException}
import org.scalatest.matchers.should.Matchers

trait SourcingSpec
    extends org.scalatest.wordspec.AnyWordSpecLike
    with Matchers
    with Inspectors
    with OptionValues
    with TryValues {

  class EitherValuable[L, R](either: Either[L, R], pos: source.Position) {
    def rightValue: R =
      either match {
        case Right(value) => value
        case Left(_)      =>
          throw new TestFailedException(
            (_: StackDepthException) => Some("The Either value is not a Right(_)"),
            None,
            pos
          )
      }

    def leftValue: L =
      either match {
        case Left(value) => value
        case Right(_)    =>
          throw new TestFailedException(
            (_: StackDepthException) => Some("The Either value is not a Left(_)"),
            None,
            pos
          )
      }
  }

  implicit def convertEitherToValuable[L, R](either: Either[L, R])(implicit p: source.Position): EitherValuable[L, R] =
    new EitherValuable(either, p)

} 
Example 20
Source File: HttpErrorFunctionsSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import com.github.ghik.silencer.silent
import org.scalacheck.Gen
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.TryValues
import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

import scala.util.Try

@silent("deprecated")
class HttpErrorFunctionsSpec
    extends AnyWordSpec
    with Matchers
    with ScalaCheckDrivenPropertyChecks
    with TableDrivenPropertyChecks
    with TryValues {

  "HttpErrorFunctions" should {
    "return the response if the status code is between 200 and 299" in new HttpErrorFunctions {
      forAll(Gen.choose(200, 299)) { statusCode: Int =>
        val expectedResponse = HttpResponse(statusCode, "")
        handleResponse(exampleVerb, exampleUrl)(expectedResponse) should be(expectedResponse)
      }
    }

    "return the correct exception if the status code is 400" in {
      expectA[BadRequestException](forStatus = 400)
    }

    "return the correct exception if the status code is 404" in {
      expectA[NotFoundException](forStatus   = 404)
    }

    "return the correct exception for all other status codes" in {
      forAll(Gen.choose(0, 199))(expectA[Exception](_))
      forAll(Gen.choose(400, 499).suchThat(!Seq(400, 404).contains(_)))(expectA[Upstream4xxResponse](_, Some(500)))
      forAll(Gen.choose(500, 599))(expectA[Upstream5xxResponse](_, Some(502)))
      forAll(Gen.choose(600, 1000))(expectA[Exception](_))
    }
  }

  val exampleVerb = "GET"
  val exampleUrl  = "http://example.com/something"
  val exampleBody = "this is the string body"

  def expectA[T: Manifest](forStatus: Int, reportStatus: Option[Int] = None): Unit = new HttpErrorFunctions {
    val e =
      Try(handleResponse(exampleVerb, exampleUrl)(HttpResponse(forStatus, exampleBody))).failure.exception
    e            should be(a[T])
    e.getMessage should (include(exampleUrl) and include(exampleVerb) and include(exampleBody))
    reportStatus.map { s =>
      e should have('upstreamResponseCode (forStatus))
      e should have('reportAs (s))
    }
  }
} 
Example 21
Source File: ExceptionSerializerSpec.scala    From reliable-http-client   with Apache License 2.0 5 votes vote down vote up
package rhttpc.transport.json4s

import org.json4s.{DefaultFormats, TypeHints}
import org.scalatest.{FlatSpec, Matchers, TryValues}

class ExceptionSerializerSpec extends FlatSpec with Matchers with TryValues {

  it should "round-trip serialize case class exception" in {
    roundTrip(CaseClassException(123))
  }

  it should "round-trip serialize exception with message" in {
    roundTrip(new ExceptionWithMessage("foo"))
  }

  it should "round-trip serialize exception with null message" in {
    roundTrip(new ExceptionWithMessage(null))
  }

  it should "round-trip serialize exception with message and cause" in {
    roundTrip(new ExceptionWithMessageAndCause("foo", CaseClassException(123)))
  }

  private def roundTrip(ex: Throwable): Unit = {
    implicit val formats = new DefaultFormats {
      override val typeHints: TypeHints = AllTypeHints
    } + ExceptionSerializer
    val serializer = new Json4sSerializer[Throwable]()
    val deserializer = new Json4sDeserializer[Throwable]()
    val serialized = serializer.serialize(ex)
    val deserialized = deserializer.deserialize(serialized)
    deserialized.success.value shouldEqual ex
  }

}

case class CaseClassException(x: Int) extends Exception(s"x: $x")

class ExceptionWithMessage(msg: String) extends Exception(msg) {
  def canEqual(other: Any): Boolean = other.isInstanceOf[ExceptionWithMessage]

  override def equals(other: Any): Boolean = other match {
    case that: ExceptionWithMessage =>
      (that canEqual this) &&
        getMessage == that.getMessage
    case _ => false
  }

  override def hashCode(): Int = {
    val state = Seq(getMessage)
    state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
  }
}

class ExceptionWithMessageAndCause(msg: String, cause: Throwable) extends Exception(msg, cause) {
  def canEqual(other: Any): Boolean = other.isInstanceOf[ExceptionWithMessageAndCause]

  override def equals(other: Any): Boolean = other match {
    case that: ExceptionWithMessageAndCause =>
      (that canEqual this) &&
        getMessage == that.getMessage &&
        getCause == that.getCause
    case _ => false
  }

  override def hashCode(): Int = {
    val state = Seq(getMessage, getCause)
    state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
  }
} 
Example 22
Source File: B3FormatPropagationSpec.scala    From opencensus-scala   with Apache License 2.0 5 votes vote down vote up
package io.opencensus.scala.http.testSuite.propagation

import io.opencensus.scala.http.propagation.B3FormatPropagation
import io.opencensus.trace.BlankSpan
import org.scalatest.TryValues

import scala.util.Failure
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class B3FormatPropagationSpec
    extends AnyFlatSpec
    with Matchers
    with TryValues
    with B3FormatPropagation[(String, String), Map[String, String]] {

  val fakeTraceId = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  val fakeSpanId  = "bbbbbbbbbbbbbbbb"

  "headersWithTracingContext" should "return the correct B3 headers from a spans context" in {
    headersWithTracingContext(BlankSpan.INSTANCE) should contain theSameElementsAs List(
      "X-B3-TraceId" -> "00000000000000000000000000000000",
      "X-B3-SpanId"  -> "0000000000000000"
    )
  }

  behavior of "extractContext"
  it should "return a span context with the values from the B3 http headers" in {
    val request = Map(
      "X-B3-TraceId" -> fakeTraceId,
      "X-B3-SpanId"  -> fakeSpanId,
      "X-B3-Sampled" -> "1"
    )

    val context = extractContext(request).success.value
    context.getTraceId.toLowerBase16 shouldBe fakeTraceId
    context.getSpanId.toLowerBase16 shouldBe fakeSpanId
    context.getTraceOptions.isSampled shouldBe true
  }

  it should "return a failure when the headers are missing" in {
    extractContext(Map.empty) shouldBe a[Failure[_]]
  }

  override def headerValue(
      req: Map[String, String],
      key: String
  ): Option[String] = req.get(key)

  override def createHeader(key: String, value: String): (String, String) =
    (key, value)
} 
Example 23
Source File: TemplateClassSpec.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.codegen.backend.java.inner

import java.util.Optional

import com.daml.ledger.javaapi
import com.squareup.javapoet.{ClassName, ParameterizedTypeName, TypeName}
import javax.lang.model.element.Modifier
import org.scalatest.{FlatSpec, Matchers, OptionValues, TryValues}

import scala.collection.JavaConverters.iterableAsScalaIterableConverter

final class TemplateClassSpec extends FlatSpec with Matchers with OptionValues with TryValues {

  behavior of "TemplateClass.generateFromIdAndRecord"

  it should "generate a public static method" in {
    fromIdAndRecord.modifiers.asScala should contain only (Modifier.STATIC, Modifier.PUBLIC)
  }

  it should "generate a method returning the class itself" in {
    fromIdAndRecord.returnType shouldEqual className
  }

  it should "generate a method taking the expected parameters (with contract key)" in {
    val parameters = fromIdAndRecord.parameters.asScala.map(p => p.name -> p.`type`).toList
    parameters should contain theSameElementsInOrderAs Seq(
      "contractId" -> string,
      "record$" -> record,
      "agreementText" -> optionalString,
      "key" -> optionalContractKey,
      "signatories" -> setOfStrings,
      "observers" -> setOfStrings
    )
  }

  it should "generate a method taking the expected parameters (without contract key)" in {
    val parameters =
      fromIdAndRecordWithoutKey.parameters.asScala.map(p => p.name -> p.`type`).toList
    parameters should contain theSameElementsInOrderAs Seq(
      "contractId" -> string,
      "record$" -> record,
      "agreementText" -> optionalString,
      "signatories" -> setOfStrings,
      "observers" -> setOfStrings)
  }

  private[this] val className = ClassName.bestGuess("Test")
  private[this] val templateClassName = ClassName.bestGuess("Template")
  private[this] val idClassName = ClassName.bestGuess("Id")
  private[this] val ckClassName = ClassName.bestGuess("Ck")
  private[this] val fromIdAndRecord =
    TemplateClass.generateFromIdAndRecord(
      className,
      templateClassName,
      idClassName,
      Some(ckClassName))
  private[this] val fromIdAndRecordWithoutKey =
    TemplateClass.generateFromIdAndRecord(className, templateClassName, idClassName, None)
  private[this] val string = TypeName.get(classOf[String])
  private[this] val record = TypeName.get(classOf[javaapi.data.Record])
  private[this] val optionalString =
    ParameterizedTypeName.get(classOf[Optional[_]], classOf[String])
  private[this] val optionalContractKey =
    ParameterizedTypeName.get(ClassName.get(classOf[Optional[_]]), ckClassName)
  private[this] val setOfStrings =
    ParameterizedTypeName.get(classOf[java.util.Set[_]], classOf[String])

}