Skip to content

Commit

Permalink
Merge pull request #498 from RustedBones/tc-serialization-test-scal2
Browse files Browse the repository at this point in the history
[scala2] Add test for serializable generated type-class
  • Loading branch information
adamw authored Nov 13, 2023
2 parents b038dfe + 8932d0c commit 3d99434
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion examples/src/main/scala/magnolia1/examples/show.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import scala.language.experimental.macros
*
* Note that this is a more general form of `Show` than is usual, as it permits the return type to be something other than a string.
*/
trait Show[Out, T] { def show(value: T): Out }
trait Show[Out, T] extends Serializable { def show(value: T): Out }

trait GenericShow[Out] {

Expand Down
27 changes: 27 additions & 0 deletions test/src/test/scala/magnolia1/tests/tests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package magnolia1.tests
import magnolia1.TypeName
import magnolia1.examples._

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}
import java.time.LocalDate
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
Expand Down Expand Up @@ -243,6 +244,12 @@ case class Bar(

case class Hamster(name: String, age: Int, likesNuts: Boolean, @MyAnnotation(4) likesVeggies: Boolean) extends Rodent

// not serializable outer
class Outer {
val showAddress: Show[String, Address] = Show.gen
val showColor: Show[String, Color] = Show.gen
}

class Tests extends munit.FunSuite {

test("construct a Show product instance with alternative apply functions") {
Expand Down Expand Up @@ -857,4 +864,24 @@ class Tests extends munit.FunSuite {
val res = Show.gen[Bar].show(Bar("foo", "bar"))
assertEquals(res, "Bar(foo{MyAnnotation(2),MyAnnotation(1)}=foo,bar{MyAnnotation(2),MyAnnotation(1)}=bar)")
}

private def serializeToByteArray(value: Serializable): Array[Byte] = {
val buffer = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(buffer)
oos.writeObject(value)
buffer.toByteArray
}

private def deserializeFromByteArray(encodedValue: Array[Byte]): AnyRef = {
val ois = new ObjectInputStream(new ByteArrayInputStream(encodedValue))
ois.readObject()
}

def ensureSerializable[T <: Serializable](value: T): T =
deserializeFromByteArray(serializeToByteArray(value)).asInstanceOf[T]

test("generate serializable type-classes") {
ensureSerializable(new Outer().showAddress)
ensureSerializable(new Outer().showColor)
}
}

0 comments on commit 3d99434

Please sign in to comment.