-
Notifications
You must be signed in to change notification settings - Fork 0
/
gomockctx.go
70 lines (57 loc) · 1.67 KB
/
gomockctx.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
59
60
61
62
63
64
65
66
67
68
69
70
// Package gomockctx contains gomock helpers for matching context.Context
// objects.
package gomockctx
import (
"context"
"go.uber.org/mock/gomock"
)
type (
contextKey string
contextValue string
)
var ctxKey contextKey = "gomockctx ID"
func newCtxID() contextValue {
id, err := randString(32)
if err != nil {
panic(err)
}
return contextValue(id)
}
func getValue(ctx context.Context) contextValue {
var value contextValue
if ctx == nil {
return value
}
v := ctx.Value(ctxKey)
if s, ok := v.(contextValue); ok {
value = s
}
return value
}
// New returns a context as a child of the given parent, which includes a
// randomized gomockctx ID value set, which makes it a gomockctx context. This
// can then be used with Eq to get a gomock Matcher which returns true for the
// context from New, or any child contexts of it.
//
// If crypto/rand returns an error, this will panic trying to generate the
// gomockctx ID. In practice though, crypto/rand should never return a error.
func New(parent context.Context) context.Context {
return context.WithValue(parent, ctxKey, newCtxID())
}
// Eq accepts a context with a gomockctx ID value (as returned from New), and
// returns a gomock.Matcher which returns true for the given context, and any
// child contexts of it.
//
// If ctx was not returned from New, the resulting matcher will ALWAYS return
// false.
func Eq(ctx context.Context) gomock.Matcher {
return WithValue(ctxKey, getValue(ctx))
}
// ID returns the gomockctx ID value in the given context, or a empty string if
// the context does not have a gomockctx ID value.
func ID(ctx context.Context) string {
if ctx == nil {
return ""
}
return string(getValue(ctx))
}