@@ -18,6 +18,8 @@ import (
18
18
"go.mongodb.org/mongo-driver/mongo"
19
19
"go.mongodb.org/mongo-driver/mongo/integration/mtest"
20
20
"go.mongodb.org/mongo-driver/mongo/options"
21
+ "go.mongodb.org/mongo-driver/mongo/readpref"
22
+ "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
21
23
)
22
24
23
25
const (
@@ -60,6 +62,32 @@ func TestDatabase(t *testing.T) {
60
62
assert .Equal (mt , true , result .IsMaster , "expected isMaster value true, got false" )
61
63
assert .Equal (mt , 1.0 , result .Ok , "expected ok value 1.0, got %v" , result .Ok )
62
64
})
65
+
66
+ // We set min server version 3.6 because pre-3.6 servers use OP_QUERY, so the command document will look like
67
+ // {$query: {...}, $readPreference: {...}}. Per the command monitoring spec, the $query subdocument is unwrapped
68
+ // and the $readPreference is dropped for monitoring purposes, so we can't examine it.
69
+ readPrefOpts := mtest .NewOptions ().
70
+ Topologies (mtest .Sharded ).
71
+ MinServerVersion ("3.6" )
72
+ mt .RunOpts ("read pref passed to mongos" , readPrefOpts , func (mt * mtest.T ) {
73
+ // When communicating with a mongos, the supplied read preference should be passed down to the operations
74
+ // layer, which should add a top-level $readPreference field to the command.
75
+
76
+ runCmdOpts := options .RunCmd ().
77
+ SetReadPreference (readpref .SecondaryPreferred ())
78
+ err := mt .DB .RunCommand (mtest .Background , bson.D {{"isMaster" , 1 }}, runCmdOpts ).Err ()
79
+ assert .Nil (mt , err , "RunCommand error: %v" , err )
80
+
81
+ expected := bson .Raw (bsoncore .BuildDocumentFromElements (
82
+ nil ,
83
+ bsoncore .AppendStringElement (nil , "mode" , "secondaryPreferred" ),
84
+ ))
85
+ evt := mt .GetStartedEvent ()
86
+ assert .Equal (mt , "isMaster" , evt .CommandName , "expected 'isMaster' command to be sent, got %q" , evt .CommandName )
87
+ actual , ok := evt .Command .Lookup ("$readPreference" ).DocumentOK ()
88
+ assert .True (mt , ok , "expected command %v to contain a $readPreference document" , evt .Command )
89
+ assert .Equal (mt , expected , actual , "expected $readPreference document %v, got %v" , expected , actual )
90
+ })
63
91
})
64
92
65
93
dropOpts := mtest .NewOptions ().DatabaseName ("dropDb" )
0 commit comments