Skip to content

Commit

Permalink
GODRIVER-2822 Add error on empty for ReadConcern marshaler. (mongodb#…
Browse files Browse the repository at this point in the history
  • Loading branch information
qingyang-hu authored and prestonvasquez committed Aug 1, 2023
1 parent 7770c49 commit 7a6694f
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
6 changes: 6 additions & 0 deletions mongo/readconcern/readconcern.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
package readconcern // import "go.mongodb.org/mongo-driver/mongo/readconcern"

import (
"errors"

"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
Expand Down Expand Up @@ -106,6 +108,10 @@ func New(options ...Option) *ReadConcern {
//
// Deprecated: Marshaling a ReadConcern to BSON will not be supported in Go Driver 2.0.
func (rc *ReadConcern) MarshalBSONValue() (bsontype.Type, []byte, error) {
if rc == nil {
return 0, nil, errors.New("cannot marshal nil ReadConcern")
}

var elems []byte

if len(rc.Level) > 0 {
Expand Down
64 changes: 64 additions & 0 deletions mongo/readconcern/readconcern_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright (C) MongoDB, Inc. 2023-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

package readconcern_test

import (
"testing"

"go.mongodb.org/mongo-driver/internal/assert"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)

func TestReadConcern_MarshalBSONValue(t *testing.T) {
t.Parallel()

testCases := []struct {
name string
rc *readconcern.ReadConcern
bytes []byte
wantErrorMsg *string
}{
{
name: "local",
rc: readconcern.Local(),
bytes: bsoncore.BuildDocument(nil, bsoncore.AppendStringElement(nil, "level", "local")),
wantErrorMsg: nil,
},
{
name: "empty",
rc: readconcern.New(),
bytes: bsoncore.BuildDocument(nil, nil),
wantErrorMsg: nil,
},
{
name: "nil",
rc: nil,
bytes: nil,
wantErrorMsg: func() *string {
msg := "cannot marshal nil ReadConcern"
return &msg
}(),
},
}

for _, tc := range testCases {
tc := tc // Capture range variable.

t.Run(tc.name, func(t *testing.T) {
t.Parallel()

_, b, err := tc.rc.MarshalBSONValue()
assert.Equal(t, tc.bytes, b, "expected and actual outputs do not match")
if tc.wantErrorMsg == nil {
assert.NoError(t, err, "an unexpected error is returned")
} else {
assert.ErrorContains(t, err, *tc.wantErrorMsg, "expected and actual errors do not match")
}
})
}
}

0 comments on commit 7a6694f

Please sign in to comment.