diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9724dd05..4b20e09d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,7 +29,7 @@ jobs: matrix: os: [ubuntu-22.04] scala: [2.13, 3] - java: [temurin@11, temurin@17] + java: [temurin@17, temurin@21] runs-on: ${{ matrix.os }} timeout-minutes: 60 steps: @@ -41,30 +41,30 @@ jobs: - name: Setup sbt uses: sbt/setup-sbt@v1 - - name: Setup Java (temurin@11) - id: setup-java-temurin-11 - if: matrix.java == 'temurin@11' + - name: Setup Java (temurin@17) + id: setup-java-temurin-17 + if: matrix.java == 'temurin@17' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 11 + java-version: 17 cache: sbt - name: sbt update - if: matrix.java == 'temurin@11' && steps.setup-java-temurin-11.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' run: sbt +update - - name: Setup Java (temurin@17) - id: setup-java-temurin-17 - if: matrix.java == 'temurin@17' + - name: Setup Java (temurin@21) + id: setup-java-temurin-21 + if: matrix.java == 'temurin@21' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 17 + java-version: 21 cache: sbt - name: sbt update - if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@21' && steps.setup-java-temurin-21.outputs.cache-hit == 'false' run: sbt +update - name: Check that workflows are up to date @@ -74,20 +74,20 @@ jobs: run: sbt '++ ${{ matrix.scala }}' test - name: Check binary compatibility - if: matrix.java == 'temurin@11' && matrix.os == 'ubuntu-22.04' + if: matrix.java == 'temurin@17' && matrix.os == 'ubuntu-22.04' run: sbt '++ ${{ matrix.scala }}' mimaReportBinaryIssues - name: Generate API documentation - if: matrix.java == 'temurin@11' && matrix.os == 'ubuntu-22.04' + if: matrix.java == 'temurin@17' && matrix.os == 'ubuntu-22.04' run: sbt '++ ${{ matrix.scala }}' doc - name: Make target directories if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/master') - run: mkdir -p tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target akka-http/target tagged-meta/js/target project/target + run: mkdir -p tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target tagged-meta/js/target project/target - name: Compress target directories if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/master') - run: tar cf targets.tar tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target akka-http/target tagged-meta/js/target project/target + run: tar cf targets.tar tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target tagged-meta/js/target project/target - name: Upload target directories if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/master') @@ -103,7 +103,7 @@ jobs: strategy: matrix: os: [ubuntu-22.04] - java: [temurin@11] + java: [temurin@17] runs-on: ${{ matrix.os }} steps: - name: Checkout current branch (full) @@ -114,30 +114,30 @@ jobs: - name: Setup sbt uses: sbt/setup-sbt@v1 - - name: Setup Java (temurin@11) - id: setup-java-temurin-11 - if: matrix.java == 'temurin@11' + - name: Setup Java (temurin@17) + id: setup-java-temurin-17 + if: matrix.java == 'temurin@17' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 11 + java-version: 17 cache: sbt - name: sbt update - if: matrix.java == 'temurin@11' && steps.setup-java-temurin-11.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' run: sbt +update - - name: Setup Java (temurin@17) - id: setup-java-temurin-17 - if: matrix.java == 'temurin@17' + - name: Setup Java (temurin@21) + id: setup-java-temurin-21 + if: matrix.java == 'temurin@21' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 17 + java-version: 21 cache: sbt - name: sbt update - if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@21' && steps.setup-java-temurin-21.outputs.cache-hit == 'false' run: sbt +update - name: Download target directories (2.13) @@ -190,7 +190,7 @@ jobs: strategy: matrix: os: [ubuntu-22.04] - java: [temurin@11] + java: [temurin@17] runs-on: ${{ matrix.os }} steps: - name: Checkout current branch (full) @@ -201,30 +201,30 @@ jobs: - name: Setup sbt uses: sbt/setup-sbt@v1 - - name: Setup Java (temurin@11) - id: setup-java-temurin-11 - if: matrix.java == 'temurin@11' + - name: Setup Java (temurin@17) + id: setup-java-temurin-17 + if: matrix.java == 'temurin@17' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 11 + java-version: 17 cache: sbt - name: sbt update - if: matrix.java == 'temurin@11' && steps.setup-java-temurin-11.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' run: sbt +update - - name: Setup Java (temurin@17) - id: setup-java-temurin-17 - if: matrix.java == 'temurin@17' + - name: Setup Java (temurin@21) + id: setup-java-temurin-21 + if: matrix.java == 'temurin@21' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 17 + java-version: 21 cache: sbt - name: sbt update - if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@21' && steps.setup-java-temurin-21.outputs.cache-hit == 'false' run: sbt +update - name: Submit Dependencies diff --git a/README.md b/README.md index 295b07c9..2b4e6711 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,6 @@ libraryDependencies ++= Seq( | `kebs-spray-json` | Spray `JsonFormat` derivation (flat, snakified, >22 fields) | | `kebs-play-json` | Play JSON `Format` instances | | `kebs-circe` | Circe `Encoder` / `Decoder` derivation (snakified/capitalized) | -| `kebs-akka-http` | Akka HTTP unmarshallers + path matchers (Scala 2 only) | | `kebs-pekko-http` | Pekko HTTP unmarshallers + path matchers | | `kebs-http4s` | http4s path/query parameter codecs | | `kebs-http4s-stir` | http4s-stir directives + path matchers | diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/KebsAkkaHttpMatchers.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/KebsAkkaHttpMatchers.scala deleted file mode 100644 index 86b47c6b..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/KebsAkkaHttpMatchers.scala +++ /dev/null @@ -1,21 +0,0 @@ -package pl.iterators.kebs.akkahttp.matchers - -import akka.http.scaladsl.server.PathMatcher1 -import pl.iterators.kebs.core.enums.{EnumLike, ValueEnumLike, ValueEnumLikeEntry} -import pl.iterators.kebs.core.instances.InstanceConverter -import pl.iterators.kebs.core.macros.ValueClassLike - -trait KebsAkkaHttpMatchers extends akka.http.scaladsl.server.PathMatchers { - implicit class SegmentIsomorphism[U](segment: PathMatcher1[U]) { - def as[T](implicit rep: ValueClassLike[T, U]): PathMatcher1[T] = segment.map(rep.apply) - def asValueEnum[T <: ValueEnumLikeEntry[U]](implicit e: ValueEnumLike[U, T]): PathMatcher1[T] = segment.map(e.withValue) - } - - implicit class SegmentConversion[Source](segment: PathMatcher1[Source]) { - def to[Type](implicit ico: InstanceConverter[Type, Source]): PathMatcher1[Type] = segment.map(ico.decode) - } - - implicit class SegmentEnumIsomorphism[U](segment: PathMatcher1[String]) { - def asEnum[T](implicit e: EnumLike[T]): PathMatcher1[T] = segment.map(e.withNameIgnoreCase) - } -} diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/package.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/package.scala deleted file mode 100644 index 17977487..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/package.scala +++ /dev/null @@ -1,3 +0,0 @@ -package pl.iterators.kebs.akkahttp - -package object matchers extends KebsAkkaHttpMatchers diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/KebsAkkaHttpUnmarshallers.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/KebsAkkaHttpUnmarshallers.scala deleted file mode 100644 index b12659ed..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/KebsAkkaHttpUnmarshallers.scala +++ /dev/null @@ -1,79 +0,0 @@ -package pl.iterators.kebs.akkahttp.unmarshallers - -import akka.http.scaladsl.unmarshalling.{FromStringUnmarshaller, Unmarshaller} -import pl.iterators.kebs.core.instances.InstanceConverter -import pl.iterators.kebs.core.macros.ValueClassLike -import akka.http.scaladsl.util.FastFuture -import akka.http.scaladsl.unmarshalling.PredefinedFromStringUnmarshallers._ -import pl.iterators.kebs.core.enums.{EnumLike, ValueEnumLike, ValueEnumLikeEntry} - -trait KebsAkkaHttpEnumUnmarshallers { - private final def enumUnmarshaller[E](`enum`: EnumLike[E]): FromStringUnmarshaller[E] = Unmarshaller { _ => name => - `enum`.withNameInsensitiveOption(name) match { - case Some(enumEntry) => FastFuture.successful(enumEntry) - case None => - FastFuture.failed( - new IllegalArgumentException(s"""Invalid value '$name'. Expected one of: ${`enum`.getNamesToValuesMap.keysIterator - .mkString(", ")}""") - ) - } - } - - implicit def kebsEnumUnmarshaller[E](implicit ev: EnumLike[E]): FromStringUnmarshaller[E] = - enumUnmarshaller(ev) -} - -trait KebsAkkaHttpValueEnumUnmarshallers { - final def valueEnumUnmarshaller[V, E <: ValueEnumLikeEntry[V]](`enum`: ValueEnumLike[V, E]): Unmarshaller[V, E] = Unmarshaller { - _ => v => - `enum`.withValueOption(v) match { - case Some(enumEntry) => FastFuture.successful(enumEntry) - case None => - FastFuture.failed( - new IllegalArgumentException(s"""Invalid value '$v'. Expected one of: ${`enum`.getValuesToEntriesMap.keysIterator - .mkString(", ")}""") - ) - } - } - - implicit def kebsValueEnumUnmarshaller[V, E <: ValueEnumLikeEntry[V]](implicit ev: ValueEnumLike[V, E]): Unmarshaller[V, E] = - valueEnumUnmarshaller(ev) - - implicit def kebsIntValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Int]](implicit - ev: ValueEnumLike[Int, E] - ): FromStringUnmarshaller[E] = - intFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) - implicit def kebsLongValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Long]](implicit - ev: ValueEnumLike[Long, E] - ): FromStringUnmarshaller[E] = - longFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) - implicit def kebsShortValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Short]](implicit - ev: ValueEnumLike[Short, E] - ): FromStringUnmarshaller[E] = - shortFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) - implicit def kebsByteValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Byte]](implicit - ev: ValueEnumLike[Byte, E] - ): FromStringUnmarshaller[E] = - byteFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) -} - -trait KebsAkkaHttpUnmarshallers extends KebsAkkaHttpEnumUnmarshallers with KebsAkkaHttpValueEnumUnmarshallers { - implicit def kebsUnmarshaller[A, B](implicit rep: ValueClassLike[B, A]): Unmarshaller[A, B] = - Unmarshaller.strict[A, B](rep.apply) - @inline - implicit def kebsFromStringUnmarshaller[A, B](implicit - rep: ValueClassLike[B, A], - fsu: FromStringUnmarshaller[A] - ): FromStringUnmarshaller[B] = - fsu andThen kebsUnmarshaller(rep) - - implicit def kebsInstancesUnmarshaller[A, B](implicit ico: InstanceConverter[B, A]): Unmarshaller[A, B] = - Unmarshaller.strict[A, B](ico.decode) - @inline - implicit def kebsInstancesFromStringUnmarshaller[A, B](implicit - ico: InstanceConverter[B, A], - fsu: FromStringUnmarshaller[A] - ): FromStringUnmarshaller[B] = - fsu andThen kebsInstancesUnmarshaller(ico) - -} diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/package.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/package.scala deleted file mode 100644 index 799b2146..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/package.scala +++ /dev/null @@ -1,3 +0,0 @@ -package pl.iterators.kebs.akkahttp - -package object unmarshallers extends KebsAkkaHttpUnmarshallers diff --git a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/domain/AkkaHttpTagsDomain.scala b/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/domain/AkkaHttpTagsDomain.scala deleted file mode 100644 index f6c34f3b..00000000 --- a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/domain/AkkaHttpTagsDomain.scala +++ /dev/null @@ -1,84 +0,0 @@ -package pl.iterators.kebs.akkahttp.domain - -import enumeratum.values.{IntEnum, IntEnumEntry, StringEnum, StringEnumEntry} -import enumeratum.{Enum, EnumEntry} -import pl.iterators.kebs.tag.meta.tagged -import pl.iterators.kebs.tagged._ -import pl.iterators.kebs.core.enums.ValueEnumLikeEntry - -import java.net.URI -import java.util.UUID - -@tagged trait Tags { - trait IdTag - type Id = Long @@ IdTag - - trait TestIdTag - type TestId = UUIDId @@ TestIdTag - - trait TestDoubleTag - type TestDouble = Double @@ TestDoubleTag - - type UUIDId = UUID - object UUIDId { - def generate[T]: UUIDId @@ T = UUID.randomUUID().taggedWith[T] - def fromString[T](str: String): UUIDId @@ T = - UUID.fromString(str).taggedWith[T] - } - - trait TestTaggedUriTag - type TestTaggedUri = URI @@ TestTaggedUriTag - -} - -object Domain extends Tags { - case class I(i: Int) - case class S(s: String) - case class P[A](a: A) - case class CantUnmarshall(s: String, i: Int) - case object O - - sealed trait Greeting extends EnumEntry - object Greeting extends Enum[Greeting] { - case object Hello extends Greeting - case object GoodBye extends Greeting - case object Hi extends Greeting - case object Bye extends Greeting - - val values = findValues - } - - sealed abstract class LibraryItem(val value: Int) extends IntEnumEntry with ValueEnumLikeEntry[Int] - - object LibraryItem extends IntEnum[LibraryItem] { - case object Book extends LibraryItem(1) - case object Movie extends LibraryItem(2) - case object Magazine extends LibraryItem(3) - case object CD extends LibraryItem(4) - - val values = findValues - } - - case class Red(value: Int) - case class Green(value: Int) - case class Blue(value: Int) - case class Color(red: Red, green: Green, blue: Blue) - - sealed abstract class ShirtSize(val value: String) extends StringEnumEntry with ValueEnumLikeEntry[String] - object ShirtSize extends StringEnum[ShirtSize] { - case object Small extends ShirtSize("S") - case object Medium extends ShirtSize("M") - case object Large extends ShirtSize("L") - - val values = findValues - } - - sealed trait SortOrder extends EnumEntry - object SortOrder extends Enum[SortOrder] { - case object Asc extends SortOrder - case object Desc extends SortOrder - - override val values = findValues - } - -} diff --git a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/matchers/AkkaHttpMatchersTests.scala b/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/matchers/AkkaHttpMatchersTests.scala deleted file mode 100644 index 8ae23585..00000000 --- a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/matchers/AkkaHttpMatchersTests.scala +++ /dev/null @@ -1,131 +0,0 @@ -package pl.iterators.kebs.akkahttp.matchers - -import akka.http.scaladsl.server.Directives -import akka.http.scaladsl.testkit.ScalatestRouteTest -import org.scalatest.concurrent.ScalaFutures -import org.scalatest.funsuite.AnyFunSuite -import org.scalatest.matchers.should.Matchers -import pl.iterators.kebs.akkahttp.domain.Domain._ -import pl.iterators.kebs.core.macros.CaseClass1ToValueClass -import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} -import pl.iterators.kebs.instances.net.URIString -import pl.iterators.kebs.instances.time.{DayOfWeekInt, ZonedDateTimeString} -import pl.iterators.kebs.instances.time.mixins.InstantEpochMilliLong - -import java.net.URI -import java.time.{DayOfWeek, Instant, ZonedDateTime} - -class AkkaHttpMatchersTests - extends AnyFunSuite - with Matchers - with Directives - with ScalatestRouteTest - with ScalaFutures - with ZonedDateTimeString - with DayOfWeekInt - with InstantEpochMilliLong - with KebsEnumeratum - with KebsValueEnumeratum - with CaseClass1ToValueClass - with URIString { - - test("No ValueClassLike implicits derived") { - import pl.iterators.kebs.core.macros.ValueClassLike - - "implicitly[ValueClassLike[DayOfWeek, Int]]" shouldNot typeCheck - "implicitly[ValueClassLike[Int, DayOfWeek]]" shouldNot typeCheck - "implicitly[ValueClassLike[Instant, Long]]" shouldNot typeCheck - "implicitly[ValueClassLike[Long, Instant]]" shouldNot typeCheck - "implicitly[ValueClassLike[URI, String]]" shouldNot typeCheck - "implicitly[ValueClassLike[String, URI]]" shouldNot typeCheck - } - - test("Extract String to ZonedDateTime") { - val testRoute = path("test" / Segment.to[ZonedDateTime]) { zdt => - complete(zdt.toString) - } - Get("/test/2011-12-03T10:15:30+01:00") ~> testRoute ~> check { - responseAs[String] shouldEqual "2011-12-03T10:15:30+01:00" - } - } - - test("Extract Int to DayOfWeek") { - val testRoute = path("test" / IntNumber.to[DayOfWeek]) { dayOfWeek => - complete(dayOfWeek.getValue.toString) - } - Get("/test/1") ~> testRoute ~> check { - responseAs[String] shouldEqual "1" - } - } - - test("Extract Long to Instant ") { - val testRoute = path("test" / LongNumber.to[Instant]) { instant => - complete(instant.toEpochMilli.toString) - } - Get("/test/1621258399") ~> testRoute ~> check { - responseAs[String] shouldEqual "1621258399" - } - } - test("Extract Double as tagged Double") { - val testRoute = path("test" / DoubleNumber.as[TestDouble]) { test => - complete(test.toString) - } - Get("/test/1.23") ~> testRoute ~> check { - responseAs[String] shouldEqual "1.23" - } - } - - test("Extract Long as tagged Long") { - val testRoute = path("test" / LongNumber.as[Id]) { id => - complete(id.toString) - } - Get("/test/123456") ~> testRoute ~> check { - responseAs[String] shouldEqual "123456" - } - } - - test("Extract UUID as tagged UUID") { - val testRoute = path("test" / JavaUUID.as[TestId]) { id => - complete(id.toString) - } - Get("/test/ce7a7cf1-8c00-49a9-a963-9fd119dd0642") ~> testRoute ~> check { - responseAs[String] shouldEqual "ce7a7cf1-8c00-49a9-a963-9fd119dd0642" - } - } - - test("Extract String as Enum") { - val testRoute = path("test" / Segment.asEnum[Greeting]) { greeting => - complete(greeting.toString) - } - Get("/test/hello") ~> testRoute ~> check { - responseAs[String] shouldEqual "Hello" - } - } - - test("Extract String as value class") { - val testRoute = path("test" / Segment.as[S]) { item => - complete(item.toString) - } - Get("/test/check") ~> testRoute ~> check { - responseAs[String] shouldEqual "S(check)" - } - } - - test("Extract Int as ValueEnum") { - val testRoute = path("test" / IntNumber.asValueEnum[LibraryItem]) { item => - complete(item.toString) - } - Get("/test/1") ~> testRoute ~> check { - responseAs[String] shouldEqual "Book" - } - } - - test("Extract String to URI as tagged URI") { - val testRoute = path("test" / Segment.to[URI].as[TestTaggedUri]) { id => - complete(id.toString) - } - Get("/test/ce7a7cf1-8c00-49a9-a963-9fd119dd0642") ~> testRoute ~> check { - responseAs[String] shouldEqual "ce7a7cf1-8c00-49a9-a963-9fd119dd0642" - } - } -} diff --git a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/unmarshallers/AkkaHttpUnmarshallersTests.scala b/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/unmarshallers/AkkaHttpUnmarshallersTests.scala deleted file mode 100644 index e2797a1d..00000000 --- a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/unmarshallers/AkkaHttpUnmarshallersTests.scala +++ /dev/null @@ -1,240 +0,0 @@ -package pl.iterators.kebs.akkahttp.unmarshallers - -import akka.http.scaladsl.model.FormData -import akka.http.scaladsl.server.{Directives, MalformedQueryParamRejection} -import akka.http.scaladsl.testkit.ScalatestRouteTest -import akka.http.scaladsl.unmarshalling.Unmarshal -import org.scalatest.concurrent.ScalaFutures -import org.scalatest.funsuite.AnyFunSuite -import org.scalatest.matchers.should.Matchers -import pl.iterators.kebs.akkahttp.domain.Domain.{Blue, Color, Green, Greeting, I, LibraryItem, P, Red, S, ShirtSize, SortOrder} -import pl.iterators.kebs.akkahttp.domain.Domain._ -import pl.iterators.kebs.instances.net.URIString -import pl.iterators.kebs.instances.time.{DayOfWeekInt, YearMonthString} -import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} -import pl.iterators.kebs.core.macros.CaseClass1ToValueClass - -import java.time.{DayOfWeek, YearMonth} - -class AkkaHttpUnmarshallersTests - extends AnyFunSuite - with Matchers - with ScalatestRouteTest - with ScalaFutures - with Directives - with KebsAkkaHttpUnmarshallers - with URIString - with YearMonthString - with DayOfWeekInt - with KebsEnumeratum - with KebsValueEnumeratum - with CaseClass1ToValueClass { - - test("No ValueClassLike implicits derived") { - import pl.iterators.kebs.core.macros.ValueClassLike - - "implicitly[ValueClassLike[URI, String]]" shouldNot typeCheck - "implicitly[ValueClassLike[String, URI]]" shouldNot typeCheck - "implicitly[ValueClassLike[YearMonth, String]]" shouldNot typeCheck - "implicitly[ValueClassLike[String, YearMonth]]" shouldNot typeCheck - "implicitly[ValueClassLike[DayOfWeek, Int]]" shouldNot typeCheck - "implicitly[ValueClassLike[Int, DayOfWeek]]" shouldNot typeCheck - } - - test("Unmarshal") { - Unmarshal(42).to[I].futureValue shouldBe I(42) - Unmarshal("42").to[S].futureValue shouldBe S("42") - } - - test("Unmarshal parametrized") { - Unmarshal("42").to[P[String]].futureValue shouldBe P("42") - } - - test("Unmarshal case object") { - """Unmarshal(42).to[O.type]""" shouldNot typeCheck - } - - test("Unmarshal enum") { - Unmarshal("hello").to[Greeting].futureValue shouldBe Greeting.Hello - Unmarshal("blah").to[Greeting].failed.futureValue shouldBe a[IllegalArgumentException] - } - - test("Unmarshal value enum") { - Unmarshal(3).to[LibraryItem].futureValue shouldBe LibraryItem.Magazine - Unmarshal(5).to[LibraryItem].failed.futureValue shouldBe a[IllegalArgumentException] - } - - test("No unmarshaller for case-classes of arity > 1") { - """Unmarshal("42").to[CantUnmarshall]""" shouldNot typeCheck - } - - test("Unmarshalling value enums is type-safe") { - """Unmarshal(1L).to[LibraryItem]""" shouldNot typeCheck - } - - test("Unmarshal from string") { - Unmarshal("42").to[I].futureValue shouldBe I(42) - } - - test("Unmarshalling parameter") { - val testRoute = parameters(Symbol("i").as[I]) { i => - complete(i.toString) - } - Get("/?i=42") ~> testRoute ~> check { - responseAs[String] shouldEqual "I(42)" - } - } - - test("Unmarshalling optional parameter") { - val testRoute = parameters(Symbol("i").as[I].?) { i => - complete(i.toString) - } - Get("/?i=42") ~> testRoute ~> check { - responseAs[String] shouldEqual "Some(I(42))" - } - } - - test("Unmarshalling enum parameter") { - val testRoute = parameters(Symbol("greeting").as[Greeting]) { greeting => - complete(greeting.toString) - } - Get("/?greeting=hi") ~> testRoute ~> check { - responseAs[String] shouldEqual "Hi" - } - Get("/?greeting=blah") ~> testRoute ~> check { - rejection shouldEqual MalformedQueryParamRejection( - "greeting", - "Invalid value 'blah'. Expected one of: Hello, GoodBye, Hi, Bye", - None - ) - } - } - - test("Unmarshalling value enum parameter") { - val testRoute = parameters(Symbol("libraryItem").as[LibraryItem]) { item => - complete(item.toString) - } - Get("/?libraryItem=1") ~> testRoute ~> check { - responseAs[String] shouldEqual "Book" - } - Get("/?libraryItem=10") ~> testRoute ~> check { - rejection shouldEqual MalformedQueryParamRejection("libraryItem", "Invalid value '10'. Expected one of: 1, 2, 3, 4", None) - } - } - - test("Case class extraction") { - val route = - path("color") { - parameters(Symbol("red").as[Red], Symbol("green").as[Green], Symbol("blue").as[Blue]).as(Color) { color => - complete(color.toString) - } - } - Get("/color?red=1&green=2&blue=3") ~> route ~> check { responseAs[String] shouldEqual "Color(Red(1),Green(2),Blue(3))" } - } - - test("Unmarshalling instances parameter") { - val testRoute = path("instances") { - parameters(Symbol("year").as[YearMonth]) { year => - complete(year.toString) - } - } - Get("/instances?year=2021-05") ~> testRoute ~> check { - responseAs[String] shouldEqual "2021-05" - } - } - - test("Unmarshalling string value enum parameter") { - val testRoute = parameters(Symbol("shirtSize").as[ShirtSize]) { shirtSize => - complete(shirtSize.toString) - } - Get("/?shirtSize=M") ~> testRoute ~> check { - responseAs[String] shouldEqual "Medium" - } - Get("/?shirtSize=XL") ~> testRoute ~> check { - rejection shouldEqual MalformedQueryParamRejection("shirtSize", "Invalid value 'XL'. Expected one of: S, M, L", None) - } - } - - test("bug: work with default enum values") { - val route = - path("test_enum") { - parameter(Symbol("sort").as[SortOrder] ? (SortOrder.Desc: SortOrder)) { sort => - complete { - s"Sort was $sort" - } - } - } - - Get("/test_enum?sort=Asc") ~> route ~> check { - responseAs[String] shouldBe "Sort was Asc" - } - Get("/test_enum") ~> route ~> check { - responseAs[String] shouldBe "Sort was Desc" - } - } - - test("Unmarshal form field from String") { - val route = - path("test_form_fields") { - formFields("yearMonth".as[YearMonth]) { yearMonth => - complete(yearMonth.toString) - } - } - - Post("/test_form_fields", FormData("yearMonth" -> "2021-05")) ~> route ~> check { - responseAs[String] shouldEqual "2021-05" - } - } - - test("Unmarshal form fields from Int") { - val route = - path("test_form_fields") { - formFields("dayOfWeek".as[DayOfWeek]) { dayOfWeek => - complete(dayOfWeek.getValue.toString) - } - } - - Post("/test_form_fields", FormData("dayOfWeek" -> "1")) ~> route ~> check { - responseAs[String] shouldEqual "1" - } - } - - test("Unmarshal tagged parameters from Long") { - val route = - path("test_tagged") { - parameter("tagged".as[Id]) { id => - complete(id.toString) - } - } - - Get("/test_tagged?tagged=123456") ~> route ~> check { - responseAs[String] shouldBe "123456" - } - } - - test("Unmarshal tagged parameters from UUID") { - val route = - path("test_tagged") { - parameter("tagged".as[TestId]) { id => - complete(id.toString) - } - } - - Get("/test_tagged?tagged=ce7a7cf1-8c00-49a9-a963-9fd119dd0642") ~> route ~> check { - responseAs[String] shouldBe "ce7a7cf1-8c00-49a9-a963-9fd119dd0642" - } - } - - test("Unmarshal tagged URI") { - val route = - path("test_tagged") { - parameter("tagged".as[TestTaggedUri]) { id => - complete(id.toString) - } - } - - Get("/test_tagged?tagged=www.test.pl") ~> route ~> check { - responseAs[String] shouldBe "www.test.pl" - } - } -} diff --git a/build.sbt b/build.sbt index 0ef9d17c..eb781f7a 100644 --- a/build.sbt +++ b/build.sbt @@ -1,7 +1,7 @@ import sbt.librarymanagement.ConflictWarning val scala_2_13 = "2.13.18" -val scala_3 = "3.3.9" +val scala_3 = "3.9.0" val mainScalaVersion = scala_3 val supportedScalaVersions = Seq(scala_2_13, scala_3) @@ -17,10 +17,10 @@ ThisBuild / publishTo := { else localStaging.value } -ThisBuild / tlBaseVersion := "2.3" +ThisBuild / tlBaseVersion := "3.0" ThisBuild / tlCiHeaderCheck := false -ThisBuild / tlMimaPreviousVersions := Set("2.2.2") -ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.temurin("11"), JavaSpec.temurin("17")) +ThisBuild / tlMimaPreviousVersions := Set.empty +ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.temurin("17"), JavaSpec.temurin("21")) ThisBuild / githubWorkflowPublishTargetBranches := Seq(RefPredicate.StartsWith(Ref.Tag("v")), RefPredicate.Equals(Ref.Branch("master"))) lazy val baseSettings = Seq( @@ -30,7 +30,7 @@ lazy val baseSettings = Seq( homepage := Some(url("https://github.com/theiterators/kebs")), scalacOptions ++= Seq("-deprecation", "-unchecked", "-feature", "-encoding", "utf8") ++ (if (scalaVersion.value.startsWith("3")) Seq("-Xmax-inlines", "64", "-Yretain-trees") - else Seq.empty) + else Seq("-Xsource:3", "-Wconf:cat=scala3-migration:s")) ) lazy val commonMacroSettings = baseSettings ++ Seq( @@ -110,6 +110,8 @@ def paradiseFlag(scalaVersion: String): Seq[String] = else Seq("-Ymacro-annotations") +val hearthV = "0.4.5" + val scalaTest = Def.setting("org.scalatest" %%% "scalatest" % "3.2.20") val scalaCheck = Def.setting("org.scalacheck" %%% "scalacheck" % "1.19.0") @@ -118,8 +120,8 @@ val slick = "com.typesafe.slick" %% "slick" % "3.6.1" val optionalSlick = optional(slick) val playJson = Def.setting("org.playframework" %%% "play-json" % "3.0.6") val slickPg = "com.github.tminglei" %% "slick-pg" % "0.23.1" -val doobie = "org.tpolecat" %% "doobie-core" % "1.0.0-RC12" -val doobiePg = "org.tpolecat" %% "doobie-postgres" % "1.0.0-RC12" +val doobie = "org.typelevel" %% "doobie-core" % "1.0.0-RC14" +val doobiePg = "org.typelevel" %% "doobie-postgres" % "1.0.0-RC14" val sprayJson = "io.spray" %% "spray-json" % "1.3.6" val circeV = "0.14.17" val circe = Def.setting("io.circe" %%% "circe-core" % circeV) @@ -144,21 +146,6 @@ def enumeratumInExamples = { val optionalEnumeratum = Def.setting("com.beachape" %%% "enumeratum" % enumeratumVersion % "provided") val enumeratumInTest = Def.setting("com.beachape" %%% "enumeratum" % enumeratumVersion % "test") -val akkaVersion = "2.6.20" -val akkaHttpVersion = "10.2.10" -val akkaStream = "com.typesafe.akka" %% "akka-stream" % akkaVersion -val akkaStreamTestkit = "com.typesafe.akka" %% "akka-stream-testkit" % akkaVersion -val akkaHttp = "com.typesafe.akka" %% "akka-http" % akkaHttpVersion -val akkaHttpTestkit = "com.typesafe.akka" %% "akka-http-testkit" % akkaHttpVersion -def akkaHttpInExamples = { - val akkaHttpSprayJson = "com.typesafe.akka" %% "akka-http-spray-json" % akkaHttpVersion - Seq( - akkaStream.cross(CrossVersion.for3Use2_13), - akkaHttp.cross(CrossVersion.for3Use2_13), - akkaHttpSprayJson.cross(CrossVersion.for3Use2_13) - ) -} - val pekkoVersion = "1.7.1" val pekkoHttpVersion = "1.4.2" val pekkoHttpJsonV = "2.0.0" @@ -184,12 +171,12 @@ val pureConfig = "com.github.pureconfig" %% "pureconfig-core" val pureConfigGeneric = "com.github.pureconfig" %% "pureconfig-generic" % pureConfigVersion val pureConfigGenericScala3 = "com.github.pureconfig" %% "pureconfig-generic-scala3" % pureConfigVersion -val scalaJavaTime = Def.setting("io.github.cquiroz" %%% "scala-java-time" % "2.7.0") +val scalaJavaTime = Def.setting("io.github.cquiroz" %%% "scala-java-time" % "2.11.0") lazy val commonSettings = baseSettings ++ Seq( scalacOptions ++= (if (scalaVersion.value.startsWith("3")) - Seq("-language:implicitConversions", "-Ykind-projector", "-Xignore-scala2-macros") + Seq("-language:implicitConversions", "-Xkind-projector", "-Xignore-scala2-macros") else Seq("-language:implicitConversions", "-language:experimental.macros")), // (scalacOptions in Test) ++= Seq("-Ymacro-debug-lite" /*, "-Xlog-implicits"*/ ), libraryDependencies += scalaTest.value % "test" @@ -213,7 +200,15 @@ lazy val doobieSettings = commonSettings ++ Seq( ) lazy val coreSettings = commonMacroSettings ++ Seq( - libraryDependencies += (scalaCheck.value % "test") + libraryDependencies += "com.kubuszok" %%% "hearth" % hearthV, + libraryDependencies ++= (if (scalaVersion.value.startsWith("3")) + Seq(compilerPlugin("com.kubuszok" % "hearth-cross-quotes_3" % hearthV)) + else Nil), + // harmless on hearth's path-dependent Method/Type ADTs + scalacOptions ++= (if (scalaVersion.value.startsWith("3")) Nil + else Seq("-Wconf:msg=The outer reference in this type test cannot be checked at run time:s")), + libraryDependencies += (scalaCheck.value % "test"), + libraryDependencies += (scalaTest.value % "test") ) lazy val enumSettings = commonMacroSettings ++ Seq( @@ -249,14 +244,6 @@ lazy val circeSettings = commonSettings ++ Seq( else Seq(circeAutoExtras.value)) ) -lazy val akkaHttpSettings = commonSettings ++ Seq( - libraryDependencies += (akkaHttp).cross(CrossVersion.for3Use2_13), - libraryDependencies += (akkaStreamTestkit % "test").cross(CrossVersion.for3Use2_13), - libraryDependencies += (akkaHttpTestkit % "test").cross(CrossVersion.for3Use2_13), - libraryDependencies += optionalEnumeratum.value, - scalacOptions ++= paradiseFlag(scalaVersion.value) -) - lazy val pekkoHttpSettings = commonSettings ++ Seq( libraryDependencies += pekkoHttp, libraryDependencies += pekkoStream, @@ -367,7 +354,7 @@ lazy val doobieSupport = project lazy val sprayJsonSupport = project .in(file("spray-json")) - .dependsOn(enumeratumSupport.jvm, instances.jvm % "test -> test") + .dependsOn(enumeratumSupport.jvm, instances.jvm % "test -> test", testkit.jvm % "test -> compile") .settings(sprayJsonSettings *) .settings(publishSettings *) .settings( @@ -381,7 +368,7 @@ lazy val playJsonSupport = crossProject(JSPlatform, JVMPlatform) .withoutSuffixFor(JVMPlatform) .crossType(CrossType.Pure) .in(file("play-json")) - .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test") + .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test", testkit % "test -> compile") .settings(playJsonSettings *) .settings(publishSettings *) .settings( @@ -395,7 +382,7 @@ lazy val circeSupport = crossProject(JSPlatform, NativePlatform, JVMPlatform) .withoutSuffixFor(JVMPlatform) .crossType(CrossType.Pure) .in(file("circe")) - .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test") + .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test", testkit % "test -> compile") .settings(circeSettings *) .settings(crossBuildSettings *) .settings(publishSettings *) @@ -405,19 +392,6 @@ lazy val circeSupport = crossProject(JSPlatform, NativePlatform, JVMPlatform) moduleName := "kebs-circe" ) -lazy val akkaHttpSupport = project - .in(file("akka-http")) - .dependsOn(core.jvm, enumeratumSupport.jvm, instances.jvm % "test -> test", tagged.jvm % "test -> test", taggedMeta.jvm % "test -> test") - .settings(akkaHttpSettings *) - .settings(publishSettings *) - .settings(disableScala(List("3"))) - .settings( - name := "akka-http", - description := "Automatic generation of akka-http deserializers for 1-element case classes", - moduleName := "kebs-akka-http", - crossScalaVersions := supportedScalaVersions - ) - lazy val pekkoHttpSupport = project .in(file("pekko-http")) .dependsOn( @@ -651,6 +625,21 @@ lazy val docs = project ) ) +lazy val testkit = crossProject(JSPlatform, NativePlatform, JVMPlatform) + .withoutSuffixFor(JVMPlatform) + .crossType(CrossType.Pure) + .in(file("testkit")) + .dependsOn(core) + .settings(commonSettings *) + .settings(noPublishSettings *) + .settings( + name := "testkit", + description := "Shared test models and contract suites (not published)", + moduleName := "kebs-testkit", + crossScalaVersions := supportedScalaVersions, + libraryDependencies += enumeratum.value + ) + lazy val kebs = project .in(file(".")) .aggregate( @@ -663,6 +652,9 @@ lazy val kebs = project core.jvm, core.js, core.native, + testkit.jvm, + testkit.js, + testkit.native, baklavaSupport, slickSupport, doobieSupport, @@ -674,7 +666,6 @@ lazy val kebs = project circeSupport.native, jsonschemaSupport, scalacheckSupport, - akkaHttpSupport, pekkoHttpSupport, http4sSupport.jvm, http4sSupport.js, diff --git a/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala b/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala new file mode 100644 index 00000000..5cceca4c --- /dev/null +++ b/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala @@ -0,0 +1,27 @@ +package pl.iterators.kebs.circe.golden + +import io.circe.{Decoder, Encoder, Json} +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.circe.KebsCirce +import pl.iterators.kebs.testkit.model._ + +// Scala 2 only: kebs 2 on Scala 3 does not derive sealed traits +class CirceAdtGoldenTests extends AnyFunSuite with Matchers { + private def json(s: String): Json = io.circe.parser.parse(s).fold(throw _, identity) + + object Default extends KebsCirce + import Default._ + + test("sealed trait - case class child (wrapper object)") { + val value: Shape = Circle(1.0, "c") + implicitly[Encoder[Shape]].apply(value) shouldBe json("""{"Circle":{"r":1.0,"label":"c"}}""") + implicitly[Decoder[Shape]].decodeJson(json("""{"Circle":{"r":1.0,"label":"c"}}""")) shouldBe Right(value) + } + + test("sealed trait - case object child (wrapper object)") { + val value: Shape = Empty + implicitly[Encoder[Shape]].apply(value) shouldBe json("""{"Empty":{}}""") + implicitly[Decoder[Shape]].decodeJson(json("""{"Empty":{}}""")) shouldBe Right(value) + } +} diff --git a/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala new file mode 100644 index 00000000..757a54a9 --- /dev/null +++ b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala @@ -0,0 +1,106 @@ +package pl.iterators.kebs.circe.golden + +import io.circe.{Decoder, Encoder, Json} +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.circe.KebsCirce +import pl.iterators.kebs.circe.enums.{KebsCirceEnums, KebsCirceEnumsLowercase, KebsCirceEnumsUppercase, KebsCirceValueEnums} +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass +import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} +import pl.iterators.kebs.instances.TimeInstances +import pl.iterators.kebs.testkit.model._ + +import java.time.Instant + +// kebs 2.x wire format (verified against v2.3.0); a deliberate change goes to the migration guide, not into these expectations +class CirceGoldenTests extends AnyFunSuite with Matchers { + private def json(s: String): Json = io.circe.parser.parse(s).fold(throw _, identity) + + private def golden[A](value: A, expected: String)(implicit encoder: Encoder[A], decoder: Decoder[A]): Unit = { + encoder(value) shouldBe json(expected) + decoder.decodeJson(json(expected)) shouldBe Right(value) + } + + object Default extends KebsCirce + object Flat extends KebsCirce with CaseClass1ToValueClass + object FlatTime extends KebsCirce with CaseClass1ToValueClass with TimeInstances + object FlatEnums + extends KebsCirce + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsCirceEnums + with KebsCirceValueEnums + object FlatEnumsUppercase + extends KebsCirce + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsCirceEnumsUppercase + with KebsCirceValueEnums + object FlatEnumsLowercase + extends KebsCirce + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsCirceEnumsLowercase + with KebsCirceValueEnums + + test("person default") { + import Default._ + golden(Person(Id("x"), "Ann", 30, None), """{"id":{"value":"x"},"name":"Ann","age":30,"nickname":null}""") + } + + test("person flat") { + import Flat._ + golden(Person(Id("x"), "Ann", 30, Some("A")), """{"id":"x","name":"Ann","age":30,"nickname":"A"}""") + } + + test("naming snakified") { + import pl.iterators.kebs.circe.snakified._ + golden(Naming(1, "a", 2, "u"), """{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}""") + } + + test("naming capitalized") { + import pl.iterators.kebs.circe.capitalized._ + golden(Naming(1, "a", 2, "u"), """{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}""") + } + + test("enums") { + import FlatEnums._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DarkBlue","level":2}""") + } + + test("enums are decoded case-insensitively by default") { + import FlatEnums._ + implicitly[Decoder[Paint]].decodeJson(json("""{"color":"darkblue","level":2}""")) shouldBe Right(Paint(Color.DarkBlue, Level.High)) + } + + test("enums uppercase") { + import FlatEnumsUppercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DARKBLUE","level":2}""") + } + + test("enums lowercase") { + import FlatEnumsLowercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"darkblue","level":2}""") + } + + test("instance converter") { + import FlatTime._ + golden(Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z")), """{"id":"e","at":"2026-01-02T03:04:05Z"}""") + } + + test("wide (>22 fields)") { + import Default._ + golden( + Wide.sample, + """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22,"f23":null}""" + ) + } + + test("private-constructor value class (flat)") { + import Flat._ + golden(Contact(Email.from("a@b.pl"), "n"), """{"email":"a@b.pl","name":"n"}""") + } +} diff --git a/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala new file mode 100644 index 00000000..75fab1ea --- /dev/null +++ b/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -0,0 +1,16 @@ +package pl.iterators.kebs.core.macros + +import pl.iterators.kebs.core.macros.internal.ValueClassLikeMacrosImpl + +import scala.language.experimental.macros +import scala.reflect.macros.whitebox + +private[macros] trait CaseClass1ToValueClassCompat { + implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] = macro ValueClassRepMacros.materializeValueClassRep[VC, F1] +} + +// whitebox, so that the expansion's type fixes F1 left open by the caller +final private[macros] class ValueClassRepMacros(val c: whitebox.Context) extends hearth.MacroCommonsScala2 with ValueClassLikeMacrosImpl { + def materializeValueClassRep[VC <: Product: c.WeakTypeTag, F1: c.WeakTypeTag]: c.Expr[ValueClassLike[VC, F1]] = + c.Expr[ValueClassLike[VC, F1]](deriveValueClassLike[VC].value.tree) +} diff --git a/core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala b/core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala deleted file mode 100644 index b6822885..00000000 --- a/core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala +++ /dev/null @@ -1,34 +0,0 @@ -package pl.iterators.kebs.core.macros - -import scala.language.experimental.macros -import scala.reflect.macros.whitebox - -final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1) - -trait CaseClass1ToValueClass { - implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] = macro ValueClassRepMacros.materializeValueClassRep[VC, F1] -} -object CaseClass1ToValueClass extends CaseClass1ToValueClass - -class ValueClassRepMacros(override val c: whitebox.Context) extends MacroUtils { - import c.universe._ - - def materializeValueClassRep[VC <: Product: c.WeakTypeTag, F1: c.WeakTypeTag]: c.Expr[ValueClassLike[VC, F1]] = { - val ValueClass = weakTypeOf[VC] - assertCaseClass(ValueClass, s"To materialize value class representation, ${ValueClass.typeSymbol} must be a value class") - - ValueClass match { - case Product1(_1) => c.Expr[ValueClassLike[VC, F1]](materializeRep1(ValueClass, _1)) - case _ => c.abort(c.enclosingPosition, "To materialize ValueClassLike, case class must have arity == 1") - } - } - - private def materializeRep1(caseClassType: Type, caseAccessor: MethodSymbol) = { - val f1 = resultType(caseAccessor, caseClassType) - - val unapplyF = q"_.$caseAccessor" - val applyF = apply(caseClassType) - - q"new _root_.pl.iterators.kebs.core.macros.ValueClassLike[$caseClassType, $f1]($applyF, $unapplyF)" - } -} diff --git a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala new file mode 100644 index 00000000..c4347962 --- /dev/null +++ b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -0,0 +1,29 @@ +package pl.iterators.kebs.core.macros + +import pl.iterators.kebs.core.macros.internal.ValueClassLikeMacrosImpl + +import scala.deriving.Mirror +import scala.quoted.* + +private[macros] trait CaseClass1ToValueClassCompat { + // selected via the Mirror, so the macro must not abort: a private/protected constructor or field is not accessible at + // the call site, but the Mirror's fromProduct (generated in the companion) is + inline implicit def repFromCaseClass[T <: Product, F1](using + m: Mirror.ProductOf[T], + teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type + ): ValueClassLike[T, F1] = ${ ValueClassLikeMacros.materialize[T, F1]('m) } +} + +final private[macros] class ValueClassLikeMacros(q: Quotes) extends hearth.MacroCommonsScala3(using q), ValueClassLikeMacrosImpl + +private[macros] object ValueClassLikeMacros { + def materialize[T <: Product: Type, F1: Type](m: Expr[Mirror.ProductOf[T]])(using q: Quotes): Expr[ValueClassLike[T, F1]] = { + val macros = new ValueClassLikeMacros(q) + macros.deriveValueClassLikeWithFallback[T, F1]( + new macros.ProductFallback[T, F1]( + f => '{ $m.fromProduct(Tuple1($f)) }, + t => '{ $t.productElement(0).asInstanceOf[F1] } + ) + ) + } +} diff --git a/core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala b/core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala deleted file mode 100644 index b9b2e5e7..00000000 --- a/core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala +++ /dev/null @@ -1,15 +0,0 @@ -package pl.iterators.kebs.core.macros - -import scala.deriving.Mirror - -final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1) - -trait CaseClass1ToValueClass { - implicit def repFromCaseClass[T <: Product, F1](using - m: Mirror.ProductOf[T], - teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type - ): ValueClassLike[T, F1] = { - new ValueClassLike[T, F1](f1 => m.fromProduct(Tuple1(f1)), _.productElement(0).asInstanceOf[F1]) - } -} -object CaseClass1ToValueClass extends CaseClass1ToValueClass diff --git a/core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala b/core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala new file mode 100644 index 00000000..67bd39ee --- /dev/null +++ b/core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala @@ -0,0 +1,6 @@ +package pl.iterators.kebs.core.macros + +final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1) + +trait CaseClass1ToValueClass extends CaseClass1ToValueClassCompat +object CaseClass1ToValueClass extends CaseClass1ToValueClass diff --git a/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala new file mode 100644 index 00000000..cd17a8fe --- /dev/null +++ b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala @@ -0,0 +1,91 @@ +package pl.iterators.kebs.core.macros.internal + +import hearth.fp.effect.MIO +import hearth.fp.instances.* +import hearth.fp.syntax.* +import pl.iterators.kebs.core.macros.ValueClassLike + +private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => + + final class ProductFallback[T, F](val construct: Expr[F] => Expr[T], val access: Expr[T] => Expr[F]) + + def deriveValueClassLike[T: Type]: Expr_?? = { + val caseClass: CaseClass[T] = CaseClass.parse[T].toOption match { + case Some(cc) => cc + case None => Environment.reportErrorAndAbort(s"${Type[T].prettyPrint} is not a case class") + } + val field: Parameter = singleField(caseClass).getOrElse( + Environment.reportErrorAndAbort(s"To derive ValueClassLike, ${Type[T].prettyPrint} must have exactly one field") + ) + // a nested path (field.tpe.Underlying) breaks cross-quotes on 2.13 + val fieldType: ?? = field.tpe + import fieldType.Underlying as F + implicit val ValueClassLikeType: Type[ValueClassLike[T, F]] = Type.of[ValueClassLike[T, F]] + build[T, F](Some(caseClass), None).as_?? + } + + def deriveValueClassLikeWithFallback[T: Type, F: Type](fallback: ProductFallback[T, F]): Expr[ValueClassLike[T, F]] = { + val caseClass = CaseClass.parse[T].toOption.filter(cc => singleField(cc).exists(_.tpe.Underlying =:= Type[F])) + build[T, F](caseClass, Some(fallback)) + } + + private def singleField[T](caseClass: CaseClass[T]): Option[Parameter] = + caseClass.primaryConstructor.parameters.flatMap(_.values.toList) match { + case single :: Nil => Some(single) + case _ => None + } + + private def build[T: Type, F: Type]( + caseClass: Option[CaseClass[T]], + fallback: Option[ProductFallback[T, F]] + ): Expr[ValueClassLike[T, F]] = { + // companion apply first, so that validating/normalising applys are honoured + def construct(arg: Expr[F]): Expr[T] = + viaCompanionApply[T, F](arg) + .orElse(caseClass.flatMap(viaConstructor[T, F](_, arg))) + .orElse(fallback.map(_.construct(arg))) + .getOrElse(Environment.reportErrorAndAbort(s"${Type[T].prettyPrint} has no accessible apply or constructor")) + + def access(value: Expr[T]): Expr[F] = + caseClass + .flatMap(_.caseFieldValuesAt(value).headOption) + .map { case (_, fieldValue) => + import fieldValue.{Underlying as G, value as extracted} + extracted.asInstanceOf[Expr[F]] + } + .orElse(fallback.map(_.access(value))) + .getOrElse(Environment.reportErrorAndAbort(s"The field of ${Type[T].prettyPrint} is not accessible")) + + Expr.quote { + new ValueClassLike[T, F]( + (f: F) => Expr.splice(construct(Expr.quote(f))), + (t: T) => Expr.splice(access(Expr.quote(t))) + ) + } + } + + private def viaConstructor[T: Type, F: Type](caseClass: CaseClass[T], arg: Expr[F]): Option[Expr[T]] = + caseClass.construct[MIO](_ => MIO.pure(arg.as_??)).unsafe.runSync._2 match { + case Right(Some(constructed)) => Some(constructed) + case _ => None + } + + private def viaCompanionApply[T: Type, F: Type](arg: Expr[F]): Option[Expr[T]] = { + def walk(method: Method): Option[Expr[T]] = method match { + case _: Method.OnInstance => None + case types: Method.ApplyTypes => + val typeParams = types.typeParams.flatten + val typeArgs = Type.typeArguments[T] + if (typeParams.size == typeArgs.size) walk(types.apply(typeParams.zip(typeArgs).toMap)) else None + case values: Method.ApplyValues => + values.parameters.flatMap(_.toList) match { + case (name, param) :: Nil if param.tpe.Underlying =:= Type[F] => walk(values.apply(Map(name -> arg.as_??))) + case _ => None + } + case result: Method.Result[?] => + import result.Returned + if (Returned <:< Type[T]) result.build().toOption.map(_.asInstanceOf[Expr[T]]) else None + } + Type[T].unsortedMethodsNamed("apply").iterator.filter(_.isAvailable(AtCallSite)).map(walk).collectFirst { case Some(e) => e } + } +} diff --git a/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala b/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala new file mode 100644 index 00000000..24eb177d --- /dev/null +++ b/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala @@ -0,0 +1,18 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass + +object ValueClassLikeScala2SelectionDomain { + final case class PrivateField(private val value: Int) +} + +// a private case field has no accessor on Scala 2: no instance, as in kebs 2 +class ValueClassLikeScala2SelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeScala2SelectionDomain._ + + test("case class with a private field falls back silently") { + implicitly[Pick[PrivateField]].chosen shouldBe "fallback" + } +} diff --git a/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala b/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala new file mode 100644 index 00000000..02f496e7 --- /dev/null +++ b/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala @@ -0,0 +1,30 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} + +object ValueClassLikeScala3SelectionDomain { + final case class ProtectedCtor protected (value: Int) + object ProtectedCtor { + def from(value: Int): ProtectedCtor = new ProtectedCtor(value) + } + final case class PrivateField(private val value: Int) +} + +// Scala 3 has a Mirror for these, so kebs 2 derived them via Mirror.fromProduct; kebs 3 must not lose them +class ValueClassLikeScala3SelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeScala3SelectionDomain._ + + test("protected-constructor value class gets the flat instance and round-trips") { + implicitly[Pick[ProtectedCtor]].chosen shouldBe "flat" + val rep = implicitly[ValueClassLike[ProtectedCtor, Int]] + rep.unapply(rep.apply(5)) shouldBe 5 + } + + test("case class with a private field gets the flat instance and round-trips") { + implicitly[Pick[PrivateField]].chosen shouldBe "flat" + val rep = implicitly[ValueClassLike[PrivateField, Int]] + rep.unapply(rep.apply(7)) shouldBe 7 + } +} diff --git a/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala new file mode 100644 index 00000000..8aedc42d --- /dev/null +++ b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala @@ -0,0 +1,51 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} + +// flat formats are searched like this everywhere in kebs: no ValueClassLike must mean the fallback, never a compile error +final class Pick[A](val chosen: String) +trait LowPriorityPick { + implicit def fallback[A]: Pick[A] = new Pick[A]("fallback") +} +object Pick extends LowPriorityPick { + implicit def flat[T, A](implicit rep: ValueClassLike[T, A]): Pick[T] = new Pick[T]("flat") +} + +object ValueClassLikeSelectionDomain { + final case class Plain(value: String) + final case class Two(a: Int, b: Int) + final class NotCase(val value: Int) + final case class PrivateCtor private (value: String) + object PrivateCtor { + def from(value: String): PrivateCtor = new PrivateCtor(value) + } + final case class MultiList(a: Int)(val b: Int) +} + +class ValueClassLikeSelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeSelectionDomain._ + + test("single-field case class gets the flat instance") { + implicitly[Pick[Plain]].chosen shouldBe "flat" + } + + test("2-field case class falls back silently") { + implicitly[Pick[Two]].chosen shouldBe "fallback" + } + + test("non-case class falls back silently") { + implicitly[Pick[NotCase]].chosen shouldBe "fallback" + } + + test("private-constructor value class gets the flat instance and round-trips") { + implicitly[Pick[PrivateCtor]].chosen shouldBe "flat" + val rep = implicitly[ValueClassLike[PrivateCtor, String]] + rep.unapply(rep.apply("x")) shouldBe "x" + } + + test("case class with several parameter lists never fails compilation") { + implicitly[Pick[MultiList]].chosen should (equal("flat") or equal("fallback")) + } +} diff --git a/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala new file mode 100644 index 00000000..42dacdf2 --- /dev/null +++ b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala @@ -0,0 +1,56 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} + +object ValueClassLikeTestDomain { + final case class Plain(value: String) + final case class Box[A](a: A) + final case class Positive(value: Int) + object Positive { + def apply(value: Int): Positive = { + require(value > 0, "must be positive") + new Positive(value) + } + } + final case class Email(value: String) + object Email { + def apply(value: String): Email = new Email(value.toLowerCase) + } + final case class Two(a: Int, b: Int) + final class NotCase(val value: Int) +} + +class ValueClassLikeTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeTestDomain._ + + test("derives apply/unapply for a single-field case class") { + val rep = implicitly[ValueClassLike[Plain, String]] + rep.apply("a") shouldBe Plain("a") + rep.unapply(Plain("b")) shouldBe "b" + } + + test("infers the field type through an outer implicit") { + def find[T, A](implicit rep: ValueClassLike[T, A]): ValueClassLike[T, A] = rep + find[Plain, String].unapply(Plain("c")) shouldBe "c" + } + + test("generic case class") { + implicitly[ValueClassLike[Box[Int], Int]].apply(1) shouldBe Box(1) + } + + test("uses the companion apply (validation)") { + val rep = implicitly[ValueClassLike[Positive, Int]] + an[IllegalArgumentException] should be thrownBy rep.apply(-1) + } + + test("uses the companion apply (normalisation)") { + implicitly[ValueClassLike[Email, String]].apply("A@B.PL").value shouldBe "a@b.pl" + } + + test("no instance for a 2-field case class or a non-case class") { + assertDoesNotCompile("implicitly[ValueClassLike[Two, Int]]") + assertDoesNotCompile("implicitly[ValueClassLike[NotCase, Int]]") + } +} diff --git a/docs/core-concepts.md b/docs/core-concepts.md index fdbe0f06..0c78ce5e 100644 --- a/docs/core-concepts.md +++ b/docs/core-concepts.md @@ -5,7 +5,7 @@ title: Core Concepts # Core Concepts -Kebs is built on four typeclasses. Each integration module (circe, slick, akka-http, etc.) provides implicit derivation rules that delegate to these. +Kebs is built on four typeclasses. Each integration module (circe, slick, pekko-http, etc.) provides implicit derivation rules that delegate to these. ## ValueClassLike[VC, F1] diff --git a/docs/http4s.md b/docs/http4s.md index 17d04c41..b508164c 100644 --- a/docs/http4s.md +++ b/docs/http4s.md @@ -106,4 +106,4 @@ import pl.iterators.kebs.http4sstir.matchers.KebsHttp4sStirMatchers // or: import pl.iterators.kebs.http4sstir.matchers._ ``` -Same extension methods as [Akka/Pekko HTTP matchers](akka-http.md#path-matchers): `.as[T]`, `.to[T]`, `.asEnum[T]`, `.asValueEnum[T]`, and chaining (`.to[URI].as[TaggedUri]`). +Same extension methods as [Pekko HTTP matchers](pekko-http.md#path-matchers): `.as[T]`, `.to[T]`, `.asEnum[T]`, `.asValueEnum[T]`, and chaining (`.to[URI].as[TaggedUri]`). diff --git a/docs/akka-http.md b/docs/pekko-http.md similarity index 83% rename from docs/akka-http.md rename to docs/pekko-http.md index 5c6b89e1..8ca8b584 100644 --- a/docs/akka-http.md +++ b/docs/pekko-http.md @@ -1,19 +1,15 @@ --- sidebar_position: 12 -title: Akka HTTP / Pekko HTTP +title: Pekko HTTP --- -# kebs-akka-http / kebs-pekko-http +# kebs-pekko-http -Automatic unmarshallers and path matchers for Akka HTTP and Pekko HTTP. +Automatic unmarshallers and path matchers for Pekko HTTP. ## Setup ```scala -// Akka HTTP (Scala 2 only) -libraryDependencies += "pl.iterators" %% "kebs-akka-http" % kebsVersion - -// Pekko HTTP (Scala 2 & 3) libraryDependencies += "pl.iterators" %% "kebs-pekko-http" % kebsVersion ``` @@ -46,12 +42,6 @@ val formRoute = post { } ``` -For Akka HTTP, use `KebsAkkaHttpUnmarshallers` instead: - -```scala -import pl.iterators.kebs.akkahttp.unmarshallers.KebsAkkaHttpUnmarshallers -``` - ## Path matchers A separate `matchers` package provides typed path segment extraction via extension methods on `PathMatcher1`: @@ -59,9 +49,6 @@ A separate `matchers` package provides typed path segment extraction via extensi ```scala import pl.iterators.kebs.pekkohttp.matchers.KebsPekkoHttpMatchers // or: import pl.iterators.kebs.pekkohttp.matchers._ - -// For Akka HTTP: -// import pl.iterators.kebs.akkahttp.matchers.KebsAkkaHttpMatchers ``` ### `.as[T]` — value class wrapping diff --git a/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala b/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala index 453858a4..a0ae7133 100644 --- a/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala +++ b/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala @@ -1,6 +1,6 @@ package pl.iterators.kebs.doobie -import doobie.Meta +import org.typelevel.doobie.Meta import pl.iterators.kebs.core.instances.InstanceConverter import pl.iterators.kebs.core.macros.ValueClassLike diff --git a/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala b/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala index 3c56bb5d..af5eeef3 100644 --- a/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala +++ b/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala @@ -1,6 +1,6 @@ package pl.iterators.kebs.doobie.enums -import doobie.Meta +import org.typelevel.doobie.Meta import pl.iterators.kebs.core.enums.{EnumLike, ValueEnumLike, ValueEnumLikeEntry} import scala.reflect.ClassTag diff --git a/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala b/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala index 34452e4a..be7c2b5c 100644 --- a/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala +++ b/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala @@ -2,10 +2,10 @@ package pl.iterators.kebs.doobie import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers -import doobie._ -import doobie.implicits._ -import doobie.postgres._ -import doobie.postgres.implicits._ +import org.typelevel.doobie._ +import org.typelevel.doobie.implicits._ +import org.typelevel.doobie.postgres._ +import org.typelevel.doobie.postgres.implicits._ import pl.iterators.kebs.core.macros.CaseClass1ToValueClass import pl.iterators.kebs.doobie.enums._ import pl.iterators.kebs.doobie._ diff --git a/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala new file mode 100644 index 00000000..1c1a2c3c --- /dev/null +++ b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala @@ -0,0 +1,66 @@ +package pl.iterators.kebs.playjson.golden + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass +import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} +import pl.iterators.kebs.instances.TimeInstances +import pl.iterators.kebs.playjson.KebsPlayJson +import pl.iterators.kebs.testkit.model._ +import play.api.libs.json._ + +import java.time.Instant + +// kebs 2.x output next to user-written Json.format codecs (verified against v2.3.0); those codecs must keep winning over derivation +class PlayJsonGoldenTests extends AnyFunSuite with Matchers { + private def golden[A](value: A, expected: String)(implicit format: Format[A]): Unit = { + format.writes(value) shouldBe Json.parse(expected) + format.reads(Json.parse(expected)) shouldBe JsSuccess(value) + } + + object Flat extends KebsPlayJson with CaseClass1ToValueClass with KebsEnumeratum with KebsValueEnumeratum with TimeInstances + + test("flat value class") { + import Flat._ + golden(Id("x"), "\"x\"") + } + + test("user Json.format with kebs field formats") { + import Flat._ + implicit val personFormat: OFormat[Person] = Json.format[Person] + golden(Person(Id("x"), "Ann", 30, None), """{"id":"x","name":"Ann","age":30}""") + } + + test("enums") { + import Flat._ + import pl.iterators.kebs.playjson.enums._ + implicit val paintFormat: OFormat[Paint] = Json.format[Paint] + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DarkBlue","level":2}""") + } + + test("enums uppercase") { + import Flat._ + import pl.iterators.kebs.playjson.enums.uppercase._ + implicit val paintFormat: OFormat[Paint] = Json.format[Paint] + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DARKBLUE","level":2}""") + } + + test("enums lowercase") { + import Flat._ + import pl.iterators.kebs.playjson.enums.lowercase._ + implicit val paintFormat: OFormat[Paint] = Json.format[Paint] + golden(Paint(Color.DarkBlue, Level.High), """{"color":"darkblue","level":2}""") + } + + test("instance converter") { + import Flat._ + implicit val eventFormat: OFormat[Event] = Json.format[Event] + golden(Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z")), """{"id":"e","at":"2026-01-02T03:04:05Z"}""") + } + + test("private-constructor value class (flat)") { + import Flat._ + implicit val contactFormat: OFormat[Contact] = Json.format[Contact] + golden(Contact(Email.from("a@b.pl"), "n"), """{"email":"a@b.pl","name":"n"}""") + } +} diff --git a/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala new file mode 100644 index 00000000..f5cff4d2 --- /dev/null +++ b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala @@ -0,0 +1,116 @@ +package pl.iterators.kebs.sprayjson.golden + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass +import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} +import pl.iterators.kebs.instances.TimeInstances +import pl.iterators.kebs.sprayjson.{KebsSprayJson, KebsSprayJsonEnums, KebsSprayJsonValueEnums} +import pl.iterators.kebs.sprayjson.enums.{KebsSprayJsonEnumsLowercase, KebsSprayJsonEnumsUppercase} +import pl.iterators.kebs.testkit.model._ +import spray.json._ + +import java.time.Instant + +// kebs 2.x wire format (verified against v2.3.0); a deliberate change goes to the migration guide, not into these expectations +class SprayGoldenTests extends AnyFunSuite with Matchers { + private def golden[A](value: A, expected: String)(implicit format: JsonFormat[A]): Unit = { + format.write(value) shouldBe expected.parseJson + format.read(expected.parseJson) shouldBe value + } + + object Default extends DefaultJsonProtocol with KebsSprayJson + object Flat extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass + object FlatNulls extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass with NullOptions + object FlatTime extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass with TimeInstances + object FlatEnums + extends DefaultJsonProtocol + with KebsSprayJson + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsSprayJsonEnums + with KebsSprayJsonValueEnums + object FlatEnumsUppercase + extends DefaultJsonProtocol + with KebsSprayJson + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsSprayJsonEnumsUppercase + with KebsSprayJsonValueEnums + object FlatEnumsLowercase + extends DefaultJsonProtocol + with KebsSprayJson + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsSprayJsonEnumsLowercase + with KebsSprayJsonValueEnums + + test("person default") { + import Default._ + golden(Person(Id("x"), "Ann", 30, None), """{"id":{"value":"x"},"name":"Ann","age":30}""") + } + + test("person flat") { + import Flat._ + golden(Person(Id("x"), "Ann", 30, Some("A")), """{"id":"x","name":"Ann","age":30,"nickname":"A"}""") + } + + test("person NullOptions") { + import FlatNulls._ + golden(Person(Id("x"), "Ann", 30, None), """{"id":"x","name":"Ann","age":30,"nickname":null}""") + } + + test("naming snakified") { + import pl.iterators.kebs.sprayjson.snakified._ + golden(Naming(1, "a", 2, "u"), """{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}""") + } + + test("naming capitalized") { + import pl.iterators.kebs.sprayjson.capitalized._ + golden(Naming(1, "a", 2, "u"), """{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}""") + } + + test("enums") { + import FlatEnums._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DarkBlue","level":2}""") + } + + test("enums uppercase") { + import FlatEnumsUppercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DARKBLUE","level":2}""") + } + + test("enums lowercase") { + import FlatEnumsLowercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"darkblue","level":2}""") + } + + test("instance converter") { + import FlatTime._ + golden(Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z")), """{"id":"e","at":"2026-01-02T03:04:05Z"}""") + } + + test("wide (>22 fields)") { + import Default._ + golden( + Wide.sample, + """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22}""" + ) + } + + test("wide NullOptions") { + import FlatNulls._ + golden( + Wide.sample, + """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22,"f23":null}""" + ) + } + + test("private-constructor value class (flat)") { + import Flat._ + golden(Contact(Email.from("a@b.pl"), "n"), """{"email":"a@b.pl","name":"n"}""") + } +} diff --git a/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala new file mode 100644 index 00000000..d403cf8e --- /dev/null +++ b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala @@ -0,0 +1,70 @@ +package pl.iterators.kebs.testkit + +import enumeratum.values.{IntEnum, IntEnumEntry} +import enumeratum.{Enum, EnumEntry} +import pl.iterators.kebs.core.enums.ValueEnumLikeEntry + +import java.time.Instant + +// a separate module on purpose: derivation must also work for types read from the classpath +object model { + final case class Id(value: String) + final case class Person(id: Id, name: String, age: Int, nickname: Option[String]) + final case class Naming(someField: Int, anotherFieldName: String, field1Name: Int, httpURL: String) + final case class Event(id: Id, at: Instant) + + final case class Email private (value: String) + object Email { + def from(value: String): Email = new Email(value.toLowerCase) + } + final case class Contact(email: Email, name: String) + + final case class Wide( + f1: Int, + f2: Int, + f3: Int, + f4: Int, + f5: Int, + f6: Int, + f7: Int, + f8: Int, + f9: Int, + f10: Int, + f11: Int, + f12: Int, + f13: Int, + f14: Int, + f15: Int, + f16: Int, + f17: Int, + f18: Int, + f19: Int, + f20: Int, + f21: Int, + f22: Int, + f23: Option[String] + ) + object Wide { + val sample: Wide = Wide(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, None) + } + + sealed abstract class Color extends EnumEntry + object Color extends Enum[Color] { + case object Red extends Color + case object DarkBlue extends Color + val values = findValues + } + + sealed abstract class Level(val value: Int) extends IntEnumEntry with ValueEnumLikeEntry[Int] + object Level extends IntEnum[Level] { + case object Low extends Level(1) + case object High extends Level(2) + val values = findValues + } + + final case class Paint(color: Color, level: Level) + + sealed trait Shape + final case class Circle(r: Double, label: String) extends Shape + case object Empty extends Shape +}