forked from mostafa/xk6-kafka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kafka_helpers_test.go
89 lines (78 loc) · 2.24 KB
/
kafka_helpers_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
package kafka
import (
"context"
"testing"
"github.com/dop251/goja"
"github.com/stretchr/testify/require"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modulestest"
"go.k6.io/k6/lib"
"go.k6.io/k6/metrics"
"gopkg.in/guregu/null.v3"
)
// struct to keep all the things test need in one place
type kafkaTest struct {
rt *goja.Runtime
module *KafkaModule
vu *modulestest.VU
samples chan metrics.SampleContainer
cancelContext context.CancelFunc
}
// GetTestModuleInstance returns a new instance of the Kafka module for testing
func GetTestModuleInstance(t testing.TB) *kafkaTest {
rt := goja.New()
rt.SetFieldNameMapper(common.FieldNameMapper{})
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
root := New()
mockVU := &modulestest.VU{
RuntimeField: rt,
InitEnvField: &common.InitEnvironment{
Registry: metrics.NewRegistry(),
},
CtxField: ctx,
}
mi, ok := root.NewModuleInstance(mockVU).(*KafkaModule)
require.True(t, ok)
require.NoError(t, rt.Set("kafka", mi.Exports().Default))
return &kafkaTest{
rt: rt,
module: mi,
vu: mockVU,
cancelContext: cancel,
}
}
// moveToVUCode moves to the VU code from the init code (to test certain functions)
func (k *kafkaTest) moveToVUCode() error {
rootGroup, err := lib.NewGroup("", nil)
if err != nil {
return err
}
samples := make(chan metrics.SampleContainer, 1000)
// Save it, so we can reuse it in other tests
k.samples = samples
state := &lib.State{
Group: rootGroup,
Options: lib.Options{
UserAgent: null.StringFrom("TestUserAgent"),
Paused: null.BoolFrom(false),
},
Samples: k.samples,
BuiltinMetrics: metrics.RegisterBuiltinMetrics(metrics.NewRegistry()),
}
k.vu.StateField = state
k.vu.InitEnvField = nil
return nil
}
// GetCounterMetricsValues returns the samples of the collected metrics in the VU
func (k *kafkaTest) GetCounterMetricsValues() map[string]float64 {
metricsValues := make(map[string]float64)
for _, sampleContainer := range metrics.GetBufferedSamples(k.samples) {
for _, sample := range sampleContainer.GetSamples() {
if sample.Metric.Type == metrics.Counter {
metricsValues[sample.Metric.Name] = sample.Value
}
}
}
return metricsValues
}