All checks were successful
/ Build and Release Library (push) Successful in 1m24s
Reviewed-on: #4
106 lines
2.7 KiB
Scala
106 lines
2.7 KiB
Scala
package gs.hex.v0
|
|
|
|
import java.security.SecureRandom
|
|
import java.util.UUID
|
|
|
|
class EncodeDecodeTests extends munit.FunSuite:
|
|
|
|
val Rng = new SecureRandom()
|
|
val MinLength = 1
|
|
val MaxLength = 100
|
|
|
|
test("should encode/decode using summoners") {
|
|
(0 to 10).foreach { _ =>
|
|
val data = randomByteArray()
|
|
val encoded = HexEncode[Array[Byte]].toHexString(data)
|
|
val decoded = HexDecode[Array[Byte]].fromHexString(encoded)
|
|
assert(decoded.isDefined)
|
|
assert(decoded.map(_.sameElements(data)).getOrElse(false))
|
|
}
|
|
}
|
|
|
|
test("should encode/decode byte arrays") {
|
|
(0 to 10).foreach { _ =>
|
|
val data = randomByteArray()
|
|
val encoded = encode(data)
|
|
val decoded = decode[Array[Byte]](encoded)
|
|
assert(decoded.isDefined)
|
|
assert(decoded.map(_.sameElements(data)).getOrElse(false))
|
|
}
|
|
}
|
|
|
|
test("should encode/decode strings") {
|
|
(0 to 10).foreach { _ =>
|
|
val data = UUID.randomUUID().toString()
|
|
val encoded = encode(data)
|
|
val decoded = decode[String](encoded)
|
|
assert(decoded == Some(data))
|
|
}
|
|
}
|
|
|
|
test("should encode/decode boolean values") {
|
|
val et = encode(true)
|
|
val dt = decode[Boolean](et)
|
|
assert(dt == Some(true))
|
|
val ef = encode(false)
|
|
val df = decode[Boolean](ef)
|
|
assert(df == Some(false))
|
|
}
|
|
|
|
test("should encode/decode integers") {
|
|
(0 to 10).foreach { _ =>
|
|
val data = Rng.nextInt(9999)
|
|
val encoded = encode(data)
|
|
val decoded = decode[Int](encoded)
|
|
assert(decoded == Some(data))
|
|
}
|
|
}
|
|
|
|
test("should encode/decode longs") {
|
|
(0 to 10).foreach { _ =>
|
|
val data = Rng.nextLong(9999L)
|
|
val encoded = encode(data)
|
|
val decoded = decode[Long](encoded)
|
|
assert(decoded == Some(data))
|
|
}
|
|
}
|
|
|
|
test("should fail to decode invalid data to byte arrays") {
|
|
assert(decode[Array[Byte]]("!") == None)
|
|
}
|
|
|
|
test("should fail to decode invalid data to strings") {
|
|
assert(decode[String]("!") == None)
|
|
}
|
|
|
|
test("should fail to decode invalid data to bools") {
|
|
assert(decode[Boolean]("!") == None)
|
|
}
|
|
|
|
test("should fail to decode invalid data to integers") {
|
|
assert(decode[Int]("!") == None)
|
|
}
|
|
|
|
test("should fail to decode invalid data to longs") {
|
|
assert(decode[Long]("!") == None)
|
|
}
|
|
|
|
private def encode[A](
|
|
data: A
|
|
)(
|
|
using
|
|
H: HexEncode[A]
|
|
): String = H.toHexString(data)
|
|
|
|
private def decode[A](
|
|
data: String
|
|
)(
|
|
using
|
|
H: HexDecode[A]
|
|
): Option[A] = H.fromHexString(data)
|
|
|
|
private def randomByteArray(): Array[Byte] =
|
|
val length = Rng.nextInt(MaxLength) + MinLength
|
|
val bytes = new Array[Byte](length)
|
|
val _ = Rng.nextBytes(bytes)
|
|
bytes
|