Skip to content

Commit 4028be8

Browse files
author
Alice Thum
committed
Add truncation check to DecodeValue.
GODRIVER-1233 Change-Id: Ie1b85a73ba7e0eb3b387d596d654eb4da2082cf1
1 parent 5cb4398 commit 4028be8

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

bson/bsoncodec/struct_codec.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val r
195195
}
196196
field = field.Addr()
197197

198-
dctx := DecodeContext{Registry: r.Registry, Truncate: fd.truncate}
198+
dctx := DecodeContext{Registry: r.Registry, Truncate: fd.truncate || r.Truncate}
199199
if fd.decoder == nil {
200200
return ErrNoDecoder{Type: field.Elem().Type()}
201201
}

bson/truncation_test.go

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

0 commit comments

Comments
 (0)