chore(deps): Bump golangci-lint from v1.64.5 to v2.0.2 (#16683)

This commit is contained in:
Paweł Żak 2025-03-31 14:52:09 +02:00 committed by GitHub
parent 9d20624068
commit 080e9a1338
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
50 changed files with 625 additions and 547 deletions

View File

@ -106,7 +106,7 @@ jobs:
- run: 'make check-deps' - run: 'make check-deps'
- run: - run:
name: "Install golangci-lint" 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: - run:
name: "golangci-lint/Linux" name: "golangci-lint/Linux"
# There are only 4 vCPUs available for this executor, so use only 4 instead of the default number # 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 - check-changed-files-or-halt
- run: - run:
name: "Install golangci-lint" 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: - run:
name: "golangci-lint/macOS" name: "golangci-lint/macOS"
# There are only 4 vCPUs available for this executor, so use only 4 instead of the default number # 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 - check-changed-files-or-halt
- run: - run:
name: "Install golangci-lint" 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: - run:
name: "golangci-lint/Windows" name: "golangci-lint/Windows"
# There are only 4 vCPUs available for this executor, so use only 4 instead of the default number # There are only 4 vCPUs available for this executor, so use only 4 instead of the default number

View File

@ -1,5 +1,13 @@
version: "2"
linters: 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: enable:
- asasalint - asasalint
- asciicheck - asciicheck
@ -11,12 +19,10 @@ linters:
- errcheck - errcheck
- errname - errname
- errorlint - errorlint
- gci
- gocheckcompilerdirectives - gocheckcompilerdirectives
- gocritic - gocritic
- goprintffuncname - goprintffuncname
- gosec - gosec
- gosimple
- govet - govet
- ineffassign - ineffassign
- interfacebloat - interfacebloat
@ -34,38 +40,57 @@ linters:
- staticcheck - staticcheck
- testifylint - testifylint
- tparallel - tparallel
- typecheck
- unconvert - unconvert
- unparam - unparam
- unused - unused
- usetesting - usetesting
linters-settings: settings:
depguard: 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: rules:
# Name of a rule. # Name of a rule.
main: main:
# Packages that are not allowed where the value is a suggestion. # 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: deny:
- pkg: log - pkg: log
desc: 'Use injected telegraf.Logger instead' 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: errcheck:
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`. # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`.
# Such cases aren't reported by default. # Such cases aren't reported by default.
@ -75,16 +100,10 @@ linters-settings:
# List of functions to exclude from checking, where each entry is a single function to exclude. # 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. # See https://github.com/kisielk/errcheck#excluding-functions for details.
exclude-functions: exclude-functions:
- "(*hash/maphash.Hash).Write" - '(*hash/maphash.Hash).Write'
- "(*hash/maphash.Hash).WriteByte" - '(*hash/maphash.Hash).WriteByte'
- "(*hash/maphash.Hash).WriteString" - '(*hash/maphash.Hash).WriteString'
- "(*github.com/influxdata/telegraf/plugins/outputs/postgresql/sqltemplate.Template).UnmarshalText" - '(*github.com/influxdata/telegraf/plugins/outputs/postgresql/sqltemplate.Template).UnmarshalText'
gci:
sections:
- standard
- default
- localmodule
gocritic: gocritic:
# Disable all checks. # Disable all checks.
@ -200,6 +219,7 @@ linters-settings:
- G602 # Slice access out of bounds - G602 # Slice access out of bounds
# G104, G105, G113, G204, G304, G307, G402, G504 were not enabled intentionally # 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) # TODO: review G115 when reporting false positives is fixed (https://github.com/securego/gosec/issues/1212)
# To specify the configuration of rules. # To specify the configuration of rules.
config: config:
# Maximum allowed permissions mode for os.OpenFile and os.Chmod # Maximum allowed permissions mode for os.OpenFile and os.Chmod
@ -208,21 +228,26 @@ linters-settings:
# Maximum allowed permissions mode for os.WriteFile and ioutil.WriteFile # Maximum allowed permissions mode for os.WriteFile and ioutil.WriteFile
# Default: "0600" # Default: "0600"
G306: "0640" G306: "0640"
govet: govet:
# Settings per analyzer.
settings: settings:
## Check the logging function like it would be a printf # Analyzer name, run `go tool vet help` to see all analyzers.
printf: printf:
# Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`). # Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`).
# Default: [] # Default: []
funcs: funcs:
- (github.com/influxdata/telegraf.Logger).Tracef
- (github.com/influxdata/telegraf.Logger).Debugf - (github.com/influxdata/telegraf.Logger).Debugf
- (github.com/influxdata/telegraf.Logger).Infof - (github.com/influxdata/telegraf.Logger).Infof
- (github.com/influxdata/telegraf.Logger).Warnf - (github.com/influxdata/telegraf.Logger).Warnf
- (github.com/influxdata/telegraf.Logger).Errorf - (github.com/influxdata/telegraf.Logger).Errorf
- (github.com/influxdata/telegraf.Logger).Trace
- (github.com/influxdata/telegraf.Logger).Debug - (github.com/influxdata/telegraf.Logger).Debug
- (github.com/influxdata/telegraf.Logger).Info - (github.com/influxdata/telegraf.Logger).Info
- (github.com/influxdata/telegraf.Logger).Warn - (github.com/influxdata/telegraf.Logger).Warn
- (github.com/influxdata/telegraf.Logger).Error - (github.com/influxdata/telegraf.Logger).Error
lll: lll:
# Max line length, lines longer will be reported. # 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. # '\t' is counted as 1 character by default, and can be changed with the tab-width option.
@ -231,10 +256,12 @@ linters-settings:
# Tab width in spaces. # Tab width in spaces.
# Default: 1 # Default: 1
tab-width: 4 tab-width: 4
nakedret: nakedret:
# Make an issue if func has more lines of code than this setting, and it has naked returns. # Make an issue if func has more lines of code than this setting, and it has naked returns.
# Default: 30 # Default: 30
max-func-lines: 1 max-func-lines: 1
nolintlint: nolintlint:
# Enable to require an explanation of nonzero length after each nolint directive. # Enable to require an explanation of nonzero length after each nolint directive.
# Default: false # Default: false
@ -242,11 +269,19 @@ linters-settings:
# Enable to require nolint directives to mention the specific linter being suppressed. # Enable to require nolint directives to mention the specific linter being suppressed.
# Default: false # Default: false
require-specific: true require-specific: true
prealloc: prealloc:
# Report pre-allocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. # Report pre-allocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# Default: true # Default: true
simple: false simple: false
revive: 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: rules:
- name: argument-limit - name: argument-limit
arguments: [ 6 ] arguments: [ 6 ]
@ -270,12 +305,15 @@ linters-settings:
- name: empty-block - name: empty-block
- name: empty-lines - name: empty-lines
- name: enforce-map-style - name: enforce-map-style
arguments: ["make"]
exclude: [ "TEST" ] exclude: [ "TEST" ]
arguments:
- "make"
- name: enforce-repeated-arg-type-style - name: enforce-repeated-arg-type-style
arguments: ["short"] arguments:
- "short"
- name: enforce-slice-style - name: enforce-slice-style
arguments: ["make"] arguments:
- "make"
- name: error-naming - name: error-naming
- name: error-return - name: error-return
- name: error-strings - name: error-strings
@ -292,8 +330,8 @@ linters-settings:
- name: increment-decrement - name: increment-decrement
- name: indent-error-flow - name: indent-error-flow
- name: max-public-structs - name: max-public-structs
exclude: [ "TEST" ]
arguments: [ 5 ] arguments: [ 5 ]
exclude: [ "TEST" ]
- name: modifies-parameter - name: modifies-parameter
- name: modifies-value-receiver - name: modifies-value-receiver
- name: optimize-operands-order - name: optimize-operands-order
@ -329,6 +367,62 @@ linters-settings:
- name: var-declaration - name: var-declaration
- name: var-naming - name: var-naming
- name: waitgroup-by-value - 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: testifylint:
# Disable all checkers (https://github.com/Antonboom/testifylint#checkers). # Disable all checkers (https://github.com/Antonboom/testifylint#checkers).
# Default: false # Default: false
@ -358,77 +452,104 @@ linters-settings:
- suite-subtest-run - suite-subtest-run
- suite-thelper - suite-thelper
- useless-assert - useless-assert
usetesting: usetesting:
# Enable/disable `os.TempDir()` detections. # Enable/disable `os.TempDir()` detections.
# Default: false # Default: false
os-temp-dir: true os-temp-dir: true
issues: # Defines a set of rules to ignore issues.
# List of regexps of issue texts to exclude. # It does not skip the analysis, and so does not ignore "typecheck" errors.
exclusions:
# Mode of the generated files analysis.
# #
# But independently of this option we use default exclude patterns, # - `strict`: sources are excluded by strictly following the Go generated file convention.
# it can be disabled by `exclude-use-default: false`. # Source files that have lines matching only the following regular expression will be excluded: `^// Code generated .* DO NOT EDIT\.$`
# To list all excluded by default patterns execute `golangci-lint run --help` # 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: https://golangci-lint.run/usage/false-positives/#default-exclusions # Default: lax
exclude: generated: lax
# 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
# Excluding configuration per-path, per-linter, per-text and per-source.
rules:
# errcheck
- path: cmd/telegraf/(main|printer|cmd_plugins).go - path: cmd/telegraf/(main|printer|cmd_plugins).go
text: "Error return value of `outputBuffer.Write` is not checked" #errcheck text: "Error return value of `outputBuffer.Write` is not checked"
- path: plugins/inputs/win_perf_counters/pdh.go - path: plugins/inputs/win_perf_counters/pdh.go
linters: linters:
- errcheck - errcheck
# gosec:G101
- path: _test\.go - path: _test\.go
text: "Potential hardcoded credentials" #gosec:G101 text: "Potential hardcoded credentials"
# gosec:G404
- path: _test\.go - path: _test\.go
text: "Use of weak random number generator" #gosec:G404 text: "Use of weak random number generator"
# revive:max-public-structs
- path-except: ^plugins/(aggregators|inputs|outputs|parsers|processors|serializers)/... - path-except: ^plugins/(aggregators|inputs|outputs|parsers|processors|serializers)/...
text: "max-public-structs: you have exceeded the maximum number" #revive:max-public-structs text: "max-public-structs: you have exceeded the maximum number"
# Independently of option `exclude` we use default exclude patterns, # revive:var-naming
# it can be disabled by this option. - path: (.+)\.go$
# To list all excluded by default patterns execute `golangci-lint run --help`. text: don't use an underscore in package name
# Default: true
exclude-use-default: false
# Which dirs to exclude: issues from them won't be reported. # EXC0001 errcheck: Almost all programs ignore errors on these functions, and in most cases it's ok
# Can use regexp here: `generated.*`, regexp is applied on full path, - path: (.+)\.go$
# including the path prefix if one is set. 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
# 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. # 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: [] # Default: []
exclude-dirs: paths:
- 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* - 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:
# Maximum issues count per one linter. # Maximum issues count per one linter.
# Set to 0 to disable. # Set to 0 to disable.
# Default: 50 # Default: 50
@ -443,49 +564,48 @@ issues:
# Default: true # Default: true
uniq-by-line: false uniq-by-line: false
# output configuration options # Output configuration options.
output: output:
# The formats used to render issues. # 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: 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 path: stdout
# Sort results by the order defined in `sort-order`. # Order to use when sorting results.
# Default: false # Possible values: `file`, `linter`, and `severity`.
sort-results: true #
# 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. # Show statistics per linter.
# Default: false # Default: true
show-stats: true show-stats: true
# Options for analysis running. severity:
run: # Set the default severity for issues.
# Timeout for analysis, e.g. 30s, 5m. #
# If the value is lower or equal to 0, the timeout is disabled. # If severity rules are defined and the issues do not match or no severity is provided to the rule
# Default: 1m # this will be the default severity applied.
timeout: 10m # 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

View File

@ -180,7 +180,7 @@ vet:
.PHONY: lint-install .PHONY: lint-install
lint-install: lint-install:
@echo "Installing golangci-lint" @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" @echo "Installing markdownlint"
npm install -g markdownlint-cli npm install -g markdownlint-cli

View File

@ -903,7 +903,7 @@ func TestConfig_MultipleProcessorsOrder(t *testing.T) {
} }
require.NoError(t, c.LoadAll(filenames...)) 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 var order []string
for _, p := range c.Processors { for _, p := range c.Processors {

View File

@ -85,7 +85,7 @@ func TestRunTimeoutFastExit(t *testing.T) {
// Verify "process already finished" log doesn't occur. // Verify "process already finished" log doesn't occur.
time.Sleep(time.Millisecond * 75) time.Sleep(time.Millisecond * 75)
require.Equal(t, "", buf.String()) require.Empty(t, buf.String())
} }
func TestCombinedOutputTimeout(t *testing.T) { func TestCombinedOutputTimeout(t *testing.T) {

View File

@ -19,7 +19,7 @@ func TestEngineAlternateSeparator(t *testing.T) {
require.Equal(t, map[string]string{ require.Equal(t, map[string]string{
"origin": "host01", "origin": "host01",
}, tags) }, tags)
require.Equal(t, "", field) require.Empty(t, field)
} }
func TestEngineWithWildcardTemplate(t *testing.T) { func TestEngineWithWildcardTemplate(t *testing.T) {

View File

@ -88,6 +88,7 @@ func TestCases(t *testing.T) {
output, n, err := config.ApplyMigrations(input) output, n, err := config.ApplyMigrations(input)
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, output) require.NotEmpty(t, output)
//nolint:testifylint // "useless-assert: meaningless assertion" - false positive
require.Positive(t, n, "expected migration application but none applied") require.Positive(t, n, "expected migration application but none applied")
actual := config.NewConfig() actual := config.NewConfig()
require.NoError(t, actual.LoadConfigData(output, config.EmptySourcePath)) require.NoError(t, actual.LoadConfigData(output, config.EmptySourcePath))

View File

@ -525,5 +525,5 @@ func assertContainsTaggedField(t *testing.T, acc *testutil.Accumulator, metricNa
return 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)
} }

View File

@ -96,7 +96,7 @@ func TestJolokia2_makeReadRequests(t *testing.T) {
for _, c := range cases { for _, c := range cases {
payload := makeReadRequests([]Metric{c.metric}) 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 { for _, actual := range payload {
require.Contains(t, c.expected, actual, "Failing case: "+c.metric.Name) require.Contains(t, c.expected, actual, "Failing case: "+c.metric.Name)
} }

View File

@ -107,7 +107,7 @@ func (s *Shim) writeProcessedMetrics() error {
if err := serializer.Init(); err != nil { if err := serializer.Init(); err != nil {
return fmt.Errorf("creating serializer failed: %w", err) 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 { select {
case m, open := <-s.metricCh: case m, open := <-s.metricCh:
if !open { if !open {

View File

@ -1,7 +1,6 @@
package amd_rocm_smi package amd_rocm_smi
import ( import (
"errors"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -29,7 +28,7 @@ func TestErrorBehaviorDefault(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
var ferr *internal.FatalError 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) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected)
} }
@ -48,7 +47,7 @@ func TestErrorBehaviorError(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
var ferr *internal.FatalError 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) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected)
} }
@ -67,7 +66,7 @@ func TestErrorBehaviorRetry(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
var ferr *internal.FatalError 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) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected)
} }

View File

@ -15,7 +15,7 @@ import (
func TestClusterIncludeExcludeFilter(t *testing.T) { func TestClusterIncludeExcludeFilter(t *testing.T) {
ch := ClickHouse{} ch := ClickHouse{}
require.Equal(t, "", ch.clusterIncludeExcludeFilter()) require.Empty(t, ch.clusterIncludeExcludeFilter())
ch.ClusterExclude = []string{"test_cluster"} ch.ClusterExclude = []string{"test_cluster"}
require.Equal(t, "WHERE cluster NOT IN ('test_cluster')", ch.clusterIncludeExcludeFilter()) require.Equal(t, "WHERE cluster NOT IN ('test_cluster')", ch.clusterIncludeExcludeFilter())

View File

@ -1,7 +1,6 @@
package cpu package cpu
import ( import (
"fmt"
"testing" "testing"
"github.com/shirou/gopsutil/v4/cpu" "github.com/shirou/gopsutil/v4/cpu"
@ -139,16 +138,14 @@ func assertContainsTaggedFloat(
return return
} }
} else { } 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( require.Failf(t, "Measurement not found",
"Could not find measurement %q with requested tags within %f of %f, Actual: %f", "Could not find measurement %q with requested tags within %f of %f, Actual: %f", measurement, delta, expectedValue, actualValue)
measurement, delta, expectedValue, actualValue)
require.Fail(t, msg)
} }
// TestCPUCountChange tests that no errors are encountered if the number of // TestCPUCountChange tests that no errors are encountered if the number of

View File

@ -117,7 +117,7 @@ func Test_getCommandResponse(t *testing.T) {
buf, err := connector.getCommandResponse(command) buf, err := connector.getCommandResponse(command)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, len(response), len(buf)) require.Len(t, buf, len(response))
require.Equal(t, response, string(buf)) require.Equal(t, response, string(buf))
} }
}) })

View File

@ -31,7 +31,7 @@ func Test_Init(t *testing.T) {
SocketPath: "", SocketPath: "",
} }
require.Equal(t, "", dpdk.SocketPath) require.Empty(t, dpdk.SocketPath)
require.NoError(t, dpdk.Init()) require.NoError(t, dpdk.Init())

View File

@ -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) { 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, "")) commandParams := getParams(commandWithParams(command, ""))
require.Equal(t, "", commandParams) require.Empty(t, commandParams)
}) })
} }

View File

@ -355,7 +355,7 @@ func readChanWithTimeout(t *testing.T, metrics chan telegraf.Metric, timeout tim
case m := <-metrics: case m := <-metrics:
return m return m
case <-to.C: case <-to.C:
require.FailNow(t, "timeout waiting for metric") require.Fail(t, "Timeout waiting for metric")
} }
return nil return nil
} }

View File

@ -59,7 +59,7 @@ func TestValidatePath(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
returnPath, err := validatePath(tc.path, tc.ft) returnPath, err := validatePath(tc.path, tc.ft)
require.Equal(t, "", returnPath) require.Empty(t, returnPath)
require.ErrorContains(t, err, tc.expectedErrorContains) require.ErrorContains(t, err, tc.expectedErrorContains)
} }
}) })
@ -77,7 +77,7 @@ func TestValidatePath(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
returnPath, err := validatePath(tc.path, tc.ft) returnPath, err := validatePath(tc.path, tc.ft)
require.Equal(t, "", returnPath) require.Empty(t, returnPath)
require.ErrorContains(t, err, tc.expectedErrorContains) require.ErrorContains(t, err, tc.expectedErrorContains)
} }
}) })
@ -93,7 +93,7 @@ func TestValidatePath(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
returnPath, err := validatePath(tc.path, tc.ft) returnPath, err := validatePath(tc.path, tc.ft)
require.Equal(t, "", returnPath) require.Empty(t, returnPath)
require.ErrorContains(t, err, tc.expectedErrorContains) require.ErrorContains(t, err, tc.expectedErrorContains)
} }
}) })

View File

@ -26,7 +26,7 @@ func TestDLB_Init(t *testing.T) {
SocketPath: "", SocketPath: "",
Log: testutil.Logger{}, 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 //nolint:errcheck // we are just testing that socket path gets set to default, not that default is valid
dlb.Init() dlb.Init()

View File

@ -689,7 +689,7 @@ func (m *mockOptGenerator) generate(cfg optConfig) []ptel.Option {
func TestSampleConfig(t *testing.T) { func TestSampleConfig(t *testing.T) {
p := &PowerStat{} p := &PowerStat{}
require.NotZero(t, p.SampleConfig()) require.NotEmpty(t, p.SampleConfig())
} }
func TestInit(t *testing.T) { func TestInit(t *testing.T) {

View File

@ -61,7 +61,7 @@ func TestSplitCSVLineIntoValues(t *testing.T) {
wrongLine := "2020-08-12 13:34:36,37,44,0.00,0,0.0" wrongLine := "2020-08-12 13:34:36,37,44,0.00,0,0.0"
splitCSV, err = splitCSVLineIntoValues(wrongLine) splitCSV, err = splitCSVLineIntoValues(wrongLine)
require.Error(t, err) require.Error(t, err)
require.Equal(t, "", splitCSV.timeValue) require.Empty(t, splitCSV.timeValue)
require.Nil(t, splitCSV.metricsValues) require.Nil(t, splitCSV.metricsValues)
require.Nil(t, splitCSV.coreOrPIDsValues) require.Nil(t, splitCSV.coreOrPIDsValues)
} }
@ -76,7 +76,7 @@ func TestFindPIDsInMeasurement(t *testing.T) {
line = "pids not included" line = "pids not included"
result, err = findPIDsInMeasurement(line) result, err = findPIDsInMeasurement(line)
require.Error(t, err) require.Error(t, err)
require.Equal(t, "", result) require.Empty(t, result)
} }
func TestCreateArgsProcesses(t *testing.T) { func TestCreateArgsProcesses(t *testing.T) {

View File

@ -57,7 +57,7 @@ func TestParseCoresMeasurement(t *testing.T) {
result, err := parseCoresMeasurement(measurement) result, err := parseCoresMeasurement(measurement)
require.Error(t, err) require.Error(t, err)
require.Equal(t, "", result.cores) require.Empty(t, result.cores)
require.Nil(t, result.values) require.Nil(t, result.values)
require.Equal(t, time.Time{}, result.time) require.Equal(t, time.Time{}, result.time)
}) })
@ -75,7 +75,7 @@ func TestParseCoresMeasurement(t *testing.T) {
result, err := parseCoresMeasurement(measurement) result, err := parseCoresMeasurement(measurement)
require.Error(t, err) require.Error(t, err)
require.Equal(t, "", result.cores) require.Empty(t, result.cores)
require.Nil(t, result.values) require.Nil(t, result.values)
require.Equal(t, time.Time{}, result.time) require.Equal(t, time.Time{}, result.time)
}) })
@ -94,7 +94,7 @@ func TestParseCoresMeasurement(t *testing.T) {
result, err := parseCoresMeasurement(measurement) result, err := parseCoresMeasurement(measurement)
require.Error(t, err) require.Error(t, err)
require.Equal(t, "", result.cores) require.Empty(t, result.cores)
require.Nil(t, result.values) require.Nil(t, result.values)
require.Equal(t, time.Time{}, result.time) require.Equal(t, time.Time{}, result.time)
}) })
@ -187,8 +187,8 @@ func TestParseProcessesMeasurement(t *testing.T) {
result, err := parseProcessesMeasurement(newMeasurement) result, err := parseProcessesMeasurement(newMeasurement)
require.Error(t, err) require.Error(t, err)
require.Equal(t, "", result.process) require.Empty(t, result.process)
require.Equal(t, "", result.cores) require.Empty(t, result.cores)
require.Nil(t, result.values) require.Nil(t, result.values)
require.Equal(t, time.Time{}, result.time) require.Equal(t, time.Time{}, result.time)
}) })

View File

@ -107,7 +107,7 @@ func TestGostats(t *testing.T) {
switch value.(type) { switch value.(type) {
case int64, uint64, float64: case int64, uint64, float64:
default: 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)
} }
} }
} }

View File

@ -70,7 +70,7 @@ func (l *Lanz) Stop() {
} }
func receive(acc telegraf.Accumulator, in <-chan *pb.LanzRecord, deviceURL *url.URL) { 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 { for {
select { select {
case msg, ok := <-in: case msg, ok := <-in:

View File

@ -364,7 +364,7 @@ func TestMasterFilter(t *testing.T) {
// getMetrics(). We have to find them by checking name prefixes. // getMetrics(). We have to find them by checking name prefixes.
for k := range masterMetrics { for k := range masterMetrics {
if strings.HasPrefix(k, "master/frameworks/") || strings.HasPrefix(k, "frameworks/") { 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)
} }
} }
} }

View File

@ -92,7 +92,7 @@ func TestGather(t *testing.T) {
case "step": case "step":
require.InDelta(t, 0.0, v, testutil.DefaultDelta) require.InDelta(t, 0.0, v, testutil.DefaultDelta)
default: default:
require.Failf(t, "unexpected field %q", k) require.Failf(t, "Unexpected field", "Extra field: %q", k)
} }
} }
} }

View File

@ -470,13 +470,13 @@ func generateExpectation(defs []requestExpectation) []request {
} }
func requireEqualRequests(t *testing.T, expected, actual []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 { for i, e := range expected {
a := actual[i] a := actual[i]
require.Equalf(t, e.address, a.address, "address mismatch in request %d", 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, 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 { for j, ef := range e.fields {
af := a.fields[j] af := a.fields[j]
require.Equalf(t, ef.address, af.address, "address mismatch in field %d of request %d", j, i) require.Equalf(t, ef.address, af.address, "address mismatch in field %d of request %d", j, i)

View File

@ -80,7 +80,7 @@ func waitForPoint(acc *testutil.Accumulator, t *testing.T) {
defer ticker.Stop() defer ticker.Stop()
counter := 0 counter := 0
//nolint:gosimple // for-select used on purpose //nolint:staticcheck // for-select used on purpose
for { for {
select { select {
case <-ticker.C: case <-ticker.C:

View File

@ -1,7 +1,6 @@
package nvidia_smi package nvidia_smi
import ( import (
"errors"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -79,7 +78,7 @@ func TestErrorBehaviorDefault(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
var ferr *internal.FatalError 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) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected)
} }
@ -98,7 +97,7 @@ func TestErrorBehaviorError(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
var ferr *internal.FatalError 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) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected)
} }
@ -117,7 +116,7 @@ func TestErrorBehaviorRetry(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
var ferr *internal.FatalError 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) require.ErrorIs(t, model.Gather(&acc), internal.ErrNotConnected)
} }

View File

@ -210,7 +210,7 @@ func TestChangeNamespaceLabelName(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
tags := prom.kubernetesPods[podID(id)].tags tags := prom.kubernetesPods[podID(id)].tags
require.Equal(t, "default", tags["pod_namespace"]) require.Equal(t, "default", tags["pod_namespace"])
require.Equal(t, "", tags["namespace"]) require.Empty(t, tags["namespace"])
} }
func TestPodHasMatchingNamespace(t *testing.T) { func TestPodHasMatchingNamespace(t *testing.T) {

View File

@ -1208,7 +1208,7 @@ func TestListMetricDescriptorFilter(t *testing.T) {
err := s.Gather(&acc) err := s.Gather(&acc)
require.NoError(t, err) 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 { for i, expected := range tt.calls {
actual := client.calls[i] actual := client.calls[i]
require.Equal(t, expected.name, actual.name) require.Equal(t, expected.name, actual.name)

View File

@ -1963,7 +1963,7 @@ func TestParseKeyValue(t *testing.T) {
require.Equalf(t, "bar", v, "Expected %s, got %s", "bar", v) require.Equalf(t, "bar", v, "Expected %s, got %s", "bar", v)
k2, v2 := parseKeyValue("baz") 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) require.Equalf(t, "baz", v2, "Expected %s, got %s", "baz", v2)
} }

View File

@ -610,7 +610,7 @@ func TestJsonTypes(t *testing.T) {
MetricVersion: 2, MetricVersion: 2,
} }
require.NoError(t, v.Gather(acc)) 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 { for _, metric := range acc.Metrics {
require.Equal(t, "varnish", metric.Measurement) require.Equal(t, "varnish", metric.Measurement)
for fieldName, value := range metric.Fields { for fieldName, value := range metric.Fields {

View File

@ -169,12 +169,7 @@ func TestWinPerfCountersConfigGet2Integration(t *testing.T) {
hostCounters, ok := m.hostCounters["localhost"] hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok) require.True(t, ok)
require.Len(t, hostCounters.counters, 1, "There should be exactly one result returned from the counterPath")
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))
}
} }
func TestWinPerfCountersConfigGet3Integration(t *testing.T) { func TestWinPerfCountersConfigGet3Integration(t *testing.T) {
@ -208,12 +203,7 @@ func TestWinPerfCountersConfigGet3Integration(t *testing.T) {
hostCounters, ok := m.hostCounters["localhost"] hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok) require.True(t, ok)
require.Len(t, hostCounters.counters, 2, "There should be exactly two results returned from the counterPath")
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))
}
} }
func TestWinPerfCountersConfigGet4Integration(t *testing.T) { func TestWinPerfCountersConfigGet4Integration(t *testing.T) {
@ -245,12 +235,7 @@ func TestWinPerfCountersConfigGet4Integration(t *testing.T) {
hostCounters, ok := m.hostCounters["localhost"] hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok) require.True(t, ok)
require.Len(t, hostCounters.counters, 2, "There should be exactly two results returned from the counterPath")
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))
}
} }
func TestWinPerfCountersConfigGet5Integration(t *testing.T) { func TestWinPerfCountersConfigGet5Integration(t *testing.T) {
@ -282,12 +267,7 @@ func TestWinPerfCountersConfigGet5Integration(t *testing.T) {
hostCounters, ok := m.hostCounters["localhost"] hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok) require.True(t, ok)
require.Len(t, hostCounters.counters, 4, "There should be exactly four results returned from the counterPath")
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))
}
} }
func TestWinPerfCountersConfigGet6Integration(t *testing.T) { func TestWinPerfCountersConfigGet6Integration(t *testing.T) {
@ -347,12 +327,7 @@ func TestWinPerfCountersConfigGet7Integration(t *testing.T) {
hostCounters, ok := m.hostCounters["localhost"] hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok) require.True(t, ok)
require.Len(t, hostCounters.counters, 2, "There should be exactly two results returned from the counterPath")
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))
}
} }
func TestWinPerfCountersConfigError1Integration(t *testing.T) { func TestWinPerfCountersConfigError1Integration(t *testing.T) {

View File

@ -64,7 +64,7 @@ func TestConnect(t *testing.T) {
errFunc: func(t *testing.T, output *AMQP, err error) { errFunc: func(t *testing.T, output *AMQP, err error) {
cfg := output.config cfg := output.config
require.Equal(t, []string{DefaultURL}, cfg.brokers) require.Equal(t, []string{DefaultURL}, cfg.brokers)
require.Equal(t, "", cfg.exchange) require.Empty(t, cfg.exchange)
require.Equal(t, "topic", cfg.exchangeType) require.Equal(t, "topic", cfg.exchangeType)
require.False(t, cfg.exchangePassive) require.False(t, cfg.exchangePassive)
require.True(t, cfg.exchangeDurable) require.True(t, cfg.exchangeDurable)

View File

@ -32,7 +32,7 @@ func TestBuildDimensions(t *testing.T) {
if len(testPoint.Tags()) >= maxDimensions { if len(testPoint.Tags()) >= maxDimensions {
require.Len(t, dimensions, maxDimensions, "Number of dimensions should be less than MaxDimensions") require.Len(t, dimensions, maxDimensions, "Number of dimensions should be less than MaxDimensions")
} else { } 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 { for i, key := range tagKeys {

View File

@ -588,7 +588,7 @@ func TestGetPipelineName(t *testing.T) {
for _, test := range tests { for _, test := range tests {
pipelineName := e.getPipelineName(e.pipelineName, e.pipelineTagKeys, test.Tags) pipelineName := e.getPipelineName(e.pipelineName, e.pipelineTagKeys, test.Tags)
require.Equal(t, "", pipelineName) require.Empty(t, pipelineName)
} }
} }

View File

@ -816,7 +816,7 @@ func TestDBRPTags(t *testing.T) {
}, },
handlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { handlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
require.Equal(t, "telegraf", r.FormValue("db")) require.Equal(t, "telegraf", r.FormValue("db"))
require.Equal(t, "", r.FormValue("rp")) require.Empty(t, r.FormValue("rp"))
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
}, },
}, },
@ -920,7 +920,7 @@ func TestDBRPTags(t *testing.T) {
}, },
handlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { handlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
require.Equal(t, "telegraf", r.FormValue("db")) require.Equal(t, "telegraf", r.FormValue("db"))
require.Equal(t, "", r.FormValue("rp")) require.Empty(t, r.FormValue("rp"))
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
}, },
}, },

View File

@ -68,7 +68,7 @@ func TestPartitionKey(t *testing.T) {
Method: "not supported", 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{ k = KinesisOutput{
Log: testutil.Logger{}, Log: testutil.Logger{},
@ -520,11 +520,7 @@ func (m *mockKinesisPutRecords) AssertRequests(
t *testing.T, t *testing.T,
expected []*kinesis.PutRecordsInput, expected []*kinesis.PutRecordsInput,
) { ) {
require.Equalf(t, require.Lenf(t, m.requests, len(expected), "Expected %v requests", len(expected))
len(expected),
len(m.requests),
"Expected %v requests", len(expected),
)
for i, expectedInput := range expected { for i, expectedInput := range expected {
actualInput := m.requests[i] actualInput := m.requests[i]
@ -535,11 +531,7 @@ func (m *mockKinesisPutRecords) AssertRequests(
"Expected request %v to have correct StreamName", i, "Expected request %v to have correct StreamName", i,
) )
require.Equalf(t, require.Lenf(t, actualInput.Records, len(expectedInput.Records), "Expected request %v to have %v Records", i, len(expectedInput.Records))
len(expectedInput.Records),
len(actualInput.Records),
"Expected request %v to have %v Records", i, len(expectedInput.Records),
)
for r, expectedRecord := range expectedInput.Records { for r, expectedRecord := range expectedInput.Records {
actualRecord := actualInput.Records[r] actualRecord := actualInput.Records[r]

View File

@ -214,7 +214,7 @@ func TestWriteTagsAsResourceLabels(t *testing.T) {
case "test_cpu_value/unknown": case "test_cpu_value/unknown":
require.Equal(t, "cpu", ts.Resource.Labels["job_name"]) require.Equal(t, "cpu", ts.Resource.Labels["job_name"])
default: 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": case "custom.googleapis.com/test_mem_h/histogram":
require.Equal(t, metricpb.MetricDescriptor_CUMULATIVE, ts.MetricKind) require.Equal(t, metricpb.MetricDescriptor_CUMULATIVE, ts.MetricKind)
default: 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": case "custom.googleapis.com/test/mem_g/value":
require.Equal(t, metricpb.MetricDescriptor_GAUGE, ts.MetricKind) require.Equal(t, metricpb.MetricDescriptor_GAUGE, ts.MetricKind)
default: default:
require.False(t, true, "Unknown metric type", ts.Metric.Type) require.Failf(t, "Wrong metric type", "Unknown metric type: %v", ts.Metric.Type)
} }
} }
} }

View File

@ -1265,7 +1265,7 @@ func comparison(t *testing.T,
timestreamRecords []*timestreamwrite.WriteRecordsInput) { timestreamRecords []*timestreamwrite.WriteRecordsInput) {
result := plugin.TransformMetrics(telegrafMetrics) 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 { for _, tsRecord := range timestreamRecords {
require.True(t, arrayContains(result, tsRecord), "Expected that the list of requests to Timestream: \n%s\n\n "+ 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) "will contain request: \n%s\n\nUsed MappingMode: %s", result, tsRecord, mappingMode)

View File

@ -400,7 +400,7 @@ func TestDefaults(t *testing.T) {
defaultWavefront := outputs.Outputs["wavefront"]().(*Wavefront) defaultWavefront := outputs.Outputs["wavefront"]().(*Wavefront)
require.Equal(t, 10000, defaultWavefront.HTTPMaximumBatchSize) require.Equal(t, 10000, defaultWavefront.HTTPMaximumBatchSize)
require.Equal(t, config.Duration(10*time.Second), defaultWavefront.Timeout) 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) { func TestMakeAuthOptions(t *testing.T) {

View File

@ -68,8 +68,8 @@ func TestZabbixAutoregisterPush(t *testing.T) {
zabbixSender.Reset() zabbixSender.Reset()
z.autoregisterPush() z.autoregisterPush()
require.Len(t, z.autoregisterLastSend, 1) require.Len(t, z.autoregisterLastSend, 1)
require.Equal(t, "", zabbixSender.hostname) require.Empty(t, zabbixSender.hostname)
require.Equal(t, "", zabbixSender.hostMetadata) require.Empty(t, zabbixSender.hostMetadata)
// Test that autoregister is sent if last send was more than autoregisterSendPeriod ago. // Test that autoregister is sent if last send was more than autoregisterSendPeriod ago.
z.Autoregister = "autoregister" z.Autoregister = "autoregister"

View File

@ -313,7 +313,7 @@ func writeValueList(testContext context.Context, valueLists []api.ValueList) (*n
} }
func assertEqualMetrics(t *testing.T, expected []metricData, received []telegraf.Metric) { 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 { for i, m := range received {
require.Equal(t, expected[i].name, m.Name()) require.Equal(t, expected[i].name, m.Name())
require.Equal(t, expected[i].tags, m.Tags()) require.Equal(t, expected[i].tags, m.Tags())

View File

@ -621,7 +621,7 @@ func TestParser(t *testing.T) {
require.Equal(t, tt.err.Error(), err.Error()) 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 { for i, expected := range tt.metrics {
require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Name(), metrics[i].Name())
require.Equal(t, expected.Tags(), metrics[i].Tags()) 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, 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 { for i, expected := range tt.metrics {
require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Name(), metrics[i].Name())
require.Equal(t, expected.Tags(), metrics[i].Tags()) 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 { for i, err := range errs {
require.Equal(t, tt.errs[i], err.Error()) require.Equal(t, tt.errs[i], err.Error())
} }

View File

@ -591,7 +591,7 @@ func TestParser(t *testing.T) {
metrics, err := parser.Parse(tt.input) metrics, err := parser.Parse(tt.input)
require.Equal(t, tt.err, err) 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 { for i, expected := range tt.metrics {
require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Name(), metrics[i].Name())
require.Equal(t, expected.Tags(), metrics[i].Tags()) 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, 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 { for i, expected := range tt.metrics {
require.Equal(t, expected.Name(), metrics[i].Name()) require.Equal(t, expected.Name(), metrics[i].Name())
require.Equal(t, expected.Tags(), metrics[i].Tags()) 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 { for i, err := range errs {
require.Equal(t, tt.errs[i], err.Error()) require.Equal(t, tt.errs[i], err.Error())
} }

View File

@ -91,7 +91,7 @@ func TestMultipleConfigs(t *testing.T) {
// The milliseconds weren't matching, seemed like a rounding difference between the influx parser // The milliseconds weren't matching, seemed like a rounding difference between the influx parser
// Compares each metrics times separately and ignores milliseconds // Compares each metrics times separately and ignores milliseconds
if strings.HasPrefix(f.Name(), "timestamp") { if strings.HasPrefix(f.Name(), "timestamp") {
require.Equal(t, len(expected), len(actual)) require.Len(t, actual, len(expected))
for i, m := range actual { for i, m := range actual {
require.Equal(t, expected[i].Time().Truncate(time.Second), m.Time().Truncate(time.Second)) require.Equal(t, expected[i].Time().Truncate(time.Second), m.Time().Truncate(time.Second))
} }

View File

@ -80,7 +80,7 @@ func (b *metricBuilder) b() telegraf.Metric {
// assertEqual asserts two slices to be equal. Note, that the order // assertEqual asserts two slices to be equal. Note, that the order
// of the entries matters. // of the entries matters.
func assertEqual(t *testing.T, exp, actual []telegraf.Metric) { 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++ { for i := 0; i < len(exp); i++ {
ok := testutil.MetricEqual(exp[i], actual[i]) ok := testutil.MetricEqual(exp[i], actual[i])
require.True(t, ok) require.True(t, ok)

View File

@ -366,7 +366,7 @@ func TestSerializeValueString(t *testing.T) {
buf, err := s.Serialize(m) buf, err := s.Serialize(m)
require.NoError(t, err) require.NoError(t, err)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
require.Equal(t, "", mS[0]) require.Empty(t, mS[0])
} }
func TestSerializeValueStringWithTagSupport(t *testing.T) { func TestSerializeValueStringWithTagSupport(t *testing.T) {
@ -390,7 +390,7 @@ func TestSerializeValueStringWithTagSupport(t *testing.T) {
buf, err := s.Serialize(m) buf, err := s.Serialize(m)
require.NoError(t, err) require.NoError(t, err)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
require.Equal(t, "", mS[0]) require.Empty(t, mS[0])
} }
func TestSerializeValueBoolean(t *testing.T) { func TestSerializeValueBoolean(t *testing.T) {

View File

@ -399,8 +399,8 @@ func (a *Accumulator) AssertContainsTaggedFields(
t.Log("measurement", p.Measurement, "tags", p.Tags, "fields", p.Fields) 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( func (a *Accumulator) AssertDoesNotContainsTaggedFields(
@ -417,10 +417,7 @@ func (a *Accumulator) AssertDoesNotContainsTaggedFields(
} }
if p.Measurement == measurement && reflect.DeepEqual(fields, p.Fields) { if p.Measurement == measurement && reflect.DeepEqual(fields, p.Fields) {
msg := fmt.Sprintf( require.Failf(t, "Wrong measurement", "Found measurement %s with tagged fields (tags %v) which should not be there", measurement, tags)
"found measurement %s with tagged fields (tags %v) which should not be there",
measurement, tags)
require.Fail(t, msg)
} }
} }
} }
@ -437,8 +434,7 @@ func (a *Accumulator) AssertContainsFields(
return return
} }
} }
msg := fmt.Sprintf("unknown measurement %q", measurement) require.Failf(t, "Unknown measurement", "Unknown measurement %q", measurement)
require.Fail(t, msg)
} }
func (a *Accumulator) HasPoint( func (a *Accumulator) HasPoint(
@ -471,8 +467,7 @@ func (a *Accumulator) AssertDoesNotContainMeasurement(t *testing.T, measurement
defer a.Unlock() defer a.Unlock()
for _, p := range a.Metrics { for _, p := range a.Metrics {
if p.Measurement == measurement { if p.Measurement == measurement {
msg := "found unexpected measurement " + measurement require.Failf(t, "Unexpected measurement", "Found unexpected measurement %q", measurement)
require.Fail(t, msg)
} }
} }
} }