fix: Linter fixes for plugins/processors/[a-z]* (#10161)

Co-authored-by: Pawel Zak <Pawel Zak>
This commit is contained in:
Paweł Żak 2021-11-24 20:38:08 +01:00 committed by GitHub
parent 64bc0ae9c0
commit 2b1a79f327
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 192 additions and 167 deletions

View File

@ -26,13 +26,13 @@ type AwsEc2Processor struct {
Timeout config.Duration `toml:"timeout"` Timeout config.Duration `toml:"timeout"`
Ordered bool `toml:"ordered"` Ordered bool `toml:"ordered"`
MaxParallelCalls int `toml:"max_parallel_calls"` MaxParallelCalls int `toml:"max_parallel_calls"`
Log telegraf.Logger `toml:"-"` Log telegraf.Logger `toml:"-"`
imdsClient *imds.Client `toml:"-"`
imdsTags map[string]struct{} `toml:"-"` imdsClient *imds.Client
ec2Client *ec2.Client `toml:"-"` imdsTagsMap map[string]struct{}
parallel parallel.Parallel `toml:"-"` ec2Client *ec2.Client
instanceID string `toml:"-"` parallel parallel.Parallel
instanceID string
} }
const sampleConfig = ` const sampleConfig = `
@ -128,9 +128,9 @@ func (r *AwsEc2Processor) Init() error {
if len(tag) == 0 || !isImdsTagAllowed(tag) { if len(tag) == 0 || !isImdsTagAllowed(tag) {
return fmt.Errorf("not allowed metadata tag specified in configuration: %s", tag) return fmt.Errorf("not allowed metadata tag specified in configuration: %s", tag)
} }
r.imdsTags[tag] = struct{}{} r.imdsTagsMap[tag] = struct{}{}
} }
if len(r.imdsTags) == 0 && len(r.EC2Tags) == 0 { if len(r.imdsTagsMap) == 0 && len(r.EC2Tags) == 0 {
return errors.New("no allowed metadata tags specified in configuration") return errors.New("no allowed metadata tags specified in configuration")
} }
@ -186,7 +186,7 @@ func (r *AwsEc2Processor) Start(acc telegraf.Accumulator) error {
func (r *AwsEc2Processor) Stop() error { func (r *AwsEc2Processor) Stop() error {
if r.parallel == nil { if r.parallel == nil {
return errors.New("Trying to stop unstarted AWS EC2 Processor") return errors.New("trying to stop unstarted AWS EC2 Processor")
} }
r.parallel.Stop() r.parallel.Stop()
return nil return nil
@ -197,7 +197,7 @@ func (r *AwsEc2Processor) asyncAdd(metric telegraf.Metric) []telegraf.Metric {
defer cancel() defer cancel()
// Add IMDS Instance Identity Document tags. // Add IMDS Instance Identity Document tags.
if len(r.imdsTags) > 0 { if len(r.imdsTagsMap) > 0 {
iido, err := r.imdsClient.GetInstanceIdentityDocument( iido, err := r.imdsClient.GetInstanceIdentityDocument(
ctx, ctx,
&imds.GetInstanceIdentityDocumentInput{}, &imds.GetInstanceIdentityDocumentInput{},
@ -207,7 +207,7 @@ func (r *AwsEc2Processor) asyncAdd(metric telegraf.Metric) []telegraf.Metric {
return []telegraf.Metric{metric} return []telegraf.Metric{metric}
} }
for tag := range r.imdsTags { for tag := range r.imdsTagsMap {
if v := getTagFromInstanceIdentityDocument(iido, tag); v != "" { if v := getTagFromInstanceIdentityDocument(iido, tag); v != "" {
metric.AddTag(tag, v) metric.AddTag(tag, v)
} }
@ -244,7 +244,7 @@ func newAwsEc2Processor() *AwsEc2Processor {
return &AwsEc2Processor{ return &AwsEc2Processor{
MaxParallelCalls: DefaultMaxParallelCalls, MaxParallelCalls: DefaultMaxParallelCalls,
Timeout: config.Duration(DefaultTimeout), Timeout: config.Duration(DefaultTimeout),
imdsTags: make(map[string]struct{}), imdsTagsMap: make(map[string]struct{}),
} }
} }

View File

@ -4,9 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/stretchr/testify/assert"
) )
func createTestMetric() telegraf.Metric { func createTestMetric() telegraf.Metric {
@ -18,8 +19,8 @@ func createTestMetric() telegraf.Metric {
return m return m
} }
func calculateProcessedTags(processor Clone, metric telegraf.Metric) map[string]string { func calculateProcessedTags(processor Clone, m telegraf.Metric) map[string]string {
processed := processor.Apply(metric) processed := processor.Apply(m)
return processed[0].Tags() return processed[0].Tags()
} }
@ -29,8 +30,8 @@ func TestRetainsTags(t *testing.T) {
tags := calculateProcessedTags(processor, createTestMetric()) tags := calculateProcessedTags(processor, createTestMetric())
value, present := tags["metric_tag"] value, present := tags["metric_tag"]
assert.True(t, present, "Tag of metric was not present") require.True(t, present, "Tag of metric was not present")
assert.Equal(t, "from_metric", value, "Value of Tag was changed") require.Equal(t, "from_metric", value, "Value of Tag was changed")
} }
func TestAddTags(t *testing.T) { func TestAddTags(t *testing.T) {
@ -39,9 +40,9 @@ func TestAddTags(t *testing.T) {
tags := calculateProcessedTags(processor, createTestMetric()) tags := calculateProcessedTags(processor, createTestMetric())
value, present := tags["added_tag"] value, present := tags["added_tag"]
assert.True(t, present, "Additional Tag of metric was not present") require.True(t, present, "Additional Tag of metric was not present")
assert.Equal(t, "from_config", value, "Value of Tag was changed") require.Equal(t, "from_config", value, "Value of Tag was changed")
assert.Equal(t, 3, len(tags), "Should have one previous and two added tags.") require.Equal(t, 3, len(tags), "Should have one previous and two added tags.")
} }
func TestOverwritesPresentTagValues(t *testing.T) { func TestOverwritesPresentTagValues(t *testing.T) {
@ -50,9 +51,9 @@ func TestOverwritesPresentTagValues(t *testing.T) {
tags := calculateProcessedTags(processor, createTestMetric()) tags := calculateProcessedTags(processor, createTestMetric())
value, present := tags["metric_tag"] value, present := tags["metric_tag"]
assert.True(t, present, "Tag of metric was not present") require.True(t, present, "Tag of metric was not present")
assert.Equal(t, 1, len(tags), "Should only have one tag.") require.Equal(t, 1, len(tags), "Should only have one tag.")
assert.Equal(t, "from_config", value, "Value of Tag was not changed") require.Equal(t, "from_config", value, "Value of Tag was not changed")
} }
func TestOverridesName(t *testing.T) { func TestOverridesName(t *testing.T) {
@ -60,8 +61,8 @@ func TestOverridesName(t *testing.T) {
processed := processor.Apply(createTestMetric()) processed := processor.Apply(createTestMetric())
assert.Equal(t, "overridden", processed[0].Name(), "Name was not overridden") require.Equal(t, "overridden", processed[0].Name(), "Name was not overridden")
assert.Equal(t, "m1", processed[1].Name(), "Original metric was modified") require.Equal(t, "m1", processed[1].Name(), "Original metric was modified")
} }
func TestNamePrefix(t *testing.T) { func TestNamePrefix(t *testing.T) {
@ -69,8 +70,8 @@ func TestNamePrefix(t *testing.T) {
processed := processor.Apply(createTestMetric()) processed := processor.Apply(createTestMetric())
assert.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied") require.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied")
assert.Equal(t, "m1", processed[1].Name(), "Original metric was modified") require.Equal(t, "m1", processed[1].Name(), "Original metric was modified")
} }
func TestNameSuffix(t *testing.T) { func TestNameSuffix(t *testing.T) {
@ -78,6 +79,6 @@ func TestNameSuffix(t *testing.T) {
processed := processor.Apply(createTestMetric()) processed := processor.Apply(createTestMetric())
assert.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied") require.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied")
assert.Equal(t, "m1", processed[1].Name(), "Original metric was modified") require.Equal(t, "m1", processed[1].Name(), "Original metric was modified")
} }

View File

@ -328,7 +328,7 @@ func (p *Converter) convertFields(metric telegraf.Metric) {
} }
} }
func toBool(v interface{}) (bool, bool) { func toBool(v interface{}) (val bool, ok bool) {
switch value := v.(type) { switch value := v.(type) {
case int64: case int64:
return value != 0, true return value != 0, true

View File

@ -4,12 +4,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func MustMetric(name string, tags map[string]string, fields map[string]interface{}, metricTime time.Time) telegraf.Metric { func MustMetric(name string, tags map[string]string, fields map[string]interface{}, metricTime time.Time) telegraf.Metric {
@ -53,9 +53,9 @@ func TestMonthTag(t *testing.T) {
m2 := MustMetric("bar", nil, nil, currentTime) m2 := MustMetric("bar", nil, nil, currentTime)
m3 := MustMetric("baz", nil, nil, currentTime) m3 := MustMetric("baz", nil, nil, currentTime)
monthApply := dateFormatMonth.Apply(m1, m2, m3) monthApply := dateFormatMonth.Apply(m1, m2, m3)
assert.Equal(t, map[string]string{"month": month}, monthApply[0].Tags(), "should add tag 'month'") require.Equal(t, map[string]string{"month": month}, monthApply[0].Tags(), "should add tag 'month'")
assert.Equal(t, map[string]string{"month": month}, monthApply[1].Tags(), "should add tag 'month'") require.Equal(t, map[string]string{"month": month}, monthApply[1].Tags(), "should add tag 'month'")
assert.Equal(t, map[string]string{"month": month}, monthApply[2].Tags(), "should add tag 'month'") require.Equal(t, map[string]string{"month": month}, monthApply[2].Tags(), "should add tag 'month'")
} }
func TestMonthField(t *testing.T) { func TestMonthField(t *testing.T) {
@ -74,9 +74,9 @@ func TestMonthField(t *testing.T) {
m2 := MustMetric("bar", nil, nil, currentTime) m2 := MustMetric("bar", nil, nil, currentTime)
m3 := MustMetric("baz", nil, nil, currentTime) m3 := MustMetric("baz", nil, nil, currentTime)
monthApply := dateFormatMonth.Apply(m1, m2, m3) monthApply := dateFormatMonth.Apply(m1, m2, m3)
assert.Equal(t, map[string]interface{}{"month": month}, monthApply[0].Fields(), "should add field 'month'") require.Equal(t, map[string]interface{}{"month": month}, monthApply[0].Fields(), "should add field 'month'")
assert.Equal(t, map[string]interface{}{"month": month}, monthApply[1].Fields(), "should add field 'month'") require.Equal(t, map[string]interface{}{"month": month}, monthApply[1].Fields(), "should add field 'month'")
assert.Equal(t, map[string]interface{}{"month": month}, monthApply[2].Fields(), "should add field 'month'") require.Equal(t, map[string]interface{}{"month": month}, monthApply[2].Fields(), "should add field 'month'")
} }
func TestOldDateTag(t *testing.T) { func TestOldDateTag(t *testing.T) {
@ -90,7 +90,7 @@ func TestOldDateTag(t *testing.T) {
m7 := MustMetric("foo", nil, nil, time.Date(1993, 05, 27, 0, 0, 0, 0, time.UTC)) m7 := MustMetric("foo", nil, nil, time.Date(1993, 05, 27, 0, 0, 0, 0, time.UTC))
customDateApply := dateFormatYear.Apply(m7) customDateApply := dateFormatYear.Apply(m7)
assert.Equal(t, map[string]string{"year": "1993"}, customDateApply[0].Tags(), "should add tag 'year'") require.Equal(t, map[string]string{"year": "1993"}, customDateApply[0].Tags(), "should add tag 'year'")
} }
func TestFieldUnix(t *testing.T) { func TestFieldUnix(t *testing.T) {
@ -107,7 +107,7 @@ func TestFieldUnix(t *testing.T) {
m8 := MustMetric("foo", nil, nil, currentTime) m8 := MustMetric("foo", nil, nil, currentTime)
unixApply := dateFormatUnix.Apply(m8) unixApply := dateFormatUnix.Apply(m8)
assert.Equal(t, map[string]interface{}{"unix": unixTime}, unixApply[0].Fields(), "should add unix time in s as field 'unix'") require.Equal(t, map[string]interface{}{"unix": unixTime}, unixApply[0].Fields(), "should add unix time in s as field 'unix'")
} }
func TestFieldUnixNano(t *testing.T) { func TestFieldUnixNano(t *testing.T) {
@ -124,7 +124,7 @@ func TestFieldUnixNano(t *testing.T) {
m9 := MustMetric("foo", nil, nil, currentTime) m9 := MustMetric("foo", nil, nil, currentTime)
unixNanoApply := dateFormatUnixNano.Apply(m9) unixNanoApply := dateFormatUnixNano.Apply(m9)
assert.Equal(t, map[string]interface{}{"unix_ns": unixNanoTime}, unixNanoApply[0].Fields(), "should add unix time in ns as field 'unix_ns'") require.Equal(t, map[string]interface{}{"unix_ns": unixNanoTime}, unixNanoApply[0].Fields(), "should add unix time in ns as field 'unix_ns'")
} }
func TestFieldUnixMillis(t *testing.T) { func TestFieldUnixMillis(t *testing.T) {
@ -141,7 +141,7 @@ func TestFieldUnixMillis(t *testing.T) {
m10 := MustMetric("foo", nil, nil, currentTime) m10 := MustMetric("foo", nil, nil, currentTime)
unixMillisApply := dateFormatUnixMillis.Apply(m10) unixMillisApply := dateFormatUnixMillis.Apply(m10)
assert.Equal(t, map[string]interface{}{"unix_ms": unixMillisTime}, unixMillisApply[0].Fields(), "should add unix time in ms as field 'unix_ms'") require.Equal(t, map[string]interface{}{"unix_ms": unixMillisTime}, unixMillisApply[0].Fields(), "should add unix time in ms as field 'unix_ms'")
} }
func TestFieldUnixMicros(t *testing.T) { func TestFieldUnixMicros(t *testing.T) {
@ -158,7 +158,7 @@ func TestFieldUnixMicros(t *testing.T) {
m11 := MustMetric("foo", nil, nil, currentTime) m11 := MustMetric("foo", nil, nil, currentTime)
unixMicrosApply := dateFormatUnixMicros.Apply(m11) unixMicrosApply := dateFormatUnixMicros.Apply(m11)
assert.Equal(t, map[string]interface{}{"unix_us": unixMicrosTime}, unixMicrosApply[0].Fields(), "should add unix time in us as field 'unix_us'") require.Equal(t, map[string]interface{}{"unix_us": unixMicrosTime}, unixMicrosApply[0].Fields(), "should add unix time in us as field 'unix_us'")
} }
func TestDateOffset(t *testing.T) { func TestDateOffset(t *testing.T) {
@ -171,7 +171,7 @@ func TestDateOffset(t *testing.T) {
err := plugin.Init() err := plugin.Init()
require.NoError(t, err) require.NoError(t, err)
metric := testutil.MustMetric( m := testutil.MustMetric(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -193,6 +193,6 @@ func TestDateOffset(t *testing.T) {
), ),
} }
actual := plugin.Apply(metric) actual := plugin.Apply(m)
testutil.RequireMetricsEqual(t, expected, actual) testutil.RequireMetricsEqual(t, expected, actual)
} }

View File

@ -77,6 +77,7 @@ func assertMetricPassed(t *testing.T, target []telegraf.Metric, source telegraf.
tValue, present := target[0].GetField("value") tValue, present := target[0].GetField("value")
require.True(t, present) require.True(t, present)
sValue, present := source.GetField("value") sValue, present := source.GetField("value")
require.True(t, present)
require.Equal(t, tValue, sValue) require.Equal(t, tValue, sValue)
// target metric has proper timestamp // target metric has proper timestamp
require.Equal(t, target[0].Time(), source.Time()) require.Equal(t, target[0].Time(), source.Time())
@ -100,9 +101,9 @@ func TestSuppressRepeatedValue(t *testing.T) {
deduplicate := createDedup(time.Now()) deduplicate := createDedup(time.Now())
// Create metric in the past // Create metric in the past
source := createMetric(1, time.Now().Add(-1*time.Second)) source := createMetric(1, time.Now().Add(-1*time.Second))
target := deduplicate.Apply(source) _ = deduplicate.Apply(source)
source = createMetric(1, time.Now()) source = createMetric(1, time.Now())
target = deduplicate.Apply(source) target := deduplicate.Apply(source)
assertCacheHit(t, &deduplicate, source) assertCacheHit(t, &deduplicate, source)
assertMetricSuppressed(t, target) assertMetricSuppressed(t, target)
@ -113,9 +114,10 @@ func TestPassUpdatedValue(t *testing.T) {
// Create metric in the past // Create metric in the past
source := createMetric(1, time.Now().Add(-1*time.Second)) source := createMetric(1, time.Now().Add(-1*time.Second))
target := deduplicate.Apply(source) target := deduplicate.Apply(source)
assertMetricPassed(t, target, source)
source = createMetric(2, time.Now()) source = createMetric(2, time.Now())
target = deduplicate.Apply(source) target = deduplicate.Apply(source)
assertCacheRefresh(t, &deduplicate, source) assertCacheRefresh(t, &deduplicate, source)
assertMetricPassed(t, target, source) assertMetricPassed(t, target, source)
} }
@ -125,9 +127,10 @@ func TestPassAfterCacheExpire(t *testing.T) {
// Create metric in the past // Create metric in the past
source := createMetric(1, time.Now().Add(-1*time.Hour)) source := createMetric(1, time.Now().Add(-1*time.Hour))
target := deduplicate.Apply(source) target := deduplicate.Apply(source)
assertMetricPassed(t, target, source)
source = createMetric(1, time.Now()) source = createMetric(1, time.Now())
target = deduplicate.Apply(source) target = deduplicate.Apply(source)
assertCacheRefresh(t, &deduplicate, source) assertCacheRefresh(t, &deduplicate, source)
assertMetricPassed(t, target, source) assertMetricPassed(t, target, source)
} }

View File

@ -1,9 +1,10 @@
package defaults package defaults
import ( import (
"strings"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/processors" "github.com/influxdata/telegraf/plugins/processors"
"strings"
) )
const sampleConfig = ` const sampleConfig = `
@ -58,10 +59,10 @@ func (def *Defaults) Apply(inputMetrics ...telegraf.Metric) []telegraf.Metric {
} }
func maybeTrimmedString(v interface{}) (string, bool) { func maybeTrimmedString(v interface{}) (string, bool) {
switch value := v.(type) { if value, ok := v.(string); ok {
case string:
return strings.TrimSpace(value), true return strings.TrimSpace(value), true
} }
return "", false return "", false
} }

View File

@ -4,9 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
) )
func TestDefaults(t *testing.T) { func TestDefaults(t *testing.T) {
@ -124,7 +125,7 @@ func TestDefaults(t *testing.T) {
defaults := scenario.defaults defaults := scenario.defaults
resultMetrics := defaults.Apply(scenario.input) resultMetrics := defaults.Apply(scenario.input)
assert.Len(t, resultMetrics, 1) require.Len(t, resultMetrics, 1)
testutil.RequireMetricsEqual(t, scenario.expected, resultMetrics) testutil.RequireMetricsEqual(t, scenario.expected, resultMetrics)
}) })
} }

View File

@ -4,10 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func createTestMetric() telegraf.Metric { func createTestMetric() telegraf.Metric {
@ -19,7 +19,7 @@ func createTestMetric() telegraf.Metric {
map[string]interface{}{ map[string]interface{}{
"string_value": "test", "string_value": "test",
"duplicate_string_value": "test", "duplicate_string_value": "test",
"int_value": int(200), "int_value": 200,
"uint_value": uint(500), "uint_value": uint(500),
"float_value": float64(3.14), "float_value": float64(3.14),
"true_value": true, "true_value": true,
@ -29,26 +29,26 @@ func createTestMetric() telegraf.Metric {
return m return m
} }
func calculateProcessedValues(mapper EnumMapper, metric telegraf.Metric) map[string]interface{} { func calculateProcessedValues(mapper EnumMapper, m telegraf.Metric) map[string]interface{} {
processed := mapper.Apply(metric) processed := mapper.Apply(m)
return processed[0].Fields() return processed[0].Fields()
} }
func calculateProcessedTags(mapper EnumMapper, metric telegraf.Metric) map[string]string { func calculateProcessedTags(mapper EnumMapper, m telegraf.Metric) map[string]string {
processed := mapper.Apply(metric) processed := mapper.Apply(m)
return processed[0].Tags() return processed[0].Tags()
} }
func assertFieldValue(t *testing.T, expected interface{}, field string, fields map[string]interface{}) { func assertFieldValue(t *testing.T, expected interface{}, field string, fields map[string]interface{}) {
value, present := fields[field] value, present := fields[field]
assert.True(t, present, "value of field '"+field+"' was not present") require.True(t, present, "value of field '"+field+"' was not present")
assert.EqualValues(t, expected, value) require.EqualValues(t, expected, value)
} }
func assertTagValue(t *testing.T, expected interface{}, tag string, tags map[string]string) { func assertTagValue(t *testing.T, expected interface{}, tag string, tags map[string]string) {
value, present := tags[tag] value, present := tags[tag]
assert.True(t, present, "value of tag '"+tag+"' was not present") require.True(t, present, "value of tag '"+tag+"' was not present")
assert.EqualValues(t, expected, value) require.EqualValues(t, expected, value)
} }
func TestRetainsMetric(t *testing.T) { func TestRetainsMetric(t *testing.T) {
@ -65,9 +65,9 @@ func TestRetainsMetric(t *testing.T) {
assertFieldValue(t, 500, "uint_value", fields) assertFieldValue(t, 500, "uint_value", fields)
assertFieldValue(t, float64(3.14), "float_value", fields) assertFieldValue(t, float64(3.14), "float_value", fields)
assertFieldValue(t, true, "true_value", fields) assertFieldValue(t, true, "true_value", fields)
assert.Equal(t, "m1", target.Name()) require.Equal(t, "m1", target.Name())
assert.Equal(t, source.Tags(), target.Tags()) require.Equal(t, source.Tags(), target.Tags())
assert.Equal(t, source.Time(), target.Time()) require.Equal(t, source.Time(), target.Time())
} }
func TestMapsSingleStringValueTag(t *testing.T) { func TestMapsSingleStringValueTag(t *testing.T) {
@ -118,7 +118,7 @@ func TestMappings(t *testing.T) {
for index := range mapping["target_value"] { for index := range mapping["target_value"] {
mapper := EnumMapper{Mappings: []Mapping{{Field: fieldName, ValueMappings: map[string]interface{}{mapping["target_value"][index].(string): mapping["mapped_value"][index]}}}} mapper := EnumMapper{Mappings: []Mapping{{Field: fieldName, ValueMappings: map[string]interface{}{mapping["target_value"][index].(string): mapping["mapped_value"][index]}}}}
err := mapper.Init() err := mapper.Init()
assert.Nil(t, err) require.Nil(t, err)
fields := calculateProcessedValues(mapper, createTestMetric()) fields := calculateProcessedValues(mapper, createTestMetric())
assertFieldValue(t, mapping["expected_value"][index], fieldName, fields) assertFieldValue(t, mapping["expected_value"][index], fieldName, fields)
} }
@ -171,7 +171,7 @@ func TestDoNotWriteToDestinationWithoutDefaultOrDefinedMapping(t *testing.T) {
assertFieldValue(t, "test", "string_value", fields) assertFieldValue(t, "test", "string_value", fields)
_, present := fields[field] _, present := fields[field]
assert.False(t, present, "value of field '"+field+"' was present") require.False(t, present, "value of field '"+field+"' was present")
} }
func TestFieldGlobMatching(t *testing.T) { func TestFieldGlobMatching(t *testing.T) {

View File

@ -7,13 +7,13 @@ import (
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/plugins/parsers/influx" "github.com/influxdata/telegraf/plugins/parsers/influx"
"github.com/influxdata/telegraf/plugins/serializers" "github.com/influxdata/telegraf/plugins/serializers"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestExternalProcessorWorks(t *testing.T) { func TestExternalProcessorWorks(t *testing.T) {
@ -32,7 +32,6 @@ func TestExternalProcessorWorks(t *testing.T) {
now := time.Now() now := time.Now()
orig := now orig := now
metrics := []telegraf.Metric{}
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
m := metric.New("test", m := metric.New("test",
map[string]string{ map[string]string{
@ -43,17 +42,16 @@ func TestExternalProcessorWorks(t *testing.T) {
"count": 1, "count": 1,
}, },
now) now)
metrics = append(metrics, m)
now = now.Add(1) now = now.Add(1)
e.Add(m, acc) require.NoError(t, e.Add(m, acc))
} }
acc.Wait(1) acc.Wait(1)
require.NoError(t, e.Stop()) require.NoError(t, e.Stop())
acc.Wait(9) acc.Wait(9)
metrics = acc.GetTelegrafMetrics() metrics := acc.GetTelegrafMetrics()
m := metrics[0] m := metrics[0]
expected := testutil.MustMetric("test", expected := testutil.MustMetric("test",
@ -105,7 +103,7 @@ func TestParseLinesWithNewLines(t *testing.T) {
}, },
now) now)
e.Add(m, acc) require.NoError(t, e.Add(m, acc))
acc.Wait(1) acc.Wait(1)
require.NoError(t, e.Stop()) require.NoError(t, e.Stop())
@ -144,40 +142,51 @@ func runCountMultiplierProgram() {
serializer, _ := serializers.NewInfluxSerializer() serializer, _ := serializers.NewInfluxSerializer()
for { for {
metric, err := parser.Next() m, err := parser.Next()
if err != nil { if err != nil {
if err == influx.EOF { if err == influx.EOF {
return // stream ended return // stream ended
} }
if parseErr, isParseError := err.(*influx.ParseError); isParseError { if parseErr, isParseError := err.(*influx.ParseError); isParseError {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "parse ERR %v\n", parseErr) fmt.Fprintf(os.Stderr, "parse ERR %v\n", parseErr)
//nolint:revive // os.Exit called intentionally
os.Exit(1) os.Exit(1)
} }
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "ERR %v\n", err) fmt.Fprintf(os.Stderr, "ERR %v\n", err)
//nolint:revive // os.Exit called intentionally
os.Exit(1) os.Exit(1)
} }
c, found := metric.GetField("count") c, found := m.GetField("count")
if !found { if !found {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "metric has no count field\n") fmt.Fprintf(os.Stderr, "metric has no count field\n")
//nolint:revive // os.Exit called intentionally
os.Exit(1) os.Exit(1)
} }
switch t := c.(type) { switch t := c.(type) {
case float64: case float64:
t *= 2 t *= 2
metric.AddField("count", t) m.AddField("count", t)
case int64: case int64:
t *= 2 t *= 2
metric.AddField("count", t) m.AddField("count", t)
default: default:
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "count is not an unknown type, it's a %T\n", c) fmt.Fprintf(os.Stderr, "count is not an unknown type, it's a %T\n", c)
//nolint:revive // os.Exit called intentionally
os.Exit(1) os.Exit(1)
} }
b, err := serializer.Serialize(metric) b, err := serializer.Serialize(m)
if err != nil { if err != nil {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "ERR %v\n", err) fmt.Fprintf(os.Stderr, "ERR %v\n", err)
//nolint:revive // os.Exit called intentionally
os.Exit(1) os.Exit(1)
} }
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, string(b)) fmt.Fprint(os.Stdout, string(b))
} }
} }

View File

@ -80,7 +80,7 @@ type valType = nameMap
type mapFunc func(agent string) (nameMap, error) type mapFunc func(agent string) (nameMap, error)
type makeTableFunc func(string) (*si.Table, error) type makeTableFunc func(string) (*si.Table, error)
type sigMap map[string](chan struct{}) type sigMap map[string]chan struct{}
type IfName struct { type IfName struct {
SourceTag string `toml:"tag"` SourceTag string `toml:"tag"`
@ -96,24 +96,24 @@ type IfName struct {
Log telegraf.Logger `toml:"-"` Log telegraf.Logger `toml:"-"`
ifTable *si.Table `toml:"-"` ifTable *si.Table
ifXTable *si.Table `toml:"-"` ifXTable *si.Table
lock sync.Mutex `toml:"-"` lock sync.Mutex
cache *TTLCache `toml:"-"` cache *TTLCache
parallel parallel.Parallel `toml:"-"` parallel parallel.Parallel
acc telegraf.Accumulator `toml:"-"` acc telegraf.Accumulator
getMapRemote mapFunc `toml:"-"` getMapRemote mapFunc
makeTable makeTableFunc `toml:"-"` makeTable makeTableFunc
gsBase snmp.GosnmpWrapper `toml:"-"` gsBase snmp.GosnmpWrapper
sigs sigMap `toml:"-"` sigs sigMap
} }
const minRetry time.Duration = 5 * time.Minute const minRetry = 5 * time.Minute
func (d *IfName) SampleConfig() string { func (d *IfName) SampleConfig() string {
return sampleConfig return sampleConfig

View File

@ -18,15 +18,16 @@ func TestTable(t *testing.T) {
t.Skip("Skipping test due to connect failures") t.Skip("Skipping test due to connect failures")
d := IfName{} d := IfName{}
d.Init() err := d.Init()
require.NoError(t, err)
tab, err := d.makeTable("IF-MIB::ifTable") tab, err := d.makeTable("IF-MIB::ifTable")
require.NoError(t, err) require.NoError(t, err)
config := snmp.ClientConfig{ clientConfig := snmp.ClientConfig{
Version: 2, Version: 2,
Timeout: config.Duration(5 * time.Second), // Doesn't work with 0 timeout Timeout: config.Duration(5 * time.Second), // Doesn't work with 0 timeout
} }
gs, err := snmp.NewWrapper(config) gs, err := snmp.NewWrapper(clientConfig)
require.NoError(t, err) require.NoError(t, err)
err = gs.SetAgent("127.0.0.1") err = gs.SetAgent("127.0.0.1")
require.NoError(t, err) require.NoError(t, err)

View File

@ -4,9 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/stretchr/testify/assert"
) )
func createTestMetric() telegraf.Metric { func createTestMetric() telegraf.Metric {
@ -18,8 +19,8 @@ func createTestMetric() telegraf.Metric {
return m return m
} }
func calculateProcessedTags(processor Override, metric telegraf.Metric) map[string]string { func calculateProcessedTags(processor Override, m telegraf.Metric) map[string]string {
processed := processor.Apply(metric) processed := processor.Apply(m)
return processed[0].Tags() return processed[0].Tags()
} }
@ -29,8 +30,8 @@ func TestRetainsTags(t *testing.T) {
tags := calculateProcessedTags(processor, createTestMetric()) tags := calculateProcessedTags(processor, createTestMetric())
value, present := tags["metric_tag"] value, present := tags["metric_tag"]
assert.True(t, present, "Tag of metric was not present") require.True(t, present, "Tag of metric was not present")
assert.Equal(t, "from_metric", value, "Value of Tag was changed") require.Equal(t, "from_metric", value, "Value of Tag was changed")
} }
func TestAddTags(t *testing.T) { func TestAddTags(t *testing.T) {
@ -39,9 +40,9 @@ func TestAddTags(t *testing.T) {
tags := calculateProcessedTags(processor, createTestMetric()) tags := calculateProcessedTags(processor, createTestMetric())
value, present := tags["added_tag"] value, present := tags["added_tag"]
assert.True(t, present, "Additional Tag of metric was not present") require.True(t, present, "Additional Tag of metric was not present")
assert.Equal(t, "from_config", value, "Value of Tag was changed") require.Equal(t, "from_config", value, "Value of Tag was changed")
assert.Equal(t, 3, len(tags), "Should have one previous and two added tags.") require.Equal(t, 3, len(tags), "Should have one previous and two added tags.")
} }
func TestOverwritesPresentTagValues(t *testing.T) { func TestOverwritesPresentTagValues(t *testing.T) {
@ -50,9 +51,9 @@ func TestOverwritesPresentTagValues(t *testing.T) {
tags := calculateProcessedTags(processor, createTestMetric()) tags := calculateProcessedTags(processor, createTestMetric())
value, present := tags["metric_tag"] value, present := tags["metric_tag"]
assert.True(t, present, "Tag of metric was not present") require.True(t, present, "Tag of metric was not present")
assert.Equal(t, 1, len(tags), "Should only have one tag.") require.Equal(t, 1, len(tags), "Should only have one tag.")
assert.Equal(t, "from_config", value, "Value of Tag was not changed") require.Equal(t, "from_config", value, "Value of Tag was not changed")
} }
func TestOverridesName(t *testing.T) { func TestOverridesName(t *testing.T) {
@ -60,7 +61,7 @@ func TestOverridesName(t *testing.T) {
processed := processor.Apply(createTestMetric()) processed := processor.Apply(createTestMetric())
assert.Equal(t, "overridden", processed[0].Name(), "Name was not overridden") require.Equal(t, "overridden", processed[0].Name(), "Name was not overridden")
} }
func TestNamePrefix(t *testing.T) { func TestNamePrefix(t *testing.T) {
@ -68,7 +69,7 @@ func TestNamePrefix(t *testing.T) {
processed := processor.Apply(createTestMetric()) processed := processor.Apply(createTestMetric())
assert.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied") require.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied")
} }
func TestNameSuffix(t *testing.T) { func TestNameSuffix(t *testing.T) {
@ -76,5 +77,5 @@ func TestNameSuffix(t *testing.T) {
processed := processor.Apply(createTestMetric()) processed := processor.Apply(createTestMetric())
assert.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied") require.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied")
} }

View File

@ -4,9 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/stretchr/testify/assert"
) )
func newMetric(name string, tags map[string]string, fields map[string]interface{}) telegraf.Metric { func newMetric(name string, tags map[string]string, fields map[string]interface{}) telegraf.Metric {
@ -31,9 +32,9 @@ func TestMeasurementRename(t *testing.T) {
m2 := newMetric("bar", nil, nil) m2 := newMetric("bar", nil, nil)
m3 := newMetric("baz", nil, nil) m3 := newMetric("baz", nil, nil)
results := r.Apply(m1, m2, m3) results := r.Apply(m1, m2, m3)
assert.Equal(t, "bar", results[0].Name(), "Should change name from 'foo' to 'bar'") require.Equal(t, "bar", results[0].Name(), "Should change name from 'foo' to 'bar'")
assert.Equal(t, "bar", results[1].Name(), "Should not name from 'bar'") require.Equal(t, "bar", results[1].Name(), "Should not name from 'bar'")
assert.Equal(t, "quux", results[2].Name(), "Should change name from 'baz' to 'quux'") require.Equal(t, "quux", results[2].Name(), "Should change name from 'baz' to 'quux'")
} }
func TestTagRename(t *testing.T) { func TestTagRename(t *testing.T) {
@ -45,7 +46,7 @@ func TestTagRename(t *testing.T) {
m := newMetric("foo", map[string]string{"hostname": "localhost", "region": "east-1"}, nil) m := newMetric("foo", map[string]string{"hostname": "localhost", "region": "east-1"}, nil)
results := r.Apply(m) results := r.Apply(m)
assert.Equal(t, map[string]string{"host": "localhost", "region": "east-1"}, results[0].Tags(), "should change tag 'hostname' to 'host'") require.Equal(t, map[string]string{"host": "localhost", "region": "east-1"}, results[0].Tags(), "should change tag 'hostname' to 'host'")
} }
func TestFieldRename(t *testing.T) { func TestFieldRename(t *testing.T) {
@ -57,5 +58,5 @@ func TestFieldRename(t *testing.T) {
m := newMetric("foo", nil, map[string]interface{}{"time_msec": int64(1250), "snakes": true}) m := newMetric("foo", nil, map[string]interface{}{"time_msec": int64(1250), "snakes": true})
results := r.Apply(m) results := r.Apply(m)
assert.Equal(t, map[string]interface{}{"time": int64(1250), "snakes": true}, results[0].Fields(), "should change field 'time_msec' to 'time'") require.Equal(t, map[string]interface{}{"time": int64(1250), "snakes": true}, results[0].Fields(), "should change field 'time_msec' to 'time'")
} }

View File

@ -104,10 +104,7 @@ func (d *ReverseDNSCache) Lookup(ip string) ([]string, error) {
if len(ip) == 0 { if len(ip) == 0 {
return nil, nil return nil, nil
} }
return d.lookup(ip)
}
func (d *ReverseDNSCache) lookup(ip string) ([]string, error) {
// check if the value is cached // check if the value is cached
d.rwLock.RLock() d.rwLock.RLock()
result, found := d.lockedGetFromCache(ip) result, found := d.lockedGetFromCache(ip)
@ -298,12 +295,6 @@ func (d *ReverseDNSCache) cleanup() {
} }
} }
// blockAllWorkers is a test function that eats up all the worker pool space to
// make sure workers are done running and there's no room to acquire a new worker.
func (d *ReverseDNSCache) blockAllWorkers() {
d.sem.Acquire(context.Background(), int64(d.maxWorkers))
}
func (d *ReverseDNSCache) Stats() RDNSCacheStats { func (d *ReverseDNSCache) Stats() RDNSCacheStats {
stats := RDNSCacheStats{} stats := RDNSCacheStats{}
stats.CacheHit = atomic.LoadUint64(&d.stats.CacheHit) stats.CacheHit = atomic.LoadUint64(&d.stats.CacheHit)

View File

@ -18,7 +18,8 @@ func TestSimpleReverseDNSLookup(t *testing.T) {
answer, err := d.Lookup("127.0.0.1") answer, err := d.Lookup("127.0.0.1")
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []string{"localhost"}, answer) require.Equal(t, []string{"localhost"}, answer)
d.blockAllWorkers() err = blockAllWorkers(d)
require.NoError(t, err)
// do another request with no workers available. // do another request with no workers available.
// it should read from cache instantly. // it should read from cache instantly.
@ -134,3 +135,9 @@ type localResolver struct{}
func (r *localResolver) LookupAddr(_ context.Context, _ string) (names []string, err error) { func (r *localResolver) LookupAddr(_ context.Context, _ string) (names []string, err error) {
return []string{"localhost"}, nil return []string{"localhost"}, nil
} }
// blockAllWorkers is a test function that eats up all the worker pool space to
// make sure workers are done running and there's no room to acquire a new worker.
func blockAllWorkers(d *ReverseDNSCache) error {
return d.sem.Acquire(context.Background(), int64(d.maxWorkers))
}

View File

@ -33,9 +33,12 @@ func TestSimpleReverseLookup(t *testing.T) {
}, },
} }
acc := &testutil.Accumulator{} acc := &testutil.Accumulator{}
dns.Start(acc) err := dns.Start(acc)
dns.Add(m, acc) require.NoError(t, err)
dns.Stop() err = dns.Add(m, acc)
require.NoError(t, err)
err = dns.Stop()
require.NoError(t, err)
// should be processed now. // should be processed now.
require.Len(t, acc.GetTelegrafMetrics(), 1) require.Len(t, acc.GetTelegrafMetrics(), 1)

View File

@ -9,15 +9,16 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
starlarktime "go.starlark.net/lib/time"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
common "github.com/influxdata/telegraf/plugins/common/starlark" common "github.com/influxdata/telegraf/plugins/common/starlark"
"github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
starlarktime "go.starlark.net/lib/time"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
) )
// Tests for runtime errors in the processors Init function. // Tests for runtime errors in the processors Init function.
@ -2674,11 +2675,11 @@ func buildPlugin(configContent string) (*Starlark, error) {
return nil, err return nil, err
} }
if len(c.Processors) != 1 { if len(c.Processors) != 1 {
return nil, errors.New("Only one processor was expected") return nil, errors.New("only one processor was expected")
} }
plugin, ok := (c.Processors[0].Processor).(*Starlark) plugin, ok := (c.Processors[0].Processor).(*Starlark)
if !ok { if !ok {
return nil, errors.New("Only a Starlark processor was expected") return nil, errors.New("only a Starlark processor was expected")
} }
plugin.Log = testutil.Logger{} plugin.Log = testutil.Logger{}
return plugin, nil return plugin, nil
@ -3199,7 +3200,8 @@ def apply(metric):
b.ResetTimer() b.ResetTimer()
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
for _, m := range tt.input { for _, m := range tt.input {
plugin.Add(m, &acc) err = plugin.Add(m, &acc)
require.NoError(b, err)
} }
} }
@ -3213,7 +3215,7 @@ func TestAllScriptTestData(t *testing.T) {
// can be run from multiple folders // can be run from multiple folders
paths := []string{"testdata", "plugins/processors/starlark/testdata"} paths := []string{"testdata", "plugins/processors/starlark/testdata"}
for _, testdataPath := range paths { for _, testdataPath := range paths {
filepath.Walk(testdataPath, func(path string, info os.FileInfo, err error) error { err := filepath.Walk(testdataPath, func(path string, info os.FileInfo, err error) error {
if info == nil || info.IsDir() { if info == nil || info.IsDir() {
return nil return nil
} }
@ -3252,6 +3254,7 @@ func TestAllScriptTestData(t *testing.T) {
}) })
return nil return nil
}) })
require.NoError(t, err)
} }
} }
@ -3316,7 +3319,7 @@ func testLoadFunc(module string, logger telegraf.Logger) (starlark.StringDict, e
return result, nil return result, nil
} }
func testNow(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { func testNow(_ *starlark.Thread, _ *starlark.Builtin, _ starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) {
return starlarktime.Time(time.Date(2021, 4, 15, 12, 0, 0, 999, time.UTC)), nil return starlarktime.Time(time.Date(2021, 4, 15, 12, 0, 0, 999, time.UTC)), nil
} }

View File

@ -4,11 +4,11 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func newM1() telegraf.Metric { func newM1() telegraf.Metric {
@ -318,6 +318,7 @@ func TestFieldKeyConversions(t *testing.T) {
check: func(t *testing.T, actual telegraf.Metric) { check: func(t *testing.T, actual telegraf.Metric) {
fv, ok := actual.GetField("Request") fv, ok := actual.GetField("Request")
require.False(t, ok) require.False(t, ok)
require.Nil(t, fv)
fv, ok = actual.GetField("REQUEST") fv, ok = actual.GetField("REQUEST")
require.True(t, ok) require.True(t, ok)
@ -686,7 +687,7 @@ func TestTagKeyConversions(t *testing.T) {
require.True(t, ok) require.True(t, ok)
require.Equal(t, "GET", tv) require.Equal(t, "GET", tv)
tv, ok = actual.GetTag("S-ComputerName") _, ok = actual.GetTag("S-ComputerName")
require.False(t, ok) require.False(t, ok)
tv, ok = actual.GetTag("s-computername") tv, ok = actual.GetTag("s-computername")
@ -708,7 +709,7 @@ func TestTagKeyConversions(t *testing.T) {
require.True(t, ok) require.True(t, ok)
require.Equal(t, "GET", tv) require.Equal(t, "GET", tv)
tv, ok = actual.GetTag("S-ComputerName") _, ok = actual.GetTag("S-ComputerName")
require.False(t, ok) require.False(t, ok)
tv, ok = actual.GetTag("S-COMPUTERNAME") tv, ok = actual.GetTag("S-COMPUTERNAME")
@ -831,8 +832,8 @@ func TestMultipleConversions(t *testing.T) {
"bar": "y", "bar": "y",
} }
assert.Equal(t, expectedFields, processed[0].Fields()) require.Equal(t, expectedFields, processed[0].Fields())
assert.Equal(t, expectedTags, processed[0].Tags()) require.Equal(t, expectedTags, processed[0].Tags())
} }
func TestReadmeExample(t *testing.T) { func TestReadmeExample(t *testing.T) {
@ -888,8 +889,8 @@ func TestReadmeExample(t *testing.T) {
"resp_bytes": int64(270), "resp_bytes": int64(270),
} }
assert.Equal(t, expectedFields, processed[0].Fields()) require.Equal(t, expectedFields, processed[0].Fields())
assert.Equal(t, expectedTags, processed[0].Tags()) require.Equal(t, expectedTags, processed[0].Tags())
} }
func newMetric(name string) telegraf.Metric { func newMetric(name string) telegraf.Metric {
@ -915,9 +916,9 @@ func TestMeasurementReplace(t *testing.T) {
newMetric("average_cpu_usage"), newMetric("average_cpu_usage"),
} }
results := plugin.Apply(metrics...) results := plugin.Apply(metrics...)
assert.Equal(t, "foo:some-value:bar", results[0].Name(), "`_` was not changed to `-`") require.Equal(t, "foo:some-value:bar", results[0].Name(), "`_` was not changed to `-`")
assert.Equal(t, "average:cpu:usage", results[1].Name(), "Input name should have been unchanged") require.Equal(t, "average:cpu:usage", results[1].Name(), "Input name should have been unchanged")
assert.Equal(t, "average-cpu-usage", results[2].Name(), "All instances of `_` should have been changed to `-`") require.Equal(t, "average-cpu-usage", results[2].Name(), "All instances of `_` should have been changed to `-`")
} }
func TestMeasurementCharDeletion(t *testing.T) { func TestMeasurementCharDeletion(t *testing.T) {
@ -936,9 +937,9 @@ func TestMeasurementCharDeletion(t *testing.T) {
newMetric("barbarbar"), newMetric("barbarbar"),
} }
results := plugin.Apply(metrics...) results := plugin.Apply(metrics...)
assert.Equal(t, ":bar:baz", results[0].Name(), "Should have deleted the initial `foo`") require.Equal(t, ":bar:baz", results[0].Name(), "Should have deleted the initial `foo`")
assert.Equal(t, "foofoofoo", results[1].Name(), "Should have refused to delete the whole string") require.Equal(t, "foofoofoo", results[1].Name(), "Should have refused to delete the whole string")
assert.Equal(t, "barbarbar", results[2].Name(), "Should not have changed the input") require.Equal(t, "barbarbar", results[2].Name(), "Should not have changed the input")
} }
func TestBase64Decode(t *testing.T) { func TestBase64Decode(t *testing.T) {

View File

@ -2,9 +2,9 @@ package taglimit
import ( import (
"fmt" "fmt"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/processors" "github.com/influxdata/telegraf/plugins/processors"
"log"
) )
const sampleConfig = ` const sampleConfig = `
@ -18,6 +18,7 @@ const sampleConfig = `
type TagLimit struct { type TagLimit struct {
Limit int `toml:"limit"` Limit int `toml:"limit"`
Keep []string `toml:"keep"` Keep []string `toml:"keep"`
Log telegraf.Logger `toml:"-"`
init bool init bool
keepTags map[string]string keepTags map[string]string
} }
@ -49,7 +50,7 @@ func (d *TagLimit) initOnce() error {
func (d *TagLimit) Apply(in ...telegraf.Metric) []telegraf.Metric { func (d *TagLimit) Apply(in ...telegraf.Metric) []telegraf.Metric {
err := d.initOnce() err := d.initOnce()
if err != nil { if err != nil {
log.Printf("E! [processors.tag_limit] could not create tag_limit processor: %v", err) d.Log.Errorf("Could not create tag_limit processor: %v", err)
return in return in
} }
for _, point := range in { for _, point := range in {

View File

@ -4,9 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/stretchr/testify/assert"
) )
func MustMetric(name string, tags map[string]string, fields map[string]interface{}, metricTime time.Time) telegraf.Metric { func MustMetric(name string, tags map[string]string, fields map[string]interface{}, metricTime time.Time) telegraf.Metric {
@ -46,8 +47,8 @@ func TestUnderLimit(t *testing.T) {
m1 := MustMetric("foo", oneTags, nil, currentTime) m1 := MustMetric("foo", oneTags, nil, currentTime)
m2 := MustMetric("bar", tenTags, nil, currentTime) m2 := MustMetric("bar", tenTags, nil, currentTime)
limitApply := tagLimitConfig.Apply(m1, m2) limitApply := tagLimitConfig.Apply(m1, m2)
assert.Equal(t, oneTags, limitApply[0].Tags(), "one tag") require.Equal(t, oneTags, limitApply[0].Tags(), "one tag")
assert.Equal(t, tenTags, limitApply[1].Tags(), "ten tags") require.Equal(t, tenTags, limitApply[1].Tags(), "ten tags")
} }
func TestTrim(t *testing.T) { func TestTrim(t *testing.T) {
@ -78,9 +79,9 @@ func TestTrim(t *testing.T) {
m1 := MustMetric("foo", threeTags, nil, currentTime) m1 := MustMetric("foo", threeTags, nil, currentTime)
m2 := MustMetric("bar", tenTags, nil, currentTime) m2 := MustMetric("bar", tenTags, nil, currentTime)
limitApply := tagLimitConfig.Apply(m1, m2) limitApply := tagLimitConfig.Apply(m1, m2)
assert.Equal(t, threeTags, limitApply[0].Tags(), "three tags") require.Equal(t, threeTags, limitApply[0].Tags(), "three tags")
trimmedTags := limitApply[1].Tags() trimmedTags := limitApply[1].Tags()
assert.Equal(t, 3, len(trimmedTags), "ten tags") require.Equal(t, 3, len(trimmedTags), "ten tags")
assert.Equal(t, "foo", trimmedTags["a"], "preserved: a") require.Equal(t, "foo", trimmedTags["a"], "preserved: a")
assert.Equal(t, "bar", trimmedTags["b"], "preserved: b") require.Equal(t, "bar", trimmedTags["b"], "preserved: b")
} }

View File

@ -4,10 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestName(t *testing.T) { func TestName(t *testing.T) {
@ -90,7 +90,7 @@ func TestMetricMissingTagsIsNotLost(t *testing.T) {
// assert // assert
// make sure no metrics are lost when a template process fails // make sure no metrics are lost when a template process fails
assert.Equal(t, 2, len(actual), "Number of metrics input should equal number of metrics output") require.Equal(t, 2, len(actual), "Number of metrics input should equal number of metrics output")
} }
func TestTagAndFieldConcatenate(t *testing.T) { func TestTagAndFieldConcatenate(t *testing.T) {