-
Notifications
You must be signed in to change notification settings - Fork 46
/
check_test.go
286 lines (253 loc) · 6.71 KB
/
check_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
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
package checks_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/google/go-cmp/cmp"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/require"
"github.com/cloudflare/pint/internal/checks"
"github.com/cloudflare/pint/internal/parser"
)
type newCheckFn func(string) checks.RuleChecker
type problemsFn func(string) []checks.Problem
type checkTestT struct {
description string
content string
checker newCheckFn
problems problemsFn
mocks []prometheusMock
}
func runTestsT(t *testing.T, testCases []checkTestT, opts ...cmp.Option) {
p := parser.NewParser()
brokenRules, err := p.Parse([]byte(`
- alert: foo
expr: 'foo{}{} > 0'
annotations:
summary: '{{ $labels.job }} is incorrect'
- record: foo
expr: 'foo{}{}'
`))
require.NoError(t, err, "failed to parse broken test rules")
ctx := context.Background()
for _, tc := range testCases {
// original test
t.Run(tc.description, func(t *testing.T) {
var uri string
if len(tc.mocks) > 0 {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for i := range tc.mocks {
if tc.mocks[i].maybeApply(w, r) {
tc.mocks[i].wasUsed = true
return
}
}
t.Errorf("no matching response for %s request", r.URL.Path)
t.FailNow()
}))
defer srv.Close()
uri = srv.URL
}
rules, err := p.Parse([]byte(tc.content))
require.NoError(t, err, "cannot parse rule content")
for _, rule := range rules {
problems := tc.checker(uri).Check(ctx, rule)
require.Equal(t, tc.problems(uri), problems)
}
// verify that all mocks were used
for _, mock := range tc.mocks {
require.True(t, mock.wasUsed, "unused mock in %s: %s", tc.description, mock.conds)
}
})
// broken rules to test check against rules with syntax error
t.Run(tc.description+" (bogus rules)", func(t *testing.T) {
for _, rule := range brokenRules {
_ = tc.checker("").Check(ctx, rule)
}
})
}
}
func noProblems(uri string) []checks.Problem {
return nil
}
type requestCondition interface {
isMatch(*http.Request) bool
}
type responseWriter interface {
respond(w http.ResponseWriter)
}
type prometheusMock struct {
conds []requestCondition
resp responseWriter
wasUsed bool
}
func (pm *prometheusMock) maybeApply(w http.ResponseWriter, r *http.Request) bool {
for _, cond := range pm.conds {
if !cond.isMatch(r) {
return false
}
}
pm.wasUsed = true
pm.resp.respond(w)
return true
}
type requestPathCond struct {
path string
}
func (rpc requestPathCond) isMatch(r *http.Request) bool {
return r.URL.Path == rpc.path
}
type formCond struct {
key string
value string
}
func (fc formCond) isMatch(r *http.Request) bool {
err := r.ParseForm()
if err != nil {
return false
}
return r.Form.Get(fc.key) == fc.value
}
var (
// requireConfigPath = requestPathCond{path: "/api/v1/config"}
requireQueryPath = requestPathCond{path: "/api/v1/query"}
requireRangeQueryPath = requestPathCond{path: "/api/v1/query_range"}
)
type promError struct {
code int
errorType v1.ErrorType
err string
}
func (pe promError) respond(w http.ResponseWriter) {
w.WriteHeader(pe.code)
w.Header().Set("Content-Type", "application/json")
perr := struct {
Status string `json:"status"`
ErrorType v1.ErrorType `json:"errorType"`
Error string `json:"error"`
}{
Status: "error",
ErrorType: pe.errorType,
Error: pe.err,
}
d, err := json.MarshalIndent(perr, "", " ")
if err != nil {
panic(err)
}
_, _ = w.Write(d)
}
type vectorResponse struct {
samples model.Vector
}
func (vr vectorResponse) respond(w http.ResponseWriter) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
result := struct {
Status string `json:"status"`
Data struct {
ResultType string `json:"resultType"`
Result model.Vector `json:"result"`
} `json:"data"`
}{
Status: "success",
Data: struct {
ResultType string `json:"resultType"`
Result model.Vector `json:"result"`
}{
ResultType: "vector",
Result: vr.samples,
},
}
d, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
_, _ = w.Write(d)
}
type matrixResponse struct {
samples []*model.SampleStream
}
func (mr matrixResponse) respond(w http.ResponseWriter) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
result := struct {
Status string `json:"status"`
Data struct {
ResultType string `json:"resultType"`
Result []*model.SampleStream `json:"result"`
} `json:"data"`
}{
Status: "success",
Data: struct {
ResultType string `json:"resultType"`
Result []*model.SampleStream `json:"result"`
}{
ResultType: "matrix",
Result: mr.samples,
},
}
d, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
_, _ = w.Write(d)
}
var (
respondWithBadData = promError{code: 400, errorType: v1.ErrBadData, err: "bad input data"}
respondWithInternalError = promError{code: 500, errorType: v1.ErrServer, err: "internal error"}
respondWithEmptyVector = vectorResponse{samples: model.Vector{}}
respondWithEmptyMatrix = matrixResponse{samples: []*model.SampleStream{}}
respondWithSingleInstantVector = vectorResponse{
samples: generateVector(map[string]string{}),
}
respondWithSingleRangeVector1W = matrixResponse{
samples: []*model.SampleStream{
generateSampleStream(
map[string]string{},
time.Now().Add(time.Hour*24*-7),
time.Now(),
time.Minute*5,
),
},
}
)
func generateVector(labels map[string]string) (v model.Vector) {
metric := model.Metric{}
for k, v := range labels {
metric[model.LabelName(k)] = model.LabelValue(v)
}
v = append(v, &model.Sample{
Metric: metric,
Value: model.SampleValue(1),
Timestamp: model.TimeFromUnix(time.Now().Unix()),
})
return
}
func generateSampleStream(labels map[string]string, from, until time.Time, step time.Duration) (s *model.SampleStream) {
metric := model.Metric{}
for k, v := range labels {
metric[model.LabelName(k)] = model.LabelValue(v)
}
s = &model.SampleStream{
Metric: metric,
}
for from.Before(until) {
s.Values = append(s.Values, model.SamplePair{
Timestamp: model.TimeFromUnix(from.Unix()),
Value: 1,
})
from = from.Add(step)
}
return
}
func checkErrorBadData(name, uri, err string) string {
return fmt.Sprintf(`prometheus %q at %s failed with: %s`, name, uri, err)
}
func checkErrorUnableToRun(c, name, uri, err string) string {
return fmt.Sprintf(`cound't run %q checks due to prometheus %q at %s connection error: %s`, c, name, uri, err)
}