@@ -8,6 +8,7 @@ package integration
8
8
9
9
import (
10
10
"context"
11
+ "errors"
11
12
"os"
12
13
"testing"
13
14
"time"
@@ -203,6 +204,51 @@ func TestCursor(t *testing.T) {
203
204
assert .True (mt , ok , "expected mongo.CommandError, got: %T" , err )
204
205
assert .Equal (mt , failpointData .ErrorCode , mongoErr .Code , "expected code %v, got: %v" , failpointData .ErrorCode , mongoErr .Code )
205
206
})
207
+
208
+ mt .Run ("deferred Close uses context.Background" , func (mt * mtest.T ) {
209
+ initCollection (mt , mt .Coll )
210
+
211
+ // Find with batchSize 2 so All will run getMore for next 3 docs and error.
212
+ cur , err := mt .Coll .Find (context .Background (), bson.D {},
213
+ options .Find ().SetBatchSize (2 ))
214
+ assert .Nil (mt , err , "Find error: %v" , err )
215
+
216
+ // Create a context and immediately cancel it.
217
+ canceledCtx , cancel := context .WithCancel (context .Background ())
218
+ cancel ()
219
+
220
+ // Clear "insert" and "find" events.
221
+ mt .ClearEvents ()
222
+
223
+ // Call All with the canceled context and expect context.Canceled.
224
+ var docs []bson.D
225
+ err = cur .All (canceledCtx , & docs )
226
+ assert .NotNil (mt , err , "expected error for All, got nil" )
227
+ assert .True (mt , errors .Is (err , context .Canceled ),
228
+ "expected context.Canceled error, got %v" , err )
229
+
230
+ // Assert that a "getMore" command was sent and failed (Next used the
231
+ // canceled context).
232
+ stEvt := mt .GetStartedEvent ()
233
+ assert .NotNil (mt , stEvt , `expected a "getMore" started event, got no event` )
234
+ assert .Equal (mt , stEvt .CommandName , "getMore" ,
235
+ `expected a "getMore" started event, got %q` , stEvt .CommandName )
236
+ fEvt := mt .GetFailedEvent ()
237
+ assert .NotNil (mt , fEvt , `expected a failed "getMore" event, got no event` )
238
+ assert .Equal (mt , fEvt .CommandName , "getMore" ,
239
+ `expected a failed "getMore" event, got %q` , fEvt .CommandName )
240
+
241
+ // Assert that a "killCursors" command was sent and was successful (Close
242
+ // used the 2 second Client Timeout).
243
+ stEvt = mt .GetStartedEvent ()
244
+ assert .NotNil (mt , stEvt , `expected a "killCursors" started event, got no event` )
245
+ assert .Equal (mt , stEvt .CommandName , "killCursors" ,
246
+ `expected a "killCursors" started event, got %q` , stEvt .CommandName )
247
+ suEvt := mt .GetSucceededEvent ()
248
+ assert .NotNil (mt , suEvt , `expected a successful "killCursors" event, got no event` )
249
+ assert .Equal (mt , suEvt .CommandName , "killCursors" ,
250
+ `expected a successful "killCursors" event, got %q` , suEvt .CommandName )
251
+ })
206
252
})
207
253
mt .RunOpts ("close" , noClientOpts , func (mt * mtest.T ) {
208
254
failpointOpts := mtest .NewOptions ().Topologies (mtest .ReplicaSet ).MinServerVersion ("4.0" )
0 commit comments