Skip to content

Commit b2dd6bf

Browse files
author
Divjot Arora
committed
add tests
1 parent 46b4326 commit b2dd6bf

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

bson/bsoncodec/default_value_decoders_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3558,6 +3558,56 @@ func TestDefaultValueDecoders(t *testing.T) {
35583558
"expected error %v to contain key pattern %s", decodeErr, keyPath)
35593559
})
35603560
})
3561+
3562+
t.Run("values are converted", func(t *testing.T) {
3563+
// When decoding into a D or M, values must be converted if they are not being decoded to the default type.
3564+
3565+
t.Run("D", func(t *testing.T) {
3566+
trueValue := bsoncore.Value{
3567+
Type: bsontype.Boolean,
3568+
Data: bsoncore.AppendBoolean(nil, true),
3569+
}
3570+
docBytes := bsoncore.BuildDocumentFromElements(nil,
3571+
bsoncore.AppendBooleanElement(nil, "bool", true),
3572+
bsoncore.BuildArrayElement(nil, "boolArray", trueValue),
3573+
)
3574+
3575+
rb := NewRegistryBuilder()
3576+
defaultValueDecoders.RegisterDefaultDecoders(rb)
3577+
reg := rb.RegisterTypeMapEntry(bsontype.Boolean, reflect.TypeOf(mybool(true))).Build()
3578+
3579+
dc := DecodeContext{Registry: reg}
3580+
vr := bsonrw.NewBSONDocumentReader(docBytes)
3581+
val := reflect.New(tD).Elem()
3582+
err := defaultValueDecoders.DDecodeValue(dc, vr, val)
3583+
assert.Nil(t, err, "DDecodeValue error: %v", err)
3584+
3585+
want := primitive.D{
3586+
{"bool", mybool(true)},
3587+
{"boolArray", primitive.A{mybool(true)}},
3588+
}
3589+
got := val.Interface().(primitive.D)
3590+
assert.Equal(t, want, got, "want document %v, got %v", want, got)
3591+
})
3592+
t.Run("M", func(t *testing.T) {
3593+
docBytes := bsoncore.BuildDocumentFromElements(nil,
3594+
bsoncore.AppendBooleanElement(nil, "bool", true),
3595+
)
3596+
3597+
type myMap map[string]mybool
3598+
dc := DecodeContext{Registry: buildDefaultRegistry()}
3599+
vr := bsonrw.NewBSONDocumentReader(docBytes)
3600+
val := reflect.New(reflect.TypeOf(myMap{})).Elem()
3601+
err := defaultMapCodec.DecodeValue(dc, vr, val)
3602+
assert.Nil(t, err, "DecodeValue error: %v", err)
3603+
3604+
want := myMap{
3605+
"bool": mybool(true),
3606+
}
3607+
got := val.Interface().(myMap)
3608+
assert.Equal(t, want, got, "expected map %v, got %v", want, got)
3609+
})
3610+
})
35613611
}
35623612

35633613
type testValueUnmarshaler struct {

0 commit comments

Comments
 (0)