-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathmocks_for_test.go
More file actions
186 lines (160 loc) · 5.28 KB
/
Copy pathmocks_for_test.go
File metadata and controls
186 lines (160 loc) · 5.28 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package events
import (
"context"
"fmt"
"sort"
"github.com/go-logr/logr"
"go.opentelemetry.io/otel/attribute"
tracesdk "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/semconv"
"go.opentelemetry.io/otel/trace"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
dynamicFake "k8s.io/client-go/dynamic/fake"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"sigs.k8s.io/controller-runtime/pkg/client/fake" //nolint:staticcheck
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
func newMockRESTMapper() meta.RESTMapper {
cfg := &rest.Config{}
mapper, _ := apiutil.NewDynamicRESTMapper(cfg, apiutil.WithCustomMapper(func() (meta.RESTMapper, error) {
baseMapper := meta.NewDefaultRESTMapper(nil)
// Add the object kinds that we use in fixtures.
baseMapper.Add(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, meta.RESTScopeNamespace)
baseMapper.Add(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "ReplicaSet"}, meta.RESTScopeNamespace)
baseMapper.Add(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "StatefulSet"}, meta.RESTScopeNamespace)
baseMapper.Add(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"}, meta.RESTScopeNamespace)
return baseMapper, nil
}))
return mapper
}
// Initialize an EventWatcher, context and logger ready for testing
func newTestEventWatcher(initObjs ...runtime.Object) (context.Context, *EventWatcher, *fakeExporter, logr.Logger) {
ctx := context.Background()
scheme := runtime.NewScheme()
_ = clientgoscheme.AddToScheme(scheme)
log := zap.New(zap.UseDevMode(true))
fakeClient := fake.NewFakeClientWithScheme(scheme, initObjs...)
exporter := newFakeExporter()
r := &EventWatcher{
Client: fakeClient,
Log: log,
Exporter: exporter,
}
fakeDynamic := dynamicFake.NewSimpleDynamicClient(scheme)
mockRESTMapper := newMockRESTMapper()
r.initialize(scheme, fakeDynamic, mockRESTMapper)
return ctx, r, exporter, log
}
func newFakeExporter() *fakeExporter {
return &fakeExporter{}
}
// records spans sent to it, for testing purposes
type fakeExporter struct {
SpanSnapshot []*tracesdk.SpanSnapshot
}
func (f *fakeExporter) dump() []string {
f.sort()
spanMap := make(map[trace.SpanID]int)
for i, d := range f.SpanSnapshot {
spanMap[d.SpanContext.SpanID()] = i
}
var ret []string
for i, d := range f.SpanSnapshot {
parent, found := spanMap[d.ParentSpanID]
var parentStr string
if found {
parentStr = fmt.Sprintf(" (%d)", parent)
}
message := attributeValue(d.Attributes, attribute.Key("message"))
resourceName := attributeValue(d.Resource.Attributes(), semconv.ServiceNameKey)
ret = append(ret, fmt.Sprintf("%d: %s %s%s %s", i, resourceName, d.Name, parentStr, message))
}
return ret
}
// ExportSpans implements trace.SpanExporter
func (f *fakeExporter) ExportSpans(ctx context.Context, SpanSnapshot []*tracesdk.SpanSnapshot) error {
f.SpanSnapshot = append(f.SpanSnapshot, SpanSnapshot...)
return nil
}
// Shutdown implements trace.SpanExporter
func (f *fakeExporter) Shutdown(ctx context.Context) error {
return nil
}
func attributeValue(attributes []attribute.KeyValue, key attribute.Key) string {
for _, lbl := range attributes {
if lbl.Key == key {
return lbl.Value.AsString()
}
}
return ""
}
// Sort the captured spans so they are in a predictable order to check expected output.
// Use depth-first search, with edges ordered by start-time where those differ.
func (f *fakeExporter) sort() {
sort.Stable(SortableSpans(f.SpanSnapshot))
// Make a map from span-id to index in the set
spanMap := make(map[trace.SpanID]int)
for i, d := range f.SpanSnapshot {
spanMap[d.SpanContext.SpanID()] = i
}
// Prepare vertexes for depth-first sort
v := make([]*vertex, len(f.SpanSnapshot))
for i := range f.SpanSnapshot {
v[i] = &vertex{value: i}
}
topSpan := -1
for i, s := range f.SpanSnapshot {
if s.ParentSpanID.IsValid() {
p := spanMap[s.ParentSpanID]
v[p].connect(v[i])
} else {
if topSpan != -1 {
panic("More than one top span")
}
topSpan = i
}
}
if topSpan == -1 { // no top span found; can't do DFS
return
}
sortedSpans := make([]*tracesdk.SpanSnapshot, 0, len(f.SpanSnapshot))
t := dfs{
visit: func(v *vertex) {
sortedSpans = append(sortedSpans, f.SpanSnapshot[v.value])
},
}
t.walk(v[topSpan])
f.SpanSnapshot = sortedSpans
}
// SortableSpans attaches the methods of sort.Interface to []*tracesdk.SpanSnapshot, sorting by start time.
type SortableSpans []*tracesdk.SpanSnapshot
func (x SortableSpans) Len() int { return len(x) }
func (x SortableSpans) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x SortableSpans) Less(i, j int) bool { return x[i].StartTime.Before(x[j].StartTime) }
// Single-use DFS implementation.
// Not using one from a library; see https://github.com/gonum/gonum/issues/1595
type vertex struct {
visited bool
value int
neighbours []*vertex
}
func (v *vertex) connect(vertex *vertex) {
v.neighbours = append(v.neighbours, vertex)
}
type dfs struct {
visit func(*vertex)
}
func (d *dfs) walk(vertex *vertex) {
if vertex.visited {
return
}
vertex.visited = true
d.visit(vertex)
for _, v := range vertex.neighbours {
d.walk(v)
}
}