Skip to content

Commit

Permalink
add test case for BigDecimal's codec (zio#663)
Browse files Browse the repository at this point in the history
  • Loading branch information
abhishek818 committed Jun 12, 2024
1 parent 6dada71 commit 6fff70a
Showing 1 changed file with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import org.bson.codecs.{ Codec => BCodec, DecoderContext, EncoderContext }
import org.bson.conversions.Bson
import org.bson.io.BasicOutputBuffer
import org.bson.types.ObjectId
import org.bson.BsonDecimal128
import org.bson.types.Decimal128

import zio.bson.BsonBuilder._
import zio.bson._
Expand All @@ -24,6 +26,13 @@ object BsonSchemaCodecSpec extends ZIOSpecDefault {
implicit lazy val codec: BsonCodec[SimpleClass] = BsonSchemaCodec.bsonCodec(schema)
}

case class BigDecimalClass(value: BigDecimal)

object BigDecimalClass {
implicit val schema: Schema[BigDecimalClass] = DeriveSchema.gen
implicit lazy val codec: BsonCodec[BigDecimalClass] = BsonSchemaCodec.bsonCodec(schema)
}

sealed trait Tree

object Tree {
Expand Down Expand Up @@ -79,6 +88,11 @@ object BsonSchemaCodecSpec extends ZIOSpecDefault {
} yield Customer(id, name, age, friends)
}

// Custom generator for BigDecimal values with rounding to ensure exact representation as Decimal128
def genRoundedBigDecimal(scale: Int): Gen[Any, BigDecimal] = {
Gen.double.map(d => BigDecimal(d).setScale(scale, BigDecimal.RoundingMode.HALF_UP))
}

def spec: Spec[TestEnvironment with Scope, Any] = suite("BsonSchemaCodecSpec")(
suite("round trip")(
roundTripTest("SimpleClass")(
Expand Down Expand Up @@ -107,6 +121,12 @@ object BsonSchemaCodecSpec extends ZIOSpecDefault {
Customer.example.invitedFriends.map(_.value.toBsonValue): _*
)
)
),
roundTripTest("BigDecimalClass")(
// 14 decimal places in the assert value below
genRoundedBigDecimal(14).map(BigDecimalClass(_)),
BigDecimalClass(BigDecimal("279.00000000000000")),
doc("value" -> new BsonDecimal128(Decimal128.parse("279.00000000000000")))
)
),
suite("configuration")(
Expand Down

0 comments on commit 6fff70a

Please sign in to comment.