org.scalatest.matchers.must.Matchers Scala Examples
The following examples show how to use org.scalatest.matchers.must.Matchers.
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: RanCustomImpl.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package kan import cats.{Functor, Monad} import scala.language.higherKinds import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class RanCustomImpl extends AnyFunSpec with Matchers { describe("Right Kan extension implemented from Haskell definition") { def ranMonad[G[_]]: Monad[Ran3[G, G, ?]] = new Monad[Ran3[G, G, ?]] { override def map[A, B](fa: Ran3[G, G, A])(f: A => B): Ran3[G, G, B] = fa.map(f) override def flatMap[A, B](fa: Ran3[G, G, A])(f: A => Ran3[G, G, B]): Ran3[G, G, B] = flatten(map(fa)(f)) override def tailRecM[A, B](a: A)(f: A => Ran3[G, G, Either[A, B]]): Ran3[G, G, B] = ??? override def pure[A](x: A): Ran3[G, G, A] = new Ran3[G, G, A] { def runRan[C](f2: A => G[C]): G[C] = f2(x) } } } } }
Example 2
Source File: TypedStringIndexerTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless package ml package feature import frameless.ml.feature.TypedStringIndexer.HandleInvalid import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.Prop._ import shapeless.test.illTyped import org.scalatest.matchers.must.Matchers class TypedStringIndexerTests extends FramelessMlSuite with Matchers { test(".fit() returns a correct TypedTransformer") { def prop[A: TypedEncoder : Arbitrary] = forAll { x2: X2[String, A] => val indexer = TypedStringIndexer[X1[String]] val ds = TypedDataset.create(Seq(x2)) val model = indexer.fit(ds).run() val resultDs = model.transform(ds).as[X3[String, A, Double]] resultDs.collect.run() == Seq(X3(x2.a, x2.b, 0D)) } check(prop[Double]) check(prop[String]) } test("param setting is retained") { implicit val arbHandleInvalid: Arbitrary[HandleInvalid] = Arbitrary { Gen.oneOf(HandleInvalid.Keep, HandleInvalid.Error, HandleInvalid.Skip) } val prop = forAll { handleInvalid: HandleInvalid => val indexer = TypedStringIndexer[X1[String]] .setHandleInvalid(handleInvalid) val ds = TypedDataset.create(Seq(X1("foo"))) val model = indexer.fit(ds).run() model.transformer.getHandleInvalid == handleInvalid.sparkValue } check(prop) } test("create() compiles only with correct inputs") { illTyped("TypedStringIndexer.create[Double]()") illTyped("TypedStringIndexer.create[X1[Double]]()") illTyped("TypedStringIndexer.create[X2[String, Long]]()") } }
Example 3
Source File: KMeansTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless package ml package clustering import frameless.ml.classification.TypedKMeans import frameless.{TypedDataset, TypedEncoder, X1, X2, X3} import org.apache.spark.ml.linalg._ import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.Prop._ import frameless.ml._ import frameless.ml.params.kmeans.KMeansInitMode import org.scalatest.matchers.must.Matchers class KMeansTests extends FramelessMlSuite with Matchers { implicit val arbVector: Arbitrary[Vector] = Arbitrary(Generators.arbVector.arbitrary) implicit val arbKMeansInitMode: Arbitrary[KMeansInitMode] = Arbitrary{ Gen.oneOf( Gen.const(KMeansInitMode.KMeansPlusPlus), Gen.const(KMeansInitMode.Random) ) } test("fit() returns a correct TypedTransformer") { val prop = forAll { x1: X1[Vector] => val km = TypedKMeans[X1[Vector]] val ds = TypedDataset.create(Seq(x1)) val model = km.fit(ds).run() val pDs = model.transform(ds).as[X2[Vector, Int]] pDs.select(pDs.col('a)).collect().run().toList == Seq(x1.a) } def prop3[A: TypedEncoder : Arbitrary] = forAll { x2: X2[Vector, A] => val km = TypedKMeans[X1[Vector]] val ds = TypedDataset.create(Seq(x2)) val model = km.fit(ds).run() val pDs = model.transform(ds).as[X3[Vector, A, Int]] pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq((x2.a, x2.b)) } check(prop) check(prop3[Double]) } test("param setting is retained") { val prop = forAll { initMode: KMeansInitMode => val rf = TypedKMeans[X1[Vector]] .setInitMode(KMeansInitMode.Random) .setInitSteps(2) .setK(10) .setMaxIter(15) .setSeed(123223L) .setTol(12D) val ds = TypedDataset.create(Seq(X2(Vectors.dense(Array(0D)), 0))) val model = rf.fit(ds).run() model.transformer.getInitMode == KMeansInitMode.Random.sparkValue && model.transformer.getInitSteps == 2 && model.transformer.getK == 10 && model.transformer.getMaxIter == 15 && model.transformer.getSeed == 123223L && model.transformer.getTol == 12D } check(prop) } }
Example 4
Source File: BisectingKMeansTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless package ml package clustering import frameless.{TypedDataset, TypedEncoder, X1, X2, X3} import frameless.ml.classification.TypedBisectingKMeans import org.scalacheck.Arbitrary import org.apache.spark.ml.linalg._ import org.scalacheck.Prop._ import frameless.ml._ import org.scalatest.matchers.must.Matchers class BisectingKMeansTests extends FramelessMlSuite with Matchers { implicit val arbVector: Arbitrary[Vector] = Arbitrary(Generators.arbVector.arbitrary) test("fit() returns a correct TypedTransformer") { val prop = forAll { x1: X1[Vector] => val km = TypedBisectingKMeans[X1[Vector]]() val ds = TypedDataset.create(Seq(x1)) val model = km.fit(ds).run() val pDs = model.transform(ds).as[X2[Vector, Int]] pDs.select(pDs.col('a)).collect().run().toList == Seq(x1.a) } def prop3[A: TypedEncoder : Arbitrary] = forAll { x2: X2[Vector, A] => val km = TypedBisectingKMeans[X1[Vector]] val ds = TypedDataset.create(Seq(x2)) val model = km.fit(ds).run() val pDs = model.transform(ds).as[X3[Vector, A, Int]] pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq((x2.a, x2.b)) } check(prop) check(prop3[Double]) } test("param setting is retained") { val rf = TypedBisectingKMeans[X1[Vector]]() .setK(10) .setMaxIter(10) .setMinDivisibleClusterSize(1) .setSeed(123332) val ds = TypedDataset.create(Seq(X2(Vectors.dense(Array(0D)),0))) val model = rf.fit(ds).run() model.transformer.getK == 10 && model.transformer.getMaxIter == 10 && model.transformer.getMinDivisibleClusterSize == 1 && model.transformer.getSeed == 123332 } }
Example 5
Source File: TypedRandomForestClassifierTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless package ml package classification import shapeless.test.illTyped import org.apache.spark.ml.linalg._ import frameless.ml.params.trees.FeatureSubsetStrategy import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.Prop._ import org.scalatest.matchers.must.Matchers class TypedRandomForestClassifierTests extends FramelessMlSuite with Matchers { implicit val arbDouble: Arbitrary[Double] = Arbitrary(Gen.choose(1, 99).map(_.toDouble)) // num classes must be between 0 and 100 for the test implicit val arbVectorNonEmpty: Arbitrary[Vector] = Arbitrary(Generators.arbVector.arbitrary suchThat (_.size > 0)) // vector must not be empty for RandomForestClassifier import Generators.arbTreesFeaturesSubsetStrategy test("fit() returns a correct TypedTransformer") { val prop = forAll { x2: X2[Double, Vector] => val rf = TypedRandomForestClassifier[X2[Double, Vector]] val ds = TypedDataset.create(Seq(x2)) val model = rf.fit(ds).run() val pDs = model.transform(ds).as[X5[Double, Vector, Vector, Vector, Double]] pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b) } val prop2 = forAll { x2: X2[Vector, Double] => val rf = TypedRandomForestClassifier[X2[Vector, Double]] val ds = TypedDataset.create(Seq(x2)) val model = rf.fit(ds).run() val pDs = model.transform(ds).as[X5[Vector, Double, Vector, Vector, Double]] pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b) } def prop3[A: TypedEncoder: Arbitrary] = forAll { x3: X3[Vector, Double, A] => val rf = TypedRandomForestClassifier[X2[Vector, Double]] val ds = TypedDataset.create(Seq(x3)) val model = rf.fit(ds).run() val pDs = model.transform(ds).as[X6[Vector, Double, A, Vector, Vector, Double]] pDs.select(pDs.col('a), pDs.col('b), pDs.col('c)).collect.run() == Seq((x3.a, x3.b, x3.c)) } check(prop) check(prop2) check(prop3[String]) check(prop3[Double]) } test("param setting is retained") { val prop = forAll { featureSubsetStrategy: FeatureSubsetStrategy => val rf = TypedRandomForestClassifier[X2[Double, Vector]] .setNumTrees(10) .setMaxBins(100) .setFeatureSubsetStrategy(featureSubsetStrategy) .setMaxDepth(10) .setMaxMemoryInMB(100) .setMinInfoGain(0.1D) .setMinInstancesPerNode(2) .setSubsamplingRate(0.9D) val ds = TypedDataset.create(Seq(X2(0D, Vectors.dense(0D)))) val model = rf.fit(ds).run() model.transformer.getNumTrees == 10 && model.transformer.getMaxBins == 100 && model.transformer.getFeatureSubsetStrategy == featureSubsetStrategy.sparkValue && model.transformer.getMaxDepth == 10 && model.transformer.getMaxMemoryInMB == 100 && model.transformer.getMinInfoGain == 0.1D && model.transformer.getMinInstancesPerNode == 2 && model.transformer.getSubsamplingRate == 0.9D } check(prop) } test("create() compiles only with correct inputs") { illTyped("TypedRandomForestClassifier.create[Double]()") illTyped("TypedRandomForestClassifier.create[X1[Double]]()") illTyped("TypedRandomForestClassifier.create[X2[Double, Double]]()") illTyped("TypedRandomForestClassifier.create[X3[Vector, Double, Int]]()") illTyped("TypedRandomForestClassifier.create[X2[Vector, String]]()") } }
Example 6
Source File: ClassificationIntegrationTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless package ml package classification import frameless.ml.feature.{TypedIndexToString, TypedStringIndexer, TypedVectorAssembler} import org.apache.spark.ml.linalg.Vector import org.scalatest.matchers.must.Matchers class ClassificationIntegrationTests extends FramelessMlSuite with Matchers { test("predict field3 from field1 and field2 using a RandomForestClassifier") { case class Data(field1: Double, field2: Int, field3: String) // Training val trainingDataDs = TypedDataset.create(Seq.fill(10)(Data(0D, 10, "foo"))) case class Features(field1: Double, field2: Int) val vectorAssembler = TypedVectorAssembler[Features] case class DataWithFeatures(field1: Double, field2: Int, field3: String, features: Vector) val dataWithFeatures = vectorAssembler.transform(trainingDataDs).as[DataWithFeatures] case class StringIndexerInput(field3: String) val indexer = TypedStringIndexer[StringIndexerInput] val indexerModel = indexer.fit(dataWithFeatures).run() case class IndexedDataWithFeatures(field1: Double, field2: Int, field3: String, features: Vector, indexedField3: Double) val indexedData = indexerModel.transform(dataWithFeatures).as[IndexedDataWithFeatures] case class RFInputs(indexedField3: Double, features: Vector) val rf = TypedRandomForestClassifier[RFInputs] val model = rf.fit(indexedData).run() // Prediction val testData = TypedDataset.create(Seq( Data(0D, 10, "foo") )) val testDataWithFeatures = vectorAssembler.transform(testData).as[DataWithFeatures] val indexedTestData = indexerModel.transform(testDataWithFeatures).as[IndexedDataWithFeatures] case class PredictionInputs(features: Vector, indexedField3: Double) val testInput = indexedTestData.project[PredictionInputs] case class PredictionResultIndexed( features: Vector, indexedField3: Double, rawPrediction: Vector, probability: Vector, predictedField3Indexed: Double ) val predictionDs = model.transform(testInput).as[PredictionResultIndexed] case class IndexToStringInput(predictedField3Indexed: Double) val indexToString = TypedIndexToString[IndexToStringInput](indexerModel.transformer.labels) case class PredictionResult( features: Vector, indexedField3: Double, rawPrediction: Vector, probability: Vector, predictedField3Indexed: Double, predictedField3: String ) val stringPredictionDs = indexToString.transform(predictionDs).as[PredictionResult] val prediction = stringPredictionDs.select(stringPredictionDs.col('predictedField3)).collect.run().toList prediction mustEqual List("foo") } }
Example 7
Source File: TypedRandomForestRegressorTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless package ml package regression import frameless.ml.params.trees.FeatureSubsetStrategy import shapeless.test.illTyped import org.apache.spark.ml.linalg._ import org.scalacheck.Arbitrary import org.scalacheck.Prop._ import org.scalatest.matchers.must.Matchers class TypedRandomForestRegressorTests extends FramelessMlSuite with Matchers { implicit val arbVectorNonEmpty: Arbitrary[Vector] = Arbitrary(Generators.arbVector.arbitrary suchThat (_.size > 0)) // vector must not be empty for RandomForestRegressor import Generators.arbTreesFeaturesSubsetStrategy test("fit() returns a correct TypedTransformer") { val prop = forAll { x2: X2[Double, Vector] => val rf = TypedRandomForestRegressor[X2[Double, Vector]] val ds = TypedDataset.create(Seq(x2)) val model = rf.fit(ds).run() val pDs = model.transform(ds).as[X3[Double, Vector, Double]] pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b) } val prop2 = forAll { x2: X2[Vector, Double] => val rf = TypedRandomForestRegressor[X2[Vector, Double]] val ds = TypedDataset.create(Seq(x2)) val model = rf.fit(ds).run() val pDs = model.transform(ds).as[X3[Vector, Double, Double]] pDs.select(pDs.col('a), pDs.col('b)).collect.run() == Seq(x2.a -> x2.b) } def prop3[A: TypedEncoder: Arbitrary] = forAll { x3: X3[Vector, Double, A] => val rf = TypedRandomForestRegressor[X2[Vector, Double]] val ds = TypedDataset.create(Seq(x3)) val model = rf.fit(ds).run() val pDs = model.transform(ds).as[X4[Vector, Double, A, Double]] pDs.select(pDs.col('a), pDs.col('b), pDs.col('c)).collect.run() == Seq((x3.a, x3.b, x3.c)) } check(prop) check(prop2) check(prop3[String]) check(prop3[Double]) } test("param setting is retained") { val prop = forAll { featureSubsetStrategy: FeatureSubsetStrategy => val rf = TypedRandomForestRegressor[X2[Double, Vector]] .setNumTrees(10) .setMaxBins(100) .setFeatureSubsetStrategy(featureSubsetStrategy) .setMaxDepth(10) .setMaxMemoryInMB(100) .setMinInfoGain(0.1D) .setMinInstancesPerNode(2) .setSubsamplingRate(0.9D) val ds = TypedDataset.create(Seq(X2(0D, Vectors.dense(0D)))) val model = rf.fit(ds).run() model.transformer.getNumTrees == 10 && model.transformer.getMaxBins == 100 && model.transformer.getFeatureSubsetStrategy == featureSubsetStrategy.sparkValue && model.transformer.getMaxDepth == 10 && model.transformer.getMaxMemoryInMB == 100 && model.transformer.getMinInfoGain == 0.1D && model.transformer.getMinInstancesPerNode == 2 && model.transformer.getSubsamplingRate == 0.9D } check(prop) } test("create() compiles only with correct inputs") { illTyped("TypedRandomForestRegressor.create[Double]()") illTyped("TypedRandomForestRegressor.create[X1[Double]]()") illTyped("TypedRandomForestRegressor.create[X2[Double, Double]]()") illTyped("TypedRandomForestRegressor.create[X3[Vector, Double, Int]]()") illTyped("TypedRandomForestRegressor.create[X2[Vector, String]]()") } }
Example 8
Source File: Github415.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.github import java.io.{FileOutputStream, ObjectOutputStream} import com.sksamuel.avro4s.Encoder import com.sksamuel.avro4s.github.Github415.PlaybackSession import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.must.Matchers class Github415 extends AnyFunSuite with Matchers { test("github 415") { val fileOut = new FileOutputStream("remove_me") val out = new ObjectOutputStream(fileOut) out.writeObject(Encoder[PlaybackSession]) } } object Github415 { object Rebuffers { case class Metrics(count: Int) case class EarlyLate(early: Metrics) case class Stats(session: Option[EarlyLate]) } case class Rebuffers(network: Option[Rebuffers.Stats]) case class PlaybackSession(rebuffers: Option[Rebuffers]) }
Example 9
Source File: JvmMonitoringTest.scala From datadog4s with MIT License | 5 votes |
package com.avast.datadog4s.extension.jvm import java.time.Duration import cats.effect.{ ContextShift, IO, Timer } import com.avast.cloud.datadog4s.inmemory.MockMetricsFactory import com.avast.datadog4s.extension.jvm.JvmMonitoring.Config import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers import cats.syntax.flatMap._ import scala.concurrent.ExecutionContext import scala.concurrent.duration._ class JvmMonitoringTest extends AnyFlatSpec with Matchers { private val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global implicit val contextShift: ContextShift[IO] = cats.effect.IO.contextShift(ec) implicit val timer: Timer[IO] = IO.timer(ec) val noopErrHandler: Throwable => IO[Unit] = (_: Throwable) => IO.unit "JvmMonitoring" should "create all expected metrics and update them periodically" in { val testEffect = MockMetricsFactory.make[IO].flatMap { inmemory => val runTest = JvmMonitoring .configured(inmemory, Config().copy(delay = Duration.ofMillis(10)), noopErrHandler) .use(_ => IO.never) .timeout(100.millis) .attempt runTest >> inmemory.state.get } val result = testEffect.unsafeRunSync() result.keySet must equal(expectedAspects) result.values.foreach { vector => vector.groupBy(_.tags).foreach { case (_, records) => records.size must be > 0 records.size must be < 15 } } } val minorGcParams = if (System.getProperty("java.version").startsWith("1.8.")) Set.empty else Set("jvm.gc.minor_collection_time", "jvm.gc.minor_collection_count") val expectedAspects: Set[String] = Set( "jvm.cpu.load", "jvm.cpu.time", "jvm.filedescriptor.open", "jvm.heap_memory", "jvm.heap_memory_committed", "jvm.heap_memory_init", "jvm.heap_memory_max", "jvm.heap_memory.eden", "jvm.heap_memory.eden_committed", "jvm.heap_memory.eden_max", "jvm.heap_memory.survivor", "jvm.heap_memory.survivor_committed", "jvm.heap_memory.survivor_max", "jvm.heap_memory.old_gen", "jvm.heap_memory.old_gen_committed", "jvm.heap_memory.old_gen_max", "jvm.non_heap_memory", "jvm.non_heap_memory_committed", "jvm.non_heap_memory_init", "jvm.non_heap_memory_max", "jvm.non_heap_memory.code_cache", "jvm.non_heap_memory.code_cache_committed", "jvm.non_heap_memory.code_cache_max", "jvm.non_heap_memory.metaspace", "jvm.non_heap_memory.metaspace_committed", "jvm.non_heap_memory.metaspace_max", "jvm.non_heap_memory.compressed_class_space", "jvm.non_heap_memory.compressed_class_space_committed", "jvm.non_heap_memory.compressed_class_space_max", "jvm.uptime", "jvm.thread_count", "jvm.thread_daemon", "jvm.thread_started", "jvm.loaded_classes", "jvm.bufferpool.instances", "jvm.bufferpool.bytes", "jvm.gc.major_collection_time", "jvm.gc.major_collection_count" ) ++ minorGcParams }
Example 10
Source File: NameSpec.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema package swagger import io.circe.Encoder import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers import ru.tinkoff.tschema.swagger.OpenApi.Method import ru.tinkoff.tschema.syntax._ class NameSpec extends AnyFlatSpec { val swagger = MkSwagger(NameSpec.api).make() "renaming" should "change cases" in { val method = swagger.paths("/test-api/TEST/first")(Method.get) val params = method.parameters.map(_.name).toSet assert(method.tags === Vector("TestApi")) assert(params === Set("myparam", "foo")) } } object NameSpec { def api = kebab("TestApi").tagPrefix |> upper("test").groupPrefix |> snake("first").operation |> lower("MyParam").header[Int] |> renamed("foo", "bar").queryParam[String] |> get |> complete[String] }
Example 11
Source File: ReaderMonadSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package monad import scala.concurrent.duration.Duration import scala.concurrent.duration._ import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers case class Reader[A, B](run: A => B) { // B is changing and A is constant def map[C](f: B => C): Reader[A, C] = Reader(run andThen f) def flatMap[C](f: B => Reader[A, C]): Reader[A, C] = { // def attempt1: A => Reader[A, C] = a => f(run(a)) // def attempt2: A => (A => C) = (a:A) => f(run(a)).run def attempt3: A => C = (a:A) => { val b: B = run(a) val reader: Reader[A, C] = f(b) reader.run(a) } Reader(attempt3) } def flatten(r: Reader[A, Reader[A, B]]): Reader[A, B] = { // pass the context A to outer computation and inner computation def newRun: A => B = a => { val firstRun: Reader[A, B] = r.run(a) firstRun.run(a) } Reader(newRun) } } object Reader { def ask[A]: Reader[A, A] = Reader(identity) } class ReaderMonadSpec extends AnyFunSpec with Matchers { describe("Reader") { case class DbConfig(maxTimeout: Duration, jdbc: String, user: String, pass: String) val baseConfig = DbConfig(60.seconds, "jdbc://localhost:5432/db", "admin", "1234") type FindById = Int => String def getAllCustomerIds: DbConfig => List[Int] = _ => List(1, 42) // it pass the tests so who cares def getDefaultCustomer: DbConfig => FindById = conf => id => s"Johnny Bravo $id" it("produces something from configuration") { val reader: Reader[DbConfig, (Int => String)] = Reader(getDefaultCustomer) reader.run(baseConfig)(1) mustBe "Johnny Bravo 1" } it("is like Functor") { val reader: Reader[DbConfig, List[Int]] = Reader(getAllCustomerIds) reader.map(_.mkString(", ")).run(baseConfig) mustBe "1, 42" } } }
Example 12
Source File: TraverseEmptyListPermutationsSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package mtl import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class TraverseEmptyListPermutationsSpec extends AnyFunSpec with Matchers { describe("filterA") { it("compute all permutations of the lit if given List(true, false)") { import cats._ import cats.implicits._ val allPermutations = List( List(1, 2, 3), List(1, 2), List(1, 3), List(2, 3), List(1), List(2), List(3), Nil ) val result: List[List[Int]] = List(1, 2, 3).filterA(_ => List(true, false)) result contains theSameElementsAs (allPermutations) } } }
Example 13
Source File: ContravariantSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package contravariant import scalaz.Contravariant import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class ContravariantSpec extends AnyFunSpec with Matchers { case class Predicate[A](fun: A => Boolean) describe("Contravariant") { it("split complex Predicate into simpler + function - csutom contramap") { val lenAbove5 = Predicate[String](_.length > 5) lenAbove5.fun("123456") mustBe true // predicate val above5 = Predicate[Int](_ > 5) above5.fun(42) mustBe true // function val len: String => Int = _.length // way to combine them def contramap(pred: Predicate[Int], f: String => Int): Predicate[String] = Predicate[String](f andThen pred.fun) // yeach ! val pr = contramap(above5, len) pr.fun("123456") mustBe true } it("custom contramap for Predicate on Person and Balance") { case class Person(name: String) case class Balance(amount: Int) val balanceOverdrawnPred = Predicate[Balance](_.amount > 0) val getAccountBalance: Person => Balance = p => // that hows Banks works :) if(p.name.startsWith("A")) Balance(-1) else Balance(42) def contramap[A, B](pred: Predicate[A])(f: B => A): Predicate[B] = Predicate[B](f andThen pred.fun) val hasOverdrawnBalance = contramap(balanceOverdrawnPred)(getAccountBalance) hasOverdrawnBalance.fun(Person("Alice")) mustBe false hasOverdrawnBalance.fun(Person("Bob")) mustBe true } it("contramap with Contravariant instance") { implicit val predicateContravariant: Contravariant[Predicate] = new Contravariant[Predicate] { def contramap[A, B](pred: Predicate[A])(fba: B => A): Predicate[B] = Predicate[B](fba andThen pred.fun) } case class Person(name: String) case class Balance(amount: Int) val balanceOverdrawn = Predicate[Balance](_.amount > 0) val getAccountBalance: Person => Balance = p => if(p.name.startsWith("A")) Balance(-1) else Balance(42) val hasOverdrawnBalance = Contravariant[Predicate] .contramap(balanceOverdrawn)(getAccountBalance) hasOverdrawnBalance.fun(Person("Alice")) mustBe false hasOverdrawnBalance.fun(Person("Bob")) mustBe true } } }
Example 14
Source File: DivideSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package contravariant import scalaz.Divide import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class DivideSpec extends AnyFunSpec with Matchers { describe("Divide") { case class Serializer[A](run: A => Array[Byte]) val strSerial = Serializer[String](_.getBytes) val intSerial = Serializer[Int](_.toString.getBytes) case class Fragment(name: String, size: Int) it("custom implementation of Fragment serializer") { val fragmentSerial = Serializer[Fragment] { frag => val a1 = strSerial.run(frag.name) val a2 = intSerial.run(frag.size) a1 ++ a2 } val serialized = fragmentSerial.run(Fragment("Area", 52)) new String(serialized ) mustBe "Area52" } it("Fragment serializer using Divide") { implicit val fragmentDivide: Divide[Serializer] = new Divide[Serializer] { def divide2[A1, A2, Z](s1: => Serializer[A1], s2: => Serializer[A2])(f: Z => (A1, A2)): Serializer[Z] = Serializer{ frag => val (a1,a2) = f(frag) val serialized1 = s1.run(a1) val serializedB = s2.run(a2) serialized1 ++ serializedB } def contramap[A, B](r: Serializer[A])(f: B => A): Serializer[B] = Serializer(f andThen r.run) } val fragAsTuple: Fragment => (String, Int) = frag => (frag.name, frag.size) val fragmentSerial: Serializer[Fragment] = Divide[Serializer].divide( strSerial, intSerial)(fragAsTuple) val serialized = fragmentSerial.run(Fragment("Area", 52)) new String(serialized ) mustBe "Area52" } } }
Example 15
Source File: BifunctorExamplesSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package bifunctor import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class BifunctorExamplesSpec extends AnyFunSpec with Matchers { describe("Bifunctor") { describe("bimap") { it("apply given functions for first and second element of tuple") { import cats.implicits._ (List("foo", "bar"), 42).bimap(_.headOption, _ - 1) mustBe(Some("foo"), 41) } } describe("leftmap") { it("apply given functions for first and second element of tuple") { import cats.implicits._ (List("foo", "bar"), 42).leftMap(_.headOption) mustBe (Some("foo"), 42) } } } }
Example 16
Source File: TraverseExamplesSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package traverse import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class TraverseExamplesSpec extends AnyFunSpec with Matchers { describe("Traversing List ") { it("traverse") { import cats.implicits._ val xs1: Vector[Int] = Vector(1, 2, 3) xs1.traverse(a => Option(a)) mustBe Some(Vector(1, 2, 3)) } it("sequence") { import cats.implicits._ val xs1: List[Option[Int]] = List(Some(1), Some(2), None) xs1.sequence mustBe None val xs2: List[Option[Int]] = List(Some(1), Some(2), Some(42)) xs2.sequence mustBe Some(List(1,2,42)) } } }
Example 17
Source File: TypedIndexToStringTests.scala From frameless with Apache License 2.0 | 5 votes |
package frameless package ml package feature import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.Prop._ import shapeless.test.illTyped import org.scalatest.matchers.must.Matchers class TypedIndexToStringTests extends FramelessMlSuite with Matchers { test(".transform() correctly transform an input dataset") { implicit val arbDouble = Arbitrary(Gen.choose(0, 99).map(_.toDouble)) def prop[A: TypedEncoder: Arbitrary] = forAll { x2: X2[Double, A] => val transformer = TypedIndexToString[X1[Double]](Array.fill(100)("foo")) val ds = TypedDataset.create(Seq(x2)) val ds2 = transformer.transform(ds) ds2.collect.run() == Seq((x2.a, x2.b, "foo")) } check(prop[Double]) check(prop[String]) } test("create() compiles only with correct inputs") { illTyped("TypedIndexToString.create[String](Array(\"foo\"))") illTyped("TypedIndexToString.create[X1[String]](Array(\"foo\"))") illTyped("TypedIndexToString.create[X1[Long]](Array(\"foo\"))") illTyped("TypedIndexToString.create[X2[String, Int]](Array(\"foo\"))") } }
Example 18
Source File: MonoidExamplesSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package monoid import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class MonoidExamplesSpec extends AnyFunSpec with Matchers { describe("combineAll") { it("invoke operation for all elements") { import cats.implicits._ List(1, 2, 3).combineAll mustBe 6 List[Int]().combineAll mustBe 0 } } }
Example 19
Source File: AlternativeMonoidInstancesSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package monoid import cats.Monoid import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class AlternativeMonoidInstancesSpec extends AnyFunSpec with Matchers { implicit def createMonoidTuple[L, R](left: Monoid[L], right: Monoid[R]): Monoid[(L, R)] = new Monoid[(L, R)] { def empty: (L, R) = (left.empty, right.empty) def combine(x: (L, R), y: (L, R)): (L, R) = ( left.combine(x._1, y._1), right.combine(x._2, y._2) ) } describe("custom Monoid for multiply Int") { it("can use |+| syntax and combineAll method") { import cats.Monoid import cats.syntax.semigroup._ import monoid.AlternativeMonoidInstances.multiplyIntMonoid Monoid[Int].combineAll(Nil) mustBe 1 Monoid[Int].combineAll(List(1, 2, 3, 4)) mustBe 24 2 |+| 3 mustBe 6 } } describe("custom Monoid instance for first non empty Option") { it("get first non empty option") { import cats.Monoid import cats.syntax.semigroup._ import cats.syntax.option._ import monoid.AlternativeMonoidInstances.optionFirstNonEmpty case class Foo(v: Int) Monoid[Option[Foo]].combineAll(List(None, Foo(2).some, Foo(3).some)) mustBe Some(Foo(2)) Foo(2).some |+| Foo(3).some mustBe Foo(2).some } } } object AlternativeMonoidInstances { def createMonoid[A](mempty: A, mapply: (A, A) => A): Monoid[A] = new Monoid[A] { def empty: A = mempty def combine(x: A, y: A) = mapply(x, y) } implicit val multiplyIntMonoid: Monoid[Int] = createMonoid(1, _ * _) implicit def optionFirstNonEmpty[A]: Monoid[Option[A]] = createMonoid(None, _ orElse _) }
Example 20
Source File: ProfunctorSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package educational.category_theory.two.profunctor import scalaz._ import Scalaz._ import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class ProfunctorSpec extends AnyFunSpec with Matchers { describe("Profunctor") { it("Profunctor for Function1 is Functor + Contravariant") { case class Person(name: String, age: Int) val len: String => Int = _.length // String => Int val getPersonName: Person => String = _.name // Person => String val above5: Int => Boolean = _ > 5 // Int => Boolean val personNameAbove5 = Profunctor[Function1].dimap(len)(getPersonName)(above5) // AA => BB personNameAbove5(Person("Foo", 100)) mustBe false } } }
Example 21
Source File: StrongSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package educational.category_theory.two.profunctor import educational.category_theory.two.profunctor.strong.Strong import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers case class DoubleFun[X,Y](fun: (X,X) => (Y,Y)) trait DoubleFunPro extends Profunctor[DoubleFun] { override def dimap[S, T, A, B](pab: DoubleFun[A, B])(f: S => A, g: B => T): DoubleFun[S, T] = DoubleFun[S, T] { (c1, c2) => pab.fun(f(c1), f(c2)) match {case (z1, z2) => (g(z1), g(z2)) } } } class StrongSpec extends AnyFunSpec with Matchers { it("Functions from A to B are Strong Profunctors") { trait Function1Profunctor extends Profunctor[Function1] { override def dimap[S,T,A,B](pab: A => B)(ab: S => A, cd: B => T): S => T = ab andThen pab andThen cd } val functionPro: Profunctor[Function1] = new Function1Profunctor {} val functionStrong: Strong[Function1] = new Strong[Function1] with Function1Profunctor { def first[X, Y, Z](pab: X => Y): Function1[(X, Z), (Y, Z)] = (xz: (X, Z)) => (pab(xz._1), xz._2) } def len: String => Int = _.length functionStrong.first(len)(("foo", 42)) mustBe (3,42) } it("You can define multiple Strong Profunctors for P[_,_]") { val doubleFunProStrength: Strong[DoubleFun] with DoubleFunPro = new Strong[DoubleFun] with DoubleFunPro { override def first[A, B, C](fa: DoubleFun[A, B]): DoubleFun[(A, C), (B, C)] = DoubleFun { (a1: (A, C), a2: (A, C)) => val bb = fa.fun(a1._1, a2._1) ((bb._1, a1._2), (bb._2, a2._2)) } } val doubleFunProStrength2: Strong[DoubleFun] with DoubleFunPro = new Strong[DoubleFun] with DoubleFunPro { override def first[A, B, C](fa: DoubleFun[A, B]): DoubleFun[(A, C), (B, C)] = DoubleFun { (a1: (A, C), a2: (A, C)) => val bb = fa.fun(a1._1, a2._1) ((bb._1, a1._2), (bb._1, a2._2)) } } def bothLength(a: String, b: String): (Int, Int) = (a.length, b.length) doubleFunProStrength.first(DoubleFun(bothLength)) must not be doubleFunProStrength2.first(DoubleFun(bothLength)) } }
Example 22
Source File: FunctorExamplesSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package functor import cats.Id import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class FunctorExamplesSpec extends AnyFunSpec with Matchers { private def isOdd(i: Int): Boolean = i % 2 == 1 describe("Functor") { describe("map") { it("apply given function for each element of List") { import cats.Functor import cats.implicits._ Functor[List].map(List(2, 3, 4))(isOdd) mustBe List(false, true, false) Functor[Option].map(Option(42))(isOdd) mustBe Option(false) val myId: Id[Int] = 42 Functor[Id].map(myId)(isOdd) mustBe false } } describe("derived methods") { it("can be called directly when Functor syntax is imported") { import cats.syntax.functor._ import cats.implicits.catsStdInstancesForList List(2, 3, 4).void mustBe List((), (), ()) List(2, 3, 4).as("foo") mustBe List("foo", "foo", "foo") List(2, 3, 4).fproduct(isOdd) mustBe List((2, false), (3, true), (4, false)) } it("for Vector") { import cats.syntax.functor._ import cats.implicits.catsStdInstancesForVector Vector(2, 3, 4).void mustBe Vector((), (), ()) Vector(2, 3, 4).as("foo") mustBe Vector("foo", "foo", "foo") Vector(2, 3, 4).fproduct(isOdd) mustBe Vector((2, false), (3, true), (4, false)) } it("for Option") { import cats.syntax.functor._ import cats.implicits.catsStdInstancesForOption Option(42).void mustBe Option(()) Option(42).as("foo") mustBe Option("foo") Option(42).fproduct(isOdd) mustBe Option((42, false)) } } describe("compose") { it("can chain multiple map") { import cats.Functor import cats.implicits.catsStdInstancesForList import cats.implicits.catsStdInstancesForOption val functor = Functor[List] compose Functor[Option] functor.map(List(Some(42), Some(15), None))(isOdd) mustBe List(Some(false), Some(true), None) } it("can chain multiple map 2") { import cats.Functor import cats.implicits.catsStdInstancesForList import cats.implicits.catsStdInstancesForOption val listOption = Functor[List] compose Functor[Option] import listOption.map map(List(Some(42), Some(15), None))(isOdd) mustBe List(Some(false), Some(true), None) } } } }
Example 23
Source File: TreeFunctorSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package functor import educational.collections.{Branch, Leaf} import educational.collections.TreeInstances.treeFunctor.map import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class TreeFunctorSpec extends AnyFunSpec with Matchers { describe("map over Tree") { it("execute function for value stored inside Left") { map(Leaf("foo"))(stringLength) mustBe Leaf(3) map(Leaf("foo"))(toUpperCase) mustBe Leaf("FOO") } it("called with Branch execute function for every subtree") { map(Branch(Leaf("foo"), Leaf("bar")))(stringLength) mustBe Branch(Leaf(3), Leaf(3)) map(Branch(Leaf("foo"), Branch(Leaf("quux"), Leaf("foobar"))))(toUpperCase) mustBe Branch(Leaf("FOO"), Branch(Leaf("QUUX"), Leaf("FOOBAR"))) } it("called with complicated Tree execute function for every subtree") { val tree = Branch( Leaf("a"), Branch( Leaf("b"), Leaf("c"))) val expected = Branch( Leaf("A"), Branch( Leaf("B"), Leaf("C"))) map(tree)(toUpperCase) mustBe expected } } private def stringLength(s: String) = s.length private def toUpperCase(s: String) = s.toUpperCase }
Example 24
Source File: ApplicativeExamplesSpec.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package applicative import educational.category_theory.Applicative import educational.collections.HeadNel import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class ApplicativeExamplesSpec extends AnyFunSpec with Matchers { describe("derived methods") { it("option instance") { val optionApplicative: Applicative[Option] = new Applicative[Option] { def pure[A](a: A): Option[A] = ??? def ap[A, B](ff: Option[A => B])(fa: Option[A]): Option[B] = ??? } // TODO } it("ValidatedNel instance") { sealed trait ValidatedNel[A] case class SuccessVN[A](value: A) extends ValidatedNel[A] case class Errors[A](errors: HeadNel[Throwable]) extends ValidatedNel[A] val optionApplicative: Applicative[ValidatedNel] = new Applicative[ValidatedNel] { override def pure[A](value: A): ValidatedNel[A] = ??? override def ap[A, B](ff: ValidatedNel[A => B])(fa: ValidatedNel[A]): ValidatedNel[B] = ??? } // TODO } it("examples for Option") { import cats.Applicative import cats.implicits.catsStdInstancesForOption val add3: Int => Int = a => a + 3 Applicative[Option].pure(42) mustBe Some(42) Applicative[Option].ap(Some(add3))(Some(39)) mustBe Some(42) } it("examples for List") { import cats.Applicative import cats.implicits.catsStdInstancesForList val list1 = List(1, 2) val listFns: List[Int => Int] = List(a => a + 3, a => a * a) Applicative[List].ap(listFns)(list1) mustBe List(4,5,1,4) Applicative[List].pure("foo") mustBe List("foo") } it("map2 on composed Applicative") { import cats.Applicative import cats.implicits.catsStdInstancesForList import cats.implicits.catsStdInstancesForOption val listOpt = Applicative[List] compose Applicative[Option] val list1 = List(Some(2), None) val list2 = List(Some(10), Some(2)) listOpt.map2(list1, list2)(_ + _) mustBe List(Some(12), Some(4), None, None) } } }
Example 25
Source File: TypeRegistrySpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
package scalapb.json4s import com.google.protobuf.wrappers.UInt64Value import jsontest.test3.{MyTest3, Test3Proto, Wrapper} import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class TypeRegistrySpec extends AnyFlatSpec with Matchers with OptionValues { "addFile" should "add all messages in the file" in { val reg = TypeRegistry().addFile(Test3Proto) reg.findType("type.googleapis.com/jsontest.MyTest3").value must be(MyTest3) reg.findType("type.googleapis.com/jsontest.Wrapper").value must be(Wrapper) reg .findType("type.googleapis.com/google.protobuf.UInt64Value") .value must be(UInt64Value) reg.findType("type.googleapis.com/something.else") must be(None) } "addMessage" should "not add other messages from same file" in { val reg = TypeRegistry().addMessage[MyTest3] reg.findType("type.googleapis.com/jsontest.MyTest3").value must be(MyTest3) reg.findType("type.googleapis.com/jsontest.Wrapper") must be(None) } }
Example 26
Source File: AnyFormatSpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
package scalapb.json4s import com.google.protobuf.any.{Any => PBAny} import jsontest.anytests.{AnyTest, ManyAnyTest} import org.json4s.jackson.JsonMethods._ import scala.language.existentials 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"}""") val AnyExample = PBAny.pack(RawExample) val AnyJson = parse( s"""{"@type":"type.googleapis.com/jsontest.AnyTest","field":"test"}""" ) val CustomPrefixAny = PBAny.pack(RawExample, "example.com/") val CustomPrefixJson = parse( s"""{"@type":"example.com/jsontest.AnyTest","field":"test"}""" ) 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 ) 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 "be serialized the same as in Java (and parsed back to original)" in { assertJsonIsSameAsJava(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 27
Source File: EnumFormatSpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
package scalapb.json4s import com.google.protobuf.{InvalidProtocolBufferException, Message} import jsontest.test.{EnumTest, MyEnum} import jsontest.test3.EnumTest3 import jsontest.test3.MyTest3.MyEnum3 import org.scalatest.Assertion import scalapb.GeneratedMessageCompanion import scalapb.JavaProtoSupport import com.google.protobuf.util.JsonFormat.{Parser => JavaParser} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class EnumFormatSpec extends AnyFlatSpec with Matchers with JavaAssertions { // not ignoring unknown fields: "default parser" should "match Java behavior for string enums" in new DefaultParserContext { assertFails("""{"enum":"ZAZA"}""", EnumTest) assertFails("""{"enum":"ZAZA"}""", EnumTest3) assertFails("""{"enum":""}""", EnumTest) assertFails("""{"enum":""}""", EnumTest3) assertParse("""{"enum":"V1"}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":"V1"}""", EnumTest3(MyEnum3.V1)) assertParse("""{"enum":"0"}""", EnumTest(Some(MyEnum.UNKNOWN))) assertParse("""{"enum":"0"}""", EnumTest3()) assertParse("""{"enum":"1.0"}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":"1.0"}""", EnumTest3(MyEnum3.V1)) assertFails("""{"enum":"1.4"}""", EnumTest) assertFails("""{"enum":"1.4"}""", EnumTest3) assertFails("""{"enum":"10"}""", EnumTest) assertParse("""{"enum":"10"}""", EnumTest3(MyEnum3.Unrecognized(10))) } "default parser" should "match Java behavior for int enums" in new DefaultParserContext { assertFails("""{"enum":10}""", EnumTest) assertParse("""{"enum":10}""", EnumTest3(MyEnum3.Unrecognized(10))) assertParse("""{"enum":0}""", EnumTest(Some(MyEnum.UNKNOWN))) assertParse("""{"enum":0}""", EnumTest3(MyEnum3.UNKNOWN)) assertParse("""{"enum":0.0}""", EnumTest(Some(MyEnum.UNKNOWN))) assertParse("""{"enum":0.0}""", EnumTest3(MyEnum3.UNKNOWN)) assertFails("""{"enum":0.4}""", EnumTest) assertFails("""{"enum":0.4}""", EnumTest3) assertParse("""{"enum":1}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":1}""", EnumTest3(MyEnum3.V1)) assertParse("""{"enum":1.0}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":1.0}""", EnumTest3(MyEnum3.V1)) assertFails("""{"enum":-1}""", EnumTest) assertParse("""{"enum":-1}""", EnumTest3(MyEnum3.Unrecognized(-1))) } "ignoring unknown fields parser" should "match Java behavior for strings enums" in new IgnoringUnknownParserContext { assertParse("""{"enum":"ZAZA"}""", EnumTest()) assertParse("""{"enum":"ZAZA"}""", EnumTest3()) assertParse("""{"enum":""}""", EnumTest()) assertParse("""{"enum":""}""", EnumTest3()) assertParse("""{"enum":"V1"}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":"V1"}""", EnumTest3(MyEnum3.V1)) assertParse("""{"enum":"0"}""", EnumTest(Some(MyEnum.UNKNOWN))) assertParse("""{"enum":"0"}""", EnumTest3()) assertParse("""{"enum":"1.0"}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":"1.0"}""", EnumTest3(MyEnum3.V1)) assertParse("""{"enum":"1.4"}""", EnumTest()) assertParse("""{"enum":"1.4"}""", EnumTest3()) assertParse("""{"enum":"10"}""", EnumTest()) assertParse("""{"enum":"10"}""", EnumTest3(MyEnum3.Unrecognized(10))) } "ignoring unknown fields parser" should "match Java behavior for int enums" in new IgnoringUnknownParserContext { assertParse("""{"enum":10}""", EnumTest()) assertParse("""{"enum":10}""", EnumTest3(MyEnum3.Unrecognized(10))) assertParse("""{"enum":0}""", EnumTest(Some(MyEnum.UNKNOWN))) assertParse("""{"enum":0}""", EnumTest3(MyEnum3.UNKNOWN)) assertParse("""{"enum":0.0}""", EnumTest(Some(MyEnum.UNKNOWN))) assertParse("""{"enum":0.0}""", EnumTest3(MyEnum3.UNKNOWN)) assertParse("""{"enum":0.4}""", EnumTest()) assertParse("""{"enum":0.4}""", EnumTest()) assertParse("""{"enum":1}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":1}""", EnumTest3(MyEnum3.V1)) assertParse("""{"enum":1.0}""", EnumTest(Some(MyEnum.V1))) assertParse("""{"enum":1.0}""", EnumTest3(MyEnum3.V1)) assertParse("""{"enum":-1}""", EnumTest()) assertParse("""{"enum":-1}""", EnumTest3(MyEnum3.Unrecognized(-1))) } "Enum" should "be serialized the same way as java" in { assertJsonIsSameAsJava(jsontest.test.EnumTest()) assertJsonIsSameAsJava(jsontest.test.EnumTest(Some(MyEnum.V1))) } }
Example 28
Source File: RepeatablesSpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
import scalapb.e2e.repeatables.RepeatablesTest import scalapb.e2e.repeatables.RepeatablesTest.Nested import org.scalatest._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalacheck.{Arbitrary, Gen} import scalapb.json4s.JsonFormat import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class JsonSpec extends AnyFlatSpec with ScalaCheckDrivenPropertyChecks with Matchers { val nestedGen = Arbitrary.arbitrary[Option[Int]].map(s => Nested(nestedField = s)) val repGen = for { strings <- Gen.listOf(Arbitrary.arbitrary[String]) ints <- Gen.listOf(Arbitrary.arbitrary[Int]) doubles <- Gen.listOf(Arbitrary.arbitrary[Double]) nesteds <- Gen.listOf(nestedGen) } yield RepeatablesTest( strings = strings, ints = ints, doubles = doubles, nesteds = nesteds ) "fromJson" should "invert toJson (single)" in { val rep = RepeatablesTest( strings = Seq("s1", "s2"), ints = Seq(14, 19), doubles = Seq(3.14, 2.17), nesteds = Seq(Nested()) ) val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } "fromJson" should "invert toJson" in { forAll(repGen) { rep => val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } } }
Example 29
Source File: ArbitrarySpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
package scalapb.json4s import scalapb.e2e.repeatables.RepeatablesTest import scalapb.e2e.repeatables.RepeatablesTest.Nested import org.scalatest._ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalacheck.{Arbitrary, Gen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class ArbitrarySpec extends AnyFlatSpec with ScalaCheckDrivenPropertyChecks with Matchers { val nestedGen = Arbitrary.arbitrary[Option[Int]].map(s => Nested(nestedField = s)) val repGen = for { strings <- Gen.listOf(Arbitrary.arbitrary[String]) ints <- Gen.listOf(Arbitrary.arbitrary[Int]) doubles <- Gen.listOf(Arbitrary.arbitrary[Double]) nesteds <- Gen.listOf(nestedGen) } yield RepeatablesTest( strings = strings, ints = ints, doubles = doubles, nesteds = nesteds ) "fromJson" should "invert toJson (single)" in { val rep = RepeatablesTest( strings = Seq("s1", "s2"), ints = Seq(14, 19), doubles = Seq(3.14, 2.17), nesteds = Seq(Nested()) ) val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } "fromJson" should "invert toJson" in { forAll(repGen) { rep => val j = JsonFormat.toJson(rep) JsonFormat.fromJson[RepeatablesTest](j) must be(rep) } } }
Example 30
Source File: NameUtilsSpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
package scalapb.json4s import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class NameUtilsSpec extends AnyFlatSpec with Matchers { "snakeCaseToCamelCase" should "work for normal names" in { NameUtils.snakeCaseToCamelCase("scala_pb") must be("scalaPb") NameUtils.snakeCaseToCamelCase("foo_bar") must be("fooBar") NameUtils.snakeCaseToCamelCase("foo_bar_123baz") must be("fooBar123Baz") NameUtils.snakeCaseToCamelCase("foo_bar_123_baz") must be("fooBar123Baz") NameUtils.snakeCaseToCamelCase("__foo_bar") must be("FooBar") NameUtils.snakeCaseToCamelCase("_foo_bar") must be("FooBar") NameUtils.snakeCaseToCamelCase("_scala_pb") must be("ScalaPb") NameUtils.snakeCaseToCamelCase("foo__bar") must be("fooBar") NameUtils.snakeCaseToCamelCase("123bar") must be("123Bar") NameUtils.snakeCaseToCamelCase("123_bar") must be("123Bar") } "snakeCaseToCamelCase" should "work when already in camel case" in { NameUtils.snakeCaseToCamelCase("fooBar") must be("fooBar") NameUtils.snakeCaseToCamelCase("fooBar_baz") must be("fooBarBaz") NameUtils.snakeCaseToCamelCase("FooBar") must be("fooBar") } }
Example 31
Source File: OneOfSpec.scala From scalapb-json4s with Apache License 2.0 | 5 votes |
package scalapb.json4s import com.google.protobuf.util.JsonFormat.{printer => ProtobufJavaPrinter} import jsontest.oneof.OneOf._ import jsontest.oneof.Pair.ValueByType._ import jsontest.oneof.{Dictionary, OneOf, OneOfMessage, Pair} import org.json4s.jackson.JsonMethods.parse import org.scalatest.prop._ 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().toJson(message) must be( parse(json) ) new Printer().toJson(message) must be( parse( ProtobufJavaPrinter().print(toJavaProto(message)) ) ) new Printer().includingDefaultValueFields.toJson(message) must be( parse(json) ) new Printer().includingDefaultValueFields.toJson(message) must be( parse( ProtobufJavaPrinter() .includingDefaultValueFields() .print(toJavaProto(message)) ) ) } "dictionary test" should "preserve zero values in one of" in { val message = Dictionary(Seq(Pair("myKey", Uint32Value(0)))) new Printer().toJson(message) must be( parse("""{"pairs":[{"key": "myKey", "uint32Value": 0}]}""") ) new Printer().includingDefaultValueFields.toJson(message) must be( parse("""{"pairs":[{"key": "myKey", "uint32Value": 0}]}""") ) } }
Example 32
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 33
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 34
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 35
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 36
Source File: ScalazIntegrationSpec.scala From octopus with Apache License 2.0 | 5 votes |
package octopus.scalaz import octopus.example.domain._ import octopus.syntax._ import octopus.{Fixtures, ValidationError} import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec import scalaz.{NonEmptyList, Validation} class ScalazIntegrationSpec extends AnyWordSpec with Matchers with Fixtures { "Scalaz Integration" should { "support ValidationNel" when { "success scenario" in { 1.validate.toValidationNel mustBe Validation.success(1) userId_Valid.validate.toValidationNel mustBe Validation.success(userId_Valid) user_Valid.validate.toValidationNel mustBe Validation.success(user_Valid) } "failure scenario" in { userId_Invalid.validate.toValidationNel mustBe Validation.failure( NonEmptyList.nels(ValidationError(UserId.Err_MustBePositive)) ) user_Invalid1.validate.toValidationNel.leftMap(_.map(_.toPair)) mustBe Validation.failure( NonEmptyList.nels( "id" -> UserId.Err_MustBePositive, "email" -> Email.Err_MustContainAt, "email" -> Email.Err_MustContainDotAfterAt, "address.postalCode" -> PostalCode.Err_MustBeLengthOf5, "address.postalCode" -> PostalCode.Err_MustContainOnlyDigits, "address.city" -> Address.Err_MustNotBeEmpty, "address.street" -> Address.Err_MustNotBeEmpty ) ) } } "support Validation" when { "success scenario" in { 1.validate.toValidation mustBe Validation.success(1) userId_Valid.validate.toValidation mustBe Validation.success(userId_Valid) user_Valid.validate.toValidation mustBe Validation.success(user_Valid) } "failure scenario" in { userId_Invalid.validate.toValidation mustBe Validation.failure( List(ValidationError(UserId.Err_MustBePositive)) ) user_Invalid1.validate.toValidation.leftMap(_.map(_.toPair)) mustBe Validation.failure( List( "id" -> UserId.Err_MustBePositive, "email" -> Email.Err_MustContainAt, "email" -> Email.Err_MustContainDotAfterAt, "address.postalCode" -> PostalCode.Err_MustBeLengthOf5, "address.postalCode" -> PostalCode.Err_MustContainOnlyDigits, "address.city" -> Address.Err_MustNotBeEmpty, "address.street" -> Address.Err_MustNotBeEmpty ) ) } } } }
Example 37
Source File: CatsIntegrationSpec.scala From octopus with Apache License 2.0 | 5 votes |
package octopus.cats import cats.data.{NonEmptyList, Validated} import octopus.example.domain._ import octopus.syntax._ import octopus.{Fixtures, ValidationError} import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec class CatsIntegrationSpec extends AnyWordSpec with Matchers with Fixtures { "Cats Integration" should { "support ValidatedNel" when { "Valid scenario" in { 1.validate.toValidatedNel mustBe Validated.Valid(1) userId_Valid.validate.toValidatedNel mustBe Validated.Valid(userId_Valid) user_Valid.validate.toValidatedNel mustBe Validated.Valid(user_Valid) } "Invalid scenario" in { userId_Invalid.validate.toValidatedNel mustBe Validated.Invalid( NonEmptyList.of(ValidationError(UserId.Err_MustBePositive)) ) user_Invalid1.validate.toValidatedNel.leftMap(_.map(_.toPair)) mustBe Validated.Invalid( NonEmptyList.of( "id" -> UserId.Err_MustBePositive, "email" -> Email.Err_MustContainAt, "email" -> Email.Err_MustContainDotAfterAt, "address.postalCode" -> PostalCode.Err_MustBeLengthOf5, "address.postalCode" -> PostalCode.Err_MustContainOnlyDigits, "address.city" -> Address.Err_MustNotBeEmpty, "address.street" -> Address.Err_MustNotBeEmpty ) ) } } "support Validated" when { "Valid scenario" in { 1.validate.toValidated mustBe Validated.Valid(1) userId_Valid.validate.toValidated mustBe Validated.Valid(userId_Valid) user_Valid.validate.toValidated mustBe Validated.Valid(user_Valid) } "Invalid scenario" in { userId_Invalid.validate.toValidated mustBe Validated.Invalid( List(ValidationError(UserId.Err_MustBePositive)) ) user_Invalid1.validate.toValidated.leftMap(_.map(_.toPair)) mustBe Validated.Invalid( List( "id" -> UserId.Err_MustBePositive, "email" -> Email.Err_MustContainAt, "email" -> Email.Err_MustContainDotAfterAt, "address.postalCode" -> PostalCode.Err_MustBeLengthOf5, "address.postalCode" -> PostalCode.Err_MustContainOnlyDigits, "address.city" -> Address.Err_MustNotBeEmpty, "address.street" -> Address.Err_MustNotBeEmpty ) ) } } } }
Example 38
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 39
Source File: JavaAssertionsPlatform.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.util.JsonFormat.{TypeRegistry => JavaTypeRegistry} import scalapb.{GeneratedMessage, GeneratedMessageCompanion, JavaProtoSupport} import org.scalatest.matchers.must.Matchers trait JavaAssertionsPlatform { self: Matchers with JavaAssertions => def registeredCompanions: Seq[GeneratedMessageCompanion[_]] val JavaJsonTypeRegistry = registeredCompanions.foldLeft(JavaTypeRegistry.newBuilder())(_ add _.javaDescriptor).build() val JavaJsonPrinter = com.google.protobuf.util.JsonFormat.printer().usingTypeRegistry(JavaJsonTypeRegistry) val JavaJsonParser = com.google.protobuf.util.JsonFormat.parser() def assertJsonIsSameAsJava[T <: GeneratedMessage](v: T, checkRoundtrip: Boolean = true)( implicit cmp: GeneratedMessageCompanion[T] ) = { val scalaJson = ScalaJsonPrinter.print(v) val javaJson = JavaJsonPrinter.print( cmp.asInstanceOf[JavaProtoSupport[T, com.google.protobuf.GeneratedMessageV3]].toJavaProto(v) ) import io.circe.parser.parse parse(scalaJson).isRight must be(true) parse(scalaJson) must be(parse(javaJson)) if (checkRoundtrip) { ScalaJsonParser.fromJsonString[T](scalaJson) must be(v) } } def javaParse[T <: com.google.protobuf.GeneratedMessageV3.Builder[T]]( json: String, b: com.google.protobuf.GeneratedMessageV3.Builder[T] ) = { JavaJsonParser.merge(json, b) b.build() } }
Example 40
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 41
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 42
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 43
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 44
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 45
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 46
Source File: TupleSpec.scala From play-json with Apache License 2.0 | 5 votes |
package play.api.libs.json import org.scalatest._ import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec final class TupleSpec extends AnyWordSpec with Matchers { "Reading/Write tuples" should { def check[T: Reads: Writes](value: T, expected: String) = { Json.stringify(Json.toJson(value)).mustEqual(expected) Json.fromJson(Json.parse(expected)).get.mustEqual(value) } "work for small tuples" in { check(Tuple1(1), "[1]") check((1, 2, "lol"), """[1,2,"lol"]""") } "work for large tuples" in { check( (1, 2, "lol", "foo", "bar", "baz", true, Seq(1, 2)), """[1,2,"lol","foo","bar","baz",true,[1,2]]""" ) } "work for nested tuples" in { check( (1, 2, ("lol", ("foo", "bar"))), """[1,2,["lol",["foo","bar"]]]""" ) } } }
Example 47
Source File: JsonRichSpec.scala From play-json with Apache License 2.0 | 5 votes |
package play.api.libs.json import play.api.libs.json.Json._ import org.scalatest._ import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec class JsonRichSpec extends AnyWordSpec with Matchers { "JSON" should { "create json with rich syntax" in { def js = Json.obj( "key1" -> Json.obj("key11" -> "value11", "key12" -> 123L, "key13" -> JsNull), "key2" -> 123, "key3" -> true, "key4" -> Json.arr("value41", 345.6, JsString("test"), JsObject(Seq("key411" -> obj("key4111" -> 987.654)))) ) js.mustEqual( JsObject( Seq( "key1" -> JsObject( Seq( "key11" -> JsString("value11"), "key12" -> JsNumber(123L), "key13" -> JsNull ) ), "key2" -> JsNumber(123), "key3" -> JsTrue, "key4" -> JsArray( Array( JsString("value41"), JsNumber(345.6), JsString("test"), JsObject(Seq("key411" -> JsObject(Seq("key4111" -> JsNumber(987.654))))) ) ) ) ) ) } } }
Example 48
Source File: JsonSpec.scala From play-json with Apache License 2.0 | 5 votes |
package play.api.libs.json import play.api.libs.json.Json._ import org.scalatest._ import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec class JsonSpec extends AnyWordSpec with Matchers { "Complete JSON should create full object" when { "lose precision when parsing BigDecimals" in { val n = BigDecimal("12345678901234567890.123456789") parse(stringify(toJson(n))).mustEqual( JsNumber( BigDecimal("12345678901234567000") ) ) } "lose precision when parsing big integers" in { // By big integers, we just mean integers that overflow long, // since Jackson has different code paths for them from decimals val json = toJson(BigDecimal("1.2345678901234568E+29")) parse(stringify(json)).mustEqual(json) } "keep similar object between serialized and deserialized data".taggedAs(UnstableInScala213) in { val original = Json.obj( "key1" -> "value1", "key2" -> true, "key3" -> JsNull, "key4" -> Json.arr(1, 2.5, "value2", false, JsNull), "key5" -> Json.obj( "key6" -> "こんにちは", "key7" -> BigDecimal("12345678901234567000") ) ) val originalString = Json.stringify(original) val parsed = Json.parse(originalString) parsed.asInstanceOf[JsObject].fields.mustEqual(original.fields) Json.stringify(parsed).mustEqual(originalString) } "parse from InputStream" in { val orig = Json.obj( "key1" -> "value1", "key2" -> true, "key3" -> JsNull, "key4" -> Json.arr(1, 2.5, "value2", false, JsNull), "key5" -> Json.obj( "key6" -> "こんにちは", "key7" -> BigDecimal("12345678901234567890.123456789") ) ) def stream = new java.io.ByteArrayInputStream( orig.toString.getBytes("UTF-8") ) def expected = Json.obj( "key1" -> "value1", "key2" -> true, "key3" -> JsNull, "key4" -> Json.arr(1, 2.5, "value2", false, JsNull), "key5" -> Json.obj( "key6" -> "こんにちは", "key7" -> BigDecimal( // JS loose precision on BigDec "12345678901234567000" ) ) ) Json.parse(stream).mustEqual(expected) } } }
Example 49
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 50
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 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 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 52
Source File: PrintableSpec.scala From tutorial-cats with MIT License | 5 votes |
package example import example.fixtures.GatoFixture import org.scalatest.wordspec.AnyWordSpec import org.scalatest.matchers.must.Matchers class PrintableSpec extends AnyWordSpec with Matchers with GatoFixture { "Printable" must { "handle Int" in { // TODO 02: Define the mandatory type class to make this work import PrintableInstances._ //format(123) must be("value=123") fail("WIP") } "handle String" in { // TODO 02: Define the mandatory type class to make this work import PrintableInstances._ //format("a") must be("value=a") fail("WIP") } "allow a printable" in { // TODO 02: Implement the printable syntax to make this work import PrintableInstances._ import PrintableSyntax._ //michin.format must be("name=michin, age=3, color=black") fail("WIP") } } }
Example 53
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 54
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 55
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 56
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 57
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 58
Source File: ServiceLocatorHolderSpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.internal.persistence.cassandra import akka.actor.ActorSystem import akka.testkit.TestKit import org.scalatest.BeforeAndAfterAll import scala.concurrent.Await import scala.concurrent.duration._ import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec class ServiceLocatorHolderSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll { val system = ActorSystem("test") protected override def afterAll(): Unit = { TestKit.shutdownActorSystem(actorSystem = system, verifySystemShutdown = true) } "ServiceLocatorHolder" should { "timeout when no service locator is found" in { val eventually = ServiceLocatorHolder(system).serviceLocatorEventually assertThrows[NoServiceLocatorException]( Await.result(eventually, ServiceLocatorHolder.TIMEOUT + 2.seconds) ) } } }
Example 59
Source File: ServiceLocatorSessionProviderSpec.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.internal.persistence.cassandra import java.net.InetSocketAddress import java.net.URI import akka.actor.ActorSystem import akka.testkit.TestKit import com.typesafe.config.Config import com.typesafe.config.ConfigFactory import org.scalatest.BeforeAndAfterAll import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import scala.concurrent.Await import scala.concurrent.Future import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec class ServiceLocatorSessionProviderSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll { val system = ActorSystem("test") val config: Config = ConfigFactory.load() val uri = new URI("http://localhost:8080") protected override def afterAll(): Unit = { TestKit.shutdownActorSystem(actorSystem = system, verifySystemShutdown = true) } val locator = new ServiceLocatorAdapter { override def locateAll(name: String): Future[List[URI]] = { name match { case "existing" => Future.successful(List(uri)) case "absent" => Future.successful(Nil) } } } val providerConfig: Config = config.getConfig("lagom.persistence.read-side.cassandra") val provider = new ServiceLocatorSessionProvider(system, providerConfig) ServiceLocatorHolder(system).setServiceLocator(locator) "ServiceLocatorSessionProvider" should { "Get the address when the contact points exist" in { val future = provider.lookupContactPoints("existing") Await.result(future, 3.seconds) mustBe Seq(new InetSocketAddress(uri.getHost, uri.getPort)) } "Fail the future when the contact points do not exist" in { val future = provider.lookupContactPoints("absent") intercept[NoContactPointsException] { Await.result(future, 3.seconds) } } } }
Example 60
Source File: CheckpointTrackerActorSpec.scala From kinesis-stream with MIT License | 5 votes |
package px.kinesis.stream.consumer.checkpoint import akka.actor.Status.Failure import akka.actor.{ActorRef, ActorSystem} import akka.testkit.{ImplicitSender, TestKit} import org.scalamock.scalatest.MockFactory import org.scalatest.funspec.AnyFunSpecLike import org.scalatest.BeforeAndAfterAll import org.scalatest.matchers.must.Matchers import px.kinesis.stream.consumer.checkpoint.CheckpointTrackerActor._ import px.kinesis.stream.consumer.checkpoint.{ShardCheckpointTrackerActor => shard} import software.amazon.kinesis.retrieval.kpl.ExtendedSequenceNumber import scala.collection.immutable.Seq class CheckpointTrackerActorSpec extends TestKit(ActorSystem("CheckpointTrackerActorSpec")) with ImplicitSender with AnyFunSpecLike with Matchers with BeforeAndAfterAll with MockFactory { override def afterAll: Unit = { TestKit.shutdownActorSystem(system) } val workerId = "123" def toSequenceNum(i: Int): ExtendedSequenceNumber = new ExtendedSequenceNumber(i.toString) def createTracker(): ActorRef = system.actorOf( CheckpointTrackerActor .props(workerId, 10, 10)) describe("track") { it("should track successfully after creation of tracker") { val tracker = createTracker() val shardId = "01" tracker ! Command.Create(shardId) expectMsg(Response.Ack) tracker ! Command.Track(shardId, Seq(1).map(toSequenceNum)) expectMsg(shard.Response.Ack) } it("should fail if tracker is not active") { val tracker = createTracker() val shardId = "01" // shard tracker for 01 does not exist tracker ! Command.Track(shardId, Seq(1).map(toSequenceNum)) expectMsgPF() { case Failure(_) => true } } } describe("process") { it("should process successfully after creation of tracker") { val tracker = createTracker() val shardId = "01" tracker ! Command.Create(shardId) expectMsg(Response.Ack) tracker ! Command.Process(shardId, toSequenceNum(1)) expectMsg(shard.Response.Ack) } it("should process successfully even after shard tracker is shutdown") { val tracker = createTracker() val shardId = "01" tracker ! Command.Create(shardId) expectMsg(Response.Ack) tracker ! Command.Process(shardId, toSequenceNum(1)) expectMsg(shard.Response.Ack) tracker ! Command.ShutdownShard(shardId) expectMsg(Response.Ack) tracker ! Command.Process(shardId, toSequenceNum(2)) expectMsg(shard.Response.Ack) } } }
Example 61
Source File: ResultSetIteratorSpec.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill import io.getquill.context.monix.Runner import io.getquill.util.LoadConfig import monix.eval.Task import monix.execution.Scheduler import org.scalatest.BeforeAndAfterAll import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.must.Matchers import org.scalatest.matchers.should.Matchers._ import scala.collection.mutable.ArrayBuffer class ResultSetIteratorSpec extends AnyFreeSpec with Matchers with BeforeAndAfterAll { val ds = JdbcContextConfig(LoadConfig("testPostgresDB")).dataSource implicit val scheduler = Scheduler.global val ctx = new PostgresMonixJdbcContext(Literal, ds, Runner.default) import ctx._ case class Person(name: String, age: Int) val peopleInsert = quote((p: Person) => query[Person].insert(p)) val peopleEntries = List( Person("Alex", 60), Person("Bert", 55), Person("Cora", 33) ) override def beforeAll = { ctx.transaction { for { _ <- ctx.run(query[Person].delete) _ <- ctx.run(liftQuery(peopleEntries).foreach(p => peopleInsert(p))) } yield () }.runSyncUnsafe() } "traverses correctly" in { val results = Task(ds.getConnection).bracket { conn => Task { val stmt = conn.prepareStatement("select * from person") val rs = new ResultSetIterator[String](stmt.executeQuery(), extractor = (rs) => { rs.getString(1) }) val accum = ArrayBuffer[String]() while (rs.hasNext) accum += rs.next() accum } } { conn => Task(conn.close()) }.runSyncUnsafe() results should contain theSameElementsAs (peopleEntries.map(_.name)) } "can take head element" in { val result = Task(ds.getConnection).bracket { conn => Task { val stmt = conn.prepareStatement("select * from person where name = 'Alex'") val rs = new ResultSetIterator(stmt.executeQuery(), extractor = (rs) => { rs.getString(1) }) rs.head } } { conn => Task(conn.close()) }.runSyncUnsafe() result must equal("Alex") } }
Example 62
Source File: JacksonNestedTest.scala From guardrail with MIT License | 5 votes |
package core.Jackson import java.lang.reflect.Modifier import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.must.Matchers import polymorphismNested.client.dropwizard.definitions.{ A, B, C, TestResponse } class JacksonNestedTest extends AnyFreeSpec with Matchers { "Jackson nested schemas" - { "Should have the nested objects in the right place" in { new TestResponse.Builder() .withEnum1(A.Enum1.B) .withEnum2(B.Enum2.D) .withObj(new C.Obj.Builder().withValue("foo").build()) .build() } "Should have nested classes as public static members" in { classOf[C.Obj].getModifiers & Modifier.PUBLIC mustBe Modifier.PUBLIC classOf[C.Obj].getModifiers & Modifier.STATIC mustBe Modifier.STATIC } "Should have nested enums as public non-static members that nonetheless reflect as static" in { classOf[A.Enum1].getModifiers & Modifier.PUBLIC mustBe Modifier.PUBLIC classOf[A.Enum1].getModifiers & Modifier.STATIC mustBe Modifier.STATIC } } }
Example 63
Source File: JavaInvalidCharacterEscapingTest.scala From guardrail with MIT License | 5 votes |
package core.Dropwizard import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.ObjectMapper import invalidCharacters.client.dropwizard.invalidCharacters.InvalidCharactersClient import invalidCharacters.server.dropwizard.definitions.{InvalidCharacters, InvalidCharactersEnum} import io.netty.buffer.Unpooled import java.net.{SocketAddress, URI, URLDecoder} import java.util.concurrent.{CompletableFuture, CompletionStage} import java.util.function import org.asynchttpclient.Response.ResponseBuilder import org.asynchttpclient.netty.EagerResponseBodyPart import org.asynchttpclient.uri.Uri import org.asynchttpclient.{HttpResponseStatus, Request, Response} import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.must.Matchers import scala.collection.JavaConverters._ object JavaInvalidCharacterEscapingTest { private implicit class RichString(private val s: String) extends AnyVal { def dec: String = URLDecoder.decode(s, "UTF-8") } private object OkStatus extends HttpResponseStatus(Uri.create("http://localhost:1234/foo?foo^bar=query-param")) { override def getStatusCode = 200 override def getStatusText = "OK" override def getProtocolName = "HTTP" override def getProtocolMajorVersion = 1 override def getProtocolMinorVersion = 1 override def getProtocolText = "HTTP/1.1" override def getRemoteAddress: SocketAddress = ??? override def getLocalAddress: SocketAddress = ??? } } class JavaInvalidCharacterEscapingTest extends AnyFreeSpec with Matchers { import JavaInvalidCharacterEscapingTest._ "Invalid characters in Java enums should be escaped" in { InvalidCharactersEnum.NORMAL.getName mustBe "normal" InvalidCharactersEnum.BANG_MOO_COLON_COW_SEMICOLON.getName mustBe "!moo:cow;" InvalidCharactersEnum.POUND_YEAH.getName mustBe "#yeah" InvalidCharactersEnum.WEIRD_AT.getName mustBe "weird@" } "Invalid characters in Java POJO properties should be escaped" in { val invChar = new InvalidCharacters.Builder("stuff", InvalidCharactersEnum.POUND_YEAH).build() invChar.getCloseSquareBraceMoo mustBe "stuff" invChar.getSomeEnumAsteriskCaret mustBe InvalidCharactersEnum.POUND_YEAH classOf[InvalidCharacters].getDeclaredField("closeSquareBraceMoo").getAnnotation(classOf[JsonProperty]).value mustBe "]moo" classOf[InvalidCharacters].getDeclaredField("someEnumAsteriskCaret").getAnnotation(classOf[JsonProperty]).value mustBe "some-enum*^" } "Invalid characters in Java operation param names should be escaped" in { val httpClient = new function.Function[Request, CompletionStage[Response]] { override def apply(request: Request): CompletionStage[Response] = { println(request.getUri) println(request.getQueryParams.asScala.map(_.getName)) val qps = request.getQueryParams.asScala.map(p => (p.getName.dec, p.getValue.dec)) val fps = request.getFormParams.asScala.map(p => (p.getName.dec, p.getValue.dec)) qps.find(_._1 == "foo^bar").map(_._2) mustBe Some("firstarg") fps.find(_._1 == "a*b").map(_._2) mustBe Some("secondarg") fps.find(_._1 == "bc?").map(_._2) mustBe Some("thirdarg") fps.find(_._1 == "d/c").map(_._2) mustBe Some("fourtharg") val response = new ResponseBuilder() response.accumulate(OkStatus) response.accumulate(new EagerResponseBodyPart( Unpooled.copiedBuffer(new ObjectMapper().writeValueAsBytes(new InvalidCharacters.Builder("foo", InvalidCharactersEnum.WEIRD_AT).build())), true )) CompletableFuture.completedFuture(response.build()) } } val client = new InvalidCharactersClient.Builder(new URI("http://localhost:1234")).withHttpClient(httpClient).build() val response = client.getFoo("firstarg", "secondarg", "thirdarg", "fourtharg").call().toCompletableFuture.get() response.fold( { invChar => invChar.getCloseSquareBraceMoo mustBe "foo" invChar.getSomeEnumAsteriskCaret mustBe invalidCharacters.client.dropwizard.definitions.InvalidCharactersEnum.WEIRD_AT } ) } }
Example 64
Source File: DropwizardContentTypesTest.scala From guardrail with MIT License | 5 votes |
package tests.generators.dropwizard.server import com.github.javaparser.ast.body.MethodDeclaration import com.twilio.guardrail.generators.Java.Dropwizard import com.twilio.guardrail.{ Context, Server, Servers } import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.must.Matchers import scala.collection.JavaConverters._ import scala.compat.java8.OptionConverters._ import support.SwaggerSpecRunner class DropwizardContentTypesTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner { private val swagger: String = s""" |openapi: 3.0.1 |paths: | /foo: | post: | operationId: foo | responses: | 204: {} | 404: | content: | application/json: | schema: | type: object | /foo-multiple: | post: | operationId: fooMultiple | responses: | 204: | content: | application/json: | schema: | type: object | 404: | content: | text/plain: | schema: | type: string |""".stripMargin "Produces annotation should still be added when success response has no body, but errors do" in { val ( _, _, Servers(Server(_, _, _, genResource :: Nil) :: Nil, _) ) = runSwaggerSpec(swagger)(Context.empty, Dropwizard) genResource .asClassOrInterfaceDeclaration() .getMembers .asScala .collectFirst({ case method: MethodDeclaration if method.getNameAsString == "foo" => method }) .value .getAnnotationByName("Produces") .asScala .value .asSingleMemberAnnotationExpr() .getMemberValue .toString mustBe "MediaType.APPLICATION_JSON" } // This doesn't yet work because when the core threads through response info, we lose which content-type // is associated with which response. But I'll leave the test here to re-enable later when we fix that. }