truncation_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package bson
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. "go.mongodb.org/mongo-driver/bson/bsoncodec"
  6. )
  7. type inputArgs struct {
  8. Name string
  9. Val *float64
  10. }
  11. type outputArgs struct {
  12. Name string
  13. Val *int64
  14. }
  15. func TestTruncation(t *testing.T) {
  16. t.Run("truncation", func(t *testing.T) {
  17. inputName := "truncation"
  18. inputVal := 4.7892
  19. input := inputArgs{Name: inputName, Val: &inputVal}
  20. ec := bsoncodec.EncodeContext{Registry: DefaultRegistry}
  21. doc, err := MarshalWithContext(ec, &input)
  22. assert.Nil(t, err)
  23. var output outputArgs
  24. dc := bsoncodec.DecodeContext{
  25. Registry: DefaultRegistry,
  26. Truncate: true,
  27. }
  28. err = UnmarshalWithContext(dc, doc, &output)
  29. assert.Nil(t, err)
  30. assert.Equal(t, inputName, output.Name)
  31. assert.Equal(t, int64(inputVal), *output.Val)
  32. })
  33. t.Run("no truncation", func(t *testing.T) {
  34. inputName := "no truncation"
  35. inputVal := 7.382
  36. input := inputArgs{Name: inputName, Val: &inputVal}
  37. ec := bsoncodec.EncodeContext{Registry: DefaultRegistry}
  38. doc, err := MarshalWithContext(ec, &input)
  39. assert.Nil(t, err)
  40. var output outputArgs
  41. dc := bsoncodec.DecodeContext{
  42. Registry: DefaultRegistry,
  43. Truncate: false,
  44. }
  45. // case throws an error when truncation is disabled
  46. err = UnmarshalWithContext(dc, doc, &output)
  47. assert.NotNil(t, err)
  48. })
  49. }