/
testutil.go
320 lines (276 loc) · 8.56 KB
/
testutil.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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package testutil
import (
"context"
"fmt"
"math/rand"
"path/filepath"
"reflect"
"runtime"
"runtime/debug"
"sort"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/pmezard/go-difflib/difflib"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/index"
"go.uber.org/goleak"
"github.com/thanos-io/thanos/pkg/errors"
)
// Assert fails the test if the condition is false.
func Assert(tb testing.TB, condition bool, v ...interface{}) {
tb.Helper()
if condition {
return
}
_, file, line, _ := runtime.Caller(1)
var msg string
if len(v) > 0 {
msg = fmt.Sprintf(v[0].(string), v[1:]...)
}
tb.Fatalf("\033[31m%s:%d: "+msg+"\033[39m\n\n", filepath.Base(file), line)
}
// Ok fails the test if an err is not nil.
func Ok(tb testing.TB, err error, v ...interface{}) {
tb.Helper()
if err == nil {
return
}
_, file, line, _ := runtime.Caller(1)
var msg string
if len(v) > 0 {
msg = fmt.Sprintf(v[0].(string), v[1:]...)
}
tb.Fatalf("\033[31m%s:%d:"+msg+"\n\n unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
}
// NotOk fails the test if an err is nil.
func NotOk(tb testing.TB, err error, v ...interface{}) {
tb.Helper()
if err != nil {
return
}
_, file, line, _ := runtime.Caller(1)
var msg string
if len(v) > 0 {
msg = fmt.Sprintf(v[0].(string), v[1:]...)
}
tb.Fatalf("\033[31m%s:%d:"+msg+"\n\n expected error, got nothing \033[39m\n\n", filepath.Base(file), line)
}
// Equals fails the test if exp is not equal to act.
func Equals(tb testing.TB, exp, act interface{}, v ...interface{}) {
tb.Helper()
if reflect.DeepEqual(exp, act) {
return
}
_, file, line, _ := runtime.Caller(1)
var msg string
if len(v) > 0 {
msg = fmt.Sprintf(v[0].(string), v[1:]...)
}
tb.Fatal(sprintfWithLimit("\033[31m%s:%d:"+msg+"\n\n\texp: %#v\n\n\tgot: %#v%s\033[39m\n\n", filepath.Base(file), line, exp, act, diff(exp, act)))
}
func sprintfWithLimit(act string, v ...interface{}) string {
s := fmt.Sprintf(act, v...)
if len(s) > 10000 {
return s[:10000] + "...(output trimmed)"
}
return s
}
func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
t := reflect.TypeOf(v)
k := t.Kind()
if k == reflect.Ptr {
t = t.Elem()
k = t.Kind()
}
return t, k
}
// diff returns a diff of both values as long as both are of the same type and
// are a struct, map, slice, array or string. Otherwise it returns an empty string.
func diff(expected, actual interface{}) string {
if expected == nil || actual == nil {
return ""
}
et, ek := typeAndKind(expected)
at, _ := typeAndKind(actual)
if et != at {
return ""
}
if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
return ""
}
var e, a string
c := spew.ConfigState{
Indent: " ",
DisablePointerAddresses: true,
DisableCapacities: true,
SortKeys: true,
}
if et != reflect.TypeOf("") {
e = c.Sdump(expected)
a = c.Sdump(actual)
} else {
e = reflect.ValueOf(expected).String()
a = reflect.ValueOf(actual).String()
}
diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: difflib.SplitLines(e),
B: difflib.SplitLines(a),
FromFile: "Expected",
FromDate: "",
ToFile: "Actual",
ToDate: "",
Context: 1,
})
return "\n\nDiff:\n" + diff
}
// GatherAndCompare compares the metrics of a Gatherers pair.
func GatherAndCompare(t *testing.T, g1, g2 prometheus.Gatherer, filter string) {
g1m, err := g1.Gather()
Ok(t, err)
g2m, err := g2.Gather()
Ok(t, err)
var m1 *dto.MetricFamily
for _, m := range g1m {
if *m.Name == filter {
m1 = m
}
}
var m2 *dto.MetricFamily
for _, m := range g2m {
if *m.Name == filter {
m2 = m
}
}
Equals(t, m1.String(), m2.String())
}
// TolerantVerifyLeakMain verifies go leaks but excludes the go routines that are
// launched as side effects of some of our dependencies.
func TolerantVerifyLeakMain(m *testing.M) {
goleak.VerifyTestMain(m,
// https://github.com/census-instrumentation/opencensus-go/blob/d7677d6af5953e0506ac4c08f349c62b917a443a/stats/view/worker.go#L34
goleak.IgnoreTopFunction("go.opencensus.io/stats/view.(*worker).start"),
// https://github.com/kubernetes/klog/blob/c85d02d1c76a9ebafa81eb6d35c980734f2c4727/klog.go#L417
goleak.IgnoreTopFunction("k8s.io/klog/v2.(*loggingT).flushDaemon"),
goleak.IgnoreTopFunction("k8s.io/klog.(*loggingT).flushDaemon"),
// https://github.com/baidubce/bce-sdk-go/blob/9a8c1139e6a3ad23080b9b8c51dec88df8ce3cda/util/log/logger.go#L359
goleak.IgnoreTopFunction("github.com/baidubce/bce-sdk-go/util/log.NewLogger.func1"),
)
}
// TolerantVerifyLeak verifies go leaks but excludes the go routines that are
// launched as side effects of some of our dependencies.
func TolerantVerifyLeak(t *testing.T) {
goleak.VerifyNone(t,
// https://github.com/census-instrumentation/opencensus-go/blob/d7677d6af5953e0506ac4c08f349c62b917a443a/stats/view/worker.go#L34
goleak.IgnoreTopFunction("go.opencensus.io/stats/view.(*worker).start"),
// https://github.com/kubernetes/klog/blob/c85d02d1c76a9ebafa81eb6d35c980734f2c4727/klog.go#L417
goleak.IgnoreTopFunction("k8s.io/klog/v2.(*loggingT).flushDaemon"),
goleak.IgnoreTopFunction("k8s.io/klog.(*loggingT).flushDaemon"),
// https://github.com/baidubce/bce-sdk-go/blob/9a8c1139e6a3ad23080b9b8c51dec88df8ce3cda/util/log/logger.go#L359
goleak.IgnoreTopFunction("github.com/baidubce/bce-sdk-go/util/log.NewLogger.func1"),
)
}
// FaultOrPanicToErr returns error if panic of fault was triggered during execution of function.
func FaultOrPanicToErr(f func()) (err error) {
// Set this go routine to panic on segfault to allow asserting on those.
debug.SetPanicOnFault(true)
defer func() {
if r := recover(); r != nil {
err = errors.Errorf("invoked function panicked or caused segmentation fault: %v", r)
}
debug.SetPanicOnFault(false)
}()
f()
return err
}
var indexFilename = "index"
type indexWriterSeries struct {
labels labels.Labels
chunks []chunks.Meta // series file offset of chunks
}
type indexWriterSeriesSlice []*indexWriterSeries
// PutOutOfOrderIndex updates the index in blockDir with an index containing an out-of-order chunk
// copied from https://github.com/prometheus/prometheus/blob/b1ed4a0a663d0c62526312311c7529471abbc565/tsdb/index/index_test.go#L346
func PutOutOfOrderIndex(blockDir string, minTime int64, maxTime int64) error {
if minTime >= maxTime || minTime+4 >= maxTime {
return fmt.Errorf("minTime must be at least 4 less than maxTime to not create overlapping chunks")
}
lbls := []labels.Labels{
[]labels.Label{
{Name: "lbl1", Value: "1"},
},
}
// Sort labels as the index writer expects series in sorted order.
sort.Sort(labels.Slice(lbls))
symbols := map[string]struct{}{}
for _, lset := range lbls {
for _, l := range lset {
symbols[l.Name] = struct{}{}
symbols[l.Value] = struct{}{}
}
}
var input indexWriterSeriesSlice
// Generate ChunkMetas for every label set.
for _, lset := range lbls {
var metas []chunks.Meta
// only need two chunks that are out-of-order
chk1 := chunks.Meta{
MinTime: maxTime - 2,
MaxTime: maxTime - 1,
Ref: chunks.ChunkRef(rand.Uint64()),
Chunk: chunkenc.NewXORChunk(),
}
metas = append(metas, chk1)
chk2 := chunks.Meta{
MinTime: minTime + 1,
MaxTime: minTime + 2,
Ref: chunks.ChunkRef(rand.Uint64()),
Chunk: chunkenc.NewXORChunk(),
}
metas = append(metas, chk2)
input = append(input, &indexWriterSeries{
labels: lset,
chunks: metas,
})
}
iw, err := index.NewWriter(context.Background(), filepath.Join(blockDir, indexFilename))
if err != nil {
return err
}
syms := []string{}
for s := range symbols {
syms = append(syms, s)
}
sort.Strings(syms)
for _, s := range syms {
if err := iw.AddSymbol(s); err != nil {
return err
}
}
// Population procedure as done by compaction.
var (
postings = index.NewMemPostings()
values = map[string]map[string]struct{}{}
)
for i, s := range input {
if err := iw.AddSeries(storage.SeriesRef(i), s.labels, s.chunks...); err != nil {
return err
}
for _, l := range s.labels {
valset, ok := values[l.Name]
if !ok {
valset = map[string]struct{}{}
values[l.Name] = valset
}
valset[l.Value] = struct{}{}
}
postings.Add(storage.SeriesRef(i), s.labels)
}
return iw.Close()
}