org.scalatest.funsuite.AnyFunSuite Scala Examples
The following examples show how to use org.scalatest.funsuite.AnyFunSuite.
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: OutputStreamTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.streams.output import java.io.ByteArrayOutputStream import com.sksamuel.avro4s._ import org.apache.avro.file.{DataFileReader, SeekableByteArrayInput} import org.apache.avro.generic.{GenericDatumReader, GenericRecord} import org.apache.avro.io.DecoderFactory import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers trait OutputStreamTest extends AnyFunSuite with Matchers { def readData[T: SchemaFor](out: ByteArrayOutputStream): GenericRecord = readData(out.toByteArray) def readData[T: SchemaFor](bytes: Array[Byte]): GenericRecord = { val datumReader = new GenericDatumReader[GenericRecord](AvroSchema[T]) val dataFileReader = new DataFileReader[GenericRecord](new SeekableByteArrayInput(bytes), datumReader) dataFileReader.next } def writeData[T: Encoder : SchemaFor](t: T): ByteArrayOutputStream = { val out = new ByteArrayOutputStream val avro = AvroOutputStream.data[T].to(out).build() avro.write(t) avro.close() out } def readBinary[T: SchemaFor](out: ByteArrayOutputStream): GenericRecord = readBinary(out.toByteArray) def readBinary[T: SchemaFor](bytes: Array[Byte]): GenericRecord = { val datumReader = new GenericDatumReader[GenericRecord](AvroSchema[T]) val decoder = DecoderFactory.get().binaryDecoder(new SeekableByteArrayInput(bytes), null) datumReader.read(null, decoder) } def writeBinary[T: Encoder : SchemaFor](t: T): ByteArrayOutputStream = { val out = new ByteArrayOutputStream val avro = AvroOutputStream.binary[T].to(out).build() avro.write(t) avro.close() out } def readJson[T: SchemaFor](out: ByteArrayOutputStream): GenericRecord = readJson(out.toByteArray) def readJson[T: SchemaFor](bytes: Array[Byte]): GenericRecord = { val schema = AvroSchema[T] val datumReader = new GenericDatumReader[GenericRecord](schema) val decoder = DecoderFactory.get().jsonDecoder(schema, new SeekableByteArrayInput(bytes)) datumReader.read(null, decoder) } def writeJson[T: Encoder : SchemaFor](t: T): ByteArrayOutputStream = { val out = new ByteArrayOutputStream val avro = AvroOutputStream.json[T].to(out).build() avro.write(t) avro.close() out } def writeRead[T: Encoder : SchemaFor](t: T)(fn: GenericRecord => Any): Unit = { { val out = writeData(t) val record = readData(out) fn(record) } { val out = writeBinary(t) val record = readBinary(out) fn(record) } { val out = writeJson(t) val record = readJson(out) fn(record) } } }
Example 2
Source File: InputStreamTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.streams.input import java.io.ByteArrayOutputStream import com.sksamuel.avro4s._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers trait InputStreamTest extends AnyFunSuite with Matchers { def readData[T: SchemaFor: Decoder](out: ByteArrayOutputStream): T = readData(out.toByteArray) def readData[T: SchemaFor: Decoder](bytes: Array[Byte]): T = { AvroInputStream.data.from(bytes).build(implicitly[SchemaFor[T]].schema).iterator.next() } def writeData[T: Encoder: SchemaFor](t: T): ByteArrayOutputStream = { val out = new ByteArrayOutputStream val avro = AvroOutputStream.data[T].to(out).build() avro.write(t) avro.close() out } def readBinary[T: SchemaFor: Decoder](out: ByteArrayOutputStream): T = readBinary(out.toByteArray) def readBinary[T: SchemaFor: Decoder](bytes: Array[Byte]): T = { AvroInputStream.binary.from(bytes).build(implicitly[SchemaFor[T]].schema).iterator.next() } def writeBinary[T: Encoder](t: T): ByteArrayOutputStream = { val out = new ByteArrayOutputStream val avro = AvroOutputStream.binary[T].to(out).build() avro.write(t) avro.close() out } def writeRead[T: Encoder: Decoder: SchemaFor](t: T): Unit = { { val out = writeData(t) readData(out) shouldBe t } { val out = writeBinary(t) readBinary(out) shouldBe t } } def writeRead[T: Encoder: Decoder: SchemaFor](t: T, expected: T): Unit = { { val out = writeData(t) readData(out) shouldBe expected } { val out = writeBinary(t) readBinary(out) shouldBe expected } } }
Example 3
Source File: EnumInputStreamTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.streams.input import com.sksamuel.avro4s.schema.{Colours, Wine} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class EnumInputStreamTest extends AnyFunSuite with Matchers with InputStreamTest { case class JavaEnumTest(z: Wine) case class OptionalJavaEnumTest(z: Option[Wine]) case class ScalaEnumTest(z: Colours.Value) case class OptionalScalaEnumTest(z: Option[Colours.Value]) test("java enum") { writeRead(JavaEnumTest(Wine.Malbec)) } test("optional java enum") { writeRead(OptionalJavaEnumTest(Some(Wine.Malbec))) writeRead(OptionalJavaEnumTest(None)) } test("scala enum") { writeRead(ScalaEnumTest(Colours.Green)) } test("optional scala enum") { writeRead(OptionalScalaEnumTest(Some(Colours.Green))) writeRead(OptionalScalaEnumTest(None)) } }
Example 4
Source File: ValueTypeEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import com.sksamuel.avro4s.{AvroSchema, Encoder, ImmutableRecord} import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ValueTypeEncoderTest extends AnyFunSuite with Matchers { test("top level value types") { val schema = AvroSchema[FooValueType] Encoder[FooValueType].encode(FooValueType("hello")) shouldBe new Utf8("hello") } test("support fields that are value types") { case class Test(foo: FooValueType) val schema = AvroSchema[Test] Encoder[Test].encode(Test(FooValueType("hello"))) shouldBe ImmutableRecord(schema, Vector(new Utf8("hello"))) } test("support value types inside Options") { case class Test(foo: Option[FooValueType]) val schema = AvroSchema[Test] val record = Encoder[Test].encode(Test(Some(FooValueType("hello")))) record shouldBe ImmutableRecord(schema, Vector(new Utf8("hello"))) } } case class FooValueType(s: String) extends AnyVal
Example 5
Source File: TupleEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import com.sksamuel.avro4s.{AvroSchema, Encoder} import org.apache.avro.generic.GenericRecord import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class TupleEncoderTest extends AnyFunSuite with Matchers { test("encode tuple2") { case class Test(z: (String, Option[Int])) val schema = AvroSchema[Test] val record = Encoder[Test].encode(Test("hello", Some(55))).asInstanceOf[GenericRecord] val z = record.get("z").asInstanceOf[GenericRecord] z.get("_1") shouldBe new Utf8("hello") z.get("_2") shouldBe 55 } test("encode tuple3") { case class Test(z: (String, Option[Int], Long)) val schema = AvroSchema[Test] val record = Encoder[Test].encode(Test("hello", Some(55), 9999999L)).asInstanceOf[GenericRecord] val z = record.get("z").asInstanceOf[GenericRecord] z.get("_1") shouldBe new Utf8("hello") z.get("_2") shouldBe 55 z.get("_3") shouldBe 9999999L } test("encode tuple4") { case class Test(z: (String, Option[Int], Boolean, Double)) val schema = AvroSchema[Test] val record = Encoder[Test].encode(Test("hello", Some(55), true, 0.24)).asInstanceOf[GenericRecord] val z = record.get("z").asInstanceOf[GenericRecord] z.get("_1") shouldBe new Utf8("hello") z.get("_2") shouldBe 55 z.get("_3") shouldBe true z.get("_4") shouldBe 0.24 } test("encode tuple5") { case class Test(z: (String, Option[Int], String, Boolean, String)) val schema = AvroSchema[Test] val record = Encoder[Test].encode(Test("a", Some(55), "b", true, "c")).asInstanceOf[GenericRecord] val z = record.get("z").asInstanceOf[GenericRecord] z.get("_1") shouldBe new Utf8("a") z.get("_2") shouldBe 55 z.get("_3") shouldBe new Utf8("b") z.get("_4") shouldBe true z.get("_5") shouldBe new Utf8("c") } }
Example 6
Source File: EitherEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import com.sksamuel.avro4s.{AvroSchema, Encoder, ImmutableRecord} import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class EitherEncoderTest extends AnyFunSuite with Matchers { test("generate union:T,U for Either[T,U] of primitives") { case class Test(either: Either[String, Double]) Encoder[Test].encode(Test(Left("foo"))) shouldBe ImmutableRecord(AvroSchema[Test], Vector(new Utf8("foo"))) Encoder[Test].encode(Test(Right(234.4D))) shouldBe ImmutableRecord(AvroSchema[Test], Vector(java.lang.Double.valueOf(234.4D))) } test("generate union:T,U for Either[T,U] of records") { case class Goo(s: String) case class Foo(b: Boolean) case class Test(either: Either[Goo, Foo]) Encoder[Test].encode(Test(Left(Goo("zzz")))) shouldBe ImmutableRecord(AvroSchema[Test], Vector(ImmutableRecord(AvroSchema[Goo], Vector(new Utf8("zzz"))))) Encoder[Test].encode(Test(Right(Foo(true)))) shouldBe ImmutableRecord(AvroSchema[Test], Vector(ImmutableRecord(AvroSchema[Foo], Vector(java.lang.Boolean.valueOf(true))))) } }
Example 7
Source File: DateEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import java.sql.{Date, Timestamp} import java.time.{Instant, LocalDate, LocalDateTime, LocalTime} import com.sksamuel.avro4s.{AvroSchema, DefaultFieldMapper, Encoder, ImmutableRecord} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers //noinspection ScalaDeprecation class DateEncoderTest extends AnyFunSuite with Matchers { test("encode LocalTime as TIME-MILLIS") { case class Foo(s: LocalTime) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(LocalTime.of(12, 50, 45))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(46245000000L))) } test("encode LocalDate as DATE") { case class Foo(s: LocalDate) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(LocalDate.of(2018, 9, 10))) shouldBe ImmutableRecord(schema, Vector(java.lang.Integer.valueOf(17784))) } test("encode java.sql.Date as DATE") { case class Foo(s: Date) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(Date.valueOf(LocalDate.of(2018, 9, 10)))) shouldBe ImmutableRecord(schema, Vector(java.lang.Integer.valueOf(17784))) } test("encode LocalDateTime as timestamp-nanos") { case class Foo(s: LocalDateTime) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(LocalDateTime.of(2018, 9, 10, 11, 58, 59, 123))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1536580739000000123L))) Encoder[Foo].encode(Foo(LocalDateTime.of(2018, 9, 10, 11, 58, 59, 123009))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1536580739000123009L))) Encoder[Foo].encode(Foo(LocalDateTime.of(2018, 9, 10, 11, 58, 59, 328187943))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1536580739328187943L))) } test("encode Timestamp as TIMESTAMP-MILLIS") { case class Foo(s: Timestamp) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(Timestamp.from(Instant.ofEpochMilli(1538312231000L)))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1538312231000L))) } test("encode Instant as TIMESTAMP-MILLIS") { case class Foo(s: Instant) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(Instant.ofEpochMilli(1538312231000L))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1538312231000L))) } }
Example 8
Source File: NestedStructEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import com.sksamuel.avro4s.{AvroSchema, Encoder, ImmutableRecord} import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class NestedStructEncoderTest extends AnyFunSuite with Matchers { test("encode nested structs") { case class Foo(s: String) case class Fooo(foo: Foo) case class Foooo(fooo: Fooo) Encoder[Foooo].encode(Foooo(Fooo(Foo("a")))) shouldBe ImmutableRecord( AvroSchema[Foooo], Vector( ImmutableRecord( AvroSchema[Fooo], Vector( ImmutableRecord( AvroSchema[Foo], Vector(new Utf8("a")))) ) ) ) } }
Example 9
Source File: ByteArrayEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import java.nio.ByteBuffer import com.sksamuel.avro4s.{AvroSchema, Encoder, SchemaFor} import org.apache.avro.SchemaBuilder import org.apache.avro.generic.{GenericFixed, GenericRecord} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ByteArrayEncoderTest extends AnyFunSuite with Matchers { test("encode byte arrays as BYTES type") { case class Test(z: Array[Byte]) val schema = AvroSchema[Test] Encoder[Test].encode(Test(Array[Byte](1, 4, 9))) .asInstanceOf[GenericRecord] .get("z") .asInstanceOf[ByteBuffer] .array().toList shouldBe List[Byte](1, 4, 9) } test("encode byte vectors as BYTES type") { case class Test(z: Vector[Byte]) val schema = AvroSchema[Test] Encoder[Test].encode(Test(Vector[Byte](1, 4, 9))) .asInstanceOf[GenericRecord] .get("z") .asInstanceOf[ByteBuffer] .array().toList shouldBe List[Byte](1, 4, 9) } test("encode byte seq as BYTES type") { case class Test(z: Seq[Byte]) val schema = AvroSchema[Test] Encoder[Test].encode(Test(Seq[Byte](1, 4, 9))) .asInstanceOf[GenericRecord] .get("z") .asInstanceOf[ByteBuffer] .array().toList shouldBe List[Byte](1, 4, 9) } test("encode byte list as BYTES type") { case class Test(z: List[Byte]) val schema = AvroSchema[Test] Encoder[Test].encode(Test(List[Byte](1, 4, 9))) .asInstanceOf[GenericRecord] .get("z") .asInstanceOf[ByteBuffer] .array().toList shouldBe List[Byte](1, 4, 9) } test("encode top level byte arrays") { val schema = AvroSchema[Array[Byte]] Encoder[Array[Byte]].encode(Array[Byte](1, 4, 9)) .asInstanceOf[ByteBuffer] .array().toList shouldBe List[Byte](1, 4, 9) } test("encode ByteBuffers as BYTES type") { case class Test(z: ByteBuffer) val schema = AvroSchema[Test] Encoder[Test].encode(Test(ByteBuffer.wrap(Array[Byte](1, 4, 9)))) .asInstanceOf[GenericRecord] .get("z") .asInstanceOf[ByteBuffer] .array().toList shouldBe List[Byte](1, 4, 9) } test("encode top level ByteBuffers") { val schema = AvroSchema[ByteBuffer] Encoder[ByteBuffer].encode(ByteBuffer.wrap(Array[Byte](1, 4, 9))) .asInstanceOf[ByteBuffer] .array().toList shouldBe List[Byte](1, 4, 9) } test("support FIXED") { val schema = SchemaBuilder.fixed("foo").size(7) val fixed = Encoder.ByteArrayEncoder.withSchema(SchemaFor(schema)).encode("hello".getBytes).asInstanceOf[GenericFixed] fixed.bytes().toList shouldBe Seq(104, 101, 108, 108, 111, 0, 0) fixed.bytes().length shouldBe 7 } }
Example 10
Source File: FixedEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import com.sksamuel.avro4s.{AvroFixed, Encoder, SchemaFor} import org.apache.avro.generic.{GenericFixed, GenericRecord} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers @AvroFixed(8) case class QuarterSHA256(bytes: Array[Byte]) extends AnyVal case class FixedString(@AvroFixed(7) mystring: String) case class AvroMessage(q: QuarterSHA256, payload: Array[Byte]) @AvroFixed(8) case class FixedValueType(z: String) extends AnyVal case class OptionFixedWrapper(opt: Option[FixedValueType]) class FixedEncoderTest extends AnyFunSuite with Matchers { val m = AvroMessage( QuarterSHA256(Array[Byte](0, 1, 2, 3, 4, 5, 6)), Array[Byte](0, 1, 2, 3) ) test("encode fixed when used on a value type") { val schema = SchemaFor[AvroMessage] val record = Encoder[AvroMessage].encode(m).asInstanceOf[GenericRecord] record.get("q").asInstanceOf[GenericFixed].bytes().toVector shouldBe Vector(0, 1, 2, 3, 4, 5, 6, 0) } test("encode fixed when used on a field in a case class") { val schema = SchemaFor[FixedString] val record = Encoder[FixedString].encode(FixedString("sam")).asInstanceOf[GenericRecord] record.get("mystring").asInstanceOf[GenericFixed].bytes.toVector shouldBe Vector(115, 97, 109, 0, 0, 0, 0) } test("support options of fixed") { val schema = SchemaFor[OptionFixedWrapper] val record = Encoder[OptionFixedWrapper].encode(OptionFixedWrapper(Some(FixedValueType("sam")))).asInstanceOf[GenericRecord] record.get("opt").asInstanceOf[GenericFixed].bytes.toVector shouldBe Vector(115, 97, 109, 0, 0, 0, 0, 0) } }
Example 11
Source File: FieldMapperEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import com.sksamuel.avro4s.{Encoder, SchemaFor, SnakeCase} import org.apache.avro.generic.GenericRecord import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FieldMapperEncoderTest extends AnyFunSuite with Matchers { test("adding an in scope FieldMapper should overide the fields in an encoder") { implicit val fieldMapper = SnakeCase val schema: SchemaFor[NamingTest] = SchemaFor[NamingTest] val encoder = Encoder[NamingTest] val record = encoder.encode(NamingTest("Foo")).asInstanceOf[GenericRecord] record.get("camel_case") } } case class NamingTest(camelCase: String)
Example 12
Source File: CoproductEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import com.sksamuel.avro4s._ import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import shapeless.{:+:, CNil, Coproduct} class CoproductEncoderTest extends AnyFunSuite with Matchers { test("coproducts with primitives") { val encoder = Encoder[CPWrapper] encoder.encode(CPWrapper(Coproduct[CPWrapper.ISBG](4))) shouldBe ImmutableRecord(encoder.schema, Vector(java.lang.Integer.valueOf(4))) encoder.encode(CPWrapper(Coproduct[CPWrapper.ISBG]("wibble"))) shouldBe ImmutableRecord(encoder.schema, Vector(new Utf8("wibble"))) encoder.encode(CPWrapper(Coproduct[CPWrapper.ISBG](true))) shouldBe ImmutableRecord(encoder.schema, Vector(java.lang.Boolean.valueOf(true))) } test("coproducts with case classes") { val gschema = AvroSchema[Gimble] val encoder = Encoder[CPWrapper] encoder.encode(CPWrapper(Coproduct[CPWrapper.ISBG](Gimble("foo")))) shouldBe ImmutableRecord(encoder.schema, Vector(ImmutableRecord(gschema, Vector(new Utf8("foo"))))) } test("options of coproducts") { val schema = AvroSchema[CPWithOption] Encoder[CPWithOption].encode(CPWithOption(Some(Coproduct[CPWrapper.ISBG]("foo")))) shouldBe ImmutableRecord(schema, Vector(new Utf8("foo"))) Encoder[CPWithOption].encode(CPWithOption(None)) shouldBe ImmutableRecord(schema, Vector(null)) } test("coproducts with arrays") { val schema = AvroSchema[CPWithArray] Encoder[CPWithArray].encode(CPWithArray(Coproduct[CPWrapper.SSI](Seq("foo", "bar")))) shouldBe ImmutableRecord(schema, Vector(java.util.Arrays.asList(new Utf8("foo"), new Utf8("bar")))) Encoder[CPWithArray].encode(CPWithArray(Coproduct[CPWrapper.SSI](4))) shouldBe ImmutableRecord(schema, Vector(java.lang.Integer.valueOf(4))) } } case class CPWithArray(u: CPWrapper.SSI) case class Gimble(x: String) case class CPWrapper(u: CPWrapper.ISBG) case class CPWithOption(u: Option[CPWrapper.ISBG]) object CPWrapper { type ISBG = Int :+: String :+: Boolean :+: Gimble :+: CNil type SSI = Seq[String] :+: Int :+: CNil } case class Coproducts(union: Int :+: String :+: Boolean :+: CNil) case class CoproductsOfCoproducts(union: (Int :+: String :+: CNil) :+: Boolean :+: CNil)
Example 13
Source File: ToRecordTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record import com.sksamuel.avro4s.{AvroNamespace, ToRecord} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers sealed trait Foo case class Bar(i: Int) extends Foo case class Baz(s: String) extends Foo case class MySchema(@AvroNamespace("broken") foo: Foo, id: String, x: Int) class ToRecordTest extends AnyFunSuite with Matchers { test("ToRecord should work with a namespace annotation on an ADT") { val ms = MySchema(Bar(1), "", 0) ToRecord[MySchema].to(ms) //throws } }
Example 14
Source File: FixedDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import com.sksamuel.avro4s.record.encoder.FixedValueType import com.sksamuel.avro4s.{AvroFixed, AvroSchema, Decoder} import org.apache.avro.generic.GenericData import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FixedDecoderTest extends AnyFunSuite with Matchers { case class FixedString(@AvroFixed(10) z: String) case class OptionalFixedValueType(z: Option[FixedValueType]) test("decode bytes to String") { val schema = AvroSchema[FixedString] val record = new GenericData.Record(schema) record.put("z", Array[Byte](115, 97, 109)) Decoder[FixedString].decode(record) shouldBe FixedString("sam") } test("support options of fixed") { val schema = AvroSchema[OptionalFixedValueType] val record = new GenericData.Record(schema) record.put("z", new GenericData.Fixed(AvroSchema[FixedValueType], Array[Byte](115, 97, 109))) Decoder[OptionalFixedValueType].decode(record) shouldBe OptionalFixedValueType(Some(FixedValueType("sam"))) } }
Example 15
Source File: CoproductDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import com.sksamuel.avro4s.record.decoder.CPWrapper.{ISBG, ISCB} import com.sksamuel.avro4s.{AvroSchema, Decoder} import org.apache.avro.generic.GenericData import org.apache.avro.util.Utf8 import shapeless.{:+:, CNil, Coproduct} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class CoproductDecoderTest extends AnyFunSuite with Matchers { test("coproducts with primitives") { val decoder = Decoder[CPWrapper] val record = new GenericData.Record(decoder.schema) record.put("u", new Utf8("wibble")) decoder.decode(record) shouldBe CPWrapper(Coproduct[CPWrapper.ISBG]("wibble")) } test("coproducts with case classes") { val decoder = Decoder[CPWrapper] val gimble = new GenericData.Record(AvroSchema[Gimble]) gimble.put("x", new Utf8("foo")) val record = new GenericData.Record(decoder.schema) record.put("u", gimble) decoder.decode(record) shouldBe CPWrapper(Coproduct[CPWrapper.ISBG](Gimble("foo"))) } test("coproducts with options") { val codec = Decoder[CPWithOption] val gimble = new GenericData.Record(AvroSchema[Gimble]) gimble.put("x", new Utf8("foo")) val record = new GenericData.Record(codec.schema) record.put("u", gimble) codec.decode(record) shouldBe CPWithOption(Some(Coproduct[CPWrapper.ISBG](Gimble("foo")))) } test("coproduct with array") { val schema = AvroSchema[CPWithArray] val array = new GenericData.Array(AvroSchema[Seq[String]], List(new Utf8("a"), new Utf8("b")).asJava) val record = new GenericData.Record(schema) record.put("u", array) Decoder[CPWithArray].decode(record) shouldBe CPWithArray(Coproduct[CPWrapper.SSI](Seq("a", "b"))) } test("coproduct with array of coproducts") { val coproduct = CoproductWithArrayOfCoproduct(Coproduct[ISCB](Seq(Coproduct[ISBG](3), Coproduct[ISBG]("three")))) val array = new GenericData.Array(AvroSchema[Seq[ISBG]], List(3, new Utf8("three")).asJava) val record = new GenericData.Record(AvroSchema[CoproductWithArrayOfCoproduct]) record.put("union", array) Decoder[CoproductWithArrayOfCoproduct].decode(record) shouldBe coproduct } test("coproducts") { val schema = AvroSchema[Coproducts] val record = new GenericData.Record(schema) record.put("union", new Utf8("foo")) val coproduct = Coproduct[Int :+: String :+: Boolean :+: CNil]("foo") Decoder[Coproducts].decode(record) shouldBe Coproducts(coproduct) } test("coproducts of coproducts") { val schema = AvroSchema[CoproductsOfCoproducts] val record = new GenericData.Record(schema) record.put("union", new Utf8("foo")) val coproduct = Coproduct[(Int :+: String :+: CNil) :+: Boolean :+: CNil](Coproduct[Int :+: String :+: CNil]("foo")) Decoder[CoproductsOfCoproducts].decode(record) shouldBe CoproductsOfCoproducts(coproduct) } } case class CPWithArray(u: CPWrapper.SSI) case class Gimble(x: String) case class CPWrapper(u: CPWrapper.ISBG) case class CPWithOption(u: Option[CPWrapper.ISBG]) object CPWrapper { type ISBG = Int :+: String :+: Boolean :+: Gimble :+: CNil type SSI = Seq[String] :+: Int :+: CNil type ISCB = Int :+: Seq[ISBG] :+: String :+: CNil } case class Coproducts(union: Int :+: String :+: Boolean :+: CNil) case class CoproductsOfCoproducts(union: (Int :+: String :+: CNil) :+: Boolean :+: CNil) case class CoproductWithArrayOfCoproduct(union: CPWrapper.ISCB)
Example 16
Source File: FieldMapperDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import com.sksamuel.avro4s.record.encoder.NamingTest import com.sksamuel.avro4s.{AvroSchema, Decoder, FieldMapper, SchemaFor, SnakeCase} import org.apache.avro.generic.GenericData import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FieldMapperDecoderTest extends AnyFunSuite with Matchers { test("fieldMapper should override the field names in a decoder") { implicit val fieldMapper: FieldMapper = SnakeCase val schema = AvroSchema[NamingTest] val decoder = Decoder[NamingTest] val record = new GenericData.Record(schema) record.put("camel_case", "foo") val result = decoder.decode(record) result shouldBe NamingTest("foo") } }
Example 17
Source File: EitherDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import com.sksamuel.avro4s._ import org.apache.avro.SchemaBuilder import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers case class Test(either: Either[String, Double]) case class Goo(s: String) case class Foo(b: Boolean) case class Test2(either: Either[Goo, Foo]) class EitherDecoderTest extends AnyFunSuite with Matchers { case class Voo(s: String) case class Woo(b: Boolean) case class Test3(either: Either[Voo, Woo]) @AvroName("w") case class Wobble(s: String) @AvroName("t") case class Topple(b: Boolean) case class Test4(either: Either[Wobble, Topple]) @AvroNamespace("market") case class Apple(s: String) @AvroNamespace("market") case class Orange(b: Boolean) case class Test5(either: Either[Apple, Orange]) test("decode union:T,U for Either[T,U] of primitives") { val schema = AvroSchema[Test] Decoder[Test].decode(ImmutableRecord(schema, Vector(new Utf8("foo")))) shouldBe Test(Left("foo")) Decoder[Test].decode(ImmutableRecord(schema, Vector(java.lang.Double.valueOf(234.4D)))) shouldBe Test(Right(234.4D)) } test("decode union:T,U for Either[T,U] of top level classes") { val schema = AvroSchema[Test2] Decoder[Test2].decode(ImmutableRecord(schema, Vector(ImmutableRecord(AvroSchema[Goo], Vector(new Utf8("zzz")))))) shouldBe Test2(Left(Goo("zzz"))) Decoder[Test2].decode(ImmutableRecord(schema, Vector(ImmutableRecord(AvroSchema[Foo], Vector(java.lang.Boolean.valueOf(true)))))) shouldBe Test2(Right(Foo(true))) } test("decode union:T,U for Either[T,U] of nested classes") { val schema = AvroSchema[Test3] Decoder[Test3].decode(ImmutableRecord(schema, Vector(ImmutableRecord(AvroSchema[Voo], Vector(new Utf8("zzz")))))) shouldBe Test3(Left(Voo("zzz"))) Decoder[Test3].decode(ImmutableRecord(schema, Vector(ImmutableRecord(AvroSchema[Woo], Vector(java.lang.Boolean.valueOf(true)))))) shouldBe Test3(Right(Woo(true))) } test("use @AvroName defined on a class when choosing which Either to decode") { val wschema = SchemaBuilder.record("w").namespace("com.sksamuel.avro4s.record.decoder.EitherDecoderTest").fields().requiredBoolean("s").endRecord() val tschema = SchemaBuilder.record("t").namespace("com.sksamuel.avro4s.record.decoder.EitherDecoderTest").fields().requiredString("b").endRecord() val union = SchemaBuilder.unionOf().`type`(wschema).and().`type`(tschema).endUnion() val schema = SchemaBuilder.record("Test4").fields().name("either").`type`(union).noDefault().endRecord() Decoder[Test4].decode(ImmutableRecord(schema, Vector(ImmutableRecord(tschema, Vector(java.lang.Boolean.valueOf(true)))))) shouldBe Test4(Right(Topple(true))) Decoder[Test4].decode(ImmutableRecord(schema, Vector(ImmutableRecord(wschema, Vector(new Utf8("zzz")))))) shouldBe Test4(Left(Wobble("zzz"))) } test("use @AvroNamespace when choosing which Either to decode") { val appleschema = SchemaBuilder.record("Apple").namespace("market").fields().requiredBoolean("s").endRecord() val orangeschema = SchemaBuilder.record("Orange").namespace("market").fields().requiredString("b").endRecord() val union = SchemaBuilder.unionOf().`type`(appleschema).and().`type`(orangeschema).endUnion() val schema = SchemaBuilder.record("Test5").fields().name("either").`type`(union).noDefault().endRecord() Decoder[Test5].decode(ImmutableRecord(schema, Vector(ImmutableRecord(orangeschema, Vector(java.lang.Boolean.valueOf(true)))))) shouldBe Test5(Right(Orange(true))) Decoder[Test5].decode(ImmutableRecord(schema, Vector(ImmutableRecord(appleschema, Vector(new Utf8("zzz")))))) shouldBe Test5(Left(Apple("zzz"))) } }
Example 18
Source File: ValueTypeDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import com.sksamuel.avro4s.{AvroSchema, Decoder} import org.apache.avro.generic.GenericData import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ValueTypeDecoderTest extends AnyFunSuite with Matchers { case class Test(foo: FooValueType) case class OptionTest(foo: Option[FooValueType]) test("top level value types") { val actual = Decoder[FooValueType].decode("hello") actual shouldBe FooValueType("hello") } test("support fields that are value types") { val schema = AvroSchema[Test] val record1 = new GenericData.Record(schema) record1.put("foo", new Utf8("hello")) Decoder[Test].decode(record1) shouldBe Test(FooValueType("hello")) } test("support value types inside Options") { val schema = AvroSchema[OptionTest] val record1 = new GenericData.Record(schema) record1.put("foo", new Utf8("hello")) Decoder[OptionTest].decode(record1) shouldBe OptionTest(Some(FooValueType("hello"))) } } case class FooValueType(s: String) extends AnyVal
Example 19
Source File: SchemaEvolutionTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import java.io.{ByteArrayInputStream, ByteArrayOutputStream} import com.sksamuel.avro4s._ import org.apache.avro.SchemaBuilder import org.apache.avro.generic.GenericData import org.apache.avro.util.Utf8 import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class SchemaEvolutionTest extends AnyFunSuite with Matchers { case class Version1(original: String) case class Version2(@AvroAlias("original") renamed: String) case class P1(name: String, age: Int = 18) case class P2(name: String) case class OptionalStringTest(a: String, b: Option[String]) case class DefaultStringTest(a: String, b: String = "foo") ignore("@AvroAlias should be used when a reader schema has a field missing from the write schema") { val v1schema = AvroSchema[Version1] val v1 = Version1("hello") val baos = new ByteArrayOutputStream() val output = AvroOutputStream.data[Version1].to(baos).build() output.write(v1) output.close() // we load using a v2 schema val is = new AvroDataInputStream[Version2](new ByteArrayInputStream(baos.toByteArray), Some(v1schema)) val v2 = is.iterator.toList.head v2.renamed shouldBe v1.original } test("when decoding, if the record and schema are missing a field and the target has a scala default, use that") { val f1 = RecordFormat[P1] val f2 = RecordFormat[P2] f1.from(f2.to(P2("foo"))) shouldBe P1("foo") } test("when decoding, if the record is missing a field that is present in the schema with a default, use the default from the schema") { val schema = SchemaBuilder.record("foo").fields().requiredString("a").endRecord() val record = new GenericData.Record(schema) record.put("a", new Utf8("hello")) Decoder[DefaultStringTest].decode(record) shouldBe DefaultStringTest("hello") } test("when decoding, if the record is missing a field that is present in the schema and the type is option, then set to None") { val schema1 = SchemaBuilder.record("foo").fields().requiredString("a").endRecord() val schema2 = SchemaBuilder.record("foo").fields().requiredString("a").optionalString("b").endRecord() val record = new GenericData.Record(schema1) record.put("a", new Utf8("hello")) Decoder[OptionalStringTest].decode(record) shouldBe OptionalStringTest("hello", None) } }
Example 20
Source File: ByteArrayDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import java.nio.ByteBuffer import com.sksamuel.avro4s.{AvroSchema, Decoder} import org.apache.avro.generic.GenericData import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.language.higherKinds class ByteArrayDecoderTest extends AnyFunSuite with Matchers { case class ArrayTest(z: Array[Byte]) case class ByteBufferTest(z: ByteBuffer) case class VectorTest(z: Vector[Byte]) case class SeqTest(z: Array[Byte]) case class ListTest(z: Array[Byte]) test("decode byte arrays") { val schema = AvroSchema[ArrayTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ArrayTest].decode(record).z.toList shouldBe List[Byte](1, 4, 9) } test("decode bytebuffers to array") { val schema = AvroSchema[ArrayTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ArrayTest].decode(record).z.toList shouldBe List[Byte](1, 4, 9) } test("decode byte vectors") { val schema = AvroSchema[VectorTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[VectorTest].decode(record).z shouldBe Vector[Byte](1, 4, 9) } test("decode byte lists") { val schema = AvroSchema[ListTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ListTest].decode(record).z shouldBe List[Byte](1, 4, 9) } test("decode byte seqs") { val schema = AvroSchema[SeqTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[SeqTest].decode(record).z shouldBe Seq[Byte](1, 4, 9) } test("decode top level byte arrays") { Decoder[Array[Byte]].decode(ByteBuffer.wrap(Array[Byte](1, 4, 9))).toList shouldBe List[Byte](1, 4, 9) } test("decode array to bytebuffers") { val schema = AvroSchema[ByteBufferTest] val record = new GenericData.Record(schema) record.put("z", Array[Byte](1, 4, 9)) Decoder[ByteBufferTest].decode(record).z.array().toList shouldBe List[Byte](1, 4, 9) } test("decode bytebuffers") { val schema = AvroSchema[ByteBufferTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ByteBufferTest].decode(record).z.array().toList shouldBe List[Byte](1, 4, 9) } test("decode top level ByteBuffers") { Decoder[ByteBuffer].decode(ByteBuffer.wrap(Array[Byte](1, 4, 9))).array().toList shouldBe List[Byte](1, 4, 9) } }
Example 21
Source File: DateDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import java.sql.{Date, Timestamp} import java.time.{Instant, LocalDate, LocalDateTime, LocalTime} import com.sksamuel.avro4s.SchemaFor.TimestampNanosLogicalType import com.sksamuel.avro4s.{AvroSchema, Decoder, SchemaFor} import org.apache.avro.generic.GenericData import org.apache.avro.{LogicalTypes, SchemaBuilder} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers //noinspection ScalaDeprecation class DateDecoderTest extends AnyFunSuite with Matchers { case class WithLocalTime(z: LocalTime) case class WithLocalDate(z: LocalDate) case class WithDate(z: Date) case class WithLocalDateTime(z: LocalDateTime) case class WithTimestamp(z: Timestamp) case class WithInstant(z: Instant) test("decode int to LocalTime") { val schema = AvroSchema[WithLocalTime] val record = new GenericData.Record(schema) record.put("z", 46245000000L) Decoder[WithLocalTime].decode(record) shouldBe WithLocalTime(LocalTime.of(12, 50, 45)) } test("decode int to LocalDate") { val schema = AvroSchema[WithLocalDate] val record = new GenericData.Record(schema) record.put("z", 17784) Decoder[WithLocalDate].decode(record) shouldBe WithLocalDate(LocalDate.of(2018, 9, 10)) } test("decode int to java.sql.Date") { val schema = AvroSchema[WithDate] val record = new GenericData.Record(schema) record.put("z", 17784) Decoder[WithDate].decode(record) shouldBe WithDate(Date.valueOf(LocalDate.of(2018, 9, 10))) } test("decode timestamp-millis to LocalDateTime") { val dateSchema = LogicalTypes.timestampMillis().addToSchema(SchemaBuilder.builder.longType) val schema = SchemaBuilder.record("foo").fields().name("z").`type`(dateSchema).noDefault().endRecord() val record = new GenericData.Record(schema) record.put("z", 1572707106376L) Decoder[WithLocalDateTime].withSchema(SchemaFor(schema)).decode(record) shouldBe WithLocalDateTime( LocalDateTime.of(2019, 11, 2, 15, 5, 6, 376000000)) } test("decode timestamp-micros to LocalDateTime") { val dateSchema = LogicalTypes.timestampMicros().addToSchema(SchemaBuilder.builder.longType) val schema = SchemaBuilder.record("foo").fields().name("z").`type`(dateSchema).noDefault().endRecord() val record = new GenericData.Record(schema) record.put("z", 1572707106376001L) Decoder[WithLocalDateTime].withSchema(SchemaFor(schema)).decode(record) shouldBe WithLocalDateTime( LocalDateTime.of(2019, 11, 2, 15, 5, 6, 376001000)) } test("decode timestamp-nanos to LocalDateTime") { val dateSchema = TimestampNanosLogicalType.addToSchema(SchemaBuilder.builder.longType) val schema = SchemaBuilder.record("foo").fields().name("z").`type`(dateSchema).noDefault().endRecord() val record = new GenericData.Record(schema) record.put("z", 1572707106376000002L) Decoder[WithLocalDateTime].decode(record) shouldBe WithLocalDateTime( LocalDateTime.of(2019, 11, 2, 15, 5, 6, 376000002)) } test("decode long to Timestamp") { val schema = AvroSchema[WithTimestamp] val record = new GenericData.Record(schema) record.put("z", 1538312231000L) Decoder[WithTimestamp].decode(record) shouldBe WithTimestamp(new Timestamp(1538312231000L)) } test("decode long to Instant") { val schema = AvroSchema[WithInstant] val record = new GenericData.Record(schema) record.put("z", 1538312231000L) Decoder[WithInstant].decode(record) shouldBe WithInstant(Instant.ofEpochMilli(1538312231000L)) } }
Example 22
Source File: TupleSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.AvroSchema import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class TupleSchemaTest extends AnyFunSuite with Matchers { case class Test2(z: (String, Int)) case class Test3(z: (String, Int, Boolean)) case class Test4(z: (String, Int, Boolean, Double)) case class Test5(z: (String, Int, Boolean, Double, Long)) test("tuple 2 schema") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/tuple2.json")) val schema = AvroSchema[Test2] schema.toString(true) shouldBe expected.toString(true) } test("tuple 3 schema") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/tuple3.json")) val schema = AvroSchema[Test3] schema.toString(true) shouldBe expected.toString(true) } test("tuple 4 schema") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/tuple4.json")) val schema = AvroSchema[Test4] schema.toString(true) shouldBe expected.toString(true) } test("tuple 5 schema") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/tuple5.json")) val schema = AvroSchema[Test5] schema.toString(true) shouldBe expected.toString(true) } }
Example 23
Source File: NamespaceSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.AvroSchema import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class NamespaceSchemaTest extends AnyFunSuite with Matchers { test("use package name for top level class") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/top_level_class_namespace.json")) val schema = AvroSchema[Tau] schema.toString(true) shouldBe expected.toString(true) } test("use package name without .package for classes defined in the package object") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/top_level_package_object_namespace.json")) val schema = AvroSchema[Sigma] schema.toString(true) shouldBe expected.toString(true) } test("use namespace of object for classes defined inside an object") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/top_level_object_namespace.json")) val schema = AvroSchema[A] schema.toString(true) shouldBe expected.toString(true) } test("local classes should use the namespace of their parent object package") { case class NamespaceTestFoo(inner: String) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/local_class_namespace.json")) val schema = AvroSchema[NamespaceTestFoo] schema.toString(true) shouldBe expected.toString(true) } } case class Tau(a: String, b: Boolean) case class A(inner: A.Inner) object A { final case class Inner(s: String) }
Example 24
Source File: AvroSortPrioritySchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.{AvroSchema, AvroSortPriority} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class AvroSortPrioritySchemaTest extends AnyFunSuite with Matchers { test("enums should be sorted by descending priority") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_sort_priority_enum.json")) val schema = AvroSchema[Numeric] schema.toString(true) shouldBe expected.toString(true) } test("unions should be sorted by descending priority") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_sort_priority_union.json")) val schema = AvroSchema[FightingStyleWrapper] schema.toString(true) shouldBe expected.toString(true) } test("avrosortpriority should respect union default ordering") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_sort_priority_union_with_default.json")) val schema = AvroSchema[FightingStyleWrapperWithDefault] schema.toString(true) shouldBe expected.toString(true) } } sealed trait Numeric @AvroSortPriority(1) case object RationalNumber extends Numeric @AvroSortPriority(0) case object RealNumber extends Numeric @AvroSortPriority(2) case object NaturalNumber extends Numeric case class FightingStyleWrapper(fightingstyle: FightingStyle) case class FightingStyleWrapperWithDefault(fightingstyle: FightingStyle = AggressiveFightingStyle(10)) sealed trait FightingStyle @AvroSortPriority(2) case class AggressiveFightingStyle(agressiveness: Float) extends FightingStyle @AvroSortPriority(10) case class DefensiveFightingStyle(has_armor: Boolean) extends FightingStyle
Example 25
Source File: CoproductSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.AvroSchema import shapeless.{:+:, Coproduct, CNil} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class CoproductSchemaTest extends AnyFunSuite with Matchers { test("coproducts") { val schema = AvroSchema[CPWrapper] val expected = parseSchema("/coproduct.json") schema.toString(true) shouldBe expected.toString(true) } test("options of coproducts") { val schema = AvroSchema[CPWithOption] val expected = parseSchema("/coproduct_option.json") schema.toString(true) shouldBe expected.toString(true) } test("support coproducts of coproducts") { val coproductOfCoproducts = AvroSchema[CoproductOfCoproducts] val expected = parseSchema("/coproduct_of_coproducts.json") coproductOfCoproducts.toString(true) shouldBe expected.toString(true) } test("coproducts with default arguments") { val schema = AvroSchema[CPWithDefault] val expected = parseSchema("/coproduct_with_default.json") schema.toString(true) shouldBe expected.toString(true) } def parseSchema(resourcePath: String) = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream(resourcePath)) } case class Gimble(x: String) case class CPWrapper(u: CPWrapper.ISBG) case class CPWithOption(u: Option[CPWrapper.ISBG]) case class CPWithDefault(u: CPWrapper.ISBG = Coproduct[CPWrapper.ISBG](123)) object CPWrapper { type ISBG = Int :+: String :+: Boolean :+: Gimble :+: CNil } case class Coproducts(cp: Int :+: String :+: Boolean :+: CNil) case class CoproductOfCoproducts(cp: (Int :+: String :+: CNil) :+: Boolean :+: CNil)
Example 26
Source File: AvroNameSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.{AvroName, AvroSchema, SnakeCase} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class AvroNameSchemaTest extends AnyFunSuite with Matchers { test("generate field names using @AvroName") { case class Foo(@AvroName("wibble") wobble: String, wubble: String) val schema = AvroSchema[Foo] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_name_field.json")) schema.toString(true) shouldBe expected.toString(true) } test("generate class names using @AvroName") { @AvroName("wibble") case class Foo(a: String, b: String) val schema = AvroSchema[Foo] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_name_class.json")) schema.toString(true) shouldBe expected.toString(true) } test("@AvroName on top level java enum") { val schema = AvroSchema[MyJavaEnum] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_name_java_enum.json")) schema.toString(true) shouldBe expected.toString(true) } test("@AvroName on field level java enum") { case class Wibble(e: MyJavaEnum) val schema = AvroSchema[Wibble] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_name_nested_java_enum.json")) schema.toString(true) shouldBe expected.toString(true) } test("@AvroName on top level ADT type") { val schema = AvroSchema[Weather] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_name_sealed_trait.json")) schema.toString(true) shouldBe expected.toString(true) } } @AvroName("foofoo") sealed trait Weather case object Rainy extends Weather case object Sunny extends Weather
Example 27
Source File: SealedTraitSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.{AvroSchema, AvroName} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class SealedTraitSchemaTest extends AnyFunSuite with Matchers { test("support sealed traits of case classes") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/sealed_traits.json")) val schema = AvroSchema[Wrapper] schema.toString(true) shouldBe expected.toString(true) } test("support trait subtypes fields with same name") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/trait_subtypes_duplicate_fields.json")) val schema = AvroSchema[Trapper] schema.toString(true) shouldBe expected.toString(true) } test("support trait subtypes fields with same name and same type") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/trait_subtypes_duplicate_fields_same_type.json")) val schema = AvroSchema[Napper] schema.toString(true) shouldBe expected.toString(true) } test("support top level ADTs") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/top_level_sealed_trait.json")) val schema = AvroSchema[Nibble] schema.toString(true) shouldBe expected.toString(true) } test("trait of case objects at the top level should be encoded as enum") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/sealed_trait_of_objects.json")) val schema = AvroSchema[Dibble] schema.toString(true) shouldBe expected.toString(true) } sealed trait Foo extends Product with Serializable case object Bar extends Foo case object Baz extends Foo case class Schema(foo: Foo) test("trait of case objects at a nested level should be encoded as enum") { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/sealed_trait_of_nested_objects.json")) val schema = AvroSchema[Schema] schema.toString(true) shouldBe expected.toString(true) } test("classes nested in objects should be encoded with consistent package name") { sealed trait Inner case class InnerOne(value: Double) extends Inner case class InnerTwo(height: Double) extends Inner case class Outer(inner: Inner) val schema = AvroSchema[Outer] schema.getNamespace shouldBe "com.sksamuel.avro4s.schema.SealedTraitSchemaTest" } } sealed trait Dibble case object Dabble extends Dibble @AvroName("Dobble") case object Dobbles extends Dibble sealed trait Wibble case class Wobble(str: String) extends Wibble case class Wabble(dbl: Double) extends Wibble case class Wrapper(wibble: Wibble) sealed trait Tibble case class Tabble(str: Double, age: Int) extends Tibble case class Tobble(str: String, place: String) extends Tibble case class Trapper(tibble: Tibble) sealed trait Nibble case class Nabble(str: String, age: Int) extends Nibble case class Nobble(str: String, place: String) extends Nibble case class Napper(nibble: Nibble)
Example 28
Source File: DateSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import java.sql.{Date, Timestamp} import java.time.{Instant, LocalDate, LocalDateTime, LocalTime} import com.sksamuel.avro4s.AvroSchema import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class DateSchemaTest extends AnyFunSuite with Matchers { test("generate date logical type for LocalDate") { case class LocalDateTest(date: LocalDate) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/localdate.json")) val schema = AvroSchema[LocalDateTest] schema.toString(true) shouldBe expected.toString(true) } test("generate date logical type for Date") { case class DateTest(date: Date) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/date.json")) val schema = AvroSchema[DateTest] schema.toString(true) shouldBe expected.toString(true) } test("generate time logical type for LocalTime") { case class LocalTimeTest(time: LocalTime) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/localtime.json")) val schema = AvroSchema[LocalTimeTest] schema.toString(true) shouldBe expected.toString(true) } test("generate timestamp-nanos for LocalDateTime") { case class LocalDateTimeTest(time: LocalDateTime) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/localdatetime.json")) val schema = AvroSchema[LocalDateTimeTest] schema.toString(true) shouldBe expected.toString(true) } test("generate timestamp-millis logical type for Instant") { case class InstantTest(instant: Instant) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/instant.json")) val schema = AvroSchema[InstantTest] schema.toString(true) shouldBe expected.toString(true) } test("generate timestamp-millis logical type for Timestamp") { case class TimestampTest(ts: Timestamp) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/timestamp.json")) val schema = AvroSchema[TimestampTest] schema.toString(true) shouldBe expected.toString(true) } }
Example 29
Source File: GenericSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import java.util.UUID import com.sksamuel.avro4s.{AvroErasedName, AvroName, AvroSchema} import org.apache.avro.SchemaParseException import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers case class Thing1Id(id: Int) extends AnyVal case class Thing2Id(id: UUID) extends AnyVal case class Thing2(id: Thing2Id, name: String) case class OuterId(id: UUID) extends AnyVal case class InnerId(id: String) extends AnyVal case class Inner[LEFT, RIGHT]( id: InnerId, left: LEFT, right: Option[RIGHT] = None ) case class Outer[LEFT, RIGHT]( id: OuterId, @AvroName("innerThing") theInnerThing: Inner[LEFT, RIGHT] ) class GenericSchemaTest extends AnyFunSuite with Matchers { case class Generic[T](t: T) case class SameGenericWithDifferentTypeArgs(gi: Generic[Int], gs: Generic[String]) @AvroErasedName case class GenericDisabled[T](t: T) case class SameGenericWithDifferentTypeArgsDisabled(gi: GenericDisabled[Int], gs: GenericDisabled[String]) test("support same generic with different type parameters") { val schema = AvroSchema[SameGenericWithDifferentTypeArgs] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/generic.json")) schema.toString(true) shouldBe expected.toString(true) } test("throw error if different type parameters are disabled by @AvroErasedName") { intercept[SchemaParseException] { val schema = AvroSchema[SameGenericWithDifferentTypeArgsDisabled] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/generic.json")) schema.toString(true) shouldBe expected.toString(true) } } test("support top level generic") { val schema1 = AvroSchema[Generic[String]] val expected1 = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/generic_string.json")) schema1.toString(true) shouldBe expected1.toString(true) val schema2 = AvroSchema[Generic[Int]] val expected2 = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/generic_int.json")) schema2.toString(true) shouldBe expected2.toString(true) } test("generate only raw name if @AvroErasedName is present") { val schema = AvroSchema[GenericDisabled[String]] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/generic_disabled.json")) schema.toString(true) shouldBe expected.toString(true) } test("support @AvroName on generic type args") { val schema = AvroSchema[DibDabDob] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/avro_name_on_type_arg.json")) schema.toString(true) shouldBe expected.toString(true) } test("deeply nested generics") { val schema = AvroSchema[Outer[Thing1Id, Option[Seq[Thing2]]]] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/deeply_nested_generics.json")) schema.toString(true) shouldBe expected.toString(true) } test("deeply nested generic with value type") { val schema = AvroSchema[Generic[Option[Seq[Thing1Id]]]] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/deeply_nested_generic_with_value_type.json")) schema.toString(true) shouldBe expected.toString(true) } } object First { case class TypeArg(a: String) } object Second { @AvroName("wibble") case class TypeArg(a: String) } case class Generic[T](value: T) case class DibDabDob(a: Generic[First.TypeArg], b: Generic[Second.TypeArg])
Example 30
Source File: SchemaForTypeclassOverrideTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.{AvroSchema, SchemaFor} import org.apache.avro.SchemaBuilder import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class SchemaForTypeclassOverrideTest extends AnyFunSuite with Matchers { test("allow overriding built in SchemaFor implicit for a basic type") { implicit val StringSchemaFor = SchemaFor[String] { val schema = SchemaBuilder.builder().bytesType() schema.addProp("foo", "bar": AnyRef) schema } case class OverrideTest(s: String, i: Int) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/schema_override_basic.json")) val schema = AvroSchema[OverrideTest] schema.toString(true) shouldBe expected.toString(true) } test("allow overriding built in SchemaFor implicit for a complex type") { implicit val FooSchemaFor = SchemaFor[Foo] { val schema = SchemaBuilder.builder().doubleType() schema.addProp("foo", "bar": AnyRef) schema } case class Foo(s: String, b: Boolean) case class OverrideTest(s: String, f: Foo) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/schema_override_complex.json")) val schema = AvroSchema[OverrideTest] schema.toString(true) shouldBe expected.toString(true) } test("allow overriding built in SchemaFor implicit for a value type") { implicit val FooValueTypeSchemaFor = SchemaFor[FooValueType] { val schema = SchemaBuilder.builder().intType() schema.addProp("foo", "bar": AnyRef) schema } case class OverrideTest(s: String, foo: FooValueType) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/schema_override_value_type.json")) val schema = AvroSchema[FooValueType] schema.toString(true) shouldBe expected.toString(true) } test("allow overriding built in SchemaFor implicit for a top level value type") { implicit val FooValueTypeSchemaFor = SchemaFor[FooValueType] { val schema = SchemaBuilder.builder().intType() schema.addProp("foo", "bar": AnyRef) schema } val expected = new org.apache.avro.Schema.Parser() .parse(getClass.getResourceAsStream("/schema_override_top_level_value_type.json")) val schema = AvroSchema[FooValueType] schema.toString(true) shouldBe expected.toString(true) } } case class FooValueType(s: String) extends AnyVal
Example 31
Source File: ByteArraySchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import java.nio.ByteBuffer import com.sksamuel.avro4s.AvroSchema import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ByteArraySchemaTest extends AnyFunSuite with Matchers { test("encode byte arrays as BYTES type") { case class Test(z: Array[Byte]) val schema = AvroSchema[Test] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/byte_array.json")) schema.toString(true) shouldBe expected.toString(true) } test("encode seq arrays as BYTES type") { case class Test(z: Seq[Byte]) val schema = AvroSchema[Test] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/byte_array.json")) schema.toString(true) shouldBe expected.toString(true) } test("encode list arrays as BYTES type") { case class Test(z: List[Byte]) val schema = AvroSchema[Test] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/byte_array.json")) schema.toString(true) shouldBe expected.toString(true) } test("encode vector arrays as BYTES type") { case class Test(z: Vector[Byte]) val schema = AvroSchema[Test] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/byte_array.json")) schema.toString(true) shouldBe expected.toString(true) } test("support top level byte arrays") { val schema = AvroSchema[Array[Byte]] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/top_level_byte_array.json")) schema.toString(true) shouldBe expected.toString(true) } test("encode ByteBuffer as BYTES type") { case class Test(z: ByteBuffer) val schema = AvroSchema[Test] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/bytebuffer.json")) schema.toString(true) shouldBe expected.toString(true) } test("support top level ByteBuffers") { val schema = AvroSchema[ByteBuffer] val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/top_level_bytebuffer.json")) schema.toString(true) shouldBe expected.toString(true) } }
Example 32
Source File: EnumSuite.scala From enum with MIT License | 5 votes |
package enum import org.scalatest.funsuite.AnyFunSuite class EnumSuite extends AnyFunSuite { test("Enum[Foo]") { val enum = Foo.enum assert(enum.values == Set(Foo.Bar, Foo.Baz)) assert(enum.labels == Set("Bar", "Baz")) assert(enum.encode(Foo.Bar) == "Bar") assert(enum.decode("Baz") == Right(Foo.Baz)) assert(enum.decode("invalid") == Left(DecodingFailure[Foo](Set("Bar", "Baz")))) assert(enum.decodeOpt("Bar") == Some(Foo.Bar)) assert(enum.decodeOpt("invalid") == None) } test("Enum[TwoLevels]") { assert(Enum[TwoLevels].labels == Set("FirstValue", "SecondValue", "ThirdValue")) } }
Example 33
Source File: BifunctorSpec.scala From kafka4s with Apache License 2.0 | 5 votes |
package com.banno.kafka import cats.laws.discipline.BifunctorTests import com.banno.kafka.test._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.Checkers import org.typelevel.discipline.scalatest.FunSuiteDiscipline class BifunctorSpec extends AnyFunSuite with Matchers with Checkers with FunSuiteDiscipline { checkAll( "ProducerRecordBifunctor", BifunctorTests(ProducerRecordBifunctor).bifunctor[Int, Int, Int, String, String, String] ) checkAll( "ConsumerRecordBifunctor", BifunctorTests(ConsumerRecordBifunctor).bifunctor[Int, Int, Int, String, String, String] ) }
Example 34
Source File: MonixAsyncHandlerTest.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s.monixs import java.util.UUID import com.sksamuel.pulsar4s._ import org.apache.pulsar.client.api.Schema import org.scalatest.BeforeAndAfterAll import scala.concurrent.Await import scala.concurrent.duration.Duration import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class MonixAsyncHandlerTest extends AnyFunSuite with Matchers with BeforeAndAfterAll { import monix.execution.Scheduler.Implicits.global import MonixAsyncHandler._ implicit val schema: Schema[String] = Schema.STRING val client = PulsarClient("pulsar://localhost:6650") val topic = Topic("persistent://sample/standalone/ns1/monix_" + UUID.randomUUID()) override def afterAll(): Unit = { client.close() } test("async producer should use monix") { val producer = client.producer(ProducerConfig(topic)) val t = producer.sendAsync("wibble") val f = t.runToFuture Await.result(f, Duration.Inf) should not be null producer.close() } test("async consumer should use monix") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription("mysub_" + UUID.randomUUID()))) consumer.seekEarliest() val t = consumer.receiveAsync val f = t.runToFuture new String(Await.result(f, Duration.Inf).data) shouldBe "wibble" consumer.close() } test("async consumer getMessageById should use monix") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription("mysub_" + UUID.randomUUID()))) consumer.seekEarliest() val receive = consumer.receiveAsync val valueFuture = receive.runToFuture val value = Await.result(valueFuture, Duration.Inf) val t = consumer.getLastMessageIdAsync val rFuture = t.runToFuture val r = Await.result(rFuture, Duration.Inf) val zipped = r.toString.split(":") zip value.messageId.toString.split(":") zipped.foreach(t => t._1 shouldBe t._2) consumer.close() } }
Example 35
Source File: ZioAsyncHandlerTest.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s.zio import java.util.UUID import com.sksamuel.pulsar4s.{ConsumerConfig, ProducerConfig, PulsarClient, Subscription, Topic} import org.apache.pulsar.client.api.Schema import org.scalatest.BeforeAndAfterAll import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import java.util.regex.Pattern class ZioAsyncHandlerTest extends AnyFunSuite with Matchers with BeforeAndAfterAll { import ZioAsyncHandler._ implicit val schema: Schema[String] = Schema.STRING private val client = PulsarClient("pulsar://localhost:6650") private val topic = Topic("persistent://sample/standalone/ns1/zio_" + UUID.randomUUID()) override def afterAll(): Unit = { client.close() } test("async producer should use zio") { val producer = client.producer(ProducerConfig(topic)) val t = producer.sendAsync("wibble") val r = zio.Runtime.default.unsafeRun(t.either) r.right.get should not be null producer.close() } test("async consumer should use zio") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription("mysub_" + UUID.randomUUID()))) consumer.seekEarliest() val t = consumer.receiveAsync val r = zio.Runtime.default.unsafeRun(t.either) r shouldBe Symbol("right") new String(r.right.get.data) shouldBe "wibble" consumer.close() } test("async consumer getMessageById should use zio") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription("mysub_" + UUID.randomUUID()))) consumer.seekEarliest() val receive = consumer.receiveAsync val value = zio.Runtime.default.unsafeRun(receive.either) val t = consumer.getLastMessageIdAsync val r = zio.Runtime.default.unsafeRun(t.either) val zipped = r.right.get.toString.split(":") zip value.right.get.messageId.toString.split(":") zipped.foreach(t => t._1 shouldBe t._2) consumer.close() } }
Example 36
Source File: ScalazAsyncHandlerTest.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s.scalaz import java.util.UUID import com.sksamuel.pulsar4s._ import org.apache.pulsar.client.api.Schema import org.scalatest.BeforeAndAfterAll import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ScalazAsyncHandlerTest extends AnyFunSuite with Matchers with BeforeAndAfterAll { implicit val schema: Schema[String] = Schema.STRING val client = PulsarClient("pulsar://localhost:6650") val topic = Topic("persistent://sample/standalone/ns1/scalaz_" + UUID.randomUUID()) override def afterAll(): Unit = { client.close() } import ScalazAsyncHandler._ test("async producer should use scalaz task") { val producer = client.producer(ProducerConfig(topic)) val t = producer.sendAsync("wibble") t.unsafePerformSync should not be null producer.close() } test("async consumer should use scalaz task") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription.generate) ) consumer.seekEarliest() val t = consumer.receiveAsync new String(t.unsafePerformSync.data) shouldBe "wibble" consumer.close() } test("async consumer getMessageById should use scalaz task") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription.generate) ) consumer.seekEarliest() val receive = consumer.receiveAsync val value = receive.unsafePerformSync val t = consumer.getLastMessageIdAsync val r = t.unsafePerformSync val zipped = r.toString.split(":") zip value.messageId.toString.split(":") zipped.foreach(t => t._1 shouldBe t._2) consumer.close() } }
Example 37
Source File: FutureAsyncHandlerTest.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s import java.util.UUID import org.apache.pulsar.client.api.Schema import org.scalatest.BeforeAndAfterAll import scala.concurrent.Await import scala.concurrent.duration.Duration import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FutureAsyncHandlerTest extends AnyFunSuite with Matchers with BeforeAndAfterAll { import scala.concurrent.ExecutionContext.Implicits.global implicit val schema: Schema[String] = Schema.STRING private val client = PulsarClient("pulsar://localhost:6650") private val topic = Topic("persistent://sample/standalone/ns1/futureasync_" + UUID.randomUUID()) override def afterAll(): Unit = { client.close() } test("async producer should bring future effect into scope by default") { val producer = client.producer(ProducerConfig(topic)) val f = producer.sendAsync("wibble") Await.result(f, Duration.Inf) should not be null producer.close() } test("async consumer should bring future effect into scope by default") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription("mysub_" + UUID.randomUUID))) consumer.seekEarliest() val f = consumer.receiveAsync new String(Await.result(f, Duration.Inf).data) shouldBe "wibble" consumer.close() } test("async consumer getMessageById should bring future effect into scope by default") { val consumer = client.consumer(ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription("mysub_" + UUID.randomUUID))) consumer.seekEarliest() val receive = consumer.receiveAsync val value = Await.result(receive, Duration.Inf) val t = consumer.getLastMessageIdAsync val r = Await.result(t, Duration.Inf) val zipped = r.toString.split(":") zip value.messageId.toString.split(":") zipped.foreach(t => t._1 shouldBe t._2) consumer.close() } }
Example 38
Source File: PulsarMultiSinkTest.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s.akka.streams import java.util.UUID import akka.Done import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.scaladsl.Source import com.sksamuel.pulsar4s._ import org.apache.pulsar.client.api.Schema import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.concurrent.Await import scala.concurrent.duration._ class PulsarMultiSinkTest extends AnyFunSuite with Matchers { implicit val system: ActorSystem = ActorSystem() implicit val materializer: ActorMaterializer = ActorMaterializer() implicit val schema: Schema[String] = Schema.STRING val client = PulsarClient("pulsar://localhost:6650") test("pulsar multi sink should write single-topic messages to pulsar cluster") { val topic = Topic("persistent://sample/standalone/ns1/sinktest_" + UUID.randomUUID) val producerFn = (topic: Topic) => client.producer(ProducerConfig(topic)) val f = Source.fromIterator(() => List("a", "b", "c", "d").iterator) .map(string => topic -> ProducerMessage(string)) .runWith(multiSink(producerFn)) Await.ready(f, 15.seconds) val config = ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription.generate) val consumer = client.consumer(config) consumer.seekEarliest() Iterator.continually(consumer.receive(30.seconds).get).take(4).toList.flatten.size shouldBe 4 } test("pulsar multi sink should write multi-topic messages to pulsar cluster") { val topic1 = Topic("persistent://sample/standalone/ns1/sinktest_" + UUID.randomUUID) val topic2 = Topic("persistent://sample/standalone/ns1/sinktest_" + UUID.randomUUID) val producerFn = (topic: Topic) => client.producer(ProducerConfig(topic)) val f = Source.fromIterator(() => (List("a", "b", "c", "d").map(x => topic1 -> x) ++ List("e", "f", "g", "h").map(x => topic2 -> x)).iterator) .map { case (t, s) => t -> ProducerMessage(s) } .runWith(multiSink(producerFn)) Await.ready(f, 15.seconds) val config1 = ConsumerConfig(topics = Seq(topic1), subscriptionName = Subscription.generate) val consumer1 = client.consumer(config1) consumer1.seekEarliest() Iterator.continually(consumer1.receive(30.seconds).get).take(4).toList.flatten.size shouldBe 4 val config2 = ConsumerConfig(topics = Seq(topic2), subscriptionName = Subscription.generate) val consumer2 = client.consumer(config2) consumer2.seekEarliest() Iterator.continually(consumer2.receive(30.seconds).get).take(4).toList.flatten.size shouldBe 4 } test("future done should be completed when stream completes") { val topic = Topic("persistent://sample/standalone/ns1/sinktest_" + UUID.randomUUID) val producerFn = (topic: Topic) => client.producer(ProducerConfig(topic)) val f = Source.fromIterator(() => List("a").iterator) .map(string => topic -> ProducerMessage(string)) .runWith(multiSink(producerFn)) Await.result(f, 15.seconds) shouldBe Done } }
Example 39
Source File: PulsarSinkTest.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s.akka.streams import java.util.UUID import akka.Done import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.scaladsl.Source import com.sksamuel.pulsar4s.{ConsumerConfig, ProducerConfig, ProducerMessage, PulsarClient, Subscription, Topic} import org.apache.pulsar.client.api.Schema import scala.concurrent.Await import scala.concurrent.duration._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class PulsarSinkTest extends AnyFunSuite with Matchers { implicit val system: ActorSystem = ActorSystem() implicit val materializer: ActorMaterializer = ActorMaterializer() implicit val schema: Schema[String] = Schema.STRING val client = PulsarClient("pulsar://localhost:6650") test("pulsar sink should write messages to pulsar cluster") { val topic = Topic("persistent://sample/standalone/ns1/sinktest_" + UUID.randomUUID) val producerFn = () => client.producer(ProducerConfig(topic)) val f = Source.fromIterator(() => List("a", "b", "c", "d").iterator) .map(string => ProducerMessage(string)) .runWith(sink(producerFn)) Await.ready(f, 15.seconds) val config = ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription.generate) val consumer = client.consumer(config) consumer.seekEarliest() Iterator.continually(consumer.receive(30.seconds).get).take(4).toList.flatten.size shouldBe 4 } test("future done should be completed when stream completes") { val topic = Topic("persistent://sample/standalone/ns1/sinktest_" + UUID.randomUUID) val producerFn = () => client.producer(ProducerConfig(topic)) val f = Source.fromIterator(() => List("a").iterator) .map(string => ProducerMessage(string)) .runWith(sink(producerFn)) Await.result(f, 15.seconds) shouldBe Done } }
Example 40
Source File: CirceProducerConsumerTest.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s.circe import java.util.UUID import com.sksamuel.pulsar4s._ import io.circe.generic.auto._ import io.circe.CursorOp.DownField import io.circe.DecodingFailure import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.util.Failure class CirceProducerConsumerTest extends AnyFunSuite with Matchers { test("producer and consumer synchronous round trip") { val client = PulsarClient("pulsar://localhost:6650") val topic = Topic("persistent://sample/standalone/ns1/test_" + UUID.randomUUID) val producer = client.producer[Cafe](ProducerConfig(topic)) val cafe = Cafe("le table", Place(1, "Paris")) val messageId = producer.send(cafe) producer.close() val consumer = client.consumer[Cafe](ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription.generate)) consumer.seek(MessageId.earliest) val msg = consumer.receive msg.get.value shouldBe cafe consumer.close() client.close() } test("producer and consumer synchronous round trip with failed deserialization") { val client = PulsarClient("pulsar://localhost:6650") val topic = Topic("persistent://sample/standalone/ns1/test_" + UUID.randomUUID) val producer = client.producer[String](ProducerConfig(topic)) val messageId = producer.send("""{"foo": "bar"}""") producer.close() val consumer = client.consumer[Cafe](ConsumerConfig(topics = Seq(topic), subscriptionName = Subscription.generate)) consumer.seek(MessageId.earliest) val msg = consumer.receive msg.get.valueTry shouldBe Failure(DecodingFailure("Attempt to decode value on failed cursor", List(DownField("name")))) consumer.close() client.close() } }
Example 41
Source File: VersionParserSpec.scala From sbt-dependency-updates with Apache License 2.0 | 5 votes |
package org.jmotor.sbt.parser import org.scalatest.funsuite.AnyFunSuite class VersionParserSpec extends AnyFunSuite { test("read version lines") { val text = """ |import sbt._ | |object Dependencies { | | object Versions { | val fansi = "0.2.5" | val guava = "24.0-jre" | val scala212 = "2.12.4" | val scala211 = "2.11.11" | val scalaTest = "3.0.5" | val scalaLogging = "3.7.2" | val slf4jSimple = "1.7.25" | val artifactVersions = "1.0.1" | } | | object Compile { | val fansi = "com.lihaoyi" %% "fansi" % Versions.fansi | val guava = "com.google.guava" % "guava" % Versions.guava | val slf4jSimple = "org.slf4j" % "slf4j-simple" % Versions.slf4jSimple | val artifactVersions = "org.jmotor.artifact" %% "artifact-versions" % Versions.artifactVersions | } | | object Test { | val scalaTest: ModuleID = "org.scalatest" %% "scalatest" % Versions.scalaTest % "test" | } | | import Compile._ | | lazy val dependencies = Seq(fansi, guava, slf4jSimple, artifactVersions, Test.scalaTest) | |} | """.stripMargin val versions = VersionParser.parseVersionLines(text) assert(versions.contains("""val fansi = "0.2.5"""")) } }
Example 42
Source File: VersionServiceSpec.scala From sbt-dependency-updates with Apache License 2.0 | 5 votes |
package org.jmotor.sbt.service import org.jmotor.sbt.dto.Status import org.scalatest.funsuite.AnyFunSuite import sbt.librarymanagement.MavenRepo import sbt.librarymanagement.ModuleID import sbt.librarymanagement.Resolver import sbt.util.Logger import scala.concurrent.Await import scala.concurrent.duration._ class VersionServiceSpec extends AnyFunSuite { private[this] val resolvers = Seq( MavenRepo("ali-maven", "http://maven.aliyun.com/nexus/content/groups/public/"), Resolver.bintrayIvyRepo("sbt", "sbt-plugin-releases")) test("check normal module") { val versionService = VersionService(Logger.Null, "2.12.4", "2.12", resolvers, Seq.empty) val future = versionService.checkForUpdates(ModuleID("com.google.guava", "guava", "23.0-jre")) val status = Await.result(future, 30.seconds) assert(status.status == Status.Expired) } test("check sbt plugin") { val versionService = VersionService(Logger.Null, "2.12.4", "2.12", resolvers, Seq.empty) val future = versionService.checkPluginForUpdates(ModuleID("org.jetbrains", "sbt-idea-shell", "2017.2"), "1.0", "2.12") val status = Await.result(future, 30.seconds) assert(status.status == Status.Expired) } }
Example 43
Source File: VersionSpec.scala From sbt-dependency-updates with Apache License 2.0 | 5 votes |
package org.jmotor.sbt.util import org.apache.maven.artifact.versioning.DefaultArtifactVersion import org.jmotor.artifact.Versions import org.scalatest.funsuite.AnyFunSuite class VersionSpec extends AnyFunSuite { test("is released version") { val v1 = new DefaultArtifactVersion("3.2.0-SNAP10") assert(!Versions.isReleaseVersion(v1)) val v2 = new DefaultArtifactVersion("3.2.0-PROD") assert(Versions.isReleaseVersion(v2)) val v3 = new DefaultArtifactVersion("3.2.0-pr10") assert(!Versions.isReleaseVersion(v3)) val v4 = new DefaultArtifactVersion("3.2.0-M1") assert(!Versions.isReleaseVersion(v4)) } test("scala m version") { val v = new DefaultArtifactVersion("2.13.0-M4-pre-20d3c21") assert(!Versions.isReleaseVersion(v)) } test("is jre qualifier") { assert(Versions.isJreQualifier("jre7")) assert(!Versions.isJreQualifier("jrep")) } }
Example 44
Source File: UpdatesSpec.scala From sbt-dependency-updates with Apache License 2.0 | 5 votes |
package org.jmotor.sbt import org.scalatest.funsuite.AnyFunSuite class UpdatesSpec extends AnyFunSuite { test("mapping names") { val mappings = Map( "log4j-api" -> "log4j2", "undertow.*" -> "undertow", "akka.*" -> "akka", "akka-http" -> "akkaHttp") assert("akka" == Updates.mappingModuleName("akka-actor", mappings)) assert("akkaHttp" == Updates.mappingModuleName("akka-http", mappings)) assert("log4j2" == Updates.mappingModuleName("log4j-api", mappings)) assert("scalaUtils" == Updates.mappingModuleName("scala-utils", mappings)) assert("undertow" == Updates.mappingModuleName("undertow-servlet", mappings)) } }
Example 45
Source File: CustomProductFormatTest.scala From xmlconfect with Apache License 2.0 | 5 votes |
package com.mthaler.xmlconfect import com.mthaler.xmlconfect.ProductFormat.xmlFormat2 import com.mthaler.xmlconfect.ProductFormatTest.Product2 import org.scalatest.funsuite.AnyFunSuite import scala.reflect._ class CustomProductFormatTest extends AnyFunSuite { test("xmlFormat2Attributes") { implicit val f = xmlFormat2(Product2)(BasicAttrFormats.StringXmlAttrFormat, BasicAttrFormats.IntXmlAttrFormat, classTag[Product2]) val p = Product2("test", 42) assertResult(<Product2 field1="test" field2="42"/>) { p.toNode } assertResult(p) { <Product2 field1="test" field2="42"/>.convertTo[Product2] } } test("xmlFormat2Elements") { implicit val f = xmlFormat2(Product2)(BasicElemFormats.StringXmlElemFormat, BasicElemFormats.IntXmlElemFormat, classTag[Product2]) val p = Product2("test", 42) assertResult(<Product2><field1>test</field1><field2>42</field2></Product2>) { p.toNode } assertResult(p) { <Product2><field1>test</field1><field2>42</field2></Product2>.convertTo[Product2] } } test("xmlFormat2Mixed") { implicit val f = xmlFormat2(Product2)(BasicElemFormats.StringXmlElemFormat, BasicAttrFormats.IntXmlAttrFormat, classTag[Product2]) val p = Product2("test", 42) assertResult(<Product2 field2="42"><field1>test</field1></Product2>) { p.toNode } assertResult(p) { <Product2 field2="42"><field1>test</field1></Product2>.convertTo[Product2] } } test("xmlFormat2MixedRenamed") { implicit val f = xmlFormat2(Product2)( AdditionalFormats.namedFormat(BasicElemFormats.StringXmlElemFormat, "Field1"), BasicAttrFormats.IntXmlAttrFormat, classTag[Product2]) val p = Product2("test", 42) assertResult(<Product2 field2="42"><Field1>test</Field1></Product2>) { p.toNode } assertResult(p) { <Product2 field2="42"><Field1>test</Field1></Product2>.convertTo[Product2] } } }
Example 46
Source File: ClassesTest.scala From xmlconfect with Apache License 2.0 | 5 votes |
package com.mthaler.xmlconfect import org.scalatest.funsuite.AnyFunSuite object ClassesTest { case class Person(name: String = "Albert Einstein", age: Int = 42) } class ClassesTest extends AnyFunSuite { import ClassesTest._ test("newDefault") { val p = Classes.newDefault[Person] assert(p == Person()) val p2 = Classes.newDefault(classOf[Person]) assert(p2 == Person()) } test("defaultArgs") { val defaultArgs = Classes.defaultArgs(classOf[Person]) assert(List("Albert Einstein", 42) == defaultArgs) } }
Example 47
Source File: FileParamStoreTest.scala From lighthouse with Apache License 2.0 | 5 votes |
package be.dataminded.lighthouse.paramstore import java.nio.file.NoSuchFileException import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FileParamStoreTest extends AnyFunSuite with Matchers { test("Can be used to retrieve a property from file") { //TODO: Implement } test("Non existing file trows an exception") { //TODO: Implement } test("Non existing config path trows an exception") { //TODO: Implement } test("Non existing key trows an exception") { //TODO: Implement } test("Validation happens at call, not at retrieval") { val store = new FileParamStore("/some/unexisting/file/path") val function = store.lookup("some.key") an[NoSuchFileException] should be thrownBy function.apply() } }
Example 48
Source File: AuthQueryTypeCheckSpec.scala From scala-pet-store with Apache License 2.0 | 5 votes |
package io.github.pauljamescleary.petstore package infrastructure.repository.doobie import cats.effect.IO import doobie.scalatest.IOChecker import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import PetStoreArbitraries._ import tsec.mac.jca.HMACSHA256 import tsec.authentication.AugmentedJWT import tsec.common.SecureRandomId import org.scalatest.matchers.should.Matchers class AuthQueryTypeCheckSpec extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks with IOChecker { override def transactor: doobie.Transactor[IO] = testTransactor import AuthSQL._ test("Typecheck auth queries") { forAll { jwt: AugmentedJWT[HMACSHA256, Long] => check(insert(jwt)) } forAll { jwt: AugmentedJWT[HMACSHA256, Long] => check(update(jwt)) } forAll { id: SecureRandomId => check(select(id)) } forAll { id: SecureRandomId => check(delete(id)) } } }
Example 49
Source File: PetQueryTypeCheckSpec.scala From scala-pet-store with Apache License 2.0 | 5 votes |
package io.github.pauljamescleary.petstore package infrastructure.repository.doobie import cats.data.NonEmptyList import cats.effect.IO import cats.syntax.applicative._ import doobie.scalatest.IOChecker import doobie.util.transactor.Transactor import org.scalatest.funsuite.AnyFunSuite import PetStoreArbitraries.pet import org.scalatest.matchers.should.Matchers class PetQueryTypeCheckSpec extends AnyFunSuite with Matchers with IOChecker { override val transactor: Transactor[IO] = testTransactor import PetSQL._ test("Typecheck pet queries") { pet.arbitrary.sample.map { p => check(selectByStatus(p.status.pure[NonEmptyList])) check(insert(p)) p.id.foreach(id => check(PetSQL.update(p, id))) } check(selectTagLikeString("example".pure[NonEmptyList])) check(select(1L)) check(selectAll) check(delete(1L)) check(selectByNameAndCategory("name", "category")) } }
Example 50
Source File: UserQueryTypeCheckSpec.scala From scala-pet-store with Apache License 2.0 | 5 votes |
package io.github.pauljamescleary.petstore package infrastructure.repository.doobie import org.scalatest.funsuite.AnyFunSuite import cats.effect.IO import doobie.scalatest.IOChecker import doobie.util.transactor.Transactor import PetStoreArbitraries.user import org.scalatest.matchers.should.Matchers class UserQueryTypeCheckSpec extends AnyFunSuite with Matchers with IOChecker { override val transactor: Transactor[IO] = testTransactor import UserSQL._ test("Typecheck user queries") { user.arbitrary.sample.map { u => check(insert(u)) check(byUserName(u.userName)) u.id.foreach(id => check(update(u, id))) } check(selectAll) check(select(1L)) check(delete(1L)) } }
Example 51
Source File: OrderEndpointsSpec.scala From scala-pet-store with Apache License 2.0 | 5 votes |
package io.github.pauljamescleary.petstore package infrastructure.endpoint import domain.orders._ import infrastructure.repository.inmemory._ import cats.effect._ import io.circe._ import io.circe.generic.semiauto._ import org.http4s._ import org.http4s.implicits._ import org.http4s.dsl._ import org.http4s.circe._ import org.http4s.client.dsl.Http4sClientDsl import org.http4s.server.Router import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import tsec.mac.jca.HMACSHA256 import org.scalatest.matchers.should.Matchers class OrderEndpointsSpec extends AnyFunSuite with Matchers with ScalaCheckPropertyChecks with PetStoreArbitraries with Http4sDsl[IO] with Http4sClientDsl[IO] { implicit val statusDec: EntityDecoder[IO, OrderStatus] = jsonOf implicit val statusEnc: EntityEncoder[IO, OrderStatus] = jsonEncoderOf implicit val orderEncoder: Encoder[Order] = deriveEncoder implicit val orderEnc: EntityEncoder[IO, Order] = jsonEncoderOf implicit val orderDecoder: Decoder[Order] = deriveDecoder implicit val orderDec: EntityDecoder[IO, Order] = jsonOf def getTestResources(): (AuthTest[IO], HttpApp[IO]) = { val userRepo = UserRepositoryInMemoryInterpreter[IO]() val auth = new AuthTest[IO](userRepo) val orderService = OrderService(OrderRepositoryInMemoryInterpreter[IO]()) val orderEndpoint = OrderEndpoints.endpoints[IO, HMACSHA256](orderService, auth.securedRqHandler) val orderRoutes = Router(("/orders", orderEndpoint)).orNotFound (auth, orderRoutes) } test("place and get order") { val (auth, orderRoutes) = getTestResources() forAll { (order: Order, user: AdminUser) => (for { createRq <- POST(order, uri"/orders") createRqAuth <- auth.embedToken(user.value, createRq) createResp <- orderRoutes.run(createRqAuth) orderResp <- createResp.as[Order] getOrderRq <- GET(Uri.unsafeFromString(s"/orders/${orderResp.id.get}")) getOrderRqAuth <- auth.embedToken(user.value, getOrderRq) getOrderResp <- orderRoutes.run(getOrderRqAuth) orderResp2 <- getOrderResp.as[Order] } yield { createResp.status shouldEqual Ok orderResp.petId shouldBe order.petId getOrderResp.status shouldEqual Ok orderResp2.userId shouldBe defined }).unsafeRunSync } } test("user roles") { val (auth, orderRoutes) = getTestResources() forAll { user: CustomerUser => (for { deleteRq <- DELETE(Uri.unsafeFromString(s"/orders/1")) .flatMap(auth.embedToken(user.value, _)) deleteResp <- orderRoutes.run(deleteRq) } yield { deleteResp.status shouldEqual Unauthorized }).unsafeRunSync } forAll { user: AdminUser => (for { deleteRq <- DELETE(Uri.unsafeFromString(s"/orders/1")) .flatMap(auth.embedToken(user.value, _)) deleteResp <- orderRoutes.run(deleteRq) } yield { deleteResp.status shouldEqual Ok }).unsafeRunSync } } }
Example 52
Source File: FollowRedirectsBackendTest.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FollowRedirectsBackendTest extends AnyFunSuite with Matchers { val testData = List( ("/x/y/z", true), (" /x2/y/z", true), ("/x?query=10", true), ("/foo%3F?token=xyz&url=http://minio:9000/a/b/c", true), ("http://server.com", false), ("https://server.com", false), (" https://server2.com", false), ("HTTP://server.com", false), ("httpS://server.com", false) ) for ((uri, isRelative) <- testData) { test(s"$uri should ${if (isRelative) "" else "not "}be relative") { FollowRedirectsBackend.isRelative(uri) shouldBe isRelative } } }
Example 53
Source File: FS2CronTest.scala From fs2-cron with Apache License 2.0 | 5 votes |
package eu.timepit.fs2cron import cats.effect.{ContextShift, IO, Timer} import cron4s.Cron import cron4s.expr.CronExpr import scala.concurrent.ExecutionContext import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FS2CronTest extends AnyFunSuite with Matchers { implicit val timer: Timer[IO] = IO.timer(ExecutionContext.global) val evenSeconds: CronExpr = Cron.unsafeParse("*/2 * * ? * *") def isEven(i: Int): Boolean = i % 2 == 0 test("awakeEveryCron") { val s1 = awakeEveryCron[IO](evenSeconds) >> evalNow[IO] val s2 = s1.map(_.getSecond).take(2).forall(isEven) s2.compile.last.map(_.getOrElse(false)).unsafeRunSync() } test("sleepCron") { val s1 = sleepCron[IO](evenSeconds) >> evalNow[IO] val s2 = s1.map(_.getSecond).forall(isEven) s2.compile.last.map(_.getOrElse(false)).unsafeRunSync() } test("schedule") { implicit val ctxShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val everySecond: CronExpr = Cron.unsafeParse("* * * ? * *") val s1 = schedule(List(everySecond -> evalNow[IO], evenSeconds -> evalNow[IO])).map(_.getSecond) val seconds = s1.take(3).compile.toList.unsafeRunSync() seconds.count(isEven) shouldBe 2 seconds.count(!isEven(_)) shouldBe 1 } }
Example 54
Source File: PrismSpec.scala From exercises-monocle with Apache License 2.0 | 5 votes |
package monoclelib import PrismHelper.{JNum, JStr} import org.scalaexercises.Test import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.Checkers import org.scalacheck.ScalacheckShapeless._ import shapeless.HNil class PrismSpec extends AnyFunSuite with Checkers { test("exercise get option apply") { check( Test.testSuccess( PrismExercises.exerciseGetOptionAndApply _, JStr("hello") :: Option("Hello") :: Option.empty[String] :: HNil ) ) } test("exercise set and modify") { check( Test.testSuccess( PrismExercises.exerciseSetAndModify _, JStr("Bar") :: JStr("olleH") :: HNil ) ) } test("exercise set and modify 2") { check( Test.testSuccess( PrismExercises.exerciseSetAndModify2 _, JNum(10) :: JNum(10) :: HNil ) ) } test("exercise modifyOption") { check( Test.testSuccess( PrismExercises.exerciseModifyOption _, Option(JStr("olleH")) :: Option.empty[JNum] :: HNil ) ) } test("exercise compose") { check( Test.testSuccess( PrismExercises.exerciseCompose _, JNum(5.0) :: Option(5) :: Option.empty[Int] :: Option.empty[String] :: HNil ) ) } test("exercise prism generation") { check( Test.testSuccess( PrismExercises.exercisePrismGeneration _, Option(JNum(4.5)) :: Option.empty[JNum] :: HNil ) ) } test("exercise laws") { check( Test.testSuccess( PrismExercises.exerciseLaws _, true :: true :: HNil ) ) } }
Example 55
Source File: IsoSpec.scala From exercises-monocle with Apache License 2.0 | 5 votes |
package monoclelib import IsoHelper.Person import org.scalacheck.ScalacheckShapeless._ import org.scalaexercises.Test import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.Checkers import shapeless.HNil class IsoSpec extends AnyFunSuite with Checkers { test("exercise person to tuple") { check( Test.testSuccess( IsoExercises.exercisePersonToTuple _, ("Zoe", 25) :: Person("Zoe", 25) :: HNil ) ) } test("exercise person to tuple apply") { check( Test.testSuccess( IsoExercises.exercisePersonToTupleApply _, Person("Zoe", 25) :: HNil ) ) } test("exercise list to vector") { check( Test.testSuccess( IsoExercises.exerciseListToVector _, Vector(1, 2, 3) :: HNil ) ) } test("exercise string to list") { check( Test.testSuccess( IsoExercises.exerciseStringToList _, "ello" :: HNil ) ) } test("exercise gen iso apply") { check( Test.testSuccess( IsoExercises.exerciseGenIsoApply _, "Hello" :: HNil ) ) } test("exercise gen iso fields") { check( Test.testSuccess( IsoExercises.exerciseGenIsoFields _, ("John", 42) :: HNil ) ) } test("exercise laws") { check( Test.testSuccess( IsoExercises.exerciseLaws _, true :: true :: HNil ) ) } }
Example 56
Source File: OptionalSpec.scala From exercises-monocle with Apache License 2.0 | 5 votes |
package monoclelib import org.scalacheck.ScalacheckShapeless._ import org.scalaexercises.Test import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.Checkers import shapeless.HNil class OptionalSpec extends AnyFunSuite with Checkers { test("exercise non empty") { check( Test.testSuccess( OptionalExercises.exerciseNonEmpty _, true :: false :: HNil ) ) } test("exercise getOption") { check( Test.testSuccess( OptionalExercises.exerciseGetOption _, Option(1) :: List(5, 2, 3) :: Option.empty[Int] :: List.empty[Int] :: HNil ) ) } test("exercise modify") { check( Test.testSuccess( OptionalExercises.exerciseModify _, List(2, 2, 3) :: List.empty[Int] :: HNil ) ) } test("exercise modifyOption") { check( Test.testSuccess( OptionalExercises.exerciseModifyOption _, Option(List(2, 2, 3)) :: Option.empty[List[Int]] :: HNil ) ) } test("exercise laws") { check( Test.testSuccess( OptionalExercises.exerciseLaws _, true :: true :: HNil ) ) } }
Example 57
Source File: TraversalSpec.scala From exercises-monocle with Apache License 2.0 | 5 votes |
package monoclelib import TraversalHelper.Point import org.scalacheck.ScalacheckShapeless._ import org.scalaexercises.Test import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.Checkers import shapeless.HNil class TraversalSpec extends AnyFunSuite with Checkers { test("exercise traversal") { check( Test.testSuccess( TraversalExercises.exerciseTraversal _, List(0, 0, 0, 0, 0) :: List(2, 3, 4, 5, 6) :: HNil ) ) } test("exercise fold") { check( Test.testSuccess( TraversalExercises.exerciseFold _, List(1, 2, 3, 4, 5) :: Option(1) :: Option(4) :: false :: HNil ) ) } test("exercise smart construct") { check( Test.testSuccess( TraversalExercises.exerciseSmartConstruct _, Point("bottom-left", 5, 5) :: HNil ) ) } test("exercise modifyF") { check( Test.testSuccess( TraversalExercises.exerciseModifyF _, Map(1 -> "one", 2 -> "TWO", 3 -> "three", 4 -> "FOUR") :: HNil ) ) } test("exercise laws") { check( Test.testSuccess( TraversalExercises.exerciseLaws _, true :: true :: HNil ) ) } }
Example 58
Source File: BaseTestsSuite.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect import cats.effect.internals.TestUtils import cats.effect.laws.util.{TestContext, TestInstances} import org.scalactic.source import org.scalatest.Tag import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.Checkers import org.typelevel.discipline.Laws import org.typelevel.discipline.scalatest.FunSuiteDiscipline class BaseTestsSuite extends AnyFunSuite with Matchers with Checkers with FunSuiteDiscipline with TestInstances with TestUtils { def testAsync[A](name: String, tags: Tag*)(f: TestContext => Unit)(implicit pos: source.Position): Unit = // Overriding System.err test(name, tags: _*)(silenceSystemErr(f(TestContext())))(pos) def checkAllAsync(name: String, f: TestContext => Laws#RuleSet): Unit = { val context = TestContext() val ruleSet = f(context) for ((id, prop) <- ruleSet.all.properties) test(name + "." + id) { silenceSystemErr(check(prop)) } } }
Example 59
Source File: JvmIOTimerTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect package internals import java.util.concurrent.{ScheduledThreadPoolExecutor, TimeUnit} import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import scala.util.control.NonFatal class JvmIOTimerTests extends AnyFunSuite with Matchers { private def withScheduler(props: Map[String, String])(f: ScheduledThreadPoolExecutor => Unit): Unit = { val s = IOTimer.mkGlobalScheduler(props) try f(s) finally { try s.shutdownNow() catch { case NonFatal(e) => e.printStackTrace() } } } test("global scheduler: default core pool size") { withScheduler(Map.empty) { s => s.getCorePoolSize shouldBe 2 } } test("global scheduler: custom core pool size") { withScheduler(Map("cats.effect.global_scheduler.threads.core_pool_size" -> "3")) { s => s.getCorePoolSize shouldBe 3 } } test("global scheduler: invalid core pool size") { withScheduler(Map("cats.effect.global_scheduler.threads.core_pool_size" -> "-1")) { s => s.getCorePoolSize shouldBe 2 } } test("global scheduler: malformed core pool size") { withScheduler(Map("cats.effect.global_scheduler.threads.core_pool_size" -> "banana")) { s => s.getCorePoolSize shouldBe 2 } } test("global scheduler: default core thread timeout") { withScheduler(Map.empty) { s => s.allowsCoreThreadTimeOut shouldBe false } } test("global scheduler: custom core thread timeout") { withScheduler(Map("cats.effect.global_scheduler.keep_alive_time_ms" -> "1000")) { s => s.allowsCoreThreadTimeOut shouldBe true s.getKeepAliveTime(TimeUnit.MILLISECONDS) shouldBe 1000 } } test("global scheduler: invalid core thread timeout") { withScheduler(Map("cats.effect.global_scheduler.keep_alive_time_ms" -> "0")) { s => s.allowsCoreThreadTimeOut shouldBe false } } test("global scheduler: malformed core thread timeout") { withScheduler(Map("cats.effect.global_scheduler.keep_alive_time_ms" -> "feral hogs")) { s => s.allowsCoreThreadTimeOut shouldBe false } } }
Example 60
Source File: ArrayStackTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect.internals import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite class ArrayStackTests extends AnyFunSuite with Matchers with TestUtils { test("push and pop 8 items") { val stack = new ArrayStack[String]() var times = 0 while (times < 10) { assert(stack.isEmpty, "stack.isEmpty") for (i <- 0 until 8) stack.push(i.toString) var list = List.empty[String] while (!stack.isEmpty) { assert(!stack.isEmpty, "!stack.isEmpty") list = stack.pop() :: list } list shouldBe (0 until 8).map(_.toString).toList stack.pop().asInstanceOf[AnyRef] shouldBe null stack.isEmpty shouldBe true times += 1 } } test("push and pop 100 items") { val stack = new ArrayStack[String]() var times = 0 while (times < 10) { assert(stack.isEmpty, "stack.isEmpty") for (i <- 0 until 100) stack.push(i.toString) var list = List.empty[String] while (!stack.isEmpty) { assert(!stack.isEmpty, "!stack.isEmpty") list = stack.pop() :: list } list shouldBe (0 until 100).map(_.toString).toList stack.pop().asInstanceOf[AnyRef] shouldBe null stack.isEmpty shouldBe true times += 1 } } test("pushAll(stack)") { val stack = new ArrayStack[String]() val stack2 = new ArrayStack[String]() for (i <- 0 until 100) stack2.push(i.toString) stack.pushAll(stack2) var list = List.empty[String] while (!stack.isEmpty) { assert(!stack.isEmpty) list = stack.pop() :: list } list shouldBe (0 until 100).map(_.toString).toList.reverse stack.pop().asInstanceOf[AnyRef] shouldBe null stack.isEmpty shouldBe true stack2.isEmpty shouldBe false } test("pushAll(iterable)") { val stack = new ArrayStack[String]() val expected = (0 until 100).map(_.toString).toList stack.pushAll(expected) var list = List.empty[String] while (!stack.isEmpty) { assert(!stack.isEmpty) list = stack.pop() :: list } list shouldBe expected stack.pop().asInstanceOf[AnyRef] shouldBe null stack.isEmpty shouldBe true } test("iterator") { val stack = new ArrayStack[String]() val expected = (0 until 100).map(_.toString).toList for (i <- expected) stack.push(i) stack.iteratorReversed.toList shouldBe expected.reverse } }
Example 61
Source File: ForwardCancelableTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect.internals import cats.effect.IO import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite class ForwardCancelableTests extends AnyFunSuite with Matchers { test("cancel() after complete") { var effect = 0 val ref = ForwardCancelable() ref.complete(IO(effect += 1)) effect shouldBe 0 ref.cancel.unsafeRunAsyncAndForget() effect shouldBe 1 // Weak idempotency guarantees (not thread-safe) ref.cancel.unsafeRunAsyncAndForget() effect shouldBe 1 } test("cancel() before complete") { var effect = 0 val ref = ForwardCancelable() ref.cancel.unsafeRunAsyncAndForget() effect shouldBe 0 ref.complete(IO(effect += 1)) effect shouldBe 1 intercept[IllegalStateException](ref.complete(IO(effect += 2))) // completed task was canceled before error was thrown effect shouldBe 3 ref.cancel.unsafeRunAsyncAndForget() effect shouldBe 3 } test("complete twice before cancel") { var effect = 0 val ref = ForwardCancelable() ref.complete(IO(effect += 1)) effect shouldBe 0 intercept[IllegalStateException](ref.complete(IO(effect += 2))) effect shouldBe 2 ref.cancel.unsafeRunAsyncAndForget() effect shouldBe 3 } }
Example 62
Source File: LinkedMapTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect.internals import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite final class LinkedMapTests extends AnyFunSuite with Matchers { test("empty map") { val map = LinkedMap.empty[Int, Int] map.isEmpty shouldBe true } test("inserting entries") { val ns = (0 until 10).toList val map = ns.foldLeft(LinkedMap.empty[Int, Int])((map, i) => map.updated(i, i)) map.isEmpty shouldBe false map.keys.toList shouldBe ns map.values.toList shouldBe ns } test("dequeueing entries") { val ns = (0 until 10).toList val map = ns.foldLeft(LinkedMap.empty[Int, Int])((map, i) => map.updated(i, i)) var n = 0 var acc = map while (!acc.isEmpty) { val res = acc.dequeue res._1 shouldBe n n += 1 acc = res._2 } } test("removing entry") { val ns = (0 until 10).toList val map = ns.foldLeft(LinkedMap.empty[Int, Int])((map, i) => map.updated(i, i)) val n = 2 assert(map.keys.exists(_ == n)) assert(map.values.exists(_ == n)) map.keys.exists(_ == n) shouldBe true map.values.exists(_ == n) shouldBe true val map2 = map - n map2.keys.exists(_ == n) shouldBe false map2.values.exists(_ == n) shouldBe false } }
Example 63
Source File: TrampolineECTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect package internals import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import cats.effect.internals.TrampolineEC.immediate import scala.concurrent.ExecutionContext import cats.effect.internals.IOPlatform.isJVM import scala.collection.immutable.Queue class TrampolineECTests extends AnyFunSuite with Matchers with TestUtils { implicit val ec: ExecutionContext = immediate def executeImmediate(f: => Unit): Unit = ec.execute(new Runnable { def run(): Unit = f }) test("execution should be immediate") { var effect = 0 executeImmediate { effect += 1 executeImmediate { effect += 2 executeImmediate { effect += 3 } } } effect shouldEqual 1 + 2 + 3 } test("concurrent execution") { var effect = List.empty[Int] executeImmediate { executeImmediate { effect = 1 :: effect } executeImmediate { effect = 2 :: effect } executeImmediate { effect = 3 :: effect } } effect shouldEqual List(1, 2, 3) } test("stack safety") { var effect = 0 def loop(n: Int, acc: Int): Unit = executeImmediate { if (n > 0) loop(n - 1, acc + 1) else effect = acc } val n = if (isJVM) 100000 else 5000 loop(n, 0) effect shouldEqual n } test("on blocking it should fork") { assume(isJVM, "test relevant only for the JVM") import scala.concurrent.blocking var effects = Queue.empty[Int] executeImmediate { executeImmediate { effects = effects.enqueue(4) } executeImmediate { effects = effects.enqueue(4) } effects = effects.enqueue(1) blocking { effects = effects.enqueue(2) } effects = effects.enqueue(3) } effects shouldBe Queue(1, 4, 4, 2, 3) } test("thrown exceptions should get logged to System.err (immediate)") { val dummy1 = new RuntimeException("dummy1") val dummy2 = new RuntimeException("dummy2") var effects = 0 val output = catchSystemErr { executeImmediate { executeImmediate(effects += 1) executeImmediate(effects += 1) executeImmediate { executeImmediate(effects += 1) executeImmediate(effects += 1) throw dummy2 } throw dummy1 } } output should include("dummy1") output should include("dummy2") effects shouldBe 4 } }
Example 64
Source File: CancelUtilsTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect.internals import java.io.ByteArrayOutputStream import cats.effect.IO import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import scala.util.control.NonFatal class CancelUtilsTests extends AnyFunSuite with Matchers with TestUtils { test("cancelAll works for zero references") { CancelUtils.cancelAll().unsafeRunSync() } test("cancelAll works for one reference") { var wasCanceled = false CancelUtils.cancelAll(IO { wasCanceled = true }).unsafeRunSync() wasCanceled shouldBe true } test("cancelAll catches error from one reference") { val dummy = new RuntimeException("dummy") var wasCanceled1 = false var wasCanceled2 = false val io = CancelUtils.cancelAll( IO { wasCanceled1 = true }, IO(throw dummy), IO { wasCanceled2 = true } ) try { io.unsafeRunSync() fail("should have throw exception") } catch { case `dummy` => wasCanceled1 shouldBe true wasCanceled2 shouldBe true } } test("cancelAll catches the first error and logs the rest") { val dummy1 = new RuntimeException("dummy1") val dummy2 = new RuntimeException("dummy2") var wasCanceled1 = false var wasCanceled2 = false val io = CancelUtils.cancelAll( IO { wasCanceled1 = true }, IO(throw dummy1), IO(throw dummy2), IO { wasCanceled2 = true } ) val sysErr = new ByteArrayOutputStream() try { catchSystemErrInto(sysErr) { io.unsafeRunSync() } fail("should have throw exception") } catch { case NonFatal(error) => error shouldBe dummy1 sysErr.toString("utf-8") should include("dummy2") dummy1.getSuppressed shouldBe empty // ensure memory isn't leaked with addSuppressed dummy2.getSuppressed shouldBe empty // ensure memory isn't leaked with addSuppressed } } }
Example 65
Source File: ExitCodeTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats package effect package concurrent import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.Checkers class ExitCodeTests extends AnyFunSuite with Matchers with Checkers { test("fromInt(i) == fromInt(i & 0xff)") { check { (i: Int) => ExitCode(i) == ExitCode(i & 0xff) } } test("code is in range from 0 to 255, inclusive") { check { (i: Int) => val ec = ExitCode(i) ec.code >= 0 && ec.code < 256 } } }
Example 66
Source File: AsyncFunctionLoopTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive import java.util.concurrent.{CountDownLatch, TimeUnit} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.concurrent.duration._ class AsyncFunctionLoopTest extends AnyFunSuite with Matchers { test("it loops 5 times in 10 seconds with 2s delay") { val countDownLatch = new CountDownLatch(5) val looper = new AsyncFunctionLoop(2.seconds, "test")({ countDownLatch.countDown() }) looper.start() countDownLatch.await(11000, TimeUnit.MILLISECONDS) shouldBe true looper.close() } }
Example 67
Source File: FileUtilsTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.utils import java.io.File import org.apache.kafka.common.config.ConfigException import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FileUtilsTest extends AnyFunSuite with Matchers { test("raises an exception if the file does not exists") { intercept[ConfigException] { FileUtils.throwIfNotExists("does_not_exist.file", "k1") } } test("throws an exception when the path is a directory") { val file = new File("dir") file.mkdir() shouldBe true try { intercept[ConfigException] { FileUtils.throwIfNotExists(file.getAbsolutePath, "k1") } } finally { file.delete() } } test("returns when the file exists") { val file = new File("file1.abc") file.createNewFile() shouldBe true try { FileUtils.throwIfNotExists(file.getAbsolutePath, "k1") } catch { case throwable: Throwable => fail("Should not raise an exception") } finally { file.delete() } } }
Example 68
Source File: KeytabSettingsTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.kerberos import com.landoop.streamreactor.connect.hive.sink.config.{HiveSinkConfigDefBuilder, SinkConfigSettings} import org.apache.kafka.common.config.ConfigException import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class KeytabSettingsTest extends AnyFunSuite with Matchers with FileCreation { test("validate a keytab setting") { val file = createFile("keytab1.keytab") try { val principal = "[email protected]" val config = HiveSinkConfigDefBuilder( Map( "connect.hive.database.name" -> "mydatabase", "connect.hive.metastore" -> "thrift", "connect.hive.metastore.uris" -> "thrift://localhost:9083", "connect.hive.fs.defaultFS" -> "hdfs://localhost:8020", "connect.hive.kcql" -> "insert into mytable select a,b,c from mytopic", SinkConfigSettings.KerberosKey -> "true", SinkConfigSettings.PrincipalKey -> principal, SinkConfigSettings.KerberosKeyTabKey -> file.getAbsolutePath ).asJava ) val actualSettings = KeytabSettings.from(config, SinkConfigSettings) actualSettings shouldBe KeytabSettings(principal, file.getAbsolutePath, None) } finally { file.delete() } } test("throws an exception when principal is not set") { val file = createFile("keytab2.keytab") try { val principal = "[email protected]" val config = HiveSinkConfigDefBuilder( Map( "connect.hive.database.name" -> "mydatabase", "connect.hive.metastore" -> "thrift", "connect.hive.metastore.uris" -> "thrift://localhost:9083", "connect.hive.fs.defaultFS" -> "hdfs://localhost:8020", "connect.hive.kcql" -> "insert into mytable select a,b,c from mytopic", SinkConfigSettings.KerberosKey -> "true", SinkConfigSettings.KerberosKeyTabKey -> file.getAbsolutePath ).asJava ) intercept[ConfigException] { KeytabSettings.from(config, SinkConfigSettings) } } finally { file.delete() } } test("throws an exception when the keytab is not present") { val principal = "[email protected]" val config = HiveSinkConfigDefBuilder( Map( "connect.hive.database.name" -> "mydatabase", "connect.hive.metastore" -> "thrift", "connect.hive.metastore.uris" -> "thrift://localhost:9083", "connect.hive.fs.defaultFS" -> "hdfs://localhost:8020", "connect.hive.kcql" -> "insert into mytable select a,b,c from mytopic", SinkConfigSettings.KerberosKey -> "true", SinkConfigSettings.PrincipalKey -> principal, SinkConfigSettings.KerberosKeyTabKey -> "does_not_exists.keytab" ).asJava ) intercept[ConfigException] { KeytabSettings.from(config, SinkConfigSettings) } } }
Example 69
Source File: MapValueConverterTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.sink import com.landoop.json.sql.JacksonJson import org.apache.kafka.connect.data.{Schema, Struct} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class MapValueConverterTest extends AnyFunSuite with Matchers { test("converts nested payload") { val json = """ |{ | "idType": 3, | "colorDepth": "", | "threshold" : 45.77, | "evars": { | "evars": { | "eVar1": "Tue Aug 27 2019 12:08:10", | "eVar2": 156692207943934897 | } | }, | "exclude": { | "id": 0, | "value": false | } |} |""".stripMargin val map = JacksonJson.toMap[Any](json) val struct = MapValueConverter.convert(map) //Jackson transforming the json to Map the fields order is not retained struct.schema().fields().asScala.map(_.name()).sorted shouldBe List("idType", "colorDepth", "threshold", "evars", "exclude").sorted struct.schema().field("idType").schema() shouldBe Schema.OPTIONAL_INT64_SCHEMA struct.schema().field("colorDepth").schema() shouldBe Schema.OPTIONAL_STRING_SCHEMA struct.schema().field("threshold").schema() shouldBe Schema.OPTIONAL_FLOAT64_SCHEMA struct.schema().field("exclude").schema().`type`() shouldBe Schema.Type.STRUCT struct.schema().field("exclude").schema().isOptional shouldBe true struct.schema().field("evars").schema().`type`() shouldBe Schema.Type.STRUCT struct.schema().field("evars").schema().isOptional shouldBe true struct.schema().field("evars").schema().fields().asScala.map(_.name()) shouldBe List("evars") val evarsInner = struct.schema().field("evars").schema().field("evars") evarsInner.schema().`type`() shouldBe Schema.Type.STRUCT evarsInner.schema().isOptional shouldBe true evarsInner.schema().fields().asScala.map(_.name()).sorted shouldBe List("eVar1", "eVar2").sorted evarsInner.schema().field("eVar1").schema() shouldBe Schema.OPTIONAL_STRING_SCHEMA evarsInner.schema().field("eVar2").schema() shouldBe Schema.OPTIONAL_INT64_SCHEMA val exclude = struct.schema().field("exclude").schema() exclude.schema().`type`() shouldBe Schema.Type.STRUCT exclude.schema().isOptional shouldBe true exclude.schema().fields().asScala.map(_.name()).sorted shouldBe List("id", "value").sorted exclude.schema().field("id").schema() shouldBe Schema.OPTIONAL_INT64_SCHEMA exclude.schema().field("value").schema() shouldBe Schema.OPTIONAL_BOOLEAN_SCHEMA struct.get("idType") shouldBe 3L struct.get("colorDepth") shouldBe "" struct.get("threshold") shouldBe 45.77D val evarsStruct = struct.get("evars").asInstanceOf[Struct].get("evars").asInstanceOf[Struct] evarsStruct.get("eVar1") shouldBe "Tue Aug 27 2019 12:08:10" evarsStruct.get("eVar2") shouldBe 156692207943934897L val excludeStruct = struct.get("exclude").asInstanceOf[Struct] excludeStruct.get("id") shouldBe 0L excludeStruct.get("value") shouldBe false } }
Example 70
Source File: DropPartitionValuesMapperTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.sink.mapper import cats.data.NonEmptyList import com.landoop.streamreactor.connect.hive.{PartitionKey, PartitionPlan, TableName} import org.apache.kafka.connect.data.{SchemaBuilder, Struct} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class DropPartitionValuesMapperTest extends AnyFunSuite with Matchers { test("strip partition values") { val schema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("p", SchemaBuilder.string().required().build()) .field("q", SchemaBuilder.string().required().build()) .field("z", SchemaBuilder.string().required().build()) .build() val plan = PartitionPlan(TableName("foo"), NonEmptyList.of(PartitionKey("p"), PartitionKey("q"))) val struct = new Struct(schema).put("a", "a").put("p", "p").put("q", "q").put("z", "z") val output = new DropPartitionValuesMapper(plan).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "z") } test("handle partition field is missing in input") { val schema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("q", SchemaBuilder.string().required().build()) .field("z", SchemaBuilder.string().required().build()) .build() val plan = PartitionPlan(TableName("foo"), NonEmptyList.of(PartitionKey("p"), PartitionKey("q"))) val struct = new Struct(schema).put("a", "a").put("q", "q").put("z", "z") val output = new DropPartitionValuesMapper(plan).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "z") } }
Example 71
Source File: MetastoreSchemaAlignMapperTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.sink.mapper import org.apache.kafka.connect.data.{SchemaBuilder, Struct} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class MetastoreSchemaAlignMapperTest extends AnyFunSuite with Matchers { test("pad optional missing fields with null") { val recordSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .field("c", SchemaBuilder.string().required().build()) .build() val struct = new Struct(recordSchema).put("a", "a").put("b", "b").put("c", "c") val metastoreSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .field("c", SchemaBuilder.string().required().build()) .field("z", SchemaBuilder.string().optional().build()) .build() val output = new MetastoreSchemaAlignMapper(metastoreSchema).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "b", "c", "z") } test("drop fields not specified in metastore") { val recordSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .field("c", SchemaBuilder.string().required().build()) .build() val struct = new Struct(recordSchema).put("a", "a").put("b", "b").put("c", "c") val metastoreSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .build() val output = new MetastoreSchemaAlignMapper(metastoreSchema).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "b") } }
Example 72
Source File: AsyncFunctionLoopTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive import java.util.concurrent.{CountDownLatch, TimeUnit} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.concurrent.duration._ class AsyncFunctionLoopTest extends AnyFunSuite with Matchers { test("it loops 5 times in 10 seconds with 2s delay") { val countDownLatch = new CountDownLatch(5) val looper = new AsyncFunctionLoop(2.seconds, "test")({ countDownLatch.countDown() }) looper.start() countDownLatch.await(11000, TimeUnit.MILLISECONDS) shouldBe true looper.close() } }
Example 73
Source File: FileUtilsTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.utils import java.io.File import org.apache.kafka.common.config.ConfigException import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FileUtilsTest extends AnyFunSuite with Matchers { test("raises an exception if the file does not exists") { intercept[ConfigException] { FileUtils.throwIfNotExists("does_not_exist.file", "k1") } } test("throws an exception when the path is a directory") { val file = new File("dir") file.mkdir() shouldBe true try { intercept[ConfigException] { FileUtils.throwIfNotExists(file.getAbsolutePath, "k1") } } finally { file.delete() } } test("returns when the file exists") { val file = new File("file1.abc") file.createNewFile() shouldBe true try { FileUtils.throwIfNotExists(file.getAbsolutePath, "k1") } catch { case throwable: Throwable => fail("Should not raise an exception") } finally { file.delete() } } }
Example 74
Source File: KeytabSettingsTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.kerberos import com.landoop.streamreactor.connect.hive.sink.config.{HiveSinkConfigDefBuilder, SinkConfigSettings} import org.apache.kafka.common.config.ConfigException import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class KeytabSettingsTest extends AnyFunSuite with Matchers with FileCreation { test("validate a keytab setting") { val file = createFile("keytab1.keytab") try { val principal = "[email protected]" val config = HiveSinkConfigDefBuilder( Map( "connect.hive.database.name" -> "mydatabase", "connect.hive.metastore" -> "thrift", "connect.hive.metastore.uris" -> "thrift://localhost:9083", "connect.hive.fs.defaultFS" -> "hdfs://localhost:8020", "connect.hive.kcql" -> "insert into mytable select a,b,c from mytopic", SinkConfigSettings.KerberosKey -> "true", SinkConfigSettings.PrincipalKey -> principal, SinkConfigSettings.KerberosKeyTabKey -> file.getAbsolutePath ).asJava ) val actualSettings = KeytabSettings.from(config, SinkConfigSettings) actualSettings shouldBe KeytabSettings(principal, file.getAbsolutePath, None) } finally { file.delete() } } test("throws an exception when principal is not set") { val file = createFile("keytab2.keytab") try { val principal = "[email protected]" val config = HiveSinkConfigDefBuilder( Map( "connect.hive.database.name" -> "mydatabase", "connect.hive.metastore" -> "thrift", "connect.hive.metastore.uris" -> "thrift://localhost:9083", "connect.hive.fs.defaultFS" -> "hdfs://localhost:8020", "connect.hive.kcql" -> "insert into mytable select a,b,c from mytopic", SinkConfigSettings.KerberosKey -> "true", SinkConfigSettings.KerberosKeyTabKey -> file.getAbsolutePath ).asJava ) intercept[ConfigException] { KeytabSettings.from(config, SinkConfigSettings) } } finally { file.delete() } } test("throws an exception when the keytab is not present") { val principal = "[email protected]" val config = HiveSinkConfigDefBuilder( Map( "connect.hive.database.name" -> "mydatabase", "connect.hive.metastore" -> "thrift", "connect.hive.metastore.uris" -> "thrift://localhost:9083", "connect.hive.fs.defaultFS" -> "hdfs://localhost:8020", "connect.hive.kcql" -> "insert into mytable select a,b,c from mytopic", SinkConfigSettings.KerberosKey -> "true", SinkConfigSettings.PrincipalKey -> principal, SinkConfigSettings.KerberosKeyTabKey -> "does_not_exists.keytab" ).asJava ) intercept[ConfigException] { KeytabSettings.from(config, SinkConfigSettings) } } }
Example 75
Source File: MapValueConverterTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.sink import com.landoop.json.sql.JacksonJson import org.apache.kafka.connect.data.{Schema, Struct} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class MapValueConverterTest extends AnyFunSuite with Matchers { test("converts nested payload") { val json = """ |{ | "idType": 3, | "colorDepth": "", | "threshold" : 45.77, | "evars": { | "evars": { | "eVar1": "Tue Aug 27 2019 12:08:10", | "eVar2": 156692207943934897 | } | }, | "exclude": { | "id": 0, | "value": false | } |} |""".stripMargin val map = JacksonJson.toMap[Any](json) val struct = MapValueConverter.convert(map) //Jackson transforming the json to Map the fields order is not retained struct.schema().fields().asScala.map(_.name()).sorted shouldBe List("idType", "colorDepth", "threshold", "evars", "exclude").sorted struct.schema().field("idType").schema() shouldBe Schema.OPTIONAL_INT64_SCHEMA struct.schema().field("colorDepth").schema() shouldBe Schema.OPTIONAL_STRING_SCHEMA struct.schema().field("threshold").schema() shouldBe Schema.OPTIONAL_FLOAT64_SCHEMA struct.schema().field("exclude").schema().`type`() shouldBe Schema.Type.STRUCT struct.schema().field("exclude").schema().isOptional shouldBe true struct.schema().field("evars").schema().`type`() shouldBe Schema.Type.STRUCT struct.schema().field("evars").schema().isOptional shouldBe true struct.schema().field("evars").schema().fields().asScala.map(_.name()) shouldBe List("evars") val evarsInner = struct.schema().field("evars").schema().field("evars") evarsInner.schema().`type`() shouldBe Schema.Type.STRUCT evarsInner.schema().isOptional shouldBe true evarsInner.schema().fields().asScala.map(_.name()).sorted shouldBe List("eVar1", "eVar2").sorted evarsInner.schema().field("eVar1").schema() shouldBe Schema.OPTIONAL_STRING_SCHEMA evarsInner.schema().field("eVar2").schema() shouldBe Schema.OPTIONAL_INT64_SCHEMA val exclude = struct.schema().field("exclude").schema() exclude.schema().`type`() shouldBe Schema.Type.STRUCT exclude.schema().isOptional shouldBe true exclude.schema().fields().asScala.map(_.name()).sorted shouldBe List("id", "value").sorted exclude.schema().field("id").schema() shouldBe Schema.OPTIONAL_INT64_SCHEMA exclude.schema().field("value").schema() shouldBe Schema.OPTIONAL_BOOLEAN_SCHEMA struct.get("idType") shouldBe 3L struct.get("colorDepth") shouldBe "" struct.get("threshold") shouldBe 45.77D val evarsStruct = struct.get("evars").asInstanceOf[Struct].get("evars").asInstanceOf[Struct] evarsStruct.get("eVar1") shouldBe "Tue Aug 27 2019 12:08:10" evarsStruct.get("eVar2") shouldBe 156692207943934897L val excludeStruct = struct.get("exclude").asInstanceOf[Struct] excludeStruct.get("id") shouldBe 0L excludeStruct.get("value") shouldBe false } }
Example 76
Source File: DropPartitionValuesMapperTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.sink.mapper import cats.data.NonEmptyList import com.landoop.streamreactor.connect.hive.{PartitionKey, PartitionPlan, TableName} import org.apache.kafka.connect.data.{SchemaBuilder, Struct} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class DropPartitionValuesMapperTest extends AnyFunSuite with Matchers { test("strip partition values") { val schema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("p", SchemaBuilder.string().required().build()) .field("q", SchemaBuilder.string().required().build()) .field("z", SchemaBuilder.string().required().build()) .build() val plan = PartitionPlan(TableName("foo"), NonEmptyList.of(PartitionKey("p"), PartitionKey("q"))) val struct = new Struct(schema).put("a", "a").put("p", "p").put("q", "q").put("z", "z") val output = new DropPartitionValuesMapper(plan).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "z") } test("handle partition field is missing in input") { val schema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("q", SchemaBuilder.string().required().build()) .field("z", SchemaBuilder.string().required().build()) .build() val plan = PartitionPlan(TableName("foo"), NonEmptyList.of(PartitionKey("p"), PartitionKey("q"))) val struct = new Struct(schema).put("a", "a").put("q", "q").put("z", "z") val output = new DropPartitionValuesMapper(plan).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "z") } }
Example 77
Source File: MetastoreSchemaAlignMapperTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.landoop.streamreactor.connect.hive.sink.mapper import org.apache.kafka.connect.data.{SchemaBuilder, Struct} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class MetastoreSchemaAlignMapperTest extends AnyFunSuite with Matchers { test("pad optional missing fields with null") { val recordSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .field("c", SchemaBuilder.string().required().build()) .build() val struct = new Struct(recordSchema).put("a", "a").put("b", "b").put("c", "c") val metastoreSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .field("c", SchemaBuilder.string().required().build()) .field("z", SchemaBuilder.string().optional().build()) .build() val output = new MetastoreSchemaAlignMapper(metastoreSchema).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "b", "c", "z") } test("drop fields not specified in metastore") { val recordSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .field("c", SchemaBuilder.string().required().build()) .build() val struct = new Struct(recordSchema).put("a", "a").put("b", "b").put("c", "c") val metastoreSchema = SchemaBuilder.struct() .field("a", SchemaBuilder.string().required().build()) .field("b", SchemaBuilder.string().required().build()) .build() val output = new MetastoreSchemaAlignMapper(metastoreSchema).map(struct) output.schema().fields().asScala.map(_.name) shouldBe Seq("a", "b") } }
Example 78
Source File: FtpFileListerTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.ftp.source import com.typesafe.scalalogging.StrictLogging import org.apache.commons.net.ftp.{FTPClient, FTPFile} import org.mockito.MockitoSugar import org.scalatest.BeforeAndAfter import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers val dira = mockDir("dira") val dirb = mockDir("dirb") val thisDir = mockDir(".") val parentDir = mockDir("..") when(ftp.listFiles("/a/")).thenReturn(Array[FTPFile](dira, dirb, thisDir, parentDir)) val path = mockDir("path") when(ftp.listFiles("/a/dira/")).thenReturn(Array[FTPFile](path, thisDir, parentDir)) val file1 = mockFile("file1.txt") when(ftp.listFiles("/a/dira/path/")).thenReturn(Array[FTPFile](file1, thisDir, parentDir)) val nopath = mockDir("nopath") when(ftp.listFiles("/a/dirb/")).thenReturn(Array[FTPFile](nopath, path, thisDir, parentDir)) when(ftp.listFiles("/a/dirb/nopath/")).thenThrow(new RuntimeException("Should not list this directory")) val file3 = mockFile("file3.txt") val file4 = mockFile("file4.csv") when(ftp.listFiles("/a/dirb/path/")).thenReturn(Array[FTPFile](file3, file4, thisDir, parentDir)) FtpFileLister(ftp).listFiles("/a/dir?/path/*.txt").toList should contain theSameElementsAs Seq( AbsoluteFtpFile(file1, "/a/dira/path/"), AbsoluteFtpFile(file3, "/a/dirb/path/") ) } }
Example 79
Source File: ManyFilesTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.ftp.source import com.typesafe.scalalogging.StrictLogging import org.scalatest.BeforeAndAfter import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.collection.JavaConverters._ class ManyFilesTest extends AnyFunSuite with Matchers with BeforeAndAfter with StrictLogging { val ftpServer = new EmbeddedFtpServer(3333) val fileCount = 132 val sliceSize = 1024 val maxPollRecords = 74 val lineSep = System.getProperty("line.separator") val fileContent = (1 to 12000).map(index => s"line_${"%010d".format(index)}${lineSep}").mkString.getBytes val fileName = "the_file_name" val filePath = s"/folder/${fileName}" val sourceConfig = Map( FtpSourceConfig.Address -> s"${ftpServer.host}:${ftpServer.port}", FtpSourceConfig.User -> ftpServer.username, FtpSourceConfig.Password -> ftpServer.password, FtpSourceConfig.RefreshRate -> "PT0S", FtpSourceConfig.MonitorTail -> "/folder/:output_topic", FtpSourceConfig.MonitorSliceSize -> sliceSize.toString, FtpSourceConfig.FileMaxAge -> "P7D", FtpSourceConfig.KeyStyle -> "string", FtpSourceConfig.fileFilter -> ".*", FtpSourceConfig.FtpMaxPollRecords -> s"${maxPollRecords}", FtpSourceConfig.KeyStyle -> "struct" ) test("Read only FtpMaxPollRecords even if using MonitorSliceSize") { val fs = new FileSystem(ftpServer.rootDir).clear() val cfg = new FtpSourceConfig(sourceConfig.asJava) val offsets = new DummyOffsetStorage (0 to fileCount).map(index => fs.applyChanges(Seq(s"${filePath}_${index}" -> Append(fileContent)))) val poller = new FtpSourcePoller(cfg, offsets) ftpServer.start() val slices = poller.poll() (slices.size) shouldBe (maxPollRecords) ftpServer.stop() } }
Example 80
Source File: RegExTest.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.ftp.source import com.datamountaineer.streamreactor.connect.ftp.source import com.typesafe.scalalogging.StrictLogging import org.apache.commons.net.ftp.FTPFile import org.mockito.MockitoSugar import org.scalatest.BeforeAndAfter import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class RegExTest extends AnyFunSuite with Matchers with BeforeAndAfter with StrictLogging with MockitoSugar { def mockFile(name: String) = { val f = mock[FTPFile] when(f.isFile).thenReturn(true) when(f.isDirectory).thenReturn(false) when(f.getName()).thenReturn(name) f } test("Matches RegEx"){ FtpSourceConfig.fileFilter -> ".*" var f : source.AbsoluteFtpFile = new AbsoluteFtpFile(mockFile("file.txt"),"\\"); f.name.matches(".*") shouldBe true f.name.matches("a") shouldBe false } }
Example 81
Source File: SaveComponentSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl import org.scalatest.funsuite.AnyFunSuite class SaveComponentSuite extends AnyFunSuite { test("MemorySaveComponent is working") { val save = new MemorySaveComponent {} import save.Save assert(Save.getInt("a") === None) assert(Save.getIntOrElse("a", 13) === 13) assert(Save.getIntOrElse("a", 15) === 15) assert(Save.getInt("a") === None) Save.putInt("a", 42) assert(Save.getInt("a") === Some(42)) assert(Save.getIntOrElse("a", 13) === 42) assert(Save.getInt("b") === None) } test("Testing SavedValue") { var getIntCalled = false val save = new MemorySaveComponent { override val Save = new MemorySave { override def getIntOrElse(name: String, default: Int): Int = { getIntCalled = true super.getIntOrElse(name, default) } } } val value = new save.IntSavedValue("a", 42) assert(!getIntCalled) assert(value.get === 42) assert(getIntCalled) // Initial get call require to read the store to check if anything was persisted. assert(save.Save.getInt("a") === None) // We don't persist the default value, so it should still be None. getIntCalled = false // Reset getIntCalled. As of now we should be using the cache so no more get needed. // Let's check that the default is gotten from memory only. assert(value.get === 42) assert(!getIntCalled) value.put(13) assert(!getIntCalled) // put does not need to call get assert(value.get == 13) assert(!getIntCalled) // get should use the cached value assert(save.Save.getInt("a") === Some(13)) // Check that the right value is persisted. } }
Example 82
Source File: CircleSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl.geometry import org.scalatest.funsuite.AnyFunSuite class CircleSuite extends AnyFunSuite { test("adds a Vec") { val c = Circle(0, 0, 10) val v = Vec(1, 1) val expected = Circle(1,1,10) assert(c + v === expected) } test("subtracts a Vec") { val c = Circle(0, 0, 10) val v = Vec(1, 1) val expected = Circle(-1,-1,10) assert(c - v === expected) } }
Example 83
Source File: EllipseSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl.geometry import org.scalatest.funsuite.AnyFunSuite class EllipseSuite extends AnyFunSuite { test("adds a Vec") { val c = Ellipse(0, 0, 10, 20) val v = Vec(1, 1) val expected = Ellipse(1,1,10, 20) assert(c + v === expected) } test("subtracts a Vec") { val c = Ellipse(0, 0, 10, 20) val v = Vec(1, 1) val expected = Ellipse(-1,-1,10, 20) assert(c - v === expected) } }
Example 84
Source File: CollisionsSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl.geometry import org.scalatest.funsuite.AnyFunSuite class CollisionsSuite extends AnyFunSuite { test("polygonWithPolygonSat with simple rects") { val p1 = Polygon(Vector(Vec(0,0), Vec(0, 10), Vec(10, 10), Vec(10, 0))) val p2 = Polygon(Vector(Vec(5,5), Vec(5, 15), Vec(15, 15), Vec(15, 5))) assert(Collisions.polygonWithPolygonSat(p1, p2)) assert(Collisions.polygonWithPolygonSat(p2, p1)) val p3 = Polygon(Vector(Vec(15,15), Vec(15, 20), Vec(20, 20), Vec(20, 15))) assert(!Collisions.polygonWithPolygonSat(p1, p3)) assert(!Collisions.polygonWithPolygonSat(p3, p1)) } test("polygonWithPolygonSat with triangles") { val p1 = Polygon(Vector(Vec(0,0), Vec(2, 10), Vec(8, 4))) val p2 = Polygon(Vector(Vec(4,4), Vec(10, 10), Vec(11, 1))) assert(Collisions.polygonWithPolygonSat(p1, p2)) assert(Collisions.polygonWithPolygonSat(p2, p1)) val p3 = Polygon(Vector(Vec(12,0), Vec(13, 8), Vec(17, 4.5f))) assert(!Collisions.polygonWithPolygonSat(p1, p3)) assert(!Collisions.polygonWithPolygonSat(p3, p1)) } }
Example 85
Source File: PolygonSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl.geometry import org.scalatest.funsuite.AnyFunSuite class PolygonSuite extends AnyFunSuite { test("Create polygon with correct vertices and edges") { val p = Polygon(Vector(Vec(0,0), Vec(1, 10), Vec(5, 5))) assert(p.vertices(0) === Vec(0,0)) assert(p.vertices(1) === Vec(1,10)) assert(p.vertices(2) === Vec(5,5)) assert(p.nbEdges === 3) assert(p.edgeStart(0) === Vec(0,0)) assert(p.edgeEnd(0) === Vec(1,10)) assert(p.edgeStart(1) === Vec(1,10)) assert(p.edgeEnd(1) === Vec(5,5)) assert(p.edgeStart(2) === Vec(5,5)) assert(p.edgeEnd(2) === Vec(0,0)) } test("Correct bounding box for polygon") { val p = Polygon(Vector(Vec(0, 5), Vec(3, 8), Vec(7, 4), Vec(4, -2))) val bb = p.boundingBox assert(bb.top == -2) assert(bb.left == 0) assert(bb.right == 7) assert(bb.bottom == 8) } }
Example 86
Source File: RectSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl.geometry import org.scalatest.funsuite.AnyFunSuite class RectSuite extends AnyFunSuite { test("Create rectangle with correct coordinates, dimensions, and center.") { val r1 = Rect(4, 7, 10, 20) assert(r1.left === 4) assert(r1.top === 7) assert(r1.width === 10) assert(r1.height === 20) assert(r1.right === 14) assert(r1.bottom === 27) assert(r1.centerX === 9) assert(r1.centerY === 17) } test("Rectangle intesects with a point") { val r1 = Rect(0, 0, 10, 20) assert(r1.intersect(2, 3)) assert(r1.intersect(5, 15)) assert(!r1.intersect(11, 10)) assert(!r1.intersect(5, 25)) } test("adds a Vec") { val r = Rect(0,0,10,10) val v = Vec(1,2) val expected = Rect(1,2,10,10) val result = r + v assert(result.left === expected.left) assert(result.top === expected.top) assert(result.width === expected.width) assert(result.height === expected.height) } test("subtracts a Vec") { val r = Rect(0,0,10,10) val v = Vec(1,2) val expected = Rect(-1,-2,10,10) val result = r - v assert(result.left === expected.left) assert(result.top === expected.top) assert(result.width === expected.width) assert(result.height === expected.height) } }
Example 87
Source File: SystemProviderSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl import org.scalatest.funsuite.AnyFunSuite class SystemProviderSuite extends AnyFunSuite { object InstrumentedSystemProvider extends TestSystemProvider { var instrumentedUri: java.net.URI = null class InstrumentedTestSystem extends TestSystem { override def openWebpage(uri: java.net.URI): Unit = { instrumentedUri = uri } } override val System = new InstrumentedTestSystem } test("openGooglePlayApp defaults to the correct URL without parameters") { InstrumentedSystemProvider.System.openGooglePlayApp("com.regblanc.sgl") val want = new java.net.URI("https://play.google.com/store/apps/details?id=com.regblanc.sgl") assert(InstrumentedSystemProvider.instrumentedUri == want) } test("openGooglePlayApp defaults to the correct URL with parameters") { InstrumentedSystemProvider.System.openGooglePlayApp("com.regblanc.sgl", Map("a" -> "b")) val want = new java.net.URI("https://play.google.com/store/apps/details?id=com.regblanc.sgl&a=b") assert(InstrumentedSystemProvider.instrumentedUri == want) InstrumentedSystemProvider.System.openGooglePlayApp("com.regblanc.sgl", Map("a" -> "b", "c" -> "d")) val want2 = new java.net.URI("https://play.google.com/store/apps/details?id=com.regblanc.sgl&a=b&c=d") assert(InstrumentedSystemProvider.instrumentedUri == want2) } object PartsResourcePathSystemProvider extends TestSystemNoResourcePathProvider with PartsResourcePathProvider { override val ResourcesRoot = PartsResourcePath(Vector("root")) override val MultiDPIResourcesRoot = PartsResourcePath(Vector("root")) } test("PartsResourcePath creates the correct path") { val r = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "b" / "c.txt" assert(r.path === "root/a/b/c.txt") val r2 = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "b/c.txt" assert(r2.path === "root/a/b/c.txt") } test("PartsResourcePath creates the correct pathes with multiple filenames") { val rs = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "b" / Seq("c.txt", "d.txt") assert(rs.size === 2) assert(rs(0).path === "root/a/b/c.txt") assert(rs(1).path === "root/a/b/d.txt") } test("PartsResourcePath returns proper extension") { val r = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "b" / "c.txt" assert(r.extension === Some("txt")) val r2 = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "b" / "c" assert(r2.extension === None) } test("PartsResourcePath creates the correct path with .") { val r = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "." / "b" / "c.txt" assert(r.path === "root/a/b/c.txt") val r2 = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "./b/c.txt" assert(r2.path === "root/a/b/c.txt") } test("PartsResourcePath creates the correct path with ..") { val r = PartsResourcePathSystemProvider.ResourcesRoot / "a" / ".." / "b" / "c.txt" assert(r.path === "root/b/c.txt") val r2 = PartsResourcePathSystemProvider.ResourcesRoot / ".." / "a" / "b" / "c.txt" assert(r2.path === "a/b/c.txt") val r3 = PartsResourcePathSystemProvider.ResourcesRoot / "a" / "../b/c.txt" assert(r3.path === "root/b/c.txt") val r4 = PartsResourcePathSystemProvider.ResourcesRoot / "../a/b/c.txt" assert(r4.path === "a/b/c.txt") } }
Example 88
Source File: RandomProviderSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl.util import org.scalatest.funsuite.AnyFunSuite trait RandomProviderAbstractSuite extends AnyFunSuite with RandomProvider { test("Two instances from same seed produces same stream of random data") { val r1 = Random.fromSeed(77) val r2 = Random.fromSeed(77) assert(r1.nextInt() === r2.nextInt()) assert(r1.nextInt() === r2.nextInt()) assert(r1.nextLong() === r2.nextLong()) } test("A Random instance that reset the seed reproduces the same stream of random data") { val r = Random.fromSeed(12) val n1 = r.nextInt() val n2 = r.nextInt() val n3 = r.nextLong() r.setSeed(12) assert(n1 === r.nextInt()) assert(n2 === r.nextInt()) assert(n3 === r.nextLong()) } } class DefaultRandomProviderSuite extends RandomProviderAbstractSuite with DefaultRandomProvider
Example 89
Source File: GraphicsHelpersSuite.scala From scala-game-library with MIT License | 5 votes |
package sgl import org.scalatest.funsuite.AnyFunSuite class GraphicsHelperSuite extends AnyFunSuite { val graphicsProvider = new TestGraphicsProvider with TestSystemProvider {} test("BitmapRegion with single bitmap") { import graphicsProvider.Graphics._ val testBitmap = new TestBitmap { override def height = 24 override def width = 32 } val br = BitmapRegion(testBitmap) assert(br.bitmap === testBitmap) assert(br.x === 0) assert(br.y === 0) assert(br.width === 32) assert(br.height === 24) } test("BitmapRegion split of a bitmap") { import graphicsProvider.Graphics._ val testBitmap = new TestBitmap { override def height = 64 override def width = 90 } val brs = BitmapRegion.split(testBitmap, 0, 0, 30, 32, 3, 2) assert(brs.size === 6) assert(brs(0).bitmap === testBitmap) assert(brs(0).x === 0) assert(brs(0).y === 0) assert(brs(0).width === 30) assert(brs(0).height === 32) assert(brs(1).bitmap === testBitmap) assert(brs(1).x === 30) assert(brs(1).y === 0) assert(brs(1).width === 30) assert(brs(1).height === 32) assert(brs(2).bitmap === testBitmap) assert(brs(2).x === 60) assert(brs(2).y === 0) assert(brs(2).width === 30) assert(brs(2).height === 32) assert(brs(3).bitmap === testBitmap) assert(brs(3).x === 0) assert(brs(3).y === 32) assert(brs(3).width === 30) assert(brs(3).height === 32) assert(brs(4).bitmap === testBitmap) assert(brs(4).x === 30) assert(brs(4).y === 32) assert(brs(4).width === 30) assert(brs(4).height === 32) assert(brs(5).bitmap === testBitmap) assert(brs(5).x === 60) assert(brs(5).y === 32) assert(brs(5).width === 30) assert(brs(5).height === 32) val brs2 = BitmapRegion.split(testBitmap, 30, 0, 30, 32, 1, 2) assert(brs2.size === 2) assert(brs2(0).bitmap === testBitmap) assert(brs2(0).x === 30) assert(brs2(0).y === 0) assert(brs2(0).width === 30) assert(brs2(0).height === 32) assert(brs2(1).bitmap === testBitmap) assert(brs2(1).x === 30) assert(brs2(1).y === 32) assert(brs2(1).width === 30) assert(brs2(1).height === 32) } }
Example 90
Source File: InteropTest.scala From slinky with MIT License | 5 votes |
package slinky.scalajsreact import org.scalatest.funsuite.AnyFunSuite import slinky.web.ReactDOM import org.scalajs.dom.document import japgolly.scalajs.react.vdom.html_<^._ import Converters._ import slinky.web.html.div class InteropTest extends AnyFunSuite { test("Can convert Scala.js React node to Slinky") { val target = document.createElement("div") ReactDOM.render( <.a().toSlinky, target ) assert(target.innerHTML == "<a></a>") } test("Can convert Slinky element to Scala.js React node and render through Slinky") { val target = document.createElement("div") ReactDOM.render( <.a( div("hello!").toScalaJSReact ).toSlinky, target ) assert(target.innerHTML == "<a><div>hello!</div></a>") } }
Example 91
Source File: ReactDOMTest.scala From slinky with MIT License | 5 votes |
package slinky.web import slinky.core.ComponentWrapper import slinky.core.facade.ReactElement import org.scalajs.dom.{Element, document} import scala.scalajs.js import html._ import org.scalatest.funsuite.AnyFunSuite object TestComponent extends ComponentWrapper { type Props = Unit type State = Unit class Def(jsProps: js.Object) extends Definition(jsProps) { override def initialState: Unit = () override def render(): ReactElement = { a() } } } class ReactDOMTest extends AnyFunSuite { test("Renders a single element into the DOM") { val target = document.createElement("div") ReactDOM.render( a(), target ) assert(target.innerHTML == "<a></a>") } test("Finds a dom node for a component") { val comp: ReactElement = TestComponent(()) val target = document.createElement("div") val instance = ReactDOM.render( comp, target ).asInstanceOf[TestComponent.Def] assert(target.childNodes(0).asInstanceOf[Element] == ReactDOM.findDOMNode(instance)) } test("Renders portals to the appropriate container DOM node") { val target = document.createElement("div") val container = document.createElement("div") ReactDOM.render( div( ReactDOM.createPortal(h1("hi"), container) ), target ) assert(container.innerHTML == "<h1>hi</h1>") assert(target.innerHTML == "<div></div>") } test("unmountComponentAtNode clears out the container") { val container = document.createElement("div") ReactDOM.render( div("hello"), container ) assert(container.innerHTML == "<div>hello</div>") ReactDOM.unmountComponentAtNode(container) assert(container.innerHTML.length == 0) } }
Example 92
Source File: ProfilerTest.scala From slinky with MIT License | 5 votes |
package slinky.core import org.scalajs.dom import slinky.core.facade.Profiler import slinky.web.ReactDOM import slinky.web.html.div import org.scalatest.funsuite.AnyFunSuite class ProfilerTest extends AnyFunSuite { test("Can render a Profiler component with children") { val target = dom.document.createElement("div") ReactDOM.render( Profiler(id = "profiler", onRender = (_, _, _, _, _, _, _) => {})( div("hello!") ), target ) assert(target.innerHTML == "<div>hello!</div>") } }
Example 93
Source File: ReactChildrenTest.scala From slinky with MIT License | 5 votes |
package slinky.core import slinky.core.facade.{React, ReactChildren, ReactElement} import slinky.web.html.div import scala.scalajs.js import org.scalatest.funsuite.AnyFunSuite class ReactChildrenTest extends AnyFunSuite { import React.Children._ test("Can map over a single element") { assert(count(map((div(): ReactElement).asInstanceOf[ReactChildren], elem => elem)) == 1) } test("Can map over multiple elements") { assert(count(map(js.Array[ReactElement](div(), div()).asInstanceOf[ReactChildren], elem => elem)) == 2) } test("Can iterate with forEach over a single element") { var count = 0 forEach((div(): ReactElement).asInstanceOf[ReactChildren], _ => count += 1) assert(count == 1) } test("Can iterate with forEach over multiple elements") { var count = 0 forEach(js.Array[ReactElement](div(), div()).asInstanceOf[ReactChildren], _ => count += 1) assert(count == 2) } test("Can get count of a single element") { assert(count((div(): ReactElement).asInstanceOf[ReactChildren]) == 1) } test("Can get count of multiple elements") { assert(count(js.Array[ReactElement](div(), div()).asInstanceOf[ReactChildren]) == 2) } test("Can convert single element to array") { assert(toArray((div(): ReactElement).asInstanceOf[ReactChildren]).length == 1) } test("Can convert multiple elements to array") { assert(toArray(js.Array[ReactElement](div(), div()).asInstanceOf[ReactChildren]).length == 2) } }
Example 94
Source File: SuspenseTest.scala From slinky with MIT License | 5 votes |
package slinky.core import org.scalajs.dom import slinky.core.facade.Suspense import slinky.web.ReactDOM import slinky.web.html.div import org.scalatest.funsuite.AnyFunSuite class SuspenseTest extends AnyFunSuite { test("Can render a Suspense component with children") { val target = dom.document.createElement("div") ReactDOM.render( Suspense(fallback = div())( div("hello!") ), target ) assert(target.innerHTML == "<div>hello!</div>") } }
Example 95
Source File: StrictModeTest.scala From slinky with MIT License | 5 votes |
package slinky.core import slinky.core.facade.StrictMode import slinky.web.ReactDOM import slinky.web.html.div import org.scalajs.dom import org.scalatest.funsuite.AnyFunSuite class StrictModeTest extends AnyFunSuite { test("Can render a StrictMode component with children") { val target = dom.document.createElement("div") ReactDOM.render( StrictMode( div() ), target ) assert(target.innerHTML == "<div></div>") } }
Example 96
Source File: ContextTest.scala From slinky with MIT License | 5 votes |
package slinky.core import slinky.core.facade.React import slinky.web.ReactDOM import org.scalajs.dom.document import slinky.web.html.div import org.scalatest.funsuite.AnyFunSuite class ContextTest extends AnyFunSuite { test("Can provide and read a simple context value") { val context = React.createContext(-1) var gotValue = 0 ReactDOM.render( context.Provider(value = 2)( context.Consumer { value => gotValue = value div() } ), document.createElement("div") ) assert(gotValue == 2) } test("Can provide and read a case class context value") { case class Data(foo: Int) val context = React.createContext(Data(-1)) var gotValue = 0 ReactDOM.render( context.Provider(value = Data(3))( context.Consumer { value => gotValue = value.foo div() } ), document.createElement("div") ) assert(gotValue == 3) } test("Read a case class context value from default") { case class Data(foo: Int) val context = React.createContext(Data(3)) var gotValue = 0 ReactDOM.render( context.Consumer { value => gotValue = value.foo div() }, document.createElement("div") ) assert(gotValue == 3) } }
Example 97
Source File: ComponentReturnTypeTests.scala From slinky with MIT License | 5 votes |
package slinky.core import slinky.core.facade.{Fragment, ReactElement} import slinky.web.ReactDOM import slinky.web.html._ import org.scalajs.dom import org.scalatest.funsuite.AnyFunSuite class ComponentReturnTypeTests extends AnyFunSuite { def testElement(elem: ReactElement): Unit = { assert((div(elem): ReactElement) != null) // test use in another element ReactDOM.render(div(elem), dom.document.createElement("div")) // test rendering to DOM () } test("Components can return - arrays") { testElement(Seq(h1("a"), h1("b"))) } test("Components can return - strings") { testElement("hello") } test("Components can return - numbers") { testElement(1) testElement(1D) testElement(1F) } test("Components can return - portals") { testElement(ReactDOM.createPortal(null, dom.document.createElement("div"))) } test("Components can return - null") { testElement(null) } test("Components can return - booleans") { testElement(true) testElement(false) } test("Components can return - options") { testElement(Some(h1("hi"))) testElement(Some(NoPropsComponent())) testElement(None) } test("Components can return - fragments") { testElement(Fragment(h1("hi"))) } }
Example 98
Source File: ExportedComponentTest.scala From slinky with MIT License | 5 votes |
package slinky.core import slinky.core.facade.{React, ReactElement} import slinky.web.ReactDOM import scala.scalajs.js import org.scalajs.dom.document import org.scalatest.funsuite.AnyFunSuite object TestExportedComponentWithState extends ComponentWrapper { case class Props(name: String) type State = Int class Def(jsProps: js.Object) extends Definition(jsProps) { override def initialState: Int = 1 override def render(): ReactElement = { s"${props.name} $state" } } } object TestExportedComponentStateless extends StatelessComponentWrapper { case class Props(name: String) class Def(jsProps: js.Object) extends Definition(jsProps) { override def render(): ReactElement = { s"${props.name}" } } } object TestExportedExternalComponent extends ExternalComponentNoProps { case class Props(children: Seq[ReactElement]) val component = "div" } class ExportedComponentTest extends AnyFunSuite { test("Can construct an instance of an exported component with JS-provided props") { val container = document.createElement("div") ReactDOM.render(React.createElement( TestExportedComponentWithState: ReactComponentClass[_], js.Dictionary( "name" -> "lol" ) ), container) assert(container.innerHTML == "lol 1") } test("Can construct an instance of a stateless exported component with JS-provided props") { val container = document.createElement("div") ReactDOM.render(React.createElement( TestExportedComponentStateless: ReactComponentClass[_], js.Dictionary( "name" -> "lol" ) ), container) assert(container.innerHTML == "lol") } test("Can construct an instance of an exported functional component with JS-provided props") { case class FunctionalProps(name: String) val TestExportedFunctionalComponent = FunctionalComponent((p: FunctionalProps) => { p.name }) val container = document.createElement("div") ReactDOM.render(React.createElement( TestExportedFunctionalComponent: ReactComponentClass[_], js.Dictionary( "name" -> "lol" ) ), container) assert(container.innerHTML == "lol") } test("Can construct an instance of an exported external component with JS-provided props") { val container = document.createElement("div") ReactDOM.render(React.createElement( TestExportedExternalComponent: ReactComponentClass[_], js.Dictionary( "children" -> js.Array("hello") ) ), container) assert(container.innerHTML == "<div>hello</div>") } }
Example 99
Source File: NativeStaticAPITest.scala From slinky with MIT License | 5 votes |
package slinky.native import org.scalatest.funsuite.AnyFunSuite import scala.scalajs.js class NativeStaticAPITest extends AnyFunSuite { test("Can fire an alert") { Alert.alert("alert!") } test("Can read clipboard value") { assert(!js.isUndefined(Clipboard.getString)) } test("Can write clipboard value") { Clipboard.setString("bar") } }
Example 100
Source File: JsWriterTest.scala From scalajs-react-bridge with MIT License | 5 votes |
package com.payalabs.scalajs.react.bridge.test import scala.concurrent.Future import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue import scala.scalajs.js import com.payalabs.scalajs.react.bridge._ import org.scalatest.funsuite.AnyFunSuite class JsWriterTest extends AnyFunSuite { test("unionWriter") { val writer = unionWriter[Seq[String], Future[String]] val value1 = Seq("hello", "goodbye") val value2 = Future.successful("hello") val res1 = writer.toJs(value1) val res2 = writer.toJs(value2) assert(res1.isInstanceOf[js.Array[_]]) assert(!res1.isInstanceOf[js.Promise[_]]) assert(!res2.isInstanceOf[js.Array[_]]) assert(res2.isInstanceOf[js.Promise[_]]) } }
Example 101
Source File: AppModuleSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.atlas.aggregator import javax.inject.Singleton import com.google.inject.AbstractModule import com.google.inject.Guice import com.google.inject.Provider import com.netflix.spectator.api.Clock import com.netflix.spectator.api.NoopRegistry import com.netflix.spectator.api.Registry import com.netflix.spectator.atlas.AtlasConfig import com.netflix.spectator.atlas.AtlasRegistry import com.typesafe.config.Config import com.typesafe.config.ConfigFactory import org.scalatest.funsuite.AnyFunSuite class AppModuleSuite extends AnyFunSuite { import AppModuleSuite._ private val config = ConfigFactory.load() test("aggr service") { val injector = Guice.createInjector( new AppModule, new AbstractModule { override def configure(): Unit = { bind(classOf[Config]).toInstance(config) bind(classOf[Registry]).toProvider(classOf[RegistryProvider]) } } ) val aggr = injector.getInstance(classOf[AtlasAggregatorService]) assert(aggr != null) } test("aggr config should use prefix") { val config = ConfigFactory.parseString(""" |netflix.atlas.aggr.registry.atlas.uri = "test" """.stripMargin) val aggr = new AggrConfig(config, new NoopRegistry) assert(aggr.uri() === "test") } test("aggr config should use default for missing props") { val config = ConfigFactory.parseString(""" |netflix.atlas.aggr.registry.atlas.uri = "test" """.stripMargin) val aggr = new AggrConfig(config, new NoopRegistry) assert(aggr.batchSize() === 10000) } } object AppModuleSuite { @Singleton class RegistryProvider extends Provider[Registry] { override def get(): Registry = { val cfg = new AtlasConfig { override def get(k: String): String = null } new AtlasRegistry(Clock.SYSTEM, cfg) } } }
Example 102
Source File: EvalFlowSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.atlas.stream import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.scaladsl.Sink import akka.stream.scaladsl.Source import com.netflix.atlas.akka.DiagnosticMessage import com.netflix.atlas.eval.stream.Evaluator.DataSource import com.netflix.atlas.eval.stream.Evaluator.DataSources import com.netflix.atlas.eval.stream.Evaluator.MessageEnvelope import com.netflix.spectator.api.NoopRegistry import com.typesafe.config.ConfigFactory import org.scalatest.funsuite.AnyFunSuite import scala.concurrent.Await import scala.concurrent.duration.Duration class EvalFlowSuite extends AnyFunSuite { private implicit val system = ActorSystem(getClass.getSimpleName) private implicit val mat = ActorMaterializer() private val config = ConfigFactory.load private val registry = new NoopRegistry() private val validateNoop: DataSource => Unit = _ => () private val dataSourceStr = """[{"id":"abc", "step": 10, "uri":"http://local-dev/api/v1/graph?q=name,a,:eq"}]""" test("register and get message") { val evalService = new EvalService(config, registry, null, system) { override def updateDataSources(streamId: String, dataSources: DataSources): Unit = { val handler = getStreamInfo(streamId).handler handler.offer(new MessageEnvelope("mockId", DiagnosticMessage.info("mockMsg"))) handler.complete() } } val evalFlow = EvalFlow.createEvalFlow(evalService, DataSourceValidator(10, validateNoop)) Source.single(dataSourceStr).via(evalFlow) val future = Source .single(dataSourceStr) .via(evalFlow) .filter(envelope => envelope.getId != "_") //filter out heartbeat .runWith(Sink.head) val messageEnvelope = Await.result(future, Duration.Inf) assert(messageEnvelope.getId === "mockId") } }
Example 103
Source File: StatsApiSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.lwc import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.testkit.RouteTestTimeout import akka.http.scaladsl.testkit.ScalatestRouteTest import com.netflix.atlas.akka.RequestHandler import com.netflix.atlas.core.model.Datapoint import com.netflix.atlas.json.Json import com.netflix.spectator.atlas.impl.Subscription import com.typesafe.config.ConfigFactory import org.scalatest.BeforeAndAfter import org.scalatest.funsuite.AnyFunSuite class StatsApiSuite extends AnyFunSuite with ScalatestRouteTest with BeforeAndAfter { import scala.jdk.CollectionConverters._ import scala.concurrent.duration._ private implicit val routeTestTimeout = RouteTestTimeout(5.second) private val config = ConfigFactory.load() private val evaluator = new ExpressionsEvaluator(config) private val endpoint = new StatsApi(evaluator) private val routes = RequestHandler.standardOptions(endpoint.routes) private def assertJsonContentType(response: HttpResponse): Unit = { assert(response.entity.contentType.mediaType === MediaTypes.`application/json`) } private def assertResponse(response: HttpResponse, expected: StatusCode): Unit = { assert(response.status === expected) assertJsonContentType(response) } before { evaluator.clear() } test("empty") { Get("/api/v1/stats") ~> routes ~> check { assertResponse(response, StatusCodes.OK) assert(responseAs[String] === "[]") } } test("has data") { // Add sample subscription val subs = List( new Subscription() .withId("1") .withExpression("name,ssCpuUser,:eq,:sum"), new Subscription() .withId("2") .withExpression("name,ssCpuSystem,:eq,:sum") ) evaluator.sync(subs.asJava) // Stats only get updated when data is sent val datapoints = List( Datapoint(Map("name" -> "ssCpuUser", "node" -> "i-1"), 60000, 42.0), Datapoint(Map("name" -> "ssCpuUser", "node" -> "i-2"), 60000, 44.0) ) evaluator.eval(60000, datapoints) // Query the data Get("/api/v1/stats") ~> routes ~> check { assertResponse(response, StatusCodes.OK) val stats = Json.decode[List[ExpressionsEvaluator.SubscriptionStats]](responseAs[String]) assert(stats.length === 1) assert(stats.head.updateCount.get() === 2) } } }
Example 104
Source File: DynamoOpsSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.atlas.slotting import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.time.Duration import org.scalatest.funsuite.AnyFunSuite class DynamoOpsSuite extends AnyFunSuite with DynamoOps { def mkByteBuffer(s: String): ByteBuffer = { ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)) } test("compress and decompress") { val input = "Atlas Slotting Service" val compressed = Util.compress(input) assert(input === Util.decompress(compressed)) } test("active items spec") { val scanSpec = activeItemsScanSpec() assert(scanSpec.getFilterExpression === "#a = :v1") assert(scanSpec.getNameMap.toString === s"{#a=$Active}") assert(scanSpec.getValueMap.toString === "{:v1=true}") } test("old items spec") { val scanSpec = oldItemsScanSpec(Duration.ofDays(1)) assert(scanSpec.getFilterExpression === "#t < :v1") assert(scanSpec.getProjectionExpression === "#n") assert(scanSpec.getNameMap.toString === s"{#n=$Name, #t=$Timestamp}") } test("new asg item") { val newData = mkByteBuffer("""{"name": "atlas_app-main-all-v001", "desiredCapacity": 3}""") val item = newAsgItem("atlas_app-main-all-v001", newData) assert(item.hasAttribute(Name)) assert(item.hasAttribute(Data)) assert(item.hasAttribute(Active)) assert(item.hasAttribute(Timestamp)) } test("update asg spec") { val oldData = mkByteBuffer("""{"name": "atlas_app-main-all-v001", "desiredCapacity": 3}""") val newData = mkByteBuffer("""{"name": "atlas_app-main-all-v001", "desiredCapacity": 6}""") val updateSpec = updateAsgItemSpec("atlas_app-main-all-v001", oldData, newData) assert(updateSpec.getConditionExpression === "#d = :v1") assert(updateSpec.getUpdateExpression === s"set #d = :v2, #a = :v3, #t = :v4") assert(updateSpec.getNameMap.toString === s"{#d=data, #a=$Active, #t=$Timestamp}") } test("update timestamp spec") { val updateSpec = updateTimestampItemSpec("atlas_app-main-all-v001", 1556568270713L) assert(updateSpec.getConditionExpression === "#t = :v1") assert(updateSpec.getUpdateExpression === s"set #a = :v2, #t = :v3") assert(updateSpec.getNameMap.toString === s"{#a=$Active, #t=$Timestamp}") } test("deactivate asg spec") { val updateSpec = deactivateAsgItemSpec("atlas_app-main-all-v001") assert(updateSpec.getConditionExpression === "#a = :v1") assert(updateSpec.getUpdateExpression === s"set #a = :v2, #t = :v3") assert(updateSpec.getNameMap.toString === s"{#a=$Active, #t=$Timestamp}") } }
Example 105
Source File: RollingFileWriterSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.atlas.persistence import java.io.File import java.nio.file.Files import java.nio.file.Paths import com.netflix.atlas.core.model.Datapoint import com.netflix.spectator.api.NoopRegistry import org.apache.avro.file.DataFileReader import org.apache.avro.specific.SpecificDatumReader import org.scalatest.BeforeAndAfter import org.scalatest.BeforeAndAfterAll import org.scalatest.funsuite.AnyFunSuite import scala.collection.mutable.ListBuffer class RollingFileWriterSuite extends AnyFunSuite with BeforeAndAfter with BeforeAndAfterAll { private val outputDir = "./target/unitTestAvroOutput" private val registry = new NoopRegistry before { listFilesSorted(outputDir).foreach(_.delete()) // Clean up files if exits Files.createDirectories(Paths.get(outputDir)) } after { listFilesSorted(outputDir).foreach(_.delete()) Files.deleteIfExists(Paths.get(outputDir)) } // Write 3 datapoints, first 2 is written in file 1, rollover, and 3rd one is written in file 2 test("avro writer rollover by max records") { val rollingConf = RollingConfig(2, 12000, 12000) val hourStart = 3600000 val hourEnd = 7200000 val writer = new RollingFileWriter(s"$outputDir/prefix", rollingConf, hourStart, hourEnd, registry) writer.initialize() createData(hourStart, 0, 1, 2).foreach(writer.write) writer.write(Datapoint(Map.empty, hourEnd, 3)) // out of range, should be ignored writer.close() // Check num of files val files = listFilesSorted(outputDir) assert(files.size == 2) // Check file 1 records val file1 = files.head assert(file1.getName.endsWith(".0000-0001")) val dpArray1 = readAvro(file1) assert(dpArray1.size == 2) assert(dpArray1(0).getValue == 0) assert(dpArray1(0).getTags.get("node") == "0") assert(dpArray1(1).getValue == 1) assert(dpArray1(1).getTags.get("node") == "1") // Check file 2 records val file2 = files.last assert(file2.getName.endsWith(".0002-0002")) val dpArray2 = readAvro(file2) assert(dpArray2.size == 1) assert(dpArray2(0).getValue == 2) assert(dpArray2(0).getTags.get("node") == "2") } private def createData(startTime: Long, values: Double*): List[Datapoint] = { values.toList.zipWithIndex.map { case (v, i) => val tags = Map( "name" -> "cpu", "node" -> s"$i" ) Datapoint(tags, startTime + i * 1000, v, 60000) } } private def listFilesSorted(dir: String): List[File] = { val d = new File(dir) if (!d.exists()) { Nil } else { new File(dir).listFiles().filter(_.isFile).toList.sortBy(_.getName) } } private def readAvro(file: File): Array[AvroDatapoint] = { val userDatumReader = new SpecificDatumReader[AvroDatapoint](classOf[AvroDatapoint]) val dataFileReader = new DataFileReader[AvroDatapoint](file, userDatumReader) val dpListBuf = ListBuffer.empty[AvroDatapoint] try { while (dataFileReader.hasNext) { dpListBuf.addOne(dataFileReader.next) } } finally { dataFileReader.close() } dpListBuf.toArray } }
Example 106
Source File: PropertiesApiSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.archaius import java.io.StringReader import java.util.Properties import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.headers._ import akka.http.scaladsl.testkit.RouteTestTimeout import akka.http.scaladsl.testkit.ScalatestRouteTest import com.netflix.atlas.akka.RequestHandler import com.netflix.atlas.json.Json import com.netflix.spectator.api.DefaultRegistry import com.netflix.spectator.api.ManualClock import org.scalatest.funsuite.AnyFunSuite class PropertiesApiSuite extends AnyFunSuite with ScalatestRouteTest { import scala.concurrent.duration._ implicit val routeTestTimeout = RouteTestTimeout(5.second) val clock = new ManualClock() val registry = new DefaultRegistry(clock) val propContext = new PropertiesContext(registry) val endpoint = new PropertiesApi(propContext, system) val routes = RequestHandler.standardOptions(endpoint.routes) private def assertJsonContentType(response: HttpResponse): Unit = { assert(response.entity.contentType.mediaType === MediaTypes.`application/json`) } private def assertResponse(response: HttpResponse, expected: StatusCode): Unit = { assert(response.status === expected) assertJsonContentType(response) } test("no asg") { Get("/api/v1/property") ~> routes ~> check { assert(response.status === StatusCodes.BadRequest) } } test("empty") { propContext.update(Nil) Get("/api/v1/property?asg=foo-main-v001") ~> addHeader(Accept(MediaTypes.`application/json`)) ~> routes ~> check { assertResponse(response, StatusCodes.OK) assert(responseAs[String] === "[]") } } test("properties response") { propContext.update( List( PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L), PropertiesApi.Property("foo-main::1", "foo-main", "1", "2", 12345L), PropertiesApi.Property("bar-main::c", "bar-main", "c", "d", 12345L) ) ) Get("/api/v1/property?asg=foo-main-v001") ~> routes ~> check { assert(response.status === StatusCodes.OK) val props = new Properties props.load(new StringReader(responseAs[String])) assert(props.size === 2) assert(props.getProperty("a") === "b") assert(props.getProperty("1") === "2") } } test("json response") { propContext.update( List( PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L) ) ) Get("/api/v1/property?asg=foo-main-v001") ~> addHeader(Accept(MediaTypes.`application/json`)) ~> routes ~> check { assertResponse(response, StatusCodes.OK) val props = Json.decode[List[PropertiesApi.Property]](responseAs[String]) assert(props === List(PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L))) } } }
Example 107
Source File: CwForwardingConfigSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.lwc.fwd.admin import akka.actor.ActorSystem import com.netflix.atlas.eval.stream.Evaluator import com.netflix.spectator.api.NoopRegistry import com.typesafe.config.ConfigFactory import com.typesafe.scalalogging.StrictLogging import org.scalatest.funsuite.AnyFunSuite class CwForwardingConfigSuite extends AnyFunSuite with CwForwardingTestConfig with StrictLogging { private val config = ConfigFactory.load() private val system = ActorSystem() val validations = new CwExprValidations( new ExprInterpreter(config), new Evaluator(config, new NoopRegistry(), system) ) test("Skip the given checks") { val config = makeConfig(checksToSkip = List("DefaultDimension")) assert(config.shouldSkip("DefaultDimension")) } test("Do checks that are not flagged to skip") { val config = makeConfig(checksToSkip = List("DefaultDimension")) assert(!config.shouldSkip("SingleExpression")) } }
Example 108
Source File: ExprInterpreterSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.lwc.fwd.admin import com.typesafe.config.ConfigFactory import org.scalatest.funsuite.AnyFunSuite class ExprInterpreterSuite extends AnyFunSuite { val interpreter = new ExprInterpreter(ConfigFactory.load()) test("Should be able to parse a valid expression") { val atlasUri = makeAtlasUri( expr = """ |name,nodejs.cpuUsage,:eq, |:node-avg, |(,nf.account,nf.asg,),:by """.stripMargin ) assert(interpreter.eval(atlasUri).size == 1) } test("Should fail for invalid expression") { val atlasUri = makeAtlasUri( expr = """ |name,nodejs.cpuUsage,:e, |:node-avg, |(,nf.account,nf.asg,),:by """.stripMargin ) val exception = intercept[IllegalStateException]( interpreter.eval(atlasUri) ) assert(exception.getMessage == "unknown word ':e'") } def makeAtlasUri( expr: String ): String = { s"""http://localhost/api/v1/graph?q=$expr""" .replace("\n", "") .trim } }
Example 109
Source File: ValidationSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.lwc.fwd.admin import com.netflix.atlas.core.model.StyleExpr import com.netflix.iep.lwc.fwd.cw.ForwardingDimension import com.netflix.iep.lwc.fwd.cw.ForwardingExpression import org.scalatest.funsuite.AnyFunSuite class ValidationSuite extends AnyFunSuite with TestAssertions with CwForwardingTestConfig { test("Perform a required validation") { val validation = Validation( "RequiredCheck", true, (_, _) => throw new IllegalArgumentException("Validation failed") ) assertFailure( validation.validate( makeConfig(), ForwardingExpression("", "", None, "", List.empty[ForwardingDimension]), List.empty[StyleExpr] ), "Validation failed" ) } test("Perform an optional validation") { val validation = Validation( "OptionalCheck", false, (_, _) => throw new IllegalArgumentException("Validation failed") ) assertFailure( validation.validate( makeConfig(), ForwardingExpression("", "", None, "", List.empty[ForwardingDimension]), List.empty[StyleExpr] ), "Validation failed" ) } test("Skip an optional validation") { val validation = Validation( "OptionalCheck", false, (_, _) => throw new IllegalArgumentException("Validation failed") ) validation.validate( makeConfig(checksToSkip = List("OptionalCheck")), ForwardingExpression("", "", None, "", List.empty[ForwardingDimension]), List.empty[StyleExpr] ) } }
Example 110
Source File: LoadGenServiceSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.loadgen import java.time.Duration import org.scalatest.funsuite.AnyFunSuite class LoadGenServiceSuite extends AnyFunSuite { test("extract step from uri") { val actual = LoadGenService.extractStep("/graph?q=name,foo,:eq&step=60s") assert(actual === Some(Duration.ofSeconds(60))) } test("extract step from uri, not present") { val actual = LoadGenService.extractStep("/graph?q=name,foo,:eq") assert(actual === None) } test("extract step from uri, invalid uri") { val actual = LoadGenService.extractStep("/graph?q=name,{{ .SpinnakerApp }},:eq") assert(actual === None) } test("extract step from uri, invalid step") { val actual = LoadGenService.extractStep("/graph?q=name,foo,:eq&step=bad") assert(actual === None) } }
Example 111
Source File: catzSpecBase.scala From interop-cats with Apache License 2.0 | 5 votes |
package zio.interop import cats.Eq import cats.effect.laws.util.{ TestContext, TestInstances } import cats.implicits._ import org.scalacheck.Arbitrary import org.scalatest.funsuite.AnyFunSuite import org.scalatest.prop.Configuration import org.typelevel.discipline.Laws import org.typelevel.discipline.scalatest.FunSuiteDiscipline import zio.clock.Clock import zio.console.Console import zio.internal.{ Executor, Platform, Tracing } import zio.interop.catz.taskEffectInstance import zio.random.Random import zio.system.System import zio.{ =!=, Cause, IO, Runtime, Task, UIO, ZIO, ZManaged } private[zio] trait catzSpecBase extends AnyFunSuite with FunSuiteDiscipline with Configuration with TestInstances with catzSpecBaseLowPriority { type Env = Clock with Console with System with Random implicit def rts(implicit tc: TestContext): Runtime[Unit] = Runtime( (), Platform .fromExecutor(Executor.fromExecutionContext(Int.MaxValue)(tc)) .withTracing(Tracing.disabled) .withReportFailure(_ => ()) ) implicit val zioEqCauseNothing: Eq[Cause[Nothing]] = Eq.fromUniversalEquals implicit def zioEqIO[E: Eq, A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[IO[E, A]] = Eq.by(_.either) implicit def zioEqTask[A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[Task[A]] = Eq.by(_.either) implicit def zioEqUIO[A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[UIO[A]] = Eq.by(uio => taskEffectInstance.toIO(uio.sandbox.either)) implicit def zioEqZManaged[E: Eq, A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[ZManaged[Any, E, A]] = Eq.by( zm => ZManaged.ReleaseMap.make.flatMap(releaseMap => zm.zio.provideSome[Any]((_, releaseMap)).map(_._2).either) ) def checkAllAsync(name: String, f: TestContext => Laws#RuleSet): Unit = checkAll(name, f(TestContext())) } private[interop] sealed trait catzSpecBaseLowPriority { this: catzSpecBase => implicit def zioEq[R: Arbitrary, E: Eq, A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[ZIO[R, E, A]] = { def run(r: R, zio: ZIO[R, E, A]) = taskEffectInstance.toIO(zio.provide(r).either) Eq.instance((io1, io2) => Arbitrary.arbitrary[R].sample.fold(false)(r => catsSyntaxEq(run(r, io1)) eqv run(r, io2))) } // 'R =!= Any' evidence fixes the 'diverging implicit expansion for type Arbitrary' error reproducible on scala 2.12 and 2.11. implicit def zmanagedEq[R: * =!= Any: Arbitrary, E: Eq, A: Eq]( implicit rts: Runtime[Any], tc: TestContext ): Eq[ZManaged[R, E, A]] = { def run(r: R, zm: ZManaged[R, E, A]) = taskEffectInstance.toIO( ZManaged.ReleaseMap.make.flatMap(releaseMap => zm.zio.provide((r, releaseMap)).map(_._2).either) ) Eq.instance((io1, io2) => Arbitrary.arbitrary[R].sample.fold(false)(r => catsSyntaxEq(run(r, io1)) eqv run(r, io2))) } }
Example 112
Source File: ConsoleModuleTest.scala From scala-server-toolkit with MIT License | 5 votes |
package com.avast.sst.jvm.system.console import java.io.{ByteArrayInputStream, ByteArrayOutputStream} import cats.effect.SyncIO import org.scalatest.funsuite.AnyFunSuite import scala.{Console => SConsole} class ConsoleModuleTest extends AnyFunSuite { test("Console input") { SConsole.withIn(new ByteArrayInputStream("test input\n".getBytes("UTF-8"))) { val test = for { line <- ConsoleModule.make[SyncIO].readLine } yield assert(line === "test input") test.unsafeRunSync() } } test("Console output") { val out = new ByteArrayOutputStream() SConsole.withOut(out) { val test = for { _ <- ConsoleModule.make[SyncIO].printLine("test output") } yield () test.unsafeRunSync() } assert(out.toString("UTF-8") === "test output\n") } test("Console error") { val out = new ByteArrayOutputStream() SConsole.withErr(out) { val test = for { _ <- ConsoleModule.make[SyncIO].printLineToError("test output") } yield () test.unsafeRunSync() } assert(out.toString("UTF-8") === "test output\n") } }
Example 113
Source File: PureConfigModuleTest.scala From scala-server-toolkit with MIT License | 5 votes |
package com.avast.sst.pureconfig import cats.data.NonEmptyList import cats.effect.SyncIO import org.scalatest.funsuite.AnyFunSuite import pureconfig.error.ConfigReaderException import pureconfig.generic.semiauto.deriveReader import pureconfig.{ConfigReader, ConfigSource} class PureConfigModuleTest extends AnyFunSuite { private val source = ConfigSource.string("""|number = 123 |string = "test"""".stripMargin) private case class TestConfig(number: Int, string: String) implicit private val configReader: ConfigReader[TestConfig] = deriveReader test("Simple configuration loading") { assert(PureConfigModule.make[SyncIO, TestConfig](source).unsafeRunSync() === Right(TestConfig(123, "test"))) assert( PureConfigModule.make[SyncIO, TestConfig](ConfigSource.empty).unsafeRunSync() === Left( NonEmptyList("Invalid configuration : Key not found: 'number'.", List("Invalid configuration : Key not found: 'string'.")) ) ) } test("Configuration loading with exceptions") { assert(PureConfigModule.makeOrRaise[SyncIO, TestConfig](source).unsafeRunSync() === TestConfig(123, "test")) assertThrows[ConfigReaderException[TestConfig]] { PureConfigModule.makeOrRaise[SyncIO, TestConfig](ConfigSource.empty).unsafeRunSync() } } }
Example 114
Source File: SslContextModuleTest.scala From scala-server-toolkit with MIT License | 5 votes |
package com.avast.sst.ssl import cats.effect.SyncIO import com.typesafe.config.ConfigFactory import org.scalatest.funsuite.AnyFunSuite class SslContextModuleTest extends AnyFunSuite { test("SslContextModule initializes properly from JKS store with reference config") { val sslContext = SslContextModule.make[SyncIO](ConfigFactory.empty()).unsafeRunSync() assert(sslContext.getProtocol === "TLSv1.2") } test("SslContextModule initializes properly from JKS store with provided config") { val sslContext = SslContextModule.make[SyncIO](ConfigFactory.load().getConfig("ssl-config"), withReference = false).unsafeRunSync() assert(sslContext.getProtocol === "TLSv1.2") } test("SslContextModule fails to initialize for empty config and no reference config") { val result = SslContextModule.make[SyncIO](ConfigFactory.empty(), withReference = false).attempt.unsafeRunSync() assert(result.isLeft) } }
Example 115
Source File: MicrometerHttp4sMetricsOpsModuleTest.scala From scala-server-toolkit with MIT License | 5 votes |
package com.avast.sst.http4s.server.micrometer import java.util.concurrent.TimeUnit import cats.effect.IO import io.micrometer.core.instrument.simple.SimpleMeterRegistry import org.http4s.{Method, Status} import org.scalatest.funsuite.AnyFunSuite class MicrometerHttp4sMetricsOpsModuleTest extends AnyFunSuite { test("http4s MetricsOps for Micrometer") { val registry = new SimpleMeterRegistry() val metricsOps = MicrometerHttp4sMetricsOpsModule.make[IO](registry).unsafeRunSync() metricsOps.increaseActiveRequests(None).unsafeRunSync() metricsOps.recordTotalTime(Method.GET, Status.Ok, 2500, None).unsafeRunSync() assert(registry.get("http.global.active-requests").gauge().value() === 1) assert(registry.get("http.global.total-time").timer().count() === 1) assert(registry.get("http.global.total-time").timer().totalTime(TimeUnit.NANOSECONDS) > 2499) assert(registry.get("http.global.total-time").tags("status", "200").timer().count() === 1) assert(registry.get("http.global.total-time").tags("status-class", "2xx").timer().count() === 1) } }
Example 116
Source File: RouteMetricsTest.scala From scala-server-toolkit with MIT License | 5 votes |
package com.avast.sst.http4s.server.micrometer import java.util.concurrent.TimeUnit import cats.effect.SyncIO import io.micrometer.core.instrument.simple.SimpleMeterRegistry import org.http4s.Response import org.scalatest.funsuite.AnyFunSuite class RouteMetricsTest extends AnyFunSuite { test("Single route metrics") { val registry = new SimpleMeterRegistry() val target = new RouteMetrics[SyncIO](registry) target.wrap("test")(SyncIO.pure(Response.notFound[SyncIO])).unsafeRunSync() assert(registry.get("http.test").timer().count() === 1) assert(registry.get("http.test").timer().totalTime(TimeUnit.MILLISECONDS) > 0) assert(registry.get("http.test").tags("status", "404").timer().count() === 1) } }
Example 117
Source File: AllCodecTest.scala From aws-lambda-scala with MIT License | 5 votes |
package io.github.mkotsur.aws.codecs import java.io.ByteArrayOutputStream import com.amazonaws.services.lambda.runtime.Context import io.circe.generic.auto._ import io.github.mkotsur.StringInputStream import org.scalatest.EitherValues._ import org.scalatest.concurrent.Eventually import org.mockito.MockitoSugar import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should import org.scalatest.{FunSuite, Matchers} class AllCodecTest extends AnyFunSuite with should.Matchers with MockitoSugar with Eventually { test("should decode null") { new AllCodec { val is = new StringInputStream("""null""") val value = canDecodeAll[None.type].readStream(is) value.right.value shouldBe Option.empty[None.type] } } test("should decode empty string") { new AllCodec { val is = new StringInputStream("") val value = canDecodeAll[None.type].readStream(is) value.right.value shouldBe Option.empty[None.type] } } test("should encode null") { new AllCodec { val os = new ByteArrayOutputStream() val context: Context = mock[Context] canEncodeAll[None.type].writeStream(os, Right(None), context) os.toString shouldBe "null" } } }
Example 118
Source File: NamingTest.scala From yoda-orm with MIT License | 5 votes |
package in.norbor.yoda.orm import org.scalatest.funsuite.AnyFunSuite class NamingTest extends AnyFunSuite { test("testCamelToSnakecase 1") { val input = "thisIsA1Test" val expected = "this_is_a_1_test" val result = Naming.camelToSnakecase(input) assert(result === expected) } test("testCamelToSnakecase 2") { val input = "citizenId" val expected = "citizen_id" val result = Naming.camelToSnakecase(input) assert(result === expected) } test("testSnakecaseToCamel") { val input = "this_is_a_1_test" val expected = "thisIsA1Test" val result = Naming.snakecaseToCamel(input) assert(result === expected) } }
Example 119
Source File: PStatementTest.scala From yoda-orm with MIT License | 5 votes |
package in.norbor.yoda.orm import java.sql.{Connection, DriverManager, ResultSet, Timestamp} import com.typesafe.scalalogging.LazyLogging import in.norbor.yoda.implicits.JavaSqlImprovement._ import mocks.People import org.joda.time.DateTime import org.scalatest.funsuite.AnyFunSuite class PStatementTest extends AnyFunSuite { Class.forName("org.h2.Driver") private implicit val conn: Connection = DriverManager.getConnection("jdbc:h2:~/test", "sa", "") test("0) apply") { val ps = PStatement("SELECT 1")(conn) assert(ps !== null) ps.equals(null) ps.canEqual(null) ps.hashCode ps.toString ps.productPrefix ps.productArity ps.productElement(0) ps.productIterator ps.copy() } test("0) query") { PStatement("DROP TABLE IF EXISTS yoda_sql; CREATE TABLE yoda_sql (id INTEGER);") .update } test("0) update") { val rs = PStatement("""select 1""") .query assert(rs !== null) } test("0) queryOne with non index parameter") { val result = PStatement("""select ?, ?, ?, ?, ?, ?, ?, ?""") .setBoolean(true) .setInt(1) .setLong(1L) .setDouble(1) .setString("YO") .setDateTime(DateTime.now) .setTimestamp(new Timestamp(System.currentTimeMillis)) .setTimestamp(null) .queryOne(parse) assert(result.head._1 === true) } test("3) queryList with parse method") { val peoples = PStatement("""select 1 as id, 'Peerapat' as name, now() as born;""") .queryList(parsePeople) assert(peoples.head.id === 1) assert(peoples.head.name === "Peerapat") assert(peoples.head.born.getMillis <= DateTime.now.getMillis) } test("5) batch") { val insert = PStatement("INSERT INTO yoda_sql VALUES(?)") .setInt(1) .addBatch() .setInt(2) .addBatch() .executeBatch assert(insert.length === 2) } private def parse(rs: ResultSet): (Boolean, Int, Long, Double, String, DateTime, Timestamp) = (rs.getBoolean(1) , rs.getInt(2) , rs.getLong(3) , rs.getDouble(4) , rs.getString(5) , rs.getDateTime(6) , rs.getTimestamp(7) ) private def parsePeople(rs: ResultSet): People = People(id = rs.getLong("id") , name = rs.getString("name") , born = rs.getDateTime("born") ) }
Example 120
Source File: SmoothFeeProviderSpec.scala From eclair with Apache License 2.0 | 5 votes |
package fr.acinq.eclair.blockchain.fee import org.scalatest.funsuite.AnyFunSuite import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import scala.concurrent.{Await, Future} class SmoothFeeProviderSpec extends AnyFunSuite { test("smooth fee rates") { val rates = Array( FeeratesPerKB(100, 200, 300, 400, 500, 600, 650), FeeratesPerKB(200, 300, 400, 500, 600, 700, 750), FeeratesPerKB(300, 400, 500, 600, 700, 800, 850), FeeratesPerKB(300, 400, 500, 600, 700, 800, 850), FeeratesPerKB(300, 400, 500, 600, 700, 800, 850) ) val provider = new FeeProvider { var index = 0 override def getFeerates: Future[FeeratesPerKB] = { val rate = rates(index) index = (index + 1) % rates.length Future.successful(rate) } } val smoothProvider = new SmoothFeeProvider(provider, windowSize = 3) val f = for { rate1 <- smoothProvider.getFeerates rate2 <- smoothProvider.getFeerates rate3 <- smoothProvider.getFeerates rate4 <- smoothProvider.getFeerates rate5 <- smoothProvider.getFeerates } yield (rate1, rate2, rate3, rate4, rate5) val (rate1, rate2, rate3, rate4, rate5) = Await.result(f, 5 seconds) assert(rate1 == rates(0)) assert(rate2 == SmoothFeeProvider.smooth(Seq(rates(0), rates(1)))) assert(rate3 == SmoothFeeProvider.smooth(Seq(rates(0), rates(1), rates(2)))) assert(rate3 == FeeratesPerKB(200, 300, 400, 500, 600, 700, 750)) assert(rate4 == SmoothFeeProvider.smooth(Seq(rates(1), rates(2), rates(3)))) assert(rate5 == rates(4)) // since the last 3 values are the same } }
Example 121
Source File: BitgoFeeProviderSpec.scala From eclair with Apache License 2.0 | 5 votes |
package fr.acinq.eclair.blockchain.fee import akka.actor.ActorSystem import akka.util.Timeout import com.softwaremill.sttp.okhttp.OkHttpFutureBackend import fr.acinq.bitcoin.Block import org.json4s.DefaultFormats import org.scalatest.funsuite.AnyFunSuite import scala.concurrent.Await class BitgoFeeProviderSpec extends AnyFunSuite { import BitgoFeeProvider._ import org.json4s.jackson.JsonMethods.parse implicit val formats = DefaultFormats val sample_response = """ {"feePerKb":136797,"cpfpFeePerKb":136797,"numBlocks":2,"confidence":80,"multiplier":1,"feeByBlockTarget":{"1":149453,"2":136797,"5":122390,"6":105566,"8":100149,"9":96254,"10":122151,"13":116855,"15":110860,"17":87402,"27":82635,"33":71098,"42":105782,"49":68182,"73":59207,"97":17336,"121":16577,"193":13545,"313":12268,"529":11122,"553":9139,"577":5395,"793":5070}} """ test("parse test") { val json = parse(sample_response) val feeRanges = parseFeeRanges(json) assert(feeRanges.size === 23) } test("extract fee for a particular block delay") { val json = parse(sample_response) val feeRanges = parseFeeRanges(json) val fee = extractFeerate(feeRanges, 6) assert(fee === 105566) } test("extract all fees") { val json = parse(sample_response) val feeRanges = parseFeeRanges(json) val feerates = extractFeerates(feeRanges) val ref = FeeratesPerKB( block_1 = 149453, blocks_2 = 136797, blocks_6 = 105566, blocks_12 = 96254, blocks_36 = 71098, blocks_72 = 68182, blocks_144 = 16577) assert(feerates === ref) } test("make sure API hasn't changed") { import scala.concurrent.duration._ implicit val system = ActorSystem("test") implicit val ec = system.dispatcher implicit val sttp = OkHttpFutureBackend() implicit val timeout = Timeout(30 seconds) val bitgo = new BitgoFeeProvider(Block.LivenetGenesisBlock.hash, 5 seconds) assert(Await.result(bitgo.getFeerates, timeout.duration).block_1 > 0) } test("check that read timeout is enforced") { import scala.concurrent.duration._ implicit val system = ActorSystem("test") implicit val ec = system.dispatcher implicit val sttp = OkHttpFutureBackend() implicit val timeout = Timeout(30 second) val bitgo = new BitgoFeeProvider(Block.LivenetGenesisBlock.hash, 1 millisecond) val e = intercept[Exception] { Await.result(bitgo.getFeerates, timeout.duration) } assert(e.getMessage.contains("Read timed out")) } }
Example 122
Source File: DbFeeProviderSpec.scala From eclair with Apache License 2.0 | 5 votes |
package fr.acinq.eclair.blockchain.fee import akka.util.Timeout import fr.acinq.eclair.TestConstants import fr.acinq.eclair.db.sqlite.SqliteFeeratesDb import org.scalatest.funsuite.AnyFunSuite import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import scala.concurrent.{Await, Future} class DbFeeProviderSpec extends AnyFunSuite { val feerates1: FeeratesPerKB = FeeratesPerKB(100, 200, 300, 400, 500, 600, 700) test("db fee provider saves feerates in database") { val sqlite = TestConstants.sqliteInMemory() val db = new SqliteFeeratesDb(sqlite) val provider = new DbFeeProvider(db, new ConstantFeeProvider(feerates1)) assert(db.getFeerates().isEmpty) assert(Await.result(provider.getFeerates, Timeout(30 seconds).duration) == feerates1) assert(db.getFeerates().get == feerates1) } }
Example 123
Source File: MilliSatoshiSpec.scala From eclair with Apache License 2.0 | 5 votes |
package fr.acinq.eclair import fr.acinq.bitcoin.Satoshi import org.scalatest.funsuite.AnyFunSuite class MilliSatoshiSpec extends AnyFunSuite { test("millisatoshi numeric operations") { // add assert(MilliSatoshi(561) + 0.msat === MilliSatoshi(561)) assert(MilliSatoshi(561) + 0.sat === MilliSatoshi(561)) assert(MilliSatoshi(561) + 1105.msat === MilliSatoshi(1666)) assert(MilliSatoshi(2000) + 3.sat === MilliSatoshi(5000)) // subtract assert(MilliSatoshi(561) - 0.msat === MilliSatoshi(561)) assert(MilliSatoshi(1105) - 561.msat === MilliSatoshi(544)) assert(561.msat - 1105.msat === -MilliSatoshi(544)) assert(MilliSatoshi(561) - 1105.msat === -MilliSatoshi(544)) assert(MilliSatoshi(1105) - 1.sat === MilliSatoshi(105)) // multiply assert(MilliSatoshi(561) * 1 === 561.msat) assert(MilliSatoshi(561) * 2 === 1122.msat) assert(MilliSatoshi(561) * 2.5 === 1402.msat) // divide assert(MilliSatoshi(561) / 1 === MilliSatoshi(561)) assert(MilliSatoshi(561) / 2 === MilliSatoshi(280)) // compare assert(MilliSatoshi(561) <= MilliSatoshi(561)) assert(MilliSatoshi(561) <= 1105.msat) assert(MilliSatoshi(561) < MilliSatoshi(1105)) assert(MilliSatoshi(561) >= MilliSatoshi(561)) assert(MilliSatoshi(1105) >= MilliSatoshi(561)) assert(MilliSatoshi(1105) > MilliSatoshi(561)) assert(MilliSatoshi(1000) <= Satoshi(1)) assert(MilliSatoshi(1000) <= 2.sat) assert(MilliSatoshi(1000) < Satoshi(2)) assert(MilliSatoshi(1000) >= Satoshi(1)) assert(MilliSatoshi(2000) >= Satoshi(1)) assert(MilliSatoshi(2000) > Satoshi(1)) // maxOf assert((561 msat).max(1105 msat) === MilliSatoshi(1105)) assert((1105 msat).max(1 sat) === MilliSatoshi(1105)) assert((1105 msat).max(2 sat) === MilliSatoshi(2000)) assert((1 sat).max(2 sat) === Satoshi(2)) // minOf assert((561 msat).min(1105 msat) === MilliSatoshi(561)) assert((1105 msat).min(1 sat) === MilliSatoshi(1000)) assert((1105 msat).min(2 sat) === MilliSatoshi(1105)) assert((1 sat).min(2 sat) === Satoshi(1)) } }
Example 124
Source File: sbt-test-test.scala From scala-course with GNU General Public License v3.0 | 5 votes |
import org.scalatest.funsuite.AnyFunSuite // Here using FunSuite style - but other possibilities... class SetSuite extends AnyFunSuite { test("An empty Set should have size 0") { assert(Set.empty.size == 0) } test("A Gaussian sample of length 10 should have length 10") { import breeze.stats.distributions.Gaussian val x = Gaussian(2.0,4.0).sample(10) assert(x.length === 10) } test("Cats map merge") { import cats.instances.all._ import cats.syntax.semigroup._ val m1 = Map("a"->1,"b"->2) val m2 = Map("b"->2,"c"->1) val m3 = m1 |+| m2 val m4 = Map("b" -> 4, "c" -> 1, "a" -> 1) assert(m3 === m4) } } // eof
Example 125
Source File: KeyEscaperTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package mongo import com.mongodb.internal.validator.CollectibleDocumentFieldNameValidator import org.scalacheck.{Arbitrary, Gen} import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class KeyEscaperTest extends AnyFunSuite with ScalaCheckPropertyChecks { import KeyEscaper._ import KeyEscaperTest._ test("custom keys") { val customCases = List( "plain" -> "plain", "<plain, but strange>" -> "<plain, but strange>", "not_so_plain" -> "not_so_plain", "$" -> "\\$", "." -> "\\_", "plain$ with$ $dollars$" -> "plain$ with$ $dollars$", "Sentence." -> "Sentence\\_", "$operator" -> "\\$operator", "$worst.of.both.worlds" -> "\\$worst\\_of\\_both\\_worlds" ) for ((input, expected) <- customCases) { val escaped = escape(input) assert(validator.validate(escaped)) assert(escaped == expected) assert(unescape(escaped) == input) } } test("plain keys") { forAll(plainKeyGen) { plainKey => val escaped = escape(plainKey) assert(validator.validate(escaped)) assert(escaped == plainKey) assert(unescape(escaped) == plainKey) } } test("arbitrary keys") { forAll(deniedKeyGen) { arbitraryKey => val escaped = escape(arbitraryKey) assert(validator.validate(escaped)) assert(unescape(escaped) == arbitraryKey) } } } object KeyEscaperTest { def isPlain(char: Char): Boolean = char != '.' && char != '$' && char != '\\' val validator = new CollectibleDocumentFieldNameValidator val plainCharGen: Gen[Char] = Arbitrary.arbitrary[Char].filter(isPlain) val plainKeyGen: Gen[String] = Gen.listOf(plainCharGen).map(_.mkString) val deniedCharGen: Gen[Char] = Gen.oneOf('.', '$') val deniedKeyGen: Gen[String] = Gen.listOf(Gen.oneOf(plainCharGen, deniedCharGen)).map(_.mkString) }
Example 126
Source File: BsonRefTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package mongo import com.avsystem.commons.serialization.{GenCodec, name, transparent} import org.scalatest.funsuite.AnyFunSuite case class InnerClass( map: Map[String, String] ) object InnerClass extends BsonRef.Creator[InnerClass] { implicit val codec: GenCodec[InnerClass] = GenCodec.materialize final val MapRef = ref(_.map) } @transparent case class Wrapper(s: String) extends AnyVal object Wrapper { implicit val codec: GenCodec[Wrapper] = GenCodec.materialize } case class TestEntity( `$special.field`: String, wrapper: Wrapper, @name("inner") innerClass: InnerClass ) object TestEntity extends BsonRef.Creator[TestEntity] { implicit val codec: GenCodec[TestEntity] = GenCodec.materialize } class BsonRefTest extends AnyFunSuite with BsonRef.Creator[TestEntity] { test("basic test") { assert(ref(_.wrapper).path == "wrapper") assert(ref(_.wrapper.s).path == "wrapper") assert(ref(_.innerClass).path == "inner") assert(ref(_.innerClass.map).path == "inner.map") assert(ref(_.innerClass).andThen(InnerClass.MapRef).path == "inner.map") assert(ref(_.innerClass.map("key")).path == "inner.map.key") assert(ref(_.`$special.field`).path == "\\$special\\_field") } }
Example 127
Source File: BsonValueCodecsTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package mongo import com.avsystem.commons.serialization.{GenCodec, HasGenCodecWithDeps} import org.bson.json.JsonReader import org.bson.types.{Decimal128, ObjectId} import org.bson.{BsonArray, BsonBinary, BsonBoolean, BsonDateTime, BsonDecimal128, BsonDocument, BsonDouble, BsonElement, BsonInt32, BsonInt64, BsonNull, BsonObjectId, BsonString, BsonValue} import org.scalatest.funsuite.AnyFunSuite case class AllTypesInABag( array: BsonArray, binary: BsonBinary, boolean: BsonBoolean, dateTime: BsonDateTime, document: BsonDocument, decimal128: BsonDecimal128, double: BsonDouble, int32: BsonInt32, int64: BsonInt64, objectId: BsonObjectId, string: BsonString, value: BsonValue ) object AllTypesInABag extends HasGenCodecWithDeps[BsonGenCodecs.type, AllTypesInABag] class BsonValueCodecsTest extends AnyFunSuite { test("codec roundtrip") { val doc = new BsonDocument(JList( new BsonElement("someInt64", new BsonInt64(64)), new BsonElement("someString", new BsonString("some")) )) val bag = AllTypesInABag( new BsonArray(JList(BsonBoolean.TRUE, new BsonInt32(131))), new BsonBinary(Array.tabulate[Byte](16)(_.toByte)), BsonBoolean.FALSE, new BsonDateTime(313), doc, new BsonDecimal128(new Decimal128(1331)), new BsonDouble(1.31), new BsonInt32(132), new BsonInt64(164), new BsonObjectId(new ObjectId("12345678901234567890ABCD")), new BsonString("sss"), doc ) var value: BsonValue = null val output = new BsonValueOutput(value = _) GenCodec.write(output, bag) assert(value.isInstanceOf[BsonDocument]) val outDoc = value.asInstanceOf[BsonDocument] assert(outDoc.getArray("array") === bag.array) assert(outDoc.getBinary("binary") === bag.binary) assert(outDoc.getBoolean("boolean") === bag.boolean) assert(outDoc.getDateTime("dateTime") === bag.dateTime) assert(outDoc.getDocument("document") === bag.document) assert(outDoc.getDecimal128("decimal128") === bag.decimal128) assert(outDoc.getDouble("double") === bag.double) assert(outDoc.getInt32("int32") === bag.int32) assert(outDoc.getInt64("int64") === bag.int64) assert(outDoc.getObjectId("objectId") === bag.objectId) assert(outDoc.getString("string") === bag.string) assert(outDoc.get("value") === bag.value) val input = new BsonValueInput(value) assert(GenCodec.read[AllTypesInABag](input) === bag) } test("null handling") { import BsonGenCodecs.bsonDocumentCodec val reader = new JsonReader("""{"key": null}""") val input = new BsonReaderInput(reader) val document = GenCodec.read[BsonDocument](input) assert(document === new BsonDocument("key", BsonNull.VALUE)) var decoded: BsonValue = null val output = new BsonValueOutput(decoded = _) GenCodec.write(output, document) assert(decoded === document) } test("null in doc in array") { import BsonGenCodecs.bsonArrayCodec val reader = new JsonReader("""[{"key": null}]""") val input = new BsonReaderInput(reader) val array = GenCodec.read[BsonArray](input) assert(array === new BsonArray(JList(new BsonDocument("key", BsonNull.VALUE)))) } }
Example 128
Source File: DocTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package mongo import org.bson.BsonString import org.scalatest.funsuite.AnyFunSuite class DocTest extends AnyFunSuite { import DocTest._ test("get variance") { val doc = Doc() doc.get(something): Option[Something] doc.get(somethingCool): Option[SomethingCool.type] doc.get(somethingCool): Option[Something] doc.get(stringSet): Option[BSet[String]] assertDoesNotCompile("doc.get(something): Option[SomethingCool.type]") assertDoesNotCompile("doc.get(something): Option[SomethingShiny.type]") assertDoesNotCompile("doc.get(stringSet): Option[ISet[String]") assertDoesNotCompile("doc.get(stringSet): Option[MSet[String]") } test("put variance") { val doc = Doc() doc .put(something, SomethingShiny) .put(somethingCool, SomethingCool) .put(stringSet, ISet("one", "two", "three")) .put(stringSet, MSet("one", "two", "three")) assertDoesNotCompile("doc.put(somethingCool, SomethingShiny)") } } object DocTest { sealed trait Something object SomethingCool extends Something object SomethingShiny extends Something val Cool = "cool" val Shiny = "shiny" val something = new BsonCodec[Something, BsonString] { override def fromBson(bson: BsonString) = bson.getValue match { case Cool => SomethingCool case Shiny => SomethingShiny } override def toBson(a: Something) = new BsonString(a match { case SomethingCool => Cool case SomethingShiny => Shiny }) }.key("something") val somethingCool = new BsonCodec[SomethingCool.type, BsonString] { override def fromBson(bson: BsonString) = SomethingCool override def toBson(a: SomethingCool.type) = new BsonString(Cool) }.key("somethingCool") val stringSet = BsonCodec.string.collection[BSet].key("stringSet") }
Example 129
Source File: SortingTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package mongo.core.ops import com.avsystem.commons.mongo.core.ops.BsonEquality.bsonEquality import com.avsystem.commons.mongo.{BsonCodec, BsonRef, DocKey} import com.avsystem.commons.serialization.GenCodec import com.mongodb.client.model.Sorts import org.scalatest.funsuite.AnyFunSuite class SortingTest extends AnyFunSuite { import Sorting._ val someKey = "someKey" val otherKey = "otherKey" test("docKey tests") { val someDocKey = DocKey(someKey, BsonCodec.string) val otherDocKey = DocKey(otherKey, BsonCodec.int32) assert(someDocKey.ascending === Sorts.ascending(someKey)) assert(someDocKey.descending === Sorts.descending(someKey)) assert(someDocKey.metaTextScore === Sorts.metaTextScore(someKey)) assert(ascending(someDocKey, otherDocKey) === Sorts.ascending(someKey, otherKey)) assert(descending(someDocKey, otherDocKey) === Sorts.descending(someKey, otherKey)) assert(orderBy(someDocKey.ascending, otherDocKey.descending) === Sorts.orderBy(Sorts.ascending(someKey), Sorts.descending(otherKey))) } test("bsonRef tests") { val someRef = BsonRef(someKey, GenCodec.StringCodec, null) val otherRef = BsonRef(otherKey, GenCodec.IntCodec, null) assert(someRef.ascending === Sorts.ascending(someKey)) assert(someRef.descending === Sorts.descending(someKey)) assert(someRef.metaTextScore === Sorts.metaTextScore(someKey)) assert(ascending(someRef, otherRef) === Sorts.ascending(someKey, otherKey)) assert(descending(someRef, otherRef) === Sorts.descending(someKey, otherKey)) assert(orderBy(someRef.ascending, otherRef.descending) === Sorts.orderBy(Sorts.ascending(someKey), Sorts.descending(otherKey))) } }
Example 130
Source File: FilteringTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package mongo.core.ops import java.util.regex.Pattern import com.avsystem.commons.mongo.BsonRef import com.avsystem.commons.serialization.GenCodec import com.mongodb.client.model.Filters import org.bson.BsonType import org.bson.conversions.Bson import org.scalatest.funsuite.AnyFunSuite class FilteringTest extends AnyFunSuite { import Filtering._ import FilteringTest._ private def testCase(name: String)(filter: (Ref[String]) => Bson)(verify: (String) => Bson): Unit = { import BsonEquality.bsonEquality test(name) { assert(filter(sRef) === verify("s")) } } private def testValue(name: String)(filter: (Ref[String], String) => Bson)(verify: (String, String) => Bson): Unit = { val someValue = "someValue" testCase(name)(filter(_, someValue))(verify(_, someValue)) } testValue("equal")(_ equal _)(Filters.eq) testValue("notEqual")(_ notEqual _)(Filters.ne) testValue("gt")(_ gt _)(Filters.gt) testValue("lt")(_ lt _)(Filters.lt) testValue("gte")(_ gte _)(Filters.gte) testValue("lte")(_ lte _)(Filters.lte) testValue("in")(_ in _)(Filters.in(_, _)) testValue("nin")(_ nin _)(Filters.nin(_, _)) testCase("exists")(_.exists())(Filters.exists) testCase("notExists")(_.exists(false))(Filters.exists(_, false)) testCase("ofType")(_.ofType("someTypeName"))(Filters.`type`(_, "someTypeName")) testCase("ofTypeEnum")(_.ofType(BsonType.STRING))(Filters.`type`(_, BsonType.STRING)) testCase("mod")(_.mod(313, 131))(Filters.mod(_, 313, 131)) private val regexString = "\\d" private val regexScala = regexString.r private val regexJava = Pattern.compile(regexString) testCase("regexScala")(_ regex regexScala)(Filters.regex(_, regexString)) testCase("regexJava")(_ regex regexJava)(Filters.regex(_, regexJava)) testCase("regexString")(_ regex regexString)(Filters.regex(_, regexString)) testCase("regexOptions")(_.regex(regexString, "ops"))(Filters.regex(_, regexString, "ops")) import BsonEquality.bsonEquality test("contains") { assert(aRef.contains("elem") === Filters.eq("a", "elem")) } private val simpleFilter = Filters.eq("key", "value") test("elemMatch") { assert(aRef.elemMatch(simpleFilter) === Filters.elemMatch("a", simpleFilter)) } test("size") { assert(aRef.size(131) === Filters.size("a", 131)) } test("all") { assert(aRef.all("e1", "e2") === Filters.all("a", "e1", "e2")) } private val otherFilter = Filters.eq("key2", "value2") test("and") { assert(and(simpleFilter, otherFilter) === Filters.and(simpleFilter, otherFilter)) } test("or") { assert(or(simpleFilter, otherFilter) === Filters.or(simpleFilter, otherFilter)) } test("nor") { assert(nor(simpleFilter, otherFilter) === Filters.nor(simpleFilter, otherFilter)) } test("not") { assert(not(simpleFilter) === Filters.not(simpleFilter)) } } object FilteringTest extends BsonRef.Creator[SomeEntity] { implicit val codec: GenCodec[SomeEntity] = GenCodec.materialize val sRef: Ref[String] = ref(_.s) val aRef: Ref[List[String]] = ref(_.a) }
Example 131
Source File: HoconBeanDefinitionReaderTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package spring import java.{util => ju} import com.typesafe.config.{Config, ConfigFactory} import org.scalatest.funsuite.AnyFunSuite import org.springframework.beans.factory.support.DefaultListableBeanFactory import org.springframework.context.support.GenericApplicationContext import scala.beans.BeanProperty class TestBean(val constrInt: Int = 1, val constrString: String = "constrDefault") { @BeanProperty var int: Int = _ @BeanProperty var string: String = _ @BeanProperty var strIntMap: ju.Map[String, Int] = _ @BeanProperty var strList: ju.List[String] = _ @BeanProperty var strSet: ju.Set[String] = _ @BeanProperty var nestedBean: TestBean = _ @BeanProperty var config: Config = _ } object TestBean { def create(theInt: Int = -1, theString: String = "factoryDefault"): TestBean = new TestBean(theInt, theString) } class HoconBeanDefinitionReaderTest extends AnyFunSuite { def createContext(resource: String): GenericApplicationContext = { val pnd = new ScalaParameterNameDiscoverer val beanFactory = new DefaultListableBeanFactory beanFactory.setParameterNameDiscoverer(pnd) val ctx = new GenericApplicationContext(beanFactory) ctx.addBeanFactoryPostProcessor(new ScalaDefaultValuesInjector) val rdr = new HoconBeanDefinitionReader(ctx) rdr.loadBeanDefinitions(resource) ctx.refresh() ctx } test("hocon bean definition reader should work") { val ctx = createContext("testBean.conf") val testBean = ctx.getBean("testBean", classOf[TestBean]) assert(42 == testBean.constrInt) assert("lolzsy" == testBean.constrString) assert(5 == testBean.int) assert("lol" == testBean.string) assert(Map("fuu" -> 42).asJava == testBean.strIntMap) assert(List("a", "b").asJava == testBean.strList) assert(Set("A", "B").asJava == testBean.strSet) assert(6 == testBean.nestedBean.int) assert(1 == testBean.nestedBean.constrInt) assert("wut" == testBean.nestedBean.constrString) assert(2 == testBean.nestedBean.nestedBean.constrInt) assert("yes" == testBean.nestedBean.nestedBean.constrString) assert(ConfigFactory.parseString("srsly = dafuq") == testBean.config) val testBeanDefInt = ctx.getBean("testBeanDefInt", classOf[TestBean]) assert(testBeanDefInt.constrInt == 1) assert(testBeanDefInt.constrString == "constrNonDefault") val testBeanDefString = ctx.getBean("testBeanDefString", classOf[TestBean]) assert(testBeanDefString.constrInt == 2) assert(testBeanDefString.constrString == "constrDefault") val testBeanDefAll = ctx.getBean("testBeanDefAll", classOf[TestBean]) assert(testBeanDefAll.constrInt == 1) assert(testBeanDefAll.constrString == "constrDefault") val testBeanFMDefInt = ctx.getBean("testBeanFMDefInt", classOf[TestBean]) assert(testBeanFMDefInt.constrInt == -1) assert(testBeanFMDefInt.constrString == "factoryNonDefault") val testBeanFMDefString = ctx.getBean("testBeanFMDefString", classOf[TestBean]) assert(testBeanFMDefString.constrInt == -2) assert(testBeanFMDefString.constrString == "factoryDefault") val testBeanFMDefAll = ctx.getBean("testBeanFMDefAll", classOf[TestBean]) assert(testBeanFMDefAll.constrInt == -1) assert(testBeanFMDefAll.constrString == "factoryDefault") } }
Example 132
Source File: HFloatTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization.cbor import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite class HFloatTest extends AnyFunSuite { def testConv(name: String)(floatBits: Int, hfloatBits: Int, roundedBits: Int)(implicit pos: Position): Unit = { val float = java.lang.Float.intBitsToFloat(floatBits) test(name) { val hfloat = HFloat.fromFloat(float) assert(hfloat.raw.toHexString == hfloatBits.toShort.toHexString) assert(java.lang.Float.floatToIntBits(hfloat.toFloat).toHexString == roundedBits.toHexString) } } private def mkHFloat(exponent: Int, significand: Int): Int = ((exponent + 15) << 10) | significand private def mkFloat(exponent: Int, significand: Int): Int = ((exponent + 127) << 23) | significand testConv("zero")(0x00000000, 0x0000, 0x00000000) testConv("-zero")(0x80000000, 0x8000, 0x80000000) testConv("Inf")(0x7F800000, 0x7C00, 0x7F800000) testConv("-Inf")(0xFF800000, 0xFC00, 0xFF800000) testConv("1.0")(mkFloat(0, 0), mkHFloat(0, 0), mkFloat(0, 0)) testConv("2.0")(mkFloat(1, 0), mkHFloat(1, 0), mkFloat(1, 0)) testConv("very small float")(0x00000001, 0x0000, 0x00000000) testConv("rounding down")(mkFloat(0, 0xFFF), mkHFloat(0, 0), mkFloat(0, 0)) testConv("rounding up")(mkFloat(0, 0x1000), mkHFloat(0, 0x1), mkFloat(0, 0x2000)) testConv("rounding up exponent")(mkFloat(0, 0x7FFF000), mkHFloat(1, 0), mkFloat(1, 0)) testConv("subnormal")(mkFloat(-15, 0), mkHFloat(-15, 0x200), mkFloat(-15, 0)) testConv("subnormal with rounding")(mkFloat(-16, 0x7FE000), mkHFloat(-15, 0x200), mkFloat(-15, 0)) testConv("subnormal with exp rounding")(mkFloat(-15, 0x7FE000), mkHFloat(-14, 0), mkFloat(-14, 0)) }
Example 133
Source File: GenCodecErrorsTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization import com.avsystem.commons.serialization.GenCodec.{ReadFailure, WriteFailure} import org.scalatest.funsuite.AnyFunSuite import scala.collection.immutable.ListMap case class Inner(int: Int) object Inner extends HasGenCodec[Inner] class Unwritable object Unwritable { implicit val codec: GenCodec[Unwritable] = GenCodec.create( _ => throw new ReadFailure("cannot"), (_, _) => throw new WriteFailure("cannot") ) } sealed trait Base case class Outer(inner: Inner) extends Base case class Other(unwritable: Unwritable) extends Base object Base extends HasGenCodec[Base] class GenCodecErrorsTest extends AnyFunSuite { def causeChain(t: Throwable): List[Throwable] = if (t == null) Nil else t :: causeChain(t.getCause) test("deep reading failure test") { val failure = intercept[ReadFailure] { SimpleValueInput.read[Base](ListMap("Outer" -> ListMap("inner" -> ListMap("int" -> "NOT INT")))) } assert(causeChain(failure).size == 4) } test("deep writing failure test") { val failure = intercept[WriteFailure] { SimpleValueOutput.write[Base](Other(new Unwritable)) } assert(causeChain(failure).size == 3) } }
Example 134
Source File: IsoInstantTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization import com.avsystem.commons.serialization.GenCodec.ReadFailure import org.scalacheck.Gen import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class IsoInstantTest extends AnyFunSuite with ScalaCheckPropertyChecks { test("basic parsing") { assert(IsoInstant.parse("1970-01-01T00:00:00Z") == 0) assert(IsoInstant.parse("1970-01-01T00:00:00.000Z") == 0) intercept[ReadFailure](IsoInstant.parse("1970-01-01T00:00:00")) intercept[ReadFailure](IsoInstant.parse("1970-01-01")) intercept[ReadFailure](IsoInstant.parse("1970-13-01T00:00:00Z")) intercept[ReadFailure](IsoInstant.parse("1970-01-32T00:00:00Z")) intercept[ReadFailure](IsoInstant.parse("1970-01-01T25:00:00Z")) intercept[ReadFailure](IsoInstant.parse("1970-01-01T00:61:00Z")) intercept[ReadFailure](IsoInstant.parse("1970-01-01T00:00:61Z")) } test("basic formatting") { assert(IsoInstant.format(0) == "1970-01-01T00:00:00.000Z") assert(IsoInstant.format(1) == "1970-01-01T00:00:00.001Z") } test("roundtrip") { val genTstamp = Gen.choose[Long](-(1L << 50), 1L << 50) forAll(genTstamp) { l: Long => assert(IsoInstant.parse(IsoInstant.format(l)) == l) } } }
Example 135
Source File: ObjectSizeTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization import org.scalatest.funsuite.AnyFunSuite case class RecordWithDefaults( @transientDefault a: String = "", b: Int = 42 ) { @generated def c: String = s"$a-$b" } object RecordWithDefaults extends HasApplyUnapplyCodec[RecordWithDefaults] class CustomRecordWithDefaults(val a: String, val b: Int) object CustomRecordWithDefaults extends HasApplyUnapplyCodec[CustomRecordWithDefaults] { def apply(@transientDefault a: String = "", b: Int = 42): CustomRecordWithDefaults = new CustomRecordWithDefaults(a, b) def unapply(crwd: CustomRecordWithDefaults): Opt[(String, Int)] = Opt((crwd.a, crwd.b)) } class CustomWrapper(val a: String) object CustomWrapper extends HasApplyUnapplyCodec[CustomWrapper] { def apply(@transientDefault a: String = ""): CustomWrapper = new CustomWrapper(a) def unapply(cw: CustomWrapper): Opt[String] = Opt(cw.a) } class ObjectSizeTest extends AnyFunSuite { test("computing object size") { assert(RecordWithDefaults.codec.size(RecordWithDefaults()) == 2) assert(RecordWithDefaults.codec.size(RecordWithDefaults("fuu")) == 3) assert(CustomRecordWithDefaults.codec.size(CustomRecordWithDefaults()) == 1) assert(CustomRecordWithDefaults.codec.size(CustomRecordWithDefaults("fuu")) == 2) assert(CustomWrapper.codec.size(CustomWrapper()) == 0) assert(CustomWrapper.codec.size(CustomWrapper("fuu")) == 1) } }
Example 136
Source File: AbstractCodecTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite trait AbstractCodecTest extends AnyFunSuite { def assertSameTypeValue[T](v1: T, v2: T)(implicit pos: Position): Unit = { assert(v1 == v2) assert(v1 == null || v1.getClass == v2.getClass) } type Raw def writeToOutput(write: Output => Unit): Raw def createInput(raw: Raw): Input def testWrite[T: GenCodec](value: T, expectedRepr: Raw)(implicit pos: Position): Unit = { val repr = writeToOutput(GenCodec.write[T](_, value)) assert(repr == expectedRepr) } def testRead[T: GenCodec](repr: Raw, expected: T)(implicit pos: Position): Unit = { assert(expected == GenCodec.read[T](createInput(repr))) } def testRoundtrip[T: GenCodec](value: T)(implicit pos: Position): Unit = { val written: Raw = writeToOutput(GenCodec.write[T](_, value)) val readBack = GenCodec.read[T](createInput(written)) assertSameTypeValue(value, readBack) } }
Example 137
Source File: GenRefTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization import org.scalatest.funsuite.AnyFunSuite @flatten sealed trait Seal { def id: String } case class Klass(@name("_id") id: String) extends Seal case object Objekt extends Seal { @generated @name("_id") def id: String = "O" } case class Bottom(mapa: Map[String, Int]) case class Middle(@name("bot") bottom: Bottom) case class Toplevel(middle: Opt[Middle], seal: Seal = Objekt) @transparent case class TransparentToplevel(toplevel: Toplevel) case class CodecRef[S, T](ref: GenRef[S, T])(implicit targetCodec: GenCodec[T]) class GenRefTest extends AnyFunSuite { test("simple raw ref") { val path = RawRef.create[TransparentToplevel].ref(_.toplevel.middle.get.bottom.mapa("str")).normalize.toList assert(path == List("middle", "bot", "mapa", "str").map(RawRef.Field)) } test("simple gen ref") { val ref = GenRef.create[TransparentToplevel].ref(_.toplevel.middle.get.bottom.mapa("str")) val obj = TransparentToplevel(Toplevel(Middle(Bottom(Map("str" -> 42))).opt)) assert(ref(obj) == 42) } test("gen ref composition") { val subRef = GenRef.create[TransparentToplevel].ref(_.toplevel.middle.get) val ref1 = subRef andThen GenRef.create[Middle].ref(_.bottom.mapa("str")) val ref2 = subRef andThen GenRef.create[Middle].ref(_.bottom.mapa("str")) val obj = TransparentToplevel(Toplevel(Middle(Bottom(Map("str" -> 42))).opt)) assert(ref1(obj) == 42) assert(ref1.rawRef.normalize.toList == List("middle", "bot", "mapa", "str").map(RawRef.Field)) assert(ref2(obj) == 42) assert(ref2.rawRef.normalize.toList == List("middle", "bot", "mapa", "str").map(RawRef.Field)) } test("gen ref implicits test") { import GenRef.Implicits._ val codecRef = CodecRef((_: TransparentToplevel).toplevel.middle.get.bottom.mapa("str")) val obj = TransparentToplevel(Toplevel(Middle(Bottom(Map("str" -> 42))).opt)) assert(codecRef.ref(obj) == 42) } test("sealed trait common field test") { val ref = GenRef.create[Toplevel].ref(_.seal.id) assert(ref.rawRef.normalize.toList == List("seal", "_id").map(RawRef.Field)) } }
Example 138
Source File: AdtTaggingTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package meta import com.avsystem.commons.rpc.{RpcTag, caseTag, paramTag, tagged} import org.scalatest.funsuite.AnyFunSuite class AdtTaggingTest extends AnyFunSuite { sealed trait AdtTag extends RpcTag class Good extends AdtTag class Bad extends AdtTag case class Info[T]( @reifyName name: String ) extends TypedMetadata[T] @paramTag[AdtTag](new Good) case class AdtClassInfo[T]( @multi @tagged[Good] @adtParamMetadata goodParams: List[Info[_]], @multi @tagged[Bad] @adtParamMetadata badParams: List[Info[_]] ) extends TypedMetadata[T] { def goodNames: List[String] = goodParams.map(_.name) def badNames: List[String] = badParams.map(_.name) } object AdtClassInfo extends AdtMetadataCompanion[AdtClassInfo] @caseTag[AdtTag](new Good) case class AdtHierarchyInfo[T]( @multi @tagged[Good] @adtCaseMetadata goodCases: List[Info[_]], @multi @tagged[Bad] @adtCaseMetadata badCases: List[Info[_]] ) extends TypedMetadata[T] { def goodNames: List[String] = goodCases.map(_.name) def badNames: List[String] = badCases.map(_.name) } object AdtHierarchyInfo extends AdtMetadataCompanion[AdtHierarchyInfo] case class Klass(good: Int, @Bad bad: String, @Good alsoGood: String) test("adt param tagging") { val klassInfo = AdtClassInfo.materialize[Klass] assert(klassInfo.goodNames == List("good", "alsoGood")) assert(klassInfo.badNames == List("bad")) } sealed trait Hierarchy class GoodCase extends Hierarchy @Bad class BadCase extends Hierarchy @Good class AlsoGoodCase extends Hierarchy test("adt case tagging") { val hierarchyInfo = AdtHierarchyInfo.materialize[Hierarchy] assert(hierarchyInfo.goodNames == List("GoodCase", "AlsoGoodCase")) assert(hierarchyInfo.badNames == List("BadCase")) } }
Example 139
Source File: GenericMetadataTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package rpc import com.avsystem.commons.meta._ import com.avsystem.commons.misc.TypeString import org.scalatest.funsuite.AnyFunSuite class GenericMeta[T]( @reifyName name: String, @multi @rpcTypeParamMetadata typeParams: List[GenericMeta.TypeParam], @multi @rpcMethodMetadata methods: List[GenericMeta.Method[_]] ) { def repr: String = { val targs = typeParams.map(_.typeString) s"$name${GenericMeta.tparams(typeParams)} {\n ${methods.iterator.map(_.repr(targs)).mkString("\n ")}\n}" } } object GenericMeta extends RpcMetadataCompanion[GenericMeta] { case class TypeParam(@reifyName name: String) { def typeString: TypeString[_] = new TypeString(name) } case class Param[T]( @reifyName name: String, @infer @forTypeParams tpe: List[TypeString[_]] => TypeString[T] ) extends TypedMetadata[T] { def repr(targs: List[TypeString[_]]): String = s"$name: ${tpe(targs)}" } case class Method[T]( @reifyName name: String, @multi @rpcTypeParamMetadata typeParams: List[TypeParam], @multi @rpcParamMetadata params: List[Param[_]], @infer @forTypeParams result: List[TypeString[_]] => TypeString[T] ) extends TypedMetadata[T] { def repr(targs: List[TypeString[_]]): String = { val fullTargs = targs ++ typeParams.map(_.typeString) val paramsRepr = params.iterator.map(_.repr(fullTargs)).mkStringOrEmpty("(", ", ", ")") s"$name${tparams(typeParams)}$paramsRepr: ${result(fullTargs)}" } } def tparams(typeParams: List[TypeParam]): String = typeParams.iterator.map(_.name).mkStringOrEmpty("[", ", ", "]") } trait GenericTrait[A, B] { def method(a: A, int: Int): List[A] def genericMethod[C](map: Map[A, C]): Map[B, C] } object GenericTrait { implicit val meta: GenericMeta[GenericTrait[_, _]] = GenericMeta.materialize } class GenericMetadataTest extends AnyFunSuite { test("generic metadata") { assert(GenericTrait.meta.repr == """GenericTrait[A, B] { | method(a: A, int: Int): List[A] | genericMethod[C](map: Map[A, C]): Map[B, C] |}""".stripMargin) } }
Example 140
Source File: MangleOverloadsTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package rpc import com.avsystem.commons.meta.multi import org.scalatest.funsuite.AnyFunSuite trait MangleOverloadsRaw { @multi @mangleOverloads def select(@methodName name: String, @multi args: List[Int]): String } object MangleOverloadsRaw extends RawRpcCompanion[MangleOverloadsRaw] trait Overloads { def one: String def one(i: Int): String def two: String def two(i: Int): String def two(i: Int, j: Int): String } object Overloads { implicit val asRawReal: AsRawReal[MangleOverloadsRaw, Overloads] = MangleOverloadsRaw.materializeAsRawReal } class MangleOverloadsTest extends AnyFunSuite { test("overload mangling") { val raw = new MangleOverloadsRaw { def select(name: String, args: List[Int]): String = args.mkString(name + "(", ",", ")") } val real = MangleOverloadsRaw.asReal[Overloads](raw) assert(real.one == "one()") assert(real.one(42) == "one_1(42)") assert(real.two == "two()") assert(real.two(42) == "two_1(42)") assert(real.two(42, 13) == "two_2(42,13)") } }
Example 141
Source File: RPCMetadataTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package rpc import com.avsystem.commons.misc.TypeString import com.avsystem.commons.rpc.DummyRPC._ import com.avsystem.commons.serialization.GenCodec import org.scalatest.funsuite.AnyFunSuite class RPCMetadataTest extends AnyFunSuite { case class Annot(str: String) extends MetadataAnnotation @Annot("on base class") trait Base[T] { def genproc(p: T): Unit @Annot("on base method") def proc(@Annot("on base param") p: String): Unit @rpcName("function") def func[A](a: A)(implicit @encodingDependency tag: Tag[A]): Future[A] } object Base { implicit def codecFromTag[T: Tag]: GenCodec[T] = Tag[T].codec implicit def asRawReal[T: GenCodec]: AsRawRealRPC[Base[T]] = RawRPC.materializeAsRawReal implicit def metadata[T: TypeString]: RPCMetadata[Base[T]] = RPCMetadata.materialize } @Annot("on subclass") trait Sub extends Base[String] { @Annot("on submethod") def proc(@Annot("on subparam") param: String): Unit def getter(i: Int)(s: String): Base[String] def selfGetter: Sub } object Sub extends RPCCompanion[Sub] test("RPC metadata should be correct") { val m = Sub.metadata assert(m.name == "Sub") assert(m.annotations == List(Annot("on subclass"), Annot("on base class"))) assert(m.procedureSignatures.keySet == Set("proc", "genproc")) assert(m.functionSignatures.keySet == Set("function")) assert(m.getterSignatures.keySet == Set("getter", "selfGetter")) assert(m.procedureSignatures("proc") == ProcedureSignature("proc", List( ParamMetadata("param", List(Annot("on subparam"), Annot("on base param")), new TypeString("String")) ), List(Annot("on submethod"), Annot("on base method")) )) assert(m.procedureSignatures("genproc") == ProcedureSignature("genproc", List( ParamMetadata("p", Nil, new TypeString("String")) ), Nil)) m.functionSignatures("function") uncheckedMatch { case FunctionSignature("func", List(TypeParamMetadata("A")), List(apm, tagpm), Nil, resTnFun) => assert(resTnFun(List(classTag[String])) == classTag[String]) apm uncheckedMatch { case GenericParamMetadata("a", Nil, tnFun) => assert(tnFun(List(new TypeString("AAA"))) == new TypeString("AAA")) } tagpm uncheckedMatch { case GenericParamMetadata("tag", Nil, tnFun) => assert(tnFun(List(new TypeString("AAA"))) == new TypeString("com.avsystem.commons.rpc.Tag[AAA]")) } } val resultMetadata = m.getterSignatures("getter").resultMetadata.value assert(resultMetadata.annotations == List(Annot("on base class"))) assert(resultMetadata.procedureSignatures.keySet == Set("proc", "genproc")) assert(resultMetadata.functionSignatures.keySet == Set("function")) assert(resultMetadata.getterSignatures.keySet == Set()) assert(resultMetadata.procedureSignatures("proc") == ProcedureSignature("proc", List( ParamMetadata("p", List(Annot("on base param")), new TypeString("String")) ), List(Annot("on base method")))) assert(m.procedureSignatures("genproc") == ProcedureSignature("genproc", List( ParamMetadata("p", Nil, new TypeString("String")) ), Nil)) } }
Example 142
Source File: JavaClassNameTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package macros import com.avsystem.commons.misc.{JavaClassName, TypeString} import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite object JavaClassNameTest { class Inner { class MoreInner { class SuperInner } } object Inner { class EvenInner object EvenInner } } class JavaClassNameTest extends AnyFunSuite { def test[T: ClassTag : JavaClassName : TypeString](implicit pos: Position): Unit = test(TypeString.of[T])(assert(JavaClassName.of[T] == classTag[T].runtimeClass.getName)) test[Any] test[AnyRef] test[AnyVal] test[Unit] test[Boolean] test[Char] test[Byte] test[Short] test[Int] test[Long] test[Float] test[Double] test[String] test[Nothing] test[Array[Boolean]] test[Array[Char]] test[Array[Byte]] test[Array[Short]] test[Array[Int]] test[Array[Long]] test[Array[Float]] test[Array[Double]] test[Array[String]] test[Array[Nothing]] test[JavaClassNameTest] test[JavaClassNameTest.type] test[JavaClassNameTest.Inner] test[JavaClassNameTest.Inner#MoreInner] test[JavaClassNameTest.Inner#MoreInner#SuperInner] test[JavaClassNameTest.Inner.type] test[JavaClassNameTest.Inner.EvenInner] test[JavaClassNameTest.Inner.EvenInner.type] }
Example 143
Source File: AnnotationOfTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import com.avsystem.commons.annotation.AnnotationAggregate import org.scalatest.funsuite.AnyFunSuite case class genann[T](value: T) extends StaticAnnotation case class genagg[T](value: T) extends AnnotationAggregate { @genann(value) final def aggregated: List[StaticAnnotation] = reifyAggregated } @genagg(42) class Subject abstract class SelfAnnots(implicit val annots: SelfAnnotations[genann[_]]) @genagg(42) @genann("fuu") class Klass extends SelfAnnots @genagg(42) @genann("fuu") object Objekt extends SelfAnnots class AnnotationOfTest extends AnyFunSuite { test("aggregate with generic") { assert(AnnotationOf.materialize[genann[Int], Subject].annot.value == 42) } test("self annotations") { assert(new Klass().annots.annots == List(genann(42), genann("fuu"))) assert(Objekt.annots.annots == List(genann(42), genann("fuu"))) } }
Example 144
Source File: SealedEnumTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import org.scalatest.funsuite.AnyFunSuite class SealedEnumTest extends AnyFunSuite { sealed abstract class SomeEnum(implicit val sourceInfo: SourceInfo) extends OrderedEnum object SomeEnum extends SealedEnumCompanion[SomeEnum] { case object First extends SomeEnum case object Second extends SomeEnum case object Third extends SomeEnum case object Fourth extends SomeEnum val values: List[SomeEnum] = caseObjects val classTags: List[ClassTag[_ <: SomeEnum]] = SealedUtils.instancesFor[ClassTag, SomeEnum] } test("case objects listing") { import SomeEnum._ assert(values == List(First, Second, Third, Fourth)) } test("typeclass instance listing") { import SomeEnum._ assert(classTags.map(_.runtimeClass) == List(First.getClass, Second.getClass, Third.getClass, Fourth.getClass)) } }
Example 145
Source File: OptRefTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import com.avsystem.commons.JInteger import org.scalatest.funsuite.AnyFunSuite class OptRefTest extends AnyFunSuite { test("nonempty test") { val opt = OptRef("lol") opt match { case OptRef(str) => assert(str == "lol") } } test("empty test") { val str: String = null val opt = OptRef(str) opt match { case OptRef.Empty => } } test("null some test") { intercept[NullPointerException](OptRef.some[String](null)) } test("unboxing matching test") { val opt = OptRef[JInteger](42) opt match { case OptRef.Boxed(num) => assert(num == 42) } } test("zip") { assert(OptRef(3).zip(OptRef(2)) == OptRef((3, 2))) assert(OptRef.Empty.zip(OptRef(2)) == OptRef.Empty) assert(OptRef(3).zip(OptRef.Empty) == OptRef.Empty) } }
Example 146
Source File: ValueEnumTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import org.scalatest.funsuite.AnyFunSuite class ValueEnumTest extends AnyFunSuite { class SomeValueEnum(implicit enumCtx: EnumCtx) extends AbstractValueEnum object SomeValueEnum extends AbstractValueEnumCompanion[SomeValueEnum] { final val One, Two, Three: Value = new SomeValueEnum final val Four: Value = new SomeValueEnum {} final val Five_? : Value = new SomeValueEnum } test("value enum test") { import SomeValueEnum._ assert(values == List(One, Two, Three, Four, Five_?)) assert(values.map(_.ordinal) == List.range(0, 5)) assert(values.map(_.name) == List("One", "Two", "Three", "Four", "Five_?")) } test("enum constant member validation") { assertCompiles( """ |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | final val Constant: Value = new Enumz |} """.stripMargin ) assertDoesNotCompile( """ |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | private final val Constant: Value = new Enumz |} """.stripMargin ) assertDoesNotCompile( """ |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | final def Constant: Value = new Enumz |} """.stripMargin ) assertDoesNotCompile( """ |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | val Constant: Value = new Enumz |} """.stripMargin ) assertDoesNotCompile( """ |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | final lazy val Constant: Value = new Enumz |} """.stripMargin ) assertDoesNotCompile( """ |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | final val Constant = new Enumz |} """.stripMargin ) assertDoesNotCompile( """ |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | object Inner { | final val Constant: Value = new Enumz | } |} """.stripMargin ) } }
Example 147
Source File: ApplierUnapplierTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import com.avsystem.commons import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite case class Empty() case class Single(str: String) case class Multiple(str: String, int: Int) case class Varargs(str: String, ints: Int*) case class Generic[T](str: String, value: T) case class Over22( p01: String = "01", p02: String = "02", p03: String = "03", p04: String = "04", p05: String = "05", p06: String = "06", p07: String = "07", p08: String = "08", p09: String = "09", p10: String = "10", p11: String = "11", p12: String = "12", p13: String = "13", p14: String = "13", p15: String = "15", p16: String = "16", p17: String = "17", p18: String = "18", p19: String = "18", p20: String = "18", p21: String = "21", p22: String = "22", p23: String = "23", p24: String = "24", p25: String = "25" ) class Custom(val str: String, val i: Int) { override def hashCode(): Int = (str, i).hashCode() override def equals(obj: Any): Boolean = obj match { case c: Custom => str == c.str && i == c.i case _ => false } } object Custom { def apply(str: String, i: Int): Custom = new Custom(str, i) def unapply(custom: Custom): commons.Opt[(String, Int)] = Opt((custom.str, custom.i)) } class ApplierUnapplierTest extends AnyFunSuite { def roundtrip[T](value: T)(implicit applier: Applier[T], unapplier: Unapplier[T], applierUnapplier: ApplierUnapplier[T], pos: Position ): Unit = { assert(value == applier(unapplier.unapply(value))) assert(value == applierUnapplier(applierUnapplier.unapply(value))) } test("no params") { roundtrip(Empty()) } test("single param") { roundtrip(Single("")) } test("multiple params") { roundtrip(Multiple("", 42)) } test("varargs") { roundtrip(Varargs("", 1, 2, 3)) } test("generic") { roundtrip(Generic("a", "b")) } test("more than 22 params") { roundtrip(Over22()) } test("custom") { roundtrip(Custom("", 42)) } test("tuple") { roundtrip(("", 42, 3.14)) } }
Example 148
Source File: NOptTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import org.scalatest.funsuite.AnyFunSuite import com.avsystem.commons.JInteger class NOptTest extends AnyFunSuite { test("nonempty test") { val opt = NOpt(23) opt match { case NOpt(num) => assert(num == 23) } } test("empty test") { val str: String = null val opt = NOpt(str) opt match { case NOpt.Empty => } } test("null some test") { val str: String = null val opt = NOpt.some(str) opt match { case NOpt(null) => } } test("boxing unboxing test") { val opt: NOpt[Int] = NOpt(42) val boxedNOpt: NOpt[JInteger] = opt.boxed val unboxedNOpt: NOpt[Int] = boxedNOpt.unboxed assert(opt == unboxedNOpt) } test("nesting test") { assert((NOpt(NOpt.empty): Any) match { case NOpt.Empty => false case NOpt(NOpt.Empty) => true }) assert((NOpt.Empty: Any) match { case NOpt(NOpt.Empty) => false case NOpt.Empty => true }) } test("empty hash code") { NOpt.Empty.hashCode } test("collect") { assert(NOpt(3).collect { case 2 => 2 } == NOpt.Empty) assert(NOpt(3).collect { case 3 => 2 } == NOpt.some(2)) assert(NOpt(3).collect { case 3 => null } == NOpt.some(null)) } test("zip") { assert(NOpt(3).zip(NOpt(2)) == NOpt((3, 2))) assert(NOpt.Empty.zip(NOpt(2)) == NOpt.Empty) assert(NOpt(3).zip(NOpt.Empty) == NOpt.Empty) } }
Example 149
Source File: SourceInfoTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class SourceInfoTest extends AnyFunSuite with Matchers { val srcInfo = SourceInfo.here test("simple") { srcInfo should matchPattern { case SourceInfo(_, "SourceInfoTest.scala", 216, 8, 28, " val srcInfo = SourceInfo.here", List("srcInfo", "SourceInfoTest", "misc", "commons", "avsystem", "com")) => } } }
Example 150
Source File: CaseMethodsTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import org.scalatest.funsuite.AnyFunSuite case class Whatever(str: String, int: Int) extends AbstractCase class CaseMethodsTest extends AnyFunSuite { val first = Whatever("lol", 42) val second = Whatever("lol", 42) val other = Whatever("lol", 41) test("equality") { assert(first canEqual second) assert(first == second) assert(first equals second) } test("inequality") { assert(first != other) assert(!(first equals other)) } test("hashCode") { assert(first.hashCode == second.hashCode) assert(first.## == second.##) } test("toString") { assert(first.toString == "Whatever(lol,42)") } }
Example 151
Source File: OptArgTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import com.avsystem.commons.SharedExtensions._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class OptArgTest extends AnyFunSuite with Matchers { test("nonempty") { val opt = OptArg(23) opt match { case OptArg(num) => assert(num == 23) } } test("empty") { val str: String = null val opt = OptArg(str) opt match { case OptArg.Empty => } } test("null some") { intercept[NullPointerException](OptArg.some[String](null)) } def takeMaybeString(str: OptArg[String] = OptArg.Empty): Opt[String] = str.toOpt test("argument passing") { takeMaybeString() shouldEqual Opt.Empty takeMaybeString("stringzor") shouldEqual "stringzor".opt } }
Example 152
Source File: NamedEnumTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class NamedEnumTest extends AnyFunSuite with Matchers { sealed trait SomeNamedEnum extends NamedEnum trait WithName { val name = "I am from withName" } object TopLevel extends SomeNamedEnum { override val name: String = "I am toplvl" } sealed trait AnotherNamedEnum extends NamedEnum { override val name: String = "Another one" } case object Fourth extends AnotherNamedEnum with SomeNamedEnum object SomeNamedEnum extends NamedEnumCompanion[SomeNamedEnum] { case object First extends SomeNamedEnum { override val name: String = "First" } case object Second extends SomeNamedEnum { override lazy val name: String = "Second" } case object Third extends SomeNamedEnum with AnotherNamedEnum { override val name: String = "Third" } case object FromWithName extends SomeNamedEnum with WithName override val values: List[SomeNamedEnum] = caseObjects } object AnotherNamedEnum extends NamedEnumCompanion[AnotherNamedEnum] { override val values: List[AnotherNamedEnum] = caseObjects } test("all possible ways of `name` override") { import SomeNamedEnum._ assert(byName == Map( "First" -> First, "Second" -> Second, "Third" -> Third, "Another one" -> Fourth, "I am toplvl" -> TopLevel, "I am from withName" -> FromWithName )) } test("object in two hierarchies") { SomeNamedEnum.byName.get("Another one") should contain(Fourth) AnotherNamedEnum.byName.get("Another one") should contain(Fourth) } test("object recognized by scope") { SomeNamedEnum.byName.get("Third") should contain(SomeNamedEnum.Third) AnotherNamedEnum.byName.get("Third") should contain(SomeNamedEnum.Third) } test("top level objects") { assert(SomeNamedEnum.byName.contains("I am toplvl")) } }
Example 153
Source File: DelegationTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import org.scalatest.funsuite.AnyFunSuite class DelegationTest extends AnyFunSuite { trait Destination[T] { val te: T def simple(omg: Int): String def meth[C[+X] >: Null <: Iterable[X]](map: Map[T, C[String]]): C[(T, String)] def multi(a: String)(b: String): String def vararg(values: String*): String } class Source { val te: Double = 3.14 def simple(omg: Int): String = omg.toString def meth[C[+X] >: Null <: Iterable[X]](map: Map[Double, C[String]]): C[(Double, String)] = null def multi(a: String)(b: String): String = a + b def vararg(values: String*): String = values.mkString("") } test("simple test") { val source = new Source val destination = Delegation[Destination[Double]](source) assert(source.te == destination.te) assert(source.simple(42) == destination.simple(42)) assert(source.meth[List](Map.empty) == destination.meth[List](Map.empty)) assert(source.multi("4")("2") == destination.multi("4")("2")) assert(source.vararg("4", "2") == destination.vararg("4", "2")) } }
Example 154
Source File: SharedExtensionsPropertyTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import com.avsystem.commons.SharedExtensions._ import org.scalacheck.{Gen, Shrink} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class SharedExtensionsPropertyTest extends AnyFunSuite with Matchers with ScalaCheckDrivenPropertyChecks { implicit def shrinkNonEmpty[C[_] <: Iterable[_], T](implicit base: Shrink[C[T]]): Shrink[C[T]] = Shrink(base.shrink(_).filter(_.nonEmpty)) private val elementGen = Gen.alphaChar private val listGen = Gen.listOf(elementGen) private val listWithElementGen = for { list <- Gen.nonEmptyListOf(elementGen) elem <- Gen.oneOf(list) } yield (list, elem) test("indexOfOpt(elem) should return Opt.Empty if the element does not occur in the list") { forAll(listGen, elementGen) { (elemList, element) => elemList.filterNot(_ == element).indexOfOpt(element) shouldEqual Opt.Empty } } test("indexOfOpt(elem) should not return Opt.Empty when the element occurs in the list") { forAll(listWithElementGen) { case (elemList, elem) => elemList.indexOfOpt(elem) should not equal Opt.Empty } } test("indexOfOpt(elem).getOrElse(-1) should behave identically to indexOf(elem)") { forAll(listGen, elementGen) { (elemList, element) => elemList.indexOf(element) shouldEqual elemList.indexOfOpt(element).getOrElse(-1) } } test("indexWhereOpt(elem).getOrElse(-1) should behave identically to indexWhere(elem)") { forAll(listGen, elementGen) { (elemList, element) => elemList.indexWhere(_ == element) shouldEqual elemList.indexWhereOpt(_ == element).getOrElse(-1) } } }
Example 155
Source File: OptTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import com.avsystem.commons import org.scalatest.funsuite.AnyFunSuite import com.avsystem.commons.JInteger class OptTest extends AnyFunSuite { test("nonempty test") { val opt = Opt(23) opt match { case Opt(num) => assert(num == 23) } } test("empty test") { val str: String = null val opt = Opt(str) opt match { case Opt.Empty => } } test("null some test") { intercept[NullPointerException](Opt.some[String](null)) } test("boxing unboxing test") { val opt: Opt[Int] = Opt(42) val boxedOpt: Opt[JInteger] = opt.boxed val unboxedOpt: Opt[Int] = boxedOpt.unboxed assert(opt == unboxedOpt) } test("nesting test") { assert((Opt(Opt.empty): Any) match { case Opt.Empty => false case Opt(Opt.Empty) => true }) assert((Opt.Empty: Any) match { case Opt(Opt.Empty) => false case Opt.Empty => true }) } test("empty hash code") { Opt.Empty.hashCode } test("orNull") { assert((Opt.Empty.orNull: Any) == null) assert(Opt("").orNull == "") } test("collect") { assert(Opt(3).collect { case 3 => 2 } == Opt(2)) assert(Opt(3).collect { case 2 => 2 } == Opt.Empty) assert(Opt(3).collect { case 3 => null } == Opt.Empty) } test("zip") { assert(Opt(3).zip(Opt(2)) == Opt((3, 2))) assert(Opt.Empty.zip(Opt(2)) == Opt.Empty) assert(Opt(3).zip(Opt.Empty) == Opt.Empty) } test("mapOr") { val seq: Seq[Int] = Opt(5).mapOr(Nil, i => 0 until i) assert(seq == (0 until 5)) } }
Example 156
Source File: ValueOfTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package misc import org.scalatest.funsuite.AnyFunSuite object Obj { val x: String = "fuu" class Inner { val x: String = "fuu" def valueOfX: x.type = ValueOf[x.type] def valueOfThis: this.type = ValueOf[this.type] } } class ValueOfTest extends AnyFunSuite { test("object") { assert(ValueOf[Obj.type] == Obj) } test("static val") { assert(ValueOf[Obj.x.type] == Obj.x) } test("inner val of local") { val i = new Obj.Inner assert(ValueOf[i.x.type] == i.x) assert(i.valueOfX == i.x) } test("this") { val i = new Obj.Inner assert(i.valueOfThis == i) } }
Example 157
Source File: MutableStackTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package collection import org.scalatest.funsuite.AnyFunSuite class MutableStackTest extends AnyFunSuite { test("push") { val stack = new MutableStack[String] stack.push("lol1") stack.push("lol2") stack.push("lol3") assert(stack.asList == List("lol3", "lol2", "lol1")) } test("pushAll") { val stack = new MutableStack[String] stack.pushAll(List("lol1", "lol2", "lol3")) assert(stack.asList == List("lol3", "lol2", "lol1")) } test("pop") { val stack = new MutableStack[String] assertThrows[NoSuchElementException](stack.pop()) assert(stack.popOpt().isEmpty) assert(stack.popOption().isEmpty) stack.push("lol") assert(stack.pop() == "lol") assert(stack.isEmpty) stack.push("lol") assert(stack.popOpt() == Opt("lol")) assert(stack.isEmpty) stack.push("lol") assert(stack.popOption().contains("lol")) assert(stack.isEmpty) } test("top") { val stack = new MutableStack[String] assertThrows[NoSuchElementException](stack.top) assert(stack.topOpt.isEmpty) assert(stack.topOption.isEmpty) stack.push("lol") assert(stack.top == "lol") assert(stack.topOpt.contains("lol")) assert(stack.topOption.contains("lol")) } }
Example 158
Source File: FileBasedSuite.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package testutil import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite abstract class FileBasedSuite(testdir: String) extends AnyFunSuite { def updateTestFiles: Boolean = System.getProperty("updateTestFiles").opt.map(_.toBoolean).contains(true) def separator: String = "-----\n" def testFile(file: String)(process: String => String)(implicit position: Position): Unit = { val path = s"$testdir/$file" val contents = IO.readTestResource(path) val (input, expectedOutput) = contents.indexOf(separator) match { case -1 => (contents, "") case idx => (contents.take(idx), contents.drop(idx + separator.length)) } val output = process(input) if (updateTestFiles && output != expectedOutput) { IO.writeTestResource(path, input + separator + output) } assert(output == expectedOutput) } def assertContents(actual: String, expectedFile: String): Unit = { val filePath = s"$testdir/$expectedFile" val expected = IO.readTestResource(filePath) if (updateTestFiles) { IO.writeTestResource(filePath, actual) } assert(actual == expected) } }
Example 159
Source File: ExplicitGenericsTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class ExplicitGenericsTest extends AnyFunSuite with AnalyzerTest { test("inferred generic should be rejected") { assertErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object whatever { | val x = TestUtils.genericMethod(123) |} """.stripMargin ) } test("inferred generic in macro should be rejected") { assertErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object whatever { | val x = TestUtils.genericMacro(123) |} """.stripMargin ) } test("explicit generic should not be rejected") { assertNoErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object whatever { | val x = TestUtils.genericMethod[Int](123) |} """.stripMargin ) } test("explicit generic in macro should not be rejected") { assertNoErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object whatever { | val x = TestUtils.genericMacro[Int](123) |} """.stripMargin ) } }
Example 160
Source File: ImportJavaUtilTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class ImportJavaUtilTest extends AnyFunSuite with AnalyzerTest { test("import java.util should be rejected") { assertErrors( """ |import java.util | |object whatever """.stripMargin ) } }
Example 161
Source File: CheckMacroPrivateTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class CheckMacroPrivateTest extends AnyFunSuite with AnalyzerTest { test("macro private method invoked directly should be rejected") { assertErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object test { | TestUtils.macroPrivateMethod |} """.stripMargin ) } test("macro private extractor used directly should be rejected") { assertErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object test { | 123 match { | case TestUtils.Extractor(_) => | } |} """.stripMargin ) } test("macro private method invoked by macro-generated code should not be rejected") { assertNoErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object test { | TestUtils.invokeMacroPrivateMethod |} """.stripMargin ) } test("definitions of macro private symbols themselves should not be rejected") { assertNoErrors( """ |import com.avsystem.commons.annotation.macroPrivate | |object test { | @macroPrivate def macroPrivateMethod = { println("whatever"); 5 } | @macroPrivate object macroPrivateObject { | val x = 42 | } |} """.stripMargin ) } }
Example 162
Source File: VarargsAtLeastTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class VarargsAtLeastTest extends AnyFunSuite with AnalyzerTest { test("too few varargs parameters should be rejected") { assertErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object whatever { | TestUtils.need3Params(1, 2) |} """.stripMargin ) } test("enough varargs parameters should not be rejected") { assertNoErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object whatever { | TestUtils.need3Params(1, 2, 3) | TestUtils.need3Params(1, 2, 3, 4) |} """.stripMargin ) } test("collection passed as varargs parameter should not be rejected") { assertNoErrors( """ |import com.avsystem.commons.analyzer.TestUtils | |object whatever { | TestUtils.need3Params(List(1,2): _*) |} """.stripMargin ) } }
Example 163
Source File: CheckBincompatTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class CheckBincompatTest extends AnyFunSuite with AnalyzerTest { test("definitions of @bincompat annotated symbols should not be rejected") { assertNoErrors( """ |import com.avsystem.commons.annotation.bincompat | |@bincompat class klass | |@bincompat object objekt { | @bincompat def method: Int = 42 |} """.stripMargin ) } test("usage of @bincompat annotated symbols should be rejected") { assertErrors(3, """ |import com.avsystem.commons.annotation.bincompat | |@bincompat class klass | |@bincompat object objekt | |object outer { | @bincompat def method: Int = 42 |} | |object test { | println(objekt) | println(new klass) | println(outer.method) |} """.stripMargin ) } }
Example 164
Source File: ThrowableObjectsTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class ThrowableObjectsTest extends AnyFunSuite with AnalyzerTest { test("throwable objects with stack trace should be rejected") { assertErrors(1, """ |object throwableObject extends Throwable |object noStackTraceThrowableObject extends Throwable with scala.util.control.NoStackTrace """.stripMargin) } }
Example 165
Source File: FindUsagesTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class FindUsagesTest extends AnyFunSuite with AnalyzerTest { settings.pluginOptions.value ++= List("AVSystemAnalyzer:+findUsages:java.lang.String") test("java.lang.String usages should be found") { assertErrors(2, """ |object whatever { | val x: String = String.valueOf(123) |} """.stripMargin ) } }
Example 166
Source File: ImplicitTypesTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class ImplicitTypesTest extends AnyFunSuite with AnalyzerTest { ignore("implicit definitions without explicit types should be rejected") { assertErrors(2, """ |object whatever { | implicit val x = 5 | implicit val y: Int = 5 | implicit def conv(x: Int) = x.toString | implicit def conv2(x: Int): String = x.toString | implicit object objekt | implicit class wtf(x: Int) |} """.stripMargin) } }
Example 167
Source File: ValueEnumExhaustiveMatchTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalatest.funsuite.AnyFunSuite class ValueEnumExhaustiveMatchTest extends AnyFunSuite with AnalyzerTest { def source(caseDefs: String): String = s""" |import com.avsystem.commons.misc._ | |final class Enumz(implicit enumCtx: EnumCtx) extends AbstractValueEnum |object Enumz extends AbstractValueEnumCompanion[Enumz] { | final val One, Two, Three: Value = new Enumz |} | |object Main { | val enum: Enumz = Enumz.One | import Enumz._ | enum match { | $caseDefs | } |} """.stripMargin test("should report two unmatched enum values") { assertErrors(source( """ |case Enumz.One => |case null => """.stripMargin )) } test("should report one unmatched enum value") { assertErrors(source( """ |case Enumz.One => |case Enumz.Two => """.stripMargin )) } test("should report one unmatched by alternative enum value") { assertErrors(source( """ |case One | Two => """.stripMargin )) } test("should not report unmatched values on wildcard") { assertNoErrors(source( """ |case _ => """.stripMargin )) } test("should not report unmatched values with guard") { assertNoErrors(source( """ |case x if x.ordinal > 1 => """.stripMargin )) } test("should not report no unmatched values in alternative") { assertNoErrors(source( """ |case One | Two | Three => """.stripMargin )) } test("should not report no unmatched values") { assertNoErrors(source( """ |case Enumz.One => |case Enumz.Two => |case Three => """.stripMargin )) } }
Example 168
Source File: RedisMsgTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package redis.protocol import akka.util.ByteString import com.avsystem.commons.redis.protocol.RedisMsgScalacheck._ import org.scalacheck.Gen import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import scala.collection.immutable.VectorBuilder class RedisMsgTest extends AnyFunSuite with ScalaCheckPropertyChecks { def splitAtIndices(repr: ByteString, indices: Seq[Int]): Seq[ByteString] = (indices :+ repr.length).foldLeft((0, Vector.empty[ByteString])) { case ((prevIdx, acc), nextIdx) => (nextIdx, acc :+ repr.slice(prevIdx, nextIdx)) }._2 test("encoded and then decoded messages should be equal to the original messages") { val gen = for { redisMsgs <- Gen.buildableOf[Seq[RedisMsg], RedisMsg](redisProtocolMsgGen) splitPoints <- Gen.buildableOf[Seq[Double], Double](Gen.choose(0.0, 1.0)) } yield (redisMsgs, splitPoints) forAll(gen) { case (redisMsgs, splitPoints) => val repr = RedisMsg.encode(redisMsgs) val splitIndices = splitPoints.map(sp => (sp * (repr.size - 1)).toInt).toSet.toVector.sorted val encodedParts = splitAtIndices(repr, splitIndices) val decoded = new VectorBuilder[RedisMsg] val decoder = new RedisMsg.Decoder encodedParts.foreach(bs => decoder.decodeMore(bs)(decoded += _)) val decodedMsgs = decoded.result() assert(decodedMsgs == redisMsgs) } } test("encoded size") { forAll(redisProtocolMsgGen) { msg => assert(RedisMsg.encode(msg).length == RedisMsg.encodedSize(msg)) } } test("simple string encode") { assert(RedisMsg.encode(SimpleStringMsg("asdf")).utf8String == "+asdf\r\n") } test("error encode") { assert(RedisMsg.encode(ErrorMsg("asdf")).utf8String == "-asdf\r\n") } test("bulk string encode") { assert(RedisMsg.encode(BulkStringMsg(ByteString("srsly"))).utf8String == "$5\r\nsrsly\r\n") } test("null bulk string encode") { assert(RedisMsg.encode(NullBulkStringMsg).utf8String == "$-1\r\n") } test("array encode") { assert(RedisMsg.encode(ArrayMsg(Vector(IntegerMsg(42), IntegerMsg(43)))).utf8String == "*2\r\n:42\r\n:43\r\n") } test("null array encode") { assert(RedisMsg.encode(NullArrayMsg).utf8String == "*-1\r\n") } test("integer encode") { assert(RedisMsg.encode(IntegerMsg(-1)).utf8String == ":-1\r\n") } }
Example 169
Source File: RedisMasterSlaveClientTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package redis import com.avsystem.commons.redis.exception.MasterSlaveInitializationException import org.scalatest.concurrent.ScalaFutures import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class RedisMasterSlaveClientInitTest extends AnyFunSuite with Matchers with ScalaFutures with UsesActorSystem with UsesPreconfiguredMasterSlave { import RedisApi.Batches.StringTyped._ def createClient(sentinelPorts: Int*): RedisMasterSlaveClient = new RedisMasterSlaveClient(masterName, sentinelPorts.map(p => NodeAddress(port = p))) test("client init test") { val client = createClient(sentinelPorts.head) client.initialized.futureValue shouldBe client client.executeBatch(get("key")).futureValue shouldBe Opt.Empty } test("not a sentinel") { val client = createClient(ports.head) client.initialized.failed.futureValue shouldBe a[MasterSlaveInitializationException] client.executeBatch(get("lol")).failed.futureValue shouldBe a[MasterSlaveInitializationException] } test("wrong master name") { val client = new RedisMasterSlaveClient("wrongmaster", sentinelPorts.map(p => NodeAddress(port = p))) client.initialized.failed.futureValue shouldBe a[MasterSlaveInitializationException] client.executeBatch(get("lol")).failed.futureValue shouldBe a[MasterSlaveInitializationException] } } class RedisMasterSlaveFailoverTest extends RedisMasterSlaveCommandsSuite { import RedisApi.Batches.StringTyped._ test("failover test") { val failoverPromise = Promise[Unit] redisClient.setMasterListener { client => if (client.address.port != ports.head) { failoverPromise.success(()) } } val getset = set("key", "walue") *> get("key") getset.assertEquals(Opt("walue")) val smFut = switchMaster() getset.assertEquals(Opt("walue")) smFut.futureValue getset.assertEquals(Opt("walue")) failoverPromise.future.futureValue // wait on new master getset.assertEquals(Opt("walue")) } }
Example 170
Source File: RedisConnectionClientTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package redis import akka.util.ByteString import com.avsystem.commons.redis.config.ConnectionConfig import com.avsystem.commons.redis.exception.{ConnectionFailedException, ConnectionInitializationFailure} import org.scalatest.concurrent.ScalaFutures import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class RedisConnectionClientTest extends AnyFunSuite with Matchers with ScalaFutures with UsesActorSystem with UsesRedisServer with ByteStringInterpolation { def createClient(initCommands: RedisBatch[Any]): RedisConnectionClient = new RedisConnectionClient(address, config = ConnectionConfig(initCommands)) test("client initialization test") { import RedisApi.Batches.StringTyped._ val client = createClient(select(0) *> clientSetname("name") *> ping) val f1 = client.executeBatch(echo(ByteString("LOL1"))) val f2 = client.executeBatch(echo(ByteString("LOL2"))) val f3 = client.executeBatch(clientGetname) client.initialized.futureValue shouldBe client f1.futureValue shouldBe ByteString("LOL1") f2.futureValue shouldBe ByteString("LOL2") f3.futureValue shouldBe "name".opt } test("client connection failure test") { import RedisApi.Batches.StringTyped._ val client = new RedisConnectionClient(NodeAddress(port = 63498)) val f1 = client.executeBatch(echo(ByteString("LOL1"))) val f2 = client.executeBatch(echo(ByteString("LOL2"))) client.initialized.failed.futureValue shouldBe a[ConnectionFailedException] f1.failed.futureValue shouldBe a[ConnectionFailedException] f2.failed.futureValue shouldBe a[ConnectionFailedException] } test("client initialization failure test") { import RedisApi.Batches.StringTyped._ val client = createClient(clusterInfo) val f1 = client.executeBatch(echo(ByteString("LOL1"))) val f2 = client.executeBatch(echo(ByteString("LOL2"))) client.initialized.failed.futureValue shouldBe a[ConnectionInitializationFailure] f1.failed.futureValue shouldBe a[ConnectionInitializationFailure] f2.failed.futureValue shouldBe a[ConnectionInitializationFailure] } test("api traits usage test") { val api = RedisApi.Connection.Async.StringTyped(createClient(RedisBatch.unit)) val bvApi: api.WithValue[ByteString] = api.valueType[ByteString] api.set("key", "value").futureValue shouldEqual true bvApi.set("key", ByteString.empty).futureValue shouldEqual true api.keyType[ByteString].set(ByteString("key"), "value").futureValue shouldEqual true bvApi.keyType[ByteString].set(ByteString("key"), ByteString.empty).futureValue shouldEqual true } } class RedisTlsConnectionClientTest extends RedisConnectionClientTest with UsesSslContext { override def createClient(initCommands: RedisBatch[Any]): RedisConnectionClient = new RedisConnectionClient(tlsAddress, config = ConnectionConfig(initCommands, () => sslContext.createSSLEngine)) }
Example 171
Source File: ExponentialBackoffTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package redis.config import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.concurrent.duration._ class ExponentialBackoffTest extends AnyFunSuite with Matchers { test("simple") { import RetryStrategy._ val eb = immediately.andThen(exponentially(1.second)).maxDelay(20.seconds).maxRetries(8) val allDelays = Iterator.iterateUntilEmpty(eb.nextRetry)(_._2.nextRetry).map(_._1).toList allDelays shouldBe List( Duration.Zero, 1.second, 2.seconds, 4.seconds, 8.seconds, 16.seconds, 20.seconds, 20.seconds ) } }
Example 172
Source File: LoadBalancerTestUtils.scala From scastie with Apache License 2.0 | 5 votes |
package com.olegych.scastie.balancer import java.time.Instant import com.olegych.scastie.api._ import org.scalatest.Assertion import org.scalatest.funsuite.AnyFunSuite object TestTaskId { def apply(i: Int) = TaskId(SnippetId(i.toString, None)) } case class TestServerRef(id: Int) case class TestState(state: String, ready: Boolean = true) extends ServerState { def isReady: Boolean = ready } trait LoadBalancerTestUtils extends AnyFunSuite with TestUtils { type TestServer0 = Server[TestServerRef, TestState] type TestLoadBalancer0 = LoadBalancer[TestServerRef, TestState] @transient private var taskId = 1000 def add(balancer: TestLoadBalancer0, config: Inputs): TestLoadBalancer0 = synchronized { val (_, balancer0) = balancer.add(Task(config, nextIp, TestTaskId(taskId), Instant.now)).get taskId += 1 balancer0 } // Ordering only for debug purposes object Multiset { def apply[T: Ordering](xs: Seq[T]): Multiset[T] = Multiset(xs.groupBy(x => x).map { case (k, vs) => (k, vs.size) }) } case class Multiset[T: Ordering](inner: Map[T, Int]) { override def toString: String = { val size = inner.values.sum inner.toList .sortBy { case (k, v) => (-v, k) } .map { case (k, v) => s"$k($v)" } .mkString("Multiset(", ", ", s") {$size}") } } def assertConfigs(balancer: TestLoadBalancer0)(columns: Seq[String]*): Assertion = { assert( Multiset(balancer.servers.map(_.currentConfig.sbtConfigExtra)) == Multiset( columns.flatten.map(i => sbtConfig(i.toString).sbtConfigExtra) ) ) } @transient private var serverId = 0 def server( c: String, mailbox: Vector[Task] = Vector(), state: TestState = TestState("default-state") ): TestServer0 = synchronized { val t = Server(TestServerRef(serverId), sbtConfig(c), state, mailbox) serverId += 1 t } def servers(columns: Seq[String]*): Vector[TestServer0] = { columns.to(Vector).flatten.map(c => server(c)) } @transient private var currentIp = 0 def nextIp: Ip = synchronized { val t = Ip("ip" + currentIp) currentIp += 1 t } def server(v: Int): TestServerRef = TestServerRef(v) def code(code: String) = Inputs.default.copy(code = code) def sbtConfig(sbtConfig: String) = Inputs.default.copy(sbtConfigExtra = sbtConfig) def history(columns: Seq[String]*): TaskHistory = { val records = columns.to(Vector).flatten.map(i => Task(Inputs.default.copy(code = i.toString), nextIp, TestTaskId(1), Instant.now)).reverse TaskHistory(Vector(records: _*), maxSize = 20) } }
Example 173
Source File: InstrumentSpecs.scala From scastie with Apache License 2.0 | 5 votes |
package com.olegych.scastie package instrumentation import java.nio.file._ import com.olegych.scastie.api.ScalaTarget import com.olegych.scastie.util.ScastieFileUtil.slurp import org.scalatest.funsuite.AnyFunSuite import scala.jdk.CollectionConverters._ class InstrumentSpecs extends AnyFunSuite { import InstrumentationFailure._ private val testFiles = { val path = Paths.get("instrumentation", "src", "test", "resources") val s = Files.newDirectoryStream(path) val t = s.asScala.toList s.close() t } testFiles.foreach { path => val dirName = path.getFileName.toString test(dirName) { val original = slurp(path.resolve("original.scala")).get val expected = slurp(path.resolve("instrumented.scala")).get val target = if (dirName == "scalajs") ScalaTarget.Js.default else ScalaTarget.Jvm.default val Right(obtained) = Instrument(original, target) // Files.write(path.resolve("obtained.scala"), obtained.getBytes(java.nio.charset.StandardCharsets.UTF_8)) Diff.assertNoDiff(obtained.trim, expected.trim) } } test("top level fails") { val Left(e) = Instrument("package foo { }") assert(e.isInstanceOf[ParsingError]) } test("main method fails") { val Left(HasMainMethod) = Instrument("object Main { def main(args: Array[String]): Unit = () }") } test("extends App trait fails") { val Left(HasMainMethod) = Instrument("object Main extends App { }") } test("with App trait fails") { val Left(HasMainMethod) = Instrument("trait Foo; object Main extends Foo with App { }") } test("extends App primary fails") { val Left(HasMainMethod) = Instrument("object Main extends App") } test("extends App secondary fails") { val Left(HasMainMethod) = Instrument("object Main extends A with App") } test("bug #83") { val Right(_) = Instrument("val answer: 42 = 42", ScalaTarget.Dotty.default) } }
Example 174
Source File: PropertyTests.scala From cats-stm with Apache License 2.0 | 5 votes |
package io.github.timwspence.cats.stm import cats.effect.{ContextShift, IO, Timer} import cats.instances.list._ import cats.syntax.functor._ import cats.syntax.traverse._ import org.scalacheck._ import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.concurrent.ExecutionContext import scala.util.Random class MaintainsInvariants extends AnyFunSuite with ScalaCheckDrivenPropertyChecks with Matchers { implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global implicit val timer: Timer[IO] = IO.timer(executionContext) implicit val cs: ContextShift[IO] = IO.contextShift(executionContext) val tvarGen: Gen[TVar[Long]] = for { value <- Gen.posNum[Long] } yield TVar.of(value).commit[IO].unsafeRunSync val txnGen: List[TVar[Long]] => Gen[STM[Unit]] = tvars => for { fromIdx <- Gen.choose(0, tvars.length - 1) toIdx <- Gen.choose(0, tvars.length - 1) suchThat (_ != fromIdx) txn <- for { balance <- tvars(fromIdx).get transfer = Math.abs(Random.nextLong()) % balance _ <- tvars(fromIdx).modify(_ - transfer) _ <- tvars(toIdx).modify(_ + transfer) } yield () } yield txn val gen: Gen[(Long, List[TVar[Long]], IO[Unit])] = for { tvars <- Gen.listOfN(50, tvarGen) total = tvars.foldLeft(0L)((acc, tvar) => acc + tvar.value) txns <- Gen.listOf(txnGen(tvars)) commit = txns.traverse(_.commit[IO].start) run = commit.flatMap(l => l.traverse(_.join)).void } yield (total, tvars, run) test("Transactions maintain invariants") { forAll(gen) { g => val total = g._1 val tvars = g._2 val txn = g._3 txn.unsafeRunSync() tvars.map(_.value).sum shouldBe total } } }
Example 175
Source File: ApplyTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.wartremover.contrib.warts.Apply import org.wartremover.test.WartTestTraverser import org.scalatest.funsuite.AnyFunSuite class ApplyTest extends AnyFunSuite with ResultAssertions { test("apply is disabled") { val result = WartTestTraverser(Apply) { class c { def apply() = 1 } } assertError(result)("apply is disabled") } test("object's apply is enabled") { val result = WartTestTraverser(Apply) { object c { def apply() = 1 } } assertEmpty(result) } test("Apply wart obeys SuppressWarnings") { val result = WartTestTraverser(Apply) { class c { @SuppressWarnings(Array("org.wartremover.contrib.warts.Apply")) def apply() = 1 } } assertEmpty(result) } }
Example 176
Source File: SomeApplyTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.wartremover.contrib.warts.SomeApply import org.wartremover.test.WartTestTraverser import org.scalatest.funsuite.AnyFunSuite class SomeApplyTest extends AnyFunSuite with ResultAssertions { test("can't use Some.apply with null") { val result = WartTestTraverser(SomeApply) { Some(null) } assertError(result)("Some.apply is disabled - use Option.apply instead") } test("can't use Some.apply with a literal") { val result = WartTestTraverser(SomeApply) { Some(1) } assertError(result)("Some.apply is disabled - use Option.apply instead") } test("can't use Some.apply with an identifier") { val result = WartTestTraverser(SomeApply) { val x = 1 Some(x) } assertError(result)("Some.apply is disabled - use Option.apply instead") } test("can use Some.unapply in pattern matching") { val result = WartTestTraverser(SomeApply) { Option("test") match { case Some(test) => println(test) case None => println("not gonna happen") } } assertEmpty(result) } test("obeys SuppressWarnings") { val result = WartTestTraverser(SomeApply) { @SuppressWarnings(Array("org.wartremover.contrib.warts.SomeApply")) val x = Some(null) } assertEmpty(result) } }
Example 177
Source File: RefinedClasstagTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package wartremover package contrib.warts import org.wartremover.contrib.test.ResultAssertions import org.wartremover.contrib.warts.RefinedClasstag import org.wartremover.test.WartTestTraverser import scala.reflect.ClassTag import scala.reflect.runtime.universe._ import org.scalatest.funsuite.AnyFunSuite class RefinedClasstagTest extends AnyFunSuite with ResultAssertions { import RefinedClasstagTest._ def methodWithClassTag[T]()(implicit ct: ClassTag[T]): Unit = {} def methodWithManifest[T]()(implicit mf: Manifest[T]): Unit = {} test("can't use refined types with classTags") { val result: WartTestTraverser.Result = WartTestTraverser(RefinedClasstag) { methodWithClassTag[A with B]() } assertError(result)(RefinedClasstag.ctMessage(typeOf[A with B].toString)) } test("can't use refined types with manifests") { val result: WartTestTraverser.Result = WartTestTraverser(RefinedClasstag) { methodWithManifest[A with B]() } assertError(result)(RefinedClasstag.mfMessage(typeOf[A with B].toString)) } test("can use single trait or an object in classtags") { val result: WartTestTraverser.Result = WartTestTraverser(RefinedClasstag) { methodWithClassTag[A]() methodWithClassTag[B]() methodWithClassTag[C]() methodWithClassTag[Obj.type]() } assertEmpty(result) } test("can use single trait or an object in manifests") { val result: WartTestTraverser.Result = WartTestTraverser(RefinedClasstag) { methodWithManifest[A]() methodWithManifest[B]() methodWithManifest[C]() methodWithManifest[Obj.type]() } assertEmpty(result) } test("obeys SuppressWarnings") { val result: WartTestTraverser.Result = WartTestTraverser(RefinedClasstag) { @SuppressWarnings(Array("org.wartremover.contrib.warts.RefinedClasstag")) def fun = { methodWithClassTag[A with B]() } } assertEmpty(result) } } object RefinedClasstagTest { trait A trait B trait C extends A with B case object Obj extends A with C type Ab = A with B }
Example 178
Source File: DiscardedFutureTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.scalatest.funsuite.AnyFunSuite import org.wartremover.contrib.warts.DiscardedFuture import org.wartremover.test.WartTestTraverser import scala.concurrent.Future import scala.util.Try class DiscardedFutureTest extends AnyFunSuite with ResultAssertions { implicit val ec: scala.concurrent.ExecutionContext = scala.concurrent.ExecutionContext.global test("error if Future is a return type of anonymous partial function`") { val result = WartTestTraverser(DiscardedFuture) { val f = Future.successful(1) f.andThen { case _ => f } } assertError(result)(DiscardedFuture.message) } test("error if Future is a return type of the value") { val result = WartTestTraverser(DiscardedFuture) { val f = Future.successful(1) val pf: PartialFunction[Try[Int], Future[String]] = { case _ => Future.successful("") } f.andThen(pf) } assertError(result)(DiscardedFuture.message) } test("success if non-Future is a type of return value") { val result = WartTestTraverser(DiscardedFuture) { val f = Future.successful(1) f.andThen { case _ => 1 } } assertEmpty(result) } test("can suppress warnings") { val result = WartTestTraverser(DiscardedFuture) { @SuppressWarnings(Array("org.wartremover.contrib.warts.DiscardedFuture")) def m() = { val f = Future.successful(1) f.andThen { case _ => f } } } assertEmpty(result) } }
Example 179
Source File: UnsafeInheritanceTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.wartremover.contrib.warts.UnsafeInheritance import org.wartremover.test.WartTestTraverser import org.scalatest.funsuite.AnyFunSuite class UnsafeInheritanceTest extends AnyFunSuite with ResultAssertions { test("Method must be final or abstract") { val result = WartTestTraverser(UnsafeInheritance) { trait T { def m() = {} } } assertError(result)("Method must be final or abstract") } test("Final and abstract, private, object methods are allowed") { val result = WartTestTraverser(UnsafeInheritance) { trait T { final def m2() = {} def m1(): Unit private def m3() = {} } final class C1 { def m() = {} } sealed class C2 { def m() = {} } object O { def m() = {} } case class CC(i: Int) } assertEmpty(result) } test("UnsafeInheritance wart obeys SuppressWarnings") { val result = WartTestTraverser(UnsafeInheritance) { trait T { @SuppressWarnings(Array("org.wartremover.contrib.warts.UnsafeInheritance")) def m() = {} } } assertEmpty(result) } }
Example 180
Source File: UnintendedLazinessTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.wartremover.contrib.warts.UnintendedLaziness import org.wartremover.test.WartTestTraverser import org.scalatest.funsuite.AnyFunSuite class UnintendedLazinessTest extends AnyFunSuite with ResultAssertions { private lazy val isScala213: Boolean = try { Class.forName("scala.collection.GenMapLike") false } catch { case _: ClassNotFoundException => true } test("Can't call filterKeys on a map") { val map = Map.empty[String, Int] val result = WartTestTraverser(UnintendedLaziness) { map.filterKeys(_.isEmpty) } if (isScala213) { assertEmpty(result) } else { assertError(result)(UnintendedLaziness.errorForFilterKeys) } } test("Can't call mapValues on a map") { val map = Map.empty[String, Int] val result = WartTestTraverser(UnintendedLaziness) { map.mapValues(_ + 1) } if (isScala213) { assertEmpty(result) } else { assertError(result)(UnintendedLaziness.errorForMapValues) } } test("Can call other methods on a map") { val map = Map.empty[String, Int] val result = WartTestTraverser(UnintendedLaziness) { map.filter { case (key, _) => key.isEmpty } map.map { case (key, value) => key -> (value + 1) } } assertEmpty(result) } test("Can call filterKeys on anything that's not a map") { val notAMap = new { def filterKeys(p: String => Boolean): Map[String, Int] = ??? } val result = WartTestTraverser(UnintendedLaziness) { notAMap.filterKeys(_.isEmpty) } assertEmpty(result) } test("Can't call mapValues on anything that's not a map") { val notAMap = new { def mapValues[W](f: Int => W): Map[String, W] = ??? } val result = WartTestTraverser(UnintendedLaziness) { notAMap.mapValues(_ + 1) } assertEmpty(result) } test("obeys SuppressWarnings") { val map = Map.empty[String, Int] val result = WartTestTraverser(UnintendedLaziness) { @SuppressWarnings(Array("org.wartremover.contrib.warts.UnintendedLaziness")) val _ = { map.filterKeys(_.isEmpty) map.mapValues(_ + 1) } } assertEmpty(result) } }
Example 181
Source File: NoNeedImportTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package wartremover.contrib.warts import org.scalatest.funsuite.AnyFunSuite import org.wartremover.contrib.test.ResultAssertions import org.wartremover.contrib.warts.NoNeedImport import org.wartremover.test.WartTestTraverser class NoNeedImportTest extends AnyFunSuite with ResultAssertions { test("`import scala.util.{ Try, _ }` is disabled") { val result = WartTestTraverser(NoNeedImport) { import scala.util.{ Try, _ } } assertError(result)("The wildcard import exists. Remove other explicitly names of the `import`.") } test("`import scala.util.{ Try => _ }` is disabled") { val result = WartTestTraverser(NoNeedImport) { import scala.util.{ Try => _ } } assertError(result)("Import into the wildcard(`something => _`) is meaningless. Remove it.") } test("`import scala.util.{ Try, Success => MySuccess, _ }` is disabled") { val result = WartTestTraverser(NoNeedImport) { import scala.util.{ Try, Success => MySuccess, _ } } assertError(result)("The wildcard import exists. Remove other explicitly names of the `import`.") } test("`import scala.util.{ Try => _ , _ }` can be used") { val result = WartTestTraverser(NoNeedImport) { import scala.util.{ Try => _, _ } } assertEmpty(result) } test("`import scala.util._` can be used") { val result = WartTestTraverser(NoNeedImport) { import scala.util._ import scala.util.{ _ } } assertEmpty(result) } test("`import scala.util.{ Try => MyTry , _ }` can be used") { val result = WartTestTraverser(NoNeedImport) { import scala.util.{ Try => MyTry, _ } } assertEmpty(result) } }
Example 182
Source File: SealedCaseClassTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.wartremover.contrib.warts.SealedCaseClass import org.wartremover.test.WartTestTraverser import org.scalatest.funsuite.AnyFunSuite class SealedCaseClassTest extends AnyFunSuite with ResultAssertions { test("can't declare sealed case classes") { val result = WartTestTraverser(SealedCaseClass) { sealed case class Foo(i: Int) } assertError(result)("case classes must not be sealed") } test("can declare non-sealed case classes") { val result = WartTestTraverser(SealedCaseClass) { case class Foo(i: Int) } assertEmpty(result) } test("can declare sealed regular classes") { val result = WartTestTraverser(SealedCaseClass) { sealed class Foo(i: Int) sealed trait Bar sealed abstract class Baz } assertEmpty(result) } test("SealedCaseClass wart obeys SuppressWarnings") { val result = WartTestTraverser(SealedCaseClass) { @SuppressWarnings(Array("org.wartremover.contrib.warts.SealedCaseClass")) sealed case class Foo(i: Int) } assertEmpty(result) } }
Example 183
Source File: SymbolicNameTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.wartremover.contrib.warts.SymbolicName import org.wartremover.test.WartTestTraverser import org.scalatest.funsuite.AnyFunSuite class SymbolicNameTest extends AnyFunSuite with ResultAssertions { test("Symbolic name is disabled") { val result = WartTestTraverser(SymbolicName) { class \&/ { def &&&() = {} } } assertError(result)("Symbolic name is disabled") } test("Short symbolic name is allowed") { val result = WartTestTraverser(SymbolicName) { def ::() = {} } assertEmpty(result) } test("All third-party names are allowed") { val result = WartTestTraverser(SymbolicName) { List(1) ::: List(2) } assertEmpty(result) } test("Normal names are allowed") { val result = WartTestTraverser(SymbolicName) { val name = 0 val _aB = 1 val `typ` = 2 } assertEmpty(result) } test("SymbolicName wart obeys SuppressWarnings") { val result = WartTestTraverser(SymbolicName) { @SuppressWarnings(Array("org.wartremover.contrib.warts.SymbolicName")) def :+:() = {} } assertEmpty(result) } test("issue 48") { // https://github.com/wartremover/wartremover-contrib/issues/48 val result = WartTestTraverser(SymbolicName) { case class Foo( a: Boolean = false, b: Boolean = false, c: Boolean = false, d: Boolean = false) val a = Foo(a = true) val b = Foo(b = true) val c = Foo(c = true) val d = Foo(d = true) } assertEmpty(result) } }
Example 184
Source File: MissingOverrideTest.scala From wartremover-contrib with Apache License 2.0 | 5 votes |
package org.wartremover package contrib.test import org.wartremover.contrib.warts.MissingOverride import org.wartremover.test.WartTestTraverser import org.scalatest.funsuite.AnyFunSuite class MissingOverrideTest extends AnyFunSuite with ResultAssertions { test("Method must have override modifier") { val result = WartTestTraverser(MissingOverride) { trait T { def f(): Unit } class C extends T { def f() = {} } } assertError(result)("Method must have override modifier") } test("Explicit override is allowed") { val result = WartTestTraverser(MissingOverride) { trait T { def f(): Unit } class C extends T { override def f() = {} } } assertEmpty(result) } test("MissingOverride wart obeys SuppressWarnings") { val result = WartTestTraverser(MissingOverride) { trait T { def f(): Unit } class C extends T { @SuppressWarnings(Array("org.wartremover.contrib.warts.MissingOverride")) def f() = {} } } assertEmpty(result) } test("issue #28. PartialFunction") { val result = WartTestTraverser(MissingOverride) { val list = List(1, 2, 3) list.collect { case 3 => "test" } } assertEmpty(result) } }
Example 185
Source File: ErrorTransInstanceSpec.scala From hotpotato with Apache License 2.0 | 5 votes |
package hotpotato import cats.Eq import cats.data.EitherT import cats.implicits._ import cats.laws.discipline.arbitrary._ import hotpotato.ErrorTransInstanceSpec.SimpleError import hotpotato.laws.{ErrorTransTests, ErrorTransThrowTests} import org.scalacheck.Arbitrary import org.scalatest.funsuite.AnyFunSuite import org.typelevel.discipline.scalatest.Discipline class ErrorTransInstanceSpec extends AnyFunSuite with Discipline { checkAll( "Either.ErrorTransLaws", ErrorTransTests[Either[*, *]].errorTrans[Int, Int, Int, String, String, String], ) checkAll( "EitherT.ErrorTransLaws", ErrorTransTests[EitherT[Option, *, *]].errorTrans[Int, Int, Int, String, String, String], ) // Cheat a little bit by only generating only one type of throwable private implicit val arbThrowable: Arbitrary[Throwable] = Arbitrary( Arbitrary.arbitrary[String].map(SimpleError).map(x => x: Throwable), ) private implicit val eqThrowable: Eq[Throwable] = new Eq[Throwable] { override def eqv(x: Throwable, y: Throwable): Boolean = x == y } checkAll( "EitherT.ErrorTransThrowLaws", ErrorTransThrowTests[EitherT[Either[Throwable, *], *, *]] .errorTransThrow[Int, Int, Int, String, String, String], ) } object ErrorTransInstanceSpec { final case class SimpleError(message: String) extends Exception(message) }
Example 186
Source File: MouseSuite.scala From mouse with MIT License | 5 votes |
package mouse import cats._ import cats.instances.AllInstances import org.scalactic.TripleEqualsSupport.BToAEquivalenceConstraint import org.scalactic.{CanEqual, Equivalence} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks trait MouseSuite extends AnyFunSuite with Matchers with ScalaCheckDrivenPropertyChecks with AllSharedSyntax with AllInstances { implicit val eq0 = new Eq[NumberFormatException] { override def eqv(x: NumberFormatException, y: NumberFormatException): Boolean = x.getMessage == y.getMessage } implicit val eq1 = new Eq[IllegalArgumentException] { override def eqv(x: IllegalArgumentException, y: IllegalArgumentException): Boolean = x.getMessage == y.getMessage } final class MouseEquivalence[T](T: Eq[T]) extends Equivalence[T] { def areEquivalent(a: T, b: T): Boolean = T.eqv(a, b) } implicit def mouseCanEqual[A, B](implicit A: Eq[A], ev: B <:< A): CanEqual[A, B] = new BToAEquivalenceConstraint[A, B](new MouseEquivalence(A), ev) }
Example 187
Source File: ScalazLawsSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.scalaz import com.typesafe.config.ConfigValue import org.scalacheck.{ Prop, Properties } import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.Checkers import pureconfig.error.ConfigReaderFailures import pureconfig.module.scalaz.arbitrary._ import pureconfig.module.scalaz.equal._ import pureconfig.module.scalaz.instances._ import pureconfig.{ ConfigConvert, ConfigReader, ConfigWriter } import scalaz.scalacheck.ScalazProperties._ import scalaz.std.anyVal.intInstance class ScalazLawsSuite extends AnyFunSuite with Checkers { import ScalazLawsSuite._ test("contravariant.laws[ConfigWriter]") { check(properties2prop(contravariant.laws[ConfigWriter])) } test("invariantFunctor.laws[ConfigConvert]") { check(properties2prop(invariantFunctor.laws[ConfigConvert])) } test("monadError.laws[ConfigReader, ConfigReaderFailures]") { check(properties2prop(monadError.laws[ConfigReader, ConfigReaderFailures])) } test("semigroup.laws[ConfigReaderFailures]") { check(properties2prop(semigroup.laws[ConfigReaderFailures])) } test("semigroup.laws[ConfigValue]") { check(properties2prop(semigroup.laws[ConfigValue])) } } object ScalazLawsSuite { def properties2prop(ps: Properties): Prop = Prop.all(ps.properties.map(_._2).toSeq: _*) }
Example 188
Source File: JsonProducerSpec.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka.producer import java.nio.charset.StandardCharsets.UTF_8 import com.evolutiongaming.skafka.{Bytes, Partition, ToBytes, TopicPartition} import play.api.libs.json.{JsString, Json} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class JsonProducerSpec extends AnyFunSuite with Matchers { test("apply") { val metadata = RecordMetadata(TopicPartition("topic", Partition.min)) var actual = Option.empty[(Option[Bytes], Option[Bytes])] type Id[A] = A val send = new Producer.Send[Id] { def apply[K, V]( record: ProducerRecord[K, V])(implicit toBytesK: ToBytes[Id, K], toBytesV: ToBytes[Id, V] ) = { val topic = record.topic val value = record.value.map(toBytesV(_, topic)) val key = record.key.map(toBytesK(_, topic)) actual = Some((key, value)) metadata } } val producer = JsonProducer(send) val value = JsString("value") val key = "key" val record = ProducerRecord("topic", value, key) producer(record) shouldEqual metadata val (Some(keyBytes), valueBytes) = actual.get new String(keyBytes, UTF_8) shouldEqual key valueBytes.map(Json.parse) shouldEqual Some(value) } }
Example 189
Source File: ProducerConfigSpec.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka.producer import cats.data.{NonEmptyList => Nel} import com.evolutiongaming.skafka.CommonConfig import com.typesafe.config.ConfigFactory import org.apache.kafka.clients.producer.internals.DefaultPartitioner import scala.concurrent.duration._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ProducerConfigSpec extends AnyFunSuite with Matchers { val custom = ProducerConfig( batchSize = 1, deliveryTimeout = 2.seconds, acks = Acks.All, linger = 3.millis, maxRequestSize = 4, maxBlock = 5.seconds, bufferMemory = 6, compressionType = CompressionType.Lz4, retries = 8, maxInFlightRequestsPerConnection = 7, partitionerClass = Some(classOf[DefaultPartitioner]), interceptorClasses = List("interceptorClasses"), idempotence = true, transactionTimeout = 8.minute, transactionalId = Some("transactionalId")) test("apply from empty config") { val config = ConfigFactory.empty() ProducerConfig(config) shouldEqual ProducerConfig.Default } test("apply from config") { val config = ConfigFactory.parseURL(getClass.getResource("valid.conf")) ProducerConfig(config) shouldEqual custom } test("apply from deprecated config") { val config = ConfigFactory.parseURL(getClass.getResource("deprecated.conf")) ProducerConfig(config) shouldEqual custom } test("bindings") { val configs = ProducerConfig( common = CommonConfig( bootstrapServers = Nel.of("localhost:9092", "127.0.0.1:9092"), clientId = Some("clientId"))) configs.bindings shouldEqual Map( "reconnect.backoff.max.ms" -> "1000", "retries" -> "2147483647", "compression.type" -> "none", "buffer.memory" -> "33554432", "connections.max.idle.ms" -> "540000", "max.request.size" -> "1048576", "metrics.sample.window.ms" -> "30000", "security.protocol" -> "PLAINTEXT", "bootstrap.servers" -> "localhost:9092,127.0.0.1:9092", "request.timeout.ms" -> "30000", "max.block.ms" -> "60000", "client.id" -> "clientId", "metric.reporters" -> "", "transaction.timeout.ms" -> "60000", "interceptor.classes" -> "", "delivery.timeout.ms" -> "120000", "acks" -> "1", "metadata.max.age.ms" -> "300000", "enable.idempotence" -> "false", "metrics.num.samples" -> "2", "metrics.recording.level" -> "INFO", "max.in.flight.requests.per.connection" -> "5", "retry.backoff.ms" -> "100", "receive.buffer.bytes" -> "32768", "reconnect.backoff.ms" -> "50", "linger.ms" -> "0", "batch.size" -> "16384", "send.buffer.bytes" -> "131072") } }
Example 190
Source File: ConsumerRecordsTest.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka.consumer import cats.data.{NonEmptyList => Nel} import cats.implicits._ import com.evolutiongaming.skafka.{Offset, Partition, Topic, TopicPartition} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ConsumerRecordsTest extends AnyFunSuite with Matchers { test("summaryShow") { def consumerRecord(topic: Topic, partition: Int, offset: Long, key: Int) = { ConsumerRecord( topicPartition = TopicPartition(topic, Partition.unsafe(partition)), offset = Offset.unsafe(offset), timestampAndType = none, key = Some(WithSize(key)), value = none[WithSize[Nothing]], headers = Nil) } val records = Nel.of( consumerRecord(topic = "0", partition = 0, offset = 1, key = 0), consumerRecord(topic = "0", partition = 0, offset = 2, key = 1), consumerRecord(topic = "0", partition = 0, offset = 4, key = 2), consumerRecord(topic = "0", partition = 0, offset = 0, key = 0), consumerRecord(topic = "0", partition = 0, offset = 3, key = 0), consumerRecord(topic = "0", partition = 1, offset = 1, key = 11), consumerRecord(topic = "0", partition = 2, offset = 1, key = 21), consumerRecord(topic = "1", partition = 0, offset = 1, key = 0), consumerRecord(topic = "1", partition = 0, offset = 0, key = 0), consumerRecord(topic = "0", partition = 1, offset = 0, key = 11)) val consumerRecords = ConsumerRecords(records.sorted.groupBy(_.topicPartition)) val expected = "0-0:0..4 records: 5, 0-1:0..1 records: 2, 0-2:1 records: 1, 1-0:0..1 records: 2" ConsumerRecords .summaryShow .show(consumerRecords) shouldEqual expected } }
Example 191
Source File: ConsumerConfigSpec.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka.consumer import cats.data.{NonEmptyList => Nel} import com.evolutiongaming.skafka.CommonConfig import com.typesafe.config.ConfigFactory import scala.concurrent.duration._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ConsumerConfigSpec extends AnyFunSuite with Matchers { val custom = ConsumerConfig( groupId = Some("groupId"), maxPollRecords = 1, maxPollInterval = 2.millis, sessionTimeout = 3.seconds, heartbeatInterval = 4.minutes, autoCommit = false, autoCommitInterval = 5.hours, partitionAssignmentStrategy = "partitionAssignmentStrategy", autoOffsetReset = AutoOffsetReset.Earliest, defaultApiTimeout = 6.seconds, fetchMinBytes = 6, fetchMaxBytes = 7, fetchMaxWait = 8.millis, maxPartitionFetchBytes = 9, checkCrcs = false, interceptorClasses = List("interceptorClasses"), excludeInternalTopics = false, isolationLevel = IsolationLevel.ReadCommitted) test("apply from empty config") { val config = ConfigFactory.empty() ConsumerConfig(config) shouldEqual ConsumerConfig.Default } test("apply from config") { val config = ConfigFactory.parseURL(getClass.getResource("valid.conf")) ConsumerConfig(config) shouldEqual custom } test("apply from deprecated config") { val config = ConfigFactory.parseURL(getClass.getResource("deprecated.conf")) ConsumerConfig(config) shouldEqual custom } test("bindings") { val configs = ConsumerConfig( common = CommonConfig( bootstrapServers = Nel.of("localhost:9092", "127.0.0.1:9092"), clientId = Some("clientId"))) configs.bindings shouldEqual Map( "exclude.internal.topics" -> "true", "reconnect.backoff.max.ms" -> "1000", "auto.offset.reset" -> "latest", "partition.assignment.strategy" -> "org.apache.kafka.clients.consumer.RangeAssignor", "heartbeat.interval.ms" -> "3000", "check.crcs" -> "true", "auto.commit.interval.ms" -> "5000", "default.api.timeout.ms" -> "60000", "connections.max.idle.ms" -> "540000", "fetch.max.wait.ms" -> "500", "fetch.min.bytes" -> "1", "metrics.sample.window.ms" -> "30000", "security.protocol" -> "PLAINTEXT", "bootstrap.servers" -> "localhost:9092,127.0.0.1:9092", "enable.auto.commit" -> "true", "fetch.max.bytes" -> "52428800", "max.partition.fetch.bytes" -> "1048576", "request.timeout.ms" -> "30000", "max.poll.records" -> "500", "client.id" -> "clientId", "max.poll.interval.ms" -> "300000", "metric.reporters" -> "", "interceptor.classes" -> "", "metadata.max.age.ms" -> "300000", "metrics.num.samples" -> "2", "metrics.recording.level" -> "INFO", "retry.backoff.ms" -> "100", "session.timeout.ms" -> "10000", "receive.buffer.bytes" -> "32768", "reconnect.backoff.ms" -> "50", "isolation.level" -> "read_uncommitted", "send.buffer.bytes" -> "131072") } }
Example 192
Source File: OffsetAndMetadataSpec.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka.consumer import com.evolutiongaming.skafka.{Offset, OffsetAndMetadata} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class OffsetAndMetadataSpec extends AnyFunSuite with Matchers { for { (value, expected) <- List( (OffsetAndMetadata.empty, "OffsetAndMetadata(0)"), (OffsetAndMetadata(Offset.min, "2"), "OffsetAndMetadata(0,2)")) } { test(s"$value.toString") { value.toString shouldEqual expected } } }
Example 193
Source File: ConsumerRecordSpec.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka.consumer import com.evolutiongaming.skafka.{Offset, Partition, Topic, TopicPartition} import cats.data.{NonEmptyList => Nel} import cats.implicits._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class ConsumerRecordSpec extends AnyFunSuite with Matchers { test("order") { def consumerRecord(topic: Topic, partition: Int, offset: Long, key: Int) = { ConsumerRecord( topicPartition = TopicPartition(topic, Partition.unsafe(partition)), offset = Offset.unsafe(offset), timestampAndType = none, key = Some(WithSize(key)), value = none, headers = Nil) } val notSorted = Nel.of( consumerRecord(topic = "0", partition = 0, offset = 1, key = 0), consumerRecord(topic = "0", partition = 0, offset = 2, key = 1), consumerRecord(topic = "0", partition = 0, offset = 4, key = 2), consumerRecord(topic = "0", partition = 0, offset = 0, key = 0), consumerRecord(topic = "0", partition = 0, offset = 3, key = 0), consumerRecord(topic = "0", partition = 1, offset = 1, key = 11), consumerRecord(topic = "0", partition = 2, offset = 0, key = 21), consumerRecord(topic = "1", partition = 0, offset = 1, key = 0), consumerRecord(topic = "1", partition = 0, offset = 0, key = 0), consumerRecord(topic = "0", partition = 1, offset = 0, key = 11)) val expected = Nel.of( consumerRecord(topic = "0", partition = 0, offset = 0, key = 0), consumerRecord(topic = "0", partition = 0, offset = 1, key = 0), consumerRecord(topic = "0", partition = 0, offset = 3, key = 0), consumerRecord(topic = "0", partition = 0, offset = 2, key = 1), consumerRecord(topic = "0", partition = 0, offset = 4, key = 2), consumerRecord(topic = "0", partition = 1, offset = 0, key = 11), consumerRecord(topic = "0", partition = 1, offset = 1, key = 11), consumerRecord(topic = "0", partition = 2, offset = 0, key = 21), consumerRecord(topic = "1", partition = 0, offset = 0, key = 0), consumerRecord(topic = "1", partition = 0, offset = 1, key = 0)) notSorted.sorted shouldEqual expected } }
Example 194
Source File: TopicPartitionSpec.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka import cats.data.{NonEmptyList => Nel} import cats.implicits._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class TopicPartitionSpec extends AnyFunSuite with Matchers { test("show") { val topicPartition = TopicPartition(topic = "topic", partition = Partition.min) topicPartition.show shouldEqual "topic-0" } test("order") { def topicPartition(topic: Topic, partition: Int) = { TopicPartition(topic = topic, partition = Partition.unsafe(partition)) } Nel.of( topicPartition(topic = "0", partition = 1), topicPartition(topic = "1", partition = 0), topicPartition(topic = "0", partition = 0) ).sorted shouldEqual Nel.of( topicPartition(topic = "0", partition = 0), topicPartition(topic = "0", partition = 1), topicPartition(topic = "1", partition = 0)) } }
Example 195
Source File: CommonConfigSpec.scala From skafka with MIT License | 5 votes |
package com.evolutiongaming.skafka import cats.data.{NonEmptyList => Nel} import com.typesafe.config.ConfigFactory import scala.concurrent.duration._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class CommonConfigSpec extends AnyFunSuite with Matchers { val custom = CommonConfig( bootstrapServers = Nel.of("host:port"), clientId = Some("clientId"), connectionsMaxIdle = 1.millis, receiveBufferBytes = 2, sendBufferBytes = 3, requestTimeout = 4.seconds, metadataMaxAge = 5.seconds, reconnectBackoffMax = 5.hours, reconnectBackoff = 6.millis, retryBackoff = 7.seconds, securityProtocol = SecurityProtocol.Ssl, metrics = MetricsConfig( sampleWindow = 9.hours, numSamples = 10, recordingLevel = "DEBUG", reporters = List("reporter"))) test("apply from empty config") { val config = ConfigFactory.empty() CommonConfig(config) shouldEqual CommonConfig.Default } test("apply from config") { val config = ConfigFactory.parseURL(getClass.getResource("valid.conf")) CommonConfig(config) shouldEqual custom } test("apply from deprecated config") { val config = ConfigFactory.parseURL(getClass.getResource("deprecated.conf")) CommonConfig(config) shouldEqual custom } test("bindings") { val configs = CommonConfig( bootstrapServers = Nel.of("localhost:9092", "127.0.0.1:9092"), clientId = Some("clientId")) configs.bindings shouldEqual Map( "bootstrap.servers" -> "localhost:9092,127.0.0.1:9092", "client.id" -> "clientId", "connections.max.idle.ms" -> "540000", "receive.buffer.bytes" -> "32768", "send.buffer.bytes" -> "131072", "request.timeout.ms" -> "30000", "metadata.max.age.ms" -> "300000", "reconnect.backoff.max.ms" -> "1000", "retry.backoff.ms" -> "100", "security.protocol" -> "PLAINTEXT", "reconnect.backoff.ms" -> "50", "metrics.sample.window.ms" -> "30000", "metrics.num.samples" -> "2", "metrics.recording.level" -> "INFO", "metric.reporters" -> "") } }
Example 196
Source File: BsonCodecInstancesTest.scala From circe-bson with Apache License 2.0 | 5 votes |
package io.circe.bson import io.circe.{ Json, JsonNumber } import io.circe.testing.ArbitraryInstances import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import reactivemongo.bson.BSONDecimal import scala.util.{ Failure, Success, Try } class BsonCodecInstancesTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks with ArbitraryInstances { override def transformJsonNumber(n: JsonNumber): JsonNumber = Try(BSONDecimal.parse(n.toString)).flatten match { case Success(_) => n case Failure(_) => JsonNumber.fromString("0").get } test("BsonCodecInstances should round-trip JSON values") { forAll { json: Json => assert(Right(json) === jsonToBson(json).flatMap(bsonToJson)) } } test("BsonCodecInstances should support BSON Date values") { val json = Json.obj("myDate" -> Json.obj("$date" -> Json.fromLong(1570040789432L))) assert(Right(json) === jsonToBson(json).flatMap(bsonToJson)) } }
Example 197
Source File: DagTest.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill.codegen import java.time.LocalDateTime import io.getquill.codegen.dag.CatalogBasedAncestry import org.scalatest.BeforeAndAfter import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers._ import scala.reflect.{ ClassTag, classTag } // I.e. something the type-ancestry does not know about class UnknownClass class CodeGeneratorRunnerDagTest extends AnyFunSuite with BeforeAndAfter { case class TestCase[O](one: ClassTag[_], twos: Seq[ClassTag[_]], result: ClassTag[_]) val cases = Seq( TestCase(classTag[Int], Seq(classTag[Long]), classTag[Long]), TestCase(classTag[Long], Seq(classTag[Boolean], classTag[Int], classTag[Byte], classTag[Long]), classTag[Long]), TestCase(classTag[Int], Seq(classTag[Boolean], classTag[Int], classTag[Byte]), classTag[Int]), TestCase( classTag[BigDecimal], Seq( classTag[Boolean], classTag[Int], classTag[Byte], classTag[Long], classTag[BigDecimal] ), classTag[BigDecimal] ), TestCase( classTag[String], Seq( classTag[Boolean], classTag[Int], classTag[Long], classTag[Byte], classTag[BigDecimal], classTag[java.time.LocalDate], classTag[java.time.LocalDateTime] ), classTag[String] ), TestCase(classTag[java.time.LocalDate], Seq(classTag[LocalDateTime]), classTag[LocalDateTime]), TestCase(classTag[Short], Seq(classTag[Boolean], classTag[Byte]), classTag[Short]), TestCase(classTag[Short], Seq(classTag[Int]), classTag[Int]), TestCase(classTag[Int], Seq(classTag[Short]), classTag[Int]), TestCase(classTag[UnknownClass], Seq(classTag[String]), classTag[String]), TestCase(classTag[UnknownClass], Seq(classTag[UnknownClass]), classTag[UnknownClass]), // Don't know ancestry of unknown class to an Int (or any kind) so go directly to root of the ancestry i.e. String. TestCase(classTag[UnknownClass], Seq(classTag[Int]), classTag[String]) ) val casesIter = for { cas <- cases two <- cas.twos } yield (cas.one, two, cas.result) casesIter.foreach({ case (one, two, expected) => test(s"Common Ancestry between ${one} and ${two} should be ${expected}") { new CatalogBasedAncestry().apply(one, two) should equal(expected) } }) }
Example 198
Source File: VendorExtensionTest.scala From guardrail with MIT License | 5 votes |
package swagger import java.util import com.twilio.guardrail.extract.VendorExtension import io.swagger.parser.OpenAPIParser import io.swagger.v3.parser.core.models.ParseOptions import scala.collection.JavaConverters._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class VendorExtensionTest extends AnyFunSuite with Matchers { val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io |produces: | - application/json |x-scala-garbage: io.swagger.models.Swagger |paths: | foo: | x-scala-garbage: io.swagger.models.Path | get: | x-scala-garbage: io.swagger.models.Operation | parameters: | - name: id | in: query | required: true | type: integer | x-scala-garbage: io.swagger.models.parameters.Parameter | responses: | '200': | description: successful operation | x-scala-garbage: io.swagger.models.Response | schema: | "$$ref": "#/definitions/Order" | '404': | description: Order not found | x-scala-garbage: io.swagger.models.Response |definitions: | Order: | type: object | x-scala-garbage: io.swagger.models.Model | properties: | id: | type: integer | format: int64 | x-scala-garbage: io.swagger.models.properties.Property |""".stripMargin test("Able to extract strings") { val parseOpts = new ParseOptions parseOpts.setResolve(true) val swagger = new OpenAPIParser().readContents(spec, new util.LinkedList(), parseOpts).getOpenAPI // VendorExtension(swagger).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Swagger")) for { (k, v) <- swagger.getPaths.asScala _ = VendorExtension(v).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Path")) op <- v.readOperations().asScala _ = VendorExtension(op).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Operation")) _ = for { param <- op.getResponses.asScala.values // _ = VendorExtension(param).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.parameters.Parameter")) } () _ = for { (_, resp) <- op.getResponses.asScala _ = VendorExtension(resp) .extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Response")) } () } () for { (_, defn) <- swagger.getComponents.getSchemas.asScala _ = VendorExtension(defn).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Model")) _ = for { (_, prop) <- defn.getProperties.asScala _ = VendorExtension(prop) .extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.properties.Property")) } () } () } }
Example 199
Source File: WriteTreeSuite.scala From guardrail with MIT License | 5 votes |
package com.twilio.guardrail.core import com.twilio.guardrail.WriteTree import java.nio.file.Files import scala.concurrent.Future import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class WriteTreeSuite extends AnyFunSuite with Matchers { test("Ensure that even if we don't overwrite output files, the path is returned") { val path = Files.createTempFile("guardrail-writeTree", ".txt") Files.delete(path) val contents = "example contents".getBytes val (firstLog, firstPath) = WriteTree.unsafeWriteTreeLogged(WriteTree(path, Future.successful(contents))).run val (secondLog, secondPath) = WriteTree.unsafeWriteTreeLogged(WriteTree(path, Future.successful(contents))).run val _1 = firstLog shouldBe (Nil) val _2 = secondLog shouldBe (Nil) val _3 = firstPath shouldBe (secondPath) Files.delete(path) } }
Example 200
Source File: PropertyExtractors.scala From guardrail with MIT License | 5 votes |
package tests.generators.akkaHttp import com.twilio.guardrail.generators.Scala.AkkaHttp import com.twilio.guardrail.generators.syntax.Scala.companionForStaticDefns import com.twilio.guardrail.{ ClassDefinition, Context, ProtocolDefinitions } import support.SwaggerSpecRunner import scala.meta._ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class PropertyExtractors extends AnyFunSuite with Matchers with SwaggerSpecRunner { val swagger: String = s""" |swagger: "2.0" |info: | title: Whatever | version: 1.0.0 |host: localhost:1234 |schemes: | - http |definitions: | Something: | type: object | required: | - map | properties: | boolean_value: | type: boolean | string_value: | type: string | date_property: | type: date | date_time_property: | type: date-time | long_property: | type: integer | format: int64 | int_property: | type: integer | format: int32 | integer_property: | type: integer | float_property: | type: number | format: float | double_property: | type: number | format: double | number_property: | type: number | untyped_property: | default: "what" | object_property: | type: object |""".stripMargin ) """ val companion = q""" object Something { implicit val encodeSomething: Encoder.AsObject[Something] = { val readOnlyKeys = Set[String]() Encoder.AsObject.instance[Something](a => JsonObject.fromIterable(Vector(("boolean_value", a.booleanValue.asJson), ("string_value", a.stringValue.asJson), ("long_property", a.longProperty.asJson), ("int_property", a.intProperty.asJson), ("integer_property", a.integerProperty.asJson), ("float_property", a.floatProperty.asJson), ("double_property", a.doubleProperty.asJson), ("number_property", a.numberProperty.asJson), ("untyped_property", a.untypedProperty.asJson), ("object_property", a.objectProperty.asJson)))).mapJsonObject(_.filterKeys(key => !(readOnlyKeys contains key))) } implicit val decodeSomething: Decoder[Something] = new Decoder[Something] { final def apply(c: HCursor): Decoder.Result[Something] = for (v0 <- c.downField("boolean_value").as[Option[Boolean]]; v1 <- c.downField("string_value").as[Option[String]]; v2 <- c.downField("long_property").as[Option[Long]]; v3 <- c.downField("int_property").as[Option[Int]]; v4 <- c.downField("integer_property").as[Option[BigInt]]; v5 <- c.downField("float_property").as[Option[Float]]; v6 <- c.downField("double_property").as[Option[Double]]; v7 <- c.downField("number_property").as[Option[BigDecimal]]; v8 <- c.downField("untyped_property").as[Option[io.circe.Json]]; v9 <- c.downField("object_property").as[Option[io.circe.Json]]) yield Something(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) } } """ cls.structure should equal(definition.structure) cmp.structure should equal(companion.structure) } }