test(processors.tag_limit): Add unit-tests for tracking metrics (#14812)

This commit is contained in:
Joshua Powers 2024-02-14 06:07:37 -05:00 committed by GitHub
parent a5a5fac376
commit a89461554f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 66 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package tag_limit
import (
"sync"
"testing"
"time"
@ -8,6 +9,7 @@ import (
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil"
)
func MustMetric(name string, tags map[string]string, fields map[string]interface{}, metricTime time.Time) telegraf.Metric {
@ -85,3 +87,67 @@ func TestTrim(t *testing.T) {
require.Equal(t, "foo", trimmedTags["a"], "preserved: a")
require.Equal(t, "bar", trimmedTags["b"], "preserved: b")
}
func TestTracking(t *testing.T) {
inputRaw := []telegraf.Metric{
metric.New("foo", map[string]string{"tag": "testing"}, map[string]interface{}{"value": 42}, time.Unix(0, 0)),
metric.New("bar", map[string]string{"tag": "other", "host": "locahost"}, map[string]interface{}{"value": 23}, time.Unix(0, 0)),
metric.New("baz", map[string]string{"tag": "value", "host": "locahost", "module": "main"}, map[string]interface{}{"value": 99}, time.Unix(0, 0)),
}
var mu sync.Mutex
delivered := make([]telegraf.DeliveryInfo, 0, len(inputRaw))
notify := func(di telegraf.DeliveryInfo) {
mu.Lock()
defer mu.Unlock()
delivered = append(delivered, di)
}
input := make([]telegraf.Metric, 0, len(inputRaw))
for _, m := range inputRaw {
tm, _ := metric.WithTracking(m, notify)
input = append(input, tm)
}
expected := []telegraf.Metric{
metric.New(
"foo",
map[string]string{"tag": "testing"},
map[string]interface{}{"value": 42},
time.Unix(0, 0),
),
metric.New(
"bar",
map[string]string{"tag": "other", "host": "locahost"},
map[string]interface{}{"value": 23},
time.Unix(0, 0),
),
metric.New(
"baz",
map[string]string{"tag": "value", "host": "locahost"},
map[string]interface{}{"value": 99},
time.Unix(0, 0),
),
}
plugin := &TagLimit{
Limit: 2,
Keep: []string{"tag", "host"},
}
// Process expected metrics and compare with resulting metrics
actual := plugin.Apply(input...)
testutil.RequireMetricsEqual(t, expected, actual)
// Simulate output acknowledging delivery
for _, m := range actual {
m.Accept()
}
// Check delivery
require.Eventuallyf(t, func() bool {
mu.Lock()
defer mu.Unlock()
return len(expected) == len(delivered)
}, time.Second, 100*time.Millisecond, "%d delivered but %d expected", len(delivered), len(expected))
}