-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_test.go
More file actions
89 lines (74 loc) · 2.35 KB
/
context_test.go
File metadata and controls
89 lines (74 loc) · 2.35 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package cli
import (
"context"
"errors"
"syscall"
"testing"
"github.com/krostar/test"
)
func Test_ctxCommand(t *testing.T) {
{ // check context setup
ctx := NewCommandContext(test.Context(t))
value := ctx.Value(ctxKeyCommand)
test.Assert(t, value != nil)
}
{ // check setting and getting values
{ // unprepared context
ctx := test.Context(t)
SetInitializedFlagsInContext(ctx, []Flag{nil, nil}, []Flag{nil, nil})
local, persistent := GetInitializedFlagsFromContext(ctx)
test.Assert(t, local == nil)
test.Assert(t, persistent == nil)
}
{ // prepared context
ctx := NewCommandContext(test.Context(t))
SetInitializedFlagsInContext(ctx, []Flag{nil, nil}, []Flag{nil})
local, persistent := GetInitializedFlagsFromContext(ctx)
test.Assert(t, len(local) == 2)
test.Assert(t, len(persistent) == 1)
}
}
}
func Test_ctxMetadata(t *testing.T) {
{ // check context setup
ctx := NewContextWithMetadata(test.Context(t))
value := ctx.Value(ctxKeyMetadata)
test.Assert(t, value != nil)
}
{ // check setting and getting values
{ // unprepared context
ctx := test.Context(t)
SetMetadataInContext(ctx, "key", "value")
test.Assert(t, GetMetadataFromContext(ctx, "key") == nil)
}
{ // prepared context
ctx := NewContextWithMetadata(test.Context(t))
SetMetadataInContext(ctx, "key", "value")
test.Assert(t, GetMetadataFromContext(ctx, "key").(string) == "value")
}
}
}
func Test_NewContextCancelableBySignal(t *testing.T) {
t.Run("calling cancel func cancels the context", func(t *testing.T) {
ctx, cancel := NewContextCancelableBySignal(syscall.SIGUSR1)
test.Assert(t, ctx.Err() == nil)
cancel()
<-ctx.Done()
test.Assert(t, errors.Is(ctx.Err(), context.Canceled))
})
t.Run("sending provided signal cancels the context", func(t *testing.T) {
ctx, cancel := NewContextCancelableBySignal(syscall.SIGUSR1)
defer cancel()
test.Assert(t, ctx.Err() == nil)
test.Assert(t, syscall.Kill(syscall.Getpid(), syscall.SIGUSR1) == nil)
<-ctx.Done()
test.Assert(t, errors.Is(ctx.Err(), context.Canceled))
})
t.Run("sending unknown signal keeps context intact", func(t *testing.T) {
ctx, cancel := NewContextCancelableBySignal(syscall.SIGUSR1)
defer cancel()
test.Assert(t, ctx.Err() == nil)
test.Assert(t, syscall.Kill(syscall.Getpid(), syscall.SIGUSR2) == nil)
test.Assert(t, ctx.Err() == nil)
})
}