chore(linters): Enable `appendCombine` checker for gocritic (#14451)

This commit is contained in:
Paweł Żak 2024-01-03 15:16:26 +01:00 committed by GitHub
parent 08747905bf
commit 5810a9e4e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 207 additions and 189 deletions

View File

@ -117,6 +117,7 @@ linters-settings:
- unnecessaryDefer - unnecessaryDefer
- weakCond - weakCond
# performance # performance
- appendCombine
- equalFold - equalFold
- indexAlloc - indexAlloc
- hugeParam - hugeParam

View File

@ -187,9 +187,10 @@ func TestHistogramWithReset(t *testing.T) {
// TestHistogramWithAllFields tests two metrics for one period and for all fields // TestHistogramWithAllFields tests two metrics for one period and for all fields
func TestHistogramWithAllFields(t *testing.T) { func TestHistogramWithAllFields(t *testing.T) {
var cfg []config cfg := []config{
cfg = append(cfg, config{Metric: "first_metric_name", Buckets: []float64{0.0, 15.5, 20.0, 30.0, 40.0}}) {Metric: "first_metric_name", Buckets: []float64{0.0, 15.5, 20.0, 30.0, 40.0}},
cfg = append(cfg, config{Metric: "second_metric_name", Buckets: []float64{0.0, 4.0, 10.0, 23.0, 30.0}}) {Metric: "second_metric_name", Buckets: []float64{0.0, 4.0, 10.0, 23.0, 30.0}},
}
histogram := NewTestHistogram(cfg, false, true, false) histogram := NewTestHistogram(cfg, false, true, false)
acc := &testutil.Accumulator{} acc := &testutil.Accumulator{}
@ -265,9 +266,10 @@ func TestHistogramWithAllFields(t *testing.T) {
// TestHistogramWithAllFieldsNonCumulative tests two metrics for one period and for all fields // TestHistogramWithAllFieldsNonCumulative tests two metrics for one period and for all fields
func TestHistogramWithAllFieldsNonCumulative(t *testing.T) { func TestHistogramWithAllFieldsNonCumulative(t *testing.T) {
var cfg []config cfg := []config{
cfg = append(cfg, config{Metric: "first_metric_name", Buckets: []float64{0.0, 15.5, 20.0, 30.0, 40.0}}) {Metric: "first_metric_name", Buckets: []float64{0.0, 15.5, 20.0, 30.0, 40.0}},
cfg = append(cfg, config{Metric: "second_metric_name", Buckets: []float64{0.0, 4.0, 10.0, 23.0, 30.0}}) {Metric: "second_metric_name", Buckets: []float64{0.0, 4.0, 10.0, 23.0, 30.0}},
}
histogram := NewTestHistogram(cfg, false, false, false) histogram := NewTestHistogram(cfg, false, false, false)
acc := &testutil.Accumulator{} acc := &testutil.Accumulator{}
@ -429,9 +431,10 @@ func TestHistogramMetricExpiration(t *testing.T) {
timeNow = time.Now timeNow = time.Now
}() }()
var cfg []config cfg := []config{
cfg = append(cfg, config{Metric: "first_metric_name", Fields: []string{"a"}, Buckets: []float64{0.0, 10.0, 20.0, 30.0, 40.0}}) {Metric: "first_metric_name", Fields: []string{"a"}, Buckets: []float64{0.0, 10.0, 20.0, 30.0, 40.0}},
cfg = append(cfg, config{Metric: "second_metric_name", Buckets: []float64{0.0, 4.0, 10.0, 23.0, 30.0}}) {Metric: "second_metric_name", Buckets: []float64{0.0, 4.0, 10.0, 23.0, 30.0}},
}
histogram := NewTestHistogramWithExpirationInterval(cfg, false, true, false, telegrafConfig.Duration(30)) histogram := NewTestHistogramWithExpirationInterval(cfg, false, true, false, telegrafConfig.Duration(30))
acc := &testutil.Accumulator{} acc := &testutil.Accumulator{}

View File

@ -19,6 +19,7 @@ import (
"github.com/gopcua/opcua" "github.com/gopcua/opcua"
"github.com/gopcua/opcua/debug" "github.com/gopcua/opcua/debug"
"github.com/gopcua/opcua/ua" "github.com/gopcua/opcua/ua"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
) )
@ -151,9 +152,11 @@ func (o *OpcUAClient) generateClientOpts(endpoints []*ua.EndpointDescription) ([
appname := "Telegraf" appname := "Telegraf"
// ApplicationURI is automatically read from the cert so is not required if a cert if provided // ApplicationURI is automatically read from the cert so is not required if a cert if provided
opts = append(opts, opcua.ApplicationURI(appuri)) opts = append(opts,
opts = append(opts, opcua.ApplicationName(appname)) opcua.ApplicationURI(appuri),
opts = append(opts, opcua.RequestTimeout(time.Duration(o.Config.RequestTimeout))) opcua.ApplicationName(appname),
opcua.RequestTimeout(time.Duration(o.Config.RequestTimeout)),
)
certFile := o.Config.Certificate certFile := o.Config.Certificate
keyFile := o.Config.PrivateKey keyFile := o.Config.PrivateKey

View File

@ -218,8 +218,7 @@ func genOutput() [][]byte {
out := make([][]byte, 0, 2*len(kvs)) out := make([][]byte, 0, 2*len(kvs))
for _, kv := range kvs { for _, kv := range kvs {
lenb, kvb := kvBytes(kv) lenb, kvb := kvBytes(kv)
out = append(out, lenb) out = append(out, lenb, kvb)
out = append(out, kvb)
} }
return out return out
@ -233,8 +232,7 @@ func genBadOutput() [][]byte {
out := make([][]byte, 0, 2*len(kvs)) out := make([][]byte, 0, 2*len(kvs))
for _, kv := range kvs { for _, kv := range kvs {
lenb, kvb := kvBytes(kv) lenb, kvb := kvBytes(kv)
out = append(out, lenb) out = append(out, lenb, kvb)
out = append(out, kvb)
} }
return out return out

View File

@ -118,8 +118,7 @@ func (m *Ipmi) parse(acc telegraf.Accumulator, server string) error {
if os.IsNotExist(err) { if os.IsNotExist(err) {
dumpOpts := opts dumpOpts := opts
// init cache file // init cache file
dumpOpts = append(dumpOpts, "dump") dumpOpts = append(dumpOpts, "dump", cacheFile)
dumpOpts = append(dumpOpts, cacheFile)
name := m.Path name := m.Path
if m.UseSudo { if m.UseSudo {
// -n - avoid prompting the user for input of any kind // -n - avoid prompting the user for input of any kind
@ -132,8 +131,7 @@ func (m *Ipmi) parse(acc telegraf.Accumulator, server string) error {
return fmt.Errorf("failed to run command %q: %w - %s", strings.Join(sanitizeIPMICmd(cmd.Args), " "), err, string(out)) return fmt.Errorf("failed to run command %q: %w - %s", strings.Join(sanitizeIPMICmd(cmd.Args), " "), err, string(out))
} }
} }
opts = append(opts, "-S") opts = append(opts, "-S", cacheFile)
opts = append(opts, cacheFile)
} }
if m.MetricVersion == 2 { if m.MetricVersion == 2 {
opts = append(opts, "elist") opts = append(opts, "elist")

View File

@ -56,8 +56,10 @@ func TestLanzGeneratesMetrics(t *testing.T) {
l := NewLanz() l := NewLanz()
l.Servers = append(l.Servers, "tcp://switch01.int.example.com:50001") l.Servers = append(l.Servers,
l.Servers = append(l.Servers, "tcp://switch02.int.example.com:50001") "tcp://switch01.int.example.com:50001",
"tcp://switch02.int.example.com:50001",
)
deviceURL1, err := url.Parse(l.Servers[0]) deviceURL1, err := url.Parse(l.Servers[0])
if err != nil { if err != nil {
t.Fail() t.Fail()

View File

@ -316,81 +316,80 @@ func TestLustre2GeneratesJobstatsMetrics(t *testing.T) {
} }
// make this for two tags // make this for two tags
var fields []map[string]interface{} fields := []map[string]interface{}{
{
fields = append(fields, map[string]interface{}{ "jobstats_read_calls": uint64(1),
"jobstats_read_calls": uint64(1), "jobstats_read_min_size": uint64(4096),
"jobstats_read_min_size": uint64(4096), "jobstats_read_max_size": uint64(4096),
"jobstats_read_max_size": uint64(4096), "jobstats_read_bytes": uint64(4096),
"jobstats_read_bytes": uint64(4096), "jobstats_write_calls": uint64(25),
"jobstats_write_calls": uint64(25), "jobstats_write_min_size": uint64(1048576),
"jobstats_write_min_size": uint64(1048576), "jobstats_write_max_size": uint64(16777216),
"jobstats_write_max_size": uint64(16777216), "jobstats_write_bytes": uint64(26214400),
"jobstats_write_bytes": uint64(26214400), "jobstats_ost_getattr": uint64(0),
"jobstats_ost_getattr": uint64(0), "jobstats_ost_setattr": uint64(0),
"jobstats_ost_setattr": uint64(0), "jobstats_punch": uint64(1),
"jobstats_punch": uint64(1), "jobstats_ost_sync": uint64(0),
"jobstats_ost_sync": uint64(0), "jobstats_destroy": uint64(0),
"jobstats_destroy": uint64(0), "jobstats_create": uint64(0),
"jobstats_create": uint64(0), "jobstats_ost_statfs": uint64(0),
"jobstats_ost_statfs": uint64(0), "jobstats_get_info": uint64(0),
"jobstats_get_info": uint64(0), "jobstats_set_info": uint64(0),
"jobstats_set_info": uint64(0), "jobstats_quotactl": uint64(0),
"jobstats_quotactl": uint64(0), "jobstats_open": uint64(5),
"jobstats_open": uint64(5), "jobstats_close": uint64(4),
"jobstats_close": uint64(4), "jobstats_mknod": uint64(6),
"jobstats_mknod": uint64(6), "jobstats_link": uint64(8),
"jobstats_link": uint64(8), "jobstats_unlink": uint64(90),
"jobstats_unlink": uint64(90), "jobstats_mkdir": uint64(521),
"jobstats_mkdir": uint64(521), "jobstats_rmdir": uint64(520),
"jobstats_rmdir": uint64(520), "jobstats_rename": uint64(9),
"jobstats_rename": uint64(9), "jobstats_getattr": uint64(11),
"jobstats_getattr": uint64(11), "jobstats_setattr": uint64(1),
"jobstats_setattr": uint64(1), "jobstats_getxattr": uint64(3),
"jobstats_getxattr": uint64(3), "jobstats_setxattr": uint64(4),
"jobstats_setxattr": uint64(4), "jobstats_statfs": uint64(1205),
"jobstats_statfs": uint64(1205), "jobstats_sync": uint64(2),
"jobstats_sync": uint64(2), "jobstats_samedir_rename": uint64(705),
"jobstats_samedir_rename": uint64(705), "jobstats_crossdir_rename": uint64(200),
"jobstats_crossdir_rename": uint64(200), },
}) {
"jobstats_read_calls": uint64(1),
fields = append(fields, map[string]interface{}{ "jobstats_read_min_size": uint64(1024),
"jobstats_read_calls": uint64(1), "jobstats_read_max_size": uint64(1024),
"jobstats_read_min_size": uint64(1024), "jobstats_read_bytes": uint64(1024),
"jobstats_read_max_size": uint64(1024), "jobstats_write_calls": uint64(25),
"jobstats_read_bytes": uint64(1024), "jobstats_write_min_size": uint64(2048),
"jobstats_write_calls": uint64(25), "jobstats_write_max_size": uint64(2048),
"jobstats_write_min_size": uint64(2048), "jobstats_write_bytes": uint64(51200),
"jobstats_write_max_size": uint64(2048), "jobstats_ost_getattr": uint64(0),
"jobstats_write_bytes": uint64(51200), "jobstats_ost_setattr": uint64(0),
"jobstats_ost_getattr": uint64(0), "jobstats_punch": uint64(1),
"jobstats_ost_setattr": uint64(0), "jobstats_ost_sync": uint64(0),
"jobstats_punch": uint64(1), "jobstats_destroy": uint64(0),
"jobstats_ost_sync": uint64(0), "jobstats_create": uint64(0),
"jobstats_destroy": uint64(0), "jobstats_ost_statfs": uint64(0),
"jobstats_create": uint64(0), "jobstats_get_info": uint64(0),
"jobstats_ost_statfs": uint64(0), "jobstats_set_info": uint64(0),
"jobstats_get_info": uint64(0), "jobstats_quotactl": uint64(0),
"jobstats_set_info": uint64(0), "jobstats_open": uint64(6),
"jobstats_quotactl": uint64(0), "jobstats_close": uint64(7),
"jobstats_open": uint64(6), "jobstats_mknod": uint64(8),
"jobstats_close": uint64(7), "jobstats_link": uint64(9),
"jobstats_mknod": uint64(8), "jobstats_unlink": uint64(20),
"jobstats_link": uint64(9), "jobstats_mkdir": uint64(200),
"jobstats_unlink": uint64(20), "jobstats_rmdir": uint64(210),
"jobstats_mkdir": uint64(200), "jobstats_rename": uint64(8),
"jobstats_rmdir": uint64(210), "jobstats_getattr": uint64(10),
"jobstats_rename": uint64(8), "jobstats_setattr": uint64(2),
"jobstats_getattr": uint64(10), "jobstats_getxattr": uint64(4),
"jobstats_setattr": uint64(2), "jobstats_setxattr": uint64(5),
"jobstats_getxattr": uint64(4), "jobstats_statfs": uint64(1207),
"jobstats_setxattr": uint64(5), "jobstats_sync": uint64(3),
"jobstats_statfs": uint64(1207), "jobstats_samedir_rename": uint64(706),
"jobstats_sync": uint64(3), "jobstats_crossdir_rename": uint64(201),
"jobstats_samedir_rename": uint64(706), },
"jobstats_crossdir_rename": uint64(201), }
})
for index := 0; index < len(fields); index++ { for index := 0; index < len(fields); index++ {
acc.AssertContainsTaggedFields(t, "lustre2", fields[index], tags[index]) acc.AssertContainsTaggedFields(t, "lustre2", fields[index], tags[index])

View File

@ -208,10 +208,12 @@ func setSystemctl(timeout config.Duration, unitType string, pattern string) (*by
psplit := strings.SplitN(pattern, " ", -1) psplit := strings.SplitN(pattern, " ", -1)
params = append(params, psplit...) params = append(params, psplit...)
} }
params = append(params, "--all", "--plain") params = append(params,
// add type as configured in config "--all", "--plain",
params = append(params, fmt.Sprintf("--type=%s", unitType)) // add type as configured in config
params = append(params, "--no-legend") "--type="+unitType,
"--no-legend",
)
cmd := exec.Command(systemctlPath, params...) cmd := exec.Command(systemctlPath, params...)
var out bytes.Buffer var out bytes.Buffer
cmd.Stdout = &out cmd.Stdout = &out

View File

@ -6,8 +6,9 @@ import (
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
) )
func TestUpsdGather(t *testing.T) { func TestUpsdGather(t *testing.T) {
@ -201,45 +202,46 @@ type interaction struct {
func genOutput() []interaction { func genOutput() []interaction {
m := make([]interaction, 0) m := make([]interaction, 0)
m = append(m, interaction{ m = append(m,
Expected: "VER\n", interaction{
Response: "1\n", Expected: "VER\n",
}) Response: "1\n",
m = append(m, interaction{ },
Expected: "NETVER\n", interaction{
Response: "1\n", Expected: "NETVER\n",
}) Response: "1\n",
m = append(m, interaction{ },
Expected: "LIST UPS\n", interaction{
Response: `BEGIN LIST UPS Expected: "LIST UPS\n",
Response: `BEGIN LIST UPS
UPS fake "fakescription" UPS fake "fakescription"
END LIST UPS END LIST UPS
`, `,
}) },
m = append(m, interaction{ interaction{
Expected: "LIST CLIENT fake\n", Expected: "LIST CLIENT fake\n",
Response: `BEGIN LIST CLIENT fake Response: `BEGIN LIST CLIENT fake
CLIENT fake 192.168.1.1 CLIENT fake 192.168.1.1
END LIST CLIENT fake END LIST CLIENT fake
`, `,
}) },
m = append(m, interaction{ interaction{
Expected: "LIST CMD fake\n", Expected: "LIST CMD fake\n",
Response: `BEGIN LIST CMD fake Response: `BEGIN LIST CMD fake
END LIST CMD fake END LIST CMD fake
`, `,
}) },
m = append(m, interaction{ interaction{
Expected: "GET UPSDESC fake\n", Expected: "GET UPSDESC fake\n",
Response: "UPSDESC fake \"stub-ups-description\"\n", Response: "UPSDESC fake \"stub-ups-description\"\n",
}) },
m = append(m, interaction{ interaction{
Expected: "GET NUMLOGINS fake\n", Expected: "GET NUMLOGINS fake\n",
Response: "NUMLOGINS fake 1\n", Response: "NUMLOGINS fake 1\n",
}) },
m = append(m, interaction{ interaction{
Expected: "LIST VAR fake\n", Expected: "LIST VAR fake\n",
Response: `BEGIN LIST VAR fake Response: `BEGIN LIST VAR fake
VAR fake device.serial "ABC123" VAR fake device.serial "ABC123"
VAR fake device.model "Model 12345" VAR fake device.model "Model 12345"
VAR fake input.voltage "242.0" VAR fake input.voltage "242.0"
@ -257,7 +259,8 @@ VAR fake battery.mfr.date "2016-07-26"
VAR fake ups.status "OL" VAR fake ups.status "OL"
END LIST VAR fake END LIST VAR fake
`, `,
}) },
)
m = appendVariable(m, "device.serial", "STRING:64") m = appendVariable(m, "device.serial", "STRING:64")
m = appendVariable(m, "device.model", "STRING:64") m = appendVariable(m, "device.model", "STRING:64")
m = appendVariable(m, "input.voltage", "NUMBER") m = appendVariable(m, "input.voltage", "NUMBER")
@ -278,14 +281,16 @@ END LIST VAR fake
} }
func appendVariable(m []interaction, name string, typ string) []interaction { func appendVariable(m []interaction, name string, typ string) []interaction {
m = append(m, interaction{ m = append(m,
Expected: "GET DESC fake " + name + "\n", interaction{
Response: "DESC fake" + name + " \"No description here\"\n", Expected: "GET DESC fake " + name + "\n",
}) Response: "DESC fake" + name + " \"No description here\"\n",
m = append(m, interaction{ },
Expected: "GET TYPE fake " + name + "\n", interaction{
Response: "TYPE fake " + name + " " + typ + "\n", Expected: "GET TYPE fake " + name + "\n",
}) Response: "TYPE fake " + name + " " + typ + "\n",
},
)
return m return m
} }

View File

@ -166,8 +166,10 @@ func TestSendMetrics(t *testing.T) {
// Init metrics // Init metrics
// Simple metrics are exported as a gauge unless in additional_counters // Simple metrics are exported as a gauge unless in additional_counters
expected = append(expected, "simple_metric.value,dt.metrics.source=telegraf gauge,3.14 1289430000000") expected = append(expected,
expected = append(expected, "simple_metric.counter,dt.metrics.source=telegraf count,delta=5 1289430000000") "simple_metric.value,dt.metrics.source=telegraf gauge,3.14 1289430000000",
"simple_metric.counter,dt.metrics.source=telegraf count,delta=5 1289430000000",
)
d.AddCounterMetrics = append(d.AddCounterMetrics, "simple_metric.counter") d.AddCounterMetrics = append(d.AddCounterMetrics, "simple_metric.counter")
m1 := metric.New( m1 := metric.New(
"simple_metric", "simple_metric",
@ -177,8 +179,10 @@ func TestSendMetrics(t *testing.T) {
) )
// Even if Type() returns counter, all metrics are treated as a gauge unless explicitly added to additional_counters // Even if Type() returns counter, all metrics are treated as a gauge unless explicitly added to additional_counters
expected = append(expected, "counter_type.value,dt.metrics.source=telegraf gauge,3.14 1289430000000") expected = append(expected,
expected = append(expected, "counter_type.counter,dt.metrics.source=telegraf count,delta=5 1289430000000") "counter_type.value,dt.metrics.source=telegraf gauge,3.14 1289430000000",
"counter_type.counter,dt.metrics.source=telegraf count,delta=5 1289430000000",
)
d.AddCounterMetrics = append(d.AddCounterMetrics, "counter_type.counter") d.AddCounterMetrics = append(d.AddCounterMetrics, "counter_type.counter")
m2 := metric.New( m2 := metric.New(
"counter_type", "counter_type",
@ -188,12 +192,14 @@ func TestSendMetrics(t *testing.T) {
telegraf.Counter, telegraf.Counter,
) )
expected = append(expected, "complex_metric.int,dt.metrics.source=telegraf gauge,1 1289430000000") expected = append(expected,
expected = append(expected, "complex_metric.int64,dt.metrics.source=telegraf gauge,2 1289430000000") "complex_metric.int,dt.metrics.source=telegraf gauge,1 1289430000000",
expected = append(expected, "complex_metric.float,dt.metrics.source=telegraf gauge,3 1289430000000") "complex_metric.int64,dt.metrics.source=telegraf gauge,2 1289430000000",
expected = append(expected, "complex_metric.float64,dt.metrics.source=telegraf gauge,4 1289430000000") "complex_metric.float,dt.metrics.source=telegraf gauge,3 1289430000000",
expected = append(expected, "complex_metric.true,dt.metrics.source=telegraf gauge,1 1289430000000") "complex_metric.float64,dt.metrics.source=telegraf gauge,4 1289430000000",
expected = append(expected, "complex_metric.false,dt.metrics.source=telegraf gauge,0 1289430000000") "complex_metric.true,dt.metrics.source=telegraf gauge,1 1289430000000",
"complex_metric.false,dt.metrics.source=telegraf gauge,0 1289430000000",
)
m3 := metric.New( m3 := metric.New(
"complex_metric", "complex_metric",
map[string]string{}, map[string]string{},

View File

@ -206,8 +206,10 @@ func marshalMetric(metric telegraf.Metric) bson.D {
for k, v := range metric.Tags() { for k, v := range metric.Tags() {
tags = append(tags, primitive.E{Key: k, Value: v}) tags = append(tags, primitive.E{Key: k, Value: v})
} }
bdoc = append(bdoc, primitive.E{Key: "tags", Value: tags}) bdoc = append(bdoc,
bdoc = append(bdoc, primitive.E{Key: "timestamp", Value: metric.Time()}) primitive.E{Key: "tags", Value: tags},
primitive.E{Key: "timestamp", Value: metric.Time()},
)
return bdoc return bdoc
} }

View File

@ -23,9 +23,11 @@ func (m *MQTT) collectHomieDeviceMessages(topic string, metric telegraf.Metric)
if err != nil { if err != nil {
return nil, "", fmt.Errorf("generating device name failed: %w", err) return nil, "", fmt.Errorf("generating device name failed: %w", err)
} }
messages = append(messages, message{topic + "/$homie", []byte("4.0")}) messages = append(messages,
messages = append(messages, message{topic + "/$name", []byte(deviceName)}) message{topic + "/$homie", []byte("4.0")},
messages = append(messages, message{topic + "/$state", []byte("ready")}) message{topic + "/$name", []byte(deviceName)},
message{topic + "/$state", []byte("ready")},
)
m.homieSeen[topic] = make(map[string]bool) m.homieSeen[topic] = make(map[string]bool)
} }
@ -43,14 +45,10 @@ func (m *MQTT) collectHomieDeviceMessages(topic string, metric telegraf.Metric)
nodeIDs = append(nodeIDs, id) nodeIDs = append(nodeIDs, id)
} }
sort.Strings(nodeIDs) sort.Strings(nodeIDs)
messages = append(messages, message{ messages = append(messages,
topic + "/$nodes", message{topic + "/$nodes", []byte(strings.Join(nodeIDs, ","))},
[]byte(strings.Join(nodeIDs, ",")), message{topic + "/" + nodeID + "/$name", []byte(nodeName)},
}) )
messages = append(messages, message{
topic + "/" + nodeID + "/$name",
[]byte(nodeName),
})
} }
properties := make([]string, 0, len(metric.TagList())+len(metric.FieldList())) properties := make([]string, 0, len(metric.TagList())+len(metric.FieldList()))

View File

@ -270,9 +270,11 @@ func (m *MQTT) collectHomieV4(hostname string, metrics []telegraf.Metric) []mess
continue continue
} }
propID := normalizeID(tag.Key) propID := normalizeID(tag.Key)
collection = append(collection, message{path + "/" + propID, []byte(tag.Value)}) collection = append(collection,
collection = append(collection, message{path + "/" + propID + "/$name", []byte(tag.Key)}) message{path + "/" + propID, []byte(tag.Value)},
collection = append(collection, message{path + "/" + propID + "/$datatype", []byte("string")}) message{path + "/" + propID + "/$name", []byte(tag.Key)},
message{path + "/" + propID + "/$datatype", []byte("string")},
)
} }
for _, field := range metric.FieldList() { for _, field := range metric.FieldList() {
@ -283,9 +285,11 @@ func (m *MQTT) collectHomieV4(hostname string, metrics []telegraf.Metric) []mess
continue continue
} }
propID := normalizeID(field.Key) propID := normalizeID(field.Key)
collection = append(collection, message{path + "/" + propID, []byte(v)}) collection = append(collection,
collection = append(collection, message{path + "/" + propID + "/$name", []byte(field.Key)}) message{path + "/" + propID, []byte(v)},
collection = append(collection, message{path + "/" + propID + "/$datatype", []byte(dt)}) message{path + "/" + propID + "/$name", []byte(field.Key)},
message{path + "/" + propID + "/$datatype", []byte(dt)},
)
} }
} }

View File

@ -187,18 +187,14 @@ func TestWriteIntegration(t *testing.T) {
// Verify positive and negative test cases of writing data // Verify positive and negative test cases of writing data
metrics := testutil.MockMetrics() metrics := testutil.MockMetrics()
metrics = append(metrics, testutil.TestMetric(float64(1.0), metrics = append(metrics,
"justametric.float")) testutil.TestMetric(float64(1.0), "justametric.float"),
metrics = append(metrics, testutil.TestMetric(int64(123456789), testutil.TestMetric(int64(123456789), "justametric.int"),
"justametric.int")) testutil.TestMetric(uint64(123456789012345), "justametric.uint"),
metrics = append(metrics, testutil.TestMetric(uint64(123456789012345), testutil.TestMetric("Lorem Ipsum", "justametric.string"),
"justametric.uint")) testutil.TestMetric(float64(42.0), "justametric.anotherfloat"),
metrics = append(metrics, testutil.TestMetric("Lorem Ipsum", testutil.TestMetric(float64(42.0), "metric w/ specialchars"),
"justametric.string")) )
metrics = append(metrics, testutil.TestMetric(float64(42.0),
"justametric.anotherfloat"))
metrics = append(metrics, testutil.TestMetric(float64(42.0),
"metric w/ specialchars"))
err = o.Write(metrics) err = o.Write(metrics)
require.NoError(t, err) require.NoError(t, err)

View File

@ -8,12 +8,12 @@ import (
"testing" "testing"
"time" "time"
ws "github.com/gorilla/websocket"
"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/testutil" "github.com/influxdata/telegraf/testutil"
ws "github.com/gorilla/websocket"
"github.com/stretchr/testify/require"
) )
// testSerializer serializes to a number of metrics to simplify tests here. // testSerializer serializes to a number of metrics to simplify tests here.
@ -151,9 +151,10 @@ func TestWebSocket_Write_OK(t *testing.T) {
w := initWebSocket(s) w := initWebSocket(s)
connect(t, w) connect(t, w)
var metrics []telegraf.Metric metrics := []telegraf.Metric{
metrics = append(metrics, testutil.TestMetric(0.4, "test")) testutil.TestMetric(0.4, "test"),
metrics = append(metrics, testutil.TestMetric(0.5, "test")) testutil.TestMetric(0.5, "test"),
}
err := w.Write(metrics) err := w.Write(metrics)
require.NoError(t, err) require.NoError(t, err)