fix: Linter fixes for plugins/inputs/[n-o]* (#10011)

This commit is contained in:
Paweł Żak 2021-11-02 15:42:22 +01:00 committed by GitHub
parent 934db67c2b
commit e6b107b062
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 169 additions and 165 deletions

View File

@ -11,10 +11,11 @@ import (
"path"
"time"
gnatsd "github.com/nats-io/nats-server/v2/server"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
gnatsd "github.com/nats-io/nats-server/v2/server"
)
type Nats struct {
@ -41,16 +42,16 @@ func (n *Nats) Description() string {
}
func (n *Nats) Gather(acc telegraf.Accumulator) error {
url, err := url.Parse(n.Server)
address, err := url.Parse(n.Server)
if err != nil {
return err
}
url.Path = path.Join(url.Path, "varz")
address.Path = path.Join(address.Path, "varz")
if n.client == nil {
n.client = n.createHTTPClient()
}
resp, err := n.client.Get(url.String())
resp, err := n.client.Get(address.String())
if err != nil {
return err
}

View File

@ -245,7 +245,7 @@ func findProbe(probe string, probes []probe) int {
// returns a time.Time struct.
func parseTime(val string, tz float64) (time.Time, error) {
// Magic time constant from https://golang.org/pkg/time/#Parse
const TimeLayout = "01/02/2006 15:04:05 -0700"
const timeLayout = "01/02/2006 15:04:05 -0700"
// Timezone offset needs to be explicit
sign := '+'
@ -256,7 +256,7 @@ func parseTime(val string, tz float64) (time.Time, error) {
// Build a time string with the timezone in a format Go can parse.
tzs := fmt.Sprintf("%c%04d", sign, int(math.Abs(tz))*100)
ts := fmt.Sprintf("%s %s", val, tzs)
t, err := time.Parse(TimeLayout, ts)
t, err := time.Parse(timeLayout, ts)
if err != nil {
return time.Now(), fmt.Errorf("unable to parse %q (%v)", ts, err)
}

View File

@ -17,10 +17,10 @@ type ResultType uint64
const (
Success ResultType = 0
Timeout = 1
ConnectionFailed = 2
ReadFailed = 3
StringMismatch = 4
Timeout ResultType = 1
ConnectionFailed ResultType = 2
ReadFailed ResultType = 3
StringMismatch ResultType = 4
)
// NetResponse struct
@ -120,8 +120,8 @@ func (n *NetResponse) TCPGather() (map[string]string, map[string]interface{}, er
setResult(ReadFailed, fields, tags, n.Expect)
} else {
// Looking for string in answer
RegEx := regexp.MustCompile(`.*` + n.Expect + `.*`)
find := RegEx.FindString(data)
regEx := regexp.MustCompile(`.*` + n.Expect + `.*`)
find := regEx.FindString(data)
if find != "" {
setResult(Success, fields, tags, n.Expect)
} else {
@ -186,8 +186,8 @@ func (n *NetResponse) UDPGather() (map[string]string, map[string]interface{}, er
}
// Looking for string in answer
RegEx := regexp.MustCompile(`.*` + n.Expect + `.*`)
find := RegEx.FindString(string(buf))
regEx := regexp.MustCompile(`.*` + n.Expect + `.*`)
find := regEx.FindString(string(buf))
if find != "" {
setResult(Success, fields, tags, n.Expect)
} else {
@ -232,22 +232,25 @@ func (n *NetResponse) Gather(acc telegraf.Accumulator) error {
tags := map[string]string{"server": host, "port": port}
var fields map[string]interface{}
var returnTags map[string]string
// Gather data
if n.Protocol == "tcp" {
switch n.Protocol {
case "tcp":
returnTags, fields, err = n.TCPGather()
if err != nil {
return err
}
tags["protocol"] = "tcp"
} else if n.Protocol == "udp" {
case "udp":
returnTags, fields, err = n.UDPGather()
if err != nil {
return err
}
tags["protocol"] = "udp"
} else {
default:
return errors.New("bad protocol")
}
// Merge the tags
for k, v := range returnTags {
tags[k] = v

View File

@ -8,9 +8,9 @@ import (
"net/url"
"testing"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
)
const nginxSampleResponse = `
@ -33,7 +33,7 @@ func TestNginxTags(t *testing.T) {
for _, url1 := range urls {
addr, _ = url.Parse(url1)
tagMap := getTags(addr)
assert.Contains(t, tagMap["server"], "localhost")
require.Contains(t, tagMap["server"], "localhost")
}
}

View File

@ -49,11 +49,11 @@ func addError(acc telegraf.Accumulator, err error) {
}
func (n *NginxPlusAPI) gatherURL(addr *url.URL, path string) ([]byte, error) {
url := fmt.Sprintf("%s/%d/%s", addr.String(), n.APIVersion, path)
resp, err := n.client.Get(url)
address := fmt.Sprintf("%s/%d/%s", addr.String(), n.APIVersion, path)
resp, err := n.client.Get(address)
if err != nil {
return nil, fmt.Errorf("error making HTTP request to %s: %s", url, err)
return nil, fmt.Errorf("error making HTTP request to %s: %s", address, err)
}
defer resp.Body.Close()
@ -64,7 +64,7 @@ func (n *NginxPlusAPI) gatherURL(addr *url.URL, path string) ([]byte, error) {
// features are either optional, or only available in some versions
return nil, errNotFound
default:
return nil, fmt.Errorf("%s returned HTTP status %s", url, resp.Status)
return nil, fmt.Errorf("%s returned HTTP status %s", address, resp.Status)
}
contentType := strings.Split(resp.Header.Get("Content-Type"), ";")[0]
@ -77,7 +77,7 @@ func (n *NginxPlusAPI) gatherURL(addr *url.URL, path string) ([]byte, error) {
return body, nil
default:
return nil, fmt.Errorf("%s returned unexpected content type %s", url, contentType)
return nil, fmt.Errorf("%s returned unexpected content type %s", address, contentType)
}
}

View File

@ -121,7 +121,7 @@ func (check *NginxUpstreamCheck) createHTTPClient() (*http.Client, error) {
}
// gatherJSONData query the data source and parse the response JSON
func (check *NginxUpstreamCheck) gatherJSONData(url string, value interface{}) error {
func (check *NginxUpstreamCheck) gatherJSONData(address string, value interface{}) error {
var method string
if check.Method != "" {
method = check.Method
@ -129,7 +129,7 @@ func (check *NginxUpstreamCheck) gatherJSONData(url string, value interface{}) e
method = "GET"
}
request, err := http.NewRequest(method, url, nil)
request, err := http.NewRequest(method, address, nil)
if err != nil {
return err
}
@ -153,7 +153,7 @@ func (check *NginxUpstreamCheck) gatherJSONData(url string, value interface{}) e
if response.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := io.ReadAll(io.LimitReader(response.Body, 200))
return fmt.Errorf("%s returned HTTP status %s: %q", url, response.Status, body)
return fmt.Errorf("%s returned HTTP status %s: %q", address, response.Status, body)
}
err = json.NewDecoder(response.Body).Decode(value)
@ -187,10 +187,10 @@ func (check *NginxUpstreamCheck) Gather(accumulator telegraf.Accumulator) error
return nil
}
func (check *NginxUpstreamCheck) gatherStatusData(url string, accumulator telegraf.Accumulator) error {
func (check *NginxUpstreamCheck) gatherStatusData(address string, accumulator telegraf.Accumulator) error {
checkData := &NginxUpstreamCheckData{}
err := check.gatherJSONData(url, checkData)
err := check.gatherJSONData(address, checkData)
if err != nil {
return err
}
@ -201,7 +201,7 @@ func (check *NginxUpstreamCheck) gatherStatusData(url string, accumulator telegr
"type": server.Type,
"name": server.Name,
"port": strconv.Itoa(int(server.Port)),
"url": url,
"url": address,
}
fields := map[string]interface{}{

View File

@ -61,20 +61,20 @@ func (s *NSD) SampleConfig() string {
}
// Shell out to nsd_stat and return the output
func nsdRunner(cmdName string, timeout config.Duration, useSudo bool, Server string, ConfigFile string) (*bytes.Buffer, error) {
func nsdRunner(cmdName string, timeout config.Duration, useSudo bool, server string, configFile string) (*bytes.Buffer, error) {
cmdArgs := []string{"stats_noreset"}
if Server != "" {
host, port, err := net.SplitHostPort(Server)
if server != "" {
host, port, err := net.SplitHostPort(server)
if err == nil {
Server = host + "@" + port
server = host + "@" + port
}
cmdArgs = append([]string{"-s", Server}, cmdArgs...)
cmdArgs = append([]string{"-s", server}, cmdArgs...)
}
if ConfigFile != "" {
cmdArgs = append([]string{"-c", ConfigFile}, cmdArgs...)
if configFile != "" {
cmdArgs = append([]string{"-c", configFile}, cmdArgs...)
}
cmd := exec.Command(cmdName, cmdArgs...)
@ -119,7 +119,7 @@ func (s *NSD) Gather(acc telegraf.Accumulator) error {
fieldValue, err := strconv.ParseFloat(value, 64)
if err != nil {
acc.AddError(fmt.Errorf("Expected a numerical value for %s = %v",
acc.AddError(fmt.Errorf("expected a numerical value for %s = %v",
stat, value))
continue
}

View File

@ -3,16 +3,13 @@ package nsd
import (
"bytes"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
)
var TestTimeout = config.Duration(time.Second)
func NSDControl(output string) func(string, config.Duration, bool, string, string) (*bytes.Buffer, error) {
return func(string, config.Duration, bool, string, string) (*bytes.Buffer, error) {
return bytes.NewBuffer([]byte(output)), nil
@ -26,13 +23,13 @@ func TestParseFullOutput(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
require.NoError(t, err)
assert.True(t, acc.HasMeasurement("nsd"))
assert.True(t, acc.HasMeasurement("nsd_servers"))
require.True(t, acc.HasMeasurement("nsd"))
require.True(t, acc.HasMeasurement("nsd_servers"))
assert.Len(t, acc.Metrics, 2)
assert.Equal(t, 99, acc.NFields())
require.Len(t, acc.Metrics, 2)
require.Equal(t, 99, acc.NFields())
acc.AssertContainsFields(t, "nsd", parsedFullOutput)
acc.AssertContainsFields(t, "nsd_servers", parsedFullOutputServerAsTag)

View File

@ -11,10 +11,11 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/testutil"
"github.com/nsqio/go-nsq"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/testutil"
)
// This test is modeled after the kafka consumer integration test
@ -36,7 +37,7 @@ func TestReadsMetricsFromNSQ(t *testing.T) {
}
addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:4155")
newMockNSQD(script, addr.String())
newMockNSQD(t, script, addr.String())
consumer := &NSQConsumer{
Log: testutil.Logger{},
@ -76,6 +77,8 @@ func waitForPoint(acc *testutil.Accumulator, t *testing.T) {
ticker := time.NewTicker(5 * time.Millisecond)
defer ticker.Stop()
counter := 0
//nolint:gosimple // for-select used on purpose
for {
select {
case <-ticker.C:
@ -89,16 +92,15 @@ func waitForPoint(acc *testutil.Accumulator, t *testing.T) {
}
}
func newMockNSQD(script []instruction, addr string) *mockNSQD {
func newMockNSQD(t *testing.T, script []instruction, addr string) *mockNSQD {
n := &mockNSQD{
script: script,
exitChan: make(chan int),
}
tcpListener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("FATAL: listen (%s) failed - %s", n.tcpAddr.String(), err)
}
require.NoError(t, err, "listen (%s) failed", n.tcpAddr.String())
n.tcpListener = tcpListener
n.tcpAddr = tcpListener.Addr().(*net.TCPAddr)
@ -139,6 +141,7 @@ func (n *mockNSQD) handle(conn net.Conn) {
buf := make([]byte, 4)
_, err := io.ReadFull(conn, buf)
if err != nil {
//nolint:revive // log.Fatalf called intentionally
log.Fatalf("ERROR: failed to read protocol version - %s", err)
}
@ -171,14 +174,14 @@ func (n *mockNSQD) handle(conn net.Conn) {
l := make([]byte, 4)
_, err := io.ReadFull(rdr, l)
if err != nil {
log.Printf(err.Error())
log.Print(err.Error())
goto exit
}
size := int32(binary.BigEndian.Uint32(l))
b := make([]byte, size)
_, err = io.ReadFull(rdr, b)
if err != nil {
log.Printf(err.Error())
log.Print(err.Error())
goto exit
}
case bytes.Equal(params[0], []byte("RDY")):

View File

@ -138,10 +138,10 @@ func (ns *Nstat) loadGoodTable(table []byte) map[string]interface{} {
if bytes.Equal(fields[i+1], zeroByte) {
if !ns.DumpZeros {
continue
} else {
entries[string(fields[i])] = int64(0)
continue
}
entries[string(fields[i])] = int64(0)
continue
}
// the counter is not zero, so parse it.
value, err = strconv.ParseInt(string(fields[i+1]), 10, 64)
@ -176,10 +176,10 @@ func (ns *Nstat) loadUglyTable(table []byte) map[string]interface{} {
if bytes.Equal(metrics[j], zeroByte) {
if !ns.DumpZeros {
continue
} else {
entries[string(append(prefix, headers[j]...))] = int64(0)
continue
}
entries[string(append(prefix, headers[j]...))] = int64(0)
continue
}
// the counter is not zero, so parse it.
value, err = strconv.ParseInt(string(metrics[j]), 10, 64)

View File

@ -50,7 +50,7 @@ func (n *NTPQ) Gather(acc telegraf.Accumulator) error {
// Due to problems with a parsing, we have to use regexp expression in order
// to remove string that starts from '(' and ends with space
// see: https://github.com/influxdata/telegraf/issues/2386
reg, err := regexp.Compile("\\s+\\([\\S]*")
reg, err := regexp.Compile(`\s+\([\S]*`)
if err != nil {
return err
}

View File

@ -5,10 +5,10 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSingleNTPQ(t *testing.T) {
@ -20,7 +20,7 @@ func TestSingleNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(101),
@ -49,7 +49,7 @@ func TestBadIntNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.Error(t, acc.GatherError(n.Gather))
require.Error(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(101),
@ -77,7 +77,7 @@ func TestBadFloatNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.Error(t, acc.GatherError(n.Gather))
require.Error(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(2),
@ -105,7 +105,7 @@ func TestDaysNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(172800),
@ -134,7 +134,7 @@ func TestHoursNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(7200),
@ -163,7 +163,7 @@ func TestMinutesNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(120),
@ -192,7 +192,7 @@ func TestBadWhenNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.Error(t, acc.GatherError(n.Gather))
require.Error(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"poll": int64(256),
@ -222,7 +222,7 @@ func TestParserNTPQ(t *testing.T) {
n := newNTPQ()
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"poll": int64(64),
@ -285,7 +285,7 @@ func TestMultiNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"delay": float64(54.033),
@ -329,7 +329,7 @@ func TestBadHeaderNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(101),
@ -357,7 +357,7 @@ func TestMissingDelayColumnNTPQ(t *testing.T) {
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.NoError(t, acc.GatherError(n.Gather))
require.NoError(t, acc.GatherError(n.Gather))
fields := map[string]interface{}{
"when": int64(101),
@ -378,13 +378,13 @@ func TestMissingDelayColumnNTPQ(t *testing.T) {
func TestFailedNTPQ(t *testing.T) {
tt := tester{
ret: []byte(singleNTPQ),
err: fmt.Errorf("Test failure"),
err: fmt.Errorf("test failure"),
}
n := newNTPQ()
n.runQ = tt.runqTest
acc := testutil.Accumulator{}
assert.Error(t, acc.GatherError(n.Gather))
require.Error(t, acc.GatherError(n.Gather))
}
// It is possible for the output of ntqp to be missing the refid column. This

View File

@ -10,6 +10,7 @@ import (
"github.com/gopcua/opcua"
"github.com/gopcua/opcua/ua"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/choice"
@ -242,14 +243,14 @@ func (o *OpcUA) validateEndpoint() error {
//search security policy type
switch o.SecurityPolicy {
case "None", "Basic128Rsa15", "Basic256", "Basic256Sha256", "auto":
break
// Valid security policy type - do nothing.
default:
return fmt.Errorf("invalid security type '%s' in '%s'", o.SecurityPolicy, o.MetricName)
}
//search security mode type
switch o.SecurityMode {
case "None", "Sign", "SignAndEncrypt", "auto":
break
// Valid security mode type - do nothing.
default:
return fmt.Errorf("invalid security type '%s' in '%s'", o.SecurityMode, o.MetricName)
}
@ -384,7 +385,7 @@ func (o *OpcUA) validateOPCTags() error {
//search identifier type
switch node.tag.IdentifierType {
case "s", "i", "g", "b":
break
// Valid identifier type - do nothing.
default:
return fmt.Errorf("invalid identifier type '%s' in '%s'", node.tag.IdentifierType, node.tag.FieldName)
}
@ -468,7 +469,7 @@ func (o *OpcUA) setupOptions() error {
if o.Certificate == "" && o.PrivateKey == "" {
if o.SecurityPolicy != "None" || o.SecurityMode != "None" {
o.Certificate, o.PrivateKey, err = generateCert("urn:telegraf:gopcua:client", 2048, o.Certificate, o.PrivateKey, (365 * 24 * time.Hour))
o.Certificate, o.PrivateKey, err = generateCert("urn:telegraf:gopcua:client", 2048, o.Certificate, o.PrivateKey, 365*24*time.Hour)
if err != nil {
return err
}

View File

@ -6,11 +6,10 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type OPCTags struct {
@ -137,30 +136,30 @@ nodes = [{name="name4", identifier="4000", tags=[["tag1", "override"]]}]
func TestTagsSliceToMap(t *testing.T) {
m, err := tagsSliceToMap([][]string{{"foo", "bar"}, {"baz", "bat"}})
assert.NoError(t, err)
assert.Len(t, m, 2)
assert.Equal(t, m["foo"], "bar")
assert.Equal(t, m["baz"], "bat")
require.NoError(t, err)
require.Len(t, m, 2)
require.Equal(t, m["foo"], "bar")
require.Equal(t, m["baz"], "bat")
}
func TestTagsSliceToMap_twoStrings(t *testing.T) {
var err error
_, err = tagsSliceToMap([][]string{{"foo", "bar", "baz"}})
assert.Error(t, err)
require.Error(t, err)
_, err = tagsSliceToMap([][]string{{"foo"}})
assert.Error(t, err)
require.Error(t, err)
}
func TestTagsSliceToMap_dupeKey(t *testing.T) {
_, err := tagsSliceToMap([][]string{{"foo", "bar"}, {"foo", "bat"}})
assert.Error(t, err)
require.Error(t, err)
}
func TestTagsSliceToMap_empty(t *testing.T) {
_, err := tagsSliceToMap([][]string{{"foo", ""}})
assert.Equal(t, fmt.Errorf("tag 1 has empty value"), err)
require.Equal(t, fmt.Errorf("tag 1 has empty value"), err)
_, err = tagsSliceToMap([][]string{{"", "bar"}})
assert.Equal(t, fmt.Errorf("tag 1 has empty name"), err)
require.Equal(t, fmt.Errorf("tag 1 has empty name"), err)
}
func TestValidateOPCTags(t *testing.T) {

View File

@ -5,10 +5,11 @@ import (
"strconv"
"strings"
"gopkg.in/ldap.v3"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"gopkg.in/ldap.v3"
)
type Openldap struct {
@ -110,13 +111,15 @@ func (o *Openldap) Gather(acc telegraf.Accumulator) error {
acc.AddError(err)
return nil
}
if o.TLS == "ldaps" {
switch o.TLS {
case "ldaps":
l, err = ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", o.Host, o.Port), tlsConfig)
if err != nil {
acc.AddError(err)
return nil
}
} else if o.TLS == "starttls" {
case "starttls":
l, err = ldap.Dial("tcp", fmt.Sprintf("%s:%d", o.Host, o.Port))
if err != nil {
acc.AddError(err)
@ -127,7 +130,7 @@ func (o *Openldap) Gather(acc telegraf.Accumulator) error {
acc.AddError(err)
return nil
}
} else {
default:
acc.AddError(fmt.Errorf("invalid setting for ssl: %s", o.TLS))
return nil
}

View File

@ -4,10 +4,10 @@ import (
"strconv"
"testing"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/ldap.v3"
"github.com/influxdata/telegraf/testutil"
)
func TestOpenldapMockResult(t *testing.T) {
@ -45,9 +45,9 @@ func TestOpenldapNoConnectionIntegration(t *testing.T) {
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err) // test that we didn't return an error
assert.Zero(t, acc.NFields()) // test that we didn't return any fields
assert.NotEmpty(t, acc.Errors) // test that we set an error
require.NoError(t, err) // test that we didn't return an error
require.Zero(t, acc.NFields()) // test that we didn't return any fields
require.NotEmpty(t, acc.Errors) // test that we set an error
}
func TestOpenldapGeneratesMetricsIntegration(t *testing.T) {
@ -108,9 +108,9 @@ func TestOpenldapInvalidSSLIntegration(t *testing.T) {
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err) // test that we didn't return an error
assert.Zero(t, acc.NFields()) // test that we didn't return any fields
assert.NotEmpty(t, acc.Errors) // test that we set an error
require.NoError(t, err) // test that we didn't return an error
require.Zero(t, acc.NFields()) // test that we didn't return any fields
require.NotEmpty(t, acc.Errors) // test that we set an error
}
func TestOpenldapBindIntegration(t *testing.T) {
@ -132,11 +132,11 @@ func TestOpenldapBindIntegration(t *testing.T) {
}
func commonTests(t *testing.T, o *Openldap, acc *testutil.Accumulator) {
assert.Empty(t, acc.Errors, "accumulator had no errors")
assert.True(t, acc.HasMeasurement("openldap"), "Has a measurement called 'openldap'")
assert.Equal(t, o.Host, acc.TagValue("openldap", "server"), "Has a tag value of server=o.Host")
assert.Equal(t, strconv.Itoa(o.Port), acc.TagValue("openldap", "port"), "Has a tag value of port=o.Port")
assert.True(t, acc.HasInt64Field("openldap", "total_connections"), "Has an integer field called total_connections")
require.Empty(t, acc.Errors, "accumulator had no errors")
require.True(t, acc.HasMeasurement("openldap"), "Has a measurement called 'openldap'")
require.Equal(t, o.Host, acc.TagValue("openldap", "server"), "Has a tag value of server=o.Host")
require.Equal(t, strconv.Itoa(o.Port), acc.TagValue("openldap", "port"), "Has a tag value of port=o.Port")
require.True(t, acc.HasInt64Field("openldap", "total_connections"), "Has an integer field called total_connections")
}
func TestOpenldapReverseMetricsIntegration(t *testing.T) {
@ -155,5 +155,5 @@ func TestOpenldapReverseMetricsIntegration(t *testing.T) {
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err)
assert.True(t, acc.HasInt64Field("openldap", "connections_total"), "Has an integer field called connections_total")
require.True(t, acc.HasInt64Field("openldap", "connections_total"), "Has an integer field called connections_total")
}

View File

@ -3,16 +3,13 @@ package openntpd
import (
"bytes"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
)
var TestTimeout = config.Duration(time.Second)
func OpenntpdCTL(output string) func(string, config.Duration, bool) (*bytes.Buffer, error) {
return func(string, config.Duration, bool) (*bytes.Buffer, error) {
return bytes.NewBuffer([]byte(output)), nil
@ -26,11 +23,11 @@ func TestParseSimpleOutput(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
assert.True(t, acc.HasMeasurement("openntpd"))
assert.Equal(t, acc.NMetrics(), uint64(1))
require.NoError(t, err)
require.True(t, acc.HasMeasurement("openntpd"))
require.Equal(t, acc.NMetrics(), uint64(1))
assert.Equal(t, acc.NFields(), 7)
require.Equal(t, acc.NFields(), 7)
firstpeerfields := map[string]interface{}{
"wt": int64(1),
@ -57,11 +54,11 @@ func TestParseSimpleOutputwithStatePrefix(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
assert.True(t, acc.HasMeasurement("openntpd"))
assert.Equal(t, acc.NMetrics(), uint64(1))
require.NoError(t, err)
require.True(t, acc.HasMeasurement("openntpd"))
require.Equal(t, acc.NMetrics(), uint64(1))
assert.Equal(t, acc.NFields(), 7)
require.Equal(t, acc.NFields(), 7)
firstpeerfields := map[string]interface{}{
"wt": int64(1),
@ -89,11 +86,11 @@ func TestParseSimpleOutputInvalidPeer(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
assert.True(t, acc.HasMeasurement("openntpd"))
assert.Equal(t, acc.NMetrics(), uint64(1))
require.NoError(t, err)
require.True(t, acc.HasMeasurement("openntpd"))
require.Equal(t, acc.NMetrics(), uint64(1))
assert.Equal(t, acc.NFields(), 4)
require.Equal(t, acc.NFields(), 4)
firstpeerfields := map[string]interface{}{
"wt": int64(1),
@ -117,11 +114,11 @@ func TestParseSimpleOutputServersDNSError(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
assert.True(t, acc.HasMeasurement("openntpd"))
assert.Equal(t, acc.NMetrics(), uint64(1))
require.NoError(t, err)
require.True(t, acc.HasMeasurement("openntpd"))
require.Equal(t, acc.NMetrics(), uint64(1))
assert.Equal(t, acc.NFields(), 4)
require.Equal(t, acc.NFields(), 4)
firstpeerfields := map[string]interface{}{
"next": int64(2),
@ -159,11 +156,11 @@ func TestParseSimpleOutputServerDNSError(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
assert.True(t, acc.HasMeasurement("openntpd"))
assert.Equal(t, acc.NMetrics(), uint64(1))
require.NoError(t, err)
require.True(t, acc.HasMeasurement("openntpd"))
require.Equal(t, acc.NMetrics(), uint64(1))
assert.Equal(t, acc.NFields(), 4)
require.Equal(t, acc.NFields(), 4)
firstpeerfields := map[string]interface{}{
"next": int64(12),
@ -187,11 +184,11 @@ func TestParseFullOutput(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
assert.True(t, acc.HasMeasurement("openntpd"))
assert.Equal(t, acc.NMetrics(), uint64(20))
require.NoError(t, err)
require.True(t, acc.HasMeasurement("openntpd"))
require.Equal(t, acc.NMetrics(), uint64(20))
assert.Equal(t, acc.NFields(), 113)
require.Equal(t, acc.NFields(), 113)
firstpeerfields := map[string]interface{}{
"wt": int64(1),

View File

@ -4,9 +4,10 @@ import (
"bytes"
"testing"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
)
func SMTPCTL(output string) func(string, config.Duration, bool) (*bytes.Buffer, error) {
@ -22,11 +23,11 @@ func TestFilterSomeStats(t *testing.T) {
}
err := v.Gather(acc)
assert.NoError(t, err)
assert.True(t, acc.HasMeasurement("opensmtpd"))
assert.Equal(t, acc.NMetrics(), uint64(1))
require.NoError(t, err)
require.True(t, acc.HasMeasurement("opensmtpd"))
require.Equal(t, acc.NMetrics(), uint64(1))
assert.Equal(t, acc.NFields(), 36)
require.Equal(t, acc.NFields(), 36)
acc.AssertContainsFields(t, "opensmtpd", parsedFullOutput)
}

View File

@ -5,10 +5,6 @@ import (
"net"
"testing"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
"go.opentelemetry.io/otel/metric"
@ -18,6 +14,10 @@ import (
"go.opentelemetry.io/otel/sdk/metric/selector/simple"
"google.golang.org/grpc"
"google.golang.org/grpc/test/bufconn"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/testutil"
)
func TestOpenTelemetry(t *testing.T) {
@ -72,12 +72,11 @@ func TestOpenTelemetry(t *testing.T) {
// Check
assert.Empty(t, accumulator.Errors)
require.Empty(t, accumulator.Errors)
if assert.Len(t, accumulator.Metrics, 1) {
got := accumulator.Metrics[0]
assert.Equal(t, "measurement-counter", got.Measurement)
assert.Equal(t, telegraf.Counter, got.Type)
assert.Equal(t, "library-name", got.Tags["otel.library.name"])
}
require.Len(t, accumulator.Metrics, 1)
got := accumulator.Metrics[0]
require.Equal(t, "measurement-counter", got.Measurement)
require.Equal(t, telegraf.Counter, got.Type)
require.Equal(t, "library-name", got.Tags["otel.library.name"])
}

View File

@ -23,10 +23,10 @@ const (
// The limit of locations is 20.
owmRequestSeveralCityID int = 20
defaultBaseURL = "https://api.openweathermap.org/"
defaultResponseTimeout time.Duration = time.Second * 5
defaultUnits string = "metric"
defaultLang string = "en"
defaultBaseURL = "https://api.openweathermap.org/"
defaultResponseTimeout = time.Second * 5
defaultUnits = "metric"
defaultLang = "en"
)
type OpenWeatherMap struct {
@ -38,8 +38,8 @@ type OpenWeatherMap struct {
ResponseTimeout config.Duration `toml:"response_timeout"`
Units string `toml:"units"`
client *http.Client
baseURL *url.URL
client *http.Client
baseParsedURL *url.URL
}
var sampleConfig = `
@ -309,7 +309,7 @@ func init() {
func (n *OpenWeatherMap) Init() error {
var err error
n.baseURL, err = url.Parse(n.BaseURL)
n.baseParsedURL, err = url.Parse(n.BaseURL)
if err != nil {
return err
}
@ -353,5 +353,5 @@ func (n *OpenWeatherMap) formatURL(path string, city string) string {
RawQuery: v.Encode(),
}
return n.baseURL.ResolveReference(relative).String()
return n.baseParsedURL.ResolveReference(relative).String()
}