Skip to content

Commit

Permalink
Typeclass serialization tests
Browse files Browse the repository at this point in the history
  • Loading branch information
RustedBones committed Nov 13, 2023
1 parent 36d8479 commit d4fa285
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/examples/show.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import magnolia1._
*
* 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] extends AutoDerivation[[X] =>> Show[Out, X]] {

Expand Down
43 changes: 43 additions & 0 deletions src/test/SerializationTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package magnolia1.tests

import magnolia1.*
import magnolia1.examples.*

import java.io.*
class SerializationTests extends munit.FunSuite:
import SerializationTests.*

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)
}

object SerializationTests:
sealed trait Entity
case class Company(name: String) extends Entity
case class Person(name: String, age: Int) extends Entity
case class Address(line1: String, occupant: Person)

sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color
case object Orange extends Color
case object Pink extends Color
class Outer:
val showAddress: Show[String, Address] = summon[Show[String, Address]]
val showColor: Show[String, Color] = summon[Show[String, Color]]

0 comments on commit d4fa285

Please sign in to comment.