...
1
2
3
4
5
6
7 package mongo
8
9 import (
10 "context"
11 "testing"
12 "time"
13
14 "go.mongodb.org/mongo-driver/internal/assert"
15 )
16
17 func TestBackgroundContext(t *testing.T) {
18 t.Run("newBackgroundContext accepts a nil child", func(t *testing.T) {
19 ctx := newBackgroundContext(nil)
20 assert.Equal(t, context.Background(), ctx, "expected context.Background() for a nil child")
21 })
22 t.Run("Value requests are forwarded", func(t *testing.T) {
23
24
25 type ctxKey struct{}
26 expectedVal := "value"
27 childCtx := context.WithValue(context.Background(), ctxKey{}, expectedVal)
28
29 ctx := newBackgroundContext(childCtx)
30 gotVal, ok := ctx.Value(ctxKey{}).(string)
31 assert.True(t, ok, "expected context to contain a string value for ctxKey")
32 assert.Equal(t, expectedVal, gotVal, "expected value for ctxKey to be %q, got %q", expectedVal, gotVal)
33 })
34 t.Run("background context does not have a deadline", func(t *testing.T) {
35
36
37 childCtx, cancel := context.WithTimeout(context.Background(), time.Second)
38 defer cancel()
39
40 ctx := newBackgroundContext(childCtx)
41 deadline, ok := ctx.Deadline()
42 assert.False(t, ok, "expected context to have no deadline, but got %v", deadline)
43 })
44 t.Run("background context cannot be cancelled", func(t *testing.T) {
45
46
47 childCtx, cancel := context.WithCancel(context.Background())
48 cancel()
49
50 ctx := newBackgroundContext(childCtx)
51 select {
52 case <-ctx.Done():
53 t.Fatalf("expected context to not expire, but Done channel had a value; ctx error: %v", ctx.Err())
54 default:
55 }
56 assert.Nil(t, ctx.Err(), "expected context error to be nil, got %v", ctx.Err())
57 })
58 }
59
View as plain text