Skip to content

Commit

Permalink
test(processors.rename): Add unit-tests for tracking metrics (#14811)
Browse files Browse the repository at this point in the history
(cherry picked from commit a5a5fac)
  • Loading branch information
powersj committed Feb 20, 2024
1 parent f89fb5d commit 0012a59
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions plugins/processors/rename/rename_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package rename

import (
"sync"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil"
)

func newMetric(name string, tags map[string]string, fields map[string]interface{}) telegraf.Metric {
Expand Down Expand Up @@ -60,3 +62,68 @@ func TestFieldRename(t *testing.T) {

require.Equal(t, map[string]interface{}{"time": int64(1250), "snakes": true}, results[0].Fields(), "should change field 'time_msec' to 'time'")
}

func TestTracking(t *testing.T) {
inputRaw := []telegraf.Metric{
metric.New("foo", map[string]string{}, map[string]interface{}{"value": 42}, time.Unix(0, 0)),
metric.New("bar", map[string]string{}, map[string]interface{}{"value": 99}, time.Unix(0, 0)),
metric.New("baz", map[string]string{}, map[string]interface{}{"value": 11}, 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{},
map[string]interface{}{"new_value": 42},
time.Unix(0, 0),
),
metric.New(
"bar",
map[string]string{},
map[string]interface{}{"new_value": 99},
time.Unix(0, 0),
),
metric.New(
"baz",
map[string]string{},
map[string]interface{}{"new_value": 11},
time.Unix(0, 0),
),
}

plugin := &Rename{
Replaces: []Replace{
{Field: "value", Dest: "new_value"},
},
}

// 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))
}

0 comments on commit 0012a59

Please sign in to comment.