From 080e9a13387b4661d20e67252adedccfdea02715 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Mon, 31 Mar 2025 14:52:09 +0200 Subject: [PATCH] chore(deps): Bump golangci-lint from v1.64.5 to v2.0.2 (#16683) --- .circleci/config.yml | 6 +- .golangci.yml | 962 ++++++++++-------- Makefile | 2 +- config/config_test.go | 2 +- internal/internal_test.go | 2 +- internal/templating/engine_test.go | 2 +- migrations/global_agent/migration_test.go | 1 + .../aggregators/histogram/histogram_test.go | 2 +- plugins/common/jolokia2/gatherer_test.go | 2 +- plugins/common/shim/goshim.go | 2 +- .../inputs/amd_rocm_smi/amd_rocm_smi_test.go | 7 +- plugins/inputs/clickhouse/clickhouse_test.go | 2 +- plugins/inputs/cpu/cpu_test.go | 9 +- plugins/inputs/dpdk/dpdk_connector_test.go | 2 +- plugins/inputs/dpdk/dpdk_test.go | 2 +- plugins/inputs/dpdk/dpdk_utils_test.go | 2 +- plugins/inputs/execd/execd_test.go | 2 +- plugins/inputs/intel_baseband/utils_test.go | 6 +- plugins/inputs/intel_dlb/intel_dlb_test.go | 2 +- .../intel_powerstat/intel_powerstat_test.go | 2 +- plugins/inputs/intel_rdt/intel_rdt_test.go | 4 +- plugins/inputs/intel_rdt/publisher_test.go | 10 +- plugins/inputs/internal/internal_test.go | 2 +- plugins/inputs/lanz/lanz.go | 2 +- plugins/inputs/mesos/mesos_test.go | 2 +- plugins/inputs/mock/mock_test.go | 2 +- plugins/inputs/modbus/modbus_test.go | 4 +- .../inputs/nsq_consumer/nsq_consumer_test.go | 2 +- plugins/inputs/nvidia_smi/nvidia_smi_test.go | 7 +- plugins/inputs/prometheus/kubernetes_test.go | 2 +- .../inputs/stackdriver/stackdriver_test.go | 2 +- plugins/inputs/statsd/statsd_test.go | 2 +- plugins/inputs/varnish/varnish_test.go | 2 +- .../win_perf_counters_integration_test.go | 35 +- plugins/outputs/amqp/amqp_test.go | 2 +- plugins/outputs/cloudwatch/cloudwatch_test.go | 2 +- .../elasticsearch/elasticsearch_test.go | 2 +- plugins/outputs/influxdb/http_test.go | 4 +- plugins/outputs/kinesis/kinesis_test.go | 14 +- .../outputs/stackdriver/stackdriver_test.go | 6 +- plugins/outputs/timestream/timestream_test.go | 2 +- plugins/outputs/wavefront/wavefront_test.go | 2 +- plugins/outputs/zabbix/autoregister_test.go | 4 +- plugins/parsers/collectd/parser_test.go | 2 +- .../influx/influx_upstream/parser_test.go | 6 +- plugins/parsers/influx/parser_test.go | 6 +- plugins/parsers/json_v2/parser_test.go | 2 +- plugins/parsers/nagios/parser_test.go | 2 +- plugins/serializers/graphite/graphite_test.go | 4 +- testutil/accumulator.go | 15 +- 50 files changed, 625 insertions(+), 547 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 47ea61841..f78e1a3ea 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -106,7 +106,7 @@ jobs: - run: 'make check-deps' - run: name: "Install golangci-lint" - command: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.5 + command: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.0.2 - run: name: "golangci-lint/Linux" # There are only 4 vCPUs available for this executor, so use only 4 instead of the default number @@ -120,7 +120,7 @@ jobs: - check-changed-files-or-halt - run: name: "Install golangci-lint" - command: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.5 + command: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.0.2 - run: name: "golangci-lint/macOS" # There are only 4 vCPUs available for this executor, so use only 4 instead of the default number @@ -134,7 +134,7 @@ jobs: - check-changed-files-or-halt - run: name: "Install golangci-lint" - command: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.5 + command: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.0.2 - run: name: "golangci-lint/Windows" # There are only 4 vCPUs available for this executor, so use only 4 instead of the default number diff --git a/.golangci.yml b/.golangci.yml index 773d49df8..2b9f91587 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,13 @@ +version: "2" + linters: - disable-all: true + # Default set of linters. + # The value can be: `standard`, `all`, `none`, or `fast`. + # Default: standard + default: none + + # Enable specific linter. + # https://golangci-lint.run/usage/linters/#enabled-by-default enable: - asasalint - asciicheck @@ -11,12 +19,10 @@ linters: - errcheck - errname - errorlint - - gci - gocheckcompilerdirectives - gocritic - goprintffuncname - gosec - - gosimple - govet - ineffassign - interfacebloat @@ -34,401 +40,516 @@ linters: - staticcheck - testifylint - tparallel - - typecheck - unconvert - unparam - unused - usetesting -linters-settings: - depguard: - rules: - # Name of a rule. - main: - # Packages that are not allowed where the value is a suggestion. - deny: - - pkg: log - desc: 'Use injected telegraf.Logger instead' - # List of file globs that will match this list of settings to compare against. - # Default: $all - files: - - "!**/agent/**" - - "!**/cmd/**" - - "!**/config/**" - - "!**/filter/**" - - "!**/internal/**" - - "!**/logger/**" - - "!**/metric/**" - - "!**/models/**" - - "!**/plugins/serializers/**" - - "!**/scripts/**" - - "!**/selfstat/**" - - "!**/testutil/**" - - "!**/tools/**" - - "!**/*_test.go" - errcheck: - # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`. - # Such cases aren't reported by default. - # Default: false - check-blank: true + settings: + depguard: + # Rules to apply. + # + # Variables: + # - File Variables + # Use an exclamation mark `!` to negate a variable. + # Example: `!$test` matches any file that is not a go test file. + # + # `$all` - matches all go files + # `$test` - matches all go test files + # + # - Package Variables + # + # `$gostd` - matches all of go's standard library (Pulled from `GOROOT`) + # + # Default (applies if no custom rules are defined): Only allow $gostd in all files. + rules: + # Name of a rule. + main: + # List of file globs that will match this list of settings to compare against. + # By default, if a path is relative, it is relative to the directory where the golangci-lint command is executed. + # The placeholder '${base-path}' is substituted with a path relative to the mode defined with `run.relative-path-mode`. + # Default: $all + files: + - '!**/agent/**' + - '!**/cmd/**' + - '!**/config/**' + - '!**/filter/**' + - '!**/internal/**' + - '!**/logger/**' + - '!**/metric/**' + - '!**/models/**' + - '!**/plugins/serializers/**' + - '!**/scripts/**' + - '!**/selfstat/**' + - '!**/testutil/**' + - '!**/tools/**' + - '!**/*_test.go' + # List of packages that are not allowed. + # Entries can be a variable (starting with $), a string prefix, or an exact match (if ending with $). + # Default: [] + deny: + - pkg: log + desc: 'Use injected telegraf.Logger instead' - # List of functions to exclude from checking, where each entry is a single function to exclude. - # See https://github.com/kisielk/errcheck#excluding-functions for details. - exclude-functions: - - "(*hash/maphash.Hash).Write" - - "(*hash/maphash.Hash).WriteByte" - - "(*hash/maphash.Hash).WriteString" - - "(*github.com/influxdata/telegraf/plugins/outputs/postgresql/sqltemplate.Template).UnmarshalText" + errcheck: + # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`. + # Such cases aren't reported by default. + # Default: false + check-blank: true - gci: - sections: - - standard - - default - - localmodule - - gocritic: - # Disable all checks. - # Default: false - disable-all: true - # Which checks should be enabled in addition to default checks; can't be combined with 'disabled-checks'. - # By default, list of stable checks is used (https://go-critic.com/overview#checks-overview). - # To see which checks are enabled run `GL_DEBUG=gocritic golangci-lint run --enable=gocritic`. - enabled-checks: - # diagnostic - - argOrder - - badCall - - badCond - - badLock - - badRegexp - - badSorting - - badSyncOnceFunc - - builtinShadowDecl - - caseOrder - - codegenComment - - commentedOutCode - - deferInLoop - - deprecatedComment - - dupArg - - dupBranchBody - - dupCase - - dupSubExpr - - dynamicFmtString - - emptyDecl - - evalOrder - - exitAfterDefer - - externalErrorReassign - - filepathJoin - - flagName - - mapKey - - nilValReturn - - offBy1 - - regexpPattern - - sloppyLen - - sloppyReassign - - sloppyTypeAssert - - sortSlice - - sprintfQuotedString - - sqlQuery - - syncMapLoadAndDelete - - truncateCmp - - uncheckedInlineErr - - unnecessaryDefer - - weakCond - # performance - - appendCombine - - equalFold - - hugeParam - - indexAlloc - - preferDecodeRune - - preferFprint - - preferStringWriter - - preferWriteByte - - rangeExprCopy - - rangeValCopy - - sliceClear - - stringXbytes + # List of functions to exclude from checking, where each entry is a single function to exclude. + # See https://github.com/kisielk/errcheck#excluding-functions for details. + exclude-functions: + - '(*hash/maphash.Hash).Write' + - '(*hash/maphash.Hash).WriteByte' + - '(*hash/maphash.Hash).WriteString' + - '(*github.com/influxdata/telegraf/plugins/outputs/postgresql/sqltemplate.Template).UnmarshalText' - # Settings passed to gocritic. - # The settings key is the name of a supported gocritic checker. - # The list of supported checkers can be find in https://go-critic.com/overview. - settings: - hugeParam: - # Size in bytes that makes the warning trigger. - # Default: 80 - sizeThreshold: 512 - rangeValCopy: - # Size in bytes that makes the warning trigger. - # Default: 128 - sizeThreshold: 512 + gocritic: + # Disable all checks. + # Default: false + disable-all: true + # Which checks should be enabled in addition to default checks; can't be combined with 'disabled-checks'. + # By default, list of stable checks is used (https://go-critic.com/overview#checks-overview). + # To see which checks are enabled run `GL_DEBUG=gocritic golangci-lint run --enable=gocritic`. + enabled-checks: + # diagnostic + - argOrder + - badCall + - badCond + - badLock + - badRegexp + - badSorting + - badSyncOnceFunc + - builtinShadowDecl + - caseOrder + - codegenComment + - commentedOutCode + - deferInLoop + - deprecatedComment + - dupArg + - dupBranchBody + - dupCase + - dupSubExpr + - dynamicFmtString + - emptyDecl + - evalOrder + - exitAfterDefer + - externalErrorReassign + - filepathJoin + - flagName + - mapKey + - nilValReturn + - offBy1 + - regexpPattern + - sloppyLen + - sloppyReassign + - sloppyTypeAssert + - sortSlice + - sprintfQuotedString + - sqlQuery + - syncMapLoadAndDelete + - truncateCmp + - uncheckedInlineErr + - unnecessaryDefer + - weakCond + # performance + - appendCombine + - equalFold + - hugeParam + - indexAlloc + - preferDecodeRune + - preferFprint + - preferStringWriter + - preferWriteByte + - rangeExprCopy + - rangeValCopy + - sliceClear + - stringXbytes - gosec: - # To select a subset of rules to run. - # Available rules: https://github.com/securego/gosec#available-rules - # Default: [] - means include all rules - includes: - - G101 # Look for hard coded credentials - - G102 # Bind to all interfaces - - G103 # Audit the use of unsafe block - - G106 # Audit the use of ssh.InsecureIgnoreHostKey - - G107 # Url provided to HTTP request as taint input - - G108 # Profiling endpoint automatically exposed on /debug/pprof - - G109 # Potential Integer overflow made by strconv.Atoi result conversion to int16/32 - - G110 # Potential DoS vulnerability via decompression bomb - - G111 # Potential directory traversal - - G112 # Potential slowloris attack - - G114 # Use of net/http serve function that has no support for setting timeouts - - G201 # SQL query construction using format string - - G202 # SQL query construction using string concatenation - - G203 # Use of unescaped data in HTML templates - - G301 # Poor file permissions used when creating a directory - - G302 # Poor file permissions used with chmod - - G303 # Creating tempfile using a predictable path - - G305 # File traversal when extracting zip/tar archive - - G306 # Poor file permissions used when writing to a new file - - G401 # Detect the usage of MD5 or SHA1 - - G403 # Ensure minimum RSA key length of 2048 bits - - G404 # Insecure random number source (rand) - - G405 # Detect the usage of DES or RC4 - - G406 # Detect the usage of MD4 or RIPEMD160 - - G501 # Import blocklist: crypto/md5 - - G502 # Import blocklist: crypto/des - - G503 # Import blocklist: crypto/rc4 - - G505 # Import blocklist: crypto/sha1 - - G506 # Import blocklist: golang.org/x/crypto/md4 - - G507 # Import blocklist: golang.org/x/crypto/ripemd160 - - G601 # Implicit memory aliasing of items from a range statement - - G602 # Slice access out of bounds + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be find in https://go-critic.com/overview. + settings: + hugeParam: + # Size in bytes that makes the warning trigger. + # Default: 80 + sizeThreshold: 512 + rangeValCopy: + # Size in bytes that makes the warning trigger. + # Default: 128 + sizeThreshold: 512 + + gosec: + # To select a subset of rules to run. + # Available rules: https://github.com/securego/gosec#available-rules + # Default: [] - means include all rules + includes: + - G101 # Look for hard coded credentials + - G102 # Bind to all interfaces + - G103 # Audit the use of unsafe block + - G106 # Audit the use of ssh.InsecureIgnoreHostKey + - G107 # Url provided to HTTP request as taint input + - G108 # Profiling endpoint automatically exposed on /debug/pprof + - G109 # Potential Integer overflow made by strconv.Atoi result conversion to int16/32 + - G110 # Potential DoS vulnerability via decompression bomb + - G111 # Potential directory traversal + - G112 # Potential slowloris attack + - G114 # Use of net/http serve function that has no support for setting timeouts + - G201 # SQL query construction using format string + - G202 # SQL query construction using string concatenation + - G203 # Use of unescaped data in HTML templates + - G301 # Poor file permissions used when creating a directory + - G302 # Poor file permissions used with chmod + - G303 # Creating tempfile using a predictable path + - G305 # File traversal when extracting zip/tar archive + - G306 # Poor file permissions used when writing to a new file + - G401 # Detect the usage of MD5 or SHA1 + - G403 # Ensure minimum RSA key length of 2048 bits + - G404 # Insecure random number source (rand) + - G405 # Detect the usage of DES or RC4 + - G406 # Detect the usage of MD4 or RIPEMD160 + - G501 # Import blocklist: crypto/md5 + - G502 # Import blocklist: crypto/des + - G503 # Import blocklist: crypto/rc4 + - G505 # Import blocklist: crypto/sha1 + - G506 # Import blocklist: golang.org/x/crypto/md4 + - G507 # Import blocklist: golang.org/x/crypto/ripemd160 + - G601 # Implicit memory aliasing of items from a range statement + - G602 # Slice access out of bounds # G104, G105, G113, G204, G304, G307, G402, G504 were not enabled intentionally # TODO: review G115 when reporting false positives is fixed (https://github.com/securego/gosec/issues/1212) - # To specify the configuration of rules. - config: - # Maximum allowed permissions mode for os.OpenFile and os.Chmod - # Default: "0600" - G302: "0640" - # Maximum allowed permissions mode for os.WriteFile and ioutil.WriteFile - # Default: "0600" - G306: "0640" - govet: - settings: - ## Check the logging function like it would be a printf - printf: - # Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`). - # Default: [] - funcs: - - (github.com/influxdata/telegraf.Logger).Debugf - - (github.com/influxdata/telegraf.Logger).Infof - - (github.com/influxdata/telegraf.Logger).Warnf - - (github.com/influxdata/telegraf.Logger).Errorf - - (github.com/influxdata/telegraf.Logger).Debug - - (github.com/influxdata/telegraf.Logger).Info - - (github.com/influxdata/telegraf.Logger).Warn - - (github.com/influxdata/telegraf.Logger).Error - lll: - # Max line length, lines longer will be reported. - # '\t' is counted as 1 character by default, and can be changed with the tab-width option. - # Default: 120. - line-length: 160 - # Tab width in spaces. - # Default: 1 - tab-width: 4 - nakedret: - # Make an issue if func has more lines of code than this setting, and it has naked returns. - # Default: 30 - max-func-lines: 1 - nolintlint: - # Enable to require an explanation of nonzero length after each nolint directive. - # Default: false - require-explanation: true - # Enable to require nolint directives to mention the specific linter being suppressed. - # Default: false - require-specific: true - prealloc: - # Report pre-allocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. - # Default: true - simple: false - revive: + + # To specify the configuration of rules. + config: + # Maximum allowed permissions mode for os.OpenFile and os.Chmod + # Default: "0600" + G302: "0640" + # Maximum allowed permissions mode for os.WriteFile and ioutil.WriteFile + # Default: "0600" + G306: "0640" + + govet: + # Settings per analyzer. + settings: + # Analyzer name, run `go tool vet help` to see all analyzers. + printf: + # Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`). + # Default: [] + funcs: + - (github.com/influxdata/telegraf.Logger).Tracef + - (github.com/influxdata/telegraf.Logger).Debugf + - (github.com/influxdata/telegraf.Logger).Infof + - (github.com/influxdata/telegraf.Logger).Warnf + - (github.com/influxdata/telegraf.Logger).Errorf + - (github.com/influxdata/telegraf.Logger).Trace + - (github.com/influxdata/telegraf.Logger).Debug + - (github.com/influxdata/telegraf.Logger).Info + - (github.com/influxdata/telegraf.Logger).Warn + - (github.com/influxdata/telegraf.Logger).Error + + lll: + # Max line length, lines longer will be reported. + # '\t' is counted as 1 character by default, and can be changed with the tab-width option. + # Default: 120. + line-length: 160 + # Tab width in spaces. + # Default: 1 + tab-width: 4 + + nakedret: + # Make an issue if func has more lines of code than this setting, and it has naked returns. + # Default: 30 + max-func-lines: 1 + + nolintlint: + # Enable to require an explanation of nonzero length after each nolint directive. + # Default: false + require-explanation: true + # Enable to require nolint directives to mention the specific linter being suppressed. + # Default: false + require-specific: true + + prealloc: + # Report pre-allocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. + # Default: true + simple: false + + revive: + # Sets the default severity. + # See https://github.com/mgechev/revive#configuration + # Default: warning + severity: error + + # Run `GL_DEBUG=revive golangci-lint run --enable-only=revive` to see default, all available rules, and enabled rules. + rules: + - name: argument-limit + arguments: [ 6 ] + - name: atomic + - name: bare-return + - name: blank-imports + - name: bool-literal-in-expr + - name: call-to-gc + - name: comment-spacings + - name: confusing-naming + - name: confusing-results + - name: constant-logical-expr + - name: context-as-argument + - name: context-keys-type + - name: datarace + - name: deep-exit + - name: defer + - name: dot-imports + - name: duplicated-imports + - name: early-return + - name: empty-block + - name: empty-lines + - name: enforce-map-style + exclude: [ "TEST" ] + arguments: + - "make" + - name: enforce-repeated-arg-type-style + arguments: + - "short" + - name: enforce-slice-style + arguments: + - "make" + - name: error-naming + - name: error-return + - name: error-strings + - name: errorf + - name: function-result-limit + arguments: [ 3 ] + - name: get-return + - name: identical-branches + - name: if-return + - name: import-alias-naming + arguments: + - "^[a-z][a-z0-9_]*[a-z0-9]+$" + - name: import-shadowing + - name: increment-decrement + - name: indent-error-flow + - name: max-public-structs + arguments: [ 5 ] + exclude: [ "TEST" ] + - name: modifies-parameter + - name: modifies-value-receiver + - name: optimize-operands-order + - name: package-comments + - name: range + - name: range-val-address + - name: range-val-in-closure + - name: receiver-naming + - name: redefines-builtin-id + - name: redundant-import-alias + - name: string-format + arguments: + - - 'fmt.Errorf[0],errors.New[0]' + - '/^([^A-Z]|$)/' + - 'Error string must not start with a capital letter.' + - - 'fmt.Errorf[0],errors.New[0]' + - '/(^|[^\.!?])$/' + - 'Error string must not end in punctuation.' + - - 'panic' + - '/^[^\n]*$/' + - 'Must not contain line breaks.' + - name: string-of-int + - name: struct-tag + - name: superfluous-else + - name: time-equal + - name: time-naming + - name: unconditional-recursion + - name: unexported-naming + - name: unnecessary-stmt + - name: unreachable-code + - name: unused-parameter + - name: unused-receiver + - name: var-declaration + - name: var-naming + - name: waitgroup-by-value + + staticcheck: + # SAxxxx checks in https://staticcheck.dev/docs/configuration/options/#checks + # Example (to disable some checks): [ "all", "-SA1000", "-SA1001"] + # Default: ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"] + checks: + - all + # Poorly chosen identifier. + # https://staticcheck.dev/docs/checks/#ST1003 + - -ST1003 + # Incorrectly formatted error string. + # https://staticcheck.dev/docs/checks/#ST1005 + - -ST1005 + # Should use constants for HTTP error codes, not magic numbers. + # https://staticcheck.dev/docs/checks/#ST1013 + - -ST1013 + # Use consistent method receiver names. + # https://staticcheck.dev/docs/checks/#ST1016 + - -ST1016 + # Don't use Yoda conditions. + # https://staticcheck.dev/docs/checks/#ST1017 + - -ST1017 + # The documentation of an exported function should start with the function's name. + # https://staticcheck.dev/docs/checks/#ST1020 + - -ST1020 + # The documentation of an exported type should start with type's name. + # https://staticcheck.dev/docs/checks/#ST1021 + - -ST1021 + # The documentation of an exported variable or constant should start with variable's name. + # https://staticcheck.dev/docs/checks/#ST1022 + - -ST1022 + # Apply De Morgan's law. + # https://staticcheck.dev/docs/checks/#QF1001 + - -QF1001 + # Convert untagged switch to tagged switch. + # https://staticcheck.dev/docs/checks/#QF1002 + - -QF1002 + # Convert if/else-if chain to tagged switch. + # https://staticcheck.dev/docs/checks/#QF1003 + - -QF1003 + # Use 'strings.ReplaceAll' instead of 'strings.Replace' with 'n == -1'. + # https://staticcheck.dev/docs/checks/#QF1004 + - -QF1004 + # Lift 'if'+'break' into loop condition. + # https://staticcheck.dev/docs/checks/#QF1006 + - -QF1006 + # Merge conditional assignment into variable declaration. + # https://staticcheck.dev/docs/checks/#QF1007 + - -QF1007 + # Omit embedded fields from selector expression. + # https://staticcheck.dev/docs/checks/#QF1008 + - -QF1008 + # Use 'time.Time.Equal' instead of '==' operator. + # https://staticcheck.dev/docs/checks/#QF1009 + - -QF1009 + + testifylint: + # Disable all checkers (https://github.com/Antonboom/testifylint#checkers). + # Default: false + disable-all: true + # Enable checkers by name + enable: + - blank-import + - bool-compare + - compares + - contains + - empty + - encoded-compare + - error-is-as + - error-nil + - expected-actual + - float-compare + - formatter + - go-require + - len + - negative-positive + - nil-compare + - regexp + - require-error + - suite-broken-parallel + - suite-dont-use-pkg + - suite-extra-assert-call + - suite-subtest-run + - suite-thelper + - useless-assert + + usetesting: + # Enable/disable `os.TempDir()` detections. + # Default: false + os-temp-dir: true + + # Defines a set of rules to ignore issues. + # It does not skip the analysis, and so does not ignore "typecheck" errors. + exclusions: + # Mode of the generated files analysis. + # + # - `strict`: sources are excluded by strictly following the Go generated file convention. + # Source files that have lines matching only the following regular expression will be excluded: `^// Code generated .* DO NOT EDIT\.$` + # This line must appear before the first non-comment, non-blank text in the file. + # https://go.dev/s/generatedcode + # - `lax`: sources are excluded if they contain lines like `autogenerated file`, `code generated`, `do not edit`, etc. + # - `disable`: disable the generated files exclusion. + # + # Default: lax + generated: lax + + # Excluding configuration per-path, per-linter, per-text and per-source. rules: - - name: argument-limit - arguments: [ 6 ] - - name: atomic - - name: bare-return - - name: blank-imports - - name: bool-literal-in-expr - - name: call-to-gc - - name: comment-spacings - - name: confusing-naming - - name: confusing-results - - name: constant-logical-expr - - name: context-as-argument - - name: context-keys-type - - name: datarace - - name: deep-exit - - name: defer - - name: dot-imports - - name: duplicated-imports - - name: early-return - - name: empty-block - - name: empty-lines - - name: enforce-map-style - arguments: ["make"] - exclude: [ "TEST" ] - - name: enforce-repeated-arg-type-style - arguments: ["short"] - - name: enforce-slice-style - arguments: ["make"] - - name: error-naming - - name: error-return - - name: error-strings - - name: errorf - - name: function-result-limit - arguments: [ 3 ] - - name: get-return - - name: identical-branches - - name: if-return - - name: import-alias-naming - arguments: - - "^[a-z][a-z0-9_]*[a-z0-9]+$" - - name: import-shadowing - - name: increment-decrement - - name: indent-error-flow - - name: max-public-structs - exclude: [ "TEST" ] - arguments: [ 5 ] - - name: modifies-parameter - - name: modifies-value-receiver - - name: optimize-operands-order - - name: package-comments - - name: range - - name: range-val-address - - name: range-val-in-closure - - name: receiver-naming - - name: redefines-builtin-id - - name: redundant-import-alias - - name: string-format - arguments: - - - 'fmt.Errorf[0],errors.New[0]' - - '/^([^A-Z]|$)/' - - 'Error string must not start with a capital letter.' - - - 'fmt.Errorf[0],errors.New[0]' - - '/(^|[^\.!?])$/' - - 'Error string must not end in punctuation.' - - - 'panic' - - '/^[^\n]*$/' - - 'Must not contain line breaks.' - - name: string-of-int - - name: struct-tag - - name: superfluous-else - - name: time-equal - - name: time-naming - - name: unconditional-recursion - - name: unexported-naming - - name: unnecessary-stmt - - name: unreachable-code - - name: unused-parameter - - name: unused-receiver - - name: var-declaration - - name: var-naming - - name: waitgroup-by-value - testifylint: - # Disable all checkers (https://github.com/Antonboom/testifylint#checkers). - # Default: false - disable-all: true - # Enable checkers by name - enable: - - blank-import - - bool-compare - - compares - - contains - - empty - - encoded-compare - - error-is-as - - error-nil - - expected-actual - - float-compare - - formatter - - go-require - - len - - negative-positive - - nil-compare - - regexp - - require-error - - suite-broken-parallel - - suite-dont-use-pkg - - suite-extra-assert-call - - suite-subtest-run - - suite-thelper - - useless-assert - usetesting: - # Enable/disable `os.TempDir()` detections. - # Default: false - os-temp-dir: true + # errcheck + - path: cmd/telegraf/(main|printer|cmd_plugins).go + text: "Error return value of `outputBuffer.Write` is not checked" + + - path: plugins/inputs/win_perf_counters/pdh.go + linters: + - errcheck + + # gosec:G101 + - path: _test\.go + text: "Potential hardcoded credentials" + + # gosec:G404 + - path: _test\.go + text: "Use of weak random number generator" + + # revive:max-public-structs + - path-except: ^plugins/(aggregators|inputs|outputs|parsers|processors|serializers)/... + text: "max-public-structs: you have exceeded the maximum number" + + # revive:var-naming + - path: (.+)\.go$ + text: don't use an underscore in package name + + # EXC0001 errcheck: Almost all programs ignore errors on these functions, and in most cases it's ok + - path: (.+)\.go$ + text: Error return value of .((os\.)?std(out|err)\..*|.*Close.*|.*close.*|.*Flush|.*Disconnect|.*disconnect|.*Clear|os\.Remove(All)?|.*print(f|ln)?|os\.Setenv|os\.Unsetenv). is not checked + + # EXC0013 revive: Annoying issue about not having a comment. The rare codebase has such comments + - path: (.+)\.go$ + text: package comment should be of the form "(.+)... + + # EXC0015 revive: Annoying issue about not having a comment. The rare codebase has such comments + - path: (.+)\.go$ + text: should have a package comment + + # Which file paths to exclude: they will be analyzed, but issues from them won't be reported. + # "/" will be replaced by the current OS file path separator to properly work on Windows. + # Default: [] + paths: + - plugins/parsers/influx/machine.go* + +formatters: + # Enable specific formatter. + # Default: [] (uses standard Go formatting) + enable: + - gci + + # Formatters settings. + settings: + gci: + # Section configuration to compare against. + # Section names are case-insensitive and may contain parameters in (). + # The default order of sections is `standard > default > custom > blank > dot > alias > localmodule`, + # If `custom-order` is `true`, it follows the order of `sections` option. + # Default: ["standard", "default"] + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - localmodule # Local module section: contains all local packages. This section is not present unless explicitly enabled. + + exclusions: + # Mode of the generated files analysis. + # + # - `strict`: sources are excluded by strictly following the Go generated file convention. + # Source files that have lines matching only the following regular expression will be excluded: `^// Code generated .* DO NOT EDIT\.$` + # This line must appear before the first non-comment, non-blank text in the file. + # https://go.dev/s/generatedcode + # - `lax`: sources are excluded if they contain lines like `autogenerated file`, `code generated`, `do not edit`, etc. + # - `disable`: disable the generated files exclusion. + # + # Default: lax + generated: lax issues: - # List of regexps of issue texts to exclude. - # - # But independently of this option we use default exclude patterns, - # it can be disabled by `exclude-use-default: false`. - # To list all excluded by default patterns execute `golangci-lint run --help` - # - # Default: https://golangci-lint.run/usage/false-positives/#default-exclusions - exclude: - # revive:var-naming - - don't use an underscore in package name - # EXC0001 errcheck: Almost all programs ignore errors on these functions, and in most cases it's ok - - Error return value of .((os\.)?std(out|err)\..*|.*Close.*|.*Flush|.*Disconnect|.*Clear|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv). is not checked - # EXC0013 revive: Annoying issue about not having a comment. The rare codebase has such comments - - package comment should be of the form "(.+)... - # EXC0015 revive: Annoying issue about not having a comment. The rare codebase has such comments - - should have a package comment - - # Excluding configuration per-path, per-linter, per-text and per-source - exclude-rules: - - path: plugins/parsers/influx - linters: - - govet - - - path: cmd/telegraf/(main|printer|cmd_plugins).go - text: "Error return value of `outputBuffer.Write` is not checked" #errcheck - - - path: plugins/inputs/win_perf_counters/pdh.go - linters: - - errcheck - - - path: _test\.go - text: "Potential hardcoded credentials" #gosec:G101 - - - path: _test\.go - text: "Use of weak random number generator" #gosec:G404 - - - path-except: ^plugins/(aggregators|inputs|outputs|parsers|processors|serializers)/... - text: "max-public-structs: you have exceeded the maximum number" #revive:max-public-structs - - # Independently of option `exclude` we use default exclude patterns, - # it can be disabled by this option. - # To list all excluded by default patterns execute `golangci-lint run --help`. - # Default: true - exclude-use-default: false - - # Which dirs to exclude: issues from them won't be reported. - # Can use regexp here: `generated.*`, regexp is applied on full path, - # including the path prefix if one is set. - # Default dirs are skipped independently of this option's value (see exclude-dirs-use-default). - # "/" will be replaced by current OS file path separator to properly work on Windows. - # Default: [] - exclude-dirs: - - assets - - docs - - etc - - # Which files to exclude: they will be analyzed, but issues from them won't be reported. - # There is no need to include all autogenerated files, - # we confidently recognize autogenerated files. - # If it's not, please let us know. - # "/" will be replaced by current OS file path separator to properly work on Windows. - # Default: [] - exclude-files: - - plugins/parsers/influx/machine.go* - # Maximum issues count per one linter. # Set to 0 to disable. # Default: 50 @@ -443,49 +564,48 @@ issues: # Default: true uniq-by-line: false -# output configuration options +# Output configuration options. output: # The formats used to render issues. - # Formats: - # - `colored-line-number` - # - `line-number` - # - `json` - # - `colored-tab` - # - `tab` - # - `html` - # - `checkstyle` - # - `code-climate` - # - `junit-xml` - # - `junit-xml-extended` - # - `github-actions` - # - `teamcity` - # - `sarif` - # Output path can be either `stdout`, `stderr` or path to the file to write to. - # - # For the CLI flag (`--out-format`), multiple formats can be specified by separating them by comma. - # The output can be specified for each of them by separating format name and path by colon symbol. - # Example: "--out-format=checkstyle:report.xml,json:stdout,colored-line-number" - # The CLI flag (`--out-format`) override the configuration file. - # - # Default: - # formats: - # - format: colored-line-number - # path: stdout formats: - - format: tab + # Prints issues in columns representation separated by tabulations. + tab: + # Output path can be either `stdout`, `stderr` or path to the file to write to. + # Default: stdout path: stdout - # Sort results by the order defined in `sort-order`. - # Default: false - sort-results: true + # Order to use when sorting results. + # Possible values: `file`, `linter`, and `severity`. + # + # If the severity values are inside the following list, they are ordered in this order: + # 1. error + # 2. warning + # 3. high + # 4. medium + # 5. low + # Either they are sorted alphabetically. + # + # Default: ["linter", "file"] + sort-order: + - file # filepath, line, and column. + - linter # Show statistics per linter. - # Default: false + # Default: true show-stats: true -# Options for analysis running. -run: - # Timeout for analysis, e.g. 30s, 5m. - # If the value is lower or equal to 0, the timeout is disabled. - # Default: 1m - timeout: 10m +severity: + # Set the default severity for issues. + # + # If severity rules are defined and the issues do not match or no severity is provided to the rule + # this will be the default severity applied. + # Severities should match the supported severity names of the selected out format. + # - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity + # - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#SeverityLevel + # - GitHub: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message + # - TeamCity: https://www.jetbrains.com/help/teamcity/service-messages.html#Inspection+Instance + # + # `@linter` can be used as severity value to keep the severity from linters (e.g. revive, gosec, ...) + # + # Default: "" + default: error diff --git a/Makefile b/Makefile index 7f134c898..f9b3068c6 100644 --- a/Makefile +++ b/Makefile @@ -180,7 +180,7 @@ vet: .PHONY: lint-install lint-install: @echo "Installing golangci-lint" - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.5 + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.0.2 @echo "Installing markdownlint" npm install -g markdownlint-cli diff --git a/config/config_test.go b/config/config_test.go index 71d6de016..830ad9d7c 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -903,7 +903,7 @@ func TestConfig_MultipleProcessorsOrder(t *testing.T) { } require.NoError(t, c.LoadAll(filenames...)) - require.Equal(t, len(test.expectedOrder), len(c.Processors)) + require.Len(t, c.Processors, len(test.expectedOrder)) var order []string for _, p := range c.Processors { diff --git a/internal/internal_test.go b/internal/internal_test.go index 9834f66ea..f0cfdcfe3 100644 --- a/internal/internal_test.go +++ b/internal/internal_test.go @@ -85,7 +85,7 @@ func TestRunTimeoutFastExit(t *testing.T) { // Verify "process already finished" log doesn't occur. time.Sleep(time.Millisecond * 75) - require.Equal(t, "", buf.String()) + require.Empty(t, buf.String()) } func TestCombinedOutputTimeout(t *testing.T) { diff --git a/internal/templating/engine_test.go b/internal/templating/engine_test.go index 726a2d560..7776d42b3 100644 --- a/internal/templating/engine_test.go +++ b/internal/templating/engine_test.go @@ -19,7 +19,7 @@ func TestEngineAlternateSeparator(t *testing.T) { require.Equal(t, map[string]string{ "origin": "host01", }, tags) - require.Equal(t, "", field) + require.Empty(t, field) } func TestEngineWithWildcardTemplate(t *testing.T) { diff --git a/migrations/global_agent/migration_test.go b/migrations/global_agent/migration_test.go index 599c8c6c5..b456b0ce8 100644 --- a/migrations/global_agent/migration_test.go +++ b/migrations/global_agent/migration_test.go @@ -88,6 +88,7 @@ func TestCases(t *testing.T) { output, n, err := config.ApplyMigrations(input) require.NoError(t, err) require.NotEmpty(t, output) + //nolint:testifylint // "useless-assert: meaningless assertion" - false positive require.Positive(t, n, "expected migration application but none applied") actual := config.NewConfig() require.NoError(t, actual.LoadConfigData(output, config.EmptySourcePath)) diff --git a/plugins/aggregators/histogram/histogram_test.go b/plugins/aggregators/histogram/histogram_test.go index a9dcfa8da..cbf1658ad 100644 --- a/plugins/aggregators/histogram/histogram_test.go +++ b/plugins/aggregators/histogram/histogram_test.go @@ -525,5 +525,5 @@ func assertContainsTaggedField(t *testing.T, acc *testutil.Accumulator, metricNa return } - require.Fail(t, fmt.Sprintf("unknown measurement %q with tags: %v, fields: %v", metricName, tags, fields)) + require.Failf(t, "Unknown measurement", "Unknown measurement %q with tags: %v, fields: %v", metricName, tags, fields) } diff --git a/plugins/common/jolokia2/gatherer_test.go b/plugins/common/jolokia2/gatherer_test.go index 10e12cdc9..bdff8263b 100644 --- a/plugins/common/jolokia2/gatherer_test.go +++ b/plugins/common/jolokia2/gatherer_test.go @@ -96,7 +96,7 @@ func TestJolokia2_makeReadRequests(t *testing.T) { for _, c := range cases { payload := makeReadRequests([]Metric{c.metric}) - require.Equal(t, len(c.expected), len(payload), "Failing case: "+c.metric.Name) + require.Len(t, payload, len(c.expected), "Failing case: "+c.metric.Name) for _, actual := range payload { require.Contains(t, c.expected, actual, "Failing case: "+c.metric.Name) } diff --git a/plugins/common/shim/goshim.go b/plugins/common/shim/goshim.go index 5b271340d..8fdeb2f43 100644 --- a/plugins/common/shim/goshim.go +++ b/plugins/common/shim/goshim.go @@ -107,7 +107,7 @@ func (s *Shim) writeProcessedMetrics() error { if err := serializer.Init(); err != nil { return fmt.Errorf("creating serializer failed: %w", err) } - for { //nolint:gosimple // for-select used on purpose + for { //nolint:staticcheck // for-select used on purpose select { case m, open := <-s.metricCh: if !open { diff --git a/plugins/inputs/amd_rocm_smi/amd_rocm_smi_test.go b/plugins/inputs/amd_rocm_smi/amd_rocm_smi_test.go index 8e7b15deb..9a06e0891 100644 --- a/plugins/inputs/amd_rocm_smi/amd_rocm_smi_test.go +++ b/plugins/inputs/amd_rocm_smi/amd_rocm_smi_test.go @@ -1,7 +1,6 @@ package amd_rocm_smi import ( - "errors" "os" "path/filepath" "testing" @@ -29,7 +28,7 @@ func TestErrorBehaviorDefault(t *testing.T) { var acc testutil.Accumulator var ferr *internal.FatalError - require.False(t, errors.As(model.Start(&acc), &ferr)) + require.NotErrorAs(t, model.Start(&acc), &ferr) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected) } @@ -48,7 +47,7 @@ func TestErrorBehaviorError(t *testing.T) { var acc testutil.Accumulator var ferr *internal.FatalError - require.False(t, errors.As(model.Start(&acc), &ferr)) + require.NotErrorAs(t, model.Start(&acc), &ferr) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected) } @@ -67,7 +66,7 @@ func TestErrorBehaviorRetry(t *testing.T) { var acc testutil.Accumulator var ferr *internal.FatalError - require.False(t, errors.As(model.Start(&acc), &ferr)) + require.NotErrorAs(t, model.Start(&acc), &ferr) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected) } diff --git a/plugins/inputs/clickhouse/clickhouse_test.go b/plugins/inputs/clickhouse/clickhouse_test.go index c68225c75..2e635548a 100644 --- a/plugins/inputs/clickhouse/clickhouse_test.go +++ b/plugins/inputs/clickhouse/clickhouse_test.go @@ -15,7 +15,7 @@ import ( func TestClusterIncludeExcludeFilter(t *testing.T) { ch := ClickHouse{} - require.Equal(t, "", ch.clusterIncludeExcludeFilter()) + require.Empty(t, ch.clusterIncludeExcludeFilter()) ch.ClusterExclude = []string{"test_cluster"} require.Equal(t, "WHERE cluster NOT IN ('test_cluster')", ch.clusterIncludeExcludeFilter()) diff --git a/plugins/inputs/cpu/cpu_test.go b/plugins/inputs/cpu/cpu_test.go index 030c97a51..a21e06621 100644 --- a/plugins/inputs/cpu/cpu_test.go +++ b/plugins/inputs/cpu/cpu_test.go @@ -1,7 +1,6 @@ package cpu import ( - "fmt" "testing" "github.com/shirou/gopsutil/v4/cpu" @@ -139,16 +138,14 @@ func assertContainsTaggedFloat( return } } else { - require.Fail(t, fmt.Sprintf("Measurement %q does not have type float64", measurement)) + require.Failf(t, "Wrong type", "Measurement %q does not have type float64", measurement) } } } } } - msg := fmt.Sprintf( - "Could not find measurement %q with requested tags within %f of %f, Actual: %f", - measurement, delta, expectedValue, actualValue) - require.Fail(t, msg) + require.Failf(t, "Measurement not found", + "Could not find measurement %q with requested tags within %f of %f, Actual: %f", measurement, delta, expectedValue, actualValue) } // TestCPUCountChange tests that no errors are encountered if the number of diff --git a/plugins/inputs/dpdk/dpdk_connector_test.go b/plugins/inputs/dpdk/dpdk_connector_test.go index 3bc570cea..7f7308e47 100644 --- a/plugins/inputs/dpdk/dpdk_connector_test.go +++ b/plugins/inputs/dpdk/dpdk_connector_test.go @@ -117,7 +117,7 @@ func Test_getCommandResponse(t *testing.T) { buf, err := connector.getCommandResponse(command) require.NoError(t, err) - require.Equal(t, len(response), len(buf)) + require.Len(t, buf, len(response)) require.Equal(t, response, string(buf)) } }) diff --git a/plugins/inputs/dpdk/dpdk_test.go b/plugins/inputs/dpdk/dpdk_test.go index 499335337..dedecbd7b 100644 --- a/plugins/inputs/dpdk/dpdk_test.go +++ b/plugins/inputs/dpdk/dpdk_test.go @@ -31,7 +31,7 @@ func Test_Init(t *testing.T) { SocketPath: "", } - require.Equal(t, "", dpdk.SocketPath) + require.Empty(t, dpdk.SocketPath) require.NoError(t, dpdk.Init()) diff --git a/plugins/inputs/dpdk/dpdk_utils_test.go b/plugins/inputs/dpdk/dpdk_utils_test.go index 4ac43ef0f..1be3dac12 100644 --- a/plugins/inputs/dpdk/dpdk_utils_test.go +++ b/plugins/inputs/dpdk/dpdk_utils_test.go @@ -85,7 +85,7 @@ func Test_getParams(t *testing.T) { t.Run("when passed command with no params then empty string (representing empty params) should be returned", func(t *testing.T) { commandParams := getParams(commandWithParams(command, "")) - require.Equal(t, "", commandParams) + require.Empty(t, commandParams) }) } diff --git a/plugins/inputs/execd/execd_test.go b/plugins/inputs/execd/execd_test.go index c4c902f7b..08a4a93ee 100644 --- a/plugins/inputs/execd/execd_test.go +++ b/plugins/inputs/execd/execd_test.go @@ -355,7 +355,7 @@ func readChanWithTimeout(t *testing.T, metrics chan telegraf.Metric, timeout tim case m := <-metrics: return m case <-to.C: - require.FailNow(t, "timeout waiting for metric") + require.Fail(t, "Timeout waiting for metric") } return nil } diff --git a/plugins/inputs/intel_baseband/utils_test.go b/plugins/inputs/intel_baseband/utils_test.go index c22719b75..1539da88d 100644 --- a/plugins/inputs/intel_baseband/utils_test.go +++ b/plugins/inputs/intel_baseband/utils_test.go @@ -59,7 +59,7 @@ func TestValidatePath(t *testing.T) { for _, tc := range testCases { returnPath, err := validatePath(tc.path, tc.ft) - require.Equal(t, "", returnPath) + require.Empty(t, returnPath) require.ErrorContains(t, err, tc.expectedErrorContains) } }) @@ -77,7 +77,7 @@ func TestValidatePath(t *testing.T) { for _, tc := range testCases { returnPath, err := validatePath(tc.path, tc.ft) - require.Equal(t, "", returnPath) + require.Empty(t, returnPath) require.ErrorContains(t, err, tc.expectedErrorContains) } }) @@ -93,7 +93,7 @@ func TestValidatePath(t *testing.T) { for _, tc := range testCases { returnPath, err := validatePath(tc.path, tc.ft) - require.Equal(t, "", returnPath) + require.Empty(t, returnPath) require.ErrorContains(t, err, tc.expectedErrorContains) } }) diff --git a/plugins/inputs/intel_dlb/intel_dlb_test.go b/plugins/inputs/intel_dlb/intel_dlb_test.go index dcc42677f..e4b0f9fd0 100644 --- a/plugins/inputs/intel_dlb/intel_dlb_test.go +++ b/plugins/inputs/intel_dlb/intel_dlb_test.go @@ -26,7 +26,7 @@ func TestDLB_Init(t *testing.T) { SocketPath: "", Log: testutil.Logger{}, } - require.Equal(t, "", dlb.SocketPath) + require.Empty(t, dlb.SocketPath) //nolint:errcheck // we are just testing that socket path gets set to default, not that default is valid dlb.Init() diff --git a/plugins/inputs/intel_powerstat/intel_powerstat_test.go b/plugins/inputs/intel_powerstat/intel_powerstat_test.go index d6dc94a90..3f90253cb 100644 --- a/plugins/inputs/intel_powerstat/intel_powerstat_test.go +++ b/plugins/inputs/intel_powerstat/intel_powerstat_test.go @@ -689,7 +689,7 @@ func (m *mockOptGenerator) generate(cfg optConfig) []ptel.Option { func TestSampleConfig(t *testing.T) { p := &PowerStat{} - require.NotZero(t, p.SampleConfig()) + require.NotEmpty(t, p.SampleConfig()) } func TestInit(t *testing.T) { diff --git a/plugins/inputs/intel_rdt/intel_rdt_test.go b/plugins/inputs/intel_rdt/intel_rdt_test.go index 7f4dc0091..dbb7a7591 100644 --- a/plugins/inputs/intel_rdt/intel_rdt_test.go +++ b/plugins/inputs/intel_rdt/intel_rdt_test.go @@ -61,7 +61,7 @@ func TestSplitCSVLineIntoValues(t *testing.T) { wrongLine := "2020-08-12 13:34:36,37,44,0.00,0,0.0" splitCSV, err = splitCSVLineIntoValues(wrongLine) require.Error(t, err) - require.Equal(t, "", splitCSV.timeValue) + require.Empty(t, splitCSV.timeValue) require.Nil(t, splitCSV.metricsValues) require.Nil(t, splitCSV.coreOrPIDsValues) } @@ -76,7 +76,7 @@ func TestFindPIDsInMeasurement(t *testing.T) { line = "pids not included" result, err = findPIDsInMeasurement(line) require.Error(t, err) - require.Equal(t, "", result) + require.Empty(t, result) } func TestCreateArgsProcesses(t *testing.T) { diff --git a/plugins/inputs/intel_rdt/publisher_test.go b/plugins/inputs/intel_rdt/publisher_test.go index 84f2e09bf..7fb0d5501 100644 --- a/plugins/inputs/intel_rdt/publisher_test.go +++ b/plugins/inputs/intel_rdt/publisher_test.go @@ -57,7 +57,7 @@ func TestParseCoresMeasurement(t *testing.T) { result, err := parseCoresMeasurement(measurement) require.Error(t, err) - require.Equal(t, "", result.cores) + require.Empty(t, result.cores) require.Nil(t, result.values) require.Equal(t, time.Time{}, result.time) }) @@ -75,7 +75,7 @@ func TestParseCoresMeasurement(t *testing.T) { result, err := parseCoresMeasurement(measurement) require.Error(t, err) - require.Equal(t, "", result.cores) + require.Empty(t, result.cores) require.Nil(t, result.values) require.Equal(t, time.Time{}, result.time) }) @@ -94,7 +94,7 @@ func TestParseCoresMeasurement(t *testing.T) { result, err := parseCoresMeasurement(measurement) require.Error(t, err) - require.Equal(t, "", result.cores) + require.Empty(t, result.cores) require.Nil(t, result.values) require.Equal(t, time.Time{}, result.time) }) @@ -187,8 +187,8 @@ func TestParseProcessesMeasurement(t *testing.T) { result, err := parseProcessesMeasurement(newMeasurement) require.Error(t, err) - require.Equal(t, "", result.process) - require.Equal(t, "", result.cores) + require.Empty(t, result.process) + require.Empty(t, result.cores) require.Nil(t, result.values) require.Equal(t, time.Time{}, result.time) }) diff --git a/plugins/inputs/internal/internal_test.go b/plugins/inputs/internal/internal_test.go index 0d5cbf8e2..2fe20b3cf 100644 --- a/plugins/inputs/internal/internal_test.go +++ b/plugins/inputs/internal/internal_test.go @@ -107,7 +107,7 @@ func TestGostats(t *testing.T) { switch value.(type) { case int64, uint64, float64: default: - require.Truef(t, false, "field %s is of non-numeric type %T\n", name, value) + require.Failf(t, "Wrong type of field", "Field %s is of non-numeric type %T", name, value) } } } diff --git a/plugins/inputs/lanz/lanz.go b/plugins/inputs/lanz/lanz.go index a9589bb70..6631e5a9f 100644 --- a/plugins/inputs/lanz/lanz.go +++ b/plugins/inputs/lanz/lanz.go @@ -70,7 +70,7 @@ func (l *Lanz) Stop() { } func receive(acc telegraf.Accumulator, in <-chan *pb.LanzRecord, deviceURL *url.URL) { - //nolint:gosimple // for-select used on purpose + //nolint:staticcheck // for-select used on purpose for { select { case msg, ok := <-in: diff --git a/plugins/inputs/mesos/mesos_test.go b/plugins/inputs/mesos/mesos_test.go index 2a0981441..7b9cfff3c 100644 --- a/plugins/inputs/mesos/mesos_test.go +++ b/plugins/inputs/mesos/mesos_test.go @@ -364,7 +364,7 @@ func TestMasterFilter(t *testing.T) { // getMetrics(). We have to find them by checking name prefixes. for k := range masterMetrics { if strings.HasPrefix(k, "master/frameworks/") || strings.HasPrefix(k, "frameworks/") { - require.Failf(t, "Found key %s, it should be gone.", k) + require.Failf(t, "Wrong key", "Found key %s, it should be gone.", k) } } } diff --git a/plugins/inputs/mock/mock_test.go b/plugins/inputs/mock/mock_test.go index 7878ccb6f..f9fb7704c 100644 --- a/plugins/inputs/mock/mock_test.go +++ b/plugins/inputs/mock/mock_test.go @@ -92,7 +92,7 @@ func TestGather(t *testing.T) { case "step": require.InDelta(t, 0.0, v, testutil.DefaultDelta) default: - require.Failf(t, "unexpected field %q", k) + require.Failf(t, "Unexpected field", "Extra field: %q", k) } } } diff --git a/plugins/inputs/modbus/modbus_test.go b/plugins/inputs/modbus/modbus_test.go index 4b2d76269..e18256bea 100644 --- a/plugins/inputs/modbus/modbus_test.go +++ b/plugins/inputs/modbus/modbus_test.go @@ -470,13 +470,13 @@ func generateExpectation(defs []requestExpectation) []request { } func requireEqualRequests(t *testing.T, expected, actual []request) { - require.Equal(t, len(expected), len(actual), "request size mismatch") + require.Len(t, actual, len(expected), "request size mismatch") for i, e := range expected { a := actual[i] require.Equalf(t, e.address, a.address, "address mismatch in request %d", i) require.Equalf(t, e.length, a.length, "length mismatch in request %d", i) - require.Equalf(t, len(e.fields), len(a.fields), "no. fields mismatch in request %d", i) + require.Lenf(t, a.fields, len(e.fields), "no. fields mismatch in request %d", i) for j, ef := range e.fields { af := a.fields[j] require.Equalf(t, ef.address, af.address, "address mismatch in field %d of request %d", j, i) diff --git a/plugins/inputs/nsq_consumer/nsq_consumer_test.go b/plugins/inputs/nsq_consumer/nsq_consumer_test.go index 3355d1bb2..433fb54d8 100644 --- a/plugins/inputs/nsq_consumer/nsq_consumer_test.go +++ b/plugins/inputs/nsq_consumer/nsq_consumer_test.go @@ -80,7 +80,7 @@ func waitForPoint(acc *testutil.Accumulator, t *testing.T) { defer ticker.Stop() counter := 0 - //nolint:gosimple // for-select used on purpose + //nolint:staticcheck // for-select used on purpose for { select { case <-ticker.C: diff --git a/plugins/inputs/nvidia_smi/nvidia_smi_test.go b/plugins/inputs/nvidia_smi/nvidia_smi_test.go index 1260bc347..1420ad961 100644 --- a/plugins/inputs/nvidia_smi/nvidia_smi_test.go +++ b/plugins/inputs/nvidia_smi/nvidia_smi_test.go @@ -1,7 +1,6 @@ package nvidia_smi import ( - "errors" "os" "path/filepath" "runtime" @@ -79,7 +78,7 @@ func TestErrorBehaviorDefault(t *testing.T) { var acc testutil.Accumulator var ferr *internal.FatalError - require.False(t, errors.As(model.Start(&acc), &ferr)) + require.NotErrorAs(t, model.Start(&acc), &ferr) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected) } @@ -98,7 +97,7 @@ func TestErrorBehaviorError(t *testing.T) { var acc testutil.Accumulator var ferr *internal.FatalError - require.False(t, errors.As(model.Start(&acc), &ferr)) + require.NotErrorAs(t, model.Start(&acc), &ferr) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected) } @@ -117,7 +116,7 @@ func TestErrorBehaviorRetry(t *testing.T) { var acc testutil.Accumulator var ferr *internal.FatalError - require.False(t, errors.As(model.Start(&acc), &ferr)) + require.NotErrorAs(t, model.Start(&acc), &ferr) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected) } diff --git a/plugins/inputs/prometheus/kubernetes_test.go b/plugins/inputs/prometheus/kubernetes_test.go index 5e2e2e3ca..efa5ae05b 100644 --- a/plugins/inputs/prometheus/kubernetes_test.go +++ b/plugins/inputs/prometheus/kubernetes_test.go @@ -210,7 +210,7 @@ func TestChangeNamespaceLabelName(t *testing.T) { require.NoError(t, err) tags := prom.kubernetesPods[podID(id)].tags require.Equal(t, "default", tags["pod_namespace"]) - require.Equal(t, "", tags["namespace"]) + require.Empty(t, tags["namespace"]) } func TestPodHasMatchingNamespace(t *testing.T) { diff --git a/plugins/inputs/stackdriver/stackdriver_test.go b/plugins/inputs/stackdriver/stackdriver_test.go index be1442035..4d8457db5 100644 --- a/plugins/inputs/stackdriver/stackdriver_test.go +++ b/plugins/inputs/stackdriver/stackdriver_test.go @@ -1208,7 +1208,7 @@ func TestListMetricDescriptorFilter(t *testing.T) { err := s.Gather(&acc) require.NoError(t, err) - require.Equal(t, len(client.calls), len(tt.calls)) + require.Len(t, client.calls, len(tt.calls)) for i, expected := range tt.calls { actual := client.calls[i] require.Equal(t, expected.name, actual.name) diff --git a/plugins/inputs/statsd/statsd_test.go b/plugins/inputs/statsd/statsd_test.go index 879a0fa96..b73732a93 100644 --- a/plugins/inputs/statsd/statsd_test.go +++ b/plugins/inputs/statsd/statsd_test.go @@ -1963,7 +1963,7 @@ func TestParseKeyValue(t *testing.T) { require.Equalf(t, "bar", v, "Expected %s, got %s", "bar", v) k2, v2 := parseKeyValue("baz") - require.Equalf(t, "", k2, "Expected %s, got %s", "", k2) + require.Emptyf(t, k2, "Expected %s, got %s", "", k2) require.Equalf(t, "baz", v2, "Expected %s, got %s", "baz", v2) } diff --git a/plugins/inputs/varnish/varnish_test.go b/plugins/inputs/varnish/varnish_test.go index e239d67a2..5c3414edb 100644 --- a/plugins/inputs/varnish/varnish_test.go +++ b/plugins/inputs/varnish/varnish_test.go @@ -610,7 +610,7 @@ func TestJsonTypes(t *testing.T) { MetricVersion: 2, } require.NoError(t, v.Gather(acc)) - require.Equal(t, len(exp), len(acc.Metrics)) + require.Len(t, acc.Metrics, len(exp)) for _, metric := range acc.Metrics { require.Equal(t, "varnish", metric.Measurement) for fieldName, value := range metric.Fields { diff --git a/plugins/inputs/win_perf_counters/win_perf_counters_integration_test.go b/plugins/inputs/win_perf_counters/win_perf_counters_integration_test.go index 2b6889424..59bcabd37 100644 --- a/plugins/inputs/win_perf_counters/win_perf_counters_integration_test.go +++ b/plugins/inputs/win_perf_counters/win_perf_counters_integration_test.go @@ -169,12 +169,7 @@ func TestWinPerfCountersConfigGet2Integration(t *testing.T) { hostCounters, ok := m.hostCounters["localhost"] require.True(t, ok) - - if len(hostCounters.counters) == 0 { - require.FailNow(t, "no results returned from the counterPath: %v", len(hostCounters.counters)) - } else if len(hostCounters.counters) > 1 { - require.FailNow(t, "too many results returned from the counterPath: %v", len(hostCounters.counters)) - } + require.Len(t, hostCounters.counters, 1, "There should be exactly one result returned from the counterPath") } func TestWinPerfCountersConfigGet3Integration(t *testing.T) { @@ -208,12 +203,7 @@ func TestWinPerfCountersConfigGet3Integration(t *testing.T) { hostCounters, ok := m.hostCounters["localhost"] require.True(t, ok) - - if len(hostCounters.counters) < 2 { - require.FailNow(t, "too few results returned from the counterPath: %v", len(hostCounters.counters)) - } else if len(hostCounters.counters) > 2 { - require.FailNow(t, "too many results returned from the counterPath: %v", len(hostCounters.counters)) - } + require.Len(t, hostCounters.counters, 2, "There should be exactly two results returned from the counterPath") } func TestWinPerfCountersConfigGet4Integration(t *testing.T) { @@ -245,12 +235,7 @@ func TestWinPerfCountersConfigGet4Integration(t *testing.T) { hostCounters, ok := m.hostCounters["localhost"] require.True(t, ok) - - if len(hostCounters.counters) < 2 { - require.FailNow(t, "too few results returned from the counterPath: %v", len(hostCounters.counters)) - } else if len(hostCounters.counters) > 2 { - require.FailNow(t, "too many results returned from the counterPath: %v", len(hostCounters.counters)) - } + require.Len(t, hostCounters.counters, 2, "There should be exactly two results returned from the counterPath") } func TestWinPerfCountersConfigGet5Integration(t *testing.T) { @@ -282,12 +267,7 @@ func TestWinPerfCountersConfigGet5Integration(t *testing.T) { hostCounters, ok := m.hostCounters["localhost"] require.True(t, ok) - - if len(hostCounters.counters) < 4 { - require.FailNow(t, "too few results returned from the counterPath: %v", len(hostCounters.counters)) - } else if len(hostCounters.counters) > 4 { - require.FailNow(t, "too many results returned from the counterPath: %v", len(hostCounters.counters)) - } + require.Len(t, hostCounters.counters, 4, "There should be exactly four results returned from the counterPath") } func TestWinPerfCountersConfigGet6Integration(t *testing.T) { @@ -347,12 +327,7 @@ func TestWinPerfCountersConfigGet7Integration(t *testing.T) { hostCounters, ok := m.hostCounters["localhost"] require.True(t, ok) - - if len(hostCounters.counters) < 2 { - require.FailNow(t, "too few results returned from the counterPath: %v", len(hostCounters.counters)) - } else if len(hostCounters.counters) > 2 { - require.FailNow(t, "too many results returned from the counterPath: %v", len(hostCounters.counters)) - } + require.Len(t, hostCounters.counters, 2, "There should be exactly two results returned from the counterPath") } func TestWinPerfCountersConfigError1Integration(t *testing.T) { diff --git a/plugins/outputs/amqp/amqp_test.go b/plugins/outputs/amqp/amqp_test.go index 0e0cc471b..a4011b320 100644 --- a/plugins/outputs/amqp/amqp_test.go +++ b/plugins/outputs/amqp/amqp_test.go @@ -64,7 +64,7 @@ func TestConnect(t *testing.T) { errFunc: func(t *testing.T, output *AMQP, err error) { cfg := output.config require.Equal(t, []string{DefaultURL}, cfg.brokers) - require.Equal(t, "", cfg.exchange) + require.Empty(t, cfg.exchange) require.Equal(t, "topic", cfg.exchangeType) require.False(t, cfg.exchangePassive) require.True(t, cfg.exchangeDurable) diff --git a/plugins/outputs/cloudwatch/cloudwatch_test.go b/plugins/outputs/cloudwatch/cloudwatch_test.go index a25bcdfcd..7df4968c2 100644 --- a/plugins/outputs/cloudwatch/cloudwatch_test.go +++ b/plugins/outputs/cloudwatch/cloudwatch_test.go @@ -32,7 +32,7 @@ func TestBuildDimensions(t *testing.T) { if len(testPoint.Tags()) >= maxDimensions { require.Len(t, dimensions, maxDimensions, "Number of dimensions should be less than MaxDimensions") } else { - require.Equal(t, len(testPoint.Tags()), len(dimensions), "Number of dimensions should be equal to number of tags") + require.Len(t, dimensions, len(testPoint.Tags()), "Number of dimensions should be equal to number of tags") } for i, key := range tagKeys { diff --git a/plugins/outputs/elasticsearch/elasticsearch_test.go b/plugins/outputs/elasticsearch/elasticsearch_test.go index dbb58d88f..865a73b26 100644 --- a/plugins/outputs/elasticsearch/elasticsearch_test.go +++ b/plugins/outputs/elasticsearch/elasticsearch_test.go @@ -588,7 +588,7 @@ func TestGetPipelineName(t *testing.T) { for _, test := range tests { pipelineName := e.getPipelineName(e.pipelineName, e.pipelineTagKeys, test.Tags) - require.Equal(t, "", pipelineName) + require.Empty(t, pipelineName) } } diff --git a/plugins/outputs/influxdb/http_test.go b/plugins/outputs/influxdb/http_test.go index c0b18101a..0a7ea68fa 100644 --- a/plugins/outputs/influxdb/http_test.go +++ b/plugins/outputs/influxdb/http_test.go @@ -816,7 +816,7 @@ func TestDBRPTags(t *testing.T) { }, handlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { require.Equal(t, "telegraf", r.FormValue("db")) - require.Equal(t, "", r.FormValue("rp")) + require.Empty(t, r.FormValue("rp")) w.WriteHeader(http.StatusNoContent) }, }, @@ -920,7 +920,7 @@ func TestDBRPTags(t *testing.T) { }, handlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { require.Equal(t, "telegraf", r.FormValue("db")) - require.Equal(t, "", r.FormValue("rp")) + require.Empty(t, r.FormValue("rp")) w.WriteHeader(http.StatusNoContent) }, }, diff --git a/plugins/outputs/kinesis/kinesis_test.go b/plugins/outputs/kinesis/kinesis_test.go index acc15d673..dd3f8f970 100644 --- a/plugins/outputs/kinesis/kinesis_test.go +++ b/plugins/outputs/kinesis/kinesis_test.go @@ -68,7 +68,7 @@ func TestPartitionKey(t *testing.T) { Method: "not supported", }, } - require.Equal(t, "", k.getPartitionKey(testPoint), "PartitionKey should be value of ''") + require.Empty(t, k.getPartitionKey(testPoint), "PartitionKey should be value of ''") k = KinesisOutput{ Log: testutil.Logger{}, @@ -520,11 +520,7 @@ func (m *mockKinesisPutRecords) AssertRequests( t *testing.T, expected []*kinesis.PutRecordsInput, ) { - require.Equalf(t, - len(expected), - len(m.requests), - "Expected %v requests", len(expected), - ) + require.Lenf(t, m.requests, len(expected), "Expected %v requests", len(expected)) for i, expectedInput := range expected { actualInput := m.requests[i] @@ -535,11 +531,7 @@ func (m *mockKinesisPutRecords) AssertRequests( "Expected request %v to have correct StreamName", i, ) - require.Equalf(t, - len(expectedInput.Records), - len(actualInput.Records), - "Expected request %v to have %v Records", i, len(expectedInput.Records), - ) + require.Lenf(t, actualInput.Records, len(expectedInput.Records), "Expected request %v to have %v Records", i, len(expectedInput.Records)) for r, expectedRecord := range expectedInput.Records { actualRecord := actualInput.Records[r] diff --git a/plugins/outputs/stackdriver/stackdriver_test.go b/plugins/outputs/stackdriver/stackdriver_test.go index 7bcf63351..37b4676a7 100644 --- a/plugins/outputs/stackdriver/stackdriver_test.go +++ b/plugins/outputs/stackdriver/stackdriver_test.go @@ -214,7 +214,7 @@ func TestWriteTagsAsResourceLabels(t *testing.T) { case "test_cpu_value/unknown": require.Equal(t, "cpu", ts.Resource.Labels["job_name"]) default: - require.False(t, true, "Unknown metric type") + require.Failf(t, "Wrong metric type", "Unknown metric type: %v", ts.Metric.Type) } } } @@ -290,7 +290,7 @@ func TestWriteMetricTypesOfficial(t *testing.T) { case "custom.googleapis.com/test_mem_h/histogram": require.Equal(t, metricpb.MetricDescriptor_CUMULATIVE, ts.MetricKind) default: - require.False(t, true, "Unknown metric type", ts.Metric.Type) + require.Failf(t, "Wrong metric type", "Unknown metric type: %v", ts.Metric.Type) } } } @@ -350,7 +350,7 @@ func TestWriteMetricTypesPath(t *testing.T) { case "custom.googleapis.com/test/mem_g/value": require.Equal(t, metricpb.MetricDescriptor_GAUGE, ts.MetricKind) default: - require.False(t, true, "Unknown metric type", ts.Metric.Type) + require.Failf(t, "Wrong metric type", "Unknown metric type: %v", ts.Metric.Type) } } } diff --git a/plugins/outputs/timestream/timestream_test.go b/plugins/outputs/timestream/timestream_test.go index 6ed9f61a2..5cbbea939 100644 --- a/plugins/outputs/timestream/timestream_test.go +++ b/plugins/outputs/timestream/timestream_test.go @@ -1265,7 +1265,7 @@ func comparison(t *testing.T, timestreamRecords []*timestreamwrite.WriteRecordsInput) { result := plugin.TransformMetrics(telegrafMetrics) - require.Equal(t, len(timestreamRecords), len(result), "The number of transformed records was expected to be different") + require.Len(t, result, len(timestreamRecords), "The number of transformed records was expected to be different") for _, tsRecord := range timestreamRecords { require.True(t, arrayContains(result, tsRecord), "Expected that the list of requests to Timestream: \n%s\n\n "+ "will contain request: \n%s\n\nUsed MappingMode: %s", result, tsRecord, mappingMode) diff --git a/plugins/outputs/wavefront/wavefront_test.go b/plugins/outputs/wavefront/wavefront_test.go index bca34fd4d..c9fb07803 100644 --- a/plugins/outputs/wavefront/wavefront_test.go +++ b/plugins/outputs/wavefront/wavefront_test.go @@ -400,7 +400,7 @@ func TestDefaults(t *testing.T) { defaultWavefront := outputs.Outputs["wavefront"]().(*Wavefront) require.Equal(t, 10000, defaultWavefront.HTTPMaximumBatchSize) require.Equal(t, config.Duration(10*time.Second), defaultWavefront.Timeout) - require.Equal(t, "", defaultWavefront.TLSCA) + require.Empty(t, defaultWavefront.TLSCA) } func TestMakeAuthOptions(t *testing.T) { diff --git a/plugins/outputs/zabbix/autoregister_test.go b/plugins/outputs/zabbix/autoregister_test.go index 8b55a427d..3042aaad0 100644 --- a/plugins/outputs/zabbix/autoregister_test.go +++ b/plugins/outputs/zabbix/autoregister_test.go @@ -68,8 +68,8 @@ func TestZabbixAutoregisterPush(t *testing.T) { zabbixSender.Reset() z.autoregisterPush() require.Len(t, z.autoregisterLastSend, 1) - require.Equal(t, "", zabbixSender.hostname) - require.Equal(t, "", zabbixSender.hostMetadata) + require.Empty(t, zabbixSender.hostname) + require.Empty(t, zabbixSender.hostMetadata) // Test that autoregister is sent if last send was more than autoregisterSendPeriod ago. z.Autoregister = "autoregister" diff --git a/plugins/parsers/collectd/parser_test.go b/plugins/parsers/collectd/parser_test.go index 24c1e269e..362cd10bf 100644 --- a/plugins/parsers/collectd/parser_test.go +++ b/plugins/parsers/collectd/parser_test.go @@ -313,7 +313,7 @@ func writeValueList(testContext context.Context, valueLists []api.ValueList) (*n } func assertEqualMetrics(t *testing.T, expected []metricData, received []telegraf.Metric) { - require.Equal(t, len(expected), len(received)) + require.Len(t, received, len(expected)) for i, m := range received { require.Equal(t, expected[i].name, m.Name()) require.Equal(t, expected[i].tags, m.Tags()) diff --git a/plugins/parsers/influx/influx_upstream/parser_test.go b/plugins/parsers/influx/influx_upstream/parser_test.go index 04ccc2b04..2bbb0aab1 100644 --- a/plugins/parsers/influx/influx_upstream/parser_test.go +++ b/plugins/parsers/influx/influx_upstream/parser_test.go @@ -621,7 +621,7 @@ func TestParser(t *testing.T) { require.Equal(t, tt.err.Error(), err.Error()) } - require.Equal(t, len(tt.metrics), len(metrics)) + require.Len(t, metrics, len(tt.metrics)) for i, expected := range tt.metrics { require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Tags(), metrics[i].Tags()) @@ -754,7 +754,7 @@ func TestSeriesParser(t *testing.T) { require.Equal(t, tt.err.Error(), err.Error()) } - require.Equal(t, len(tt.metrics), len(metrics)) + require.Len(t, metrics, len(tt.metrics)) for i, expected := range tt.metrics { require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Tags(), metrics[i].Tags()) @@ -964,7 +964,7 @@ func TestStreamParserErrorString(t *testing.T) { } } - require.Equal(t, len(tt.errs), len(errs)) + require.Len(t, errs, len(tt.errs)) for i, err := range errs { require.Equal(t, tt.errs[i], err.Error()) } diff --git a/plugins/parsers/influx/parser_test.go b/plugins/parsers/influx/parser_test.go index 34df61b57..17aef0975 100644 --- a/plugins/parsers/influx/parser_test.go +++ b/plugins/parsers/influx/parser_test.go @@ -591,7 +591,7 @@ func TestParser(t *testing.T) { metrics, err := parser.Parse(tt.input) require.Equal(t, tt.err, err) - require.Equal(t, len(tt.metrics), len(metrics)) + require.Len(t, metrics, len(tt.metrics)) for i, expected := range tt.metrics { require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Tags(), metrics[i].Tags()) @@ -830,7 +830,7 @@ func TestSeriesParser(t *testing.T) { require.Equal(t, tt.err.Error(), err.Error()) } - require.Equal(t, len(tt.metrics), len(metrics)) + require.Len(t, metrics, len(tt.metrics)) for i, expected := range tt.metrics { require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Tags(), metrics[i].Tags()) @@ -931,7 +931,7 @@ func TestStreamParserErrorString(t *testing.T) { } } - require.Equal(t, len(tt.errs), len(errs)) + require.Len(t, errs, len(tt.errs)) for i, err := range errs { require.Equal(t, tt.errs[i], err.Error()) } diff --git a/plugins/parsers/json_v2/parser_test.go b/plugins/parsers/json_v2/parser_test.go index 68f3c88c4..7544b1875 100644 --- a/plugins/parsers/json_v2/parser_test.go +++ b/plugins/parsers/json_v2/parser_test.go @@ -91,7 +91,7 @@ func TestMultipleConfigs(t *testing.T) { // The milliseconds weren't matching, seemed like a rounding difference between the influx parser // Compares each metrics times separately and ignores milliseconds if strings.HasPrefix(f.Name(), "timestamp") { - require.Equal(t, len(expected), len(actual)) + require.Len(t, actual, len(expected)) for i, m := range actual { require.Equal(t, expected[i].Time().Truncate(time.Second), m.Time().Truncate(time.Second)) } diff --git a/plugins/parsers/nagios/parser_test.go b/plugins/parsers/nagios/parser_test.go index 4aef29bce..d0c4e1b44 100644 --- a/plugins/parsers/nagios/parser_test.go +++ b/plugins/parsers/nagios/parser_test.go @@ -80,7 +80,7 @@ func (b *metricBuilder) b() telegraf.Metric { // assertEqual asserts two slices to be equal. Note, that the order // of the entries matters. func assertEqual(t *testing.T, exp, actual []telegraf.Metric) { - require.Equal(t, len(exp), len(actual)) + require.Len(t, actual, len(exp)) for i := 0; i < len(exp); i++ { ok := testutil.MetricEqual(exp[i], actual[i]) require.True(t, ok) diff --git a/plugins/serializers/graphite/graphite_test.go b/plugins/serializers/graphite/graphite_test.go index cb74a5648..1bc3107e4 100644 --- a/plugins/serializers/graphite/graphite_test.go +++ b/plugins/serializers/graphite/graphite_test.go @@ -366,7 +366,7 @@ func TestSerializeValueString(t *testing.T) { buf, err := s.Serialize(m) require.NoError(t, err) mS := strings.Split(strings.TrimSpace(string(buf)), "\n") - require.Equal(t, "", mS[0]) + require.Empty(t, mS[0]) } func TestSerializeValueStringWithTagSupport(t *testing.T) { @@ -390,7 +390,7 @@ func TestSerializeValueStringWithTagSupport(t *testing.T) { buf, err := s.Serialize(m) require.NoError(t, err) mS := strings.Split(strings.TrimSpace(string(buf)), "\n") - require.Equal(t, "", mS[0]) + require.Empty(t, mS[0]) } func TestSerializeValueBoolean(t *testing.T) { diff --git a/testutil/accumulator.go b/testutil/accumulator.go index a0ffad4b9..70e04b782 100644 --- a/testutil/accumulator.go +++ b/testutil/accumulator.go @@ -399,8 +399,8 @@ func (a *Accumulator) AssertContainsTaggedFields( t.Log("measurement", p.Measurement, "tags", p.Tags, "fields", p.Fields) } } - msg := fmt.Sprintf("unknown measurement %q with tags %v", measurement, tags) - require.Fail(t, msg) + + require.Failf(t, "Unknown measurement", "Unknown measurement %q with tags %v", measurement, tags) } func (a *Accumulator) AssertDoesNotContainsTaggedFields( @@ -417,10 +417,7 @@ func (a *Accumulator) AssertDoesNotContainsTaggedFields( } if p.Measurement == measurement && reflect.DeepEqual(fields, p.Fields) { - msg := fmt.Sprintf( - "found measurement %s with tagged fields (tags %v) which should not be there", - measurement, tags) - require.Fail(t, msg) + require.Failf(t, "Wrong measurement", "Found measurement %s with tagged fields (tags %v) which should not be there", measurement, tags) } } } @@ -437,8 +434,7 @@ func (a *Accumulator) AssertContainsFields( return } } - msg := fmt.Sprintf("unknown measurement %q", measurement) - require.Fail(t, msg) + require.Failf(t, "Unknown measurement", "Unknown measurement %q", measurement) } func (a *Accumulator) HasPoint( @@ -471,8 +467,7 @@ func (a *Accumulator) AssertDoesNotContainMeasurement(t *testing.T, measurement defer a.Unlock() for _, p := range a.Metrics { if p.Measurement == measurement { - msg := "found unexpected measurement " + measurement - require.Fail(t, msg) + require.Failf(t, "Unexpected measurement", "Found unexpected measurement %q", measurement) } } }