forked from mongodb/mongo-go-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background_context_test.go
58 lines (48 loc) · 1.9 KB
/
background_context_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (C) MongoDB, Inc. 2017-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 mongo
import (
"context"
"testing"
"time"
"go.mongodb.org/mongo-driver/internal/assert"
)
func TestBackgroundContext(t *testing.T) {
t.Run("newBackgroundContext accepts a nil child", func(t *testing.T) {
ctx := newBackgroundContext(nil)
assert.Equal(t, context.Background(), ctx, "expected context.Background() for a nil child")
})
t.Run("Value requests are forwarded", func(t *testing.T) {
// Tests the Value function.
type ctxKey struct{}
expectedVal := "value"
childCtx := context.WithValue(context.Background(), ctxKey{}, expectedVal)
ctx := newBackgroundContext(childCtx)
gotVal, ok := ctx.Value(ctxKey{}).(string)
assert.True(t, ok, "expected context to contain a string value for ctxKey")
assert.Equal(t, expectedVal, gotVal, "expected value for ctxKey to be %q, got %q", expectedVal, gotVal)
})
t.Run("background context does not have a deadline", func(t *testing.T) {
// Tests the Deadline function.
childCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
ctx := newBackgroundContext(childCtx)
deadline, ok := ctx.Deadline()
assert.False(t, ok, "expected context to have no deadline, but got %v", deadline)
})
t.Run("background context cannot be cancelled", func(t *testing.T) {
// Tests the Done and Err functions.
childCtx, cancel := context.WithCancel(context.Background())
cancel()
ctx := newBackgroundContext(childCtx)
select {
case <-ctx.Done():
t.Fatalf("expected context to not expire, but Done channel had a value; ctx error: %v", ctx.Err())
default:
}
assert.Nil(t, ctx.Err(), "expected context error to be nil, got %v", ctx.Err())
})
}