org.scalatest.EitherValues Scala Examples

The following examples show how to use org.scalatest.EitherValues. 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: SqsMessageSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.sqs.queue
import java.util.Base64

import com.amazonaws.services.sqs.model.{Message, MessageAttributeValue}
import org.scalatest.EitherValues
import vinyldns.core.TestRecordSetData.pendingCreateAAAA
import vinyldns.core.TestZoneData.zoneChangePending
import vinyldns.core.domain.batch.BatchChangeCommand
import vinyldns.core.protobuf.ProtobufConversions
import vinyldns.sqs.queue.SqsMessageType.{
  SqsBatchChangeMessage,
  SqsRecordSetChangeMessage,
  SqsZoneChangeMessage
}

import scala.collection.JavaConverters._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class SqsMessageSpec extends AnyWordSpec with Matchers with EitherValues with ProtobufConversions {
  import SqsMessage._

  "parseSqsMessage" should {
    "build the command for zone change correctly" in {
      val bytes = toPB(zoneChangePending).toByteArray
      val messageBody = Base64.getEncoder.encodeToString(bytes)
      val msg = new Message()
        .withBody(messageBody)
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsZoneChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(msg).right.value.command shouldBe zoneChangePending
    }

    "build the command for record set change correctly" in {
      val bytes = toPB(pendingCreateAAAA).toByteArray
      val messageBody = Base64.getEncoder.encodeToString(bytes)
      val msg = new Message()
        .withBody(messageBody)
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsRecordSetChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(msg).right.value.command shouldBe pendingCreateAAAA
    }

    "build the command for batch change command correctly" in {
      val batchChangeCommand = BatchChangeCommand("some-id")
      val bytes = batchChangeCommand.id.getBytes
      val messageBody = Base64.getEncoder.encodeToString(bytes)
      val msg = new Message()
        .withBody(messageBody)
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsBatchChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(msg).right.value.command shouldBe batchChangeCommand
    }

    "return EmptySqsMessageContents when processing an empty message" in {
      val message = new Message()
        .withMessageId("test-id")
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsZoneChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(message) shouldBe Left(EmptySqsMessageContents(message.getMessageId))
    }
  }
} 
Example 2
Source File: Issue121.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.unmarshalling.Unmarshaller
import cats.instances.future._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import scala.concurrent.Future
import io.circe._

class Issue121Suite extends FunSuite with Matchers with EitherValues with ScalaFutures with ScalatestRouteTest {
  override implicit val patienceConfig = PatienceConfig(10 seconds, 1 second)

  test("akka-http server can respond with 204") {
    import issues.issue121.server.akkaHttp.{ Handler, Resource }
    val route = Resource.routes(new Handler {
      override def deleteFoo(respond: Resource.DeleteFooResponse.type)(id: Long): Future[Resource.DeleteFooResponse] =
        Future.successful(respond.NoContent)
    })

    Delete("/entity").withEntity(FormData("id" -> "1234").toEntity) ~> route ~> check {
      status should equal(StatusCodes.NoContent)
      response.entity.contentType should equal(ContentTypes.NoContentType)
      response.entity.contentLengthOption should equal(Some(0))
    }
  }

  test("akka-http client can respond with 204") {
    import issues.issue121.client.akkaHttp.Client

    def noContentResponse: HttpRequest => Future[HttpResponse] = _ => Future.successful(HttpResponse(204))

    
    Client
      .httpClient(noContentResponse, "http://localhost:80")
      .deleteFoo(1234)
      .fold(
        _ => failTest("Error"),
        _.fold(
          handleNoContent = ()
        )
      )
      .futureValue
  }
} 
Example 3
Source File: Issue184.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.unmarshalling.Unmarshaller
import cats.instances.future._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import scala.concurrent.Future
import io.circe._


    Delete("/1234?query=2345")
      .withEntity(
        Multipart
          .FormData(
            Multipart.FormData.BodyPart.Strict("form", "3456")
          )
          .toEntity
      ) ~> route ~> check {
      response.status shouldBe (StatusCodes.NoContent)
    }
  }
} 
Example 4
Source File: Issue143.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import _root_.issues.issue143.server.akkaHttp.{ Handler, Resource }
import akka.http.scaladsl.model._
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.scaladsl.Source
import cats.implicits._
import java.io.File
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import scala.concurrent.Future
import scala.concurrent.duration._

class Issue143 extends FunSuite with Matchers with EitherValues with ScalaFutures with ScalatestRouteTest {
  override implicit val patienceConfig = PatienceConfig(10.seconds, 1.second)

  override def testConfigSource =
    s"""
      |akka.loglevel = OFF
    """.stripMargin

  test("Ensure that failed uploads are cleaned up afterwards") {
    val tempDest = File.createTempFile("guardrail.", ".dat")
    val route = Resource.routes(new Handler {
      def uploadFile(
          respond: Resource.UploadFileResponse.type
      )(file: (File, Option[String], akka.http.scaladsl.model.ContentType)): Future[Resource.UploadFileResponse] =
        Future.successful(respond.Created)
      def uploadFileMapFileField(fieldName: String, fileName: Option[String], contentType: akka.http.scaladsl.model.ContentType): java.io.File =
        tempDest
    })

    val chunks        = 1000
    val data          = "foo"
    val contentLength = chunks * data.length
    val req = Post("/file").withEntity(
      Multipart
        .FormData(
          Multipart.FormData.BodyPart(
            "file",
            HttpEntity(
              ContentTypes.`text/plain(UTF-8)`,
              contentLength,
              Source.fromIterator(() => List.fill(chunks)(akka.util.ByteString.fromString(data)).toIterator)
            )
          )
        )
        .toEntity
        .withSizeLimit(1001)
    )

    // Working around https://github.com/akka/akka-http/issues/2381
    // The following test fails under some 2.11.12 configurations
    // (fails in TravisCI, passes in OSX; may be related to filesystem or
    //  other system particulars)
    // req ~> route ~> check {
    //   status should equal(StatusCodes.RequestEntityTooLarge)
    //   tempDest.exists() should equal(false)
    // }

    // The following workaround seems to work:

    val resp = Route.asyncHandler(route).apply(req).futureValue
    resp.status should equal(StatusCodes.RequestEntityTooLarge)
    tempDest.exists() should equal(false)
  }
} 
Example 5
Source File: Http4sTextPlainTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package generators.Http4s.Client.contentType

import _root_.tests.contentTypes.textPlain.client.http4s.foo.FooClient
import _root_.tests.contentTypes.textPlain.client.{ http4s => cdefs }
import _root_.tests.contentTypes.textPlain.server.http4s.foo.{ DoBarResponse, DoBazResponse, DoFooResponse, FooHandler, FooResource }
import _root_.tests.contentTypes.textPlain.server.{ http4s => sdefs }
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import org.http4s.dsl.io._
import org.http4s.headers._
import cats.effect.IO
import org.http4s.client.Client
import org.http4s.{ Charset, HttpRoutes, MediaType }

class Http4sTextPlainTest extends FunSuite with Matchers with EitherValues {
  import org.http4s.implicits._
  test("Plain text should be emitted for required parameters (raw)") {
    val route: HttpRoutes[IO] = HttpRoutes.of {
      case req @ POST -> Root / "foo" =>
        if (req.contentType.contains(`Content-Type`(MediaType.text.plain, Charset.`UTF-8`))) {
          for {
            value <- req.as[String]
            resp  <- if (value == "sample") Created() else NotAcceptable()
          } yield resp
        } else NotAcceptable()
    }
    val client: Client[IO] = Client.fromHttpApp(route.orNotFound)
    val fooClient          = FooClient.httpClient(client)
    fooClient.doFoo("sample").attempt.unsafeRunSync().right.value shouldBe cdefs.foo.DoFooResponse.Created
  }

  test("Plain text should be emitted for optional parameters (raw)") {
    val route: HttpRoutes[IO] = HttpRoutes.of {
      case req @ POST -> Root / "bar" =>
        if (req.contentType.contains(`Content-Type`(MediaType.text.plain, Charset.`UTF-8`))) {
          for {
            value <- req.as[String]
            resp  <- if (value == "sample") Created() else NotAcceptable()
          } yield resp
        } else NotAcceptable()
    }
    val client: Client[IO] = Client.fromHttpApp(route.orNotFound)
    val fooClient          = FooClient.httpClient(client)
    fooClient.doBar(Some("sample")).attempt.unsafeRunSync().right.value shouldBe cdefs.foo.DoBarResponse.Created
  }

  test("Plain text should be emitted for required parameters") {
    val route: HttpRoutes[IO] = new FooResource[IO]().routes(new FooHandler[IO] {
      def doFoo(respond: DoFooResponse.type)(body: String): IO[sdefs.foo.DoFooResponse] =
        if (body == "sample") {
          IO.pure(respond.Created)
        } else {
          IO.pure(respond.NotAcceptable)
        }
      def doBar(respond: DoBarResponse.type)(body: Option[String]): IO[sdefs.foo.DoBarResponse] = ???
      def doBaz(respond: DoBazResponse.type)(body: Option[String]): IO[sdefs.foo.DoBazResponse] = ???
    })

    val client: Client[IO] = Client.fromHttpApp(route.orNotFound)
    val fooClient          = FooClient.httpClient(client)
    fooClient.doFoo("sample").attempt.unsafeRunSync().right.value shouldBe cdefs.foo.DoFooResponse.Created
  }

  test("Plain text should be emitted for present optional parameters") {
    val route: HttpRoutes[IO] = new FooResource[IO]().routes(new FooHandler[IO] {
      def doFoo(respond: DoFooResponse.type)(body: String): IO[sdefs.foo.DoFooResponse] = ???
      def doBar(respond: DoBarResponse.type)(body: Option[String]): IO[sdefs.foo.DoBarResponse] =
        if (body.contains("sample")) {
          IO.pure(respond.Created)
        } else {
          IO.pure(respond.NotAcceptable)
        }
      def doBaz(respond: DoBazResponse.type)(body: Option[String]): IO[sdefs.foo.DoBazResponse] = ???
    })

    val client: Client[IO] = Client.fromHttpApp(route.orNotFound)
    val fooClient          = FooClient.httpClient(client)
    fooClient.doBar(Some("sample")).attempt.unsafeRunSync().right.value shouldBe cdefs.foo.DoBarResponse.Created
  }

  test("Plain text should be emitted for missing optional parameters") {
    val route: HttpRoutes[IO] = new FooResource[IO]().routes(new FooHandler[IO] {
      def doFoo(respond: DoFooResponse.type)(body: String): IO[sdefs.foo.DoFooResponse] = ???
      def doBar(respond: DoBarResponse.type)(body: Option[String]): IO[sdefs.foo.DoBarResponse] =
        if (body.isEmpty) {
          IO.pure(respond.Created)
        } else {
          IO.pure(respond.NotAcceptable)
        }
      def doBaz(respond: DoBazResponse.type)(body: Option[String]): IO[sdefs.foo.DoBazResponse] = ???
    })

    val client: Client[IO] = Client.fromHttpApp(route.orNotFound)
    val fooClient          = FooClient.httpClient(client)
    fooClient.doBar(None).attempt.unsafeRunSync().right.value shouldBe cdefs.foo.DoBarResponse.Created
  }
} 
Example 6
Source File: Http4sCustomHeadersTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package generators.Http4s.RoundTrip

import cats.effect.IO
import org.http4s.client.{ Client => Http4sClient }
import org.http4s.implicits._
import org.scalatest.{ EitherValues, FlatSpec, Matchers }
import tests.customTypes.customHeader.client.http4s.{ definitions => cdefs, Client }
import tests.customTypes.customHeader.server.http4s.Implicits.Formatter
import tests.customTypes.customHeader.server.http4s.{ definitions => sdefs, GetFooResponse, Handler, Resource }

class Http4sCustomHeadersTest extends FlatSpec with Matchers with EitherValues {

  it should "encode custom headers" in {
    Formatter.show(sdefs.Bar.V1) shouldBe "v1"
    Formatter.show(sdefs.Bar.ILikeSpaces) shouldBe "i like spaces"
  }

  it should "round-trip encoded values" in {
    val client = Client.httpClient(
      Http4sClient.fromHttpApp(
        new Resource[IO]()
          .routes(new Handler[IO] {
            override def getFoo(
                respond: GetFooResponse.type
            )(header: String, longHeader: Long, customHeader: sdefs.Bar, customOptionHeader: Option[sdefs.Bar], missingCustomOptionHeader: Option[sdefs.Bar])
                : IO[GetFooResponse] =
              (header, longHeader, customHeader, customOptionHeader, missingCustomOptionHeader) match {
                case ("foo", 5L, sdefs.Bar.V1, Some(sdefs.Bar.V2), None) => IO.pure(respond.Ok)
                case _                                                   => IO.pure(respond.BadRequest)
              }
          })
          .orNotFound
      )
    )

    client.getFoo("foo", 5L, cdefs.Bar.V1, Some(cdefs.Bar.V2), None).attempt.unsafeRunSync().right.value
  }

} 
Example 7
Source File: NullableTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package generators.circe

import org.scalatest.{ EitherValues, FunSuite, Matchers }
import issues.issue315.client.http4s.definitions._
import issues.issue315.client.http4s.support._
import io.circe._
import io.circe.syntax._
class NullableTest extends FunSuite with Matchers with EitherValues {
  val constant   = "constant"
  val defaultObj = TestObject(required = constant, optionalNullable = Presence.Absent)

  test("Nullability should be implemented correctly for required nullable") {
    val json = defaultObj.asJson
    getKey(json, "required-nullable") should equal(Some(Json.Null))
    json.as[TestObject].right.value should equal(defaultObj)

    val obj2  = defaultObj.copy(requiredNullable = Some(constant))
    val json2 = obj2.asJson
    getKey(json2, "required-nullable") should equal(Some(Json.fromString(constant)))
    json2.as[TestObject].right.value should equal(obj2)

    dropKey(json, "required-nullable").as[TestObject] should be('left)
  }

  test("Nullability should be implemented correctly for optional") {
    val json = defaultObj.asJson
    getKey(json, "optional") should equal(None)
    json.asObject.get.keys should not contain ("optional")
    json.as[TestObject].right.value should equal(defaultObj)

    val obj2  = defaultObj.copy(optional = Presence.Present(constant))
    val json2 = obj2.asJson
    getKey(json2, "optional") should equal(Some(Json.fromString(constant)))
    json2.as[TestObject].right.value should equal(obj2)

    val updated = json.asObject.get.add("optional", Json.Null)
    updated.asJson.as[TestObject] should be('left)
  }

  test("Nullability should be implemented correctly for optional legacy") {
    val json = defaultObj.asJson
    getKey(json, "legacy") should equal(Some(Json.Null))
    json.asObject.get.keys should contain("legacy")
    json.as[TestObject].right.value should equal(defaultObj)
    val updated = json.asObject.get.add("legacy", Json.Null)
    updated.asJson.as[TestObject].right.value should equal(defaultObj)

    val obj2  = defaultObj.copy(legacy = Some(constant))
    val json2 = obj2.asJson
    getKey(json2, "legacy") should equal(Some(Json.fromString(constant)))
    json2.as[TestObject].right.value should equal(obj2)
  }

  test("Nullability should be implemented correctly for optional nullable") {
    val json = defaultObj.asJson
    getKey(json, "optional-nullable") should equal(None)
    json.asObject.get.keys should not contain ("optional-nullable")
    json.as[TestObject].right.value should equal(defaultObj)

    val objPresent  = defaultObj.copy(optionalNullable = Presence.Present(None))
    val jsonPresent = objPresent.asJson
    getKey(jsonPresent, "optional-nullable") should equal(Some(Json.Null))
    jsonPresent.as[TestObject].right.value should equal(objPresent)

    val objValue  = defaultObj.copy(optionalNullable = Presence.Present(Some(constant)))
    val jsonValue = objValue.asJson
    getKey(jsonValue, "optional-nullable") should equal(Some(Json.fromString(constant)))
    jsonValue.as[TestObject].right.value should equal(objValue)
  }

  private def getKey(json: Json, key: String): Option[Json] = json.hcursor.downField(key).as[Json].toOption
  private def dropKey(json: Json, key: String): Json =
    json.mapObject(_.filterKeys(_ != key))
} 
Example 8
Source File: Http4sFullTracerTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.Http4s

import _root_.tracer.client.{ http4s => cdefs }
import _root_.tracer.server.http4s.addresses.{ AddressesHandler, AddressesResource, GetAddressResponse, GetAddressesResponse }
import _root_.tracer.server.http4s.users.{ GetUserResponse, UsersHandler, UsersResource }
import _root_.tracer.server.{ http4s => sdefs }
import _root_.tracer.client.http4s.users.UsersClient
import _root_.tracer.client.http4s.addresses.AddressesClient
import _root_.tracer.server.http4s.Http4sImplicits.TraceBuilder
import cats.effect.IO
import org.http4s.{ Header, HttpRoutes, Request }
import org.http4s.client.Client
import org.http4s.implicits._
import org.http4s.syntax.StringSyntax
import org.scalatest.{ EitherValues, FunSuite, Matchers }

class Http4sFullTracerTest extends FunSuite with Matchers with EitherValues with StringSyntax {

  val traceHeaderKey          = "tracer-label"
  def log(line: String): Unit = ()

  def trace: String => Request[IO] => TraceBuilder[IO] = { name => request =>
    // In a real environment, this would be where you could establish a new
    // tracing context and inject that fresh header value.
    log(s"Expecting all requests to have ${traceHeaderKey} header.")
    traceBuilder(request.headers.get(traceHeaderKey.ci).get.value)
  }

  def traceBuilder(parentValue: String): TraceBuilder[IO] = { name => httpClient =>
    Client { req =>
      httpClient.run(req.putHeaders(Header(traceHeaderKey, parentValue)))
    }
  }

  test("full tracer: passing headers through multiple levels") {
    // Establish the "Address" server
    val server2: HttpRoutes[IO] =
      new AddressesResource(trace).routes(
        new AddressesHandler[IO] {
          def getAddress(respond: GetAddressResponse.type)(id: String)(traceBuilder: TraceBuilder[IO]) =
            IO.pure(if (id == "addressId") {
              respond.Ok(sdefs.definitions.Address(Some("line1"), Some("line2"), Some("line3")))
            } else sdefs.addresses.GetAddressResponse.NotFound)
          def getAddresses(respond: GetAddressesResponse.type)()(traceBuilder: TraceBuilder[IO]) =
            IO.pure(sdefs.addresses.GetAddressesResponse.NotFound)
        }
      )

    // Establish the "User" server
    val server1: HttpRoutes[IO] =
      new UsersResource(trace).routes(
        new UsersHandler[IO] {
          // ... using the "Address" server explicitly in the addressesClient
          val addressesClient = AddressesClient.httpClient(Client.fromHttpApp(server2.orNotFound))
          def getUser(respond: GetUserResponse.type)(id: String)(traceBuilder: TraceBuilder[IO]) =
            addressesClient
              .getAddress(traceBuilder, "addressId")
              .map {
                case cdefs.addresses.GetAddressResponse.Ok(address) =>
                  respond.Ok(sdefs.definitions.User("1234", sdefs.definitions.UserAddress(address.line1, address.line2, address.line3)))
                case cdefs.addresses.GetAddressResponse.NotFound => respond.NotFound
              }
        }
      )

    // Build a UsersClient using the User server
    val usersClient = UsersClient.httpClient(Client.fromHttpApp(server1.orNotFound))
    // As this is the entry point, we either have a tracing header from
    // somewhere else, or we generate one for top-level request.
    val testTrace = traceBuilder("top-level-request")

    // Make a request against the mock servers using a hard-coded user ID
    val retrieved: cdefs.users.GetUserResponse = usersClient.getUser(testTrace, "1234").attempt.unsafeRunSync().right.value

    retrieved shouldBe cdefs.users.GetUserResponse
      .Ok(cdefs.definitions.User("1234", cdefs.definitions.UserAddress(Some("line1"), Some("line2"), Some("line3"))))
  }
} 
Example 9
Source File: Issue121.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import cats.effect.IO
import cats.data.Kleisli
import org.http4s._
import org.http4s.client.{ Client => Http4sClient }
import org.http4s.client.blaze._
import org.http4s.headers._
import org.http4s.implicits._
import org.http4s.multipart._
import cats.instances.future._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import io.circe._

class Issue121Suite extends FunSuite with Matchers with EitherValues with ScalaFutures {
  override implicit val patienceConfig = PatienceConfig(10 seconds, 1 second)

  test("http4s server can respond with 204") {
    import issues.issue121.server.http4s.{ DeleteFooResponse, Handler, Resource }

    val route = new Resource[IO]().routes(new Handler[IO] {
      override def deleteFoo(respond: DeleteFooResponse.type)(id: Long): IO[DeleteFooResponse] =
        IO.pure(respond.NoContent)
    })

    val client = Http4sClient.fromHttpApp[IO](route.orNotFound)

    val req = Request[IO](method = Method.DELETE, uri = Uri.unsafeFromString("/entity")).withEntity(UrlForm("id" -> "1234"))

    client
      .fetch(req)({
        case Status.NoContent(resp) =>
          IO.pure({
            resp.status should equal(Status.NoContent)
            resp.contentType should equal(None)
            resp.contentLength should equal(None)
            ()
          })
      })
      .unsafeRunSync()
  }

  test("http4s client can respond with 204") {
    import issues.issue121.client.http4s.Client

    def noContentResponse: Http4sClient[IO] =
      Http4sClient.fromHttpApp[IO](Kleisli.pure(Response[IO](Status.NoContent)))

    
    Client
      .httpClient(noContentResponse, "http://localhost:80")
      .deleteFoo(1234)
      .attempt
      .unsafeRunSync()
      .fold(
        _ => fail("Error"),
        _.fold(
          handleNoContent = ()
        )
      )
  }
} 
Example 10
Source File: Issue542.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import cats.effect.IO
import cats.data.Kleisli
import org.http4s._
import org.http4s.circe._
import org.http4s.client.{ Client => Http4sClient }
import org.http4s.headers._
import org.http4s.implicits._
import cats.instances.future._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import org.scalatest.{ EitherValues, FunSuite, Matchers, OptionValues }
import tests.scalatest.EitherTValues

class Issue542Suite extends FunSuite with Matchers with EitherValues with ScalaFutures with EitherTValues with OptionValues {
  override implicit val patienceConfig = PatienceConfig(10 seconds, 1 second)

  test("base64 bytes can be sent") {
    import base64.server.http4s.{ FooResponse, Handler, Resource }
    import base64.server.http4s.definitions.Foo
    import base64.server.http4s.Implicits.Base64String

    val route = new Resource[IO]().routes(new Handler[IO] {
      def foo(respond: FooResponse.type)(): IO[FooResponse] = IO.pure(respond.Ok(Foo(Some(new Base64String("foo".getBytes())))))
    })

    val client = Http4sClient.fromHttpApp[IO](route.orNotFound)

    val req = Request[IO](method = Method.GET, uri = Uri.unsafeFromString("/foo"))

    client
      .fetch(req)({
        case Status.Ok(resp) =>
          resp.status should equal(Status.Ok)
          resp.contentType should equal(Some(`Content-Type`(MediaType.application.json)))
          resp.contentLength should equal(Some(16))
          jsonOf[IO, Foo].decode(resp, strict = false).rightValue
      })
      .unsafeRunSync()
      .value
      .value
      .data should equal("foo".getBytes())
  }

  test("base64 bytes can be received") {
    import base64.client.http4s.Client
    import base64.client.http4s.definitions.Foo
    import base64.client.http4s.Implicits.Base64String
    import org.http4s.dsl._

    def staticClient: Http4sClient[IO] = {
      implicit val fooOkEncoder = jsonEncoderOf[IO, Foo]
      val response = new Http4sDsl[IO] {
        def route: HttpApp[IO] = Kleisli.liftF(Ok(Foo(Some(Base64String("foo".getBytes())))))
      }
      Http4sClient.fromHttpApp[IO](response.route)
    }

    Client
      .httpClient(staticClient, "http://localhost:80")
      .foo()
      .attempt
      .unsafeRunSync()
      .fold(
        _ => fail("Error"),
        _.fold(
          handleOk = _.value.value.data should equal("foo".getBytes())
        )
      )
  }
} 
Example 11
Source File: Issue455.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import cats.implicits._
import org.http4s.implicits._
import org.scalatest.{ EitherValues, FunSuite, Matchers }
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import cats.effect.Async
import cats.effect.implicits._
import cats.effect.IO
import org.http4s.client.{ Client => Http4sClient }

class Issue455Suite extends FunSuite with Matchers with EitherValues with ScalaFutures {
  override implicit val patienceConfig = PatienceConfig(10 seconds, 1 second)

  test("Circe NPE: https://github.com/circe/circe/issues/561") {
    val route = {
      import issues.issue455.server.http4s.{ BooResponse, Handler, Resource }
      import issues.issue455.server.http4s.definitions.RecursiveData
      new Resource[IO].routes(new Handler[IO] {
        val recData                                                              = RecursiveData(3, "three", Some(RecursiveData(2, "two", Some(RecursiveData(1, "one", None)))))
        def boo(respond: BooResponse.type)(body: RecursiveData): IO[BooResponse] = IO.pure(respond.Ok(recData))
      })
    }
    {
      import issues.issue455.client.http4s.Client
      import issues.issue455.client.http4s.definitions.RecursiveData
      val recData = RecursiveData(3, "three", Some(RecursiveData(2, "two", Some(RecursiveData(1, "one", None)))))
      val client  = Client.httpClient(Http4sClient.fromHttpApp[IO](route.orNotFound))
      val resp    = client.boo(recData).unsafeToFuture.futureValue
      resp.fold(handleOk = {
        case `recData` => ()
        case data      => fail(s"${data} != ${recData}")
      })
    }
  }
} 
Example 12
Source File: AkkaHttpCustomHeadersTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package generators.AkkaHttp.RoundTrip

import akka.actor.ActorSystem
import akka.http.scaladsl.server.{ Route }
import akka.stream.ActorMaterializer
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.SpanSugar._
import org.scalatest.{ EitherValues, FlatSpec, Matchers }
import scala.concurrent.ExecutionContext.Implicits.global
import tests.customTypes.customHeader.client.akkaHttp.Client
import tests.customTypes.customHeader.client.akkaHttp.{ definitions => cdefs }
import tests.customTypes.customHeader.server.akkaHttp.Implicits.Formatter
import tests.customTypes.customHeader.server.akkaHttp.{ definitions => sdefs, Handler, Resource }
import scala.concurrent.Future

class AkkaHttpCustomHeadersTest extends FlatSpec with Matchers with ScalaFutures with EitherValues {

  override implicit val patienceConfig = PatienceConfig(10 seconds, 1 second)

  it should "encode custom headers" in {
    Formatter.show(sdefs.Bar.V1) shouldBe "v1"
    Formatter.show(sdefs.Bar.ILikeSpaces) shouldBe "i like spaces"
  }

  it should "round-trip encoded values" in {
    implicit val as  = ActorSystem()
    implicit val mat = ActorMaterializer()
    val client = Client.httpClient(Route.asyncHandler(Resource.routes(new Handler {
      def getFoo(respond: Resource.GetFooResponse.type)(
          header: String,
          longHeader: Long,
          customHeader: sdefs.Bar,
          customOptionHeader: Option[sdefs.Bar],
          missingCustomOptionHeader: Option[sdefs.Bar]
      ): Future[Resource.GetFooResponse] =
        (header, longHeader, customHeader, customOptionHeader, missingCustomOptionHeader) match {
          case ("foo", 5L, sdefs.Bar.V1, Some(sdefs.Bar.V2), None) => Future.successful(respond.OK)
          case _                                                   => Future.successful(respond.BadRequest)
        }
    })))

    client.getFoo("foo", 5L, cdefs.Bar.V1, Some(cdefs.Bar.V2), None).value.futureValue.right.value
  }

} 
Example 13
Source File: UserChangeSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.core.domain.membership
import cats.scalatest.EitherMatchers
import org.joda.time.DateTime
import org.scalatest.EitherValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class UserChangeSpec extends AnyWordSpec with Matchers with EitherMatchers with EitherValues {

  private val newUser = User("foo", "key", "secret")
  private val currentDate = DateTime.now

  "apply" should {
    "succeed for CreateUser" in {
      val result = UserChange("foo", newUser, "bar", currentDate, None, UserChangeType.Create)
      result shouldBe Right(UserChange.CreateUser(newUser, "bar", currentDate, "foo"))
    }
    "succeed for UpdateUser" in {
      val result =
        UserChange("foo", newUser, "bar", currentDate, Some(newUser), UserChangeType.Update)
      result shouldBe Right(UserChange.UpdateUser(newUser, "bar", currentDate, newUser, "foo"))
    }
    "fail for invalid parameters" in {
      val result = UserChange("foo", newUser, "bar", currentDate, None, UserChangeType.Update)
      result shouldBe left
      result.left.value shouldBe an[IllegalArgumentException]
    }
  }
} 
Example 14
Source File: ErrorsSuite.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu

import cats.instances.either.catsStdInstancesForEither
import cats.syntax.either._
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import tofu.syntax.error._

class ErrorsSuite extends AnyFlatSpec with Matchers with EitherValues {

  "Raise" should "reRaise" in {
    val err: String = "oops"
    Raise[ErrorOr, String].reRaise(toErr[ErrorOr[Unit]](err)) shouldBe toErr[Unit](err)
  }

  "Errors" should "adoptError" in {
    val err: String                         = "oops"
    val pf: PartialFunction[String, String] = { case s if s == err => err + "_" + err }
    val fa: ErrorOr[Unit]                   = Raise[ErrorOr, String].raise(err)
    implicit val errors                     = Errors[ErrorOr, String]
    fa.adaptError(pf) shouldBe toErr(pf(err))
  }

  type ErrorOr[A] = Either[String, A]

  private def toErr[A](err: String): ErrorOr[A] = err.asLeft[A]
} 
Example 15
Source File: ProcessConfigReaderTest.scala    From stryker4s   with Apache License 2.0 5 votes vote down vote up
package stryker4s.config

import org.scalatest.EitherValues
import pureconfig.error.{ConfigReaderFailures, ConvertFailure, KeyNotFound}
import stryker4s.command.config.ProcessRunnerConfig
import stryker4s.run.process.Command
import stryker4s.scalatest.FileUtil
import stryker4s.testutil.Stryker4sSuite
import pureconfig.generic.auto._

class ProcessConfigReaderTest extends Stryker4sSuite with EitherValues {
  describe("ProcessConfig") {
    it("should read a process config") {
      val confPath = FileUtil.getResource("config/filledProcess.conf")

      val result = ConfigReader.readConfigOfType[ProcessRunnerConfig](confPath).getOrElse(fail())

      result.testRunner should equal(Command("gradle", "test"))
    }

    it("should read an empty config to errors") {
      val confPath = FileUtil.getResource("config/empty.conf")

      val result = ConfigReader.readConfigOfType[ProcessRunnerConfig](confPath)

      result.left.value should matchPattern {
        case ConfigReaderFailures(ConvertFailure(KeyNotFound("test-runner", _), _, _), _*) =>
      }
    }
  }
} 
Example 16
Source File: AliasSpecification.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.account

import com.wavesplatform.{EitherMatchers, NoShrink, TransactionGen}
import org.scalatest.{EitherValues, Matchers, PropSpec}
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class AliasSpecification extends PropSpec with PropertyChecks with Matchers with EitherMatchers with TransactionGen with NoShrink with EitherValues {

  property("Correct alias should be valid") {
    forAll(validAliasStringGen) { s =>
      Alias.create(s) should beRight
    }
  }

  property("Incorrect alias should be invalid") {
    forAll(invalidAliasStringGen) { s =>
      Alias.create(s) should beLeft
    }
  }
} 
Example 17
Source File: GenericElementDecoderSpec.scala    From phobos   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.phobos.traverse

import cats.syntax.either._
import com.softwaremill.diffx.scalatest.DiffMatcher
import org.scalatest.EitherValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import ru.tinkoff.phobos.ast.XmlLeaf
import ru.tinkoff.phobos.decoding.{DecodingError, ElementDecoder, XmlDecoder}

class GenericElementDecoderSpec extends AnyWordSpec with Matchers with DiffMatcher with EitherValues {
  import GenericElementDecoderSpec._
  "GenericElementDecoder" should {
    "work correctly with immutable accumulators" in {
      implicit val decodeAllAttributes: ElementDecoder[Acc] = GenericElementDecoder(ImmutableTraversalLogic)
      val xmlDecoder = XmlDecoder
        .fromElementDecoder[Acc]("ast")

      val sampleXml =
        """<?xml version='1.0' encoding='UTF-8'?><ans1:ast xmlns:ans1="https://tinkoff.ru" foo="5"><bar>bazz</bar><array foo2="true" foo3="false"><elem>11111111111111</elem><elem>11111111111112</elem></array><nested x="2.0"><scala>2.13</scala><dotty>0.13</dotty><scala-4/></nested></ans1:ast>"""

      val expectedResult0 = Acc(
        Map(
          "foo"  -> "5",
          "foo2" -> "true",
          "foo3" -> "false",
          "x"    -> "2.0"
        )
      )

      xmlDecoder.decode(sampleXml) should matchTo(expectedResult0.asRight[DecodingError])

      val xmlWithoutAttrs =
        """<?xml version='1.0' encoding='UTF-8'?><ans1:ast xmlns:ans1="https://tinkoff.ru"><bar>bazz</bar><array><elem>11111111111111</elem><elem>11111111111112</elem></array><nested><scala>2.13</scala><dotty>0.13</dotty><scala-4/></nested></ans1:ast>"""

      val expectedResult1 = Acc(Map.empty)

      xmlDecoder.decode(xmlWithoutAttrs) should matchTo(expectedResult1.asRight[DecodingError])
    }
  }
}

object GenericElementDecoderSpec {
  case class Acc(attributes: Map[String, String])

  object ImmutableTraversalLogic extends DecodingTraversalLogic[Acc, Acc] {
    override def newAcc(): Acc = Acc(Map.empty)

    override def onFinish(acc: Acc): Acc = acc

    override def onAttributes(acc: Acc, attributes: List[(String, XmlLeaf)]): Acc = {
      acc.copy(
        attributes = acc.attributes ++ attributes.map { case (name, leaf) => name -> leaf.value.toString }
      )
    }

    override def combine(acc: Acc, field: String, intermediateResult: Acc): Acc = {
      acc.copy(attributes = acc.attributes ++ intermediateResult.attributes)
    }
  }
} 
Example 18
Source File: XmlEntryElementDecoderSpec.scala    From phobos   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.phobos.ast

import com.softwaremill.diffx.scalatest.DiffMatcher
import org.scalatest.EitherValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import ru.tinkoff.phobos.Namespace
import ru.tinkoff.phobos.decoding.{DecodingError, XmlDecoder}
import cats.syntax.either._

class XmlEntryElementDecoderSpec extends AnyWordSpec with Matchers with DiffMatcher with EitherValues {

  "XmlEntry decoder" should {
    "decodes simple Xml into ast correctly" in {
      val sampleXml                = """<?xml version='1.0' encoding='UTF-8'?><ast foo="5"><bar>bazz</bar></ast>"""
      val decodedAst               = XmlDecoder.fromElementDecoder[XmlEntry]("ast").decode(sampleXml).right.value
      val expectedResult: XmlEntry = xml(attr("foo") := 5, node("bar") := "bazz")

      decodedAst should matchTo(expectedResult)
    }

    "decodes complicated Xml into ast correctly" in {
      case object tinkoff {
        type ns = tinkoff.type
        implicit val ns: Namespace[tinkoff.type] = Namespace.mkInstance("https://tinkoff.ru")
      }

      val sampleXml =
        """<?xml version='1.0' encoding='UTF-8'?><ans1:ast xmlns:ans1="https://tinkoff.ru" foo="5"><bar>bazz</bar><array foo2="true" foo3="false"><elem>11111111111111</elem><elem>11111111111112</elem></array><nested><scala>2.13</scala><dotty>0.13</dotty><scala-4/></nested></ans1:ast>"""

      val decodedAst = XmlDecoder.fromElementDecoderNs[XmlEntry, tinkoff.ns]("ast").decode(sampleXml)
      val expectedResult: XmlEntry = xml(attr("foo") := 5)(
        node("bar") := "bazz",
        node("array") := xml(
          attr("foo2") := true,
          attr("foo3") := false
        )(
          node("elem") := 11111111111111L,
          node("elem") := 11111111111112L
        ),
        node("nested") := xml(
          node("scala") := 2.13,
          node("dotty") := 0.13,
          node("scala-4") := xml.empty
        )
      )

      decodedAst should matchTo(expectedResult.asRight[DecodingError])
    }

    "works fine when for elements with same name" in {

      val n: XmlEntry = xml(
        node("k") :=
          xml(
            node("k") := "gbq"
          )
      )

      val encoded = ru.tinkoff.phobos.encoding.XmlEncoder.fromElementEncoder[XmlEntry]("ast").encode(n)

      val result = XmlDecoder
        .fromElementDecoder[XmlEntry]("ast")
        .decode(
          encoded
        )

      result.map(util.AstTransformer.sortNodeValues) should matchTo(
        util.AstTransformer.sortNodeValues(n).asRight[DecodingError]
      )
    }
  }
} 
Example 19
Source File: HiveParsingErrorsSpec.scala    From vizsql   with Apache License 2.0 5 votes vote down vote up
package com.criteo.vizatra.vizsql.hive

import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{EitherValues, Matchers, PropSpec}

class HiveParsingErrorsSpec extends PropSpec with Matchers with EitherValues {

  val invalidSQL99SelectStatements = TableDrivenPropertyChecks.Table(
    ("SQL", "Expected error"),

    (
      "select bucket from t",
      """select bucket from t
        |       ^
        |Error: *, table or expression expected
      """
    ),
    (
      "select foo from tbl limit 100 order by foo",
      """select foo from tbl limit 100 order by foo
        |                              ^
        |Error: ; expected
      """
    ),
    (
      "select foo from bar tablesample (bucket 2 out af 3)",
      """select foo from bar tablesample (bucket 2 out af 3)
        |                                              ^
        |Error: of expected
      """.stripMargin
    )
  )

  // --

  property("report parsing errors on invalid Hive statements") {
    TableDrivenPropertyChecks.forAll(invalidSQL99SelectStatements) {
      case (sql, expectedError) =>
        new HiveDialect(Map.empty).parser.parseStatement(sql)
          .fold(_.toString(sql, ' ').trim, _ => "[NO ERROR]") should be (expectedError.toString.stripMargin.trim)
    }
  }

} 
Example 20
Source File: ParsingErrorsSpec.scala    From vizsql   with Apache License 2.0 5 votes vote down vote up
package com.criteo.vizatra.vizsql

import sql99._
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{Matchers, EitherValues, PropSpec}

class ParsingErrorsSpec extends PropSpec with Matchers with EitherValues {

  val invalidSQL99SelectStatements = TableDrivenPropertyChecks.Table(
    ("SQL", "Expected error"),

    (
      """xxx""",
      """|xxx
         |^
         |Error: select expected
      """
    ),
    (
      """select""",
      """|select
         |      ^
         |Error: *, table or expression expected
      """
    ),
    (
      """select 1 +""",
      """|select 1 +
         |          ^
         |Error: expression expected
      """
    ),
    (
      """select 1 + *""",
      """|select 1 + *
         |           ^
         |Error: expression expected
      """
    ),
    (
      """select (1 + 3""",
      """|select (1 + 3
         |             ^
         |Error: ) expected
      """
    ),
    (
      """select * from""",
      """|select * from
         |             ^
         |Error: table, join or subselect expected
      """
    ),
    (
      """select * from (selet 1)""",
      """|select * from (selet 1)
         |               ^
         |Error: select expected
      """
    ),
    (
      """select * from (select 1sh);""",
      """|select * from (select 1sh);
         |                          ^
         |Error: ident expected
      """
    ),
    (
      """select * from (select 1)sh)""",
      """|select * from (select 1)sh)
         |                          ^
         |Error: ; expected
      """
    ),
    (
      """SELECT CustomerName; City FROM Customers;""",
      """|SELECT CustomerName; City FROM Customers;
         |                     ^
         |Error: end of statement expected
      """
    ),
    (
      """SELECT CustomerName FROM Customers UNION ALL""",
      """|SELECT CustomerName FROM Customers UNION ALL
         |                                            ^
         |Error: select expected
      """
    )
  )

  // --

  property("report parsing errors on invalid SQL-99 SELECT statements") {
    TableDrivenPropertyChecks.forAll(invalidSQL99SelectStatements) {
      case (sql, expectedError) =>
        (new SQL99Parser).parseStatement(sql)
          .fold(_.toString(sql, ' ').trim, _ => "[NO ERROR]") should be (expectedError.toString.stripMargin.trim)
    }
  }

} 
Example 21
Source File: ParseVerticaDialectSpec.scala    From vizsql   with Apache License 2.0 5 votes vote down vote up
package com.criteo.vizatra.vizsql

import com.criteo.vizatra.vizsql.vertica._
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{EitherValues, Matchers, PropSpec}

class ParseVerticaDialectSpec extends PropSpec with Matchers with EitherValues {

  val validVerticaSelectStatements = TableDrivenPropertyChecks.Table(
    ("SQL", "Expected Columns"),
    ("""SELECT
       |   NOW() as now,
       |   MAX(last_update) + 3599 / 86400 AS last_update,
       |   CONCAT('The most recent update was on ', TO_CHAR(MAX(last_update) + 3599 / 86400, 'YYYY-MM-DD at HH:MI')) as content
       |FROM
       |    City""".stripMargin,
      List(
        Column("now", TIMESTAMP(nullable = false)),
        Column("last_update", TIMESTAMP(nullable = false)),
        Column("content", STRING(nullable = false))
      ))
  )

  // --

  val SAKILA = DB(schemas = List(
    Schema(
      "sakila",
      tables = List(
        Table(
          "City",
          columns = List(
            Column("city_id", INTEGER(nullable = false)),
            Column("city", STRING(nullable = false)),
            Column("country_id", INTEGER(nullable = false)),
            Column("last_update", TIMESTAMP(nullable = false))
          )
        ),
        Table(
          "Country",
          columns = List(
            Column("country_id", INTEGER(nullable = false)),
            Column("country", STRING(nullable = false)),
            Column("last_update", TIMESTAMP(nullable = false))
          )
        )
      )
    )
  ))

  // --

  property("extract Vertica SELECT statements columns") {
    TableDrivenPropertyChecks.forAll(validVerticaSelectStatements) {
      case (sql, expectedColumns) =>
        VizSQL.parseQuery(sql, SAKILA)
          .fold(e => sys.error(s"Query doesn't parse: $e"), identity)
          .columns
          .fold(e => sys.error(s"Invalid query: $e"), identity) should be (expectedColumns)
    }
  }

} 
Example 22
Source File: SchemaErrorsSpec.scala    From vizsql   with Apache License 2.0 5 votes vote down vote up
package com.criteo.vizatra.vizsql

import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{EitherValues, Matchers, PropSpec}
import sql99._


class SchemaErrorsSpec extends PropSpec with Matchers with EitherValues {

    val invalidSQL99SelectStatements = TableDrivenPropertyChecks.Table(
      ("SQL", "Expected error"),
      (
        "SELECT region from City as C1 JOIN Country as C2 ON C1.country_id = C2.country_id WHERE region < 42",
        SchemaError("ambiguous column region", 6)
      ),(
        "SELECT nonexistent, region from City",
        SchemaError("column not found nonexistent", 6)
        )
    )

    // --

    val SAKILA = DB(schemas = List(
      Schema(
        "sakila",
        tables = List(
          Table(
            "City",
            columns = List(
              Column("city_id", INTEGER(nullable = false)),
              Column("city", STRING(nullable = false)),
              Column("country_id", INTEGER(nullable = false)),
              Column("last_update", TIMESTAMP(nullable = false)),
              Column("region", INTEGER(nullable = false))
            )
          ),
          Table(
            "Country",
            columns = List(
              Column("country_id", INTEGER(nullable = false)),
              Column("country", STRING(nullable = false)),
              Column("last_update", TIMESTAMP(nullable = false)),
              Column("region", INTEGER(nullable = false))
            )
          )
        )
      )
    ))

    // --

    property("report schema errors on invalid SQL-99 SELECT statements") {
      TableDrivenPropertyChecks.forAll(invalidSQL99SelectStatements) {
        case (sql, expectedError) =>
          VizSQL.parseQuery(sql, SAKILA)
            .fold(
              e => sys.error(s"Query doesn't parse: $e"),
              _.error.getOrElse(sys.error(s"Query should not type!"))
            ) should be (expectedError)
      }
    }

  } 
Example 23
Source File: OriginSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.binders

import org.scalatest.{EitherValues, Matchers, OptionValues, WordSpecLike}
import uk.gov.hmrc.play.binders.Origin._

class OriginSpec extends WordSpecLike with Matchers with EitherValues with OptionValues {

  "Origin" should {

    "be valid" in {
      Origin("testing1").origin                   shouldBe "testing1"
      Origin("Testing1").origin                   shouldBe "Testing1"
      Origin("test-ing1").origin                  shouldBe "test-ing1"
      Origin("tesA.ing1").origin                  shouldBe "tesA.ing1"
      Origin(List.fill(100)('0').mkString).origin shouldBe List.fill(100)('0').mkString
    }

    "be invalid" in {
      an[IllegalArgumentException] should be thrownBy Origin("withInvalidCharacters!")
      an[IllegalArgumentException] should be thrownBy Origin("with white spaces")
      an[IllegalArgumentException] should be thrownBy Origin("")
      an[IllegalArgumentException] should be thrownBy Origin(List.fill(101)('0').mkString)
    }
  }

  "Origin binder" should {

    "default when origin has invalid characters" in {
      queryBinder.bind("origin", Map("origin" -> Seq("!asdasd"))).value.right.value should be(Origin("unknown"))
    }

    "default when no origin supplied" in {
      queryBinder.bind("origin", Map("origin" -> Seq.empty)).value.right.value should be(Origin("unknown"))
    }

    "take the first when two origins supplied" in {
      queryBinder.bind("origin", Map("origin" -> Seq("origin1", "origin2"))).value.right.value should be(
        Origin("origin1"))
    }

    "create origin" in {
      queryBinder.bind("origin", Map("origin" -> Seq("theOrigin"))).value.right.value should be(Origin("theOrigin"))
    }

  }

  "Unbinding a continue URL" should {
    "return the value" in {
      queryBinder.unbind("origin", Origin("tax-account-router")) should be("origin=tax-account-router")
    }
  }

} 
Example 24
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 25
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 26
Source File: ParserTests.scala    From circe-yaml   with Apache License 2.0 5 votes vote down vote up
package io.circe.yaml

import io.circe.Json
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import io.circe.syntax._
import org.scalatest.matchers.should.Matchers

class ParserTests extends AnyFlatSpec with Matchers with EitherValues {
  // the laws should do a pretty good job of surfacing errors; these are mainly to ensure test coverage

  "Parser" should "fail on invalid tagged numbers" in {
    assert(parser.parse("!!int 12foo").isLeft)
  }

  it should "fail to parse complex keys" in {
    assert(parser.parse("""
        |? - foo
        |  - bar
        |: 1
      """.stripMargin).isLeft)
  }

  it should "fail to parse invalid YAML" in {
    assert(
      parser
        .parse(
          """foo: - bar"""
        )
        .isLeft
    )
  }

  it should "parse yes as true" in {
    assert(
      parser
        .parse(
          """foo: yes"""
        )
        .isRight
    )
  }

  it should "parse hexadecimal" in {
    assert(
      parser
        .parse(
          """[0xFF, 0xff, 0xab_cd]"""
        )
        .contains(Seq(0xFF, 0xff, 0xabcd).asJson)
    )
  }

  it should "parse decimal with underscore breaks" in {
    assert(
      parser
        .parse(
          """foo: 1_000_000"""
        )
        .contains(Map("foo" -> 1000000).asJson)
    )
  }

  it should "parse empty string as false" in {
    assert(
      parser
        .parse(
          ""
        )
        .right
        .value == Json.False
    )
  }

  it should "parse blank string as false" in {
    assert(
      parser
        .parse(
          "   "
        )
        .right
        .value == Json.False
    )
  }
} 
Example 27
Source File: PatchSpec.scala    From sonar-scala   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.mwz.sonar.scala.pr

import scala.io.Source

import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

class PatchSpec extends AnyFlatSpec with Matchers with EitherValues with ScalaCheckDrivenPropertyChecks {

  def patch(path: String): String =
    Source
      .fromResource(path)
      .getLines()
      .mkString("\n")

  it should "fail to parse an invalid patch" in {
    forAll((s: String) => Patch.parse(s) shouldBe Left(PatchError(s)))
  }

  it should "parse successfully a patch with additions only" in {
    val expected: Map[FileLine, PatchLine] =
      (69 to 84).zipWithIndex.map {
        case (fileLine, index) =>
          (FileLine(fileLine), PatchLine(index + 1))
      }.toMap

    Patch.parse(patch("patches/add.patch")).right.value shouldBe expected
  }

  it should "parse successfully a patch with deletions only" in {
    val expected: Map[FileLine, PatchLine] =
      List(
        List(26 -> 1, 27 -> 2, 28 -> 3, 29 -> 6, 30 -> 7, 31 -> 8),
        List(43 -> 10, 44 -> 11, 45 -> 12, 46 -> 15, 47 -> 16, 48 -> 20, 49 -> 21, 50 -> 22)
      ).flatten.map {
        case (k, v) =>
          FileLine(k) -> PatchLine(v)
      }.toMap

    Patch.parse(patch("patches/del.patch")).right.value shouldBe expected
  }

  it should "parse successfully a patch with additions, deletions and modifications" in {
    val expected: Map[FileLine, PatchLine] =
      List(
        (43 to 50).zipWithIndex.map(a => (a._1, a._2 + 1)),
        List(60 -> 10, 61 -> 11, 62 -> 12, 63 -> 15, 64 -> 16, 65 -> 17),
        List(77 -> 19, 78 -> 20, 79 -> 21, 80 -> 23, 81 -> 24, 82 -> 25, 83 -> 26)
      ).flatten.map {
        case (k, v) =>
          FileLine(k) -> PatchLine(v)
      }.toMap

    Patch.parse(patch("patches/add-del-mod.patch")).right.value shouldBe expected
  }
} 
Example 28
Source File: NrsSubmissionHttpParserSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.httpparsers

import org.scalatest.EitherValues
import play.api.http.Status._
import play.api.libs.json.Json
import uk.gov.hmrc.http.HttpResponse
import uk.gov.hmrc.vatapi.UnitSpec
import uk.gov.hmrc.vatapi.assets.TestConstants.NRSResponse._
import uk.gov.hmrc.vatapi.httpparsers.NrsSubmissionHttpParser.NrsSubmissionOutcomeReads.read


class NrsSubmissionHttpParserSpec extends UnitSpec with EitherValues {

    val successResponse = HttpResponse(ACCEPTED, responseJson = Some(nrsResponseJson))
    val successBadJsonResponse = HttpResponse(NOT_FOUND, responseJson = Some(Json.toJson("{}")))
    val failureResponse = HttpResponse(BAD_REQUEST, responseJson = Some(Json.toJson("{}")))

  "NrsSubmissionOutcome#read" when {
    "the response is OK" should {
      "return NrsData" when {
        "the Json returned is valid" in {
          read("", "", successResponse).right.value shouldBe nrsClientData.copy(timestamp = "")
        }

      }
      "return NrsError" when {
        "the Json returned is not valid" in {
          read("", "", successBadJsonResponse).right.value shouldBe EmptyNrsData
        }
      }
    }

    "the response status is not OK" should {
      "return NrsError" in {
        read("", "", failureResponse).left.value shouldBe NrsError
      }
    }
  }

} 
Example 29
Source File: IntermediateTraitsTest.scala    From circe-magnolia   with Apache License 2.0 5 votes vote down vote up
package io.circe.magnolia.incompat


import io.circe._
import io.circe.magnolia.CirceMagnoliaSuite
import org.scalatest.EitherValues


class IntermediateTraitsTest extends CirceMagnoliaSuite with EitherValues {

  sealed trait T
  case class A(a: Int) extends T
  case class B(b: String) extends T
  sealed trait C extends T
  case class C1(c1: Int) extends C
  case class C2(c2: String) extends C


  import io.circe.magnolia.derivation.encoder.auto._
  import io.circe.magnolia.derivation.decoder.auto._

  val encoder = Encoder[T]
  val decoder = Decoder[T]

  // here JSON is deeper nested than when using circe-generic.
  // it's not that huge problem, until you try to decode a leaf, that is under an intermediate trait (next test)
  "Magnolia encoder" should "skip intermediate traits" in {
    val json = encoder(C1(5))
    val j = json.hcursor.get[JsonObject]("C1")
    assert(j.isRight, j)
  }

  // when sending a message to JSON API we don't usually specify intermediate traits -
  // we just put the leaf type into the key.
  // Magnolia can't see the C1, because on the first dispatch it faces only A, B and C.
  "Magnolia decoder" should "skip intermediate traits" in {
    val json = Json.obj("C1" -> Json.obj("c1" -> Json.fromInt(2)))
    val j = decoder(HCursor.fromJson(json))
    assert(j.isRight, j)
  }
} 
Example 30
Source File: EventualPayloadAndTypeSpec.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.eventual


import cats.implicits._
import com.evolutiongaming.kafka.journal._
import org.scalatest.EitherValues
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{Json => PlayJson}
import scodec.bits.ByteVector

import scala.util.Try

class EventualPayloadAndTypeSpec extends AnyFunSuite with Matchers with EitherValues {

  implicit val jsonCodec: JsonCodec[Try] = JsonCodec.default[Try]

  private val eventualWrite = EventualWrite.summon[Try, Payload]
  private val eventualRead = EventualRead.summon[Try, Payload]

  for {
    (name, payload) <- List(
      ("text", Payload.text("text")),
      ("binary", PayloadBinaryFromStr("binary")),
      ("json", Payload.json("json"))
    )
  } {
    test(s"toEventual & fromEventual, payload: $name") {
      val actual = for {
        payloadAndType <- eventualWrite(payload)
        actual <- eventualRead(payloadAndType)
      } yield actual

      actual shouldBe payload.pure[Try]
    }
  }

  test("toEventual: binary") {
    val payload = PayloadBinaryFromStr("binary")

    val eventual = eventualWrite(payload)

    eventual shouldBe EventualPayloadAndType(payload.value.asRight, PayloadType.Binary).pure[Try]
  }

  test("toEventual: text") {
    val payload = Payload.Text("text")

    val eventual = eventualWrite(payload)

    eventual shouldBe EventualPayloadAndType("text".asLeft, PayloadType.Text).pure[Try]
  }

  test("toEventual: json") {
    val payload = Payload.Json(PlayJson.obj("key" -> "value"))

    val eventual = eventualWrite(payload)

    eventual shouldBe EventualPayloadAndType("""{"key":"value"}""".asLeft, PayloadType.Json).pure[Try]
  }

  test("fromEventual: returns an error for payload type binary and payload string") {
    val payloadAndType = EventualPayloadAndType("text".asLeft, PayloadType.Binary)

    val result = eventualRead(payloadAndType).toEither

    result.left.value shouldBe a[JournalError]
    result.left.value.getMessage should include("Bytes expected")
  }

  test("fromEventual: returns an error for payload type text and payload bytes") {
    val payloadAndType = EventualPayloadAndType(ByteVector.empty.asRight, PayloadType.Text)

    val result = eventualRead(payloadAndType).toEither

    result.left.value shouldBe a[JournalError]
    result.left.value.getMessage should include("String expected")
  }

  test("fromEventual: returns an error for payload type json and payload bytes") {
    val payloadAndType = EventualPayloadAndType(ByteVector.empty.asRight, PayloadType.Json)

    val result = eventualRead(payloadAndType).toEither

    result.left.value shouldBe a[JournalError]
    result.left.value.getMessage should include("String expected")
  }
} 
Example 31
Source File: EventualPayloadAndTypeSpec.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.circe

import cats.implicits._
import com.evolutiongaming.kafka.journal.TestJsonCodec.instance
import com.evolutiongaming.kafka.journal._
import com.evolutiongaming.kafka.journal.circe.Instances._
import com.evolutiongaming.kafka.journal.eventual._
import io.circe.{Json => CirceJson}
import org.scalatest.EitherValues
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{Json => PlayJson}
import scodec.bits.ByteVector

import scala.util.Try

class EventualPayloadAndTypeSpec extends AnyFunSuite with Matchers with EitherValues {

  private val playEventualWrite = EventualWrite.summon[Try, Payload]
  private val circeEventualRead = EventualRead.summon[Try, CirceJson]

  for {
    (playPayload, circePayload) <- List(
      (Payload.json(PlayJson.obj(("key", "value"))), CirceJson.obj("key" -> CirceJson.fromString("value")))
    )
  } {
    test(s"toEventual with Play, fromEventual with Circe") {
      val actual = for {
        payloadAndType <- playEventualWrite(playPayload)
        actual         <- circeEventualRead(payloadAndType)
      } yield actual

      actual shouldBe circePayload.pure[Try]
    }
  }

  for {
    (name, payloadAndType) <- List(
      ("binary", EventualPayloadAndType(ByteVector.empty.asRight, PayloadType.Binary)),
      ("text", EventualPayloadAndType("text".asLeft, PayloadType.Text))
    )
  } {
    test(s"fromEventual: returns an error for non-json payload type: $name") {
      val result = circeEventualRead(payloadAndType).toEither

      result.left.value shouldBe a[JournalError]
      result.left.value.getMessage should include(payloadAndType.payloadType.toString)
    }
  }

  test("fromEventual: returns an error for payload type json and payload bytes") {
    val payloadAndType = EventualPayloadAndType(ByteVector.empty.asRight, PayloadType.Json)

    val result = circeEventualRead(payloadAndType).toEither

    result.left.value shouldBe a[JournalError]
    result.left.value.getMessage should include("String expected")
  }

  test("fromEventual: returns an error for malformed json") {
    val malformed = "{\"key\": {sss}}"
    val payloadAndType = EventualPayloadAndType(malformed.asLeft, PayloadType.Json)

    val result = circeEventualRead(payloadAndType).toEither

    result.left.value shouldBe a[JournalError]
    result.left.value.getMessage should (include("ParsingFailure") and include("sss"))
  }

} 
Example 32
Source File: UnitSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package support

import org.scalatest.EitherValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import play.api.http.{HeaderNames, MimeTypes, Status}
import play.api.mvc.ControllerComponents
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FutureAwaits, ResultExtractors}
import uk.gov.hmrc.http.HeaderCarrier

import scala.util.control.NoStackTrace

trait UnitSpec extends AnyWordSpecLike
  with EitherValues
  with Matchers
  with FutureAwaits
  with DefaultAwaitTimeout
  with ResultExtractors
  with HeaderNames
  with Status
  with MimeTypes {

  lazy val controllerComponents: ControllerComponents = stubControllerComponents()

  implicit val hc: HeaderCarrier = HeaderCarrier()

  val testException: Throwable = new NoStackTrace {
    override def getMessage: String = "A test exception was thrown"
  }
} 
Example 33
Source File: ContinueUrlSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.binders

import org.scalatest.{EitherValues, Matchers, OptionValues, WordSpecLike}
import uk.gov.hmrc.play.binders.ContinueUrl._

class ContinueUrlSpec extends WordSpecLike with Matchers with EitherValues with OptionValues {

  "isAbsoluteUrl" should {
    "return true for an absolute URL" in {
      ContinueUrl("http://www.example.com").isAbsoluteUrl shouldBe true
    }

    "return false for a relative URL" in {
      ContinueUrl("/service/page").isAbsoluteUrl shouldBe false
    }
  }

  "isRelativeUrl" should {
    "return false for an absolute URL" in {
      ContinueUrl("http://www.example.com").isRelativeUrl shouldBe false
    }

    "return true for a relative URL" in {
      ContinueUrl("/service/page").isRelativeUrl shouldBe true
    }
  }

  "not work for protocol-relative urls" in {
    an[IllegalArgumentException] should be thrownBy ContinueUrl("//some/value?with=query")
    an[IllegalArgumentException] should be thrownBy ContinueUrl("///some/value?with=query")
    an[IllegalArgumentException] should be thrownBy ContinueUrl("////some/value?with=query")
  }

  "not work for urls with @" in {
    an[IllegalArgumentException] should be thrownBy ContinueUrl("/some/value?with=query@meh")
  }

  "not work for urls with /\\" in {
    an[IllegalArgumentException] should be thrownBy ContinueUrl("/\\www.example.com")
  }

  "not work for path-relative urls" in {
    an[IllegalArgumentException] should be thrownBy ContinueUrl("some/value?with=query")
  }

  "not work for non-urls" in {
    an[IllegalArgumentException] should be thrownBy ContinueUrl("someasdfasdfa")
  }

  "encodedUrl should produce the expected result" in {
    ContinueUrl("/some/value?with=query").encodedUrl shouldBe "%2Fsome%2Fvalue%3Fwith%3Dquery"
  }

  "Binding a continue URL" should {
    "work for host-relative URLs" in {
      val url = "/some/value"
      queryBinder.bind("continue", Map("continue" -> Seq(url))).value.right.value should be(ContinueUrl(url))
    }

    "work for host-relative URLs with query Params" in {
      val url = "/some/value?with=query"
      queryBinder.bind("continue", Map("continue" -> Seq(url))).value.right.value should be(ContinueUrl(url))
    }

    "not work for path-relative urls" in {
      val url = "some/value?with=query"
      queryBinder.bind("continue", Map("continue" -> Seq(url))).value.left.value should be(
        s"'$url' is not a valid continue URL")
    }

    "not work for non-urls" in {
      val url = "::"
      queryBinder.bind("continue", Map("continue" -> Seq(url))).value.left.value should be(
        s"'$url' is not a valid continue URL")
    }
  }

  "Unbinding a continue URL" should {
    "return the value" in {
      queryBinder.unbind("continue", ContinueUrl("/some/url")) should be("continue=%2Fsome%2Furl")
    }
  }

} 
Example 34
Source File: EnrolmentsConnectorSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package connectors

import models._
import org.joda.time.DateTime
import org.mockito.Matchers.{any, eq => eqTo}
import org.mockito.Mockito.when
import org.scalatest.EitherValues
import org.scalatest.Inspectors.forAll
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status._
import play.api.libs.json.{JsObject, JsResultException, Json}
import uk.gov.hmrc.http.{HttpException, HttpResponse}
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import util.BaseSpec

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class EnrolmentsConnectorSpec extends BaseSpec with MockitoSugar with ScalaFutures with EitherValues {

  val http = mock[DefaultHttpClient]
  val connector = new EnrolmentsConnector(http, config)
  val baseUrl = config.enrolmentStoreProxyUrl

  "getAssignedEnrolments" should {
    val utr = "1234500000"
    val url = s"$baseUrl/enrolment-store/enrolments/IR-SA~UTR~$utr/users"

    "Return the error message for a BAD_REQUEST response" in {
      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(BAD_REQUEST)))

      connector.getUserIdsWithEnrolments(utr).futureValue.left.value should include(BAD_REQUEST.toString)
    }

    "NO_CONTENT response should return no enrolments" in {
      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(NO_CONTENT)))

      connector.getUserIdsWithEnrolments(utr).futureValue.right.value shouldBe Seq.empty
    }

    "query users with no principal enrolment returns empty enrolments" in {
      val json = Json.parse("""
                              |{
                              |    "principalUserIds": [],
                              |     "delegatedUserIds": []
                              |}""".stripMargin)

      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(OK, Some(json))))

      connector.getUserIdsWithEnrolments(utr).futureValue.right.value shouldBe Seq.empty
    }

    "query users with assigned enrolment return two principleIds" in {
      val json = Json.parse("""
                              |{
                              |    "principalUserIds": [
                              |       "ABCEDEFGI1234567",
                              |       "ABCEDEFGI1234568"
                              |    ],
                              |    "delegatedUserIds": [
                              |     "dont care"
                              |    ]
                              |}""".stripMargin)

      when(http.GET[HttpResponse](eqTo(url))(any(), any(), any()))
        .thenReturn(Future.successful(HttpResponse(OK, Some(json))))

      val expected = Seq("ABCEDEFGI1234567", "ABCEDEFGI1234568")

      connector.getUserIdsWithEnrolments(utr).futureValue.right.value shouldBe expected
    }
  }
} 
Example 35
Source File: EnumeratumSupportTest.scala    From tethys   with Apache License 2.0 5 votes vote down vote up
package tethys.enumeratum

import scala.util.Try

import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.EitherValues
import tethys.commons.TokenNode.{value => token, _}
import tethys.readers.{FieldName, ReaderError}
import tethys.writers.tokens.SimpleTokenWriter._

class EnumeratumSupportTest extends AnyFlatSpec with Matchers with EitherValues {
  behavior of "TethysEnum"

  it should "work for encode" in {
    for (entry <- Direction.values) {
      entry.asTokenList shouldBe token(entry.entryName)
    }
  }

  it should "work for decode" in {
    for (entry <- Direction.values) {
      token(entry.entryName).tokensAs[Direction] shouldBe entry
    }
  }

  it should "fail for decode with unknown value" in {
    implicit val field = FieldName().appendFieldName("direction")

    (the [ReaderError] thrownBy obj("direction" -> "Wat").tokensAs[Data]).getMessage shouldBe
      ReaderError.catchNonFatal(ReaderError.wrongJson("Wat is not a member of enum Direction")).left.value.getMessage

    for (json <- List(token(1), token(1.0), token("null"), token(false), obj(), arr())) {
      Try(json.tokensAs[Direction]).toOption shouldBe None
    }
  }


  behavior of "TethysKeyEnum"

  // FIXME Type Inference doesn't work somehow w/o typehint
  val directions: Map[Direction, Int] = Map(
    Direction.Up    -> 1,
    Direction.Down  -> 2,
    Direction.Left  -> 3,
    Direction.Right -> 4
  )

  it should "work for encode" in {
    directions.asTokenList shouldBe obj("Up" -> token(1), "Down" -> token(2), "Left" -> token(3), "Right" -> token(4))
  }

  it should "work for decode" in {
    obj(
      "Up" -> token(1),
      "Down" -> token(2),
      "Left" -> token(3),
      "Right" -> token(4)
    ).tokensAs[Map[Direction, Int]] shouldBe directions
  }
} 
Example 36
Source File: ProjectionProgressSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.sourcing.projections

import java.util.UUID

import akka.persistence.query.{Offset, Sequence, TimeBasedUUID}
import ch.epfl.bluebrain.nexus.sourcing.projections.ProjectionProgress._
import ch.epfl.bluebrain.nexus.sourcing.projections.implicits._
import io.circe.Encoder
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{EitherValues, Inspectors}

class ProjectionProgressSpec extends AnyWordSpecLike with Matchers with Inspectors with TestHelpers with EitherValues {

  "A ProjectionProgress" should {
    val mapping = Map(
      OffsetProgress(Sequence(14L), 2, 0, 1)                                                            ->
        jsonContentOf("/indexing/sequence-offset-progress.json"),
      OffsetProgress(TimeBasedUUID(UUID.fromString("ee7e4360-39ca-11e9-9ed5-dbdaa32f8986")), 32, 5, 10) ->
        jsonContentOf("/indexing/timebaseduuid-offset-progress.json"),
      NoProgress                                                                                        ->
        jsonContentOf("/indexing/no-offset-progress.json"),
      OffsetsProgress(Map("noOffset" -> NoProgress, "other" -> OffsetProgress(Sequence(2L), 10L, 2L, 0L))) ->
        jsonContentOf("/indexing/offsets-progress.json")
    )

    "properly encode progress values" in {
      forAll(mapping.toList) {
        case (prog, repr) =>
          Encoder[ProjectionProgress].apply(prog) shouldEqual repr
      }
    }

    "properly decode progress values" in {
      forAll(mapping.toList) {
        case (prog, repr) =>
          repr.as[ProjectionProgress].rightValue shouldEqual prog
      }
    }

    "Add progress" in {
      val progress =
        OffsetsProgress(Map("noOffset" -> NoProgress, "other" -> OffsetProgress(Sequence(2L), 10L, 2L, 0L)))
      progress + ("noOffset", Sequence(1L), ProgressStatus.Failed("some error")) shouldEqual
        OffsetsProgress(
          Map(
            "noOffset" -> OffsetProgress(Sequence(1L), 1L, 0L, 1L),
            "other"    -> OffsetProgress(Sequence(2L), 10L, 2L, 0L)
          )
        )
      progress + ("other", Sequence(3L), ProgressStatus.Discarded) shouldEqual
        OffsetsProgress(Map("noOffset" -> NoProgress, "other" -> OffsetProgress(Sequence(3L), 11L, 3L, 0L)))
    }

    "fetch minimum progress" in {
      val progress = OffsetsProgress(
        Map(
          "one"   -> OffsetProgress(Sequence(1L), 2L, 1L, 0L),
          "other" -> OffsetProgress(Sequence(2L), 10L, 2L, 0L),
          "a"     -> OffsetProgress(Sequence(0L), 0L, 0L, 0L)
        )
      )
      progress.minProgressFilter(_.length > 1) shouldEqual OffsetProgress(Sequence(1L), 2L, 1L, 0L)
      progress.minProgress shouldEqual OffsetProgress(Sequence(0L), 0L, 0L, 0L)
    }

    "test TimeBasedUUIDd ordering" in {
      val time1 =
        TimeBasedUUID(UUID.fromString("49225740-2019-11ea-a752-ffae2393b6e4")) // 2019-12-16T15:32:36.148Z[UTC]
      val time2 =
        TimeBasedUUID(UUID.fromString("91be23d0-2019-11ea-a752-ffae2393b6e4")) // 2019-12-16T15:34:37.965Z[UTC]
      val time3 =
        TimeBasedUUID(UUID.fromString("91f95810-2019-11ea-a752-ffae2393b6e4")) // 2019-12-16T15:34:38.353Z[UTC]
      val offset1: Offset = time1
      val offset2: Offset = time2
      val offset3: Offset = time3
      time1.asInstant.isBefore(time2.asInstant) shouldEqual true
      time2.asInstant.isBefore(time3.asInstant) shouldEqual true
      offset1.gt(offset2) shouldEqual false
      offset3.gt(offset2) shouldEqual true
      List(time2, time1, time3).sorted(offsetOrdering) shouldEqual List(time1, time2, time3)
    }
  }
} 
Example 37
Source File: EvaluationSyntaxSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.sourcing

import cats.effect.IO
import org.scalatest.concurrent.ScalaFutures
import ch.epfl.bluebrain.nexus.sourcing.syntax._
import org.scalatest.EitherValues

class EvaluationSyntaxSpec extends SourcingSpec with ScalaFutures with EitherValues {
  type State   = (Int)
  type Command = Int
  "An evaluation syntax" should {
    "transform a '(state, command) => state' evaluation into a '(state, command) => F(Right(state))'" in {
      val eval: (State, Command) => State = {
        case (st, cmd) => (st + cmd)
      }
      val evalEitherF                     = eval.toEitherF[IO]
      evalEitherF(2, 3).unsafeRunSync().rightValue shouldEqual 5
    }

    "transform a '(state, command) => F(state)' evaluation into a '(state, command) => F(Right(state))'" in {
      val err                                 = new RuntimeException("error")
      val eval: (State, Command) => IO[State] = {
        case (st, cmd) if st < 0 || cmd < 0 => IO.raiseError(err)
        case (st, cmd)                      => IO.pure(st + cmd)
      }
      val evalEitherF                         = eval.toEither
      evalEitherF(1, 2).unsafeRunSync().rightValue shouldEqual 3
      evalEitherF(-1, 3).unsafeToFuture().failed.futureValue shouldEqual err
      evalEitherF(1, -3).unsafeToFuture().failed.futureValue shouldEqual err
    }
  }
} 
Example 38
Source File: SangriaCodegenBaseSpec.scala    From sbt-graphql   with Apache License 2.0 5 votes vote down vote up
package rocks.muki.graphql.codegen.style.sangria

import java.io.File

import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.EitherValues
import rocks.muki.graphql.codegen.{DocumentLoader, ScalametaGenerator, TypedDocumentParser}
import rocks.muki.graphql.schema.SchemaLoader
import sangria.schema.Schema
import sbt._

import scala.io.Source
import scala.meta._

abstract class SangriaCodegenBaseSpec(name: String, schema: Option[Schema[_, _]] = None)
    extends AnyWordSpec
    with EitherValues {
  def this(name: String, schema: Schema[_, _]) = this(name, Some(schema))

  val inputDir = new File("src/test/resources/sangria", name)

  def contentOf(file: File) =
    Source.fromFile(file).mkString

  "SangriaCodegen" should {
    for {
      input <- inputDir.listFiles()
      if input.getName.endsWith(".graphql")
      name = input.getName.replace(".graphql", "")
      expected = new File(inputDir, s"$name.scala")
      if expected.exists
    } {
      s"generate code for ${input.getName}" in {
        val generator = ScalametaGenerator(s"${name}Api")
        val schema =
          SchemaLoader
            .fromFile(inputDir / "schema.graphql")
            .loadSchema()

        val document = DocumentLoader.single(schema, input).right.value
        val typedDocument =
          TypedDocumentParser(schema, document).parse().right.value
        val out = generator(typedDocument).right.value

        val actual = out.show[Syntax]

        if (actual.trim != contentOf(expected).trim)
          println(actual)

        assert(actual.trim == contentOf(expected).trim)
      }
    }
  }
} 
Example 39
Source File: TezosTypesTest.scala    From Conseil   with Apache License 2.0 5 votes vote down vote up
package tech.cryptonomic.conseil.common.tezos

import java.time.Instant

import org.scalatest.{EitherValues, Matchers, OptionValues, WordSpec}
import tech.cryptonomic.conseil.common.tezos.TezosTypes._

class TezosTypesTest extends WordSpec with Matchers with OptionValues with EitherValues {

  val sut = TezosTypes

  "The Base58Check verifier" should {
      "accept an empty string" in {
        sut.isBase58Check("") shouldBe true
      }

      "accept a correctly encoded string" in {
        sut.isBase58Check(
          "signiRfcqmbGc6UtW1WzuJNGzRRsWDLpafxZZPwwTMntFwup8rTxXEgcLD5UBWkYmMqZECVEr33Xw5sh9NVi45c4FVAXvQSf"
        ) shouldBe true
      }

      "reject a string with forbidden chars" in {
        sut.isBase58Check(
          "signiRfcqmbGc6UtW1WzulJNGzRRsWDLpafxZZPwwTMntFwup8rTxXEgcLD5UBWkYmMqZECVEr33Xw5sh9NVi45c4FVAXvQSf"
        ) shouldBe false
        sut.isBase58Check(
          "$signiRfcqmbGc6UtW1WzulJNGzRRsWDpafxZZPwwTMntFwup8rTxXEgcLD5UBWkYmMqZECVEr33Xw5sh9NVi45c4FVAXvQSf"
        ) shouldBe false
        sut.isBase58Check(
          "signiRfcqmbGc6UtW1WzulJNGzRRsWDpafxZZPwwTMntFwup8rTxXEgcLD5UBWkYmMqZECVEr33Xw5sh9NVi45c4FVAXvQSf*"
        ) shouldBe false
      }

      "reject a string with spaces" in {
        sut.isBase58Check(
          "signiRfcqmbGc6UtW1WzuJNGzRRs DLpafxZZPwwTMntFwup8rTxXEgcLD5UBWkYmMqZECVEr33Xw5sh9NVi45c4FVAXvQSf"
        ) shouldBe false
        sut.isBase58Check(
          " signiRfcqmbGc6UtW1WzuJNGzRRsDLpafxZZPwwTMntFwup8rTxXEgcLD5UBWkYmMqZECVEr33Xw5sh9NVi45c4FVAXvQSf"
        ) shouldBe false
        sut.isBase58Check(
          "signiRfcqmbGc6UtW1WzuJNGzRRsDLpafxZZPwwTMntFwup8rTxXEgcLD5UBWkYmMqZECVEr33Xw5sh9NVi45c4FVAXvQSf "
        ) shouldBe false
      }

    }

  "The Syntax import" should {
      "allow building Block-tagged generic data" in {
        import TezosTypes.Syntax._
        val someTime = Some(Instant.ofEpochMilli(0))
        val content = "A content string"
        val (hash, level) = (BlockHash("hash"), 1)

        content.taggedWithBlock(hash, level, someTime, None, None) shouldEqual BlockTagged(
          hash,
          level,
          someTime,
          None,
          None,
          content
        )
      }
    }

  "The BlockTagged wrapper" should {
      "convert to a tuple" in {
        val someTime = Some(Instant.ofEpochMilli(0))
        val content = "A content string"
        val (hash, level) = (BlockHash("hash"), 1)

        BlockTagged(hash, level, someTime, None, None, content).asTuple shouldEqual (hash, level, someTime, None, None, content)
      }
    }

} 
Example 40
Source File: ScalaXMLSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.scalaxml

import scala.xml.Elem

import com.typesafe.config.ConfigFactory.parseString
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig.generic.auto._
import pureconfig.syntax._

class ScalaXMLSuite extends AnyFlatSpec with Matchers with EitherValues {

  case class Config(people: Elem)

  val sampleXML: Elem =
    <people>
      <person firstName="foo" lastName="bar"/>
      <person firstName="blah" lastName="stuff"/>
    </people>

  it should "be able to read a config with XML" in {
    val config = parseString(
      s"""{ people =
         |    \"\"\"$sampleXML\"\"\"
         | }""".stripMargin)
    config.to[Config] shouldEqual Right(Config(sampleXML))
  }

  it should "return an error when reading invalid XML " in {
    val config = parseString("{ people: <people> }")
    config.to[Config] shouldBe 'left
  }
} 
Example 41
Source File: JavaxSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.javax

import _root_.javax.security.auth.kerberos.KerberosPrincipal
import com.typesafe.config.ConfigFactory
import javax.security.auth.x500.X500Principal
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig.generic.auto._
import pureconfig.syntax._

class JavaxSuite extends AnyFlatSpec with Matchers with EitherValues {

  case class K5Conf(principal: KerberosPrincipal)

  it should "be able to read a config with a KerberosPrincipal" in {
    val expected = "sample/principal@pureconfig"
    val config = ConfigFactory.parseString(s"""{ principal: "$expected" }""")
    config.to[K5Conf].right.value shouldEqual K5Conf(new KerberosPrincipal(expected))
  }

  case class X500Conf(principal: X500Principal)

  it should "be able to read a config with an X500Principal" in {
    val expected = "CN=Steve Kille,O=Isode Limited,C=GBg"
    val config = ConfigFactory.parseString(s"""{ principal: "$expected" }""")
    config.to[X500Conf].right.value shouldEqual X500Conf(new X500Principal(expected))
  }
} 
Example 42
Source File: AkkaSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.akka

import scala.concurrent.duration._

import akka.actor.ActorPath
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig.generic.auto._
import pureconfig.syntax._

class AkkaSuite extends AnyFlatSpec with Matchers with EitherValues {

  case class TimeoutConf(timeout: Timeout)
  case class PathConf(path: ActorPath)

  it should "be able to read a config with a Timeout" in {
    val expected = 5.seconds
    val config = ConfigFactory.parseString(s"""{ timeout: $expected }""")
    config.to[TimeoutConf].right.value shouldEqual TimeoutConf(Timeout(expected))
  }

  it should "load a valid ActorPath" in {
    val str = "akka://my-sys/user/service-a/worker1"
    val expected = ActorPath.fromString(str)
    val config = ConfigFactory.parseString(s"""{ path: "$str" }""")
    config.to[PathConf].right.value shouldEqual PathConf(expected)
  }

  it should "not load invalid ActorPath" in {
    val config = ConfigFactory.parseString("""{ path: "this is this the path you're looking for" }""")
    config.to[PathConf] should be('left)
  }
} 
Example 43
Source File: CirceSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.circe

import com.typesafe.config.ConfigFactory
import io.circe._
import io.circe.literal._
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig._
import pureconfig.generic.auto._
import pureconfig.syntax._

class CirceSuite extends AnyFlatSpec with Matchers with EitherValues {

  case class JsonConf(json: Json)
  val confJson = json"""{ "long": 123, "double": 123.123, "alpha": "test", "arr": [1, 2, 3], "map": { "key1": "value1", "key2": "value2" } }"""
  val confString = """
    json = {
      long = 123
      double = 123.123
      alpha = test
      arr = [1, 2, 3]
      map = {
        key1 = value1
        key2 = value2
      }
    }
  """
  val config = ConfigFactory.parseString(confString)

  it should "be able to read a config as circe json" in {
    config.to[JsonConf].right.value shouldEqual JsonConf(confJson)
  }

  it should "be able to write a config as circe json" in {
    ConfigWriter[JsonConf].to(JsonConf(confJson)) shouldEqual config.root()
  }
} 
Example 44
Source File: ConfigReaderFailureOriginSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig

import java.net.URL

import com.typesafe.config.{ ConfigFactory, ConfigValueType }
import org.scalatest.{ EitherValues, Inside }
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig.error._
import pureconfig.generic.auto._


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

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

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

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

    }

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

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

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

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

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

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

    }
  }
}