-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathcontract_checker_test.go
360 lines (309 loc) · 11.1 KB
/
contract_checker_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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package receivertest
import (
"context"
"strconv"
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/consumer/consumererror"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/plog"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/pdata/ptrace"
"go.opentelemetry.io/collector/pipeline"
"go.opentelemetry.io/collector/receiver"
)
// This file is an example that demonstrates how to use the CheckConsumeContract() function.
// We declare a trivial example receiver, a data generator and then use them in TestConsumeContract().
type exampleReceiver struct {
nextLogsConsumer consumer.Logs
nextTracesConsumer consumer.Traces
nextMetricsConsumer consumer.Metrics
}
func (s *exampleReceiver) Start(context.Context, component.Host) error {
return nil
}
func (s *exampleReceiver) Shutdown(context.Context) error {
return nil
}
func (s *exampleReceiver) ReceiveLogs(data plog.Logs) {
// This very simple implementation demonstrates how a single items receiving should happen.
for {
err := s.nextLogsConsumer.ConsumeLogs(context.Background(), data)
if err != nil {
// The next consumer returned an error.
if !consumererror.IsPermanent(err) {
// It is not a permanent error, so we must retry sending it again. In network-based
// receivers instead we can ask our sender to re-retry the same data again later.
// We may also pause here a bit if we don't want to hammer the next consumer.
continue
}
}
// If we are hear either the ConsumeLogs returned success or it returned a permanent error.
// In either case we don't need to retry the same data, we are done.
return
}
}
func (s *exampleReceiver) ReceiveMetrics(data pmetric.Metrics) {
// This very simple implementation demonstrates how a single items receiving should happen.
for {
err := s.nextMetricsConsumer.ConsumeMetrics(context.Background(), data)
if err != nil {
// The next consumer returned an error.
if !consumererror.IsPermanent(err) {
// It is not a permanent error, so we must retry sending it again. In network-based
// receivers instead we can ask our sender to re-retry the same data again later.
// We may also pause here a bit if we don't want to hammer the next consumer.
continue
}
}
// If we are hear either the ConsumeLogs returned success or it returned a permanent error.
// In either case we don't need to retry the same data, we are done.
return
}
}
func (s *exampleReceiver) ReceiveTraces(data ptrace.Traces) {
// This very simple implementation demonstrates how a single items receiving should happen.
for {
err := s.nextTracesConsumer.ConsumeTraces(context.Background(), data)
if err != nil {
// The next consumer returned an error.
if !consumererror.IsPermanent(err) {
// It is not a permanent error, so we must retry sending it again. In network-based
// receivers instead we can ask our sender to re-retry the same data again later.
// We may also pause here a bit if we don't want to hammer the next consumer.
continue
}
}
// If we are hear either the ConsumeLogs returned success or it returned a permanent error.
// In either case we don't need to retry the same data, we are done.
return
}
}
// A config for exampleReceiver.
type exampleReceiverConfig struct {
generator Generator
}
// A generator that can send data to exampleReceiver.
type exampleLogGenerator struct {
t *testing.T
receiver *exampleReceiver
sequenceNum int64
}
func (g *exampleLogGenerator) Start() {
g.sequenceNum = 0
}
func (g *exampleLogGenerator) Stop() {}
func (g *exampleLogGenerator) Generate() []UniqueIDAttrVal {
// Make sure the id is atomically incremented. Generate() may be called concurrently.
id := UniqueIDAttrVal(strconv.FormatInt(atomic.AddInt64(&g.sequenceNum, 1), 10))
data := CreateOneLogWithID(id)
// Send the generated data to the receiver.
g.receiver.ReceiveLogs(data)
// And return the ids for bookkeeping by the test.
return []UniqueIDAttrVal{id}
}
// A generator that can send data to exampleReceiver.
type exampleTraceGenerator struct {
t *testing.T
receiver *exampleReceiver
sequenceNum int64
}
func (g *exampleTraceGenerator) Start() {
g.sequenceNum = 0
}
func (g *exampleTraceGenerator) Stop() {}
func (g *exampleTraceGenerator) Generate() []UniqueIDAttrVal {
// Make sure the id is atomically incremented. Generate() may be called concurrently.
id := UniqueIDAttrVal(strconv.FormatInt(atomic.AddInt64(&g.sequenceNum, 1), 10))
data := CreateOneSpanWithID(id)
// Send the generated data to the receiver.
g.receiver.ReceiveTraces(data)
// And return the ids for bookkeeping by the test.
return []UniqueIDAttrVal{id}
}
// A generator that can send data to exampleReceiver.
type exampleMetricGenerator struct {
t *testing.T
receiver *exampleReceiver
sequenceNum int64
}
func (g *exampleMetricGenerator) Start() {
g.sequenceNum = 0
}
func (g *exampleMetricGenerator) Stop() {}
func (g *exampleMetricGenerator) Generate() []UniqueIDAttrVal {
// Make sure the id is atomically incremented. Generate() may be called concurrently.
next := atomic.AddInt64(&g.sequenceNum, 1)
id := UniqueIDAttrVal(strconv.FormatInt(next, 10))
var data pmetric.Metrics
switch next % 5 {
case 0:
data = CreateGaugeMetricWithID(id)
case 1:
data = CreateSumMetricWithID(id)
case 2:
data = CreateSummaryMetricWithID(id)
case 3:
data = CreateHistogramMetricWithID(id)
case 4:
data = CreateExponentialHistogramMetricWithID(id)
}
// Send the generated data to the receiver.
g.receiver.ReceiveMetrics(data)
// And return the ids for bookkeeping by the test.
return []UniqueIDAttrVal{id}
}
func newExampleFactory() receiver.Factory {
return receiver.NewFactory(
component.MustNewType("example_receiver"),
func() component.Config {
return &exampleReceiverConfig{}
},
receiver.WithLogs(createLog, component.StabilityLevelBeta),
receiver.WithMetrics(createMetric, component.StabilityLevelBeta),
receiver.WithTraces(createTrace, component.StabilityLevelBeta),
)
}
func createTrace(_ context.Context, _ receiver.Settings, cfg component.Config, consumer consumer.Traces) (receiver.Traces, error) {
rcv := &exampleReceiver{nextTracesConsumer: consumer}
cfg.(*exampleReceiverConfig).generator.(*exampleTraceGenerator).receiver = rcv
return rcv, nil
}
func createMetric(_ context.Context, _ receiver.Settings, cfg component.Config, consumer consumer.Metrics) (receiver.Metrics, error) {
rcv := &exampleReceiver{nextMetricsConsumer: consumer}
cfg.(*exampleReceiverConfig).generator.(*exampleMetricGenerator).receiver = rcv
return rcv, nil
}
func createLog(
_ context.Context,
_ receiver.Settings,
cfg component.Config,
consumer consumer.Logs,
) (receiver.Logs, error) {
rcv := &exampleReceiver{nextLogsConsumer: consumer}
cfg.(*exampleReceiverConfig).generator.(*exampleLogGenerator).receiver = rcv
return rcv, nil
}
// TestConsumeContract is an example of testing of the receiver for the contract between the
// receiver and next consumer.
func TestConsumeContract(t *testing.T) {
// Number of log records to send per scenario.
const logsPerTest = 100
generator := &exampleLogGenerator{t: t}
cfg := &exampleReceiverConfig{generator: generator}
params := CheckConsumeContractParams{
T: t,
Factory: newExampleFactory(),
Signal: pipeline.SignalLogs,
Config: cfg,
Generator: generator,
GenerateCount: logsPerTest,
}
// Run the contract checker. This will trigger test failures if any problems are found.
CheckConsumeContract(params)
}
// TestConsumeMetricsContract is an example of testing of the receiver for the contract between the
// receiver and next consumer.
func TestConsumeMetricsContract(t *testing.T) {
// Number of metric data points to send per scenario.
const metricsPerTest = 100
generator := &exampleMetricGenerator{t: t}
cfg := &exampleReceiverConfig{generator: generator}
params := CheckConsumeContractParams{
T: t,
Factory: newExampleFactory(),
Signal: pipeline.SignalMetrics,
Config: cfg,
Generator: generator,
GenerateCount: metricsPerTest,
}
// Run the contract checker. This will trigger test failures if any problems are found.
CheckConsumeContract(params)
}
// TestConsumeTracesContract is an example of testing of the receiver for the contract between the
// receiver and next consumer.
func TestConsumeTracesContract(t *testing.T) {
// Number of trace spans to send per scenario.
const spansPerTest = 100
generator := &exampleTraceGenerator{t: t}
cfg := &exampleReceiverConfig{generator: generator}
params := CheckConsumeContractParams{
T: t,
Factory: newExampleFactory(),
Signal: pipeline.SignalTraces,
Config: cfg,
Generator: generator,
GenerateCount: spansPerTest,
}
// Run the contract checker. This will trigger test failures if any problems are found.
CheckConsumeContract(params)
}
func TestIDSetFromDataPoint(t *testing.T) {
require.Error(t, idSetFromDataPoint(map[UniqueIDAttrVal]bool{}, pcommon.NewMap()))
m := pcommon.NewMap()
m.PutStr("foo", "bar")
require.Error(t, idSetFromDataPoint(map[UniqueIDAttrVal]bool{}, m))
m.PutInt(UniqueIDAttrName, 64)
require.Error(t, idSetFromDataPoint(map[UniqueIDAttrVal]bool{}, m))
m.PutStr(UniqueIDAttrName, "myid")
result := map[UniqueIDAttrVal]bool{}
require.NoError(t, idSetFromDataPoint(result, m))
require.True(t, result["myid"])
}
func TestBadMetricPoint(t *testing.T) {
for _, test := range []struct {
name string
metrics pmetric.Metrics
}{
{
name: "gauge",
metrics: func() pmetric.Metrics {
m := pmetric.NewMetrics()
m.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()
return m
}(),
},
{
name: "sum",
metrics: func() pmetric.Metrics {
m := pmetric.NewMetrics()
m.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()
return m
}(),
},
{
name: "summary",
metrics: func() pmetric.Metrics {
m := pmetric.NewMetrics()
m.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySummary().DataPoints().AppendEmpty()
return m
}(),
},
{
name: "histogram",
metrics: func() pmetric.Metrics {
m := pmetric.NewMetrics()
m.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyHistogram().DataPoints().AppendEmpty()
return m
}(),
},
{
name: "exponential histogram",
metrics: func() pmetric.Metrics {
m := pmetric.NewMetrics()
m.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyExponentialHistogram().DataPoints().AppendEmpty()
return m
}(),
},
} {
t.Run(test.name, func(t *testing.T) {
_, err := idSetFromMetrics(test.metrics)
require.Error(t, err)
})
}
}