Skip to content

Commit b687278

Browse files
committed
GODRIVER-2822 Add error on empty for ReadConcern marshaler. (#1327)
1 parent fb6660f commit b687278

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

mongo/readconcern/readconcern.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
package readconcern // import "go.mongodb.org/mongo-driver/mongo/readconcern"
1212

1313
import (
14+
"errors"
15+
1416
"go.mongodb.org/mongo-driver/bson/bsontype"
1517
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
1618
)
@@ -106,6 +108,10 @@ func New(options ...Option) *ReadConcern {
106108
//
107109
// Deprecated: Marshaling a ReadConcern to BSON will not be supported in Go Driver 2.0.
108110
func (rc *ReadConcern) MarshalBSONValue() (bsontype.Type, []byte, error) {
111+
if rc == nil {
112+
return 0, nil, errors.New("cannot marshal nil ReadConcern")
113+
}
114+
109115
var elems []byte
110116

111117
if len(rc.Level) > 0 {

mongo/readconcern/readconcern_test.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Copyright (C) MongoDB, Inc. 2023-present.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License"); you may
4+
// not use this file except in compliance with the License. You may obtain
5+
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6+
7+
package readconcern_test
8+
9+
import (
10+
"testing"
11+
12+
"go.mongodb.org/mongo-driver/internal/assert"
13+
"go.mongodb.org/mongo-driver/mongo/readconcern"
14+
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
15+
)
16+
17+
func TestReadConcern_MarshalBSONValue(t *testing.T) {
18+
t.Parallel()
19+
20+
testCases := []struct {
21+
name string
22+
rc *readconcern.ReadConcern
23+
bytes []byte
24+
wantErrorMsg *string
25+
}{
26+
{
27+
name: "local",
28+
rc: readconcern.Local(),
29+
bytes: bsoncore.BuildDocument(nil, bsoncore.AppendStringElement(nil, "level", "local")),
30+
wantErrorMsg: nil,
31+
},
32+
{
33+
name: "empty",
34+
rc: readconcern.New(),
35+
bytes: bsoncore.BuildDocument(nil, nil),
36+
wantErrorMsg: nil,
37+
},
38+
{
39+
name: "nil",
40+
rc: nil,
41+
bytes: nil,
42+
wantErrorMsg: func() *string {
43+
msg := "cannot marshal nil ReadConcern"
44+
return &msg
45+
}(),
46+
},
47+
}
48+
49+
for _, tc := range testCases {
50+
tc := tc // Capture range variable.
51+
52+
t.Run(tc.name, func(t *testing.T) {
53+
t.Parallel()
54+
55+
_, b, err := tc.rc.MarshalBSONValue()
56+
assert.Equal(t, tc.bytes, b, "expected and actual outputs do not match")
57+
if tc.wantErrorMsg == nil {
58+
assert.NoError(t, err, "an unexpected error is returned")
59+
} else {
60+
assert.ErrorContains(t, err, *tc.wantErrorMsg, "expected and actual errors do not match")
61+
}
62+
})
63+
}
64+
}

0 commit comments

Comments
 (0)