-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptions_test.go
101 lines (78 loc) · 1.52 KB
/
Options_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
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
90
91
92
93
94
95
96
97
98
99
100
101
package sandbox
import (
"testing"
"github.com/stretchr/testify/assert"
)
type Opts struct {
cmd string
flags []string
twist bool
cnt int
}
type OptsFunc func(*Opts)
func DefaultOpts() Opts {
return Opts{
cmd: "echo",
flags: []string{"-v"},
twist: false,
cnt: 1,
}
}
func WithOpts(newOpts Opts) OptsFunc {
return func(opts *Opts) {
opts.cmd = newOpts.cmd
opts.twist = newOpts.twist
opts.flags = newOpts.flags
opts.cnt = newOpts.cnt
}
}
func WithATwist(opts *Opts) {
opts.twist = true
}
func WithFlags(flags []string) OptsFunc {
return func(opts *Opts) {
opts.flags = flags
}
}
func WithCmd(cmd string) OptsFunc {
return func(opts *Opts) {
opts.cmd = cmd
}
}
type Worker struct {
Opts
}
func NewWorker(opts ...OptsFunc) *Worker {
o := DefaultOpts()
for _, optFunc := range opts {
optFunc(&o)
}
return &Worker{
Opts: o,
}
}
func Test_Opts(t *testing.T) {
defaultOpts := DefaultOpts()
defaultW := NewWorker()
assert.Equal(t, defaultW.Opts, defaultOpts)
defaultOpts.twist = true
w := NewWorker(WithATwist)
assert.Equal(t, w.Opts, defaultOpts)
defaultOpts.twist = true
defaultOpts.cmd = "ls"
defaultOpts.flags = []string{"one", "two", "three"}
w = NewWorker(WithATwist,
WithFlags([]string{"one", "two", "three"}),
WithCmd("ls"))
assert.Equal(t, w.Opts, defaultOpts)
}
func TestWithOpts(t *testing.T) {
newOpts := Opts{
cmd: "ps",
flags: []string{"-a", "-u", "-x"},
twist: true,
cnt: 16,
}
w := NewWorker(WithOpts(newOpts))
assert.Equal(t, newOpts, w.Opts)
}