org.scalatest.flatspec.AnyFlatSpec Scala Examples
The following examples show how to use org.scalatest.flatspec.AnyFlatSpec.
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: PagePropertiesSpec.scala From paradox with Apache License 2.0 | 5 votes |
package com.lightbend.paradox.markdown import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class PagePropertiesSpec extends AnyFlatSpec with Matchers { def convertPath = Path.replaceSuffix(".md", ".html")_ val propOut = Map("out" -> "newIndex.html") val propNoOut = Map.empty[String, String] val propOutInvalid = Map("out" -> "newIndex.foo") val outProperties = new Page.Properties(propOut) val noOutProperties = new Page.Properties(propNoOut) val outInvalidProperties = new Page.Properties(propOutInvalid) "Page.Properties.convertToTarget(convertPath)(\"index.md\")" should "create target file String according to 'out' field in properties" in { outProperties.convertToTarget(convertPath)("index.md") shouldEqual "newIndex.html" } it should "create default 'index.html' (just by replacing .md by .html) when no 'out' field is specified" in { noOutProperties.convertToTarget(convertPath)("index.md") shouldEqual "index.html" } it should "drop the 'out' field if it is invalid (not finishing by '.html')" in { outInvalidProperties.convertToTarget(convertPath)("index.md") shouldEqual "index.html" } }
Example 2
Source File: FutureTrySpec.scala From scala-common with Apache License 2.0 | 5 votes |
import com.softwaremill.futuretry._ import org.scalatest.concurrent.ScalaFutures import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.matchers.must.Matchers import scala.concurrent.duration.Duration import scala.concurrent.{Future, Await, Promise} import scala.util.{Failure, Success, Try} class FutureTrySpec extends AnyFlatSpec with Matchers with TableDrivenPropertyChecks with ScalaFutures { import scala.concurrent.ExecutionContext.Implicits.global "tried" must "convert a successful result into a Success" in { val p = Promise[String] p.complete(Try("a")) val transformedFuture = p.future.tried transformedFuture.futureValue must be(Success("a")) } it must "convert an exceptional result into a Failure" in { val p = Promise[String] val exception = new RuntimeException("blah") p.complete(Try(throw exception)) val transformedFuture = p.future.tried transformedFuture.futureValue must be(Failure(exception)) } "transform" must "correctly transform between all Try variants in" in { val exception = new RuntimeException("bloh") val scenarios = Table[Try[String], Try[String] => Try[String], Try[String]] ( ("original value", "transform", "expected output"), (Success("a"), identity[Try[String]], Success("a")), (Failure(exception), (x: Try[String]) => x match { case Failure(e) => Success(e.toString); case _ => ??? }, Success(exception.toString)), (Success("a"), (x: Try[String]) => x match { case Success(_) => Failure(exception); case _ => ??? }, Failure(exception)), (Failure(exception), identity[Try[String]], Failure(exception)) ) forAll(scenarios) { (orgValue, f, output) => { val p = Promise[String] p.complete(orgValue) val transformedFuture = p.future.transformTry(f) transformedFuture.tried.futureValue must be(output) } } } }
Example 3
Source File: ExamplesSuite.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.examples import cats.instances.list._ import io.circe.testing.instances._ import io.circe.testing.golden._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.prop.Configuration import org.typelevel.discipline.scalatest.FlatSpecDiscipline class ExamplesSuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration { checkAll("GoldenCodec[Foo]", GoldenCodecTests[Foo](10).goldenCodec) checkAll("GoldenCodec[Wub]", GoldenCodecTests[Wub].goldenCodec) // Validate that golden filenames don't collide for type constructors applied // to different arguments. checkAll("GoldenCodec[MyList[Foo]]", GoldenCodecTests[MyList[Foo]].goldenCodec) checkAll("GoldenCodec[MyList[Wub]]", GoldenCodecTests[MyList[Wub]].goldenCodec) // Validated that deeply nested types are successfully given golden filenames. checkAll( "GoldenCodec[MyTuple[MyList[Wub], MyList[MyList[Foo]]]]", GoldenCodecTests[MyTuple[MyList[Wub], MyList[MyList[Foo]]]].goldenCodec ) }
Example 4
Source File: VisitSuite.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden.example import io.circe.Codec import io.circe.generic.semiauto.deriveCodec import java.time.Instant case class Visit(id: Long, page: String, ts: Instant) object Visit { implicit val codecForVisit: Codec[Visit] = deriveCodec } import cats.kernel.Eq import io.circe.testing.{ ArbitraryInstances, CodecTests } import org.scalacheck.Arbitrary import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.prop.Configuration import org.typelevel.discipline.scalatest.FlatSpecDiscipline trait VisitTestInstances extends ArbitraryInstances { implicit val eqVisit: Eq[Visit] = Eq.fromUniversalEquals implicit val arbitraryVisit: Arbitrary[Visit] = Arbitrary( for { id <- Arbitrary.arbitrary[Long] page <- Arbitrary.arbitrary[String] ts <- Arbitrary.arbitrary[Long].map(Instant.ofEpochMilli) } yield Visit(id, page, ts) ) } class OldVisitSuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitTestInstances { checkAll("Codec[Visit]", CodecTests[Visit].codec) val good = """{"id":12345,"page":"/index.html","ts":"2019-10-22T14:54:13Z"}""" val value = Visit(12345L, "/index.html", Instant.parse("2019-10-22T14:54:13Z")) "codecForVisit" should "decode JSON that's known to be good" in { assert(io.circe.jawn.decode[Visit](good) === Right(value)) } it should "produce the expected results" in { import io.circe.syntax._ assert(value.asJson.noSpaces === good) } } import io.circe.testing.golden.GoldenCodecTests class VisitSuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitTestInstances { checkAll("GoldenCodec[Visit]", GoldenCodecTests[Visit].goldenCodec) }
Example 5
Source File: VisitRepositorySuite.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden.example import io.circe.{ Codec, Printer } import io.circe.generic.semiauto.deriveCodec import java.time.Instant case class VisitRepository(visits: Map[String, Visit]) object VisitRepository { implicit val codecForVisitRepository: Codec[VisitRepository] = deriveCodec } import cats.kernel.Eq import io.circe.testing.{ ArbitraryInstances, CodecTests } import org.scalacheck.Arbitrary import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.prop.Configuration import org.typelevel.discipline.scalatest.FlatSpecDiscipline trait VisitRepositoryTestInstances extends VisitTestInstances with ArbitraryInstances { implicit val eqVisitRepository: Eq[VisitRepository] = Eq.fromUniversalEquals implicit val arbitraryVisitRepository: Arbitrary[VisitRepository] = Arbitrary( for { visits <- Arbitrary.arbitrary[Map[String, Visit]] } yield VisitRepository(visits) ) } class OldVisitRepositorySuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitRepositoryTestInstances { checkAll("Codec[VisitRepository]", CodecTests[VisitRepository].codec) val good = """{"visits":{"1":{"id":12345,"page":"/index.html","ts":"2019-10-22T14:54:13Z"}}}""" val value = VisitRepository(Map("1" -> Visit(12345L, "/index.html", Instant.parse("2019-10-22T14:54:13Z")))) "codecForVisitRepository" should "decode JSON that's known to be good" in { assert(io.circe.jawn.decode[VisitRepository](good) === Right(value)) } it should "produce the expected results" in { import io.circe.syntax._ assert(value.asJson.noSpaces === good) } } import io.circe.testing.golden.GoldenCodecTests class VisitRepositorySuite extends AnyFlatSpec with FlatSpecDiscipline with Configuration with VisitRepositoryTestInstances { checkAll("GoldenCodec[VisitRepository]", GoldenCodecTests[VisitRepository](Printer.spaces2SortKeys).goldenCodec) }
Example 6
Source File: EscapingTests.scala From circe-yaml with Apache License 2.0 | 5 votes |
package io.circe.yaml import io.circe.Encoder import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.util.{ Success, Try } import org.scalatest.matchers.should.Matchers class EscapingTests extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { import io.circe.syntax._ import io.circe.yaml.Printer.spaces2.pretty import io.circe.yaml.parser.parse // according to the YAML spec (section 5.1: character set) def isPrintable(c: Char): Boolean = ('\t' == c) || ('\n' == c) || ('\r' == c) || (' ' <= c && c <= '~') || ('\u0085' == c) || ('\u00a0' <= c && c <= '\ud7ff') || ('\ue000' <= c && c <= '\ufffd') def test1(c: Char): Unit = { val r = "'\\u%04X'".format(c.toInt) def repr[A](a: A): (String, A) = (r, a) val json = c.toString.asJson val s = pretty(json) if (s.contains(c)) repr(isPrintable(c)) shouldBe repr(true) else () // we do not enforce that printable chars are never escaped repr(s.forall(isPrintable)) shouldBe repr(true) repr(Try(parse(s))) shouldBe repr(Success(Right(json))) } "Escaping" should "properly escape JSON string values (all chars)" in { // exhaustive test: 65k test cases (Char.MinValue to Char.MaxValue).map(_.toChar).foreach(test1) } def test2(s0: String): Unit = { val json = s0.asJson val s1 = pretty(json) s1.forall(isPrintable) parse(s1) shouldBe Right(json) } it should "properly escape JSON string values" in { forAll { (s0: String) => test2(s0) } } def test3(c: Char): Unit = { val m = Map(c.toString -> c.toInt) val o = Encoder[Map[String, Int]].apply(m) parser.parse(printer.print(o)).right.flatMap(_.as[Map[String, Int]]) shouldBe Right(m) } it should "properly escape JSON object keys" in { // exhaustive test: 65k test cases (Char.MinValue to Char.MaxValue).map(_.toChar).foreach(test3) } }
Example 7
Source File: ParserTests.scala From circe-yaml with Apache License 2.0 | 5 votes |
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 8
Source File: SyntaxTests.scala From circe-yaml with Apache License 2.0 | 5 votes |
package io.circe.yaml import io.circe.Json import org.scalatest.flatspec.AnyFlatSpec import syntax._ import org.scalatest.matchers.should.Matchers class SyntaxTests extends AnyFlatSpec with Matchers { val json = Json.obj( "foo" -> Json.obj( "bar" -> Json.fromString("baz") ) ) "spaces2" should "have double space indent" in { json.asYaml.spaces2 shouldEqual """foo: | bar: baz |""".stripMargin } "spaces4" should "have quadruple space indent" in { json.asYaml.spaces4 shouldEqual """foo: | bar: baz |""".stripMargin } }
Example 9
Source File: ClockProviderSpec.scala From chronoscala with MIT License | 5 votes |
package jp.ne.opt.chronoscala import java.time.{Clock, ZoneId} import jp.ne.opt.chronoscala.Imports._ import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec class ClockProviderSpec extends AnyFlatSpec with BeforeAndAfter { after { ClockProvider.setCurrentClockSystem() } it should "set current clock" in { ClockProvider.setCurrentClock(Clock.fixed(Instant.ofEpochMilli(0L), ZoneId.of("UTC"))) assert(Instant.now() == Instant.ofEpochMilli(0L)) assert(LocalDate.now() == LocalDate.parse("1970-01-01")) assert(LocalDateTime.now() == LocalDateTime.parse("1970-01-01T00:00:00.000")) assert(LocalTime.now() == LocalTime.parse("00:00:00.000")) assert(ZonedDateTime.now() == ZonedDateTime.parse("1970-01-01T00:00:00.000+00:00[UTC]")) assert(OffsetDateTime.now() == OffsetDateTime.parse("1970-01-01T00:00:00.000+00:00")) } }
Example 10
Source File: TracingMiddlewareSpec.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.http4s import cats.effect.IO import io.opencensus.scala.http.ServiceData import io.opencensus.scala.http4s.TracingService.{TracingService, withSpan} import io.opencensus.trace.Span import org.http4s._ import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class TracingMiddlewareSpec extends AnyFlatSpec with Matchers with OptionValues with ServiceRequirementsSpec { behavior of "TracingMiddleware" val ex = new Exception("test exception") val data = ServiceData("serviceX", "x.s.2") def tracingService( response: Span => IO[Response[IO]] = span => Ok(span.getContext.toString) ): TracingService[IO] = TracingService[IO] { case GET -> Root / "my" / "fancy" / "path" withSpan span => response(span) } def service(response: IO[Response[IO]] = Ok()): HttpRoutes[IO] = HttpRoutes.of[IO] { case GET -> Root / "my" / "fancy" / "path" => response } "tracing with span" should behave like testService( successServiceFromMiddleware = _.fromTracingService(tracingService()), failingServiceFromMiddleware = _.fromTracingService(tracingService(_ => IO.raiseError(ex))), badRequestServiceFromMiddleware = _.fromTracingService(tracingService(_ => BadRequest())), errorServiceFromMiddleware = _.fromTracingService(tracingService(_ => InternalServerError())) ) "tracing with span and with service data" should behave like testService( successServiceFromMiddleware = _.fromTracingService(tracingService(), data), failingServiceFromMiddleware = _.fromTracingService(tracingService(_ => IO.raiseError(ex)), data), badRequestServiceFromMiddleware = _.fromTracingService(tracingService(_ => BadRequest()), data), errorServiceFromMiddleware = _.fromTracingService(tracingService(_ => InternalServerError()), data), Some(data) ) it should "pass the span to the service" in { val (middleware, _) = middlewareWithMock() val responseBody = middleware .fromTracingService(tracingService()) .run(request) .value .flatMap(_.get.as[String]) .unsafeRunSync() responseBody should include("SpanContext") } "tracing without span" should behave like testService( successServiceFromMiddleware = _.withoutSpan(service()), failingServiceFromMiddleware = _.withoutSpan(service(IO.raiseError(ex))), badRequestServiceFromMiddleware = _.withoutSpan(service(BadRequest())), errorServiceFromMiddleware = _.withoutSpan(service(InternalServerError())) ) "tracing without span and with service data" should behave like testService( successServiceFromMiddleware = _.withoutSpan(service(), data), failingServiceFromMiddleware = _.withoutSpan(service(IO.raiseError(ex)), data), badRequestServiceFromMiddleware = _.withoutSpan(service(BadRequest()), data), errorServiceFromMiddleware = _.withoutSpan(service(InternalServerError()), data), Some(data) ) }
Example 11
Source File: ServiceAttributesSpec.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.http import io.opencensus.scala.http.ServiceAttributes._ import io.opencensus.scala.http.testSuite.MockSpan import io.opencensus.trace.AttributeValue._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ServiceAttributesSpec extends AnyFlatSpec with Matchers { val strValue = stringAttributeValue _ behavior of "setAttributesForService" it should "set the service name only" in { val span = new MockSpan("", None) setAttributesForService(span, ServiceData("myservice")) span.attributes shouldBe Map("service.name" -> strValue("myservice")) } it should "set the version only" in { val span = new MockSpan("", None) setAttributesForService(span, ServiceData().setVersion("myversion")) span.attributes shouldBe Map("service.version" -> strValue("myversion")) } it should "set all attributes" in { val span = new MockSpan("", None) setAttributesForService(span, ServiceData("myservice", "myversion")) span.attributes shouldBe Map( "service.name" -> strValue("myservice"), "service.version" -> strValue("myversion") ) } }
Example 12
Source File: HttpAttributesSpec.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.http import io.opencensus.scala.http.testSuite.MockSpan import io.opencensus.trace.AttributeValue._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers trait HttpAttributesSpec extends AnyFlatSpec with Matchers { def httpAttributes[Request: RequestExtractor, Response: ResponseExtractor]( request: BuildRequest => Request, response: Int => Response ): Unit = { val span = new MockSpan("span", None) val strValue = stringAttributeValue _ val (host, path, userAgent) = ("example.com", "/this/is/the/path", "agent") HttpAttributes.setAttributesForRequest( span, request( BuildRequest( "http://" + host + ":8181", path + "?this¬", userAgent, None ) ) ) behavior of "setAttributesForRequest" it should "set the method" in { span.attributes("http.method") shouldBe strValue("GET") } it should "set the path" in { span.attributes("http.path") shouldBe strValue(path) } it should "set the user_agent" in { span.attributes("http.user_agent") shouldBe strValue(userAgent) } it should "set the host from the absolute uri" in { span.attributes("http.host") shouldBe strValue(host) } it should "set the host from the host header if uri is relative" in { val span = new MockSpan("span", None) HttpAttributes.setAttributesForRequest( span, request(BuildRequest("", path, userAgent, Some(host))) ) span.attributes("http.host") shouldBe strValue(host) } behavior of "setAttributesForResponse" it should "set the status code" in { val span = new MockSpan("span", None) HttpAttributes.setAttributesForResponse(span, response(203)) span .attributes("http.status_code") shouldBe longAttributeValue(203L) } } case class BuildRequest( host: String, path: String, userAgent: String, hostHeader: Option[String] ) }
Example 13
Source File: B3FormatPropagationSpec.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.http.testSuite.propagation import io.opencensus.scala.http.propagation.B3FormatPropagation import io.opencensus.trace.BlankSpan import org.scalatest.TryValues import scala.util.Failure import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class B3FormatPropagationSpec extends AnyFlatSpec with Matchers with TryValues with B3FormatPropagation[(String, String), Map[String, String]] { val fakeTraceId = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" val fakeSpanId = "bbbbbbbbbbbbbbbb" "headersWithTracingContext" should "return the correct B3 headers from a spans context" in { headersWithTracingContext(BlankSpan.INSTANCE) should contain theSameElementsAs List( "X-B3-TraceId" -> "00000000000000000000000000000000", "X-B3-SpanId" -> "0000000000000000" ) } behavior of "extractContext" it should "return a span context with the values from the B3 http headers" in { val request = Map( "X-B3-TraceId" -> fakeTraceId, "X-B3-SpanId" -> fakeSpanId, "X-B3-Sampled" -> "1" ) val context = extractContext(request).success.value context.getTraceId.toLowerBase16 shouldBe fakeTraceId context.getSpanId.toLowerBase16 shouldBe fakeSpanId context.getTraceOptions.isSampled shouldBe true } it should "return a failure when the headers are missing" in { extractContext(Map.empty) shouldBe a[Failure[_]] } override def headerValue( req: Map[String, String], key: String ): Option[String] = req.get(key) override def createHeader(key: String, value: String): (String, String) = (key, value) }
Example 14
Source File: ServiceDataTest.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.http import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ServiceDataTest extends AnyFlatSpec with Matchers { behavior of "apply" it should "be empty" in { ServiceData() shouldBe ServiceData(None, None) } it should "contain only the name" in { ServiceData("name") shouldBe ServiceData(Some("name"), None) } it should "contain the name and the version" in { ServiceData("name", "version") shouldBe ServiceData( Some("name"), Some("version") ) } "setName" should "set the name" in { ServiceData().setName("name") shouldBe ServiceData(Some("name"), None) } "setVersion" should "set the version" in { ServiceData().setVersion("version") shouldBe ServiceData( None, Some("version") ) } }
Example 15
Source File: StatsDirectiveSpec.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.akka.http import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.testkit.ScalatestRouteTest import io.opencensus.scala.http.testSuite.MockStats import io.opencensus.scala.stats.{Distribution, MeasurementDouble} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class StatsDirectiveSpec extends AnyFlatSpec with ScalatestRouteTest with Matchers { def statsDirectiveWithMock: (StatsDirective, MockStats) = { val mockStats = new MockStats val directive = new StatsDirective { override private[http] val stats = mockStats } (directive, mockStats) } def routeWithMock = { val (directive, mock) = statsDirectiveWithMock val route = directive.recordRequest("routeName") { complete(StatusCodes.OK) } (route, mock) } it should "register the correct view" in { val (route, mock) = routeWithMock Get("/foo") ~> route ~> check { status shouldBe StatusCodes.OK mock.registeredViews should have length 1 val serverLatency = mock.registeredViews.head serverLatency.name shouldBe "opencensus.io/http/server/server_latency" serverLatency.measure.name shouldBe "opencensus.io/http/server/server_latency" serverLatency.aggregation shouldBe a[Distribution] } } it should "record the correct measure value" in { val (route, mock) = routeWithMock Get("/foo") ~> route ~> check { status shouldBe StatusCodes.OK mock.recordedMeasurements should have length 1 val (measurement, _) = mock.recordedMeasurements.head measurement match { case MeasurementDouble(measure, value) => measure.name shouldBe "opencensus.io/http/server/server_latency" value.toInt shouldBe >(0) case other => fail(s"Expected MeasurementDouble got $other") } } } it should "record the correct measure tags" in { val (route, mock) = routeWithMock Get("/foo") ~> route ~> check { status shouldBe StatusCodes.OK mock.recordedMeasurements should have length 1 val (_, tags) = mock.recordedMeasurements.head val tagsKeyValues = tags.map(tag => (tag.key.getName, tag.value.asString())) val expectedTags = List( "http_server_method" -> "GET", "http_server_route" -> "routeName", "http_server_status" -> "200" ) tagsKeyValues should contain theSameElementsAs expectedTags } } }
Example 16
Source File: StatsImplSpec.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.stats import io.opencensus.implcore.internal.SimpleEventQueue import io.opencensus.implcore.stats.StatsComponentImplBase import io.opencensus.stats.AggregationData import io.opencensus.stats.AggregationData.{SumDataDouble, SumDataLong} import io.opencensus.tags.{Tags => JavaTags} import io.opencensus.testing.common.TestClock import org.scalatest.Inspectors import scala.jdk.CollectionConverters._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class StatsImplSpec extends StatsSpecs { def measureLong(name: String) = Measure.long(name, "desc", "unit").get def measureDouble(name: String) = Measure.double(name, "desc", "unit").get val measurementsLong = List( Measurement.long(measureLong("name"), 4L) -> SumDataLong.create(4L), Measurement.long(measureLong("name2"), 12L) -> SumDataLong.create(12L) ) val measurementsDouble = List( Measurement.double(measureDouble("name"), 4.0) -> SumDataDouble.create(4.0), Measurement.double(measureDouble("name2"), 12.0) -> SumDataDouble.create( 12.0 ) ) "record single measure long" should behave like recordingSpecs( measurementsLong.take(1) ) "record single measure double" should behave like recordingSpecs( measurementsDouble.take(1) ) "record different long measures in batch" should behave like recordingSpecs( measurementsLong ) "record different double measures in batch" should behave like recordingSpecs( measurementsDouble ) } trait StatsSpecs extends AnyFlatSpec with Matchers with Inspectors { def recordingSpecs( measurements: List[(Measurement, AggregationData)] ): Unit = { def view(measure: Measure, name: String) = View(name, "viewdesc", measure, List("col1"), Sum).get it should "record measurements" in { val (statsComponent, stats) = createStats() val views = measurements.zipWithIndex.map { case ((measurment, result), i) => val testView = view(measurment.measure, i.toString) stats.registerView(testView) (testView, result) } stats.record(measurements.map(_._1): _*) forAll(views) { case (view, result) => val jView = statsComponent.getViewManager.getView(view.javaView.getName) val values = jView.getAggregationMap.asScala.values values.head shouldBe result } } } private def createStats() = { val statsComponent = new StatsComponentImplBase(new SimpleEventQueue, TestClock.create()) ( statsComponent, new StatsImpl( statsComponent.getViewManager, statsComponent.getStatsRecorder, JavaTags.getTagger ) ) } }
Example 17
Source File: ReviewStatusSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.pr import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ReviewStatusSpec extends AnyFlatSpec with Matchers { it should "infer the description from a review status" in { ReviewStatus.description(ReviewStatus(blocker = 0, critical = 0)) shouldBe "no critical or blocker issues" ReviewStatus.description(ReviewStatus(blocker = 1, critical = 0)) shouldBe "1 blocker" ReviewStatus.description(ReviewStatus(blocker = 2, critical = 0)) shouldBe "2 blockers" ReviewStatus.description(ReviewStatus(blocker = 0, critical = 1)) shouldBe "1 critical issue" ReviewStatus.description(ReviewStatus(blocker = 0, critical = 2)) shouldBe "2 critical issues" ReviewStatus.description( ReviewStatus(blocker = 1, critical = 1) ) shouldBe "1 blocker and 1 critical issue" ReviewStatus.description( ReviewStatus(blocker = 2, critical = 2) ) shouldBe "2 blockers and 2 critical issues" } }
Example 18
Source File: MarkdownSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.pr import org.http4s.Uri import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.batch.fs.InputFile import org.sonar.api.batch.fs.internal.TestInputFileBuilder import org.sonar.api.batch.rule.Severity import org.sonar.api.rule.RuleKey class MarkdownSpec extends AnyFlatSpec with Matchers { it should "create a markdown comment" in { val uri: Uri = Uri.uri("https://test.com") val file: InputFile = TestInputFileBuilder .create("", "src/main/scala/Other.scala") .setLanguage("scala") .setLines(10) .setType(InputFile.Type.MAIN) .build() val issue: Issue = Issue( RuleKey.of("repo", "rule"), file, 10, Severity.MINOR, "message" ) val expected: Markdown = Markdown( "![minor](https://static.sonar-scala.com/img/severity-minor.svg 'Severity: minor') message " + "([more](https://test.com/coding_rules?open=repo%3Arule&rule_key=repo%3Arule))" ) Markdown.inline(uri, issue) shouldBe expected } }
Example 19
Source File: GlobalIssuesSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.pr import com.mwz.sonar.scala.pr.Generators._ import org.scalacheck.ScalacheckShapeless._ import org.scalatest.Inspectors import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.sonar.api.batch.fs.internal.TestInputFileBuilder import org.sonar.api.batch.rule.Severity import org.sonar.api.rule.RuleKey class GlobalIssuesSpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { it should "add a new issue" in { val issues = new GlobalIssues val file = TestInputFileBuilder .create("", "test.scala") .build val issue = Issue( key = RuleKey.of("repo", "rule"), file = file, line = 10, severity = Severity.MAJOR, message = "test" ) issues.add(issue) issues.allIssues shouldBe Map(file -> List(issue)) } it should "return all issues" in { forAll { (issues: List[Issue]) => whenever(issues.nonEmpty) { val globalIssues = new GlobalIssues val expected = issues.groupBy(_.file) issues.foreach(globalIssues.add) Inspectors.forAll(globalIssues.allIssues) { case (file, issues) => issues should contain theSameElementsAs expected(file) } } } } }
Example 20
Source File: PatchSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
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 21
Source File: JUnitReportParserSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar package scala package junit import java.io.File import java.nio.file.Paths import org.scalatest.LoneElement import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.batch.fs.InputFile import org.sonar.api.batch.fs.internal.{DefaultFileSystem, TestInputFileBuilder} class JUnitReportParserSpec extends AnyFlatSpec with Matchers with WithFiles with LoneElement { it should "get report files" in { withFiles("file.xml", "file2.xml", "other.txt") { files => val directories = files.map(_.getParentFile).distinct.toList val baseDir = directories.loneElement val fs = new DefaultFileSystem(baseDir) val parser = new JUnitReportParser(fs) parser.reportFiles(directories) should contain theSameElementsAs List( baseDir.getAbsoluteFile.toPath.resolve("file.xml").toFile, baseDir.getAbsoluteFile.toPath.resolve("file2.xml").toFile ) } } it should "parse report files" in { val fs = new DefaultFileSystem(Paths.get("./")) val parser = new JUnitReportParser(fs) val expected = JUnitReport("TestFile", tests = 8, errors = 3, failures = 2, skipped = 1, time = 0.049f) parser .parseReportFiles(List(new File("./src/test/resources/junit/report.xml"))) .loneElement shouldBe expected } it should "resolve files" in { val fs = new DefaultFileSystem(Paths.get("./")) val parser = new JUnitReportParser(fs) val testFile = TestInputFileBuilder .create("", "path/to/tests/TestFile.scala") .build() val tests = List(Paths.get("path/to/tests")) val report = JUnitReport("TestFile", tests = 8, errors = 3, failures = 2, skipped = 1, time = 0.049f) val expected: Map[InputFile, JUnitReport] = Map(testFile -> report) fs.add(testFile) parser.resolveFiles(tests, List(report)) shouldBe expected } it should "parse" in { val fs = new DefaultFileSystem(Paths.get("./")) val parser = new JUnitReportParser(fs) val tests = List(Paths.get("path/to/tests")) val directories = List(new File("src/test/resources/junit")) val testFile = TestInputFileBuilder .create("", "path/to/tests/TestFile.scala") .build() val report = JUnitReport("TestFile", tests = 8, errors = 3, failures = 2, skipped = 1, time = 0.049f) val expected: Map[InputFile, JUnitReport] = Map(testFile -> report) fs.add(testFile) parser.parse(tests, directories) shouldBe expected } }
Example 22
Source File: ScalaSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala import java.nio.file.Paths import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.config.internal.MapSettings import scalariform.ScalaVersion class ScalaSpec extends AnyFlatSpec with Matchers { val defaultScala = ScalaVersion(2, 13) "getFileSuffixes" should "return Scala file suffixes" in { val conf = new MapSettings().asConfig() new Scala(conf).getFileSuffixes shouldBe Array(".scala") val conf2 = new MapSettings() .setProperty("sonar.scala.file.suffixes", ".scala") .asConfig() new Scala(conf2).getFileSuffixes shouldBe Array(".scala") } "getScalaVersion" should "return the available version, if properly set" in { val conf = new MapSettings() .setProperty("sonar.scala.version", "2.11.11") .asConfig() Scala.getScalaVersion(conf) shouldBe ScalaVersion(2, 11) } it should "be able to parse a milestone version" in { val conf = new MapSettings() .setProperty("sonar.scala.version", "2.13.0-M3") .asConfig() Scala.getScalaVersion(conf) shouldBe defaultScala } it should "be able to parse a version without patch" in { val conf = new MapSettings() .setProperty("sonar.scala.version", "2.12") .asConfig() Scala.getScalaVersion(conf) shouldBe ScalaVersion(2, 12) } it should "not return the default version if the property is set to '2.11.0'" in { val conf = new MapSettings() .setProperty("sonar.scala.version", "2.11.0") .asConfig() val parsedVersion = Scala.getScalaVersion(conf) parsedVersion should not be ScalaVersion(2, 12) parsedVersion shouldBe ScalaVersion(2, 11) } it should "return the default version, if the property is not set" in { val conf = new MapSettings().asConfig() Scala.getScalaVersion(conf) shouldBe defaultScala } it should "return the default version, if the version property has an empty patch" in { val conf = new MapSettings() .setProperty("sonar.scala.version", "2.12.") .asConfig() Scala.getScalaVersion(conf) shouldBe defaultScala } it should "return the default version, if the version property only contains the major version" in { val conf = new MapSettings() .setProperty("sonar.scala.version", "2") .asConfig() Scala.getScalaVersion(conf) shouldBe defaultScala } "getSourcesPaths" should "return the available sources" in { val conf1 = new MapSettings() .setProperty("sonar.sources", "sources/directory") .asConfig() Scala.getSourcesPaths(conf1) shouldBe List(Paths.get("sources/directory")) val conf2 = new MapSettings() .setProperty("sonar.sources", " sources/directory, src/2 ") .asConfig() Scala.getSourcesPaths(conf2) shouldBe List( Paths.get("sources/directory"), Paths.get("src/2") ) } it should "return the default value if not set" in { val conf = new MapSettings().asConfig() Scala.getSourcesPaths(conf) shouldBe List(Paths.get("src/main/scala")) } }
Example 23
Source File: ScalastyleCheckerSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package scalastyle import org.mockito.ArgumentMatchers._ import org.mockito.Mockito._ import org.scalastyle.{FileSpec, ScalastyleConfiguration, ScalastyleChecker => Checker} import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.mockito.MockitoSugar class ScalastyleCheckerSpec extends AnyFlatSpec with MockitoSugar { "ScalastyleChecker" should "checkFiles" in { val checker = mock[Checker[FileSpec]] when(checker.checkFiles(any(), any())) .thenReturn(List.empty) val config: ScalastyleConfiguration = new ScalastyleConfiguration( "SonarQube", commentFilter = true, List.empty ) new ScalastyleChecker().checkFiles(checker, config, Seq.empty) verify(checker).checkFiles(any(), any()) } }
Example 24
Source File: ScalastyleQualityProfileSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package scalastyle import scala.jdk.CollectionConverters._ import com.mwz.sonar.scala.metadata.scalastyle.ScalastyleRules import com.mwz.sonar.scala.metadata.scalastyle.ScalastyleRulesRepository.SkipTemplateInstances import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Inspectors, LoneElement} import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.{ BuiltInActiveRule, BuiltInQualityProfile, Context } class ScalastyleQualityProfileSpec extends AnyFlatSpec with Matchers with LoneElement with Inspectors { trait Ctx { val context = new Context() new ScalastyleQualityProfile().define(context) val qualityProfile: BuiltInQualityProfile = context.profilesByLanguageAndName.loneElement.value.loneElement.value val rules: Seq[BuiltInActiveRule] = qualityProfile.rules.asScala.toSeq } "ScalastyleQualityProfile" should "define a quality profile" in new Ctx { qualityProfile.language shouldBe "scala" qualityProfile.name shouldBe "Scalastyle" } it should "not be the default profile" in new Ctx { qualityProfile.isDefault shouldBe false } it should "activate all default (non-template) rules" in new Ctx { val activated = ScalastyleRules.rules .filter(i => i.params.isEmpty && !ScalastyleQualityProfile.BlacklistRules.contains(i.key)) .map(_.key) .toList rules.map(_.ruleKey) should contain allElementsOf activated } it should "have 69 rules" in new Ctx { rules should have size 69 // 41 default rules + 28 template instances } it should "not activate templates" in new Ctx { val templates = ScalastyleRules.rules .filter(_.params.nonEmpty) .map(i => s"${i.key}-template") .toList rules.map(_.ruleKey) should contain noElementsOf templates } it should "activate not excluded template rules" in new Ctx { val templateInstances = ScalastyleRules.rules .filter(i => i.params.nonEmpty && !SkipTemplateInstances.contains(i.key)) .map(_.key) .toList rules.map(_.ruleKey) should contain allElementsOf templateInstances val excluded = ScalastyleRules.rules .filter(i => SkipTemplateInstances.contains(i.key)) .map(_.key) .toList rules.map(_.ruleKey) should contain noElementsOf excluded } it should "have all rules come from the Scalastyle rules repository" in new Ctx { forEvery(rules)(rule => rule.repoKey shouldBe "sonar-scala-scalastyle") } it should "not have overridden any of the default params" in new Ctx { forEvery(rules)(rule => rule.overriddenParams shouldBe empty) } }
Example 25
Source File: ScalastyleRulesRepositorySpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package scalastyle import scala.jdk.CollectionConverters._ import com.mwz.sonar.scala.metadata.scalastyle.ScalastyleRules import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Inspectors, LoneElement} import org.sonar.api.rule.RuleStatus import org.sonar.api.rules.RuleType import org.sonar.api.server.rule.RulesDefinition.{Context, Repository, Rule} import org.sonar.api.server.rule.{RuleParamType, RulesDefinition} class ScalastyleRulesRepositorySpec extends AnyFlatSpec with Matchers with Inspectors with LoneElement { trait Ctx { val context = new Context() new ScalastyleRulesRepository().define(context) val repository: Repository = context.repositories.loneElement } "ScalastyleRulesRepository" should "define rules repository" in new Ctx { context.repositories should have size 1 } it should "correctly define repository properties" in new Ctx { repository.key shouldBe "sonar-scala-scalastyle" repository.name shouldBe "Scalastyle" repository.language shouldBe "scala" } it should "include all Scalastyle inspections" in new Ctx { ScalastyleRules.rules.length shouldBe 73 // 31 templates + 42 default rules ScalastyleRules.rules.map(r => r.key -> r).iterator.toMap.size shouldBe ScalastyleRules.rules.length repository.rules should have size 101 // 31 templates + 42 default rules + 28 template instances } it should "have all rules with non-empty properties" in new Ctx { forEvery(repository.rules) { rule => rule.key should not be empty rule.internalKey should not be empty rule.name should not be empty rule.markdownDescription should not be empty rule.severity should not be empty } } it should "have all rules' keys start with org.scalastyle" in new Ctx { forEvery(repository.rules)(rule => rule.key should startWith("org.scalastyle")) } it should "have all rules activated by default" in new Ctx { forEvery(repository.rules)(rule => rule.activatedByDefault shouldBe true) } it should "have all rules with READY status" in new Ctx { forEvery(repository.rules)(rule => rule.status shouldBe RuleStatus.READY) } it should "have all rules marked as CODE_SMELL" in new Ctx { forEvery(repository.rules)(rule => rule.`type` shouldBe RuleType.CODE_SMELL) } it should "have rules with parameters" in new Ctx { forAtLeast(1, repository.rules)(rule => rule.params should not be empty) } it should "not have rules with empty parameters" in new Ctx { val params: Seq[RulesDefinition.Param] = repository.rules.asScala .filter(r => !r.params.isEmpty) .flatMap(_.params.asScala) .toSeq forAll(params) { param => param.name should not be empty param.description should not be empty } } it should "have all rules contain ruleClass parameter" in new Ctx { val rules: Seq[Rule] = repository.rules.asScala.filter(r => !r.params.isEmpty).toSeq forEvery(rules) { rule => rule.params.asScala.exists(p => p.key === "ruleClass" && p.defaultValue.startsWith("org.scalastyle")) } } it should "create rules with correct parameters" in new Ctx { val rule: Rule = repository.rule("org.scalastyle.file.FileLineLengthChecker") val params: Seq[(String, RuleParamType, String)] = rule.params().asScala.map(p => (p.name, p.`type`, p.defaultValue)).toSeq val expected = Seq( ("maxLineLength", RuleParamType.INTEGER, "160"), ("tabSize", RuleParamType.INTEGER, "4"), ("ignoreImports", RuleParamType.BOOLEAN, "false"), ("ruleClass", RuleParamType.STRING, "org.scalastyle.file.FileLineLengthChecker") ) params should contain theSameElementsAs expected } }
Example 26
Source File: ScalaPluginSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.internal.SonarRuntimeImpl import org.sonar.api.utils.Version import org.sonar.api.{Plugin, SonarEdition, SonarQubeSide, SonarRuntime} class ScalaPluginSpec extends AnyFlatSpec with Matchers { val runtime: SonarRuntime = SonarRuntimeImpl.forSonarQube( Version.create(8, 3), SonarQubeSide.SCANNER, SonarEdition.COMMUNITY ) val context = new Plugin.Context(runtime) new ScalaPlugin().define(context) it should "provide global config" in { context.getExtensions should contain(classOf[GlobalConfig]) } it should "provide scala sensor" in { context.getExtensions should contain(classOf[Scala]) context.getExtensions should contain(classOf[sensor.ScalaSensor]) } it should "provide Github pr review job" in { context.getExtensions should contain(classOf[pr.GlobalIssues]) context.getExtensions should contain(classOf[pr.GithubPrReviewJob]) } it should "provide Scalastyle repository, quality profile & sensor" in { context.getExtensions should contain(classOf[scalastyle.ScalastyleRulesRepository]) context.getExtensions should contain(classOf[scalastyle.ScalastyleQualityProfile]) context.getExtensions should contain(classOf[scalastyle.ScalastyleChecker]) context.getExtensions should contain(classOf[scalastyle.ScalastyleSensor]) } it should "provide scapegoat repository, quality profile & sensor" in { context.getExtensions should contain(classOf[scapegoat.ScapegoatRulesRepository]) context.getExtensions should contain(classOf[scapegoat.ScapegoatQualityProfile]) context.getExtensions should contain(classOf[scapegoat.ScapegoatReportParser]) context.getExtensions should contain(classOf[scapegoat.ScapegoatSensor]) } it should "provide additional built-in quality profiles" in { context.getExtensions should contain(classOf[qualityprofiles.ScalastyleScapegoatQualityProfile]) context.getExtensions should contain(classOf[qualityprofiles.RecommendedQualityProfile]) } it should "provide scoverage sensor" in { context.getExtensions should contain(classOf[scoverage.ScoverageMeasures]) context.getExtensions should contain(classOf[scoverage.ScoverageMetrics]) context.getExtensions should contain(classOf[scoverage.ScoverageReportParser]) context.getExtensions should contain(classOf[scoverage.ScoverageSensor]) } it should "provide junit sensor" in { context.getExtensions should contain(classOf[junit.JUnitReportParser]) context.getExtensions should contain(classOf[junit.JUnitSensor]) } }
Example 27
Source File: ScalastyleRulesReposotorySpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.metadata package scalastyle import cats.data.Chain import cats.data.NonEmptyChain import enumeratum.scalacheck._ import org.scalacheck.Prop._ import org.scalacheck.Prop._ import org.scalacheck.ScalacheckShapeless._ import org.scalacheck._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.Checkers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class ScalastyleRulesRepositorySpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks with Checkers { implicit def chainArbOf[T](implicit a: Arbitrary[T]): Arbitrary[Chain[T]] = Arbitrary(Gen.listOf[T](a.arbitrary).map(Chain.apply)) def nonEmptyChainOf[T](implicit a: Arbitrary[T]): Gen[Chain[T]] = Gen.nonEmptyListOf[T](a.arbitrary).map(Chain.apply) it should "not create an additional rule from a non-template rule" in { forAll { rule: Rule => val extraParam = ScalastyleRulesRepository.extraParam(rule.key) val expected = rule.copy( template = false, params = Chain(extraParam) ) ScalastyleRulesRepository.fromTemplate(rule.copy(params = Chain.empty)) shouldBe NonEmptyChain.one( expected ) } } it should "not create an additional rule if the instance is blacklisted" in { check( forAllNoShrink( Arbitrary.arbitrary[Rule], nonEmptyChainOf[Param], Gen.oneOf(ScalastyleRulesRepository.SkipTemplateInstances.toList) ) { (rule, params, className) => val newRule = rule.copy(key = className, params = params) val extraParam = ScalastyleRulesRepository.extraParam(newRule.key) val expected = newRule.copy( key = className + "-template", template = true, params = params :+ extraParam ) ScalastyleRulesRepository.fromTemplate(newRule) === NonEmptyChain.one(expected) } ) } it should "create an additional rule for templates" in { check( forAllNoShrink( Arbitrary.arbitrary[Rule], nonEmptyChainOf[Param] ) { (rule, params) => val newRule = rule.copy(params = params) val extraParam = ScalastyleRulesRepository.extraParam(newRule.key) val instance = newRule.copy( template = false, params = params :+ extraParam ) val template = instance.copy( key = instance.key + "-template", template = true ) ScalastyleRulesRepository.fromTemplate(newRule) === NonEmptyChain(template, instance) } ) } it should "create an additional param with scalastyle class name" in { val expected = Param( name = "ruleClass", typ = ParamType.String, description = "Scalastyle's rule (checker) class name.", default = "scalastyle.class.name.test" ) ScalastyleRulesRepository.extraParam("scalastyle.class.name.test") shouldBe expected } }
Example 28
Source File: MeasuresSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package sensor import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scalariform.ScalaVersions case class Test()", scalaVersion) val count = Measures.countNonCommentLines(tokens) assert(count === 1) } it should "count the correct number of comments" in { val tokens = Scala.tokenize(exampleSourceFile, scalaVersion) val count = Measures.countNonCommentLines(tokens) assert(count === 18) } }
Example 29
Source File: ScalaSensorSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package sensor import java.nio.file.Paths import org.scalatest.LoneElement import org.scalatest.flatspec.AnyFlatSpec import org.sonar.api.batch.fs.internal.TestInputFileBuilder import org.sonar.api.batch.sensor.internal.{DefaultSensorDescriptor, SensorContextTester} import org.sonar.api.config.internal.MapSettings import org.sonar.api.measures.{CoreMetrics => CM} class ScalaSensorSpec extends AnyFlatSpec with SensorContextMatchers with LoneElement { val globalConfig = new GlobalConfig(new MapSettings().asConfig) val sensor = new ScalaSensor(globalConfig) behavior of "A ScalaSensor" it should "correctly set descriptor" in { val descriptor = new DefaultSensorDescriptor sensor.describe(descriptor) descriptor.name() shouldBe "Scala Sensor" descriptor.languages().loneElement shouldBe "scala" } it should "correctly measure ScalaFile1" in { val context = SensorContextTester.create(Paths.get("./src/test/resources")) val inputFile = TestInputFileBuilder.create("", "src/test/resources/ScalaFile1.scala").setLanguage("scala").build() context.fileSystem().add(inputFile) sensor.execute(context) val componentKey = inputFile.key() context should have(metric[java.lang.Integer](componentKey, CM.COMMENT_LINES_KEY, 0)) context should have(metric[java.lang.Integer](componentKey, CM.CLASSES_KEY, 1)) context should have(metric[java.lang.Integer](componentKey, CM.FUNCTIONS_KEY, 1)) context should have(metric[java.lang.Integer](componentKey, CM.NCLOC_KEY, 6)) } it should "correctly measure ScalaFile2" in { val context = SensorContextTester.create(Paths.get("./src/test/resources")) val inputFile = TestInputFileBuilder.create("", "src/test/resources/ScalaFile2.scala").setLanguage("scala").build() context.fileSystem().add(inputFile) sensor.execute(context) val componentKey = inputFile.key() context should have(metric[java.lang.Integer](componentKey, CM.COMMENT_LINES_KEY, 1)) context should have(metric[java.lang.Integer](componentKey, CM.CLASSES_KEY, 2)) context should have(metric[java.lang.Integer](componentKey, CM.FUNCTIONS_KEY, 2)) } }
Example 30
Source File: PathUtilsSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package util import java.nio.file.Paths import com.mwz.sonar.scala.util.PathUtils._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.batch.fs.internal.DefaultFileSystem class PathUtilsSpec extends AnyFlatSpec with Matchers { "relativize" should "successfully resolve a relative suffix path against a 'next' path" in { PathUtils.relativize( base = Paths.get("."), next = Paths.get(""), fullOrSuffix = Paths.get("suffix") ) shouldBe Paths.get("suffix") PathUtils.relativize( base = Paths.get("."), next = Paths.get("next"), fullOrSuffix = Paths.get("suffix") ) shouldBe Paths.get(s"next/suffix") PathUtils.relativize( base = cwd, next = Paths.get("next"), fullOrSuffix = Paths.get("suffix/test") ) shouldBe Paths.get(s"next/suffix/test") } it should "construct a relative path between the 'base' path and an absolute suffix" in { PathUtils.relativize( base = cwd, next = Paths.get(""), fullOrSuffix = cwd.resolve("suffix/test") ) shouldBe Paths.get("suffix/test") } "stripOutPrefix" should "successfully strip out the prefix" in { PathUtils.stripOutPrefix( prefix = Paths.get("a/b"), path = Paths.get("a/b/c") ) shouldBe Paths.get("c") PathUtils.stripOutPrefix( prefix = Paths.get("x/y"), path = Paths.get("a/b/c") ) shouldBe Paths.get("a/b/c") } "getModuleBaseDirectory" should "get module base directory" in { getProjectBaseDirectory(new DefaultFileSystem(cwd)) shouldBe Paths.get("") getProjectBaseDirectory( new DefaultFileSystem(cwd.resolve("module")) ) shouldBe Paths.get("module") } }
Example 31
Source File: LogSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package util import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.utils.log.LoggerLevel._ import org.sonar.api.utils.log._ class LogSpec extends AnyFlatSpec with Matchers with SonarLogTester { "Log" should "log debug" in { val log = Log(classOf[LogSpec], "test") log.debug("debug") logsFor(DEBUG) shouldBe Seq("[sonar-scala-test] debug") } it should "log info" in { val log = Log(classOf[LogSpec], "test") log.info("info") logsFor(INFO) shouldBe Seq("[sonar-scala-test] info") } it should "log warn" in { val log = Log(classOf[LogSpec], "test") log.warn("warn") logsFor(WARN) shouldBe Seq("[sonar-scala-test] warn") } it should "log error" in { val log = Log(classOf[LogSpec], "test") log.error("error") logsFor(ERROR) shouldBe Seq("[sonar-scala-test] error") } it should "default the prefix to sonar-scala" in { val log = Log(classOf[LogSpec]) log.info("info") logsFor(INFO) shouldBe Seq("[sonar-scala] info") } }
Example 32
Source File: SonarSensorContextSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package util package syntax import java.nio.file.Paths import com.mwz.sonar.scala.util.syntax.SonarSensorContext._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.batch.fs.internal.TestInputFileBuilder import org.sonar.api.batch.sensor.internal.SensorContextTester import org.sonar.api.measures.CoreMetrics class SonarSensorContextSpec extends AnyFlatSpec with Matchers with SensorContextMatchers { it should "save a measure for a given input file" in { val ctx = SensorContextTester.create(Paths.get("./")) val testFile = TestInputFileBuilder .create("", "TestFile.scala") .build() ctx.saveMeasure[Integer](testFile, CoreMetrics.TESTS, 5) ctx.saveMeasure[java.lang.Long](testFile, CoreMetrics.TEST_EXECUTION_TIME, 124L) ctx should have(metric[Integer](testFile.key, "tests", 5)) ctx should have(metric[java.lang.Long](testFile.key, "test_execution_time", 124L)) } }
Example 33
Source File: SonarConfigSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package util package syntax import java.nio.file.Paths import com.mwz.sonar.scala.util.syntax.SonarConfig._ import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.config.internal.MapSettings class SonarConfigSpec extends AnyFlatSpec with Matchers with OptionValues { "config" should "get paths" in { val conf = new MapSettings() .setProperty("path", "this/is/a/path, another/path") .asConfig() val defaultPaths = List(Paths.get("default/path"), Paths.get("default/path2")) conf.getPaths("path", defaultPaths) shouldBe List( Paths.get("this/is/a/path"), Paths.get("another/path") ) conf.getPaths("not.a.path", defaultPaths) shouldBe defaultPaths } it should "get a boolean" in { val conf = new MapSettings() .setProperty("bool.true", "true") .setProperty("bool.true2", "TRUE") .setProperty("bool.false", "false") .asConfig() conf.getAs[Boolean]("bool.true") shouldBe true conf.getAs[Boolean]("bool.true2") shouldBe true conf.getAs[Boolean]("bool.false") shouldBe false conf.getAs[Boolean]("not.a.bool") shouldBe false } it should "get a string" in { val conf = new MapSettings() .setProperty("text", "hello") .setProperty("number", "55") .setProperty("bool", "true") .asConfig() conf.getAs[String]("text").value shouldBe "hello" conf.getAs[String]("number").value shouldBe "55" conf.getAs[String]("bool").value shouldBe "true" conf.getAs[String]("empty") shouldBe empty } }
Example 34
Source File: OptionalsSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package util package syntax import java.util.Optional import Optionals._ import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class OptionalsSpec extends AnyFlatSpec with Matchers with OptionValues { it should "convert Java Optional to Scala Option" in { Optional.of("test").toOption.value shouldBe "test" Optional.empty[String].toOption shouldBe empty } it should "convert Scala Option to Java Optional" in { Some("test").toOptional shouldBe Optional.of("test") None.toOptional shouldBe Optional.empty } }
Example 35
Source File: SonarFileSystemSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package util package syntax import java.nio.file.{Path, Paths} import cats.instances.list._ import cats.instances.option._ import com.mwz.sonar.scala.util.syntax.SonarFileSystem._ import org.mockito.ArgumentMatchers._ import org.mockito.Mockito._ import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.mockito.MockitoSugar import org.sonar.api.batch.fs.FileSystem import org.sonar.api.batch.fs.internal.DefaultFileSystem class SonarFileSystemSpec extends AnyFlatSpec with Matchers with OptionValues with MockitoSugar { it should "attempt to resolve paths" in { val fs = new DefaultFileSystem(Paths.get("./")) val paths = List(Paths.get("path/1"), Paths.get("path/2")) fs.resolve(paths) shouldBe List( Paths.get("./").resolve("path/1").toAbsolutePath.normalize.toFile, Paths.get("./").resolve("path/2").toAbsolutePath.normalize.toFile ) val path: Option[Path] = Some(Paths.get("another/path")) fs.resolve(path).value shouldBe Paths.get("./").resolve("another/path").toAbsolutePath.normalize.toFile } it should "handle exceptions gracefully" in { val fs = mock[FileSystem] val path = List(Paths.get("path")) when(fs.resolvePath(any())).thenThrow(new RuntimeException()) fs.resolve(path) shouldBe empty } }
Example 36
Source File: LoggerSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.util import cats.effect.IO import com.mwz.sonar.scala.util.syntax.Optionals._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{LoneElement, OptionValues} import org.sonar.api.utils.log.LoggerLevel._ import org.sonar.api.utils.log.SonarLogTester class LoggerSpec extends AnyFlatSpec with Matchers with LoneElement with OptionValues with SonarLogTester { trait Context { val log: IO[Logger[IO]] = Logger.create(classOf[LoggerSpec], "test") } it should "log debug" in new Context { log.flatMap(_.debug("debug")).unsafeRunSync() logsFor(DEBUG) shouldBe Seq("[sonar-scala-test] debug") } it should "log info" in new Context { log.flatMap(_.info("info")).unsafeRunSync() logsFor(INFO) shouldBe Seq("[sonar-scala-test] info") } it should "log warn" in new Context { log.flatMap(_.warn("warn")).unsafeRunSync() logsFor(WARN) shouldBe Seq("[sonar-scala-test] warn") } it should "log error" in new Context { log.flatMap(_.error("error")).unsafeRunSync() logsFor(ERROR) shouldBe Seq("[sonar-scala-test] error") } it should "log error with a throwable" in new Context { log.flatMap(_.error("error", new Exception("cause"))).unsafeRunSync() val result = getLogsFor(ERROR).loneElement result.getFormattedMsg shouldBe "[sonar-scala-test] error" val exception = result.getArgs.toOption.value.loneElement exception shouldBe a[Exception] exception.asInstanceOf[Exception].getMessage shouldBe "cause" } it should "default the prefix to sonar-scala" in { val log: IO[Logger[IO]] = Logger.create(classOf[LoggerSpec]) log.flatMap(_.info("info")).unsafeRunSync() logsFor(INFO) shouldBe Seq("[sonar-scala] info") } }
Example 37
Source File: RecommendedQualityProfileSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala package qualityprofiles import scala.jdk.CollectionConverters._ import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.{ BuiltInActiveRule, BuiltInQualityProfile, Context } class RecommendedQualityProfileSpec extends AnyFlatSpec with Inspectors with LoneElement with OptionValues with Matchers { trait Ctx { val context: Context = new Context() new RecommendedQualityProfile().define(context) val qualityProfile: BuiltInQualityProfile = context.profilesByLanguageAndName.loneElement.value.loneElement.value val rules: Seq[BuiltInActiveRule] = qualityProfile.rules.asScala.toSeq } "RecommendedQualityProfile" should "define a quality profile" in new Ctx { qualityProfile.language shouldBe "scala" qualityProfile.name shouldBe "Recommended by sonar-scala" } it should "be the default profile" in new Ctx { qualityProfile.isDefault shouldBe true } it should "have 179 rules" in new Ctx { rules.size shouldBe 179 // 64 from Scalastyle + 115 from Scapegoat } it should "have all rules come from either the Scalastyle or the Scapegoat rules repositories" in new Ctx { forEvery(rules) { rule => rule.repoKey should (be("sonar-scala-scalastyle") or be("sonar-scala-scapegoat")) } } it should "have overridden the default params" in new Ctx { val rulesWithOverridenParams = rules.filterNot(_.overriddenParams.isEmpty) val paramOverrides = RecommendedQualityProfile.ScapegoatOverrides.params ++ RecommendedQualityProfile.ScalastyleOverrides.params rulesWithOverridenParams.size shouldBe paramOverrides.size forEvery(rulesWithOverridenParams) { rule => rule.overriddenParams.asScala.map(p => (p.key, p.overriddenValue)) should contain theSameElementsAs paramOverrides.get(rule.ruleKey).value.toSeq } } it should "have overridden the default severities" in new Ctx { val rulesWithOverridenSeverities = rules.filterNot(rule => Option(rule.overriddenSeverity).isEmpty) val severityOverrides = RecommendedQualityProfile.ScapegoatOverrides.severities ++ RecommendedQualityProfile.ScalastyleOverrides.severities rulesWithOverridenSeverities.size shouldBe severityOverrides.size forEvery(rulesWithOverridenSeverities) { rule => rule.overriddenSeverity shouldBe severityOverrides.get(rule.ruleKey).value.name } } }
Example 38
Source File: ScalastyleScapegoatQualityProfileSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.qualityprofiles import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Inspectors, LoneElement} import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.{BuiltInQualityProfile, Context} class ScalastyleScapegoatQualityProfileSpec extends AnyFlatSpec with Inspectors with LoneElement with Matchers { trait Ctx { val context = new Context() new ScalastyleScapegoatQualityProfile().define(context) val qualityProfile: BuiltInQualityProfile = context.profilesByLanguageAndName.loneElement.value.loneElement.value val rules = qualityProfile.rules } "Scalastyle+ScapegoatQualityProfile" should "define only one quality profile" in new Ctx { context.profilesByLanguageAndName should have size 1 // by language context.profilesByLanguageAndName.loneElement.value should have size 1 // by language and name } it should "properly define the properties of the quality profile" in new Ctx { qualityProfile.name shouldBe "Scalastyle+Scapegoat" qualityProfile.language shouldBe "scala" } it should "not be the default quality profile" in new Ctx { qualityProfile.isDefault shouldBe false } it should "define all Scalastyle + Scapegoat rules" in new Ctx { qualityProfile.rules should have size 187 // 69 from Scalastyle + 118 from Scapegoat } it should "have all rules come from either the Scalastyle or the Scapegaot rules repositories" in new Ctx { forEvery(rules) { rule => rule.repoKey should (be("sonar-scala-scalastyle") or be("sonar-scala-scapegoat")) } } it should "not have overridden any of the default params" in new Ctx { forEvery(rules)(rule => rule.overriddenParams shouldBe empty) } }
Example 39
Source File: ScapegoatRulesRepositorySpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.scapegoat import com.mwz.sonar.scala.metadata.scapegoat.ScapegoatRules import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Inspectors, LoneElement} import org.sonar.api.rule.{RuleStatus, Severity} import org.sonar.api.rules.RuleType import org.sonar.api.server.rule.RulesDefinition.Context class ScapegoatRulesRepositorySpec extends AnyFlatSpec with Inspectors with LoneElement with Matchers { trait Ctx { val context = new Context() new ScapegoatRulesRepository().define(context) val repository = context.repositories.loneElement val rules = repository.rules } "ScapegoatRulesRepository" should "define only one repository" in new Ctx { context.repositories should have size 1 } it should "properly define the properties of the repository" in new Ctx { repository.key shouldBe "sonar-scala-scapegoat" repository.name shouldBe "Scapegoat" repository.language shouldBe "scala" } it should "define one rule for each scapegoat inspection" in new Ctx { rules should have size ScapegoatRules.rules.length } it should "properly define the properties of the ArrayEquals rule" in new Ctx { val arrayEqualsRule = repository.rule("com.sksamuel.scapegoat.inspections.collections.ArrayEquals") arrayEqualsRule.internalKey shouldBe "com.sksamuel.scapegoat.inspections.collections.ArrayEquals" arrayEqualsRule.name shouldBe "Array equals" arrayEqualsRule.markdownDescription shouldBe "*Checks for comparison of arrays using == which will always return false.*\n\n======= Array equals is not an equality check. Use a.deep == b.deep or convert to another collection type." arrayEqualsRule.activatedByDefault shouldBe true arrayEqualsRule.status shouldBe RuleStatus.READY arrayEqualsRule.severity shouldBe Severity.INFO arrayEqualsRule.`type` shouldBe RuleType.CODE_SMELL } "All Scapegoat Rules" should "have a valid internal key" in new Ctx { forEvery(rules)(rule => rule.internalKey should startWith("com.sksamuel.scapegoat.inspections")) } it should "have a non-empty name" in new Ctx { forEvery(rules)(rule => rule.name should not be empty) } it should "have a non-empty description" in new Ctx { forEvery(rules)(rule => rule.markdownDescription should not be empty) } it should "be activated by default" in new Ctx { forEvery(rules)(rule => rule.activatedByDefault shouldBe true) } it should "have a READY status" in new Ctx { forEvery(rules)(rule => rule.status shouldBe RuleStatus.READY) } it should "have a valid severity" in new Ctx { forEvery(rules) { rule => val ruleSeverity = rule.severity forExactly(1, Severity.ALL)(severity => ruleSeverity shouldBe severity) } } it should "be a CODE_SMELL" in new Ctx { forEvery(rules)(rule => rule.`type` shouldBe RuleType.CODE_SMELL) } }
Example 40
Source File: ScapegoatQualityProfileSpec.scala From sonar-scala with GNU Lesser General Public License v3.0 | 5 votes |
package com.mwz.sonar.scala.scapegoat import com.mwz.sonar.scala.metadata.scapegoat.ScapegoatRules import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Inspectors, LoneElement} import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.Context class ScapegoatQualityProfileSpec extends AnyFlatSpec with Inspectors with LoneElement with Matchers { trait Ctx { val context = new Context() new ScapegoatQualityProfile().define(context) val qualityProfile = context.profilesByLanguageAndName.loneElement.value.loneElement.value val rules = qualityProfile.rules } "ScapegoatQualityProfile" should "define only one quality profile" in new Ctx { context.profilesByLanguageAndName should have size 1 // by language context.profilesByLanguageAndName.loneElement.value should have size 1 // by language and name } it should "properly define the properties of the quality profile" in new Ctx { qualityProfile.name shouldBe "Scapegoat" qualityProfile.language shouldBe "scala" } it should "not be the default quality profile" in new Ctx { qualityProfile.isDefault shouldBe false } it should "activate one rule for each scapegoat inspection" in new Ctx { qualityProfile.rules should have size ScapegoatRules.rules.length } it should "have all rules come from the Scapegaot rules repository" in new Ctx { forEvery(rules)(rule => rule.repoKey shouldBe "sonar-scala-scapegoat") } it should "not have overridden any of the default params" in new Ctx { forEvery(rules)(rule => rule.overriddenParams shouldBe empty) } }
Example 41
Source File: IncompatibleClientSpec.scala From seals with Apache License 2.0 | 5 votes |
package com.example.lib import cats.effect.IO import org.scalatest.Inside import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import fs2.{ Stream, Chunk } import scodec.bits._ import scodec.stream.StreamEncoder import dev.tauri.seals.scodec.StreamCodecs import dev.tauri.seals.scodec.StreamCodecs._ import Protocol.v2 import Protocol.v1.Seed class IncompatibleClientSpec extends AnyFlatSpec with Matchers with Inside with TcpTest { protected override def ec = scala.concurrent.ExecutionContext.global val reqCodec: StreamEncoder[v2.Request] = streamEncoderFromReified[v2.Request] override def afterAll(): Unit = { super.afterAll() } "Client with incompatible schema" should "be rejected" ignore { // TODO val resp: Either[Throwable, Vector[v2.Response]] = Server.serveAddr(0, sockGroup).flatMap { localAddr => incompatibleClient(localAddr.getPort) }.take(1L).compile.toVector.attempt.unsafeRunSync() inside(resp) { case Left(ex) => ex.getMessage should include ("incompatible models") } } def incompatibleClient(port: Int): Stream[IO, v2.Response] = { Stream.resource(sockGroup.client[IO](Server.addr(port))).flatMap { socket => val bvs: Stream[IO, BitVector] = reqCodec.encode[IO](Stream(Seed(42): v2.Request)) val bs: Stream[IO, Byte] = bvs.flatMap { bv => Stream.chunk(Chunk.bytes(bv.bytes.toArray)) } val read = bs.through(socket.writes(Server.timeout)).drain.onFinalize(socket.endOfOutput) ++ socket.reads(Server.bufferSize, Server.timeout).chunks.map(ch => BitVector.view(ch.toArray)) read.through(StreamCodecs.pipe[IO, v2.Response]) } } }
Example 42
Source File: ClientSpec.scala From seals with Apache License 2.0 | 5 votes |
package com.example.lib import scala.concurrent.Await import scala.concurrent.duration._ import cats.effect.IO import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import fs2.Stream import akka.actor.ActorSystem import akka.stream.{ Materializer, ActorMaterializer } import Protocol.v1.{ Response, RandInt, Seeded } class ClientSpec extends AnyFlatSpec with Matchers with com.example.lib.TcpTest { implicit lazy val sys: ActorSystem = ActorSystem("InteropSpec") implicit lazy val mat: Materializer = ActorMaterializer() protected override def ec = sys.dispatcher override def afterAll(): Unit = { super.afterAll() sys.terminate() } "Client" should "receive the correct response" in { val sem = cats.effect.concurrent.Semaphore[IO](0).unsafeRunSync() Stream(Server.serve(1237, sockGroup).drain, Stream.eval(sem.acquire)) .parJoin(Int.MaxValue) .take(1) .compile .drain .unsafeRunAsync(_ => ()) try { val resp = Await.result(Client.client(1237), 2.seconds) // constant, because we always seed with the same value: resp should === (Vector[Response](Seeded, RandInt(42))) } finally { sem.release.unsafeRunSync() } } }
Example 43
Source File: ServerSpec.scala From seals with Apache License 2.0 | 5 votes |
package com.example.lib import java.util.concurrent.Executors import java.nio.channels.{ AsynchronousChannelGroup => ACG } import scala.concurrent.ExecutionContext import cats.effect.IO import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import fs2.{ Stream, Chunk } import scodec.bits._ import Protocol.v1.{ Response, Request, Random, RandInt, Seed, Seeded } import dev.tauri.seals.scodec.StreamCodecs class ServerSpec extends AnyFlatSpec with Matchers with TcpTest { val ex = Executors.newCachedThreadPool() implicit val cg = ACG.withThreadPool(ex) implicit override lazy val ec = ExecutionContext.global override def afterAll(): Unit = { super.afterAll() cg.shutdown() ex.shutdown() } "Server" should "respond to requests" in { val nClients = 20 val nRandom = testData.count { case Random(_, _) => true case _ => false } val nSeed = testData.count { case Seed(_) => true case _ => false } val str: Stream[IO, Stream[IO, Response]] = Server.serveAddr(0, this.sockGroup).map { localAddr => clients(localAddr.getPort, nClients) } val responses: Vector[Response] = str .parJoin(Int.MaxValue) .take((nClients * testData.size).toLong).compile.toVector.unsafeRunSync() val randInts = responses.collect { case RandInt(i) => i } val seededs = responses.collect { case Seeded => () } randInts.size should === (nClients * nRandom) randInts.foreach { i => i should be >= 1 i should be <= 100 } seededs.size should === (nClients * nSeed) } val testData = Vector[Request]( Random(10, 19), Seed(0xdeadbeefL), Random(1, 100) ) def clients(port: Int, count: Int, maxConcurrent: Int = 10): Stream[IO, Response] = { val cls: Stream[IO, Stream[IO, Response]] = { Stream.range(0, count).map { i => Stream.resource(this.sockGroup.client[IO](Server.addr(port))).flatMap { socket => val bvs: Stream[IO, BitVector] = StreamCodecs.streamEncoderFromReified[Request].encode(Stream.emits(testData).covary[IO]) val bs: Stream[IO, Byte] = bvs.flatMap { bv => Stream.chunk(Chunk.bytes(bv.bytes.toArray)) } val read = bs.through(socket.writes(Server.timeout)).drain.onFinalize(socket.endOfOutput) ++ socket.reads(Server.bufferSize, Server.timeout).chunks.map(ch => BitVector.view(ch.toArray)) read.through(StreamCodecs.pipe[IO, Response]) } } } cls.parJoin(maxConcurrent) } }
Example 44
Source File: StreamingSpec.scala From seals with Apache License 2.0 | 5 votes |
package com.example.streaming import java.io.{ ByteArrayInputStream, ByteArrayOutputStream } import shapeless.record._ import cats.effect.IO import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import fs2.Stream import scodec.Codec import scodec.bits.BitVector import scodec.stream.CodecError import dev.tauri.seals._ import dev.tauri.seals.scodec.Codecs._ import dev.tauri.seals.scodec.StreamCodecs._ class StreamingSpec extends AnyFlatSpec with Matchers { import Main.{ Animal, Elephant, Quokka, Quagga, Grey } val animals = Vector[Animal]( Elephant("Dumbo", tuskLength = 35.0f), Quokka("Nellie"), Quagga("Ford", speed = 120.0) ) val transformedAnimals = Vector[Animal]( Elephant("Dumbo", tuskLength = 35.0f + 17.0f), Quokka("Nellie", Grey) ) val animalStream = Stream.emits[IO, Animal](animals) val encoder = streamEncoderFromReified[Animal] val decoder = streamDecoderFromReified[Animal] "Encoding/decoding" should "work correctly" in { val tsk: IO[Unit] = for { bv <- encoder.encode[IO](animalStream).compile.fold(BitVector.empty)(_ ++ _) as <- decoder.decode[IO](Stream(bv)).compile.toVector } yield { as should === (animals) } tsk.unsafeRunSync() } it should "fail with incompatible models" in { val mod = Reified[Record.`'Elephant -> Elephant, 'Quokka -> Quokka`.T].model val bv: BitVector = Codec[Model].encode(mod).getOrElse(fail) val tsk: IO[Unit] = for { as <- decoder.decode[IO](Stream(bv)).compile.toVector } yield { as should === (Vector.empty) } val ex = intercept[CodecError] { tsk.unsafeRunSync() } ex.err.message should include ("incompatible models") } "Transformation" should "work correctly" in { val tsk: IO[Unit] = for { ibv <- encoder.encode[IO](animalStream).compile.fold(BitVector.empty)(_ ++ _) is = new ByteArrayInputStream(ibv.toByteArray) os = new ByteArrayOutputStream _ <- Main.transform(is, os)(Main.transformer) obv = BitVector(os.toByteArray()) transformed <- decoder.decode[IO](Stream(obv)).compile.fold(Vector.empty[Animal])(_ :+ _) } yield { transformed should === (transformedAnimals) } tsk.unsafeRunSync() } }
Example 45
Source File: UUIDMacroSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package macros import java.util.UUID import shapeless.test.{ typed, illTyped } import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalactic.TypeCheckedTripleEquals class UUIDMacroSpec extends AnyFlatSpec with Matchers with TypeCheckedTripleEquals { def uuid: Nothing = sys.error("this should never be invoked") "UUID literal macro" should "work" in { val x = uuid"3a108ce3-9284-4883-a72c-71ced1f30e4c" typed[UUID] { x } x.variant should === (2) x.version should === (4) x should === (UUID.fromString("3a108ce3-9284-4883-a72c-71ced1f30e4c")) } it should "reject non-RFC-4122 UUIDs" in { val str = "00000000-0000-0001-0000-000000000002" val u = UUID.fromString(str) u.variant should !== (2) illTyped( """uuid"00000000-0000-0001-0000-000000000002"""", ".*not an RFC-4122 UUID.*" ) } it should "reject syntactically invalid strings" in { illTyped( """uuid"abcd"""", ".*not a valid UUID.*" ) } it should "only accept string literals" in { illTyped( """ val v: String = "3a108ce3-9284-4883-a72c-71ced1f30e4c" StringContext(v).uuid() """, ".*not a string literal.*" ) } }
Example 46
Source File: ReifiedEqSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package laws import cats.Eq import shapeless._ import shapeless.syntax.singleton._ import shapeless.record._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalacheck.Arbitrary class ReifiedEqSpec extends AnyFlatSpec with Matchers { def reifiedEq[A: Arbitrary]: Eq[Reified[A]] = ReifiedEqSpec.Helper.testEqForReified type XY = Record.`'x -> Int, 'y -> String`.T type XYZ1 = Record.`'a -> XY, 'z -> Float`.T type YZ = Record.`'y -> String, 'z -> Float`.T type XYZ2 = Record.`'x -> Int, 'a -> YZ`.T implicitly[XYZ1 =:!= XYZ2] "The test Eq[Reified] instance" should "allow tuple nesting differences" in { implicit def arbXyz1(implicit arbTup: Arbitrary[(Int, String, Float)]): Arbitrary[XYZ1] = Arbitrary { for { t <- arbTup.arbitrary } yield { 'a ->> ('x ->> t._1 :: 'y ->> t._2 :: HNil) :: 'z ->> t._3 :: HNil } } val r1: Reified[XYZ1] = Reified[XYZ1] val r2: Reified[XYZ1] = Reified[XYZ2].imap[XYZ1] { xyz2 => 'a ->> ('x ->> xyz2.head :: 'y ->> xyz2.tail.head('y) :: HNil) :: 'z ->> xyz2.tail.head('z) :: HNil } { xyz1 => 'x ->> xyz1.head('x) :: 'a ->> ('y ->> xyz1.head('y) :: 'z ->> xyz1.tail.head :: HNil) :: HNil } reifiedEq[XYZ1].eqv(r1, r2) should be (true) } it should "not allow additional fields" in { val r1 = Reified[(Int, String)] val r2 = Reified[(Int, String, Float)].imap[(Int, String)] { case (i, s, _) => (i, s) } { case (i, s) => (i, s, 0.0f) } reifiedEq[(Int, String)].eqv(r1, r2) should be (false) } it should "not allow field reordering" in { val r1 = Reified[(Int, String)] val r2 = Reified[(String, Int)].imap[(Int, String)] { case (s, i) => (i, s) } { case (i, s) => (s, i) } reifiedEq[(Int, String)].eqv(r1, r2) should be (false) } } object ReifiedEqSpec { object Helper extends TestEqInstances }
Example 47
Source File: CanonicalReprSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package tests import cats.Order import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import core.CanonicalRepr import laws.TestArbInstances.{ arbModel, arbCanonicalRepr, arbSymbol } import laws.TestArbInstances.forTestData.arbDefsAdt1 import laws.TestTypes.adts.defs.Adt1 class CanonicalReprSpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { val ord = Order[CanonicalRepr] "fold-unfold" should "be an identity" in { forAll { x: Int => foldUnfold(x) should === (x) } forAll { x: String => foldUnfold(x) should === (x) } forAll { x: Model => foldUnfold(x) should === (x) } forAll { x: Adt1 => foldUnfold(x) should === (x) } } def foldUnfold[A](a: A)(implicit r: Reified[A]): A = CanonicalRepr.roundtrip(a)(r) "Order[CanonicalRepr]" should "be consistent with .equals" in { forAll { (x: CanonicalRepr, y: CanonicalRepr) => if (ord.eqv(x, y)) { x should === (y) } else { x should !== (y) } } } "product" should "create correct HCons/HNil" in { import CanonicalRepr.{ HCons, HNil } val act = CanonicalRepr.product( 'a -> CanonicalRepr.Atom("1"), 'b -> CanonicalRepr.Atom("2"), 'c -> CanonicalRepr.Atom("3") ) val exp = HCons( 'a, CanonicalRepr.Atom("1"), HCons( 'b, CanonicalRepr.Atom("2"), HCons( 'c, CanonicalRepr.Atom("3"), HNil ) ) ) act should === (exp) CanonicalRepr.product() should === (HNil) } }
Example 48
Source File: SchemaSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package test import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import shapeless.Witness @schema final case class Foo(i: Int, s: String) @schema sealed trait ST final case class X(i: Int) extends ST object ST // SI-7046 workaround object A { @schema final case class Foo(i: Int, f: Float) @schema sealed trait ST final case class X(b: Boolean) extends ST object ST // SI-7046 workaround object Bar { final val constModel = "bar" } object Baz { final val constModel: Witness.`"baz"`.T = "baz" } } class SchemaSpec extends AnyFlatSpec with Matchers { "Extract" should "work" in { import SchemaExtractor.extract extract("dev.tauri.seals.test.A.Bar", "constModel") should === ("bar") extract("dev.tauri.seals.test.A.Baz", "constModel") should === ("baz") } "@schema" should "put a cached implicit val into the companion object" in { val inst = Foo.reifiedFoo inst shouldBe theSameInstanceAs (implicitly[Reified[Foo]]) inst.model should === (Reified[Foo].model) ST.reifiedST.model should === (Reified[ST].model) ST.reifiedST shouldBe theSameInstanceAs (implicitly[Reified[ST]]) A.Foo.reifiedFoo.model should === (Reified[A.Foo].model) A.ST.reifiedST.model should === (Reified[A.ST].model) } }
Example 49
Source File: ExtractorSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package checker import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import io.circe.Decoder import circe.Codecs._ class ExtractorSpec extends AnyFlatSpec with Matchers { val decoder = Decoder[Model] val pack = this.getClass.getPackage.getName val fooName = s"$pack.Foo" val ccName = s"$pack.CC" val wfooName = s"$pack.Wrap.WFoo" val wccName = s"$pack.Wrap.WCC" // force WFoo subclasses (SI-7046 workaround): def dummy1: Wrap.Bar = sys.error("dummy1") def dummy2: Wrap.Baz.type = sys.error("dummy2") val extractor = Extractor( this.getClass.getClassLoader, new java.io.File(this.getClass.getProtectionDomain.getCodeSource.getLocation.toURI) ) "Extractor#allClasses" should "find every class" in { extractor.allClasses(pack) should contain allOf ( "Foo", "Foo$", "CC", "CC$", "Wrap$" ) } "Extractor#extractAll" should "find all marked classes in a package" in { val models: Map[String, Model] = extractor.extractAll(pack) val expected = Map( fooName -> Foo.reifiedFoo.model, ccName -> CC.reifiedCC.model, wfooName -> Wrap.WFoo.reifiedWFoo.model, wccName -> Wrap.WCC.reifiedWCC.model ) models should === (expected) } "Extractor#allSchemas" should "collect all annotated classes" in { extractor.allSchemasOfPackage(pack).map(_.fullName).toSet should === (Set( fooName, ccName, wfooName, wccName )) } }
Example 50
Source File: BoxStoreTest.scala From fs2-blobstore with Apache License 2.0 | 5 votes |
package blobstore.box import java.util.concurrent.Executors import blobstore.Path import cats.effect.{Blocker, ContextShift, IO} import com.box.sdk.BoxAPIConnection import org.scalatest.matchers.must.Matchers import org.scalatest.flatspec.AnyFlatSpec import scala.concurrent.ExecutionContext class BoxStoreTest extends AnyFlatSpec with Matchers { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val blocker = Blocker.liftExecutionContext(ExecutionContext.fromExecutor(Executors.newCachedThreadPool)) "splitPath" should "correctly split a long path" in { val boxStore = new BoxStore[IO](new BoxAPIConnection(""), "", blocker) val testPath = Path("long/path/to/filename") val (pathToParentFolder, key) = boxStore.splitPath(testPath) pathToParentFolder must be("long" :: "path" :: "to" :: Nil) key must be("filename") } it should "split a single element path into a single element list and empty string key" in { val boxStore = new BoxStore[IO](new BoxAPIConnection(""), "", blocker) val testPath = Path("filename") val (pathToParentFolder, key) = boxStore.splitPath(testPath) pathToParentFolder must be("filename"::Nil) key must be("") } it should "split an empty path into empty list, empty string key" in { val boxStore = new BoxStore[IO](new BoxAPIConnection(""), "", blocker) val testPath = Path("") val (pathToParentFolder, key) = boxStore.splitPath(testPath) pathToParentFolder must be(""::Nil) key must be("") } }
Example 51
Source File: StoreOpsTest.scala From fs2-blobstore with Apache License 2.0 | 5 votes |
package blobstore import java.nio.charset.Charset import java.nio.file.Files import java.util.concurrent.Executors import cats.effect.{Blocker, IO} import cats.effect.laws.util.TestInstances import cats.implicits._ import fs2.Pipe import org.scalatest.Assertion import org.scalatest.flatspec.AnyFlatSpec import implicits._ import org.scalatest.matchers.must.Matchers import scala.collection.mutable.ArrayBuffer import scala.concurrent.ExecutionContext class StoreOpsTest extends AnyFlatSpec with Matchers with TestInstances { implicit val cs = IO.contextShift(ExecutionContext.global) val blocker = Blocker.liftExecutionContext(ExecutionContext.fromExecutor(Executors.newCachedThreadPool)) behavior of "PutOps" it should "buffer contents and compute size before calling Store.put" in { val bytes: Array[Byte] = "AAAAAAAAAA".getBytes(Charset.forName("utf-8")) val store = DummyStore(_.size must be(Some(bytes.length))) fs2.Stream.emits(bytes).covary[IO].through(store.bufferedPut(Path("path/to/file.txt"), blocker)).compile.drain.unsafeRunSync() store.buf.toArray must be(bytes) } it should "upload a file from a nio Path" in { val bytes = "hello".getBytes(Charset.forName("utf-8")) val store = DummyStore(_.size must be(Some(bytes.length))) fs2.Stream.bracket(IO(Files.createTempFile("test-file", ".bin"))) { p => IO(p.toFile.delete).void }.flatMap { p => fs2.Stream.emits(bytes).covary[IO].through(fs2.io.file.writeAll(p, blocker)).drain ++ fs2.Stream.eval(store.put(p, Path("path/to/file.txt"), blocker)) }.compile.drain.unsafeRunSync() store.buf.toArray must be(bytes) } } final case class DummyStore(check: Path => Assertion) extends Store[IO] { val buf = new ArrayBuffer[Byte]() override def put(path: Path): Pipe[IO, Byte, Unit] = { check(path) in => { buf.appendAll(in.compile.toVector.unsafeRunSync()) fs2.Stream.emit(()) } } override def list(path: Path): fs2.Stream[IO, Path] = ??? override def get(path: Path, chunkSize: Int): fs2.Stream[IO, Byte] = ??? override def move(src: Path, dst: Path): IO[Unit] = ??? override def copy(src: Path, dst: Path): IO[Unit] = ??? override def remove(path: Path): IO[Unit] = ??? }
Example 52
Source File: PathTest.scala From fs2-blobstore with Apache License 2.0 | 5 votes |
package blobstore import org.scalatest.matchers.must.Matchers import org.scalatest.flatspec.AnyFlatSpec import blobstore.PathOps._ class PathTest extends AnyFlatSpec with Matchers { behavior of "Path" it should "parse string path to file correctly" in { val s3Path = Path("s3://some-bucket/path/to/file") val gcsPath = Path("gcs://some-bucket/path/to/file") s3Path must be(Path("some-bucket", "path/to/file", None, false, None)) gcsPath must be(Path("some-bucket", "path/to/file", None, false, None)) } it should "parse string path to file without prefix correctly" in { val path = Path("some-bucket/path/to/file") path must be(Path("some-bucket", "path/to/file", None, false, None)) } it should "parse string path to file stating with / correctly" in { val path = Path("/some-bucket/path/to/file") path must be(Path("some-bucket", "path/to/file", None, false, None)) } it should "parse string path to dir correctly" in { val path = Path("s3://some-bucket/path/to/") path must be(Path("some-bucket", "path/to/", None, true, None)) } it should "parse paths with no key" in { val path = Path("s3://some-bucket") path must be(Path("some-bucket", "", None, false, None)) } it should "extend a path with no key correctly" in { val path = Path("some-bucket") / "key" path must be(Path("some-bucket", "key", None, false, None)) } }
Example 53
Source File: IngestionFlowSpec.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.ingest.services import cats.effect.{Concurrent, ContextShift, IO} import hydra.avro.registry.SchemaRegistry import hydra.core.ingest.HydraRequest import hydra.core.ingest.RequestParams.{HYDRA_KAFKA_TOPIC_PARAM,HYDRA_RECORD_KEY_PARAM} import hydra.ingest.services.IngestionFlow.MissingTopicNameException import hydra.kafka.algebras.KafkaClientAlgebra import org.apache.avro.{Schema, SchemaBuilder} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.ExecutionContext class IngestionFlowSpec extends AnyFlatSpec with Matchers { private implicit val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global) private implicit val concurrentEffect: Concurrent[IO] = IO.ioConcurrentEffect private implicit val mode: scalacache.Mode[IO] = scalacache.CatsEffect.modes.async private val testSubject: String = "test_subject" private val testSubjectNoKey: String = "test_subject_no_key" private val testKey: String = "test" private val testPayload: String = s"""{"id": "$testKey", "testField": true}""" private val testSchema: Schema = SchemaBuilder.record("TestRecord") .prop("hydra.key", "id") .fields().requiredString("id").requiredBoolean("testField").endRecord() private val testSchemaNoKey: Schema = SchemaBuilder.record("TestRecordNoKey") .fields().requiredString("id").requiredBoolean("testField").endRecord() private def ingest(request: HydraRequest): IO[KafkaClientAlgebra[IO]] = for { schemaRegistry <- SchemaRegistry.test[IO] _ <- schemaRegistry.registerSchema(testSubject + "-value", testSchema) _ <- schemaRegistry.registerSchema(testSubjectNoKey + "-value", testSchemaNoKey) kafkaClient <- KafkaClientAlgebra.test[IO] ingestFlow <- IO(new IngestionFlow[IO](schemaRegistry, kafkaClient, "https://schemaRegistry.notreal")) _ <- ingestFlow.ingest(request) } yield kafkaClient it should "ingest a message" in { val testRequest = HydraRequest("correlationId", testPayload, metadata = Map(HYDRA_KAFKA_TOPIC_PARAM -> testSubject)) ingest(testRequest).flatMap { kafkaClient => kafkaClient.consumeStringKeyMessages(testSubject, "test-consumer").take(1).compile.toList.map { publishedMessages => val firstMessage = publishedMessages.head (firstMessage._1, firstMessage._2.get.toString) shouldBe (Some(testKey), testPayload) } }.unsafeRunSync() } it should "ingest a message with a null key" in { val testRequest = HydraRequest("correlationId", testPayload, metadata = Map(HYDRA_KAFKA_TOPIC_PARAM -> testSubjectNoKey)) ingest(testRequest).flatMap { kafkaClient => kafkaClient.consumeStringKeyMessages(testSubjectNoKey, "test-consumer").take(1).compile.toList.map { publishedMessages => val firstMessage = publishedMessages.head (firstMessage._1, firstMessage._2.get.toString) shouldBe (None, testPayload) } }.unsafeRunSync() } it should "return an error when no topic name is provided" in { val testRequest = HydraRequest("correlationId", testPayload) ingest(testRequest).attempt.unsafeRunSync() shouldBe Left(MissingTopicNameException(testRequest)) } it should "take the key from the header if present" in { val headerKey = "someDifferentKey" val testRequest = HydraRequest("correlationId", testPayload, metadata = Map(HYDRA_RECORD_KEY_PARAM -> headerKey, HYDRA_KAFKA_TOPIC_PARAM -> testSubject)) ingest(testRequest).flatMap { kafkaClient => kafkaClient.consumeStringKeyMessages(testSubject, "test-consumer").take(1).compile.toList.map { publishedMessages => val firstMessage = publishedMessages.head (firstMessage._1, firstMessage._2.get.toString) shouldBe (Some(headerKey), testPayload) } }.unsafeRunSync() } }
Example 54
Source File: ClickhouseIntervalStartFormatTest.scala From clickhouse-scala-client with GNU Lesser General Public License v3.0 | 5 votes |
package com.crobox.clickhouse.dsl.marshalling import com.crobox.clickhouse.dsl.marshalling.ClickhouseJsonSupport.ClickhouseIntervalStartFormat import org.joda.time.{DateTime, DateTimeZone} import spray.json.{JsNumber, JsString} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ClickhouseIntervalStartFormatTest extends AnyFlatSpec with Matchers { val zone = DateTimeZone.forID("Europe/Bucharest") it should "read using month relative" in { ClickhouseIntervalStartFormat.read( JsString(s"${ClickhouseIntervalStartFormat.RelativeMonthsSinceUnixStart + 3}_$zone") ) should be(new DateTime("1970-04-01T00:00:00.000+02:00", DateTimeZone.UTC)) } it should "read using 0 as JsString" in { ClickhouseIntervalStartFormat.read(JsString("0")) should be( new DateTime("1970-01-01T00:00:00.000+00:00", DateTimeZone.UTC) ) } it should "read using 0 as JsNumber" in { ClickhouseIntervalStartFormat.read(JsNumber(0)) should be( new DateTime("1970-01-01T00:00:00.000+00:00", DateTimeZone.UTC) ) } it should "read date only" in { ClickhouseIntervalStartFormat.read(JsString(s"1970-12-17_$zone")) should be( new DateTime("1970-12-17T00:00:00.000+02:00", DateTimeZone.UTC) ) } it should "read timestamp" in { val date = DateTime.now(DateTimeZone.UTC) ClickhouseIntervalStartFormat.read(JsString(s"${date.getMillis}")) should be(date) ClickhouseIntervalStartFormat.read(JsNumber(date.getMillis)) should be(date) } }
Example 55
Source File: S3RequestSpec.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.data import akka.http.scaladsl.model.{ HttpMethods, MediaTypes, RemoteAddress, Uri } import org.scalatest.diagrams.Diagrams import org.scalatest.flatspec.AnyFlatSpec class S3RequestSpec extends AnyFlatSpec with Diagrams { val testCred = AwsRequestCredential(AwsAccessKey("ak"), Some(AwsSessionToken("st"))) "S3Request" should "parse an S3 request from an http Path and Method" in { val result = S3Request(testCred, Uri.Path("/demobucket"), HttpMethods.GET, RemoteAddress.Unknown, HeaderIPs(), MediaTypes.`text/plain`) assert(result == S3Request(testCred, Some("/demobucket"), None, Read("GET"))) } it should "parse an S3 request from an http Path with object and Method" in { val result = S3Request(testCred, Uri.Path("/demobucket/demoobject"), HttpMethods.GET, RemoteAddress.Unknown, HeaderIPs(), MediaTypes.`text/plain`) assert(result == S3Request(testCred, Some("/demobucket/demoobject"), Some("demoobject"), Read("GET"))) } it should "parse an S3 request from an http Path with subfolder and Method" in { val result = S3Request(testCred, Uri.Path("/demobucket/subfolder1/"), HttpMethods.GET, RemoteAddress.Unknown, HeaderIPs(), MediaTypes.`text/plain`) assert(result == S3Request(testCred, Some("/demobucket/subfolder1/"), None, Read("GET"))) } it should "parse none for bucket if path is only root" in { val result = S3Request(testCred, Uri.Path("/"), HttpMethods.GET, RemoteAddress.Unknown, HeaderIPs(), MediaTypes.`text/plain`) assert(result == S3Request(testCred, None, None, Read("GET"))) } it should "parse none for bucket if path is empty" in { val result = S3Request(testCred, Uri.Path(""), HttpMethods.GET, RemoteAddress.Unknown, HeaderIPs(), MediaTypes.`text/plain`) assert(result == S3Request(testCred, None, None, Read("GET"))) } it should "set access to write for anything but GET" in { val result = S3Request(testCred, Uri.Path("/demobucket"), HttpMethods.POST, RemoteAddress.Unknown, HeaderIPs(), MediaTypes.`text/plain`) assert(result == S3Request(testCred, Some("/demobucket"), None, Post("POST"))) } }
Example 56
Source File: JsonFormatSpecJVM.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import org.scalatest.OptionValues import jsontest.test._ import com.google.protobuf.util.{JsonFormat => JavaJsonFormat} import com.google.protobuf.any.{Any => PBAny} import com.google.protobuf.util.JsonFormat.{TypeRegistry => JavaTypeRegistry} import scalapb_json._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class JsonFormatSpecJVM extends AnyFlatSpec with Matchers with OptionValues { val TestProto = MyTest().update( _.hello := "Foo", _.foobar := 37, _.primitiveSequence := Seq("a", "b", "c"), _.repMessage := Seq(MyTest(), MyTest(hello = Some("h11"))), _.optMessage := MyTest().update(_.foobar := 39), _.stringToInt32 := Map("foo" -> 14, "bar" -> 19), _.intToMytest := Map(14 -> MyTest(), 35 -> MyTest(hello = Some("boo"))), _.repEnum := Seq(MyEnum.V1, MyEnum.V2, MyEnum.UNKNOWN), _.optEnum := MyEnum.V2, _.intToEnum := Map(32 -> MyEnum.V1, 35 -> MyEnum.V2), _.stringToBool := Map("ff" -> false, "tt" -> true), _.boolToString := Map(false -> "ff", true -> "tt"), _.optBool := false ) "fromJsonString" should "read json produced by Java" in { val javaJson = JavaJsonFormat.printer().print(MyTest.toJavaProto(TestProto)) JsonFormat.fromJsonString[MyTest](javaJson) must be(TestProto) } "Java parser" should "read json strings produced by us" in { val b = jsontest.Test.MyTest.newBuilder JavaJsonFormat.parser().merge(JsonFormat.toJsonString(TestProto), b) TestProto must be(MyTest.fromJavaProto(b.build)) } val anyEnabledJavaTypeRegistry = JavaTypeRegistry.newBuilder().add(TestProto.companion.javaDescriptor).build() val anyEnabledJavaPrinter = JavaJsonFormat.printer().usingTypeRegistry(anyEnabledJavaTypeRegistry) val anyEnabledTypeRegistry = TypeRegistry.empty.addMessageByCompanion(TestProto.companion) val anyEnabledParser = new Parser(typeRegistry = anyEnabledTypeRegistry) "Any" should "parse JSON produced by Java for a packed TestProto" in { val javaAny = com.google.protobuf.Any.pack(MyTest.toJavaProto(TestProto)) val javaJson = anyEnabledJavaPrinter.print(javaAny) anyEnabledParser.fromJsonString[PBAny](javaJson).unpack[MyTest] must be(TestProto) } }
Example 57
Source File: StructFormatSpecJVM.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.struct._ import jsontest.test3.StructTest import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class StructFormatSpecJVM extends AnyFlatSpec with Matchers with JavaAssertions { val ListValueExample = ListValue( values = Seq( Value(Value.Kind.NumberValue(-245.0)), Value(Value.Kind.BoolValue(true)), Value(Value.Kind.StringValue("Boom")) ) ) val StructExample = Struct( fields = Map( "f1" -> Value(Value.Kind.StringValue("Boo")), "f2" -> Value(Value.Kind.ListValue(ListValueExample)), "f3" -> Value(Value.Kind.StructValue(Struct(fields = Map("f4" -> Value(Value.Kind.StringValue("f5")))))) ) ) val StructExample2 = Struct( fields = Map( "f1" -> Value(Value.Kind.StringValue("Boo")), "f2" -> Value(Value.Kind.StructValue(StructExample)), "f3" -> Value(Value.Kind.NullValue(NullValue.NULL_VALUE)) ) ) "Empty value" should "be serialized to null" in { JavaJsonPrinter.print(com.google.protobuf.Value.newBuilder().build()) must be("null") } "Value" should "be serialized the same as in Java (and parsed back to original)" in { assertJsonIsSameAsJava(Value(kind = Value.Kind.NumberValue(1.0))) assertJsonIsSameAsJava(Value(kind = Value.Kind.NumberValue(-25))) assertJsonIsSameAsJava(Value(kind = Value.Kind.NumberValue(Double.PositiveInfinity)), checkRoundtrip = false) assertJsonIsSameAsJava(Value(kind = Value.Kind.NumberValue(Double.NegativeInfinity)), checkRoundtrip = false) assertJsonIsSameAsJava(Value(kind = Value.Kind.StringValue("boo"))) assertJsonIsSameAsJava(Value(kind = Value.Kind.BoolValue(true))) assertJsonIsSameAsJava(Value(kind = Value.Kind.BoolValue(false))) assertJsonIsSameAsJava(Value(kind = Value.Kind.NullValue(com.google.protobuf.struct.NullValue.NULL_VALUE))) assertJsonIsSameAsJava(Value(kind = Value.Kind.StructValue(value = StructExample))) assertJsonIsSameAsJava( Value( kind = Value.Kind.ListValue( com.google.protobuf.struct.ListValue( values = Seq( Value(Value.Kind.NumberValue(-17.0)), Value(Value.Kind.StringValue("Boo")), Value(Value.Kind.StructValue(StructExample2)), Value(Value.Kind.BoolValue(false)), Value(Value.Kind.ListValue(ListValueExample)) ) ) ) ) ) } "Struct" should "be serialized the same as in Java (and parsed back to original)" in { assertJsonIsSameAsJava(Struct()) assertJsonIsSameAsJava(StructExample) assertJsonIsSameAsJava(StructExample2) } "ListValue" should "be serialized the same as in Java (and parsed back to original)" in { assertJsonIsSameAsJava(ListValue()) assertJsonIsSameAsJava(ListValueExample) } "NullValue" should "be serialized and parsed from JSON correctly" in { javaParse("""{"nv": 0}""", jsontest.Test3.StructTest.newBuilder).toString must be("") javaParse("""{"repNv": [0,0.0,0]}""", jsontest.Test3.StructTest.newBuilder).toString must be( "rep_nv: NULL_VALUE\n" * 3 ) assertJsonIsSameAsJava(StructTest()) assertJsonIsSameAsJava(StructTest(nv = NullValue.NULL_VALUE)) assertJsonIsSameAsJava(StructTest(repNv = Seq(NullValue.NULL_VALUE, NullValue.NULL_VALUE))) } }
Example 58
Source File: OneOfSpec.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.util.JsonFormat.{printer => ProtobufJavaPrinter} import jsontest.oneof.OneOf._ import jsontest.oneof.{OneOf, OneOfMessage} import io.circe.parser.parse import org.scalatest.prop._ import EitherOps._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class OneOfSpec extends AnyFlatSpec with Matchers with TableDrivenPropertyChecks { val examples = Table( ("message", "json"), (OneOf.defaultInstance, "{}"), (OneOf(Field.Empty), "{}"), (OneOf(Field.Primitive("")), """{"primitive":""}"""), (OneOf(Field.Primitive("test")), """{"primitive":"test"}"""), (OneOf(Field.Wrapper("")), """{"wrapper":""}"""), (OneOf(Field.Wrapper("test")), """{"wrapper":"test"}"""), (OneOf(Field.Message(OneOfMessage())), """{"message":{}}"""), (OneOf(Field.Message(OneOfMessage(Some("test")))), """{"message":{"field":"test"}}""") ) forEvery(examples) { (message: OneOf, json: String) => new Printer(includingDefaultValueFields = false).toJson(message) must be(parse(json).getOrError) new Printer(includingDefaultValueFields = false).toJson(message) must be( parse( ProtobufJavaPrinter().print(toJavaProto(message)) ).getOrError ) new Printer(includingDefaultValueFields = true).toJson(message) must be(parse(json).getOrError) new Printer(includingDefaultValueFields = true).toJson(message) must be( parse( ProtobufJavaPrinter().includingDefaultValueFields().print(toJavaProto(message)) ).getOrError ) } }
Example 59
Source File: WellKnownTypesSpec.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.duration.Duration import com.google.protobuf.timestamp.Timestamp import jsontest.test.WellKnownTest import io.circe.parser.parse import EitherOps._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class WellKnownTypesSpec extends AnyFlatSpec with Matchers { val durationProto = WellKnownTest(duration = Some(Duration(146, 3455))) "duration" should "serialize and parse correctly" in { val durationJson = """{ | "duration": "146.000003455s" |}""".stripMargin JsonFormat.printer.toJson(durationProto) must be(parse(durationJson).getOrError) JsonFormat.parser.fromJsonString[WellKnownTest](durationJson) must be(durationProto) } "timestamp" should "serialize and parse correctly" in { val timestampJson = """{ | "timestamp": "2016-09-16T12:35:24.375123456Z" |}""".stripMargin val timestampProto = WellKnownTest(timestamp = Some(Timestamp(seconds = 1474029324, nanos = 375123456))) JsonFormat.parser.fromJsonString[WellKnownTest](timestampJson) must be(timestampProto) JsonFormat.printer.toJson(timestampProto) must be(parse(timestampJson).getOrError) } }
Example 60
Source File: AnyFormatSpec.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.any.{Any => PBAny} import jsontest.anytests.{AnyTest, ManyAnyTest} import io.circe.parser.parse import scalapb_json._ import EitherOps._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class AnyFormatSpec extends AnyFlatSpec with Matchers with JavaAssertions { val RawExample = AnyTest("test") val RawJson = parse(s"""{"field":"test"}""").getOrError val AnyExample = PBAny.pack(RawExample) val AnyJson = parse(s"""{"@type":"type.googleapis.com/jsontest.AnyTest","field":"test"}""").getOrError val CustomPrefixAny = PBAny.pack(RawExample, "example.com/") val CustomPrefixJson = parse(s"""{"@type":"example.com/jsontest.AnyTest","field":"test"}""").getOrError val ManyExample = ManyAnyTest( Seq( PBAny.pack(AnyTest("1")), PBAny.pack(AnyTest("2")) ) ) val ManyPackedJson = parse(""" |{ | "@type": "type.googleapis.com/jsontest.ManyAnyTest", | "fields": [ | {"@type": "type.googleapis.com/jsontest.AnyTest", "field": "1"}, | {"@type": "type.googleapis.com/jsontest.AnyTest", "field": "2"} | ] |} """.stripMargin).getOrError override def registeredCompanions = Seq(AnyTest, ManyAnyTest) // For clarity def UnregisteredPrinter = JsonFormat.printer def UnregisteredParser = JsonFormat.parser "Any" should "fail to serialize if its respective companion is not registered" in { an[IllegalStateException] must be thrownBy UnregisteredPrinter.toJson(AnyExample) } "Any" should "fail to deserialize if its respective companion is not registered" in { a[JsonFormatException] must be thrownBy UnregisteredParser.fromJson[PBAny](AnyJson) } "Any" should "serialize correctly if its respective companion is registered" in { ScalaJsonPrinter.toJson(AnyExample) must be(AnyJson) } "Any" should "fail to serialize with a custom URL prefix if specified" in { an[IllegalStateException] must be thrownBy ScalaJsonPrinter.toJson(CustomPrefixAny) } "Any" should "fail to deserialize for a non-Google-prefixed type URL" in { a[JsonFormatException] must be thrownBy ScalaJsonParser.fromJson[PBAny](CustomPrefixJson) } "Any" should "deserialize correctly if its respective companion is registered" in { ScalaJsonParser.fromJson[PBAny](AnyJson) must be(AnyExample) } "Any" should "resolve printers recursively" in { val packed = PBAny.pack(ManyExample) ScalaJsonPrinter.toJson(packed) must be(ManyPackedJson) } "Any" should "resolve parsers recursively" in { ScalaJsonParser.fromJson[PBAny](ManyPackedJson).unpack[ManyAnyTest] must be(ManyExample) } }
Example 61
Source File: PrimitiveWrappersSpec.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.ByteString import jsontest.test3._ import io.circe.{Encoder, Json} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class PrimitiveWrappersSpec extends AnyFlatSpec with Matchers { private[this] def render[A](a: A)(implicit A: Encoder[A]): Json = A.apply(a) "Empty object" should "give empty json for Wrapper" in { JsonFormat.toJson(Wrapper()) must be(render(Map.empty[String, Json])) } "primitive values" should "serialize properly" in { JsonFormat.toJson(Wrapper(wBool = Some(false))) must be(render(Map("wBool" -> Json.fromBoolean(false)))) JsonFormat.toJson(Wrapper(wBool = Some(true))) must be(render(Map("wBool" -> Json.fromBoolean(true)))) JsonFormat.toJson(Wrapper(wDouble = Some(3.1))) must be(render(Map("wDouble" -> Json.fromDouble(3.1)))) JsonFormat.toJson(Wrapper(wFloat = Some(3.0f))) must be(render(Map("wFloat" -> Json.fromDouble(3.0)))) JsonFormat.toJson(Wrapper(wInt32 = Some(35544))) must be(render(Map("wInt32" -> Json.fromLong(35544)))) JsonFormat.toJson(Wrapper(wInt32 = Some(0))) must be(render(Map("wInt32" -> Json.fromLong(0)))) JsonFormat.toJson(Wrapper(wInt64 = Some(125))) must be(render(Map("wInt64" -> Json.fromString("125")))) JsonFormat.toJson(Wrapper(wUint32 = Some(125))) must be(render(Map("wUint32" -> Json.fromLong(125)))) JsonFormat.toJson(Wrapper(wUint64 = Some(125))) must be(render(Map("wUint64" -> Json.fromString("125")))) JsonFormat.toJson(Wrapper(wString = Some("bar"))) must be(render(Map("wString" -> Json.fromString("bar")))) JsonFormat.toJson(Wrapper(wString = Some(""))) must be(render(Map("wString" -> Json.fromString("")))) JsonFormat.toJson(Wrapper(wBytes = Some(ByteString.copyFrom(Array[Byte](3, 5, 4))))) must be( render(Map("wBytes" -> Json.fromString("AwUE"))) ) JsonFormat.toJson(Wrapper(wBytes = Some(ByteString.EMPTY))) must be(render(Map("wBytes" -> Json.fromString("")))) new Printer(formattingLongAsNumber = true).toJson(Wrapper(wUint64 = Some(125))) must be( render(Map("wUint64" -> Json.fromLong(125))) ) new Printer(formattingLongAsNumber = true).toJson(Wrapper(wInt64 = Some(125))) must be( render(Map("wInt64" -> Json.fromLong(125))) ) } "primitive values" should "parse properly" in { JsonFormat.fromJson[Wrapper](render(Map("wBool" -> Json.fromBoolean(false)))) must be(Wrapper(wBool = Some(false))) JsonFormat.fromJson[Wrapper](render(Map("wBool" -> Json.fromBoolean(true)))) must be(Wrapper(wBool = Some(true))) JsonFormat.fromJson[Wrapper](render(Map("wDouble" -> Json.fromDouble(3.1)))) must be(Wrapper(wDouble = Some(3.1))) JsonFormat.fromJson[Wrapper](render(Map("wFloat" -> Json.fromDouble(3.0)))) must be(Wrapper(wFloat = Some(3.0f))) JsonFormat.fromJson[Wrapper](render(Map("wInt32" -> Json.fromLong(35544)))) must be(Wrapper(wInt32 = Some(35544))) JsonFormat.fromJson[Wrapper](render(Map("wInt32" -> Json.fromLong(0)))) must be(Wrapper(wInt32 = Some(0))) JsonFormat.fromJson[Wrapper](render(Map("wInt64" -> Json.fromString("125")))) must be(Wrapper(wInt64 = Some(125))) JsonFormat.fromJson[Wrapper](render(Map("wUint32" -> Json.fromLong(125)))) must be(Wrapper(wUint32 = Some(125))) JsonFormat.fromJson[Wrapper](render(Map("wUint64" -> Json.fromString("125")))) must be(Wrapper(wUint64 = Some(125))) JsonFormat.fromJson[Wrapper](render(Map("wString" -> Json.fromString("bar")))) must be( Wrapper(wString = Some("bar")) ) JsonFormat.fromJson[Wrapper](render(Map("wString" -> Json.fromString("")))) must be(Wrapper(wString = Some(""))) JsonFormat.fromJson[Wrapper](render(Map("wBytes" -> Json.fromString("AwUE")))) must be( Wrapper(wBytes = Some(ByteString.copyFrom(Array[Byte](3, 5, 4)))) ) JsonFormat.fromJson[Wrapper](render(Map("wBytes" -> Json.fromString("")))) must be( Wrapper(wBytes = Some(ByteString.EMPTY)) ) } }
Example 62
Source File: StructFormatSpec.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.struct._ import jsontest.test3.StructTest import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class StructFormatSpec extends AnyFlatSpec with Matchers with JavaAssertions { "Empty value" should "be serialized to null" in { JsonFormat.toJsonString(Value()) must be("null") } "NullValue" should "be serialized and parsed from JSON correctly" in { JsonFormat.fromJsonString[StructTest]("""{"nv": null}""") must be(StructTest()) JsonFormat.fromJsonString[StructTest]("""{"nv": "NULL_VALUE"}""") must be(StructTest()) JsonFormat.fromJsonString[StructTest]("""{"nv": 0}""") must be(StructTest()) JsonFormat.fromJsonString[StructTest]("""{"repNv": [null, 0, null]}""") must be( StructTest(repNv = Seq(NullValue.NULL_VALUE, NullValue.NULL_VALUE, NullValue.NULL_VALUE)) ) } }
Example 63
Source File: OutwatchSpec.scala From outwatch with Apache License 2.0 | 5 votes |
package outwatch import scala.concurrent.Future import cats.effect.ContextShift import cats.effect.IO import monix.execution.Ack.Continue import monix.execution.ExecutionModel.SynchronousExecution import monix.execution.schedulers.TrampolineScheduler import monix.execution.{Cancelable, Scheduler} import monix.reactive.Observable import org.scalajs.dom.{document, window} import org.scalatest.BeforeAndAfterEach import org.scalatest._ import outwatch.Deprecated.IgnoreWarnings.initEvent import org.scalatest.flatspec.{ AnyFlatSpec, AsyncFlatSpec } import org.scalatest.matchers.should.Matchers trait EasySubscribe { implicit class Subscriber[T](obs: Observable[T]) { def apply(next: T => Unit)(implicit s: Scheduler): Cancelable = obs.subscribe { t => next(t) Continue } } } // TODO: We need this mock until localStorage is implemented in jsdom (https://github.com/tmpvar/jsdom/pull/2076) trait LocalStorageMock { import scala.collection.mutable import scala.scalajs.js if (js.isUndefined(window.localStorage)) { val storageObject = new js.Object { private val map = new mutable.HashMap[String, String] def getItem(key: String): String = map.getOrElse(key, null) def setItem(key: String, value: String): Unit = { map += key -> value } def removeItem(key: String): Unit = { map -= key } def clear(): Unit = map.clear() } js.Dynamic.global.window.updateDynamic("localStorage")(storageObject) } def dispatchStorageEvent(key: String, newValue: String, oldValue: String): Unit = { if (key == null) window.localStorage.clear() else window.localStorage.setItem(key, newValue) val event = document.createEvent("Events") initEvent(event)("storage", canBubbleArg = true, cancelableArg = false) event.asInstanceOf[js.Dynamic].key = key event.asInstanceOf[js.Dynamic].newValue = newValue event.asInstanceOf[js.Dynamic].oldValue = oldValue event.asInstanceOf[js.Dynamic].storageArea = window.localStorage window.dispatchEvent(event) () } } trait OutwatchSpec extends Matchers with BeforeAndAfterEach with EasySubscribe with LocalStorageMock { self: Suite => implicit val scheduler: TrampolineScheduler = TrampolineScheduler(Scheduler.global, SynchronousExecution) implicit val cs: ContextShift[IO] = IO.contextShift(scheduler) override def beforeEach(): Unit = { document.body.innerHTML = "" window.localStorage.clear() // prepare body with <div id="app"></div> val root = document.createElement("div") root.id = "app" document.body.appendChild(root) () } } abstract class JSDomSpec extends AnyFlatSpec with OutwatchSpec { implicit def executionContext = scheduler } abstract class JSDomAsyncSpec extends AsyncFlatSpec with OutwatchSpec { override def executionContext = scheduler implicit def ioAssertionToFutureAssertion(io: IO[Assertion]): Future[Assertion] = io.unsafeToFuture() }
Example 64
Source File: MockConnectorSpec.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.connector.mock import com.typesafe.config.ConfigFactory import org.apache.avro.Schema import org.apache.avro.Schema.Type import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class MockConnectorSpec extends AnyFlatSpec with Matchers { it should "load the test schemas" in { new MockConnectorCreator().create(ConfigFactory.empty()).fullLoad() should have size (2) } it should "load the test schemas and custom ones" in { val connector = new MockConnectorCreator().create(ConfigFactory.empty()) connector.insert((3L, Schema.create(Type.BYTES)) :: Nil) connector.fullLoad() should have size (3) } }
Example 65
Source File: ManagerUtilsSuite.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.app.mock import java.nio.{ByteBuffer, ByteOrder} import com.typesafe.config.ConfigFactory import it.agilelab.darwin.manager.AvroSchemaManagerFactory import it.agilelab.darwin.manager.util.{AvroSingleObjectEncodingUtils, ConfigurationKeys} import it.agilelab.darwin.manager.util.ByteArrayUtils._ import scala.util.Random import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class BigEndianManagerUtilsSuite extends ManagerUtilsSuite(ByteOrder.BIG_ENDIAN) class LittleEndianManagerUtilsSuite extends ManagerUtilsSuite(ByteOrder.LITTLE_ENDIAN) abstract class ManagerUtilsSuite(endianness: ByteOrder) extends AnyFlatSpec with Matchers { "AvroSchemaManager utilities" should "create a Single-Object encoded byte array" in { val ORIGINAL_LENGTH: Int = 10 val originalSchema = SchemaReader.readFromResources("OneField.avsc") val config = ConfigFactory .parseMap(new java.util.HashMap[String, String]() { { put(ConfigurationKeys.MANAGER_TYPE, ConfigurationKeys.CACHED_EAGER) put(ConfigurationKeys.ENDIANNESS, endianness.toString) } }) .withFallback(ConfigFactory.load()) .resolve() val manager = AvroSchemaManagerFactory.initialize(config) manager.registerAll(Seq(originalSchema)) val originalPayload = new Array[Byte](ORIGINAL_LENGTH) Random.nextBytes(originalPayload) val data: Array[Byte] = manager.generateAvroSingleObjectEncoded(originalPayload, originalSchema) assert(AvroSingleObjectEncodingUtils.isAvroSingleObjectEncoded(data)) val (schema, payload) = manager.retrieveSchemaAndAvroPayload(data) assert(schema == originalSchema) assert(originalPayload sameElements payload) } it should "convert a long to byte array and back" in { val longs = (1 to 10).map(_ => Random.nextLong()) assert( longs == longs.map( x => AvroSingleObjectEncodingUtils .readLong(ByteBuffer.wrap(x.longToByteArray(endianness)), endianness) ) ) } }
Example 66
Source File: CachedEagerApplicationSuite.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.app.mock import java.lang.reflect.Modifier import java.nio.ByteOrder import com.typesafe.config.{Config, ConfigFactory} import it.agilelab.darwin.annotations.AvroSerde import it.agilelab.darwin.app.mock.classes.{MyClass, MyNestedClass, NewClass, OneField} import it.agilelab.darwin.common.{Connector, ConnectorFactory} import it.agilelab.darwin.manager.{AvroSchemaManager, CachedEagerAvroSchemaManager} import org.apache.avro.{Schema, SchemaNormalization} import org.apache.avro.reflect.ReflectData import org.reflections.Reflections import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import it.agilelab.darwin.common.compat._ class BigEndianCachedEagerApplicationSuite extends CachedEagerApplicationSuite(ByteOrder.BIG_ENDIAN) class LittleEndianCachedEagerApplicationSuite extends CachedEagerApplicationSuite(ByteOrder.LITTLE_ENDIAN) abstract class CachedEagerApplicationSuite(val endianness: ByteOrder) extends AnyFlatSpec with Matchers { val config: Config = ConfigFactory.load() val connector: Connector = ConnectorFactory.connector(config) val manager: AvroSchemaManager = new CachedEagerAvroSchemaManager(connector, endianness) "CachedEagerAvroSchemaManager" should "not fail after the initialization" in { val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc")) assert(manager.registerAll(schemas).size == 1) } it should "load all existing schemas and register a new one" in { val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc")) manager.getSchema(0L) manager.registerAll(schemas) val id = manager.getId(schemas.head) assert(manager.getSchema(id).isDefined) assert(schemas.head == manager.getSchema(id).get) } it should "get all previously registered schemas" in { val schema: Schema = SchemaReader.readFromResources("MyNestedClass.avsc") val schema0 = manager.getSchema(0L) val schema1 = manager.getSchema(1L) assert(schema0.isDefined) assert(schema1.isDefined) assert(schema0.get != schema1.get) assert(schema != schema0.get) assert(schema != schema1.get) } it should "generate all schemas for all the annotated classes with @AvroSerde" in { val reflections = new Reflections("it.agilelab.darwin.app.mock.classes") val oneFieldSchema = ReflectData.get().getSchema(classOf[OneField]).toString val myNestedSchema = ReflectData.get().getSchema(classOf[MyNestedClass]).toString val myClassSchema = ReflectData.get().getSchema(classOf[MyClass]).toString val annotationClass: Class[AvroSerde] = classOf[AvroSerde] val classes = reflections.getTypesAnnotatedWith(annotationClass).toScala.toSeq .filter(c => !c.isInterface && !Modifier.isAbstract(c.getModifiers)) val schemas = classes.map(c => ReflectData.get().getSchema(Class.forName(c.getName)).toString) Seq(oneFieldSchema, myClassSchema, myNestedSchema) should contain theSameElementsAs schemas } it should "reload all schemas from the connector" in { val newSchema = ReflectData.get().getSchema(classOf[NewClass]) val newId = SchemaNormalization.parsingFingerprint64(newSchema) assert(manager.getSchema(newId).isEmpty) connector.insert(Seq(newId -> newSchema)) assert(manager.getSchema(newId).isEmpty) manager.reload() assert(manager.getSchema(newId).isDefined) assert(manager.getSchema(newId).get == newSchema) } }
Example 67
Source File: CachedLazyApplicationSuite.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.app.mock import java.lang.reflect.Modifier import java.nio.ByteOrder import com.typesafe.config.{Config, ConfigFactory} import it.agilelab.darwin.annotations.AvroSerde import it.agilelab.darwin.app.mock.classes.{MyClass, MyNestedClass, NewClass, OneField} import it.agilelab.darwin.common.{Connector, ConnectorFactory} import it.agilelab.darwin.manager.{AvroSchemaManager, CachedLazyAvroSchemaManager} import org.apache.avro.{Schema, SchemaNormalization} import org.apache.avro.reflect.ReflectData import org.reflections.Reflections import it.agilelab.darwin.common.compat._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class BigEndianCachedLazyApplicationSuite extends CachedLazyApplicationSuite(ByteOrder.BIG_ENDIAN) class LittleEndianCachedLazyApplicationSuite extends CachedLazyApplicationSuite(ByteOrder.LITTLE_ENDIAN) abstract class CachedLazyApplicationSuite(val endianness: ByteOrder) extends AnyFlatSpec with Matchers { val config: Config = ConfigFactory.load() val connector: Connector = ConnectorFactory.connector(config) val manager: AvroSchemaManager = new CachedLazyAvroSchemaManager(connector, endianness) "CachedLazyAvroSchemaManager" should "not fail after the initialization" in { val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc")) assert(manager.registerAll(schemas).size == 1) } it should "load all existing schemas and register a new one" in { val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc")) manager.getSchema(0L) manager.registerAll(schemas) val id = manager.getId(schemas.head) assert(manager.getSchema(id).isDefined) assert(schemas.head == manager.getSchema(id).get) } it should "get all previously registered schemas" in { val schema: Schema = SchemaReader.readFromResources("MyNestedClass.avsc") val schema0 = manager.getSchema(0L) val schema1 = manager.getSchema(1L) assert(schema0.isDefined) assert(schema1.isDefined) assert(schema0.get != schema1.get) assert(schema != schema0.get) assert(schema != schema1.get) } it should "generate all schemas for all the annotated classes with @AvroSerde" in { val reflections = new Reflections("it.agilelab.darwin.app.mock.classes") val oneFieldSchema = ReflectData.get().getSchema(classOf[OneField]).toString val myNestedSchema = ReflectData.get().getSchema(classOf[MyNestedClass]).toString val myClassSchema = ReflectData.get().getSchema(classOf[MyClass]).toString val annotationClass: Class[AvroSerde] = classOf[AvroSerde] val classes = reflections.getTypesAnnotatedWith(annotationClass).toScala.toSeq .filter(c => !c.isInterface && !Modifier.isAbstract(c.getModifiers)) val schemas = classes.map(c => ReflectData.get().getSchema(Class.forName(c.getName)).toString) Seq(oneFieldSchema, myClassSchema, myNestedSchema) should contain theSameElementsAs schemas } it should "reload all schemas from the connector" in { val newSchema = ReflectData.get().getSchema(classOf[NewClass]) val newId = SchemaNormalization.parsingFingerprint64(newSchema) assert(manager.getSchema(newId).isEmpty) connector.insert(Seq(newId -> newSchema)) assert(manager.getSchema(newId).isDefined) assert(manager.getSchema(newId).get == newSchema) } }
Example 68
Source File: LazyApplicationSuite.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.app.mock import java.lang.reflect.Modifier import java.nio.ByteOrder import com.typesafe.config.{Config, ConfigFactory} import it.agilelab.darwin.annotations.AvroSerde import it.agilelab.darwin.app.mock.classes.{MyClass, MyNestedClass, NewClass, OneField} import it.agilelab.darwin.common.{Connector, ConnectorFactory} import it.agilelab.darwin.manager.{AvroSchemaManager, LazyAvroSchemaManager} import org.apache.avro.{Schema, SchemaNormalization} import org.apache.avro.reflect.ReflectData import org.reflections.Reflections import it.agilelab.darwin.common.compat._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class BigEndianLazyApplicationSuite extends LazyApplicationSuite(ByteOrder.BIG_ENDIAN) class LittleEndianLazyApplicationSuite extends LazyApplicationSuite(ByteOrder.LITTLE_ENDIAN) abstract class LazyApplicationSuite(endianness: ByteOrder) extends AnyFlatSpec with Matchers { val config: Config = ConfigFactory.load() val connector: Connector = ConnectorFactory.connector(config) val manager: AvroSchemaManager = new LazyAvroSchemaManager(connector, endianness) "LazyAvroSchemaManager" should "not fail after the initialization" in { val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc")) assert(manager.registerAll(schemas).size == 1) } it should "load all existing schemas and register a new one" in { val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc")) manager.getSchema(0L) manager.registerAll(schemas) val id = manager.getId(schemas.head) assert(manager.getSchema(id).isDefined) assert(schemas.head == manager.getSchema(id).get) } it should "get all previously registered schemas" in { val schema: Schema = SchemaReader.readFromResources("MyNestedClass.avsc") val schema0 = manager.getSchema(0L) val schema1 = manager.getSchema(1L) assert(schema0.isDefined) assert(schema1.isDefined) assert(schema0.get != schema1.get) assert(schema != schema0.get) assert(schema != schema1.get) } it should "generate all schemas for all the annotated classes with @AvroSerde" in { val reflections = new Reflections("it.agilelab.darwin.app.mock.classes") val oneFieldSchema = ReflectData.get().getSchema(classOf[OneField]).toString val myNestedSchema = ReflectData.get().getSchema(classOf[MyNestedClass]).toString val myClassSchema = ReflectData.get().getSchema(classOf[MyClass]).toString val annotationClass: Class[AvroSerde] = classOf[AvroSerde] val classes = reflections.getTypesAnnotatedWith(annotationClass).toScala.toSeq .filter(c => !c.isInterface && !Modifier.isAbstract(c.getModifiers)) val schemas = classes.map(c => ReflectData.get().getSchema(Class.forName(c.getName)).toString) Seq(oneFieldSchema, myClassSchema, myNestedSchema) should contain theSameElementsAs schemas } it should "reload all schemas from the connector" in { val newSchema = ReflectData.get().getSchema(classOf[NewClass]) val newId = SchemaNormalization.parsingFingerprint64(newSchema) assert(manager.getSchema(newId).isEmpty) connector.insert(Seq(newId -> newSchema)) assert(manager.getSchema(newId).isDefined) assert(manager.getSchema(newId).get == newSchema) } }
Example 69
Source File: TwoConnectorsSpec.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.app.mock import com.typesafe.config.ConfigFactory import it.agilelab.darwin.common.ConnectorFactory import it.agilelab.darwin.connector.hbase.HBaseConnectorCreator import it.agilelab.darwin.connector.mock.MockConnectorCreator import it.agilelab.darwin.connector.postgres.PostgresConnectorCreator import it.agilelab.darwin.manager.util.ConfigurationKeys import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class TwoConnectorsSpec extends AnyFlatSpec with Matchers { it should "have both HBase and Postgresql available" in { ConnectorFactory.creators().map(_.getClass) should contain theSameElementsAs ( classOf[HBaseConnectorCreator] :: classOf[PostgresConnectorCreator] :: classOf[MockConnectorCreator] :: Nil ) } it should "choose HBase connector over Postgresql one" in { val config = ConfigFactory.parseString(s"""${ConfigurationKeys.CONNECTOR}: hbase""") ConnectorFactory.creator(config).map(_.getClass) should be(Some(classOf[HBaseConnectorCreator])) } it should "choose Postgresql connector over HBase one" in { val config = ConfigFactory.parseString(s"""${ConfigurationKeys.CONNECTOR}: postgresql""") ConnectorFactory.creator(config).map(_.getClass) should be(Some(classOf[PostgresConnectorCreator])) } }
Example 70
Source File: HBaseConnectorSuite.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.connector.hbase import java.nio.file.Files import com.typesafe.config.{ConfigFactory, ConfigValueFactory} import it.agilelab.darwin.common.Connector import org.apache.avro.reflect.ReflectData import org.apache.avro.{Schema, SchemaNormalization} import org.apache.hadoop.hbase.HBaseTestingUtility import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class HBaseConnectorSuite extends AnyFlatSpec with Matchers with BeforeAndAfterAll { var connector: Connector = _ "HBaseConnector" should "load all existing schemas" in { connector.fullLoad() } it should "insert and retrieve" in { val schemas = Seq(ReflectData.get().getSchema(classOf[HBaseMock]), ReflectData.get().getSchema(classOf[HBase2Mock])) .map(s => SchemaNormalization.parsingFingerprint64(s) -> s) connector.insert(schemas) val loaded: Seq[(Long, Schema)] = connector.fullLoad() assert(loaded.size == schemas.size) assert(loaded.forall(schemas.contains)) val schema = connector.findSchema(loaded.head._1) assert(schema.isDefined) assert(schema.get == loaded.head._2) val noSchema = connector.findSchema(-1L) assert(noSchema.isEmpty) } "connector.tableCreationHint" should "print the correct hint for table creation" in { connector.tableCreationHint() should be( """To create namespace and table from an HBase shell issue: | create_namespace 'AVRO' | create 'AVRO:SCHEMA_REPOSITORY', '0'""".stripMargin) } "connector.tableExists" should "return true with existent table" in { connector.tableExists() should be(true) } override def beforeAll(): Unit = { connector = new HBaseConnectorCreator().create(HBaseConnectorSuite.config) connector.createTable() } } object HBaseConnectorSuite { private lazy val config = { val util = new HBaseTestingUtility() val minicluster = util.startMiniCluster() //Hbase connector can only load configurations from a file path so we need to render the hadoop conf val confFile = Files.createTempFile("prefix", "suffix") val stream = Files.newOutputStream(confFile) minicluster.getConfiguration.writeXml(stream) stream.flush() stream.close() val hbaseConfigPath = ConfigValueFactory.fromAnyRef(confFile.toAbsolutePath.toString) //HbaseConnector will only load conf if hbase-site and core-site are given, //we give the same file to each. sys.addShutdownHook(minicluster.shutdown()) ConfigFactory.load() .withValue(ConfigurationKeys.HBASE_SITE, hbaseConfigPath) .withValue(ConfigurationKeys.CORE_SITE, hbaseConfigPath) } }
Example 71
Source File: PostgresConnectorSuite.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.connector.postgres import com.typesafe.config.{Config, ConfigFactory} import it.agilelab.darwin.common.Connector import org.apache.avro.{Schema, SchemaNormalization} import org.scalatest.BeforeAndAfterAll import ru.yandex.qatools.embed.postgresql.EmbeddedPostgres import ru.yandex.qatools.embed.postgresql.distribution.Version import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class PostgresConnectorSuite extends AnyFlatSpec with Matchers with BeforeAndAfterAll { val config: Config = ConfigFactory.load("postgres.properties") val connector: Connector = new PostgresConnectorCreator().create(config) val embeddedPostgres: EmbeddedPostgres = new EmbeddedPostgres(Version.V9_6_11) override protected def beforeAll(): Unit = { super.beforeAll() val port = 5432 val host = "localhost" val dbname = "postgres" val username = "postgres" val password = "mysecretpassword" embeddedPostgres.start(host, port, dbname, username, password) connector.createTable() } override protected def afterAll(): Unit = { super.afterAll() embeddedPostgres.stop() } "PostgresConnector" should "load all existing schemas" in { connector.fullLoad() } ignore should "insert and retrieve" in { val outerSchema = new Schema.Parser().parse(getClass.getClassLoader.getResourceAsStream("postgresmock.avsc")) val innerSchema = outerSchema.getField("four").schema() val schemas = Seq(innerSchema, outerSchema) .map(s => SchemaNormalization.parsingFingerprint64(s) -> s) connector.insert(schemas) val loaded: Seq[(Long, Schema)] = connector.fullLoad() assert(loaded.size == schemas.size) assert(loaded.forall(schemas.contains)) } }
Example 72
Source File: DarwinConcurrentHashMapSpec.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.common import java.util.concurrent.atomic.AtomicInteger import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class DarwinConcurrentHashMapSpec extends AnyFlatSpec with Matchers with BeforeAndAfter { private val realJavaVersion = System.getProperty("java.version") after { System.setProperty("java.version", realJavaVersion) } def test(): Unit = { val threadNumber = 1000 val map = DarwinConcurrentHashMap.empty[String, Int] var counter = 0 val threadCounter = new AtomicInteger(0) val runnables = for (_ <- 1 to threadNumber) yield { new Runnable { override def run(): Unit = { threadCounter.incrementAndGet() val res = map.getOrElseUpdate("A", { counter += 1 counter }) res should be(1) } } } val threads = for (r <- runnables) yield { val t = new Thread(r) t } for (t <- threads) { t.start() } for (t <- threads) { t.join() } threadCounter.get() should be(threadNumber) } it should "not evaluate the value if the key is present JAVA 8" in { test() } it should "not evaluate the value if the key is present JAVA 7" in { if (JavaVersion.parseJavaVersion(realJavaVersion) >= 8) { System.setProperty("java.version", "1.7") test() } else { assert(true) } } }
Example 73
Source File: RequestParameterSpec.scala From tsec with MIT License | 5 votes |
package tsec.oauth2.provider import cats.syntax.either._ import org.scalatest.Matchers._ import org.scalatest.flatspec.AnyFlatSpec import tsec.oauth2.provider.AccessTokenFetcher.RequestParameter class RequestParameterSpec extends AnyFlatSpec { def createRequest( oauthToken: Option[String], accessToken: Option[String], another: Map[String, Seq[String]] = Map() ): ProtectedResourceRequest = { val params = oauthToken.map { "oauth_token" -> Seq(_) } ++ accessToken.map { "access_token" -> Seq(_) } new ProtectedResourceRequest(Map(), Map() ++ params ++ another) } it should "match RequestParameter" in { RequestParameter.matches(createRequest(Some("token1"), None)) should be(true) RequestParameter.matches(createRequest(None, Some("token2"))) should be(true) RequestParameter.matches(createRequest(Some("token1"), Some("token2"))) should be(true) } it should "doesn't match RequestParameter" in { RequestParameter.matches(createRequest(None, None)) should be(false) } it should "fetch only oauth token parameter" in { val result = RequestParameter.fetch(createRequest(Some("token1"), None)).toOption.get result.token should be("token1") result.params should be(Symbol("empty")) } it should "fetch only access token parameter" in { val result = RequestParameter.fetch(createRequest(None, Some("token2"))).toOption.get result.token should be("token2") result.params should be(Symbol("empty")) } it should "fetch with another parameter" in { val result = RequestParameter.fetch(createRequest(None, Some("token2"), Map("foo" -> Seq("bar")))).toOption.get result.token should be("token2") result.params.get("foo") should be(Some("bar")) } it should "fetch illegal parameter then throws exception" in { RequestParameter.fetch(createRequest(None, None)) shouldBe(Left(InvalidRequest("missing access token"))) } }
Example 74
Source File: RefreshTokenGrantHandlerSpec.scala From tsec with MIT License | 5 votes |
package tsec.oauth2.provider import java.time.Instant import cats.effect.IO import cats.syntax.either._ import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.Matchers._ import tsec.oauth2.provider.ValidatedRequest.ValidatedRefreshToken import tsec.oauth2.provider.grantHandler.RefreshTokenGrantHandler import tsec.oauth2.provider.grantHandler.RefreshTokenHandler import scala.concurrent.duration._ class RefreshTokenGrantHandlerSpec extends AnyFlatSpec with OptionValues { it should "handle request" in { val dataHandler = new RefreshTokenHandler[IO, MockUser] { override def validateClient(request: ValidatedRefreshToken): IO[Boolean] = IO.pure(true) override def findAuthInfoByRefreshToken(refreshToken: String): IO[Option[AuthInfo[MockUser]]] = IO.pure( Some( AuthInfo( user = MockUser(10000, "username"), clientId = Some("clientId1"), scope = None, redirectUri = None ) ) ) override def refreshAccessToken(authInfo: AuthInfo[MockUser], refreshToken: String): IO[AccessToken] = IO.pure(AccessToken("token1", Some(refreshToken), None, Some(3600 seconds), Instant.now())) override def createAccessToken(authInfo: AuthInfo[MockUser]): IO[AccessToken] = ??? override def getStoredAccessToken(authInfo: AuthInfo[MockUser]): IO[Option[AccessToken]] = ??? } val handler = new RefreshTokenGrantHandler[IO, MockUser](dataHandler) val f = handler.handleRequest( ValidatedRefreshToken(ClientCredential("clientId1", Some("ClientSecret1")), "refreshToken1", Some("all")) ) val result = f.value.unsafeRunSync().toOption.get result.tokenType should be("Bearer") result.accessToken should be("token1") result.expiresIn.value.toMillis should (be <= 3600L and be > 3595L) result.refreshToken should be(Some("refreshToken1")) result.scope should be(None) } }
Example 75
Source File: ValidatedRequestSpec.scala From tsec with MIT License | 5 votes |
package tsec.oauth2.provider import cats.syntax.either._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.Matchers._ class ValidatedRequestSpec extends AnyFlatSpec { it should "fetch Basic64" in { val c = ValidatedRequest.parseClientCredential(Map("Authorization" -> Seq("Basic Y2xpZW50X2lkX3ZhbHVlOmNsaWVudF9zZWNyZXRfdmFsdWU=")), Map.empty).toOption.get c.clientId should be("client_id_value") c.clientSecret should be(Some("client_secret_value")) } it should "fetch Basic64 by case insensitive" in { val headers = Map("authorization" -> Seq("Basic Y2xpZW50X2lkX3ZhbHVlOmNsaWVudF9zZWNyZXRfdmFsdWU=")) val c = ValidatedRequest.parseClientCredential(headers, Map.empty).toOption.get c.clientId should be("client_id_value") c.clientSecret should be(Some("client_secret_value")) } it should "fetch authorization header without colon" in { val parsedCred = ValidatedRequest.parseClientCredential(Map("Authorization" -> Seq("Basic Y2xpZW50X2lkX3ZhbHVl")), Map.empty) parsedCred.isLeft shouldBe true } it should "fetch empty client_secret with colon" in { val c = ValidatedRequest.parseClientCredential(Map("Authorization" -> Seq("Basic Y2xpZW50X2lkX3ZhbHVlOg==")), Map.empty).toOption.get c.clientId should be("client_id_value") c.clientSecret should be(None) } it should "not fetch not Authorization key in header" in { val c = ValidatedRequest.parseClientCredential(Map("authorizatio" -> Seq("Basic Y2xpZW50X2lkX3ZhbHVlOmNsaWVudF9zZWNyZXRfdmFsdWU=")), Map.empty) c should be(Left(InvalidClient(s"Failed to parse client credential from header (Missing authorization header) and params"))) } it should "not fetch invalid Base64" in { val parsedCred = ValidatedRequest.parseClientCredential(Map("Authorization" -> Seq("Basic basic")), Map.empty) parsedCred shouldBe Left(InvalidClient("Failed to parse client credential from header (invalid Base 64) and params")) } it should "fetch parameter" in { val c = ValidatedRequest.parseClientCredential(Map.empty, Map("client_id" -> Seq("client_id_value"), "client_secret" -> Seq("client_secret_value"))).toOption.get c.clientId should be("client_id_value") c.clientSecret should be(Some("client_secret_value")) } it should "omit client_secret" in { val c = ValidatedRequest.parseClientCredential(Map.empty, Map("client_id" -> Seq("client_id_value"))).toOption.get c.clientId should be("client_id_value") c.clientSecret should be(None) } it should "not fetch missing parameter" in { val c = ValidatedRequest.parseClientCredential(Map.empty, Map("client_secret" -> Seq("client_secret_value"))) c should be(Left(InvalidClient("Failed to parse client credential from header (Missing authorization header) and params"))) } it should "not fetch invalid parameter" in { val parsedCred = ValidatedRequest.parseClientCredential(Map("Authorization" -> Seq("")), Map.empty) parsedCred shouldBe Left(InvalidAuthorizationHeader) } it should "not fetch invalid Authorization header" in { val parsedCred = ValidatedRequest.parseClientCredential(Map("Authorization" -> Seq("Digest Y2xpZW50X2lkX3ZhbHVlOg==")), Map.empty) parsedCred shouldBe Left(InvalidAuthorizationHeader) } it should "not fetch if Authorization header is invalid, but client_id and client_secret are valid and present in parms" in { val parsedCred = ValidatedRequest.parseClientCredential(Map("Authorization" -> Seq("fakeheader aaaa")), Map("client_id" -> Seq("client_id_value"), "client_secret" -> Seq("client_secret_value"))) parsedCred shouldBe Left(InvalidAuthorizationHeader) } }
Example 76
Source File: AggregatorTest.scala From noether with Apache License 2.0 | 5 votes |
package com.spotify.noether import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream} import com.twitter.algebird.Aggregator import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers trait AggregatorTest extends AnyFlatSpec with Matchers { def run[A, B, C](aggregator: Aggregator[A, B, C])(as: Seq[A]): C = { val bs = as.map(aggregator.prepare _ compose ensureSerializable) val b = ensureSerializable(aggregator.reduce(bs)) ensureSerializable(aggregator.present(b)) } private def serializeToByteArray(value: Any): Array[Byte] = { val buffer = new ByteArrayOutputStream() val oos = new ObjectOutputStream(buffer) oos.writeObject(value) buffer.toByteArray } private def deserializeFromByteArray(encodedValue: Array[Byte]): AnyRef = { val ois = new ObjectInputStream(new ByteArrayInputStream(encodedValue)) ois.readObject() } private def ensureSerializable[T](value: T): T = deserializeFromByteArray(serializeToByteArray(value)).asInstanceOf[T] }
Example 77
Source File: EnumSpec.scala From finagle-postgres with Apache License 2.0 | 5 votes |
package com.twitter.finagle.postgres.generic import java.nio.charset.StandardCharsets import com.twitter.finagle.postgres.generic.enumeration.InvalidValue import com.twitter.finagle.postgres.values.{ValueDecoder, ValueEncoder} import com.twitter.util.{Return, Throw} import io.netty.buffer.Unpooled import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class EnumSpec extends AnyFlatSpec with Matchers { sealed trait TestEnum case object CaseOne extends TestEnum case object CaseTwo extends TestEnum sealed trait AnotherBranch extends TestEnum case object CaseThree extends AnotherBranch val UTF8 = StandardCharsets.UTF_8 "Enum decoding" should "decode enumeration ADTs from strings" in { val decoder = ValueDecoder[TestEnum] decoder.decodeText("enum_recv", "CaseOne") shouldEqual Return(CaseOne) decoder.decodeText("enum_recv", "CaseTwo") shouldEqual Return(CaseTwo) decoder.decodeText("enum_recv", "CaseThree") shouldEqual Return(CaseThree) decoder.decodeBinary( "enum_recv", Unpooled.copiedBuffer("CaseOne", UTF8), UTF8 ) shouldEqual Return(CaseOne) decoder.decodeBinary( "enum_recv", Unpooled.copiedBuffer("CaseTwo", UTF8), UTF8 ) shouldEqual Return(CaseTwo) decoder.decodeBinary( "enum_recv", Unpooled.copiedBuffer("CaseThree", UTF8), UTF8 ) shouldEqual Return(CaseThree) } it should "fail for an invalid value" in { val decoder = ValueDecoder[TestEnum] decoder.decodeText("enum_recv", "CasePurple") shouldEqual Throw(InvalidValue("CasePurple")) decoder.decodeBinary( "enum_recv", Unpooled.copiedBuffer("CasePurple", UTF8), UTF8 ) shouldEqual Throw(InvalidValue("CasePurple")) } "Enum encoding" should "encode enumeration ADTs to Strings" in { val encoder = ValueEncoder[TestEnum] encoder.encodeText(CaseOne) shouldEqual Some("CaseOne") encoder.encodeText(CaseTwo) shouldEqual Some("CaseTwo") encoder.encodeText(CaseThree) shouldEqual Some("CaseThree") encoder.encodeBinary(CaseOne, UTF8).get.toString(UTF8) shouldEqual "CaseOne" encoder.encodeBinary(CaseTwo, UTF8).get.toString(UTF8) shouldEqual "CaseTwo" encoder.encodeBinary(CaseThree, UTF8).get.toString(UTF8) shouldEqual "CaseThree" } }
Example 78
Source File: RowDecoderSpec.scala From finagle-postgres with Apache License 2.0 | 5 votes |
package com.twitter.finagle.postgres.generic import com.twitter.finagle.postgres.Row import com.twitter.finagle.postgres.values.ValueDecoder import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class RowDecoderSpec extends AnyFlatSpec with Matchers with MockFactory { val row = mock[Row] "Row decoder" should "decode non-nullables" in { case class Foo(int: Int, string: String, numeric: BigDecimal) val decoder = RowDecoder[Foo] (row.get(_: String)(_: ValueDecoder[Int])) expects ("int", ValueDecoder.int4) returning 10 (row.get(_: String)(_: ValueDecoder[String])) expects ("string", ValueDecoder.string) returning "ten" (row.get(_: String)(_: ValueDecoder[BigDecimal])) expects ("numeric", ValueDecoder.bigDecimal) returning BigDecimal(10.0) decoder(row) shouldEqual Foo(10, "ten", 10.0) } it should "decode nullables" in { case class FooWithNulls(int: Int, string: Option[String], numeric: BigDecimal) val decoder = RowDecoder[FooWithNulls] (row.get(_: String)(_: ValueDecoder[Int])) expects ("int", ValueDecoder.int4) returning 10 (row.getOption(_: String)(_: ValueDecoder[String])) expects ("string", ValueDecoder.string) returning None (row.get(_: String)(_: ValueDecoder[BigDecimal])) expects ("numeric", ValueDecoder.bigDecimal) returning BigDecimal(10.0) decoder(row) shouldEqual FooWithNulls(10, None, 10.0) } it should "decode join results" in { case class A(int: Int, string: String) case class B(int: Int, bool: Boolean) val decoder = RowDecoder[(A, B)] (row.get(_: String)(_: ValueDecoder[Int])) expects ("_1.int", ValueDecoder.int4) returning 10 (row.get(_: String)(_: ValueDecoder[String])) expects ("_1.string", ValueDecoder.string) returning "ten" (row.get(_: String)(_: ValueDecoder[Int])) expects ("_2.int", ValueDecoder.int4) returning 20 (row.get(_: String)(_: ValueDecoder[Boolean])) expects ("_2.bool", ValueDecoder.boolean) returning true decoder(row) shouldEqual (A(10, "ten"), B(20, true)) } }
Example 79
Source File: JsonTransformSpec.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._ import play.api.libs.json._ import play.api.libs.json.scalacheck.JsValueGenerators import scala.annotation.tailrec import scala.util.Random class JsonTransformSpec extends AnyFlatSpec with CompatibilityImplicits with JsValueGenerators { @tailrec private def verifyAllRedacted(all: Seq[(JsPath, JsValue)]): Unit = { val invalid = all collect { case (path, value) if value != JsonTransform.RedactedValue => path } assert(invalid.isEmpty, s"The following paths are invalid: ${invalid.mkString(", ")}") val nextGen = all flatMap { case (path, JsArray(items)) => items.zipWithIndex map { case (item, i) => (JsPath(path.path :+ IdxPathNode(i)), item) } case (path, JsObject(fields)) => fields map { case (k, v) => (path \ k, v) } case _ => Nil } if (nextGen.nonEmpty) { verifyAllRedacted(nextGen) } } "redactPaths" should "redact selected fields by path at the top level" in { forAll { obj: JsObject => val topLevelPaths: Seq[JsPath] = obj.fields.map(__ \ _._1) whenever(topLevelPaths.nonEmpty) { val redactedPaths: Seq[JsPath] = Random.shuffle(topLevelPaths) take Random.nextInt(topLevelPaths.size) implicit val redactor: JsonTransform[Any] = JsonTransform.redactPaths[Any](redactedPaths) val redacted = obj.transformAs[Any] // Useful for debugging // if (redactedPaths.nonEmpty) { // println(Json.prettyPrint(obj)) // println(s"with redacted paths (${redactedPaths.mkString(", ")}):") // println(Json.prettyPrint(redacted)) // } for (path <- redactedPaths) { assertResult(JsonTransform.RedactedValue) { path.asSingleJson(redacted).get } } } } } "redactAll" should "redact all fields of all paths" in { implicit val redactor: JsonTransform[Any] = JsonTransform.redactAll[Any]() forAll { obj: JsObject => val redacted = obj.transformAs[Any] verifyAllRedacted(Seq(__ -> redacted)) } } }
Example 80
Source File: JsValueOpsSpec.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import org.scalacheck.{Arbitrary, Gen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._ import play.api.libs.json._ import play.api.libs.json.scalacheck.JsValueGenerators case class Troll(value: String) object Troll { implicit val format: OFormat[Troll] = Json.format[Troll] } class JsValueOpsSpec extends AnyFlatSpec with CompatibilityImplicits with JsValueGenerators { implicit val arbTroll: Arbitrary[Troll] = Arbitrary(Gen.identifier.map(Troll(_))) "transformAs" should "use the implicit JsonTransform" in { val troll = JsString("trolled :)") implicit val transform: JsonTransform[Troll] = JsonTransform(_ => troll) forAll() { json: JsValue => assertResult(troll) { json.transformAs[Troll] } } } behavior of "asOrThrow" it should "convert the json as normal" in { implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value")) forAll() { troll: Troll => assertResult(troll) { Json.toJson(troll).asOrThrow[Troll] } } } it should "transform the json when throwing an exception" in { implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value")) forAll() { json: JsObject => val ex = intercept[InvalidJsonException] { json.asOrThrow[Troll] } assertResult(JsonTransform.RedactedValue) { (ex.json \ "value").get } } } }
Example 81
Source File: JsonTransformSpec.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._ import play.api.libs.json._ import play.api.libs.json.scalacheck.JsValueGenerators import scala.annotation.tailrec import scala.util.Random class JsonTransformSpec extends AnyFlatSpec with CompatibilityImplicits with JsValueGenerators { @tailrec private def verifyAllRedacted(all: Seq[(JsPath, JsValue)]): Unit = { val invalid = all collect { case (path, value) if value != JsonTransform.RedactedValue => path } assert(invalid.isEmpty, s"The following paths are invalid: ${invalid.mkString(", ")}") val nextGen = all flatMap { case (path, JsArray(items)) => items.zipWithIndex map { case (item, i) => (JsPath(path.path :+ IdxPathNode(i)), item) } case (path, JsObject(fields)) => fields map { case (k, v) => (path \ k, v) } case _ => Nil } if (nextGen.nonEmpty) { verifyAllRedacted(nextGen) } } "redactPaths" should "redact selected fields by path at the top level" in { forAll { obj: JsObject => val topLevelPaths: Seq[JsPath] = obj.fields.map(__ \ _._1).toSeq whenever(topLevelPaths.nonEmpty) { val redactedPaths: Seq[JsPath] = Random.shuffle(topLevelPaths) take Random.nextInt(topLevelPaths.size) implicit val redactor: JsonTransform[Any] = JsonTransform.redactPaths[Any](redactedPaths) val redacted = obj.transformAs[Any] // Useful for debugging // if (redactedPaths.nonEmpty) { // println(Json.prettyPrint(obj)) // println(s"with redacted paths (${redactedPaths.mkString(", ")}):") // println(Json.prettyPrint(redacted)) // } for (path <- redactedPaths) { assertResult(JsonTransform.RedactedValue) { path.asSingleJson(redacted).get } } } } } "redactAll" should "redact all fields of all paths" in { implicit val redactor: JsonTransform[Any] = JsonTransform.redactAll[Any]() forAll { obj: JsObject => val redacted = obj.transformAs[Any] verifyAllRedacted(Seq(__ -> redacted)) } } }
Example 82
Source File: JsValueOpsSpec.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import org.scalacheck.{Arbitrary, Gen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._ import play.api.libs.json._ import play.api.libs.json.scalacheck.JsValueGenerators case class Troll(value: String) object Troll { implicit val format: OFormat[Troll] = Json.format[Troll] } class JsValueOpsSpec extends AnyFlatSpec with CompatibilityImplicits with JsValueGenerators { implicit val arbTroll: Arbitrary[Troll] = Arbitrary(Gen.identifier.map(Troll(_))) "transformAs" should "use the implicit JsonTransform" in { val troll = JsString("trolled :)") implicit val transform: JsonTransform[Troll] = JsonTransform(_ => troll) forAll() { json: JsValue => assertResult(troll) { json.transformAs[Troll] } } } behavior of "asOrThrow" it should "convert the json as normal" in { implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value")) forAll() { troll: Troll => assertResult(troll) { Json.toJson(troll).asOrThrow[Troll] } } } it should "transform the json when throwing an exception" in { implicit val transform: JsonTransform[Troll] = JsonTransform.redactPaths[Troll](Seq(__ \ "value")) forAll() { json: JsObject => val ex = intercept[InvalidJsonException] { json.asOrThrow[Troll] } assertResult(JsonTransform.RedactedValue) { (ex.json \ "value").get } } } }
Example 83
Source File: DropwizardMarshallersSpec.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.dropwizard.marshalling import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.testkit.ScalatestRouteTest import fr.davit.akka.http.metrics.core.HttpMetricsRegistry.StatusGroupDimension import fr.davit.akka.http.metrics.core.scaladsl.server.HttpMetricsDirectives._ import fr.davit.akka.http.metrics.dropwizard.DropwizardRegistry import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import spray.json.{DefaultJsonProtocol, JsValue} import scala.concurrent.duration._ class DropwizardMarshallersSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll { private case class JsonResponse(metrics: Map[String, JsValue]) private trait Fixture extends SprayJsonSupport with DefaultJsonProtocol with DropwizardMarshallers { implicit val metricsFormat = jsonFormat1(JsonResponse) val registry = DropwizardRegistry() registry.underlying.counter("other.metric") } override def afterAll(): Unit = { cleanUp() super.afterAll() } "DropwizardMarshallers" should "expose metrics as json format" in new Fixture { // use metrics so they appear in the report val dimensions = Seq(StatusGroupDimension(StatusCodes.OK)) registry.requests.inc() registry.receivedBytes.update(10) registry.active.inc() registry.responses.inc(dimensions) registry.errors.inc() registry.duration.observe(1.second, dimensions) registry.sentBytes.update(10) Get() ~> metrics(registry) ~> check { val json = responseAs[JsonResponse] // println(json) json.metrics.keys should contain theSameElementsAs Seq( "akka.http.requests.active", "akka.http.requests", "akka.http.requests.bytes", "akka.http.responses{status=2xx}", "akka.http.responses.errors", "akka.http.responses.duration{status=2xx}", "akka.http.responses.bytes", "other.metric" ).toSet } } }
Example 84
Source File: DropwizardRegistrySpec.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.dropwizard import akka.http.scaladsl.model.StatusCodes import fr.davit.akka.http.metrics.core.Dimension import fr.davit.akka.http.metrics.core.HttpMetricsRegistry.{PathDimension, StatusGroupDimension} import io.dropwizard.metrics5.MetricName import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.duration._ import scala.collection.JavaConverters._ class DropwizardRegistrySpec extends AnyFlatSpec with Matchers { val dimensions = Seq(StatusGroupDimension(StatusCodes.OK), PathDimension("/api")) trait Fixture { val registry = DropwizardRegistry() def underlyingCounter(name: String, dims: Seq[Dimension] = Seq.empty): Long = { registry.underlying.getCounters.asScala(metricName(name, dims)).getCount } def underlyingHistogram(name: String, dims: Seq[Dimension] = Seq.empty): Long = { registry.underlying.getHistograms.asScala(metricName(name, dims)).getSum } def underlyingTimer(name: String, dims: Seq[Dimension] = Seq.empty): Long = { registry.underlying.getTimers.asScala(metricName(name, dims)).getSum } private def metricName(name: String, dims: Seq[Dimension]): MetricName = { MetricName.build(name).tagged(dims.map(d => d.key -> d.value).toMap.asJava) } } "DropwizardRegistry" should "set active metrics in the underlying registry" in new Fixture { registry.active.inc() underlyingCounter("akka.http.requests.active") shouldBe 1L } it should "set requests metrics in the underlying registry" in new Fixture { registry.requests.inc() underlyingCounter("akka.http.requests") shouldBe 1L } it should "set receivedBytes metrics in the underlying registry" in new Fixture { registry.receivedBytes.update(3) underlyingHistogram("akka.http.requests.bytes") shouldBe 3L } it should "set responses metrics in the underlying registry" in new Fixture { registry.responses.inc() underlyingCounter("akka.http.responses") shouldBe 1L registry.responses.inc(dimensions) underlyingCounter("akka.http.responses", dimensions) shouldBe 1L } it should "set errors metrics in the underlying registry" in new Fixture { registry.errors.inc() underlyingCounter("akka.http.responses.errors") shouldBe 1L registry.errors.inc(dimensions) underlyingCounter("akka.http.responses.errors", dimensions) shouldBe 1L } it should "set duration metrics in the underlying registry" in new Fixture { registry.duration.observe(3.seconds) underlyingTimer("akka.http.responses.duration") shouldBe 3000000000L registry.duration.observe(3.seconds, dimensions) underlyingTimer("akka.http.responses.duration", dimensions) shouldBe 3000000000L } it should "set sentBytes metrics in the underlying registry" in new Fixture { registry.sentBytes.update(3) underlyingHistogram("akka.http.responses.bytes") shouldBe 3L registry.sentBytes.update(3, dimensions) underlyingHistogram("akka.http.responses.bytes", dimensions) shouldBe 3L } it should "set connected metrics in the underlying registry" in new Fixture { registry.connected.inc() underlyingCounter("akka.http.connections.active") shouldBe 1L } it should "set connections metrics in the underlying registry" in new Fixture { registry.connections.inc() underlyingCounter("akka.http.connections") shouldBe 1L } }
Example 85
Source File: PrometheusMarshallersSpec.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.prometheus.marshalling import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.testkit.ScalatestRouteTest import fr.davit.akka.http.metrics.core.HttpMetricsRegistry.StatusGroupDimension import fr.davit.akka.http.metrics.core.scaladsl.server.HttpMetricsDirectives.metrics import fr.davit.akka.http.metrics.prometheus.{PrometheusRegistry, PrometheusSettings} import io.prometheus.client.CollectorRegistry import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.duration._ class PrometheusMarshallersSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll { trait Fixture extends PrometheusMarshallers { val registry = PrometheusRegistry( new CollectorRegistry(), PrometheusSettings.default.withIncludeStatusDimension(true) ) io.prometheus.client.Counter .build("other_metric", "An other metric") .register(registry.underlying) } override def afterAll(): Unit = { cleanUp() super.afterAll() } "PrometheusMarshallers" should "expose metrics as prometheus format" in new Fixture { // register labeled metrics so they appear at least once // use metrics so they appear in the report val dimensions = Seq(StatusGroupDimension(StatusCodes.OK)) registry.requests.inc() registry.receivedBytes.update(10) registry.active.inc() registry.responses.inc(dimensions) registry.errors.inc(dimensions) registry.duration.observe(1.second, dimensions) registry.sentBytes.update(10, dimensions) Get() ~> metrics(registry) ~> check { response.entity.contentType shouldBe PrometheusMarshallers.PrometheusContentType val text = responseAs[String] // println(text) val metrics = text .split('\n') .filterNot(_.startsWith("#")) .map(_.takeWhile(c => c != ' ' && c != '{')) .distinct metrics should contain theSameElementsAs Seq( "akka_http_requests_active", "akka_http_requests_total", "akka_http_requests_size_bytes_bucket", "akka_http_requests_size_bytes_count", "akka_http_requests_size_bytes_sum", "akka_http_responses_total", "akka_http_responses_errors_total", "akka_http_responses_duration_seconds_bucket", "akka_http_responses_duration_seconds_count", "akka_http_responses_duration_seconds_sum", "akka_http_responses_size_bytes_bucket", "akka_http_responses_size_bytes_count", "akka_http_responses_size_bytes_sum", "akka_http_connections_active", "akka_http_connections_total", "other_metric" ) } } }
Example 86
Source File: HttpMetricsDirectivesSpec.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.core.scaladsl.server import akka.http.scaladsl.marshalling.PredefinedToEntityMarshallers._ import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.testkit.ScalatestRouteTest import fr.davit.akka.http.metrics.core.TestRegistry import fr.davit.akka.http.metrics.core.scaladsl.model.PathLabelHeader import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class HttpMetricsDirectivesSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest { import HttpMetricsDirectives._ "HttpMetricsDirectives" should "expose the registry" in { implicit val marshaller = StringMarshaller.compose[TestRegistry](r => s"active: ${r.active.value()}") val registry = new TestRegistry() registry.active.inc() val route = path("metrics") { metrics(registry) } Get("/metrics") ~> route ~> check { responseAs[String] shouldBe "active: 1" } } it should "put label on path" in { val route = pathPrefixLabeled("api") { pathPrefix("user" / LongNumber) { _ => path("address") { complete(StatusCodes.OK) } } } Get("/api/user/1234/address") ~> route ~> check { header[PathLabelHeader] shouldBe Some(PathLabelHeader("/api")) } } it should "combine labelled segments" in { val route = pathPrefixLabeled("api") { pathPrefixLabeled("user" / LongNumber, "user/:userId") { _ => pathLabeled("address") { complete(StatusCodes.OK) } } } Get("/api/user/1234/address") ~> route ~> check { header[PathLabelHeader] shouldBe Some(PathLabelHeader("/api/user/:userId/address")) } } it should "not add extra header when label directives are not used" in { val route = pathPrefix("api") { pathPrefix("user" / LongNumber) { _ => path("address") { complete(StatusCodes.OK) } } } Get("/api/user/1234/address") ~> route ~> check { header[PathLabelHeader] shouldBe empty } } }
Example 87
Source File: TestSuiteTests.scala From circe-json-schema with Apache License 2.0 | 5 votes |
package io.circe.schema import cats.data.Validated import io.circe.{ Decoder, Json } import java.io.File import org.scalatest.flatspec.AnyFlatSpec case class SchemaTestCase(description: String, data: Json, valid: Boolean) case class SchemaTest(description: String, schema: Json, tests: List[SchemaTestCase]) object SchemaTestCase { implicit val decodeSchemaTestCase: Decoder[SchemaTestCase] = io.circe.generic.semiauto.deriveDecoder } object SchemaTest { implicit val decodeSchemaTest: Decoder[SchemaTest] = io.circe.generic.semiauto.deriveDecoder } class TestSuiteTests(path: String) extends AnyFlatSpec { val tests: List[SchemaTest] = io.circe.jawn .decodeFile[List[SchemaTest]](new File(path)) .getOrElse( throw new Exception(s"Unable to load test file: $path") ) tests.foreach { case SchemaTest(description, schema, tests) => tests.foreach { case SchemaTestCase(caseDescription, data, valid) => val expected = if (valid) "validate successfully" else "fail to validate" s"$description: $caseDescription" should expected in { val errors = Schema.load(schema).validate(data) if (valid) { assert(errors == Validated.valid(())) } else { assert(errors.isInvalid) } } it should s"$expected when schema is loaded from a string" in { val errors = Schema.loadFromString(schema.noSpaces).get.validate(data) if (valid) { assert(errors == Validated.valid(())) } else { assert(errors.isInvalid) } } } } } class AdditionalItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/additionalItems.json") class AdditionalPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/additionalProperties.json") class AllOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/allOf.json") class AnyOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/anyOf.json") class BooleanSchemaTestSuiteTests extends TestSuiteTests("tests/tests/draft7/boolean_schema.json") class ConstTestSuiteTests extends TestSuiteTests("tests/tests/draft7/const.json") class ContainsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/contains.json") class DefaultTestSuiteTests extends TestSuiteTests("tests/tests/draft7/default.json") //class DefinitionsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/definitions.json") class EnumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/enum.json") class ExclusiveMaximumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/exclusiveMaximum.json") class ExclusiveMinimumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/exclusiveMinimum.json") class FormatTestSuiteTests extends TestSuiteTests("tests/tests/draft7/format.json") class IfThenElseTestSuiteTests extends TestSuiteTests("tests/tests/draft7/if-then-else.json") class ItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/items.json") class MaximumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maximum.json") class MaxItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maxItems.json") class MaxLengthTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maxLength.json") class MaxPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maxProperties.json") class MinimumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minimum.json") class MinItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minItems.json") class MinLengthTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minLength.json") class MinPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minProperties.json") class MultipleOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/multipleOf.json") class NotTestSuiteTests extends TestSuiteTests("tests/tests/draft7/not.json") class OneOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/oneOf.json") class PatternTestSuiteTests extends TestSuiteTests("tests/tests/draft7/pattern.json") class PatternPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/patternProperties.json") class PropertyNamesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/propertyNames.json") // Not currently running remote tests. //class RefTestSuiteTests extends TestSuiteTests("tests/tests/draft7/ref.json") //class RefRemoteTestSuiteTests extends TestSuiteTests("tests/tests/draft7/refRemote.json") class RequiredTestSuiteTests extends TestSuiteTests("tests/tests/draft7/required.json") class TypeTestSuiteTests extends TestSuiteTests("tests/tests/draft7/type.json") class UniqueItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/uniqueItems.json")
Example 88
Source File: BqResultSetTest.scala From scalikejdbc-bigquery with Apache License 2.0 | 5 votes |
package scalikejdbc.bigquery import java.time.{LocalDate, LocalTime, ZoneId, ZonedDateTime} import com.google.cloud.bigquery._ import org.scalatest.flatspec.AnyFlatSpec class BqResultSetTest extends AnyFlatSpec { it should "be able to instantiate from null Schema" in { val tableResult = MockUtil.tableResultFromSeq(Nil, null) new BqResultSet(tableResult) } it should "correctly traversable" in { val row1 = Seq(BqParameter.String("first")).map(MockUtil.fieldValueFromParameter(_)) val row2 = Seq(BqParameter.String("second")).map(MockUtil.fieldValueFromParameter(_)) val row3 = Seq(BqParameter.String("third")).map(MockUtil.fieldValueFromParameter(_)) val schema = Schema.of(Field.of("name", LegacySQLTypeName.STRING)); val queryResult = MockUtil.tableResultFromSeq(Seq(row1, row2, row3), schema) val resultSet = new BqResultSet(queryResult) assert(resultSet.next()) assert(resultSet.next()) assert(resultSet.next()) assert(!resultSet.next()) } it should "correctly get value" in { val row = Seq( BqParameter.Int64(42L), BqParameter.Float64(3.14159), BqParameter.Bool(true), BqParameter.String("hello"), BqParameter.Bytes(Array[Byte](104, 101, 108, 108, 111)), BqParameter.Date(LocalDate.of(2017, 3, 22)), // BqParameter.DateTime BqParameter.Time(LocalTime.of(19, 58, 0, 0)), BqParameter.Timestamp(ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo"))) ).map(MockUtil.fieldValueFromParameter(_)) val fields = Seq( Field.of("int64_column", LegacySQLTypeName.INTEGER), Field.of("float64_column", LegacySQLTypeName.FLOAT), Field.of("bool_column", LegacySQLTypeName.BOOLEAN), Field.of("string_column", LegacySQLTypeName.STRING), Field.of("bytes_column", LegacySQLTypeName.BYTES), Field.of("date_column", LegacySQLTypeName.STRING), Field.of("time_column", LegacySQLTypeName.STRING), Field.of("timestamp_column", LegacySQLTypeName.TIMESTAMP) ) val schema = Schema.of(fields: _*) val queryResult = MockUtil.tableResultFromSeq(Seq(row), schema) val resultSet = new BqResultSet(queryResult) assert(resultSet.next()) // int64 assert(resultSet.getInt(0) == 42) assert(resultSet.getInt("int64_column") == 42) // float64 assert(resultSet.getDouble(1) == 3.14159) assert(resultSet.getDouble("float64_column") == 3.14159) // bool assert(resultSet.getBoolean(2) == true) assert(resultSet.getBoolean("bool_column") == true) // string assert(resultSet.getString(3) == "hello") assert(resultSet.getString("string_column") == "hello") // bytes assert(resultSet.getBytes(4).sameElements(Array[Byte](104, 101, 108, 108, 111))) assert(resultSet.getBytes("bytes_column").sameElements(Array[Byte](104, 101, 108, 108, 111))) // date assert(resultSet.getDate(5).toLocalDate == LocalDate.of(2017, 3, 22)) assert(resultSet.getDate("date_column").toLocalDate == LocalDate.of(2017, 3, 22)) // time assert(resultSet.getTime(6).toLocalTime == LocalTime.of(19, 58, 0, 0)) assert(resultSet.getTime("time_column").toLocalTime == LocalTime.of(19, 58, 0, 0)) // timestamp assert(resultSet.getTimestamp(7).toInstant == ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo")).toInstant) assert(resultSet.getTimestamp("timestamp_column").toInstant == ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo")).toInstant) } }
Example 89
Source File: PackageObjectLazinessSpec.scala From cats-retry with Apache License 2.0 | 5 votes |
package retry.alleycats import cats.instances.future._ import org.scalatest.flatspec.AnyFlatSpec import retry._ import retry.alleycats.instances._ import scala.collection.mutable.ArrayBuffer import scala.concurrent.duration._ import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class PackageObjectLazinessSpec extends AnyFlatSpec { behavior of "retryingM" // this test reproduces issue #116 it should "not evaluate the next attempt until it has finished sleeping" in new TestContext { val policy = RetryPolicies.constantDelay[Future](5.second) // Kick off an operation which will fail, wait 5 seconds, and repeat forever, in a Future val _ = retryingM[String][Future]( policy, _ => false, (a, retryDetails) => Future.successful(onError(a, retryDetails)) ) { Future { attempts = attempts + 1 attempts.toString } } // Wait for the first attempt to complete. By now we should be part way through the first delay. Thread.sleep(1000) // Assert that we haven't eagerly evaluated any more attempts. assert(attempts == 1) assert(errors.toList == List("1")) assert(delays.toList == List(5.second)) } private class TestContext { var attempts = 0 val errors = ArrayBuffer.empty[String] val delays = ArrayBuffer.empty[FiniteDuration] var gaveUp = false def onError(error: String, details: RetryDetails): Future[Unit] = Future.successful { errors.append(error) details match { case RetryDetails.WillDelayAndRetry(delay, _, _) => delays.append(delay) case RetryDetails.GivingUp(_, _) => gaveUp = true } } } }
Example 90
Source File: FibonacciSpec.scala From cats-retry with Apache License 2.0 | 5 votes |
package retry import org.scalatest.flatspec.AnyFlatSpec class FibonacciSpec extends AnyFlatSpec { it should "calculate the Fibonacci sequence" in { assert(Fibonacci.fibonacci(0) == 0) assert(Fibonacci.fibonacci(1) == 1) assert(Fibonacci.fibonacci(2) == 1) assert(Fibonacci.fibonacci(3) == 2) assert(Fibonacci.fibonacci(4) == 3) assert(Fibonacci.fibonacci(5) == 5) assert(Fibonacci.fibonacci(6) == 8) assert(Fibonacci.fibonacci(7) == 13) assert(Fibonacci.fibonacci(75) == 2111485077978050L) } }
Example 91
Source File: RetryPolicySpec.scala From cats-retry with Apache License 2.0 | 5 votes |
package retry import cats.Id import cats.syntax.semigroup._ import org.scalatest.flatspec.AnyFlatSpec import scala.concurrent.duration._ class RetryPolicySpec extends AnyFlatSpec { behavior of "BoundedSemilattice append" it should "give up if either of the composed policies decides to give up" in { val alwaysGiveUp = RetryPolicy.lift[Id](_ => PolicyDecision.GiveUp) val alwaysRetry = RetryPolicies.constantDelay[Id](1.second) assert( (alwaysGiveUp |+| alwaysRetry) .decideNextRetry(RetryStatus.NoRetriesYet) == PolicyDecision.GiveUp ) assert( (alwaysRetry |+| alwaysGiveUp) .decideNextRetry(RetryStatus.NoRetriesYet) == PolicyDecision.GiveUp ) } it should "choose the maximum of the delays if both of the composed policies decides to retry" in { val delayOneSecond = RetryPolicy.lift[Id](_ => PolicyDecision.DelayAndRetry(1.second)) val delayTwoSeconds = RetryPolicy.lift[Id](_ => PolicyDecision.DelayAndRetry(2.seconds)) assert( (delayOneSecond |+| delayTwoSeconds).decideNextRetry( RetryStatus.NoRetriesYet ) == PolicyDecision.DelayAndRetry(2.seconds) ) assert( (delayTwoSeconds |+| delayOneSecond).decideNextRetry( RetryStatus.NoRetriesYet ) == PolicyDecision.DelayAndRetry(2.seconds) ) } }
Example 92
Source File: DefaultsSpec.scala From sparksql-scalapb with Apache License 2.0 | 5 votes |
package scalapb.spark import org.apache.spark.sql.{Row, SparkSession} import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class DefaultsSpec extends AnyFlatSpec with Matchers with BeforeAndAfterAll { val spark: SparkSession = SparkSession .builder() .appName("ScalaPB Demo") .master("local[2]") .getOrCreate() "Proto2 RDD[DefaultsRequired]" should "have non-null default values after converting to Dataframe" in { import com.example.protos.defaults.DefaultsRequired val defaults = DefaultsRequired.defaultInstance val row = ProtoSQL.createDataFrame(spark, Seq(defaults)).collect().head val expected = Row( defaults.i32Value, defaults.i64Value, defaults.u32Value, defaults.u64Value, defaults.dValue, defaults.fValue, defaults.bValue, defaults.sValue, defaults.binaryValue.toByteArray ) row must be(expected) } "Proto2 RDD[DefaultsOptional]" should "have null values after converting to Dataframe" in { import com.example.protos.defaults.DefaultsOptional val defaults = DefaultsOptional.defaultInstance val row = ProtoSQL.createDataFrame(spark, Seq(defaults)).collect().head val expected = Row(null, null, null, null, null, null, null, null, null) row must be(expected) } "Proto3 RDD[DefaultsV3]" should "have non-null default values after converting to Dataframe" in { import com.example.protos.defaultsv3.DefaultsV3 val defaults = DefaultsV3.defaultInstance val row = ProtoSQL.createDataFrame(spark, Seq(defaults)).collect().head val expected = Row( defaults.i32Value, defaults.i64Value, defaults.u32Value, defaults.u64Value, defaults.dValue, defaults.fValue, defaults.bValue, defaults.sValue, defaults.binaryValue.toByteArray ) row must be(expected) } }
Example 93
Source File: WrappersSpec.scala From sparksql-scalapb with Apache License 2.0 | 5 votes |
package scalapb.spark import com.example.protos.wrappers._ import org.apache.spark.sql.SparkSession import org.apache.hadoop.io.ArrayPrimitiveWritable import scalapb.GeneratedMessageCompanion import org.apache.spark.sql.types.IntegerType import org.apache.spark.sql.types.ArrayType import org.apache.spark.sql.types.StructField import org.apache.spark.sql.types.StructType import org.apache.spark.sql.types.StringType import org.apache.spark.sql.Row import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class WrappersSpec extends AnyFlatSpec with Matchers with BeforeAndAfterAll { val spark: SparkSession = SparkSession .builder() .appName("ScalaPB Demo") .master("local[2]") .getOrCreate() import spark.implicits.StringToColumn val data = Seq( PrimitiveWrappers( intValue = Option(45), stringValue = Option("boo"), ints = Seq(17, 19, 25), strings = Seq("foo", "bar") ), PrimitiveWrappers( intValue = None, stringValue = None, ints = Seq(17, 19, 25), strings = Seq("foo", "bar") ) ) "converting df with primitive wrappers" should "work with primitive implicits" in { import ProtoSQL.withPrimitiveWrappers.implicits._ val df = ProtoSQL.withPrimitiveWrappers.createDataFrame(spark, data) df.schema.fields.map(_.dataType).toSeq must be( Seq( IntegerType, StringType, ArrayType(IntegerType, false), ArrayType(StringType, false) ) ) df.collect must contain theSameElementsAs ( Seq( Row(45, "boo", Seq(17, 19, 25), Seq("foo", "bar")), Row(null, null, Seq(17, 19, 25), Seq("foo", "bar")) ) ) } "converting df with primitive wrappers" should "work with default implicits" in { import ProtoSQL.implicits._ val df = ProtoSQL.createDataFrame(spark, data) df.schema.fields.map(_.dataType).toSeq must be( Seq( StructType(Seq(StructField("value", IntegerType, true))), StructType(Seq(StructField("value", StringType, true))), ArrayType( StructType(Seq(StructField("value", IntegerType, true))), false ), ArrayType( StructType(Seq(StructField("value", StringType, true))), false ) ) ) df.collect must contain theSameElementsAs ( Seq( Row( Row(45), Row("boo"), Seq(Row(17), Row(19), Row(25)), Seq(Row("foo"), Row("bar")) ), Row( null, null, Seq(Row(17), Row(19), Row(25)), Seq(Row("foo"), Row("bar")) ) ) ) } }
Example 94
Source File: MapsSpec.scala From sparksql-scalapb with Apache License 2.0 | 5 votes |
package scalapb.spark import com.example.protos.maps._ import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import org.apache.spark.sql.SparkSession import org.scalatest.BeforeAndAfterAll class MapsSpec extends AnyFlatSpec with Matchers with BeforeAndAfterAll { val spark: SparkSession = SparkSession .builder() .appName("ScalaPB Demo") .master("local[2]") .getOrCreate() import spark.implicits.StringToColumn import Implicits._ val data = Seq( MapTest(attributes = Map("foo" -> "bar")) ) "converting maps to df" should "work" in { val df = ProtoSQL.createDataFrame(spark, data) val res = df.as[MapTest].map(r => r) res.show() } }
Example 95
Source File: IntegrationSpec.scala From struct-type-encoder with Apache License 2.0 | 5 votes |
package ste import org.apache.spark.sql.SparkSession import org.scalatest.BeforeAndAfterAll import ste.StructTypeEncoder._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers case class Foo(a: Int, b: String) class IntegrationSpec extends AnyFlatSpec with Matchers with BeforeAndAfterAll { val spark = SparkSession.builder() .master("local") .appName("Integration spec") .getOrCreate() import spark.implicits._ override def afterAll(): Unit = spark.close() "The derived schema" should "be applied" in { val url = getClass().getResource("/test.json").toString val ds = spark .read .schema(StructTypeEncoder[Foo].encode) .json(url) .as[Foo] .collect() ds.length shouldBe 2 ds.head shouldBe Foo(1, "str") ds(1) shouldBe Foo(2, "ing") } }
Example 96
Source File: WritingBenchmarkSpec.scala From circe-benchmarks with Apache License 2.0 | 5 votes |
package io.circe.benchmarks import argonaut.Parse, argonaut.Argonaut._ import org.scalatest.flatspec.AnyFlatSpec class WritingBenchmarkSpec extends AnyFlatSpec { val benchmark: WritingBenchmark = new WritingBenchmark import benchmark._ def decodeInts(json: String): Option[List[Int]] = Parse.decodeOption[List[Int]](json) def decodeFoos(json: String): Option[Map[String, Foo]] = Parse.decodeOption[Map[String, Foo]](json) "The writing benchmark" should "correctly write integers using Circe" in { assert(decodeInts(writeIntsCirce) === Some(ints)) } it should "correctly write integers using Argonaut" in { assert(decodeInts(writeIntsArgonaut) === Some(ints)) } it should "correctly write integers using Spray JSON" in { assert(decodeInts(writeIntsSpray) === Some(ints)) } it should "correctly write integers using Json4s" in { assert(decodeInts(writeIntsJson4s) === Some(ints)) } it should "correctly write integers using Play JSON" in { assert(decodeInts(writeIntsPlay) === Some(ints)) } it should "correctly write case classes using Circe" in { assert(decodeFoos(writeFoosCirce) === Some(foos)) } it should "correctly write case classes using Argonaut" in { assert(decodeFoos(writeFoosArgonaut) === Some(foos)) } it should "correctly write case classes using Spray JSON" in { assert(decodeFoos(writeFoosSpray) === Some(foos)) } it should "correctly write case classes using Json4s" in { assert(decodeFoos(writeFoosJson4s) === Some(foos)) } it should "correctly write case classes using Play JSON" in { assert(decodeFoos(writeFoosPlay) === Some(foos)) } }
Example 97
Source File: EncodingBenchmarkSpec.scala From circe-benchmarks with Apache License 2.0 | 5 votes |
package io.circe.benchmarks import argonaut.Parse import argonaut.Argonaut._ import org.json4s.jackson.JsonMethods import org.scalatest.flatspec.AnyFlatSpec import play.api.libs.json.Json class EncodingBenchmarkSpec extends AnyFlatSpec { val benchmark: EncodingBenchmark = new EncodingBenchmark import benchmark._ def decodeInts(json: String): Option[List[Int]] = Parse.decodeOption[List[Int]](json) def decodeFoos(json: String): Option[Map[String, Foo]] = Parse.decodeOption[Map[String, Foo]](json) "The encoding benchmark" should "correctly encode integers using Circe" in { assert(decodeInts(encodeIntsCirce.noSpaces) === Some(ints)) } it should "correctly encode integers using Argonaut" in { assert(decodeInts(encodeIntsArgonaut.nospaces) === Some(ints)) } it should "correctly encode integers using Spray JSON" in { assert(decodeInts(encodeIntsSpray.compactPrint) === Some(ints)) } it should "correctly encode integers using Json4s" in { assert(decodeInts(JsonMethods.compact(encodeIntsJson4s)) === Some(ints)) } it should "correctly encode integers using Play JSON" in { assert(decodeInts(Json.prettyPrint(encodeIntsPlay)) === Some(ints)) } it should "correctly encode case classes using Circe" in { assert(decodeFoos(encodeFoosCirce.noSpaces) === Some(foos)) } it should "correctly encode case classes using Argonaut" in { assert(decodeFoos(encodeFoosArgonaut.nospaces) === Some(foos)) } it should "correctly encode case classes using Spray JSON" in { assert(decodeFoos(encodeFoosSpray.compactPrint) === Some(foos)) } it should "correctly encode case classes using Json4s" in { assert(decodeFoos(JsonMethods.compact(encodeFoosJson4s)) === Some(foos)) } it should "correctly encode case classes using Play JSON" in { assert(decodeFoos(Json.prettyPrint(encodeFoosPlay)) === Some(foos)) } }
Example 98
Source File: PrintingBenchmarkSpec.scala From circe-benchmarks with Apache License 2.0 | 5 votes |
package io.circe.benchmarks import argonaut.Parse, argonaut.Argonaut._ import org.scalatest.flatspec.AnyFlatSpec class PrintingBenchmarkSpec extends AnyFlatSpec { val benchmark: PrintingBenchmark = new PrintingBenchmark import benchmark._ def decodeInts(json: String): Option[List[Int]] = Parse.decodeOption[List[Int]](json) def decodeFoos(json: String): Option[Map[String, Foo]] = Parse.decodeOption[Map[String, Foo]](json) "The printing benchmark" should "correctly print integers using Circe" in { assert(decodeInts(printIntsCirce) === Some(ints)) } it should "correctly print integers using Circe Jackson" in { assert(decodeInts(printIntsCirceJackson) === Some(ints)) } it should "correctly print integers using Argonaut" in { assert(decodeInts(printIntsArgonaut) === Some(ints)) } it should "correctly print integers using Spray JSON" in { assert(decodeInts(printIntsSpray) === Some(ints)) } it should "correctly print integers using Json4s" in { assert(decodeInts(printIntsJson4s) === Some(ints)) } it should "correctly print integers using Play JSON" in { assert(decodeInts(printIntsPlay) === Some(ints)) } it should "correctly print case classes using Circe" in { assert(decodeFoos(printFoosCirce) === Some(foos)) } it should "correctly print case classes using Circe Jackson" in { assert(decodeFoos(printFoosCirceJackson) === Some(foos)) } it should "correctly print case classes using Argonaut" in { assert(decodeFoos(printFoosArgonaut) === Some(foos)) } it should "correctly print case classes using Spray JSON" in { assert(decodeFoos(printFoosSpray) === Some(foos)) } it should "correctly print case classes using Json4s" in { assert(decodeFoos(printFoosJson4s) === Some(foos)) } it should "correctly print case classes using Play JSON" in { assert(decodeFoos(printFoosPlay) === Some(foos)) } }
Example 99
Source File: ParsingBenchmarkSpec.scala From circe-benchmarks with Apache License 2.0 | 5 votes |
package io.circe.benchmarks import org.scalatest.flatspec.AnyFlatSpec class ParsingBenchmarkSpec extends AnyFlatSpec { val benchmark: ParsingBenchmark = new ParsingBenchmark import benchmark._ "The parsing benchmark" should "correctly parse integers using Circe" in { assert(parseIntsCirce === Right(intsC)) } it should "correctly parse integers using Circe Jackson" in { assert(parseIntsCirceJackson === Right(intsC)) } it should "correctly parse integers using Argonaut" in { assert(parseIntsArgonaut === Right(intsA)) } it should "correctly parse integers using Spray JSON" in { assert(parseIntsSpray === intsS) } it should "correctly parse integers using Json4s" in { assert(parseIntsJson4s === ints4s) } it should "correctly parse integers using Play JSON" in { assert(parseIntsPlay === intsP) } it should "correctly parse case classes using Circe" in { assert(parseFoosCirce === Right(foosC)) } it should "correctly parse case classes using Circe Jackson" in { assert(parseFoosCirceJackson === Right(foosC)) } it should "correctly parse case classes using Argonaut" in { assert(parseFoosArgonaut === Right(foosA)) } it should "correctly parse case classes using Spray JSON" in { assert(parseFoosSpray === foosS) } it should "correctly parse case classes using Json4s" in { assert(parseFoosJson4s === foos4s) } it should "correctly parse case classes using Play JSON" in { assert(parseFoosPlay === foosP) } }
Example 100
Source File: DecodingBenchmarkSpec.scala From circe-benchmarks with Apache License 2.0 | 5 votes |
package io.circe.benchmarks import org.scalatest.flatspec.AnyFlatSpec class DecodingBenchmarkSpec extends AnyFlatSpec { val benchmark: DecodingBenchmark = new DecodingBenchmark import benchmark._ "The decoding benchmark" should "correctly decode integers using Circe" in { assert(decodeIntsCirce === Right(ints)) } it should "correctly decode integers using Argonaut" in { assert(decodeIntsArgonaut.result === Right(ints)) } it should "correctly decode integers using Spray JSON" in { assert(decodeIntsSpray === ints) } it should "correctly decode integers using Json4s" in { assert(decodeIntsJson4s === ints) } it should "correctly decode integers using Play JSON" in { assert(decodeIntsPlay === ints) } it should "correctly decode case classes using Circe" in { assert(decodeFoosCirce === Right(foos)) } it should "correctly decode case classes using Argonaut" in { assert(decodeFoosArgonaut.result === Right(foos)) } it should "correctly decode case classes using Spray JSON" in { assert(decodeFoosSpray === foos) } it should "correctly decode case classes using Json4s" in { assert(decodeFoosJson4s === foos) } it should "correctly decode case classes using Play JSON" in { assert(decodeFoosPlay === foos) } }
Example 101
Source File: ReadingBenchmarkSpec.scala From circe-benchmarks with Apache License 2.0 | 5 votes |
package io.circe.benchmarks import org.scalatest.flatspec.AnyFlatSpec class ReadingBenchmarkSpec extends AnyFlatSpec { val benchmark: ReadingBenchmark = new ReadingBenchmark import benchmark._ "The reading benchmark" should "correctly read integers using Circe" in { assert(readIntsCirce === Right(ints)) } it should "correctly read integers using Argonaut" in { assert(readIntsArgonaut === Right(ints)) } it should "correctly read integers using Spray JSON" in { assert(readIntsSpray === ints) } it should "correctly read integers using Json4s" in { assert(readIntsJson4s === ints) } it should "correctly read integers using Play JSON" in { assert(readIntsPlay === ints) } it should "correctly read case classes using Circe" in { assert(readFoosCirce === Right(foos)) } it should "correctly read case classes using Argonaut" in { assert(readFoosArgonaut === Right(foos)) } it should "correctly read case classes using Spray JSON" in { assert(readFoosSpray === foos) } it should "correctly read case classes using Json4s" in { assert(readFoosJson4s === foos) } it should "correctly read case classes using Play JSON" in { assert(readFoosPlay === foos) } }
Example 102
Source File: RerunnableBenchmarkSpec.scala From catbird with Apache License 2.0 | 5 votes |
package io.catbird.benchmark import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec class RerunnableBenchmarkSpec extends AnyFlatSpec with BeforeAndAfter { val benchmark: RerunnableBenchmark = new RerunnableBenchmark val sum = benchmark.numbers.sum before(benchmark.initPool()) after(benchmark.shutdownPool()) "The benchmark" should "correctly calculate the sum using futures" in { assert(benchmark.sumIntsF === sum) } it should "correctly calculate the sum using futures and future pools" in { assert(benchmark.sumIntsPF === sum) } it should "correctly calculate the sum using rerunnables" in { assert(benchmark.sumIntsR === sum) } it should "correctly calculate the sum using rerunnables and future pools" in { assert(benchmark.sumIntsPR === sum) } }
Example 103
Source File: StoreOpsTest.scala From fs2-blobstore with Apache License 2.0 | 5 votes |
package blobstore import java.nio.charset.Charset import java.nio.file.Files import java.util.concurrent.Executors import cats.effect.{Blocker, IO} import cats.effect.laws.util.TestInstances import fs2.{Pipe, Stream} import org.scalatest.Assertion import org.scalatest.flatspec.AnyFlatSpec import implicits._ import org.scalatest.matchers.must.Matchers import scala.collection.mutable.ArrayBuffer import scala.concurrent.ExecutionContext class StoreOpsTest extends AnyFlatSpec with Matchers with TestInstances { implicit val cs = IO.contextShift(ExecutionContext.global) val blocker = Blocker.liftExecutionContext(ExecutionContext.fromExecutor(Executors.newCachedThreadPool)) behavior of "PutOps" it should "buffer contents and compute size before calling Store.put" in { val bytes: Array[Byte] = "AAAAAAAAAA".getBytes(Charset.forName("utf-8")) val store = DummyStore(_.size must be(Some(bytes.length))) Stream .emits(bytes) .covary[IO] .through(store.bufferedPut(Path("path/to/file.txt"), blocker)) .compile .drain .unsafeRunSync() store.buf.toArray must be(bytes) } it should "upload a file from a nio Path" in { val bytes = "hello".getBytes(Charset.forName("utf-8")) val store = DummyStore(_.size must be(Some(bytes.length))) Stream .bracket(IO(Files.createTempFile("test-file", ".bin"))) { p => IO(p.toFile.delete).void } .flatMap { p => Stream.emits(bytes).covary[IO].through(fs2.io.file.writeAll(p, blocker)).drain ++ Stream.eval(store.put(p, Path("path/to/file.txt"), blocker)) } .compile .drain .unsafeRunSync() store.buf.toArray must be(bytes) } it should "download a file to a nio path" in { val bytes = "hello".getBytes(Charset.forName("utf-8")) val store = DummyStore(_ => succeed) val path = Path("path/to/file.txt") Stream.emits(bytes).through(store.put(path)).compile.drain.unsafeRunSync() Stream .bracket(IO(Files.createTempFile("test-file", ".bin")))(p => IO(p.toFile.delete).void) .flatMap { nioPath => Stream.eval(store.get(path, nioPath, blocker)) >> Stream.eval { IO { Files.readAllBytes(nioPath) mustBe bytes } } } .compile .drain .unsafeRunSync() } } final case class DummyStore(check: Path => Assertion) extends Store[IO] { val buf = new ArrayBuffer[Byte]() override def put(path: Path, overwrite: Boolean): Pipe[IO, Byte, Unit] = { check(path) in => { buf.appendAll(in.compile.toVector.unsafeRunSync()) Stream.emit(()) } } override def get(path: Path, chunkSize: Int): Stream[IO, Byte] = Stream.emits(buf) override def list(path: Path, recursive: Boolean = false): Stream[IO, Path] = ??? override def move(src: Path, dst: Path): IO[Unit] = ??? override def copy(src: Path, dst: Path): IO[Unit] = ??? override def remove(path: Path): IO[Unit] = ??? override def putRotate(computePath: IO[Path], limit: Long): Pipe[IO, Byte, Unit] = ??? }
Example 104
Source File: WindowsPluginFrontendSpec.scala From protoc-bridge with Apache License 2.0 | 5 votes |
package protocbridge.frontend import java.io.ByteArrayInputStream import protocbridge.ProtocCodeGenerator import scala.sys.process.ProcessLogger import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class WindowsPluginFrontendSpec extends AnyFlatSpec with Matchers { if (PluginFrontend.isWindows) { it must "execute a program that forwards input and output to given stream" in { val toSend = "ping" val toReceive = "pong" val fakeGenerator = new ProtocCodeGenerator { override def run(request: Array[Byte]): Array[Byte] = { request mustBe toSend.getBytes toReceive.getBytes } } val (path, state) = WindowsPluginFrontend.prepare(fakeGenerator) val actualOutput = scala.collection.mutable.Buffer.empty[String] val process = sys.process .Process(path.toAbsolutePath.toString) .#<(new ByteArrayInputStream(toSend.getBytes)) .run(ProcessLogger(o => actualOutput.append(o))) process.exitValue() actualOutput.mkString mustBe toReceive WindowsPluginFrontend.cleanup(state) } } }
Example 105
Source File: PluginFrontendSpec.scala From protoc-bridge with Apache License 2.0 | 5 votes |
package protocbridge.frontend import java.io.ByteArrayInputStream import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class PluginFrontendSpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { def expected(error: String) = CodeGeneratorResponse.newBuilder().setError(error).build() def actual(error: String) = CodeGeneratorResponse.parseFrom( PluginFrontend.createCodeGeneratorResponseWithError(error) ) "createCodeGeneratorResponseWithError" should "create valid objects" in { actual("") must be(expected("")) actual("foo") must be(expected("foo")) actual("\u2035") must be(expected("\u2035")) actual("a" * 128) must be(expected("a" * 128)) actual("a" * 256) must be(expected("a" * 256)) actual("\u3714\u3715" * 256) must be(expected("\u3714\u3715" * 256)) actual("abc" * 1000) must be(expected("abc" * 1000)) forAll(MinSuccessful(1000)) { s: String => actual(s) must be(expected(s)) } } "readInputStreamToByteArray" should "read the input stream to a byte array" in { def readInput(bs: Array[Byte]) = PluginFrontend.readInputStreamToByteArray(new ByteArrayInputStream(bs)) readInput(Array.empty) must be(Array()) readInput(Array[Byte](1, 2, 3, 4)) must be(Array(1, 2, 3, 4)) val special = Array.tabulate[Byte](10000) { n => (n % 37).toByte } readInput(special) must be(special) } }
Example 106
Source File: CodeGenAppSpec.scala From protoc-bridge with Apache License 2.0 | 5 votes |
package protocbridge.codegen import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse import protocbridge.ProtocBridge import java.io.File import java.nio.file.Files import protocbridge.JvmGenerator import protocbridge.TestUtils.readLines import scala.annotation.nowarn @nowarn("msg=(trait|class|object) CodeGen.*is deprecated") object TestCodeGenApp extends CodeGenApp { def process(request: CodeGenRequest): CodeGenResponse = { if (request.filesToGenerate.exists(_.getName().contains("error"))) CodeGenResponse.fail("Error!") else CodeGenResponse.succeed( Seq( CodeGeneratorResponse.File .newBuilder() .setName("out.out") .setContent("out!") .build() ) ) } } class CodeGenAppSpec extends AnyFlatSpec with Matchers { "protocbridge.TestCodeGenApp" should "succeed by default" in { val protoFile = new File(getClass.getResource("/test.proto").getFile).getAbsolutePath val protoDir = new File(getClass.getResource("/").getFile).getAbsolutePath val cgOutDir = Files.createTempDirectory("testout_cg").toFile() ProtocBridge.run( args => com.github.os72.protocjar.Protoc.runProtoc(args.toArray), Seq( JvmGenerator("cg", TestCodeGenApp) -> cgOutDir ), Seq(protoFile, "-I", protoDir) ) must be(0) readLines(new File(cgOutDir, "out.out")) must be(Seq("out!")) } it should "fail on error.proto" in { val protoFile = new File(getClass.getResource("/error.proto").getFile).getAbsolutePath val protoDir = new File(getClass.getResource("/").getFile).getAbsolutePath val cgOutDir = Files.createTempDirectory("testout_cg").toFile() ProtocBridge.run( args => com.github.os72.protocjar.Protoc.runProtoc(args.toArray), Seq( JvmGenerator("cg", TestCodeGenApp) -> cgOutDir ), Seq(protoFile, "-I", protoDir) ) must be(1) } }
Example 107
Source File: TargetSpec.scala From protoc-bridge with Apache License 2.0 | 5 votes |
package protocbridge import org.scalatest._ import java.io.File import Target.builtin import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class TargetSpec extends AnyFlatSpec with Matchers { val TmpPath = new File("/tmp") object FoobarGen extends ProtocCodeGenerator { override def run(request: Array[Byte]): Array[Byte] = new Array[Byte](0) } def foobarGen(opt1: String, opt2: String): (Generator, Seq[String]) = (JvmGenerator("fff", FoobarGen), Seq(opt1, opt2)) "target" should "lift string to BuiltinGeneratorCall" in { Target(builtin("java"), TmpPath) must matchPattern { case Target(BuiltinGenerator("java", Nil), TmpPath, Nil) => } (builtin("java") -> TmpPath: Target) must matchPattern { case Target(BuiltinGenerator("java", Nil), TmpPath, Nil) => } } it should "allow passing options to string generator" in { Target(builtin("java", Seq("opt1", "opt2")), TmpPath) must matchPattern { case Target( BuiltinGenerator("java", Nil), TmpPath, Seq("opt1", "opt2") ) => } (builtin( "java", Seq("opt1", "opt2") ) -> TmpPath: Target) must matchPattern { case Target( BuiltinGenerator("java", Nil), TmpPath, Seq("opt1", "opt2") ) => } } it should "allow predefined builtin constants" in { Target(gens.java, TmpPath) must matchPattern { case Target( BuiltinGenerator( "java", List(Artifact("com.google.protobuf", "protobuf-java", _, false, _, _)) ), TmpPath, Nil ) => } } it should "allow passing options to predefined plugins" in { Target(gens.java, TmpPath, Seq("ffx")) must matchPattern { case Target( BuiltinGenerator( "java", List(Artifact("com.google.protobuf", "protobuf-java", _, false, _, _)) ), TmpPath, Seq("ffx") ) => } ((gens.java, Seq("ffx")) -> TmpPath: Target) must matchPattern { case Target( BuiltinGenerator( "java", List(Artifact("com.google.protobuf", "protobuf-java", _, false, _, _)) ), TmpPath, Seq("ffx") ) => } } it should "allow using the options syntax" in { Target(foobarGen("xyz", "wf"), TmpPath) must matchPattern { case Target(JvmGenerator("fff", FoobarGen), TmpPath, Seq("xyz", "wf")) => } (foobarGen("xyz", "wf") -> TmpPath: Target) must matchPattern { case Target(JvmGenerator("fff", FoobarGen), TmpPath, Seq("xyz", "wf")) => } } }
Example 108
Source File: CodeGenAppSpec.scala From protoc-bridge with Apache License 2.0 | 5 votes |
package protocgen import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse import protocbridge.ProtocBridge import java.io.File import java.nio.file.Files import protocbridge.JvmGenerator import protocbridge.TestUtils.readLines object TestCodeGenApp extends CodeGenApp { def process(request: CodeGenRequest): CodeGenResponse = { if (request.filesToGenerate.exists(_.getName().contains("error"))) CodeGenResponse.fail("Error!") else CodeGenResponse.succeed( Seq( CodeGeneratorResponse.File .newBuilder() .setName("out.out") .setContent("out!") .build() ) ) } } class CodeGenAppSpec extends AnyFlatSpec with Matchers { "protocgen.TestCodeGenApp" should "succeed by default" in { val protoFile = new File(getClass.getResource("/test.proto").getFile).getAbsolutePath val protoDir = new File(getClass.getResource("/").getFile).getAbsolutePath val cgOutDir = Files.createTempDirectory("testout_cg").toFile() ProtocBridge.run( args => com.github.os72.protocjar.Protoc.runProtoc(args.toArray), Seq( JvmGenerator("cg", TestCodeGenApp) -> cgOutDir ), Seq(protoFile, "-I", protoDir) ) must be(0) readLines(new File(cgOutDir, "out.out")) must be(Seq("out!")) } "protocgen.TestCodeGenApp" should "fail on error.proto" in { val protoFile = new File(getClass.getResource("/error.proto").getFile).getAbsolutePath val protoDir = new File(getClass.getResource("/").getFile).getAbsolutePath val cgOutDir = Files.createTempDirectory("testout_cg").toFile() ProtocBridge.run( args => com.github.os72.protocjar.Protoc.runProtoc(args.toArray), Seq( JvmGenerator("cg", TestCodeGenApp) -> cgOutDir ), Seq(protoFile, "-I", protoDir) ) must be(1) } }
Example 109
Source File: UDPSenderSpec.scala From censorinus with MIT License | 5 votes |
package github.gphat.censorinus import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import java.nio.ByteBuffer import java.nio.channels.UnresolvedAddressException class UDPSenderSpec extends AnyFlatSpec with Matchers { "UDPSender" should "emit errors" in { // Guessing this port won't be used? :) val u = new UDPSender(hostname = "127.0.0.1789", port = 8126, allowExceptions = true) an [UnresolvedAddressException] should be thrownBy u.send(ByteBuffer.wrap("abc".getBytes("utf-8"))) } it should "swallow errors" in { // Guessing this port won't be used? :) val u = new UDPSender(hostname = "127.0.0.1789", port = 8126, allowExceptions = false) u.send(ByteBuffer.wrap("abc".getBytes("utf-8"))) } }
Example 110
Source File: SynchronySpec.scala From censorinus with MIT License | 5 votes |
package github.gphat.censorinus import org.scalatest._ import org.scalatest.concurrent.Eventually import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import github.gphat.censorinus.statsd.Encoder class SynchronySpec extends AnyFlatSpec with Matchers with Eventually { "Client" should "deal with gauges" in { val s = new TestSender(1) val client = new Client(encoder = Encoder, sender = s) // Queue up a message in the sender to ensure we can't publish yet. s.buffer.offer("BOO!") s.buffer.size should be (1) client.enqueue(GaugeMetric(name = "foobar", value = 1.0)) s.buffer.size should be (1) // New metric won't be there yet s.awaitMessage() should be ("BOO!") s.awaitMessage() should include ("foobar") client.shutdown } it should "be synchronous" in { val s = new TestSender() val client = new Client(encoder = Encoder, sender = s, asynchronous = false) client.enqueue(GaugeMetric(name = "foobar", value = 1.0)) val m = s.buffer.poll() m should include ("foobar") client.shutdown } }
Example 111
Source File: StatsDClientSpec.scala From censorinus with MIT License | 5 votes |
package github.gphat.censorinus import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class StatsDClientSpec extends AnyFlatSpec with Matchers with BeforeAndAfter { var client: StatsDClient = null before { client = new StatsDClient(prefix = "poop") // SOOOOOOOOoooooo hacky, but this will ensure the worker thread doesn't // steal our metrics before we can read them. client.shutdown } "StatsDClient" should "deal with gauges" in { client.gauge("foobar", 1.0) val m = client.queue.poll m shouldBe a [GaugeMetric] val g = m.asInstanceOf[GaugeMetric] g.name should be ("poop.foobar") g.value should be (1.00000000) } it should "deal with counters" in { client.counter("foobar", 1.0) val m = client.queue.poll m shouldBe a [CounterMetric] val c = m.asInstanceOf[CounterMetric] c.name should be ("poop.foobar") c.value should be (1.0) } it should "deal with increments" in { client.increment("foobar") val m = client.queue.poll m shouldBe a [CounterMetric] val c = m.asInstanceOf[CounterMetric] c.name should be ("poop.foobar") c.value should be (1.0) } it should "deal with decrements" in { client.decrement("foobar") val m = client.queue.poll m shouldBe a [CounterMetric] val c = m.asInstanceOf[CounterMetric] c.name should be ("poop.foobar") c.value should be (-1.0) } it should "deal with meters" in { client.meter("foobar", 1.0) val m = client.queue.poll m shouldBe a [MeterMetric] val mm = m.asInstanceOf[MeterMetric] mm.name should be ("poop.foobar") mm.value should be (1.0) } it should "deal with sets" in { client.set("foobar", "fart") val m = client.queue.poll m shouldBe a [SetMetric] val s = m.asInstanceOf[SetMetric] s.name should be ("poop.foobar") s.value should be ("fart") } it should "deal with big doubles" in { client.meter("foobar", 1.01010101010101010101) val m = client.queue.poll m shouldBe a [MeterMetric] val mm = m.asInstanceOf[MeterMetric] mm.name should be ("poop.foobar") mm.value should be (1.01010101010101010101) } }
Example 112
Source File: SamplingSpec.scala From censorinus with MIT License | 5 votes |
package github.gphat.censorinus import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import github.gphat.censorinus.statsd.Encoder class SamplingSpec extends AnyFlatSpec with Matchers { val s = new TestSender() "Client" should "sample things" in { val client = new Client(encoder = Encoder, sender = s, asynchronous = false) client.enqueue(CounterMetric(name = "foobar", value = 1.0), sampleRate = 0.0) s.buffer.size should be (0) client.shutdown } it should "bypass the sampler and send it anyway" in { val client = new Client(encoder = Encoder, sender = s, asynchronous = false) client.enqueue(CounterMetric(name = "foobar", value = 1.0), sampleRate = 0.0, bypassSampler = true) s.buffer.size should be (1) client.shutdown } "DogStatsD Client" should "sample things" in { val client = new DogStatsDClient(prefix = "poop", defaultSampleRate = 0.0) client.counter("foobar", value = 1.0) client.decrement("foobar") client.increment("foobar") client.gauge("foobar", value = 1.0) client.histogram("foobar", value = 1.0) client.set("foobar", value = "fart") client.timer("foobar", milliseconds = 1.0) client.queue.size should be (0) client.shutdown } "StatsD Client" should "sample things" in { val client = new StatsDClient(prefix = "poop", defaultSampleRate = 0.0) client.counter("foobar", value = 1.0) client.decrement("foobar") client.increment("foobar") client.gauge("foobar", value = 1.0) client.meter("foobar", value = 1.0) client.set("foobar", value = "fart") client.timer("foobar", milliseconds = 1.0) client.queue.size should be (0) client.shutdown } }
Example 113
Source File: StatsDEncoderSpec.scala From censorinus with MIT License | 5 votes |
package github.gphat.censorinus import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import github.gphat.censorinus.statsd.Encoder class StatsDEncoderSpec extends AnyFlatSpec with Matchers { "StatsD Encoder" should "encode gauges" in { val g = GaugeMetric(name = "foobar", value = 1.0) Encoder.encode(g).get should be ("foobar:1|g") } it should "encode counters" in { val m = CounterMetric(name = "foobar", value = 1.0) Encoder.encode(m).get should be ("foobar:1|c") // Counter with optional sample rate val m1 = CounterMetric(name = "foobar", value = 1.0, sampleRate = 0.5) Encoder.encode(m1).get should be ("foobar:1|c|@0.5") } it should "encode timers" in { val m = TimerMetric(name = "foobar", value = 1.0) Encoder.encode(m).get should be ("foobar:1|ms") } it should "encode meters" in { val m = MeterMetric(name = "foobar", value = 1.0) Encoder.encode(m).get should be ("foobar:1|m") } it should "encode sets" in { val m = SetMetric(name = "foobar", value = "fart") Encoder.encode(m).get should be ("foobar:fart|s") } it should "encode counters with sample rate" in { val m = CounterMetric(name = "foobar", value = 1.0, sampleRate = 0.5) Encoder.encode(m).get should be ("foobar:1|c|@0.5") } }
Example 114
Source File: ServiceRegistryInteropSpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.registry.impl import java.net.URI import java.util.Collections import java.util.Optional import akka.actor.ActorSystem import akka.testkit.TestKit import akka.util.ByteString import com.lightbend.lagom.devmode.internal.scaladsl.registry.RegisteredService import com.lightbend.lagom.devmode.internal.scaladsl.registry.ServiceRegistryService import com.lightbend.lagom.internal.javadsl.registry.{ RegisteredService => jRegisteredService } import com.lightbend.lagom.internal.javadsl.registry.{ ServiceRegistryService => jServiceRegistryService } import com.lightbend.lagom.devmode.internal.scaladsl.registry.{ RegisteredService => sRegisteredService } import com.lightbend.lagom.devmode.internal.scaladsl.registry.{ ServiceRegistryService => sServiceRegistryService } import com.lightbend.lagom.javadsl.api.ServiceAcl import com.lightbend.lagom.javadsl.api.deser.MessageSerializer import com.lightbend.lagom.javadsl.api.deser.StrictMessageSerializer import com.lightbend.lagom.javadsl.api.transport.MessageProtocol import com.lightbend.lagom.javadsl.api.transport.Method import com.lightbend.lagom.javadsl.jackson.JacksonSerializerFactory import org.scalatest.BeforeAndAfterAll import org.scalatest.concurrent.Futures import play.api.libs.json.Format import play.api.libs.json.Json import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ServiceRegistryInteropSpec extends AnyFlatSpec with Matchers with Futures with BeforeAndAfterAll { val system = ActorSystem() val jacksonSerializerFactory = new JacksonSerializerFactory(system) protected override def afterAll(): Unit = { TestKit.shutdownActorSystem(actorSystem = system, verifySystemShutdown = true) } behavior.of("ServiceRegistry serializers") it should "should interop between java and scala (RegisteredService)" in { val msg = jRegisteredService.of("inventory", URI.create("https://localhost:123/asdf"), Optional.of("https")) roundTrip(msg) should be(msg) } it should "should interop between java and scala when optional fields are empty (RegisteredService)" in { val msg = jRegisteredService.of("inventory", URI.create("https://localhost:123/asdf"), Optional.empty[String]) roundTrip(msg) should be(msg) } it should "should interop between java and scala (ServiceRegistryService)" in { val msg = jServiceRegistryService.of( URI.create("https://localhost:123/asdf"), Collections.singletonList(ServiceAcl.methodAndPath(Method.GET, "/items")) ) roundTrip(msg) should be(msg) } it should "should interop between java and scala when optional fields are empty (ServiceRegistryService)" in { val msg = jServiceRegistryService.of(URI.create("https://localhost:123/asdf"), Collections.emptyList[ServiceAcl]) roundTrip(msg) should be(msg) } private def roundTrip(input: jServiceRegistryService): jServiceRegistryService = { roundTrip( input, jacksonSerializerFactory.messageSerializerFor[jServiceRegistryService](classOf[jServiceRegistryService]), com.lightbend.lagom.scaladsl.playjson.JsonSerializer[ServiceRegistryService].format )(sServiceRegistryService.format) } private def roundTrip(input: jRegisteredService): jRegisteredService = { roundTrip( input, jacksonSerializerFactory.messageSerializerFor[jRegisteredService](classOf[jRegisteredService]), com.lightbend.lagom.scaladsl.playjson.JsonSerializer[RegisteredService].format )(sRegisteredService.format) } private def roundTrip[J, S]( input: J, jacksonSerializer: StrictMessageSerializer[J], playJsonFormatter: Format[S] )(implicit format: Format[S]): J = { val byteString: ByteString = jacksonSerializer.serializerForRequest().serialize(input) val scalaValue: S = playJsonFormatter.reads(Json.parse(byteString.toArray)).get val str: String = playJsonFormatter.writes(scalaValue).toString() val jacksonDeserializer: MessageSerializer.NegotiatedDeserializer[J, ByteString] = jacksonSerializer.deserializer( new MessageProtocol(Optional.of("application/json"), Optional.empty[String], Optional.empty[String]) ) jacksonDeserializer.deserialize(ByteString(str)) } }
Example 115
Source File: InternalRouterSpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.registry.impl import java.net.URI import java.util import java.util.Collections import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistryService import com.lightbend.lagom.javadsl.api.ServiceAcl import com.lightbend.lagom.javadsl.api.transport.Method import com.lightbend.lagom.registry.impl.ServiceRegistryActor.Found import com.lightbend.lagom.registry.impl.ServiceRegistryActor.Route import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class InternalRouterSpec extends AnyFlatSpec with Matchers { behavior.of("InternalRouter") it should "find the appropriate URI given the portName" in { val httpUri = new URI("http://localhost.com/pathABC") val httpsUri = new URI("https://localhost.com:123/pathABC") val simpleName = "my-service" val acl = ServiceAcl.methodAndPath(Method.GET, "/pathABC") val srs = ServiceRegistryService.of(util.Arrays.asList(httpUri, httpsUri), Collections.singletonList(acl)) val registry = new InternalRegistry(Map.empty) registry.register(simpleName, srs) val router = new InternalRouter router.rebuild(registry) router.routeFor(Route("GET", "/pathABC", None)) should be(Found(httpUri)) router.routeFor(Route("GET", "/pathABC", Some("http"))) should be(Found(httpUri)) router.routeFor(Route("GET", "/pathABC", Some("https"))) should be(Found(httpsUri)) } }
Example 116
Source File: LagomClientFactorySpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.javadsl.client.integration import akka.actor.Actor import akka.actor.ActorRef import akka.actor.ActorSystem import akka.actor.Props import com.typesafe.config.ConfigFactory import org.scalatest.concurrent.ScalaFutures import org.scalatest.BeforeAndAfterEach import scala.concurrent.duration._ import scala.concurrent.Await import akka.pattern._ import akka.stream.SystemMaterializer import akka.util.Timeout import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class LagomClientFactorySpec extends AnyFlatSpec with Matchers with BeforeAndAfterEach with ScalaFutures { private var system: ActorSystem = _ private var echoActor: ActorRef = _ implicit val timeout = Timeout(5.seconds) "LagomClientFactory" should "when using a unmanaged actor system, shoudl not terminate it upon closing" in { // check that actor system is operational (echoActor ? "hey").mapTo[String].futureValue shouldBe "hey" LagomClientFactory // create a factory by passing the existing ActorSystem .create( "test", this.getClass.getClassLoader, system, SystemMaterializer(system).materializer ) // closing the factory should not close the existing ActorSystem .close() // check that actor system is still operational (echoActor ? "hey").mapTo[String].futureValue shouldBe "hey" } protected override def beforeEach(): Unit = { system = ActorSystem("test", ConfigFactory.load()) echoActor = system.actorOf(Props(new EchoActor), "echo") } class EchoActor extends Actor { override def receive: Receive = { case s: String => sender() ! s } } protected override def afterEach(): Unit = { Await.ready(system.terminate(), 5.seconds) } }
Example 117
Source File: ScaladslServiceResolverSpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.internal.scaladsl.client import akka.NotUsed import com.lightbend.lagom.scaladsl.api.deser.DefaultExceptionSerializer import com.lightbend.lagom.scaladsl.api.CircuitBreaker import com.lightbend.lagom.scaladsl.api.Descriptor import com.lightbend.lagom.scaladsl.api.Service import com.lightbend.lagom.scaladsl.api.ServiceCall import com.lightbend.lagom.scaladsl.client.TestServiceClient import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ScaladslServiceResolverSpec extends AnyFlatSpec with Matchers { behavior.of("ScaladslServiceResolver") it should "setup circuit-breakers for all method calls using default values when nothing is specified" in { assertCircuitBreaking(TestServiceClient.implement[Unspecified], CircuitBreaker.PerNode) } it should "setup circuit-breakers for all method calls using descriptor value when only descriptor's CB is specified" in { assertCircuitBreaking(TestServiceClient.implement[General], CircuitBreaker.identifiedBy("general-cb")) } it should "setup circuit-breakers with each specific CB when each call has a CB described" in { assertCircuitBreaking(TestServiceClient.implement[PerCall], CircuitBreaker.identifiedBy("one-cb")) } // -------------------------------------------------------------------------------------------- private def assertCircuitBreaking(service: Service, expected: CircuitBreaker) = { val resolved = new ScaladslServiceResolver(DefaultExceptionSerializer.Unresolved).resolve(service.descriptor) resolved.calls.head.circuitBreaker should be(Some(expected)) } trait Unspecified extends Service { import Service._ def one: ServiceCall[NotUsed, NotUsed] override def descriptor: Descriptor = { named("Unspecified") .withCalls( namedCall("one", one) ) } } trait General extends Service { import Service._ def one: ServiceCall[NotUsed, NotUsed] override def descriptor: Descriptor = { named("Unspecified") .withCalls( namedCall("one", one) ) .withCircuitBreaker(CircuitBreaker.identifiedBy("general-cb")) } } trait PerCall extends Service { import Service._ def one: ServiceCall[NotUsed, NotUsed] override def descriptor: Descriptor = { named("Unspecified") .withCalls( namedCall("one", one) .withCircuitBreaker(CircuitBreaker.identifiedBy("one-cb")) // overwrites default. ) .withCircuitBreaker(CircuitBreaker.identifiedBy("general-cb")) } } }
Example 118
Source File: ScaladslKafkaSubscriberSpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.internal.scaladsl.broker.kafka import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ScaladslKafkaSubscriberSpec extends AnyFlatSpec with Matchers { behavior.of("ScaladslKafkaSubscriber") it should "create a new subscriber with updated groupId" in { val subscriber = new ScaladslKafkaSubscriber(null, null, ScaladslKafkaSubscriber.GroupId("old"), null, null, null, null)( null, null ) subscriber.withGroupId("newGID") should not be subscriber } }
Example 119
Source File: NewTypeMacrosJVMTest.scala From scala-newtype with Apache License 2.0 | 5 votes |
package io.estatico.newtype.macros import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class NewTypeMacrosJVMTest extends AnyFlatSpec with Matchers { behavior of "@newsubtype" it should "not box primitives" in { // Introspect the runtime type returned by the `apply` method def ctorReturnType(o: Any) = scala.Predef.genericArrayOps(o.getClass.getMethods).find(_.getName == "apply").get.getReturnType // newtypes will box primitive values. @newtype case class BoxedInt(private val x: Int) ctorReturnType(BoxedInt) shouldBe scala.Predef.classOf[Object] // newsubtypes will NOT box primitive values. @newsubtype case class UnboxedInt(private val x: Int) ctorReturnType(UnboxedInt) shouldBe scala.Predef.classOf[Int] } }
Example 120
Source File: FieldReaderSpec.scala From protobuf-generic with Apache License 2.0 | 5 votes |
package me.lyh.protobuf.generic.test import com.google.protobuf.{ByteString, Message} import me.lyh.protobuf.generic._ import me.lyh.protobuf.generic.proto3.Schemas._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.reflect.ClassTag class FieldReaderSpec extends AnyFlatSpec with Matchers { def read[T <: Message: ClassTag](record: T, fields: List[String], expected: List[Any]): Unit = { val schema = SerializableUtils.ensureSerializable(Schema.of[T]) val reader = SerializableUtils.ensureSerializable(FieldReader.of(schema, fields)) val actual = reader.read(record.toByteArray) actual.toList shouldBe expected } val fields: List[String] = List( "double_field", "float_field", "int32_field", "int64_field", "uint32_field", "uint64_field", "sint32_field", "sint64_field", "fixed32_field", "fixed64_field", "sfixed32_field", "sfixed64_field", "bool_field", "string_field", "bytes_field", "color_field" ) val expected: List[Any] = List( math.Pi, math.E.toFloat, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, true, "hello", ByteString.copyFromUtf8("world"), "WHITE" ) "FieldReader" should "read optional" in { read[Optional](Records.optional, fields, expected) read[Optional]( Records.optionalEmpty, fields, List(0.0, 0.0f, 0, 0L, 0, 0L, 0, 0L, 0, 0L, 0, 0L, false, "", ByteString.EMPTY, "BLACK") ) } it should "read oneofs" in { (Records.oneOfs.drop(1) zip (fields zip expected)).foreach { case (r, (f, e)) => read[OneOf](r, List(f), List(e)) } } it should "read nested" in { val fields = List( "mixed_field_o.double_field_o", "mixed_field_o.string_field_o", "mixed_field_o.bytes_field_o", "mixed_field_o.color_field_o" ) val expected = List(math.Pi, "hello", ByteString.copyFromUtf8("world"), "WHITE") read[Nested](Records.nested, fields, expected) val expectedEmpty = List(0.0, "", ByteString.EMPTY, "BLACK") read[Nested](Records.nestedEmpty, fields, expectedEmpty) } }
Example 121
Source File: ProtobufGenericSpec.scala From protobuf-generic with Apache License 2.0 | 5 votes |
package me.lyh.protobuf.generic.test import com.google.protobuf.Message import com.google.protobuf.util.JsonFormat import me.lyh.protobuf.generic._ import me.lyh.protobuf.generic.proto3.Schemas._ import scala.reflect.ClassTag import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ProtobufGenericSpec extends AnyFlatSpec with Matchers { private val printer = JsonFormat.printer().preservingProtoFieldNames() private val parser = JsonFormat.parser() def roundTrip[T <: Message: ClassTag](record: T): Unit = { val schema = SerializableUtils.ensureSerializable(Schema.of[T]) val schemaCopy = Schema.fromJson(schema.toJson) schemaCopy shouldBe schema val reader = SerializableUtils.ensureSerializable(GenericReader.of(schema)) val writer = SerializableUtils.ensureSerializable(GenericWriter.of(schema)) val jsonRecord = reader.read(record.toByteArray).toJson val bytes = writer.write(GenericRecord.fromJson(jsonRecord)) val recordCopy = ProtobufType[T].parseFrom(bytes) recordCopy shouldBe record compatibleWithJsonFormat(record) } def compatibleWithJsonFormat[T <: Message: ClassTag](record: T): Unit = { val protoType = ProtobufType[T] val schema = Schema.of[T] val reader = GenericReader.of(schema) val writer = GenericWriter.of(schema) val json1 = reader.read(record.toByteArray).toJson val record1 = { val builder = protoType.newBuilder() parser.merge(json1, builder) builder.build().asInstanceOf[T] } val json2 = printer.print(record) val record2 = protoType.parseFrom(writer.write(GenericRecord.fromJson(json2))) record1 shouldBe record2 } def test[T <: Message: ClassTag](record: T): Unit = { roundTrip(record) compatibleWithJsonFormat(record) } "ProtobufGeneric" should "round trip optional" in { test[Optional](Records.optional) test[Optional](Records.optionalEmpty) } it should "round trip repeated" in { test[Repeated](Records.repeated) test[Repeated](Records.repeatedEmpty) test[RepeatedPacked](Records.repeatedPacked) test[RepeatedUnpacked](Records.repeatedUnpacked) } it should "round trip oneofs" in { Records.oneOfs.foreach(test[OneOf]) } it should "round trip mixed" in { test[Mixed](Records.mixed) test[Mixed](Records.mixedEmpty) } it should "round trip nested" in { test[Nested](Records.nested) test[Nested](Records.nestedEmpty) } it should "round trip with custom options" in { test[CustomOptionMessage](Records.customOptionMessage) test[CustomOptionMessage](Records.customOptionMessageEmpty) } }
Example 122
Source File: ProtobufGenericSpec.scala From protobuf-generic with Apache License 2.0 | 5 votes |
package me.lyh.protobuf.generic.test import java.io.ByteArrayInputStream import java.nio.ByteBuffer import com.google.protobuf.{ByteString, Message} import me.lyh.protobuf.generic._ import me.lyh.protobuf.generic.proto2.Schemas._ import scala.reflect.ClassTag import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ProtobufGenericSpec extends AnyFlatSpec with Matchers { def roundTrip[T <: Message: ClassTag](record: T): Unit = { val schema = SerializableUtils.ensureSerializable(Schema.of[T]) val schemaCopy = Schema.fromJson(schema.toJson) schemaCopy shouldBe schema val reader = SerializableUtils.ensureSerializable(GenericReader.of(schema)) val writer = SerializableUtils.ensureSerializable(GenericWriter.of(schema)) val jsonRecord = reader.read(record.toByteArray).toJson jsonRecord shouldBe reader.read(ByteBuffer.wrap(record.toByteArray)).toJson jsonRecord shouldBe reader.read(new ByteArrayInputStream(record.toByteArray)).toJson val bytes = writer.write(GenericRecord.fromJson(jsonRecord)) val recordCopy = ProtobufType[T].parseFrom(bytes) recordCopy shouldBe record } "ProtobufGeneric" should "round trip required" in { roundTrip[Required](Records.required) } it should "round trip optional" in { roundTrip[Optional](Records.optional) roundTrip[Optional](Records.optionalEmpty) } it should "round trip repeated" in { roundTrip[Repeated](Records.repeated) roundTrip[Repeated](Records.repeatedEmpty) roundTrip[RepeatedPacked](Records.repeatedPacked) roundTrip[RepeatedUnpacked](Records.repeatedUnpacked) } it should "round trip oneofs" in { Records.oneOfs.foreach(roundTrip[OneOf]) } it should "round trip mixed" in { roundTrip[Mixed](Records.mixed) roundTrip[Mixed](Records.mixedEmpty) } it should "round trip nested" in { roundTrip[Nested](Records.nested) roundTrip[Nested](Records.nestedEmpty) } it should "round trip with custom options" in { roundTrip[CustomOptionMessage](Records.customOptionMessage) roundTrip[CustomOptionMessage](Records.customOptionMessageEmpty) } it should "round trip with custom defaults" in { roundTrip[CustomDefaults](CustomDefaults.getDefaultInstance) } it should "populate default values" in { val schema = Schema.of[CustomDefaults] val record = GenericReader.of(schema).read(CustomDefaults.getDefaultInstance.toByteArray) record.get("double_field") shouldBe 101.0 record.get("float_field") shouldBe 102.0f record.get("int32_field") shouldBe 103 record.get("int64_field") shouldBe 104L record.get("uint32_field") shouldBe 105 record.get("uint64_field") shouldBe 106L record.get("sint32_field") shouldBe 107 record.get("sint64_field") shouldBe 108L record.get("fixed32_field") shouldBe 109 record.get("fixed64_field") shouldBe 110L record.get("sfixed32_field") shouldBe 111 record.get("sfixed64_field") shouldBe 112L record.get("bool_field") shouldBe true record.get("string_field") shouldBe "hello" record.get("bytes_field") shouldBe Base64.encode(ByteString.copyFromUtf8("world").toByteArray) record.get("color_field") shouldBe "GREEN" } }
Example 123
Source File: ProtobufTypeSpec.scala From protobuf-generic with Apache License 2.0 | 5 votes |
package me.lyh.protobuf.generic.test import java.io.ByteArrayInputStream import com.google.protobuf.CodedInputStream import me.lyh.protobuf.generic._ import me.lyh.protobuf.generic.proto2.Schemas._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ProtobufTypeSpec extends AnyFlatSpec with Matchers { private val pt = ProtobufType[Optional] private val record = Records.optional "ProtobufType.descriptor" should "work" in { pt.descriptor shouldBe Optional.getDescriptor } "ProtobufType.newBuilder" should "work" in { pt.newBuilder().build() shouldBe Optional.newBuilder().build() } "ProtobufType.parseFrom" should "support byte array" in { pt.parseFrom(record.toByteArray) shouldBe record } it should "support ByteString" in { pt.parseFrom(record.toByteString) shouldBe record } it should "support InputStream" in { pt.parseFrom(new ByteArrayInputStream(record.toByteArray)) shouldBe record } it should "support CodedInputStream" in { pt.parseFrom(CodedInputStream.newInstance(record.toByteArray)) shouldBe record } }
Example 124
Source File: Base64Spec.scala From protobuf-generic with Apache License 2.0 | 5 votes |
package me.lyh.protobuf.generic import org.scalatest._ import scala.util.Random import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class Base64Spec extends AnyFlatSpec with Matchers { private def nextBytes: Array[Byte] = { val bytes = new Array[Byte](Random.nextInt(100) + 1) Random.nextBytes(bytes) bytes } "Base64" should "round trip bytes" in { val data = Seq.fill(100)(nextBytes) data.map(d => Base64.decode(Base64.encode(d)).toSeq) shouldBe data.map(_.toSeq) } }
Example 125
Source File: ResourcesSpec.scala From sbt-kubeyml with MIT License | 5 votes |
package kubeyml.deployment import scala.util.Random import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ResourcesSpec extends AnyFlatSpec with Matchers { "from cores" must "give multiples of 1000" in { val aCoresNumber: Short = (Random.nextInt(10) + 1).toShort Cpu.fromCores(aCoresNumber) shouldBe Cpu(aCoresNumber*1000) } "resources" can "be updated individually" in { val limit = Resource(Cpu.fromCores(1), Memory(512)) val request = Resource(Cpu(500), Memory(128)) val resources = Resources(request, limit) resources.copy( requests = limit.copy(memory = Memory(1024)), limits = limit.copy(memory = Memory(2048)) ) } }
Example 126
Source File: sbt-test-flatspec.scala From scala-course with GNU General Public License v3.0 | 5 votes |
import org.scalatest.flatspec.AnyFlatSpec // Tests using the "FlatSpec" style... class SetSpec extends AnyFlatSpec { "An empty Set" should "have size 0" in { assert(Set.empty.size == 0) } it should "produce NoSuchElementException when head is invoked" in { assertThrows[NoSuchElementException] { Set.empty.head } } "A Gamma(3.0,4.0)" should "have mean 12.0" in { import breeze.stats.distributions.Gamma val g = Gamma(3.0,4.0) val m = g.mean assert(math.abs(m - 12.0) < 0.000001) } } // eof
Example 127
Source File: EnumeratumSupportTest.scala From tethys with Apache License 2.0 | 5 votes |
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 128
Source File: AutoReaderDerivationTest.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.derivation import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import tethys.JsonReader import tethys.commons.{Token, TokenNode} import tethys.commons.TokenNode._ import tethys.derivation.auto._ import tethys.readers.ReaderError import tethys.readers.tokens.QueueIterator class AutoReaderDerivationTest extends AnyFlatSpec with Matchers { def read[A: JsonReader](nodes: List[TokenNode]): A = { val it = QueueIterator(nodes) val res = it.readJson[A].fold(throw _, identity) it.currentToken() shouldBe Token.Empty res } behavior of "auto derivation" it should "derive readers for simple case class hierarchy" in { read[JsonTreeTestData](obj( "a" -> 1, "b" -> true, "c" -> obj( "d" -> obj( "a" -> 2 ) ) )) shouldBe JsonTreeTestData( a = 1, b = true, c = C(D(2)) ) } it should "derive reader for recursive type" in { read[RecursiveType](obj( "a" -> 1, "children" -> arr( obj( "a" -> 2, "children" -> arr() ), obj( "a" -> 3, "children" -> arr() ) ) )) shouldBe RecursiveType(1, Seq(RecursiveType(2), RecursiveType(3))) } it should "derive writer for A => B => A cycle" in { read[ComplexRecursionA](obj( "a" -> 1, "b" -> obj( "b" -> 2, "a" -> obj( "a" -> 3 ) ) )) shouldBe ComplexRecursionA(1, Some(ComplexRecursionB(2, ComplexRecursionA(3, None)))) } }
Example 129
Source File: RedundantJsonReaderTest.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.derivation import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import tethys.JsonReader import tethys.commons._ import tethys.commons.TokenNode._ import tethys.derivation.RedundantJsonReaderTest._ import tethys.derivation.builder.ReaderBuilder import tethys.derivation.semiauto._ import tethys.readers.tokens.QueueIterator object RedundantJsonReaderTest { case class RedundantClass(i: Int) case class BaseClass(r: RedundantClass) } class RedundantJsonReaderTest extends AnyFlatSpec with Matchers { def read[A: JsonReader](nodes: List[TokenNode]): A = { val it = QueueIterator(nodes) val res = it.readJson[A].fold(throw _, identity) it.currentToken() shouldBe Token.Empty res } behavior of "jsonReader" it should "not require redundant classes for generated readers" in { implicit val reader: JsonReader[BaseClass] = jsonReader[BaseClass] { describe { ReaderBuilder[BaseClass] .extract(_.r).from("intField".as[Int])(RedundantClass.apply) } } read[BaseClass](obj( "intField" -> 1 )) shouldBe BaseClass(RedundantClass(1)) } }
Example 130
Source File: DefaultReadersTest.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.readers import org.scalatest.matchers.should.Matchers.{value => _, _} import org.scalatest.flatspec.AnyFlatSpec import tethys.JsonReader import tethys.commons.{Token, TokenNode} import tethys.commons.TokenNode._ import tethys.readers.DefaultReadersTest.TestDefinition import tethys.readers.tokens._ import scala.reflect.ClassTag class DefaultReadersTest extends AnyFlatSpec { private def test[A](result: A)(implicit jsonReader: JsonReader[A], ct: ClassTag[A]): TestDefinition[A] = { TestDefinition(result, jsonReader, ct.toString()) } private def test[A](result: A, name: String)(implicit jsonReader: JsonReader[A]): TestDefinition[A] = { TestDefinition(result, jsonReader, name) } private val cases: List[(TestDefinition[_], List[TokenNode])] = List[(TestDefinition[_], List[TokenNode])]( test("1") -> value("1"), test(1) -> value(1), test(1: Short) -> value(1: Short), test(1L) -> value(1L), test(1f) -> value(1f), test(1d) -> value(1d), test(1: BigDecimal) -> value(1: BigDecimal), test(true, "true") -> value(true), test(false, "false") -> value(false), test(List(1, 2, 3)) -> arr(1, 2, 3), test(List[Int](), "Seq.empty") -> arr(), test(Map("a" -> 1, "b" -> 2)) -> obj("a" -> 1, "b" -> 2), test(Option(1), "Option.nonEmpty") -> value(1), test(Option.empty[Int], "Option.empty") -> List(NullValueNode) , test(1: java.lang.Integer) -> value(1), test(java.lang.Short.valueOf(1: Short)) -> value(1: Short), test(1L: java.lang.Long) -> value(1L), test(1f: java.lang.Float) -> value(1f), test(1d: java.lang.Double) -> value(1d), test(java.math.BigDecimal.valueOf(1)) -> value(1: BigDecimal), test(java.math.BigInteger.valueOf(1)) -> value(1: BigInt) ) behavior of "Default readers" cases.foreach { case (TestDefinition(result, jsonReader, name), nodes) => it should s"correctly read $name" in { val iterator = QueueIterator(nodes) iterator.readJson(jsonReader).fold(throw _, identity) shouldBe result iterator.currentToken() shouldBe Token.Empty } case _ => fail("oops") } } object DefaultReadersTest { case class TestDefinition[A](result: A, jsonReader: JsonReader[A], name: String) }
Example 131
Source File: SimpleJsonObjectWriterTest.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.writers import org.scalatest.matchers.should.Matchers.{value => _, _} import org.scalatest.flatspec.AnyFlatSpec import tethys.{JsonObjectWriter, JsonWriter} import tethys.commons.TokenNode._ import tethys.writers.SimpleJsonObjectWriterTest.TestData import tethys.writers.instances.SimpleJsonObjectWriter import tethys.writers.tokens.SimpleTokenWriter._ class SimpleJsonObjectWriterTest extends AnyFlatSpec { behavior of "SimpleJsonObjectWriter" it should "write correct object to TokenWriter" in { implicit val testWriter: SimpleJsonObjectWriter[TestData] = { JsonWriter.obj[TestData] .addField("a")(_.a) .addField("b")(_.b) .addField("c")(_.b.isEmpty) } TestData(1, "test").asTokenList shouldBe obj( "a" -> 1, "b" -> "test", "c" -> false ) } it should "write correct object to TokenWriter for concatenated writers" in { implicit val testWriter: JsonObjectWriter[TestData] = { JsonWriter.obj[TestData].addField("a")(_.a) .concat(JsonWriter.obj[TestData].addField("b")(_.b)) .addField("c")(_.b.isEmpty) } TestData(1, "test").asTokenList shouldBe obj( "a" -> 1, "b" -> "test", "c" -> false ) } } object SimpleJsonObjectWriterTest { case class TestData(a: Int, b: String) }
Example 132
Source File: DefaultWritersTest.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.writers import org.scalatest.matchers.should.Matchers.{value => _, _} import org.scalatest.flatspec.AnyFlatSpec import tethys.JsonWriter import tethys.commons.TokenNode import tethys.commons.TokenNode._ import tethys.writers.DefaultWritersTest.TestDefinition import tethys.writers.tokens.SimpleTokenWriter._ import scala.reflect.ClassTag class DefaultWritersTest extends AnyFlatSpec { private def test[A](value: A)(implicit jsonWriter: JsonWriter[A], ct: ClassTag[A]): TestDefinition[A] = { TestDefinition(value, jsonWriter, ct.toString()) } private def test[A](value: A, name: String)(implicit jsonWriter: JsonWriter[A]): TestDefinition[A] = { TestDefinition(value, jsonWriter, name) } private val cases: List[(TestDefinition[_], List[TokenNode])] = List[(TestDefinition[_], List[TokenNode])]( test("1") -> value("1"), test(1) -> value(1), test(1: Short) -> value(1: Short), test(1L) -> value(1L), test(1f) -> value(1f), test(1d) -> value(1d), test(1: BigDecimal) -> value(1: BigDecimal), test(1: BigInt) -> value(1: BigInt), test(true, "true") -> value(true), test(false, "false") -> value(false), test(List(1, 2, 3)) -> arr(1, 2, 3), test(List[Int](), "Seq.empty") -> arr(), test(Map("a" -> 1, "b" -> 2)) -> obj("a" -> 1, "b" -> 2), test(Option(1), "Option.nonEmpty") -> value(1), test(Option.empty[Int], "Option.empty") -> List(NullValueNode), test(1: java.lang.Integer) -> value(1), test(java.lang.Short.valueOf(1: Short)) -> value(1: Short), test(1L: java.lang.Long) -> value(1L), test(1f: java.lang.Float) -> value(1f), test(1d: java.lang.Double) -> value(1d), test(java.math.BigDecimal.valueOf(1)) -> value(1: BigDecimal), test(java.math.BigInteger.valueOf(1)) -> value(1: BigInt) ) behavior of "Default writers" cases.foreach { case (TestDefinition(value, jsonWriter, name), result) => it should s"correctly write $name" in { value.asTokenList(jsonWriter) shouldBe result } case _ => fail("oops") } } object DefaultWritersTest { case class TestDefinition[A](value: A, jsonWriter: JsonWriter[A], name: String) }
Example 133
Source File: JacksonTokenWriterTest.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.jackson import java.io.StringWriter import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import tethys._ import tethys.writers.tokens.TokenWriter class JacksonTokenWriterTest extends AnyFlatSpec with Matchers { def iterate(fun: (TokenWriter) => Unit): String = { val sw = new StringWriter() val tokenWriter = sw.toTokenWriter fun(tokenWriter) tokenWriter.close() sw.toString } behavior of "JacksonTokenWriter" it should "write String value" in { iterate(_.writeString("string")) shouldBe """"string"""" } it should "write Short value" in { iterate(_.writeNumber(1: Short)) shouldBe """1""" } it should "write Int value" in { iterate(_.writeNumber(1: Int)) shouldBe """1""" } it should "write Long value" in { iterate(_.writeNumber(1: Long)) shouldBe """1""" } it should "write Float value" in { iterate(_.writeNumber(1: Float)) shouldBe """1.0""" } it should "write Double value" in { iterate(_.writeNumber(1: Double)) shouldBe """1.0""" } it should "write BitInt value" in { iterate(_.writeNumber(1: BigInt)) shouldBe """1""" } it should "write BigDecimal value" in { iterate(_.writeNumber(1: BigDecimal)) shouldBe """1""" } it should "write true value" in { iterate(_.writeBoolean(true)) shouldBe """true""" } it should "write false value" in { iterate(_.writeBoolean(false)) shouldBe """false""" } it should "write null value" in { iterate(_.writeNull()) shouldBe """null""" } it should "write object structure" in { iterate(_.writeObjectStart().writeObjectEnd()) shouldBe """{}""" } it should "write array structure" in { iterate(_.writeArrayStart().writeArrayEnd()) shouldBe """[]""" } it should "write raw json" in { iterate(_.writeRawJson("""{"some" : "raw json"}""")) shouldBe """{"some" : "raw json"}""" } it should "write complex object structure" in { iterate { _.writeObjectStart() .writeFieldName("a") .writeNumber(1) .writeFieldName("b") .writeArrayStart() .writeString("s") .writeRawJson("false") .writeBoolean(true) .writeObjectStart() .writeFieldName("a") .writeNull() .writeObjectEnd() .writeArrayEnd() .writeFieldName("c") .writeRawJson("""{"some" : "raw json"}""") .writeObjectEnd() } shouldBe """{"a":1,"b":["s",false,true,{"a":null}],"c":{"some" : "raw json"}}""" } }
Example 134
Source File: CirceSuite.scala From circe-optics with Apache License 2.0 | 5 votes |
package io.circe.optics import cats.kernel.Eq import cats.instances.AllInstances import cats.syntax.{ AllSyntax, EitherOps } import io.circe.testing.{ ArbitraryInstances, EqInstances } import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.{ Checkers, ScalaCheckDrivenPropertyChecks } import org.typelevel.discipline.Laws import org.typelevel.discipline.scalatest.FlatSpecDiscipline import scala.language.implicitConversions trait CirceSuite extends AnyFlatSpec with FlatSpecDiscipline with ScalaCheckDrivenPropertyChecks with AllInstances with AllSyntax with ArbitraryInstances with EqInstances { override def convertToEqualizer[T](left: T): Equalizer[T] = sys.error("Intentionally ambiguous implicit for Equalizer") implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab) def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach { case ((id, prop), 0) => name should s"obey $id" in Checkers.check(prop) case ((id, prop), _) => it should s"obey $id" in Checkers.check(prop) } def assertEq[A: Eq](expected: A, actual: A): Unit = assert( expected === actual, s"""Expected did not match actual: | |Expected: $expected |Actual: $actual""" ) }
Example 135
Source File: T03FunctionTest.scala From big-data-rosetta-code with Apache License 2.0 | 5 votes |
package com.spotify.bdrc.testing import com.spotify.scio._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers object WordCount3 { def main(cmdlineArgs: Array[String]): Unit = { val (sc, args) = ContextAndArgs(cmdlineArgs) sc.textFile(args("input")) .flatMap(split) .countByValue .map(format) .saveAsTextFile(args("output")) } def split(input: String): Seq[String] = input.split("[^a-zA-Z']+").filter(_.nonEmpty) def format(kv: (String, Long)): String = kv._1 + ": " + kv._2 } class FunctionTest extends AnyFlatSpec with Matchers { "split" should "work" in { WordCount3.split("a b,c d\te\n\nf") should equal(Seq("a", "b", "c", "d", "e", "f")) } "format" should "work" in { WordCount3.format(("a", 10L)) should equal("a: 10") } }
Example 136
Source File: DoobieSpec.scala From cron4s with Apache License 2.0 | 5 votes |
package cron4s package doobie import cats.effect.{IO, ContextShift} import _root_.doobie._ import _root_.doobie.implicits._ import _root_.doobie.util.invariant._ import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import scala.concurrent.ExecutionContext class DoobieSpec extends AnyFlatSpec with Matchers { implicit val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val xa = Transactor.fromDriverManager[IO]( "org.h2.Driver", "jdbc:h2:mem:refined;DB_CLOSE_DELAY=-1", "sa", "" ) def insertMeeting(meeting: Meeting) = { val createTable = sql""" create table meeting( meeting_id BIGINT AUTO_INCREMENT PRIMARY KEY, subject VARCHAR(255) NOT NULL, description VARCHAR(255) NOT NULL, frequency VARCHAR(255) NOT NULL ) """ val insertRecord = sql""" insert into meeting(subject, description, frequency) values(${meeting.subject}, ${meeting.description}, ${meeting.frequency}) """ for { _ <- createTable.update.run id <- insertRecord.update.withUniqueGeneratedKeys[Long]("meeting_id") } yield MeetingId(id) } def loadMeeting(meetingId: MeetingId) = sql"select subject, description, frequency from meeting where meeting_id = $meetingId" .query[Meeting] .unique "Doobie" should "store and retrieve a cron expression as a member of a storable data structure" in { val standUpMeeting = Meeting( "Daily stand-up", "Daily team morning stand-up meeting", Cron.unsafeParse("0 0 10 ? * mon-fri") ) val tx = for { meetingId <- insertMeeting(standUpMeeting) loaded <- loadMeeting(meetingId) } yield loaded val loadedMeeting = tx.transact(xa).unsafeRunSync() loadedMeeting shouldBe standUpMeeting } it should "throw a SecondaryValidationFailed in case the cron expression is invalid" in { assertThrows[SecondaryValidationFailed[CronExpr]] { sql"select '0- 0 30 * * ?'".query[CronExpr].unique.transact(xa).unsafeRunSync() } } }
Example 137
Source File: CronDateTimeTestKit.scala From cron4s with Apache License 2.0 | 5 votes |
package cron4s.testkit import cats.{Eq, Show} import cats.implicits._ import cron4s.Cron import cron4s.datetime.IsDateTime import org.scalatest.flatspec.AnyFlatSpec 10 * * * ?") // https://github.com/alonsodomin/cron4s/issues/73 final val Every31DayOfMonth = Cron.unsafeParse("1 1 1 31 * ?") // https://github.com/alonsodomin/cron4s/issues/80 final val AnyDayOfMonth = Cron.unsafeParse("4 31 4 ? * *") } abstract class CronDateTimeTestKit[DateTime: IsDateTime: Eq: Show] extends AnyFlatSpec { this: DateTimeTestKitBase[DateTime] => import CronDateTimeTestKit._ lazy val samples = Seq( //("expr", "from", "stepSize", "expected"), ( OnlyTuesdaysAt12, createDateTime(0, 0, 0, 1, 8, 2016), 1, createDateTime(0, 0, 12, 2, 8, 2016) ), ( EachMinutesOnSundays, createDateTime(0, 0, 0, 1, 8, 2016), 1, createDateTime(0, 0, 0, 7, 8, 2016) ), ( BetweenDayOfWeek, createDateTime(0, 0, 2, 11, 3, 2016), 1, createDateTime(0, 0, 0, 15, 3, 2016) ), ( BetweenDayOfWeek, createDateTime(0, 0, 2, 7, 3, 2016), -1, createDateTime(0, 0, 0, 3, 3, 2016) ), (BetweenMonth, createDateTime(0, 1, 1, 4, 11, 2016), 1, createDateTime(0, 0, 0, 1, 4, 2017)), ( Every10Minutes, createDateTime(42, 39, 16, 18, 2, 2017), 1, createDateTime(0, 40, 16, 18, 2, 2017) ), ( Every31DayOfMonth, createDateTime(0, 0, 0, 4, 9, 2016), 1, createDateTime(1, 1, 1, 31, 10, 2016) ), ( AnyDayOfMonth, createDateTime(45, 30, 23, 30, 6, 2017), 1, createDateTime(4, 31, 4, 1, 7, 2017) ) ) "Cron.step" should "match expected result" in { val test = Eq[DateTime] for ((expr, initial, stepSize, expected) <- samples) { val returnedDateTime = expr.step(initial, stepSize).get val matchesExpected = test.eqv(returnedDateTime, expected) assert( matchesExpected, s"[${expr.show}]: (${initial.show}, $stepSize) => ${returnedDateTime.show} != ${expected.show}" ) } } }
Example 138
Source File: EveryNodeValidatorRegressionSpec.scala From cron4s with Apache License 2.0 | 5 votes |
package cron4s.validation import cats.syntax.show._ import cron4s._ import cron4s.expr.{EachNode, EveryNode} import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec class EveryNodeValidatorRegressionSpec extends AnyFlatSpec with Matchers { import CronField._ "An Every node" should "pass validation if it's evenly divided" in { val eachNode = EachNode[Second] val everyNode = EveryNode[Second](eachNode, 12) val returnedErrors = NodeValidator[EveryNode[Second]].validate(everyNode) returnedErrors shouldBe List.empty[InvalidField] } it should "not pass validation if it is not evenly divided" in { val eachNode = EachNode[Second] val everyNode = EveryNode[Second](eachNode, 13) val expectedError = InvalidField( Second, s"Step '${everyNode.freq}' does not evenly divide the value '${everyNode.base.show}'" ) val returnedErrors = NodeValidator[EveryNode[Second]].validate(everyNode) returnedErrors shouldBe List(expectedError) } }
Example 139
Source File: SeveralNodeValidatorRegressionSpec.scala From cron4s with Apache License 2.0 | 5 votes |
package cron4s.validation import cats.syntax.show._ import cron4s._ import cron4s.expr._ import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec class SeveralNodeValidatorRegressionSpec extends AnyFlatSpec with Matchers { import CronField._ "A series of nodes" should "not be valid if any of them implies the other" in { val node1 = ConstNode[Minute](23) val node2 = BetweenNode[Minute](ConstNode(10), ConstNode(24)) val severalNode = SeveralNode[Minute](node1, node2) val returnedErrors = NodeValidator[SeveralNode[Minute]].validate(severalNode) returnedErrors shouldBe List( InvalidField( Minute, s"Value '${node1.show}' is implied by '${node2.show}'" ) ) } it should "not fail if they overlap without full implication" in { val node1 = BetweenNode[Minute](ConstNode(6), ConstNode(12)) val node2 = BetweenNode[Minute](ConstNode(10), ConstNode(24)) val severalNode = SeveralNode[Minute](node1, node2) val returnedErrors = NodeValidator[SeveralNode[Minute]].validate(severalNode) returnedErrors shouldBe List.empty[InvalidField] } it should "include both error messages when implication is bidirectional" in { val node1 = ConstNode[Second](10) val node2 = ConstNode[Second](10) val severalNode = SeveralNode[Second](node1, node2) val returnedErrors = NodeValidator[SeveralNode[Second]].validate(severalNode) returnedErrors shouldBe List( InvalidField(Second, s"Value '${node1.show}' is implied by '${node2.show}'"), InvalidField(Second, s"Value '${node2.show}' is implied by '${node1.show}'") ) } it should "accumulate all the implication errors" in { val node1 = ConstNode[Month](5) val node2 = BetweenNode[Month](ConstNode(2), ConstNode(6)) val node3 = BetweenNode[Month](ConstNode(4), ConstNode(8)) val severalNode = SeveralNode[Month](node1, node2, node3) val returnedErrors = NodeValidator[SeveralNode[Month]].validate(severalNode) returnedErrors shouldBe List( InvalidField(Month, s"Value '${node1.show}' is implied by '${node2.show}'"), InvalidField(Month, s"Value '${node1.show}' is implied by '${node3.show}'") ) } it should "not check for implication of elements when a subexpression is invalid" in { val node1 = ConstNode[Second](23) val node2 = BetweenNode[Second](ConstNode(-390), ConstNode(120)) val severalNode = SeveralNode[Second](node1, node2) val returnedErrors = NodeValidator[SeveralNode[Second]].validate(severalNode) returnedErrors shouldBe List( InvalidField(Second, s"Value ${node2.begin.show} is out of bounds for field: Second"), InvalidField(Second, s"Value ${node2.end.show} is out of bounds for field: Second") ) } }
Example 140
Source File: JavaTimeCronDateTimeRegressionSpec.scala From cron4s with Apache License 2.0 | 5 votes |
package cron4s.lib.javatime import java.time.LocalDateTime import java.time.temporal.{ChronoField, ChronoUnit} import cron4s._ import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec 10 * * * ?") val next = cron.next(from).get from.until(next, ChronoUnit.SECONDS) shouldBe 17L } // https://github.com/alonsodomin/cron4s/issues/59 "Cron with day of week" should "yield a date in the future" in { val cron = Cron.unsafeParse("0 0 0 ? * 1-3") for (dayOfMonth <- 1 to 30) { val from = LocalDateTime.of(2017, 3, dayOfMonth, 2, 0, 0) cron.next(from).forall(_.isAfter(from)) shouldBe true } } }
Example 141
Source File: ScalaXMLSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
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 142
Source File: JavaxSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
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 143
Source File: AkkaSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
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 144
Source File: CirceSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
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 145
Source File: ConfigReaderMatchers.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig import java.net.URL import com.typesafe.config.{ ConfigOrigin, ConfigOriginFactory } import scala.reflect.ClassTag import org.scalatest._ import org.scalatest.matchers.{ MatchResult, Matcher } import pureconfig.error._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers trait ConfigReaderMatchers { this: AnyFlatSpec with Matchers => def failWith(reason: FailureReason): Matcher[ConfigReader.Result[Any]] = matchPattern { case Left(ConfigReaderFailures(ConvertFailure(`reason`, _, _))) => } def failWith( reason: FailureReason, path: String, origin: Option[ConfigOrigin] = None): Matcher[ConfigReader.Result[Any]] = be(Left(ConfigReaderFailures(ConvertFailure(reason, origin, path)))) def failWith(failure: ConfigReaderFailure): Matcher[ConfigReader.Result[Any]] = be(Left(ConfigReaderFailures(failure))) def failWithType[Reason <: FailureReason: ClassTag]: Matcher[ConfigReader.Result[Any]] = matchPattern { case Left(ConfigReaderFailures(ConvertFailure(_: Reason, _, _))) => } def failWithType[Failure <: ConfigReaderFailure: ClassTag](implicit dummy: DummyImplicit): Matcher[ConfigReader.Result[Any]] = matchPattern { case Left(ConfigReaderFailures(_: Failure)) => } def failLike(pf: PartialFunction[ConfigReaderFailure, MatchResult]) = new Matcher[ConfigReader.Result[Any]] with Inside with PartialFunctionValues { def apply(left: ConfigReader.Result[Any]): MatchResult = { inside(left) { case Left(ConfigReaderFailures(failure)) => pf.valueAt(failure) } } } def stringConfigOrigin(line: Int) = Some(ConfigOriginFactory.newSimple("String").withLineNumber(line)) def urlConfigOrigin(url: URL, line: Int): Option[ConfigOrigin] = Some(ConfigOriginFactory.newURL(url).withLineNumber(line)) val emptyConfigOrigin: Option[ConfigOrigin] = Some(ConfigOriginFactory.newSimple()) }
Example 146
Source File: ConfigFieldMappingSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ConfigFieldMappingSuite extends AnyFlatSpec with Matchers { behavior of "ConfigFieldMapping" it should "allow defining a mapping using a function" in { val mapping = ConfigFieldMapping(_.replace("Field", "ConfigKey")) mapping("theBeautifulField") === "theBeautifulConfigKey" mapping("theUglyFld") === "theUglyFld" } it should "allow defining a mapping between two naming conventions" in { val mapping = ConfigFieldMapping(CamelCase, SnakeCase) mapping("theBeautifulField") === "the_beautiful_field" mapping("theUglyFld") === "the_ugly_fld" } it should "allow defining mappings with some overrides" in { val mapping = ConfigFieldMapping(CamelCase, SnakeCase).withOverrides( "theUglyFld" -> "the_ugly_field") mapping("theBeautifulField") === "the_beautiful_field" mapping("theUglyFld") === "the_ugly_field" } }
Example 147
Source File: SyntaxSpec.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.syntax import scala.collection.immutable.{ List, Map } import com.typesafe.config.ConfigFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import pureconfig.error.ConfigReaderException import pureconfig.generic.auto._ class SyntaxSpec extends AnyFlatSpec with Matchers { behavior of "pureconfig.syntax._" it should "be able to serialize a ConfigValue from a type with ConfigConvert using the toConfig method" in { Map("a" -> 1, "b" -> 2).toConfig shouldBe ConfigFactory.parseString("""{ "a": 1, "b": 2 }""").root() } it should "be able to load a ConfigValue to a type with ConfigConvert using the to method" in { val conf = ConfigFactory.parseString("""{ "a": [1, 2, 3, 4], "b": { "k1": "v1", "k2": "v2" } }""") conf.getList("a").to[List[Int]] shouldBe Right(List(1, 2, 3, 4)) conf.getObject("b").to[Map[String, String]] shouldBe Right(Map("k1" -> "v1", "k2" -> "v2")) } it should "be able to load a Config to a type with ConfigConvert using the to method" in { val conf = ConfigFactory.parseString("""{ "a": [1, 2, 3, 4], "b": { "k1": "v1", "k2": "v2" } }""") case class Conf(a: List[Int], b: Map[String, String]) conf.to[Conf] shouldBe Right(Conf(List(1, 2, 3, 4), Map("k1" -> "v1", "k2" -> "v2"))) } // TODO this shouldn't be here it should "fail when trying to convert to basic types from an empty string" in { val conf = ConfigFactory.parseString("""{ v: "" }""") conf.getValue("v").to[Boolean].isLeft shouldBe true conf.getValue("v").to[Double].isLeft shouldBe true conf.getValue("v").to[Float].isLeft shouldBe true conf.getValue("v").to[Int].isLeft shouldBe true conf.getValue("v").to[Long].isLeft shouldBe true conf.getValue("v").to[Short].isLeft shouldBe true } it should "fail with Exception when trying to convert to basic types from an empty string" in { val conf = ConfigFactory.parseString("""{ v: "" }""") a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Boolean] a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Double] a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Float] a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Int] a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Long] a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Short] } it should "pass when trying to convert to basic types with pureconfig.syntax toOrThrow" in { val conf = ConfigFactory.parseString("""{ b: true, d: 2.2, f: 3.3, i: 2, l: 2, s: 2, cs: "Cheese"}""") conf.getValue("b").toOrThrow[Boolean] shouldBe true conf.getValue("d").toOrThrow[Double] shouldBe 2.2 conf.getValue("f").toOrThrow[Float] shouldBe 3.3f conf.getValue("i").toOrThrow[Int] shouldBe 2 conf.getValue("l").toOrThrow[Long] shouldBe 2L conf.getValue("s").toOrThrow[Short] shouldBe 2.toShort conf.getValue("cs").toOrThrow[String] shouldBe "Cheese" } }
Example 148
Source File: ConfigReaderFailureOriginSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig import java.net.URL import com.typesafe.config.{ ConfigFactory, ConfigValueType } import org.scalatest.{ EitherValues, Inside } import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import pureconfig.error._ import pureconfig.generic.auto._ class ConfigReaderFailureOriginSuite extends BaseSuite with EitherValues with Inside { "Loading configuration from files" should "show proper error locations when loading a single file" in { import pureconfig.syntax._ case class Conf(a: Int, b: String, c: Int) val workingDir = getClass.getResource("/").getFile val file = "conf/configFailureOrigin/single/a.conf" val conf = ConfigFactory.load(file).root() inside(conf.get("conf").to[Conf].left.value.toList) { case List( ConvertFailure( KeyNotFound("a", _), Some(origin1), ""), ConvertFailure( WrongType(ConfigValueType.STRING, valueTypes), Some(origin2), "c") ) => origin1.filename() should endWith(file) origin1.url() shouldBe new URL("file", "", workingDir + file) origin1.lineNumber() shouldBe 1 origin2.filename() should endWith(file) origin2.url() shouldBe new URL("file", "", workingDir + file) origin2.lineNumber() shouldBe 3 valueTypes should contain only ConfigValueType.NUMBER } inside(conf.get("other-conf").to[Conf].left.value.toList) { case List( ConvertFailure( KeyNotFound("a", _), Some(origin1), ""), ConvertFailure( KeyNotFound("b", _), Some(origin2), ""), ConvertFailure( WrongType(ConfigValueType.STRING, valueTypes2), Some(origin3), "c") ) => origin1.filename() should endWith(file) origin1.url shouldBe new URL("file", "", workingDir + file) origin1.lineNumber shouldBe 7 origin2.filename() should endWith(file) origin2.url shouldBe new URL("file", "", workingDir + file) origin2.lineNumber shouldBe 7 origin3.filename() should endWith(file) origin3.url shouldBe new URL("file", "", workingDir + file) origin3.lineNumber shouldBe 9 valueTypes2 should contain only ConfigValueType.NUMBER } } it should "show proper error location when loading from multiple files" in { import pureconfig.syntax._ case class Conf(a: Int, b: String, c: Int) val workingDir = getClass.getResource("/").getFile val file1 = "conf/configFailureOrigin/multiple/a.conf" val file2 = "conf/configFailureOrigin/multiple/b.conf" val conf = ConfigFactory.load(file1).withFallback(ConfigFactory.load(file2)).root() inside(conf.get("conf").to[Conf].left.value.toList) { case List(ConvertFailure( WrongType(ConfigValueType.STRING, valueTypes), Some(origin), "a")) => valueTypes should contain only ConfigValueType.NUMBER origin.url() shouldBe new URL("file", "", workingDir + file2) origin.lineNumber() shouldBe 2 } } }
Example 149
Source File: InstallDirTests.scala From coursier with Apache License 2.0 | 5 votes |
package coursier.install import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec import java.nio.file.Paths import coursier.launcher.Parameters class InstallDirTests extends AnyFlatSpec with BeforeAndAfterAll { it should "pass the GraalVM version to launcher params" in { val version = "X.Y.Z" val installDir = InstallDir() .withGraalvmParamsOpt(Some(GraalvmParams(Some(version), Nil))) val params = installDir.params( AppDescriptor().withLauncherType(LauncherType.GraalvmNativeImage), AppArtifacts(), Nil, "main.class", Paths.get("/foo") ) val nativeParams = params match { case n: Parameters.NativeImage => n case _ => sys.error(s"Unrecognized parameters type: $params") } assert(nativeParams.graalvmVersion == Some(version)) } }
Example 150
Source File: CliUnitTest.scala From coursier with Apache License 2.0 | 5 votes |
package coursier.cli import java.io.{File, FileWriter} import coursier.moduleString import coursier.cli.options.DependencyOptions import coursier.cli.params.DependencyParams import coursier.parse.JavaOrScalaModule import org.junit.runner.RunWith import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class CliUnitTest extends AnyFlatSpec { def withFile(content: String)(testCode: (File, FileWriter) => Any) { val file = File.createTempFile("hello", "world") // create the fixture val writer = new FileWriter(file) writer.write(content) writer.flush() try { testCode(file, writer) // "loan" the fixture to the test } finally { writer.close() file.delete() } } "Normal text" should "parse correctly" in withFile( "org1:name1--org2:name2") { (file, _) => val options = DependencyOptions(localExcludeFile = file.getAbsolutePath) val params = DependencyParams(options, None) .fold(e => sys.error(e.toString), identity) val expected = Map(JavaOrScalaModule.JavaModule(mod"org1:name1") -> Set(JavaOrScalaModule.JavaModule(mod"org2:name2"))) assert(params.perModuleExclude.equals(expected), s"got ${params.perModuleExclude}") } "Multiple excludes" should "be combined" in withFile( "org1:name1--org2:name2\n" + "org1:name1--org3:name3\n" + "org4:name4--org5:name5") { (file, _) => val options = DependencyOptions(localExcludeFile = file.getAbsolutePath) val params = DependencyParams(options, None) .fold(e => sys.error(e.toString), identity) val expected = Map( JavaOrScalaModule.JavaModule(mod"org1:name1") -> Set(JavaOrScalaModule.JavaModule(mod"org2:name2"), JavaOrScalaModule.JavaModule(mod"org3:name3")), JavaOrScalaModule.JavaModule(mod"org4:name4") -> Set(JavaOrScalaModule.JavaModule(mod"org5:name5")) ) assert(params.perModuleExclude.equals(expected)) } "extra --" should "error" in withFile( "org1:name1--org2:name2--xxx\n" + "org1:name1--org3:name3\n" + "org4:name4--org5:name5") { (file, _) => val options = DependencyOptions(localExcludeFile = file.getAbsolutePath) DependencyParams(options, None).toEither match { case Left(errors) => assert(errors.exists(_.startsWith("Failed to parse "))) case Right(p) => sys.error(s"Should have errored (got $p)") } } "child has no name" should "error" in withFile( "org1:name1--org2:") { (file, _) => val options = DependencyOptions(localExcludeFile = file.getAbsolutePath) DependencyParams(options, None).toEither match { case Left(errors) => assert(errors.exists(_.startsWith("Failed to parse "))) case Right(p) => sys.error(s"Should have errored (got $p)") } } "child has nothing" should "error" in withFile( "org1:name1--:") { (file, _) => val options = DependencyOptions(localExcludeFile = file.getAbsolutePath) DependencyParams(options, None).toEither match { case Left(errors) => assert(errors.exists(_.startsWith("Failed to parse "))) case Right(p) => sys.error(s"Should have errored (got $p)") } } }
Example 151
Source File: ZipTests.scala From coursier with Apache License 2.0 | 5 votes |
package coursier.cli.util import java.io.{ByteArrayInputStream, ByteArrayOutputStream} import java.util.Random import java.util.zip.{Deflater, ZipEntry, ZipInputStream, ZipOutputStream} import coursier.launcher.internal.Zip import org.junit.runner.RunWith import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class ZipTests extends AnyFlatSpec { "zipEntries" should "be fine with custom deflaters" in { // Inspired by https://github.com/spring-projects/spring-boot/commit/a50646b7cc3ad941e748dfb450077e3a73706205#diff-2297c301250b25e3b80301c58daf3ea0R621 val baos = new ByteArrayOutputStream val output = new ZipOutputStream(baos) { `def` = new Deflater(Deflater.NO_COMPRESSION, true) } val data = Array.ofDim[Byte](1024 * 1024) new Random().nextBytes(data) val entry = new ZipEntry("entry.dat") output.putNextEntry(entry) output.write(data) output.closeEntry() output.close() val result = baos.toByteArray val zos = new ZipOutputStream(new ByteArrayOutputStream) val entryNames = Zip.zipEntries(new ZipInputStream(new ByteArrayInputStream(result))) .map { case (ent, content) => println(ent.getCompressedSize) val name = ent.getName zos.putNextEntry(ent) zos.write(content) zos.closeEntry() name } .toVector zos.close() assert(entryNames == Vector("entry.dat")) } }
Example 152
Source File: JsonReportTest.scala From coursier with Apache License 2.0 | 5 votes |
package coursier.cli.util import argonaut.Parse import coursier.cli.CliTestLib import org.junit.runner.RunWith import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class JsonReportTest extends AnyFlatSpec with CliTestLib { "empty JsonReport" should "be empty" in { val report: String = JsonReport[String](IndexedSeq(), Map())( children = _ => Seq(), reconciledVersionStr = _ => "", requestedVersionStr = _ => "", getFile = _ => Option(""), exclusions = _ => Set.empty ) assert( report == "{\"conflict_resolution\":{},\"dependencies\":[],\"version\":\"0.1.0\"}") } "JsonReport containing two deps" should "not be empty" in { val children = Map("a" -> Seq("b"), "b" -> Seq()) val report: String = JsonReport[String]( roots = IndexedSeq("a", "b"), conflictResolutionForRoots = Map() )( children = children(_), reconciledVersionStr = s => s"$s:reconciled", requestedVersionStr = s => s"$s:requested", getFile = _ => Option(""), exclusions = _ => Set.empty ) val reportJson = Parse.parse(report) val expectedReportJson = Parse.parse( """{ | "conflict_resolution": {}, | "dependencies": [ | { | "coord": "a:reconciled", | "file": "", | "directDependencies": [ "b:reconciled" ], | "dependencies": [ "b:reconciled" ] | }, | { | "coord": "b:reconciled", | "file": "", | "directDependencies": [], | "dependencies": [] | } | ], | "version": "0.1.0" |}""".stripMargin ) assert(reportJson == expectedReportJson) } "JsonReport containing two deps" should "be sorted alphabetically regardless of input order" in { val children = Map("a" -> Seq("b"), "b" -> Seq()) val report: String = JsonReport[String]( roots = IndexedSeq( "b", "a"), conflictResolutionForRoots = Map() )( children = children(_), reconciledVersionStr = s => s"$s:reconciled", requestedVersionStr = s => s"$s:requested", getFile = _ => Option(""), exclusions = _ => Set.empty ) val reportJson = Parse.parse(report) val expectedReportJson = Parse.parse( """{ | "conflict_resolution": {}, | "dependencies": [ | { "coord": "a:reconciled", "file": "", "directDependencies": [ "b:reconciled" ], "dependencies": [ "b:reconciled" ] }, | { "coord": "b:reconciled", "file": "", "directDependencies": [], "dependencies": [] } | ], | "version": "0.1.0" |}""".stripMargin ) assert(reportJson == expectedReportJson) } }
Example 153
Source File: InfixConvertersTests.scala From JsonSql with MIT License | 5 votes |
package com.mmalek.jsonSql import com.mmalek.jsonSql.execution.rpn.{Infix2RpnArithmeticConverter, Infix2RpnLogicalConverter} import com.mmalek.jsonSql.sqlParsing.Token._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class InfixConvertersTests extends AnyFlatSpec with Matchers { "Arithmetic converter" should "reorder tokens in simple expression" in { val tokens = Seq( Constant("5"), Operator("+"), Constant("7")) val result = Infix2RpnArithmeticConverter.convert(tokens) result.length should be (3) result.head should be (Constant("5")) result(1) should be (Constant("7")) result(2) should be (Operator("+")) } it should "reorder tokens in complex expression" in { val tokens = Seq( Bracket("("), Bracket("("), Constant("5"), Operator("+"), Constant("7"), Bracket(")"), Operator("*"), Constant("2"), Operator("+"), Constant("9"), Bracket(")"), Operator("*"), Bracket("("), Constant("8"), Operator("/"), Constant("2"), Bracket(")")) val result = Infix2RpnArithmeticConverter.convert(tokens) result.length should be (11) result.head should be (Constant("5")) result(1) should be (Constant("7")) result(2) should be (Operator("+")) result(3) should be (Constant("2")) result(4) should be (Operator("*")) result(5) should be (Constant("9")) result(6) should be (Operator("+")) result(7) should be (Constant("8")) result(8) should be (Constant("2")) result(9) should be (Operator("/")) result(10) should be (Operator("*")) } "Logical converter" should "reorder tokens in simple expression" in { val tokens = Seq( Constant("true"), Operator("OR"), Constant("false")) val result = Infix2RpnArithmeticConverter.convert(tokens) result.length should be (3) result.head should be (Constant("true")) result(1) should be (Constant("false")) result(2) should be (Operator("OR")) } it should "reorder tokens in complex expression" in { val tokens = Seq( Constant("true"), Or, Bracket("("), Constant("true"), And, Constant("true"), Bracket(")"), And, Constant("true")) val result = Infix2RpnLogicalConverter.convert(tokens) result.length should be (7) result.head should be (Constant("true")) result(1) should be (Constant("true")) result(2) should be (Constant("true")) result(3) should be (And) result(4) should be (Or) result(5) should be (Constant("true")) result(6) should be (And) } }
Example 154
Source File: NormalizerTests.scala From JsonSql with MIT License | 5 votes |
package com.mmalek.jsonSql import com.mmalek.jsonSql.jsonParsing.Normalizer import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class NormalizerTests extends AnyFlatSpec with Matchers { "A Normalizer" should "normalize json text with whitespaces" in { val query = """{ "str_key": "value", "int_key": 1 }""".stripMargin val result = Normalizer.normalize(query) result should be ("{ \"str_key\": \"value\", \"int_key\": 1 }") } }
Example 155
Source File: LoadingCacheExample.scala From scaffeine with Apache License 2.0 | 5 votes |
package com.github.blemale.scaffeine.example import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class LoadingCacheExample extends AnyFlatSpec with Matchers { "LoadingCache" should "be created from Scaffeine builder" in { import com.github.blemale.scaffeine.{LoadingCache, Scaffeine} import scala.concurrent.duration._ val cache: LoadingCache[Int, String] = Scaffeine() .recordStats() .expireAfterWrite(1.hour) .maximumSize(500) .build((i: Int) => s"foo$i") cache.get(1) should be("foo1") } }
Example 156
Source File: AsyncLoadingCacheExample.scala From scaffeine with Apache License 2.0 | 5 votes |
package com.github.blemale.scaffeine.example import org.scalatest.concurrent.ScalaFutures import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.Future class AsyncLoadingCacheExample extends AnyFlatSpec with Matchers with ScalaFutures { "AsyncLoadingCache" should "be created from Scaffeine builder with synchronous loader" in { import com.github.blemale.scaffeine.{AsyncLoadingCache, Scaffeine} import scala.concurrent.duration._ val cache: AsyncLoadingCache[Int, String] = Scaffeine() .recordStats() .expireAfterWrite(1.hour) .maximumSize(500) .buildAsync((i: Int) => s"foo$i") whenReady(cache.get(1))(value => value should be("foo1")) } "AsyncLoadingCache" should "be created from Scaffeine builder with asynchronous loader" in { import com.github.blemale.scaffeine.{AsyncLoadingCache, Scaffeine} import scala.concurrent.duration._ val cache: AsyncLoadingCache[Int, String] = Scaffeine() .recordStats() .expireAfterWrite(1.hour) .maximumSize(500) .buildAsyncFuture((i: Int) => Future.successful(s"foo$i")) whenReady(cache.get(1))(value => value should be("foo1")) } }
Example 157
Source File: CacheExample.scala From scaffeine with Apache License 2.0 | 5 votes |
package com.github.blemale.scaffeine.example import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class CacheExample extends AnyFlatSpec with Matchers { "Cache" should "be created from Scaffeine builder" in { import com.github.blemale.scaffeine.{Cache, Scaffeine} import scala.concurrent.duration._ val cache: Cache[Int, String] = Scaffeine() .recordStats() .expireAfterWrite(1.hour) .maximumSize(500) .build[Int, String]() cache.put(1, "foo") cache.getIfPresent(1) should be(Some("foo")) cache.getIfPresent(2) should be(None) } }
Example 158
Source File: OdinSpec.scala From odin with Apache License 2.0 | 5 votes |
package io.odin import java.time.LocalDateTime import cats.effect.{Clock, Timer} import cats.{Applicative, Eval} import io.odin.formatter.Formatter import io.odin.meta.Position import org.scalacheck.{Arbitrary, Cogen, Gen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.{Checkers, ScalaCheckDrivenPropertyChecks} import org.typelevel.discipline.Laws import scala.concurrent.duration.{FiniteDuration, TimeUnit} trait OdinSpec extends AnyFlatSpec with Matchers with Checkers with ScalaCheckDrivenPropertyChecks with EqInstances { def checkAll(name: String, ruleSet: Laws#RuleSet): Unit = { for ((id, prop) <- ruleSet.all.properties) it should (name + "." + id) in { check(prop) } } def zeroTimer[F[_]](implicit F: Applicative[F]): Timer[F] = new Timer[F] { def clock: Clock[F] = new Clock[F] { def realTime(unit: TimeUnit): F[Long] = F.pure(0L) def monotonic(unit: TimeUnit): F[Long] = F.pure(0L) } def sleep(duration: FiniteDuration): F[Unit] = ??? } val lineSeparator: String = System.lineSeparator() val nonEmptyStringGen: Gen[String] = Gen.nonEmptyListOf(Gen.alphaNumChar).map(_.mkString) val levelGen: Gen[Level] = Gen.oneOf(Level.Trace, Level.Debug, Level.Info, Level.Warn, Level.Error) implicit val levelArbitrary: Arbitrary[Level] = Arbitrary(levelGen) val positionGen: Gen[Position] = for { fileName <- nonEmptyStringGen enclosureName <- Gen.uuid.map(_.toString) packageName <- nonEmptyStringGen line <- Gen.posNum[Int] } yield { Position(fileName, enclosureName, packageName, line) } implicit val positionArbitrary: Arbitrary[Position] = Arbitrary(positionGen) val loggerMessageGen: Gen[LoggerMessage] = { val startTime = System.currentTimeMillis() for { level <- levelGen msg <- Gen.alphaNumStr context <- Gen.mapOfN(20, nonEmptyStringGen.flatMap(key => nonEmptyStringGen.map(key -> _))) exception <- Gen.option(Arbitrary.arbitrary[Throwable]) position <- positionGen threadName <- nonEmptyStringGen timestamp <- Gen.choose(0, startTime) } yield { LoggerMessage( level = level, message = Eval.now(msg), context = context, exception = exception, position = position, threadName = threadName, timestamp = timestamp ) } } implicit val loggerMessageArbitrary: Arbitrary[LoggerMessage] = Arbitrary(loggerMessageGen) implicit val cogenLoggerMessage: Cogen[LoggerMessage] = Cogen[LoggerMessage]((msg: LoggerMessage) => msg.level.hashCode().toLong + msg.message.value.hashCode().toLong) val formatterGen: Gen[Formatter] = Gen.oneOf(Formatter.default, Formatter.colorful) implicit val formatterArbitrary: Arbitrary[Formatter] = Arbitrary(formatterGen) val localDateTimeGen: Gen[LocalDateTime] = for { year <- Gen.choose(0, LocalDateTime.now().getYear) month <- Gen.choose(1, 12) day <- Gen.choose(1, 28) hour <- Gen.choose(0, 23) minute <- Gen.choose(0, 59) second <- Gen.choose(0, 59) } yield { LocalDateTime.of(year, month, day, hour, minute, second) } implicit val localDateTimeArbitrary: Arbitrary[LocalDateTime] = Arbitrary(localDateTimeGen) }
Example 159
Source File: TemplateParamsSpec.scala From comet-data-pipeline with Apache License 2.0 | 5 votes |
package com.ebiznext.comet.database.extractor import java.util.regex.Pattern import better.files.File import com.ebiznext.comet.schema.model._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class TemplateParamsSpec extends AnyFlatSpec with Matchers { val scriptOutputFolder: File = File("/tmp") "fromSchema" should "generate the correct TemplateParams for a given Schema" in { val schema: Schema = Schema( name = "table1", pattern = Pattern.compile("output_file.*.csv"), List(Attribute(name = "col1"), Attribute(name = "col2")), metadata = Option(Metadata(write = Some(WriteMode.APPEND))), merge = Some(MergeOptions(List("col1", "col2"), None, timestamp = Some("updateCol"))), comment = None, presql = None, postsql = None ) val expectedTemplateParams = TemplateParams( tableToExport = "table1", columnsToExport = List("col1", "col2"), fullExport = false, dsvDelimiter = ",", deltaColumn = Some("updateCol"), exportOutputFileBase = "output_file", scriptOutputFile = scriptOutputFolder / "EXTRACT_table1.sql" ) TemplateParams.fromSchema(schema, scriptOutputFolder) shouldBe expectedTemplateParams } it should "generate the correct TemplateParams for an other Schema" in { val schema: Schema = Schema( name = "table1", pattern = Pattern.compile("output_file.*.csv"), List(Attribute(name = "col1"), Attribute(name = "col2")), metadata = Option(Metadata(write = Some(WriteMode.OVERWRITE), separator = Some("|"))), merge = Some(MergeOptions(List("col1", "col2"), None, timestamp = Some("updateCol"))), comment = None, presql = None, postsql = None ) val expectedTemplateParams = TemplateParams( tableToExport = "table1", columnsToExport = List("col1", "col2"), fullExport = true, dsvDelimiter = "|", deltaColumn = None, exportOutputFileBase = "output_file", scriptOutputFile = scriptOutputFolder / "EXTRACT_table1.sql" ) TemplateParams.fromSchema(schema, scriptOutputFolder) shouldBe expectedTemplateParams } }
Example 160
Source File: ExtractScriptGenSpec.scala From comet-data-pipeline with Apache License 2.0 | 5 votes |
package com.ebiznext.comet.database.extractor import better.files.File import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ExtractScriptGenSpec extends AnyFlatSpec with Matchers { val scriptOutputFolder: File = File("/tmp") "templatize" should "generate an export script from a TemplateSettings" in { val templateParams: TemplateParams = TemplateParams( tableToExport = "table1", columnsToExport = List("col1", "col2"), fullExport = false, dsvDelimiter = ",", deltaColumn = Some("updateCol"), exportOutputFileBase = "output_file", scriptOutputFile = scriptOutputFolder / "EXTRACT_table1.sql" ) val templatePayload: String = ScriptGen.templatize( File( getClass.getResource("/sample/database/EXTRACT_TABLE.sql.mustache").getPath ), templateParams ) templatePayload shouldBe File( getClass.getResource("/sample/database/expected_script_payload.txt").getPath ).lines.mkString("\n") } }
Example 161
Source File: FormatParserSpec.scala From scalalaz-gen with Apache License 2.0 | 5 votes |
package ru.scalalaz.gen.parsing import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.Inside class FormatParserSpec extends AnyFlatSpec with Matchers with Inside { val raw = """title=value |key2=value2 |---- |### Yoyoyo! |it is a new episode!""".stripMargin it should "parse from string" in { val result = FormatParser.parseContent(raw) inside(result) { case Right(parsed) => parsed.header shouldBe Map("title" -> Some("value"), "key2" -> Some("value2")) parsed.otherData shouldBe "### Yoyoyo!\nit is a new episode!" } } val raw2 = """ |title=Выпуск 01 |enc.url=https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3 |enc.length=63337733 |page=http://scalalaz.ru/series-01.html |date=2016-08-07 |---- |### Выпуск 01 | |@:audioControls "https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3". | |Темы: | |- [Релиз-кандидат Akka](http://akka.io/news/2016/08/02/akka-…4.9-RC1-released.html) |- [Релиз Spark](https://exit.sc/?url=http%3A%2F%2Fspark.apache.org%2Freleases%2Fspark-release-2-0-0.html) |- [Релиз Spark](https://exit.sc/?url=http%3A%2F%2Fspark.apache.org%2Freleases%2Fspark-release-2-0-0.html) |- [Релиз Spark](https://exit.sc/?url=http%3A%2F%2Fspark.apache.org%2Freleases%2Fspark-release-2-0-0.html) |- [Pants](http://www.pantsbuild.org/)""".stripMargin it should "parse more complicated case" in { val result = FormatParser.parseContent(raw2) inside(result) { case Right(parsed) => } } }
Example 162
Source File: EpisodeParserSpec.scala From scalalaz-gen with Apache License 2.0 | 5 votes |
package ru.scalalaz.gen.parsing import java.time.LocalDate import cats.data.Validated.Valid import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.Inside class EpisodeParserSpec extends AnyFlatSpec with Matchers with Inside { val episodeStr = """ |title=Episode#1 |page=http://scalalaz.ru/series-01.html |date=2016-11-28 |audio.url=https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3 |audio.length=6 |---- |### Yoyoyo! |it is a new episode!""".stripMargin it should "parse from string" in { val result = EpisodeParser.fromString(episodeStr) inside(result) { case Valid(episode) => episode.content shouldBe "### Yoyoyo!\nit is a new episode!" val rss = episode.settings rss.title shouldBe "Episode#1" rss.page shouldBe "http://scalalaz.ru/series-01.html" rss.date shouldBe LocalDate.of(2016, 11, 28) rss.audio.url shouldBe "https://scalalaz.ru/mp3/scalalaz-podcast-1.mp3" rss.audio.length shouldBe 6 } } }
Example 163
Source File: BeanConverterTest.scala From beanpuree with Apache License 2.0 | 5 votes |
package me.limansky.beanpuree import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class BeanConverterTest extends AnyFlatSpec with Matchers { "BeanConverter" should "convert bean to case class" in { val converter = BeanConverter[TestBean, TestProductScala] val bean = new TestBean bean.setAmount(1L) bean.setCount(4) bean.setString("text") bean.setEnabled(true) converter.beanToProduct(bean) shouldEqual TestProductScala(4, "text", Some(1L), true) } it should "convert case class to bean" in { val converter = BeanConverter[TestBean, TestProductScala] val bean = converter.productToBean(TestProductScala(8, "back to Java", None, true)) bean.getAmount shouldBe null bean.getCount shouldEqual 8 bean.getString shouldEqual "back to Java" bean.isEnabled shouldBe true } it should "ignore fields order" in { val converter = BeanConverter[TestBean, TestProductScalaDisordered] val value = TestProductScalaDisordered(Some("ignore order"), false, 42L, 12) val bean = converter.productToBean(value) bean.getAmount shouldBe 42L bean.getCount shouldEqual 12 bean.getString shouldEqual "ignore order" bean.isEnabled shouldBe false converter.beanToProduct(bean) shouldEqual value } }
Example 164
Source File: BeanGenericTest.scala From beanpuree with Apache License 2.0 | 5 votes |
package me.limansky.beanpuree import shapeless.{ ::, Generic, HList, HNil } import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class BeanGenericTest extends AnyFlatSpec with Matchers { "BeanGeneric" should "Build Repr type" in { val gen = BeanGeneric[TestBean] implicitly[gen.Repr =:= (Int :: String :: java.lang.Long :: Boolean :: HNil)] } it should "convert bean to Repr HList" in { val gen = BeanGeneric[TestBean] val bean = new TestBean bean.setAmount(55L) bean.setString("test me") bean.setCount(33) gen.to(bean) shouldEqual 33 :: "test me" :: java.lang.Long.valueOf(55L) :: false :: HNil } it should "convert Repr HList to Bean" in { val gen = BeanGeneric[TestBean] val bean = gen.from(42 :: "abc" :: java.lang.Long.valueOf(25L) :: true :: HNil) bean.getCount shouldEqual 42 bean.getString shouldEqual "abc" bean.getAmount shouldEqual 25L bean.isEnabled shouldBe true } it should "ignore strange getters" in { val gen = BeanGeneric[WeirdBean] val bean = new WeirdBean bean.setX(5) bean.setY(6) gen.to(bean) shouldEqual 6 :: HNil } it should "aware of public methods only" in { val gen = BeanGeneric[BeanWithPrivate] val bean = new BeanWithPrivate bean.setA(6) bean.setS("test me") gen.to(bean) shouldEqual 6 :: HNil val bean2 = gen.from(10 :: HNil) bean2.getA shouldEqual 10 } }
Example 165
Source File: BeanLabellingTest.scala From beanpuree with Apache License 2.0 | 5 votes |
package me.limansky.beanpuree import shapeless.HNil import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class BeanLabellingTest extends AnyFlatSpec with Matchers { "BeanLabelling" should "extract field names" in { val lab = BeanLabelling[TestBean] lab() shouldEqual 'count :: 'string :: 'amount :: 'enabled :: HNil } it should "skip invalid setters and getters" in { val lab = BeanLabelling[WeirdBean] lab() shouldEqual 'y :: HNil } it should "ignore non-public methods" in { val lab = BeanLabelling[BeanWithPrivate] lab() shouldEqual 'a :: HNil } }
Example 166
Source File: LabelledBeanGenericTest.scala From beanpuree with Apache License 2.0 | 5 votes |
package me.limansky.beanpuree import shapeless.HNil import shapeless.syntax.singleton._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class LabelledBeanGenericTest extends AnyFlatSpec with Matchers { "LabelledBeanGeneric" should "convert bean to Repr" in { val gen = LabelledBeanGeneric[TestBean] val bean = new TestBean bean.setEnabled(true) bean.setCount(4) bean.setString("451") bean.setAmount(5L) gen.to(bean) shouldEqual Symbol("count") ->> 4 :: Symbol("string") ->> "451" :: Symbol("amount") ->> java.lang.Long.valueOf(5) :: Symbol("enabled") ->> true :: HNil } it should "convert Repr to bean" in { val gen = LabelledBeanGeneric[TestBean] val bean = gen.from(Symbol("count") ->> 4 :: Symbol("string") ->> "451" :: Symbol("amount") ->> java.lang.Long.valueOf(5) :: Symbol("enabled") ->> true :: HNil) bean.getAmount shouldEqual 5L bean.getCount shouldEqual 4 bean.getString shouldEqual "451" bean.isEnabled shouldBe true } it should "ignore invalid getters and setters" in { val gen = LabelledBeanGeneric[WeirdBean] val bean = new WeirdBean bean.setW(5) bean.setX(6) bean.setY(7) gen.to(bean) shouldEqual Symbol("y") ->> 7 :: HNil } it should "be aware of public methods only" in { val gen = LabelledBeanGeneric[BeanWithPrivate] val bean = new BeanWithPrivate bean.setA(42) bean.setS("bzzz") val repr = gen.to(bean) repr shouldEqual Symbol("a") ->> 42 :: HNil val bean2 = gen.from(repr) bean2.getA shouldEqual 42 bean2.getS shouldEqual null } }
Example 167
Source File: StrictBeanConverterTest.scala From beanpuree with Apache License 2.0 | 5 votes |
package me.limansky.beanpuree import shapeless.Generic import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class StrictBeanConverterTest extends AnyFlatSpec with Matchers { "StrictBeanConverter" should "convert bean to case class" in { val converter = StrictBeanConverter[TestBean, TestProduct] val bean = new TestBean bean.setAmount(1L) bean.setCount(4) bean.setString("text") bean.setEnabled(true) converter.beanToProduct(bean) shouldEqual TestProduct(4, "text", 1L, true) } it should "convert case class to bean" in { val converter = StrictBeanConverter[TestBean, TestProduct] val bean = converter.productToBean(TestProduct(8, "back to Java", 43L, true)) bean.getAmount shouldEqual 43L bean.getCount shouldEqual 8 bean.getString shouldEqual "back to Java" bean.isEnabled shouldBe true } it should "ignore fields order" in { val converter = StrictBeanConverter[TestBean, TestProductDisordered] val value = TestProductDisordered("a", 5L, 4, false) val bean = converter.productToBean(value) bean.getCount shouldEqual 4 bean.getAmount shouldEqual 5 bean.isEnabled shouldBe false bean.getString shouldEqual "a" converter.beanToProduct(bean) shouldEqual value } }
Example 168
Source File: RefinedSupportTest.scala From diffx with Apache License 2.0 | 5 votes |
package com.softwaremill.diffx.refined import com.softwaremill.diffx.{DiffResultObject, DiffResultString, DiffResultValue, Identical, _} import eu.timepit.refined.types.numeric.PosInt import eu.timepit.refined.auto._ import eu.timepit.refined.types.string.NonEmptyString import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class RefinedSupportTest extends AnyFlatSpec with Matchers { it should "work for refined types" in { val testData1 = TestData(1, "foo") val testData2 = TestData(1, "bar") compare(testData1, testData2) shouldBe DiffResultObject( "TestData", Map("posInt" -> Identical(1), "nonEmptyString" -> DiffResultString(List(DiffResultValue("foo", "bar")))) ) } } case class TestData(posInt: PosInt, nonEmptyString: NonEmptyString)
Example 169
Source File: DiffTaggingSupportTest.scala From diffx with Apache License 2.0 | 5 votes |
package com.softwaremill.diffx.tagging.test import com.softwaremill.diffx.{Diff, DiffResultObject, DiffResultValue, Identical} import com.softwaremill.diffx.tagging._ import com.softwaremill.tagging._ import com.softwaremill.tagging.@@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class DiffTaggingSupportTest extends AnyFlatSpec with Matchers { it should "work for tagged types" in { val p1 = 1.taggedWith[T1] val p11 = 2.taggedWith[T1] val p2 = 1.taggedWith[T2] compare(TestData(p1, p2), TestData(p11, p2)) shouldBe DiffResultObject( "TestData", Map("p1" -> DiffResultValue(p1, p11), "p2" -> Identical(p2)) ) } private def compare[T](t1: T, t2: T)(implicit d: Diff[T]) = d.apply(t1, t2) } sealed trait T1 sealed trait T2 case class TestData(p1: Int @@ T1, p2: Int @@ T2)
Example 170
Source File: DiffMatcherTest.scala From diffx with Apache License 2.0 | 5 votes |
package com.softwaremill.diffx.scalatest import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class DiffMatcherTest extends AnyFlatSpec with Matchers with DiffMatcher { val right: Foo = Foo( Bar("asdf", 5, Map("a" -> 2)), List(123, 1234), Some(Bar("asdf", 5, Map("a" -> 2))) ) val left: Foo = Foo( Bar("asdf", 66, Map("b" -> 3)), List(1234), Some(right) ) ignore should "work" in { left should matchTo(right) } } sealed trait Parent case class Bar(s: String, i: Int, ss: Map[String, Int]) extends Parent case class Foo(bar: Bar, b: List[Int], parent: Option[Parent]) extends Parent
Example 171
Source File: IgnoreMacroTest.scala From diffx with Apache License 2.0 | 5 votes |
package com.softwaremill.diffx import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class IgnoreMacroTest extends AnyFlatSpec with Matchers { "IgnoreMacroTest" should "ignore field in nested products" in { IgnoreMacro.ignoredFromPath[Family, String](_.first.name) shouldBe List("first", "name") } it should "ignore fields in list of products" in { IgnoreMacro.ignoredFromPath[Organization, String](_.people.each.name) shouldBe List("people", "name") } it should "ignore fields in product wrapped with either" in { IgnoreMacro.ignoredFromPath[Either[Person, Person], String](_.eachRight.name) shouldBe List("name") IgnoreMacro.ignoredFromPath[Either[Person, Person], String](_.eachLeft.name) shouldBe List("name") } it should "ignore fields in product wrapped with option" in { IgnoreMacro.ignoredFromPath[Option[Person], String](_.each.name) shouldBe List("name") } it should "ignore fields in map of products" in { IgnoreMacro.ignoredFromPath[Map[String, Person], String](_.each.name) shouldBe List("name") } }
Example 172
Source File: DiffIgnoreIntTest.scala From diffx with Apache License 2.0 | 5 votes |
package com.softwaremill.diffx import java.time.Instant import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class DiffIgnoreIntTest extends AnyFlatSpec with Matchers { val instant: Instant = Instant.now() val p1 = Person("p1", 22, instant) val p2 = Person("p2", 11, instant) it should "allow importing and exporting implicits" in { implicit val d: Diff[Person] = Derived[Diff[Person]].value.ignore(_.name) compare(p1, p2) shouldBe DiffResultObject( "Person", Map("name" -> Identical("p1"), "age" -> DiffResultValue(22, 11), "in" -> Identical(instant)) ) } it should "allow importing and exporting implicits using macro on derived instance" in { implicit val d: Diff[Person] = Derived[Diff[Person]].ignore(_.name) compare(p1, p2) shouldBe DiffResultObject( "Person", Map("name" -> Identical("p1"), "age" -> DiffResultValue(22, 11), "in" -> Identical(instant)) ) } it should "allow calling ignore multiple times" in { implicit val d: Diff[Person] = Derived[Diff[Person]].ignore[Person, String](_.name).ignore[Person, Int](_.age) compare(p1, p2) shouldBe Identical(p1) } }
Example 173
Source File: TensorFlowSpec.scala From tensorflow_scala with Apache License 2.0 | 5 votes |
package org.platanios.tensorflow.jni import org.scalatest.flatspec.AnyFlatSpec class TensorFlowSpec extends AnyFlatSpec { "The TensorFlow library version" must "have non-zero length" in { assert(TensorFlow.version.length > 0) } "The TensorFlow library data type sizes" must "be correct" in { assert(TensorFlow.dataTypeSize(-1) === 0) assert(TensorFlow.dataTypeSize(0) === 0) assert(TensorFlow.dataTypeSize(1) === 4) assert(TensorFlow.dataTypeSize(2) === 8) assert(TensorFlow.dataTypeSize(3) === 4) assert(TensorFlow.dataTypeSize(4) === 1) assert(TensorFlow.dataTypeSize(5) === 2) assert(TensorFlow.dataTypeSize(6) === 1) assert(TensorFlow.dataTypeSize(7) === 0) assert(TensorFlow.dataTypeSize(8) === 8) assert(TensorFlow.dataTypeSize(9) === 8) assert(TensorFlow.dataTypeSize(10) === 1) assert(TensorFlow.dataTypeSize(11) === 1) assert(TensorFlow.dataTypeSize(12) === 1) assert(TensorFlow.dataTypeSize(13) === 4) assert(TensorFlow.dataTypeSize(14) === 2) assert(TensorFlow.dataTypeSize(15) === 2) assert(TensorFlow.dataTypeSize(16) === 2) assert(TensorFlow.dataTypeSize(17) === 2) assert(TensorFlow.dataTypeSize(18) === 16) assert(TensorFlow.dataTypeSize(19) === 2) assert(TensorFlow.dataTypeSize(20) === 0) assert(TensorFlow.dataTypeSize(101) === 0) assert(TensorFlow.dataTypeSize(102) === 0) assert(TensorFlow.dataTypeSize(103) === 0) assert(TensorFlow.dataTypeSize(104) === 0) assert(TensorFlow.dataTypeSize(105) === 0) assert(TensorFlow.dataTypeSize(106) === 0) assert(TensorFlow.dataTypeSize(107) === 0) assert(TensorFlow.dataTypeSize(108) === 0) assert(TensorFlow.dataTypeSize(109) === 0) assert(TensorFlow.dataTypeSize(110) === 0) assert(TensorFlow.dataTypeSize(111) === 0) assert(TensorFlow.dataTypeSize(112) === 0) assert(TensorFlow.dataTypeSize(113) === 0) assert(TensorFlow.dataTypeSize(114) === 0) assert(TensorFlow.dataTypeSize(115) === 0) assert(TensorFlow.dataTypeSize(116) === 0) assert(TensorFlow.dataTypeSize(117) === 0) assert(TensorFlow.dataTypeSize(118) === 0) assert(TensorFlow.dataTypeSize(119) === 0) assert(TensorFlow.dataTypeSize(120) === 0) assert(TensorFlow.dataTypeSize(121) === 0) assert(TensorFlow.dataTypeSize(167) === 0) } }
Example 174
Source File: VariableSpec.scala From tensorflow_scala with Apache License 2.0 | 5 votes |
package org.platanios.tensorflow.api.ops import org.platanios.tensorflow.api._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class VariableSpec extends AnyFlatSpec with Matchers { "Variable creation" must "work" in { val graph = Graph() tf.createWith(graph = graph) { val initializer = tf.ConstantInitializer(Tensor(Tensor(2, 3))) val variable = tf.variable[Long]("variable", Shape(1, 2), initializer) assert(variable.dataType == INT64) assert(graph.getCollection(Graph.Keys.GLOBAL_VARIABLES).contains(variable)) assert(graph.getCollection(Graph.Keys.TRAINABLE_VARIABLES).contains(variable)) val session = Session(graph = graph) session.run(targets = Set(variable.initializer)) val outputs = session.run(fetches = variable.value) val expectedResult = Tensor[Long](Tensor(2, 3)) assert(outputs(0, 0).scalar == expectedResult(0, 0).scalar) assert(outputs(0, 1).scalar == expectedResult(0, 1).scalar) session.close() } graph.close() } "Variable assignment" must "work" in { val graph = Graph() tf.createWith(graph = graph) { val a = tf.constant(Tensor(Tensor(5L, 7L)), name = "A") val initializer = tf.ConstantInitializer(Tensor(Tensor(2, 3))) val variable = tf.variable[Long]("variable", Shape(1, 2), initializer) val variableAssignment = variable.assign(a) assert(variable.dataType == INT64) assert(graph.getCollection(Graph.Keys.GLOBAL_VARIABLES).contains(variable)) assert(graph.getCollection(Graph.Keys.TRAINABLE_VARIABLES).contains(variable)) val session = Session(graph = graph) session.run(targets = Set(variable.initializer)) session.run(targets = Set(variableAssignment)) val output = session.run(fetches = variable.value) val expectedResult = Tensor[Long](Tensor(5, 7)) assert(output(0, 0).scalar == expectedResult(0, 0).scalar) assert(output(0, 1).scalar == expectedResult(0, 1).scalar) session.close() } graph.close() } }
Example 175
Source File: GradientDescentSpec.scala From tensorflow_scala with Apache License 2.0 | 5 votes |
package org.platanios.tensorflow.api.ops.training.optimizers import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.ops.variables.Variable import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class GradientDescentSpec extends AnyFlatSpec with Matchers { "Gradient descent" must "work for dense updates to resource-based variables" in { val value0 = Tensor[Double](1.0, 2.0) val value1 = Tensor[Double](3.0, 4.0) val updatedValue0 = Tensor[Double](1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1) val updatedValue1 = Tensor[Double](3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01) val graph = Graph() val (variable0, variable1, gdOp) = tf.createWith(graph) { val variable0 = tf.variable[Double]("v0", Shape(2), tf.ConstantInitializer(Tensor(1, 2))) val variable1 = tf.variable[Double]("v1", Shape(2), tf.ConstantInitializer(Tensor(3, 4))) val gradient0 = tf.constant(Tensor[Double](0.1, 0.1)) val gradient1 = tf.constant(Tensor[Double](0.01, 0.01)) val gdOp = GradientDescent(3.0f).applyGradients(Seq( (gradient0, variable0.asInstanceOf[Variable[Any]]), (gradient1, variable1.asInstanceOf[Variable[Any]]))) (variable0.value, variable1.value, gdOp) } val session = Session(graph) session.run(targets = graph.trainableVariablesInitializer()) var variable0Value = session.run(fetches = variable0) var variable1Value = session.run(fetches = variable1) // TODO: !!! ??? [TENSORS] // assert(variable0Value === value0 +- 1e-6) // assert(variable1Value === value1 +- 1e-6) session.run(targets = gdOp) variable0Value = session.run(fetches = variable0) variable1Value = session.run(fetches = variable1) // assert(variable0Value === updatedValue0 +- 1e-6) // assert(variable1Value === updatedValue1 +- 1e-6) } }
Example 176
Source File: SessionSpec.scala From tensorflow_scala with Apache License 2.0 | 5 votes |
package org.platanios.tensorflow.api.core import org.platanios.tensorflow.api._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class SessionSpec extends AnyFlatSpec with Matchers { "Session run fetch by name" should "return the correct result" in { val graph = Graph() tf.createWith(graph = graph) { val a = tf.constant(Tensor(Tensor(2, 3)), name = "A") val x = tf.placeholder[Int](Shape(1, 2), name = "X") tf.subtract(tf.constant(1), tf.matmul(a = a, b = x, transposeB = true), name = "Y") } val session = Session(graph = graph) val feeds = Map(graph.getOutputByName("X:0").asInstanceOf[Output[Int]] -> Tensor(Tensor(5, 7))) val fetches = graph.getOutputByName("Y:0").asInstanceOf[Output[Int]] val output = session.run(feeds, fetches) val expectedResult = Tensor(Tensor(-30)) assert(output.scalar == expectedResult.scalar) graph.close() } }
Example 177
Source File: CirceConfigLaws.scala From circe-config with Apache License 2.0 | 5 votes |
package io.circe.config import cats.instances.either._ import cats.laws._ import cats.laws.discipline._ import io.circe.{Decoder, Json, Parser, ParsingFailure} import io.circe.testing.ParserTests import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.Checkers import org.scalacheck.{Arbitrary, Prop} import org.typelevel.discipline.Laws import com.typesafe.config.{parser => _, _} class CirceConfigLaws extends AnyFlatSpec { implicit val arbitraryConfigJson: Arbitrary[Json] = Arbitrary { def normalize(json: Json): Json = json.mapObject(_.filterKeys(_.nonEmpty).mapValues(normalize)).mapArray(_.map(normalize)).mapNumber { number => // Lower the precision to the types used internally by // Lightbend Config to ensure that numbers are representable. val double: java.lang.Double = number.toDouble val long: java.lang.Long = double.toLong val json = if (double.isInfinite) // While +/+Infinity can be represented, it cannot be round-tripped. Json.fromInt(42) else if (long == double) // Emulate Lightbend Config's internal cast: // https://github.com/lightbend/config/blob/v1.3.4/config/src/main/java/com/typesafe/config/impl/ConfigNumber.java#L96-L104 Json.fromLong(long) else Json.fromDouble(double).get json.asNumber.get } for (jsonObject <- io.circe.testing.instances.arbitraryJsonObject.arbitrary) yield normalize(Json.fromJsonObject(jsonObject)) } def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach { case ((id, prop), 0) => name should s"obey $id" in Checkers.check(prop) case ((id, prop), _) => it should s"obey $id" in Checkers.check(prop) } checkLaws("Parser", ParserTests(parser).fromString) checkLaws( "Parser", ParserTests(parser).fromFunction[Config]("fromConfig")( ConfigFactory.parseString, _.parse, _.decode[Json], _.decodeAccumulating[Json] ) ) checkLaws("Printer", PrinterTests(parser).fromJson) checkLaws("Codec", CodecTests[Config](syntax.configDecoder, parser.parse).fromFunction("fromConfig")) } case class PrinterTests(parser: Parser) extends Laws { def fromJson(implicit A: Arbitrary[Json]): RuleSet = new DefaultRuleSet( name = "printer", parent = None, "roundTrip" -> Prop.forAll { (json: Json) => parser.parse(printer.print(json)) <-> Right(json) } ) } case class CodecTests[A](decoder: Decoder[A], parse: A => Either[ParsingFailure, Json]) extends Laws { def fromFunction(name: String)(implicit arbitraryJson: Arbitrary[Json]): RuleSet = new DefaultRuleSet( name = s"codec[$name]", parent = None, "decodingRoundTrip" -> Prop.forAll { (json: Json) => decoder.decodeJson(json).flatMap(parse) <-> Right(json) } ) }
Example 178
Source File: CirceSuite.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras import cats.instances._ import cats.syntax._ import io.circe.testing.{ ArbitraryInstances, EqInstances } import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.{ Checkers, ScalaCheckDrivenPropertyChecks } import org.typelevel.discipline.Laws import scala.language.implicitConversions trait CirceSuite extends AnyFlatSpec with ScalaCheckDrivenPropertyChecks with AllInstances with AllInstancesBinCompat0 with AllInstancesBinCompat1 with AllInstancesBinCompat2 with AllInstancesBinCompat3 with AllInstancesBinCompat4 with AllInstancesBinCompat5 with AllInstancesBinCompat6 with AllSyntax with AllSyntaxBinCompat0 with AllSyntaxBinCompat1 with AllSyntaxBinCompat2 with AllSyntaxBinCompat3 with AllSyntaxBinCompat4 with AllSyntaxBinCompat5 with AllSyntaxBinCompat6 with ArbitraryInstances with EqInstances { override def convertToEqualizer[T](left: T): Equalizer[T] = sys.error("Intentionally ambiguous implicit for Equalizer") implicit def prioritizedCatsSyntaxEither[A, B](eab: Either[A, B]): EitherOps[A, B] = new EitherOps(eab) def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach { case ((id, prop), 0) => name should s"obey $id" in Checkers.check(prop) case ((id, prop), _) => it should s"obey $id" in Checkers.check(prop) } }
Example 179
Source File: ParquetIOTest.scala From ratatool with Apache License 2.0 | 5 votes |
package com.spotify.ratatool.io import java.io.{ByteArrayInputStream, ByteArrayOutputStream, File} import java.nio.file.Files import com.spotify.ratatool.Schemas import com.spotify.ratatool.avro.specific.TestRecord import com.spotify.ratatool.scalacheck._ import org.apache.commons.io.FileUtils import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ParquetIOTest extends AnyFlatSpec with Matchers { private val genericSchema = Schemas.avroSchema private val genericGen = genericRecordOf(genericSchema) private val genericData = (1 to 100).flatMap(_ => genericGen.sample) private val specificSchema = TestRecord.getClassSchema private val specificGen = specificRecordOf[TestRecord] private val specificData = (1 to 100).flatMap(_ => specificGen.sample) "ParquetIO" should "work with generic record and stream" in { val out = new ByteArrayOutputStream() ParquetIO.writeToOutputStream(genericData, genericSchema, out) val in = new ByteArrayInputStream(out.toByteArray) val result = ParquetIO.readFromInputStream(in).toList result should equal (genericData) } it should "work with generic record and file" in { val dir = Files.createTempDirectory("ratatool-") val file = new File(dir.toString, "temp.parquet") ParquetIO.writeToFile(genericData, genericSchema, file) val result = ParquetIO.readFromFile(file).toList result should equal (genericData) FileUtils.deleteDirectory(dir.toFile) } it should "work with specific record and stream" in { val out = new ByteArrayOutputStream() ParquetIO.writeToOutputStream(specificData, specificSchema, out) val in = new ByteArrayInputStream(out.toByteArray) val result = ParquetIO.readFromInputStream[TestRecord](in).toList result.map(FixRandomData(_)) should equal (specificData.map(FixRandomData(_))) } it should "work with specific record and file" in { val dir = Files.createTempDirectory("ratatool-") val file = new File(dir.toString, "temp.parquet") ParquetIO.writeToFile(specificData, specificSchema, file) val result = ParquetIO.readFromFile[TestRecord](file).toList result.map(FixRandomData(_)) should equal (specificData.map(FixRandomData(_))) FileUtils.deleteDirectory(dir.toFile) } }
Example 180
Source File: DirectSamplerParserTest.scala From ratatool with Apache License 2.0 | 5 votes |
package com.spotify.ratatool.tool import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class DirectSamplerParserTest extends AnyFlatSpec with Matchers { private def parse(cmd: String) = DirectSamplerParser.parse(cmd.split(" ")) private val config = DirectSamplerConfig(in = "in", out = "out", n = 1000) "ToolParser" should "parse avro command" in { val c = config.copy(mode = "avro") parse("avro --in in --out out -n 1000") should equal (Some(c)) parse("avro --in in --out out -n 1000 --head") should equal (Some(c.copy(head = true))) } it should "parse bigquery command" in { val c = config.copy(mode = "bigquery") parse("bigquery --in in --out out -n 1000") should equal (None) parse("bigquery --in in --out out -n 1000 --head") should equal (Some(c.copy(head = true))) parse("bigquery --in in --out out -n 1000 --head --tableOut table:out ") should equal ( Some(c.copy(head = true, tableOut = "table:out"))) } }
Example 181
Source File: AvroSamplerTest.scala From ratatool with Apache License 2.0 | 5 votes |
package com.spotify.ratatool.samplers import java.io.File import java.nio.file.Files import com.spotify.ratatool.Schemas import com.spotify.ratatool.io.AvroIO import com.spotify.ratatool.scalacheck._ import org.scalacheck.Gen import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class AvroSamplerTest extends AnyFlatSpec with Matchers with BeforeAndAfterAllConfigMap { val schema = Schemas.avroSchema val data1 = Gen.listOfN(40000, genericRecordOf(schema)).sample.get val data2 = Gen.listOfN(10000, genericRecordOf(schema)).sample.get val dir = Files.createTempDirectory("ratatool-") val file1 = new File(dir.toString, "part-00000.avro") val file2 = new File(dir.toString, "part-00001.avro") val dirWildcard = new File(dir.toString, "*.avro") override protected def beforeAll(configMap: ConfigMap): Unit = { AvroIO.writeToFile(data1, schema, file1) AvroIO.writeToFile(data2, schema, file2) dir.toFile.deleteOnExit() file1.deleteOnExit() file2.deleteOnExit() } "AvroSampler" should "support single file in head mode" in { val result = new AvroSampler(file1.getAbsolutePath).sample(10, head = true) result.size shouldBe 10 result should equal (data1.take(10)) } it should "support single file in random mode" in { val result = new AvroSampler(file1.getAbsolutePath).sample(10, head = false) result.size shouldBe 10 result.forall(data1.contains(_)) shouldBe true } it should "support multiple files in head mode" in { val result = new AvroSampler(dirWildcard.getAbsolutePath).sample(10, head = true) result.size shouldBe 10 result should equal (data1.take(10)) } it should "support multiple files in random mode" in { val result = new AvroSampler(dirWildcard.getAbsolutePath).sample(10, head = false) result.size shouldBe 10 result.exists(data1.contains(_)) shouldBe true result.exists(data2.contains(_)) shouldBe true result.forall(data1.contains(_)) shouldBe false result.forall(data2.contains(_)) shouldBe false data1.count(result.contains(_)) should be > data2.count(result.contains(_)) } }
Example 182
Source File: AvroIOTest.scala From ratatool with Apache License 2.0 | 5 votes |
package com.spotify.ratatool.io import java.io.{ByteArrayInputStream, ByteArrayOutputStream, File} import com.spotify.ratatool.Schemas import com.spotify.ratatool.avro.specific.TestRecord import org.apache.avro.generic.GenericRecord import com.spotify.ratatool.scalacheck._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class AvroIOTest extends AnyFlatSpec with Matchers { private val genericSchema = Schemas.avroSchema private val genericGen = genericRecordOf(genericSchema) private val genericData = (1 to 100).flatMap(_ => genericGen.sample) private val specificSchema = TestRecord.getClassSchema private val specificGen = specificRecordOf[TestRecord] private val specificData = (1 to 100).flatMap(_ => specificGen.sample) "AvroIO" should "work with generic record and stream" in { val out = new ByteArrayOutputStream() AvroIO.writeToOutputStream(genericData, genericSchema, out) val in = new ByteArrayInputStream(out.toByteArray) val result = AvroIO.readFromInputStream[GenericRecord](in).toList result should equal (genericData) } it should "work with generic record and file" in { val file = File.createTempFile("ratatool-", ".avro") file.deleteOnExit() AvroIO.writeToFile(genericData, genericSchema, file) val result = AvroIO.readFromFile[GenericRecord](file).toList result should equal (genericData) } it should "work with specific record and stream" in { val out = new ByteArrayOutputStream() AvroIO.writeToOutputStream(specificData, specificSchema, out) val in = new ByteArrayInputStream(out.toByteArray) val result = AvroIO.readFromInputStream[TestRecord](in).toList result.map(FixRandomData(_)) should equal (specificData.map(FixRandomData(_))) } it should "work with specific record and file" in { val file = File.createTempFile("ratatool-", ".avro") file.deleteOnExit() AvroIO.writeToFile(specificData, specificSchema, file) val result = AvroIO.readFromFile[TestRecord](file).toList result.map(FixRandomData(_)) should equal (specificData.map(FixRandomData(_))) } }
Example 183
Source File: TableRowJsonIOTest.scala From ratatool with Apache License 2.0 | 5 votes |
package com.spotify.ratatool.io import java.io.{ByteArrayInputStream, ByteArrayOutputStream, File} import com.spotify.ratatool.Schemas import com.spotify.ratatool.scalacheck._ import org.scalacheck.Gen import scala.jdk.CollectionConverters._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class TableRowJsonIOTest extends AnyFlatSpec with Matchers { private def floatGen = Gen.choose[Float](0.0F, 1.0F) private val schema = Schemas.tableSchema private val data = Gen.listOfN(100, tableRowOf(schema) .amend(Gen.oneOf( Gen.const(null), floatGen ))(_.getRecord("nullable_fields").set("float_field")) .amend(floatGen)(_.getRecord("required_fields").set("float_field")) .amend(Gen.nonEmptyListOf(floatGen) .map(_.asJava) )(_.getRecord("repeated_fields").set("float_field")) ).sample.get "TableRowJsonIO" should "work with stream" in { val out = new ByteArrayOutputStream() TableRowJsonIO.writeToOutputStream(data, out) val in = new ByteArrayInputStream(out.toByteArray) val result = TableRowJsonIO.readFromInputStream(in).toList.map(_.toString) result should equal (data.map(_.toString)) } it should "work with file" in { val file = File.createTempFile("ratatool-", ".json") file.deleteOnExit() TableRowJsonIO.writeToFile(data, file) val result = TableRowJsonIO.readFromFile(file).toList.map(_.toString) result should equal (data.map(_.toString)) } }
Example 184
Source File: CaseClassDiffyTest.scala From ratatool with Apache License 2.0 | 5 votes |
package com.spotify.ratatool.shapeless import com.spotify.ratatool.diffy.{Delta, NumericDelta, StringDelta, UnknownDelta} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class CaseClassDiffyTest extends AnyFlatSpec with Matchers { case class Foo(f1: String, f2: Int, f3: Long, f4: Seq[Double], f5: Seq[String]) case class Bar(b1: Double, b2: Foo) val f1 = Foo("foo1", 1, 3L, Seq(1,3), Seq("foo1")) val f2 = f1.copy(f1 = "foo2", f4 = Seq(1,2), f5 = Seq("foo2")) val b1 = Bar(1, f1) val b2 = Bar(2, f2) val dFoo = new CaseClassDiffy[Foo] val dBar = new CaseClassDiffy[Bar] val ignoreSet = Set("f2") val dFooWithIgnore = new CaseClassDiffy[Foo](ignore = ignoreSet) val dBarWithIgnore = new CaseClassDiffy[Bar](ignore = ignoreSet) "CaseClassDiffy" should "support primitive fields" in { val result = dFoo.apply(f1, f2) result should contain (Delta("f1", Option("foo1"), Option("foo2"), StringDelta(1.0))) result should contain (Delta("f2", Option(1), Option(1), NumericDelta(0.0))) result should contain (Delta("f3", Option(3), Option(3), NumericDelta(0.0))) result should contain (Delta("f5", Option(Vector("foo1")), Option(Vector("foo2")), UnknownDelta)) } "CaseClassDiffy" should "support nested fields" in { val result = dBar.apply(b1, b2) result should contain (Delta("b1", Option(1), Option(2), NumericDelta(1.0))) result should contain (Delta("b2.f1", Option("foo1"), Option("foo2"), StringDelta(1.0))) result should contain (Delta("b2.f2", Option(1), Option(1), NumericDelta(0.0))) result should contain (Delta("b2.f3", Option(3), Option(3), NumericDelta(0.0))) result should contain (Delta("b2.f5", Option(Vector("foo1")), Option(Vector("foo2")), UnknownDelta)) } "CaseClassDiffy" should "support ignore with exact match case" in { val result = dFooWithIgnore.apply(f1, f2) result.map(_.field) shouldNot contain ("f2") result should contain (Delta("f1", Option("foo1"), Option("foo2"), StringDelta(1.0))) result should contain (Delta("f3", Option(3), Option(3), NumericDelta(0.0))) result should contain (Delta("f5", Option(Vector("foo1")), Option(Vector("foo2")), UnknownDelta)) } "CaseClassDiffy" should "support ignore with nested field case" in { val result = dBarWithIgnore.apply(b1, b2) result.map(_.field) shouldNot contain ("f2") result should contain (Delta("b1", Option(1), Option(2), NumericDelta(1.0))) result should contain (Delta("b2.f1", Option("foo1"), Option("foo2"), StringDelta(1.0))) result should contain (Delta("b2.f3", Option(3), Option(3), NumericDelta(0.0))) result should contain (Delta("b2.f5", Option(Vector("foo1")), Option(Vector("foo2")), UnknownDelta)) } }
Example 185
Source File: ScheduleBucketSpec.scala From aecor with MIT License | 5 votes |
package aecor.tests import java.time._ import aecor.data.Folded import aecor.schedule.ScheduleEvent.{ ScheduleEntryAdded, ScheduleEntryFired } import aecor.schedule.{ DefaultScheduleBucket, ScheduleState } import cats.Id import cats.data.Chain import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec class ScheduleBucketSpec extends AnyFlatSpec with Matchers with StrictCatsEquality { val clock = Clock.fixed(Instant.now, ZoneId.systemDefault()) val aggregate = DefaultScheduleBucket.behavior[Id](ZonedDateTime.now(clock)).actions "ScheduleBucket" should "fire entry when due date is before now" in { val handler = aggregate.addScheduleEntry( "entryId", "correlation", LocalDateTime.now(clock).minusSeconds(10) ) val Folded.Next((events, _)) = handler.run(ScheduleState.fold) assert( events === Chain( ScheduleEntryAdded( "entryId", "correlation", LocalDateTime.now(clock).minusSeconds(10), Instant.now(clock) ), ScheduleEntryFired("entryId", "correlation", Instant.now(clock)) ) ) } it should "not fire entry when due date is after now" in { val handler = aggregate.addScheduleEntry("entryId", "correlation", LocalDateTime.now(clock).plusSeconds(10)) val Folded.Next((events, _)) = handler.run(ScheduleState.fold) assert( events === Chain( ScheduleEntryAdded( "entryId", "correlation", LocalDateTime.now(clock).plusSeconds(10), Instant.now(clock) ) ) ) } }
Example 186
Source File: ComposerSpec.scala From aecor with MIT License | 5 votes |
package aecor.tests import aecor.data.Composer import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec class ComposerSpec extends AnyFlatSpec with Matchers { val components = List("fo\\-o-", "bar---baz\\", "weww,--12321d''xqw\\xqw---") "Composer.WithSeparator" should "concatenate provided components" in { val separatedEncoder = Composer.WithSeparator('-') separatedEncoder.unapply(separatedEncoder(components)) should contain(components) } "Composer.WithLengthHint" should "concatenate provided components" in { val lengthHintedEncoder = Composer.WithLengthHint('=') lengthHintedEncoder.unapply(lengthHintedEncoder(components)) should contain(components) } }
Example 187
Source File: EventsourcedBehaviorSpec.scala From aecor with MIT License | 5 votes |
package aecor.tests import aecor.data._ import aecor.tests.e2e.{ CounterEvent, CounterState } import cats.implicits._ import org.scalatest.matchers.should.Matchers import org.scalatest.flatspec.AnyFlatSpec class EventsourcedBehaviorSpec extends AnyFlatSpec with Matchers { "EventsourcedBehavior.optional" should "correctly use init function applying events" in { val behavior: Fold[Folded, Option[CounterState], CounterEvent] = Fold.optional(e => CounterState(0L).applyEvent(e))(_.applyEvent(_)) behavior .reduce(behavior.initial, CounterEvent.CounterIncremented) .toOption .flatten shouldEqual CounterState(1).some } }
Example 188
Source File: GenericSerdeTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.kafka import com.sksamuel.avro4s.{BinaryFormat, DataFormat, JsonFormat} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers case class TheKafkaValue(name: String, location: String) class GenericSerdeTest extends AnyFlatSpec with Matchers { val someValue = TheKafkaValue("the name", "the location") "serialization with default binary avro format" should " be identical to binary format" in { val defaultSerde = new GenericSerde[TheKafkaValue]() val binarySerde = new GenericSerde[TheKafkaValue](BinaryFormat) defaultSerde.serialize("any-topic", someValue) shouldBe binarySerde.serialize("any-topic", someValue) } "round trip with default (binary) avro format" should "yield back original data" in { val defaultSerde = new GenericSerde[TheKafkaValue]() defaultSerde.deserialize( "any-topic", defaultSerde.serialize("any-topic", someValue) ) shouldBe someValue } "round trip with binary avro format" should "yield back original data" in { val binarySerde = new GenericSerde[TheKafkaValue](BinaryFormat) binarySerde.deserialize( "any-topic", binarySerde.serialize("any-topic", someValue) ) shouldBe someValue } "round trip with json avro format" should "yield back original data" in { val jsonSerde = new GenericSerde[TheKafkaValue](JsonFormat) jsonSerde.deserialize( "any-topic", jsonSerde.serialize("any-topic", someValue) ) shouldBe someValue } "round trip with data avro format" should "yield back original data" in { val dataSerde = new GenericSerde[TheKafkaValue](DataFormat) dataSerde.deserialize( "any-topic", dataSerde.serialize("any-topic", someValue) ) shouldBe someValue } }
Example 189
Source File: BigDecimalDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import com.sksamuel.avro4s._ import org.apache.avro.generic.GenericData import org.apache.avro.{Conversions, LogicalTypes, SchemaBuilder} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers case class WithBigDecimal(decimal: BigDecimal) case class OptionalBigDecimal(big: Option[BigDecimal]) class BigDecimalDecoderTest extends AnyFlatSpec with Matchers { "Decoder" should "convert byte array to decimal" in { val schema = AvroSchema[WithBigDecimal] val record = new GenericData.Record(schema) val bytes = new Conversions.DecimalConversion().toBytes(BigDecimal(123.45).bigDecimal, null, LogicalTypes.decimal(8, 2)) record.put("decimal", bytes) Decoder[WithBigDecimal].decode(record) shouldBe WithBigDecimal(BigDecimal(123.45)) } it should "support optional big decimals" in { val schema = AvroSchema[OptionalBigDecimal] val bytes = new Conversions.DecimalConversion().toBytes(BigDecimal(123.45).bigDecimal, null, LogicalTypes.decimal(8, 2)) val record = new GenericData.Record(schema) record.put("big", bytes) Decoder[OptionalBigDecimal].decode(record) shouldBe OptionalBigDecimal(Option(BigDecimal(123.45))) val emptyRecord = new GenericData.Record(schema) emptyRecord.put("big", null) Decoder[OptionalBigDecimal].decode(emptyRecord) shouldBe OptionalBigDecimal(None) } it should "be able to decode strings as bigdecimals" in { val schemaFor = BigDecimals.AsString Decoder[BigDecimal].withSchema(schemaFor).decode("123.45") shouldBe BigDecimal(123.45) } it should "be able to decode generic fixed as bigdecimals" in { val schemaFor = SchemaFor[BigDecimal]( LogicalTypes.decimal(10, 8).addToSchema(SchemaBuilder.fixed("BigDecimal").size(8)) ) val fixed = GenericData.get().createFixed(null, Array[Byte](0, 4, 98, -43, 55, 43, -114, 0), schemaFor.schema) Decoder[BigDecimal].withSchema(schemaFor).decode(fixed) shouldBe BigDecimal(12345678) } // it should "be able to decode longs as bigdecimals" in { // val schema = LogicalTypes.decimal(5, 2).addToSchema(SchemaBuilder.builder().longType()) // BigDecimalDecoder.decode(12345, schema) shouldBe "" // BigDecimalDecoder.decode(9999, schema) shouldBe "" // BigDecimalDecoder.decode(java.lang.Long.valueOf(99887766), schema) shouldBe "" // BigDecimalDecoder.decode(java.lang.Integer.valueOf(654), schema) shouldBe "" // } }
Example 190
Source File: DeletableTests.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.operation import cats.Applicative import cats.implicits._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.Utils._ import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.http4s.Status import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers trait DeletableTests[F[_], Resource <: { def metadata: Option[ObjectMeta] }, ResourceList <: { def items: Seq[Resource] }] extends AnyFlatSpec with Matchers with OptionValues with MinikubeClientProvider[F] { def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[F]): Deletable[F] def createChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Resource] def listNotContains(namespaceName: String, resourceNames: Seq[String], labels: Map[String, String] = Map.empty)( implicit client: KubernetesClient[F] ): F[ResourceList] def delete(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Status] = namespacedApi(namespaceName).delete(resourceName) "delete" should s"delete a $resourceName" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("delete-resource") _ <- createChecked(namespaceName, resourceName) _ <- delete(namespaceName, resourceName) _ <- retry(listNotContains(namespaceName, Seq(resourceName))) } yield () } it should "fail on non existing namespace" in usingMinikube { implicit client => for { status <- delete("non-existing", "non-existing") _ = status shouldBe Status.NotFound } yield () } it should s"fail on non existing $resourceName" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) status <- delete(namespaceName, "non-existing") _ = status shouldBe Status.NotFound } yield () } }
Example 191
Source File: GettableTests.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.operation import cats.Applicative import cats.implicits._ import com.goyeau.kubernetes.client.KubernetesClient import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.http4s.client.UnexpectedStatus import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers import scala.language.reflectiveCalls trait GettableTests[F[_], Resource <: { def metadata: Option[ObjectMeta] }] extends AnyFlatSpec with Matchers with OptionValues with MinikubeClientProvider[F] { def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[F]): Gettable[F, Resource] def createChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Resource] def getChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Resource] = for { resource <- namespacedApi(namespaceName).get(resourceName) _ = resource.metadata.value.namespace.value shouldBe namespaceName _ = resource.metadata.value.name.value shouldBe resourceName } yield resource "get" should s"get a $resourceName" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("some-resource-get") _ <- createChecked(namespaceName, resourceName) _ <- getChecked(namespaceName, resourceName) } yield () } it should "fail on non existing namespace" in intercept[UnexpectedStatus] { usingMinikube(implicit client => getChecked("non-existing", "non-existing")) } it should s"fail on non existing $resourceName" in intercept[UnexpectedStatus] { usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) _ <- getChecked(namespaceName, "non-existing") } yield () } } }
Example 192
Source File: ReplaceableTests.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.operation import cats.Applicative import cats.implicits._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.Utils.retry import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.http4s.Status import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Assertion, OptionValues} trait ReplaceableTests[F[_], Resource <: { def metadata: Option[ObjectMeta] }] extends AnyFlatSpec with Matchers with OptionValues with MinikubeClientProvider[F] { def namespacedApi(namespaceName: String)( implicit client: KubernetesClient[F] ): Replaceable[F, Resource] def createChecked(namespaceName: String, resourceName: String)( implicit client: KubernetesClient[F] ): F[Resource] def getChecked(namespaceName: String, resourceName: String)( implicit client: KubernetesClient[F] ): F[Resource] def sampleResource(resourceName: String, labels: Map[String, String] = Map.empty): Resource def modifyResource(resource: Resource): Resource def checkUpdated(updatedResource: Resource): Assertion def replace(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]) = for { resource <- getChecked(namespaceName, resourceName) status <- namespacedApi(namespaceName).replace(modifyResource(resource)) _ = status shouldBe Status.Ok } yield () "replace" should s"replace a $resourceName" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("some-resource") _ <- createChecked(namespaceName, resourceName) _ <- retry(replace(namespaceName, resourceName)) replaced <- getChecked(namespaceName, resourceName) _ = checkUpdated(replaced) } yield () } it should "fail on non existing namespace" in usingMinikube { implicit client => for { status <- namespacedApi("non-existing").replace( sampleResource("non-existing") ) _ = status should (equal(Status.NotFound).or( equal( Status.InternalServerError ) )) } yield () } it should s"fail on non existing $resourceName" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) status <- namespacedApi(namespaceName).replace( sampleResource("non-existing") ) _ = status should (equal(Status.NotFound).or( equal( Status.InternalServerError ) )) } yield () } }
Example 193
Source File: ListableTests.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.operation import cats.Applicative import cats.implicits._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.api.NamespacesApiTest import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.language.reflectiveCalls trait ListableTests[F[_], Resource <: { def metadata: Option[ObjectMeta] }, ResourceList <: { def items: Seq[Resource] }] extends AnyFlatSpec with Matchers with OptionValues with MinikubeClientProvider[F] { val resourceIsNamespaced = true def api(implicit client: KubernetesClient[F]): Listable[F, ResourceList] def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[F]): Listable[F, ResourceList] def createChecked(namespaceName: String, resourceName: String, labels: Map[String, String] = Map.empty)( implicit client: KubernetesClient[F] ): F[Resource] def listContains(namespaceName: String, resourceNames: Seq[String], labels: Map[String, String] = Map.empty)( implicit client: KubernetesClient[F] ): F[ResourceList] = for { resourceList <- namespacedApi(namespaceName).list(labels) _ = (resourceList.items.map(_.metadata.value.name.value) should contain).allElementsOf(resourceNames) } yield resourceList def listAllContains(resourceNames: Seq[String])( implicit client: KubernetesClient[F] ): F[ResourceList] = for { resourceList <- api.list() _ = (resourceList.items.map(_.metadata.value.name.value) should contain).allElementsOf(resourceNames) } yield resourceList def listNotContains(namespaceName: String, resourceNames: Seq[String], labels: Map[String, String] = Map.empty)( implicit client: KubernetesClient[F] ): F[ResourceList] = for { resourceList <- namespacedApi(namespaceName).list(labels) _ = (resourceList.items.map(_.metadata.value.name.value) should contain).noElementsOf(resourceNames) } yield resourceList "list" should s"list ${resourceName}s" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("list-resource") _ <- listNotContains(namespaceName, Seq(resourceName)) _ <- createChecked(namespaceName, resourceName) _ <- listContains(namespaceName, Seq(resourceName)) } yield () } "list" should s"list ${resourceName}s with a label" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) noLabelResourceName <- Applicative[F].pure("no-label-resource") _ <- createChecked(namespaceName, noLabelResourceName) withLabelResourceName <- Applicative[F].pure("label-resource") labels = Map("test" -> "1") _ <- createChecked(namespaceName, withLabelResourceName, labels) _ <- listNotContains(namespaceName, Seq(noLabelResourceName), labels) _ <- listContains(namespaceName, Seq(withLabelResourceName), labels) } yield () } it should s"list ${resourceName}s in all namespaces" in usingMinikube { implicit client => assume(resourceIsNamespaced) for { namespaceResourceNames <- Applicative[F].pure( (0 to 1).map(i => (s"${resourceName.toLowerCase}-$i", s"list-all-${resourceName.toLowerCase}-$i")) ) _ <- namespaceResourceNames.toList.traverse { case (namespaceName, resourceName) => NamespacesApiTest.createChecked[F](namespaceName) *> createChecked(namespaceName, resourceName) } _ <- listAllContains(namespaceResourceNames.map(_._2)) _ <- namespaceResourceNames.toList.traverse { case (namespaceName, _) => client.namespaces.delete(namespaceName) } } yield () } }
Example 194
Source File: DeletableTerminatedTests.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.operation import cats.Applicative import cats.implicits._ import com.goyeau.kubernetes.client.KubernetesClient import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.http4s.Status import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers trait DeletableTerminatedTests[F[_], Resource <: { def metadata: Option[ObjectMeta] }, ResourceList <: { def items: Seq[Resource] }] extends AnyFlatSpec with Matchers with OptionValues with MinikubeClientProvider[F] { def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[F]): DeletableTerminated[F] def createChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Resource] def listNotContains(namespaceName: String, resourceNames: Seq[String], labels: Map[String, String] = Map.empty)( implicit client: KubernetesClient[F] ): F[ResourceList] def deleteTerminated(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Status] = namespacedApi(namespaceName).deleteTerminated(resourceName) "deleteTerminated" should s"delete $resourceName and block until fully deleted" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("delete-terminated-resource") _ <- deleteTerminated(namespaceName, resourceName) _ <- listNotContains(namespaceName, Seq(resourceName)) } yield () } it should "fail on non existing namespace" in usingMinikube { implicit client => for { status <- deleteTerminated("non-existing", "non-existing") _ = status shouldBe Status.NotFound } yield () } it should s"fail on non existing $resourceName" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) status <- deleteTerminated(namespaceName, "non-existing") _ = status shouldBe Status.NotFound } yield () } }
Example 195
Source File: CreatableTests.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.operation import cats.Applicative import cats.implicits._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.Utils.retry import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.http4s.Status import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Assertion, OptionValues} trait CreatableTests[F[_], Resource <: { def metadata: Option[ObjectMeta] }] extends AnyFlatSpec with Matchers with OptionValues with MinikubeClientProvider[F] { def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[F]): Creatable[F, Resource] def getChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Resource] def sampleResource(resourceName: String, labels: Map[String, String] = Map.empty): Resource def modifyResource(resource: Resource): Resource def checkUpdated(updatedResource: Resource): Assertion def createChecked(namespaceName: String, resourceName: String)( implicit client: KubernetesClient[F] ): F[Resource] = createChecked(namespaceName, resourceName, Map.empty) def createChecked(namespaceName: String, resourceName: String, labels: Map[String, String])( implicit client: KubernetesClient[F] ): F[Resource] = { val resource = sampleResource(resourceName, labels) for { status <- namespacedApi(namespaceName).create(resource) _ = status shouldBe Status.Created resource <- getChecked(namespaceName, resourceName) } yield resource } "create" should s"create a $resourceName" in usingMinikube { implicit client => createChecked(resourceName.toLowerCase, "create-resource") } "createOrUpdate" should s"create a $resourceName" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName = "create-update-resource" status <- namespacedApi(namespaceName).createOrUpdate(sampleResource(resourceName)) _ = status shouldBe Status.Created _ <- getChecked(namespaceName, resourceName) } yield () } def createOrUpdate(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]) = for { resource <- getChecked(namespaceName, resourceName) status <- namespacedApi(namespaceName).createOrUpdate(modifyResource(resource)) _ = status shouldBe Status.Ok } yield () it should s"update a $resourceName already created" in usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("update-resource") _ <- createChecked(namespaceName, resourceName) _ <- retry(createOrUpdate(namespaceName, resourceName)) updatedResource <- getChecked(namespaceName, resourceName) _ = checkUpdated(updatedResource) } yield () } }
Example 196
Source File: JobsApiTest.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.api import cats.effect.{ConcurrentEffect, IO} import com.goyeau.kubernetes.client.operation._ import com.goyeau.kubernetes.client.KubernetesClient import io.chrisdavenport.log4cats.Logger import io.chrisdavenport.log4cats.slf4j.Slf4jLogger import io.k8s.api.batch.v1.{Job, JobList, JobSpec} import io.k8s.api.core.v1._ import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class JobsApiTest extends AnyFlatSpec with Matchers with OptionValues with CreatableTests[IO, Job] with GettableTests[IO, Job] with ListableTests[IO, Job, JobList] with ReplaceableTests[IO, Job] with DeletableTests[IO, Job, JobList] with DeletableTerminatedTests[IO, Job, JobList] with WatchableTests[IO, Job] with ContextProvider { implicit lazy val F: ConcurrentEffect[IO] = IO.ioConcurrentEffect implicit lazy val logger: Logger[IO] = Slf4jLogger.getLogger[IO] lazy val resourceName = classOf[Job].getSimpleName override def api(implicit client: KubernetesClient[IO]) = client.jobs override def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[IO]) = client.jobs.namespace(namespaceName) override def sampleResource(resourceName: String, labels: Map[String, String]) = Job( metadata = Option(ObjectMeta(name = Option(resourceName), labels = Option(labels))), spec = Option( JobSpec( template = PodTemplateSpec( metadata = Option(ObjectMeta(name = Option(resourceName))), spec = Option( PodSpec(containers = Seq(Container("test", image = Option("docker"))), restartPolicy = Option("Never")) ) ) ) ) ) val labels = Map("app" -> "test") override def modifyResource(resource: Job) = resource.copy( metadata = Option(ObjectMeta(name = resource.metadata.flatMap(_.name), labels = Option(labels))) ) override def checkUpdated(updatedResource: Job) = (updatedResource.metadata.value.labels.value.toSeq should contain).allElementsOf(labels.toSeq) override def deleteApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Deletable[IO] = client.jobs.namespace(namespaceName) override def watchApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Watchable[IO, Job] = client.jobs.namespace(namespaceName) }
Example 197
Source File: IngressesApiTest.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.api import cats.effect._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.operation._ import io.chrisdavenport.log4cats.Logger import io.chrisdavenport.log4cats.slf4j.Slf4jLogger import io.k8s.api.networking.v1beta1.{Ingress, IngressList, IngressRule, IngressSpec} import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class IngressesApiTest extends AnyFlatSpec with Matchers with OptionValues with CreatableTests[IO, Ingress] with GettableTests[IO, Ingress] with ListableTests[IO, Ingress, IngressList] with ReplaceableTests[IO, Ingress] with DeletableTests[IO, Ingress, IngressList] with WatchableTests[IO, Ingress] with ContextProvider { implicit lazy val F: ConcurrentEffect[IO] = IO.ioConcurrentEffect implicit lazy val logger: Logger[IO] = Slf4jLogger.getLogger[IO] lazy val resourceName = classOf[Ingress].getSimpleName override def api(implicit client: KubernetesClient[IO]) = client.ingresses override def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[IO]) = client.ingresses.namespace(namespaceName) override def sampleResource(resourceName: String, labels: Map[String, String]) = Ingress( metadata = Option(ObjectMeta(name = Option(resourceName), labels = Option(labels))), spec = Option( IngressSpec( rules = Some(Seq(IngressRule(Some("host")))) ) ) ) private val updatedHost: Option[IngressSpec] = Option( IngressSpec( rules = Some(Seq(IngressRule(Some("host2")))) ) ) override def modifyResource(resource: Ingress) = resource.copy( metadata = Option(ObjectMeta(name = resource.metadata.flatMap(_.name))), spec = updatedHost ) override def checkUpdated(updatedResource: Ingress) = updatedResource.spec should be( updatedHost ) override def deleteApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Deletable[IO] = client.ingresses.namespace(namespaceName) override def watchApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Watchable[IO, Ingress] = client.ingresses.namespace(namespaceName) }
Example 198
Source File: ServicesApiTest.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.api import cats.effect._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.operation._ import io.chrisdavenport.log4cats.Logger import io.chrisdavenport.log4cats.slf4j.Slf4jLogger import io.k8s.api.core.v1._ import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers class ServicesApiTest extends AnyFlatSpec with Matchers with OptionValues with CreatableTests[IO, Service] with GettableTests[IO, Service] with ListableTests[IO, Service, ServiceList] with ReplaceableTests[IO, Service] with DeletableTests[IO, Service, ServiceList] with WatchableTests[IO, Service] with ContextProvider { implicit lazy val F: ConcurrentEffect[IO] = IO.ioConcurrentEffect implicit lazy val logger: Logger[IO] = Slf4jLogger.getLogger[IO] lazy val resourceName = classOf[Service].getSimpleName override def api(implicit client: KubernetesClient[IO]) = client.services override def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[IO]) = client.services.namespace(namespaceName) override def sampleResource(resourceName: String, labels: Map[String, String]) = Service( metadata = Option(ObjectMeta(name = Option(resourceName), labels = Option(labels))), spec = Option(ServiceSpec(ports = Option(Seq(ServicePort(2000))))) ) val labels = Option(Map("test" -> "updated-label")) override def modifyResource(resource: Service) = resource.copy(metadata = resource.metadata.map(_.copy(labels = labels))) override def checkUpdated(updatedResource: Service) = updatedResource.metadata.value.labels shouldBe labels override def deleteApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Deletable[IO] = client.services.namespace(namespaceName) override def watchApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Watchable[IO, Service] = client.services.namespace(namespaceName) }
Example 199
Source File: DeploymentsApiTest.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.api import cats.effect.{ConcurrentEffect, IO} import com.goyeau.kubernetes.client.operation._ import com.goyeau.kubernetes.client.{IntValue, KubernetesClient, StringValue} import io.chrisdavenport.log4cats.Logger import io.chrisdavenport.log4cats.slf4j.Slf4jLogger import io.k8s.api.apps.v1._ import io.k8s.api.core.v1._ import io.k8s.apimachinery.pkg.apis.meta.v1.{LabelSelector, ObjectMeta} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers class DeploymentsApiTest extends AnyFlatSpec with Matchers with OptionValues with CreatableTests[IO, Deployment] with GettableTests[IO, Deployment] with ListableTests[IO, Deployment, DeploymentList] with ReplaceableTests[IO, Deployment] with DeletableTests[IO, Deployment, DeploymentList] with DeletableTerminatedTests[IO, Deployment, DeploymentList] with WatchableTests[IO, Deployment] with ContextProvider { implicit lazy val F: ConcurrentEffect[IO] = IO.ioConcurrentEffect implicit lazy val logger: Logger[IO] = Slf4jLogger.getLogger[IO] lazy val resourceName = classOf[Deployment].getSimpleName override def api(implicit client: KubernetesClient[IO]) = client.deployments override def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[IO]) = client.deployments.namespace(namespaceName) override def sampleResource(resourceName: String, labels: Map[String, String]) = { val label = Option(Map("app" -> "test")) Deployment( metadata = Option(ObjectMeta(name = Option(resourceName), labels = Option(labels))), spec = Option( DeploymentSpec( selector = LabelSelector(matchLabels = label), template = PodTemplateSpec( metadata = Option(ObjectMeta(name = Option(resourceName), labels = label)), spec = Option(PodSpec(containers = Seq(Container("test", image = Option("docker"))))) ) ) ) ) } val strategy = Option( DeploymentStrategy( `type` = Option("RollingUpdate"), rollingUpdate = Option(RollingUpdateDeployment(maxSurge = Option(StringValue("25%")), maxUnavailable = Option(IntValue(10)))) ) ) override def modifyResource(resource: Deployment) = resource.copy( metadata = Option(ObjectMeta(name = resource.metadata.flatMap(_.name))), spec = resource.spec.map(_.copy(strategy = strategy)) ) override def checkUpdated(updatedResource: Deployment) = updatedResource.spec.value.strategy shouldBe strategy override def deleteApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Deletable[IO] = client.deployments.namespace(namespaceName) override def watchApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Watchable[IO, Deployment] = client.deployments.namespace(namespaceName) }
Example 200
Source File: HorizontalPodAutoscalersApiTest.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.api import cats.effect._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.operation._ import io.chrisdavenport.log4cats.Logger import io.chrisdavenport.log4cats.slf4j.Slf4jLogger import io.k8s.api.autoscaling.v1.{ CrossVersionObjectReference, HorizontalPodAutoscaler, HorizontalPodAutoscalerList, HorizontalPodAutoscalerSpec } import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers class HorizontalPodAutoscalersApiTest extends AnyFlatSpec with Matchers with OptionValues with CreatableTests[IO, HorizontalPodAutoscaler] with GettableTests[IO, HorizontalPodAutoscaler] with ListableTests[IO, HorizontalPodAutoscaler, HorizontalPodAutoscalerList] with ReplaceableTests[IO, HorizontalPodAutoscaler] with DeletableTests[IO, HorizontalPodAutoscaler, HorizontalPodAutoscalerList] with WatchableTests[IO, HorizontalPodAutoscaler] with ContextProvider { implicit lazy val F: ConcurrentEffect[IO] = IO.ioConcurrentEffect implicit lazy val logger: Logger[IO] = Slf4jLogger.getLogger[IO] lazy val resourceName = classOf[HorizontalPodAutoscaler].getSimpleName override def api(implicit client: KubernetesClient[IO]) = client.horizontalPodAutoscalers override def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[IO]) = client.horizontalPodAutoscalers.namespace(namespaceName) override def sampleResource(resourceName: String, labels: Map[String, String]) = HorizontalPodAutoscaler( metadata = Option(ObjectMeta(name = Option(resourceName), labels = Option(labels))), spec = Option(HorizontalPodAutoscalerSpec(scaleTargetRef = CrossVersionObjectReference("kind", "name"), maxReplicas = 2)) ) val maxReplicas = 3 override def modifyResource(resource: HorizontalPodAutoscaler) = resource.copy( metadata = Option(ObjectMeta(name = resource.metadata.flatMap(_.name))), spec = resource.spec.map(_.copy(maxReplicas = maxReplicas)) ) override def checkUpdated(updatedResource: HorizontalPodAutoscaler) = updatedResource.spec.get.maxReplicas shouldBe maxReplicas override def deleteApi(namespaceName: String)(implicit client: KubernetesClient[IO]): Deletable[IO] = client.horizontalPodAutoscalers.namespace(namespaceName) override def watchApi( namespaceName: String )(implicit client: KubernetesClient[IO]): Watchable[IO, HorizontalPodAutoscaler] = client.horizontalPodAutoscalers.namespace(namespaceName) }