fix: use "ErrorContains" or "EqualError" instead of "Contains(t, err.Error()" and "Equal(t, err.Error()" (#15094)

* fix: use "ErrorContains" or "EqualError" instead of "Contains(t, err.Error()" and "Equal(t, err.Error()"

---------

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
Matthieu MOREL 2024-10-06 18:35:29 +02:00 committed by GitHub
parent a1c2f59bc5
commit ab64966e9d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 45 additions and 81 deletions

View file

@ -153,14 +153,4 @@ linters-settings:
disable: disable:
- float-compare - float-compare
- go-require - go-require
enable: enable-all: true
- bool-compare
- compares
- empty
- error-is-as
- error-nil
- expected-actual
- len
- require-error
- suite-dont-use-pkg
- suite-extra-assert-call

View file

@ -146,7 +146,7 @@ func TestCheckSDFile(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
_, err := checkSDFile(test.file) _, err := checkSDFile(test.file)
if test.err != "" { if test.err != "" {
require.Equalf(t, test.err, err.Error(), "Expected error %q, got %q", test.err, err.Error()) require.EqualErrorf(t, err, test.err, "Expected error %q, got %q", test.err, err.Error())
return return
} }
require.NoError(t, err) require.NoError(t, err)
@ -228,7 +228,7 @@ func TestCheckTargetConfig(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
_, err := checkConfig(false, "testdata/"+test.file, false) _, err := checkConfig(false, "testdata/"+test.file, false)
if test.err != "" { if test.err != "" {
require.Equalf(t, test.err, err.Error(), "Expected error %q, got %q", test.err, err.Error()) require.EqualErrorf(t, err, test.err, "Expected error %q, got %q", test.err, err.Error())
return return
} }
require.NoError(t, err) require.NoError(t, err)
@ -315,7 +315,7 @@ func TestCheckConfigSyntax(t *testing.T) {
expectedErrMsg = test.errWindows expectedErrMsg = test.errWindows
} }
if expectedErrMsg != "" { if expectedErrMsg != "" {
require.Equalf(t, expectedErrMsg, err.Error(), "Expected error %q, got %q", test.err, err.Error()) require.EqualErrorf(t, err, expectedErrMsg, "Expected error %q, got %q", test.err, err.Error())
return return
} }
require.NoError(t, err) require.NoError(t, err)
@ -345,7 +345,7 @@ func TestAuthorizationConfig(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
_, err := checkConfig(false, "testdata/"+test.file, false) _, err := checkConfig(false, "testdata/"+test.file, false)
if test.err != "" { if test.err != "" {
require.Contains(t, err.Error(), test.err, "Expected error to contain %q, got %q", test.err, err.Error()) require.ErrorContains(t, err, test.err, "Expected error to contain %q, got %q", test.err, err.Error())
return return
} }
require.NoError(t, err) require.NoError(t, err)

View file

@ -2095,8 +2095,7 @@ func TestBadConfigs(t *testing.T) {
}() }()
for _, ee := range expectedErrors { for _, ee := range expectedErrors {
_, err := LoadFile("testdata/"+ee.filename, false, false, log.NewNopLogger()) _, err := LoadFile("testdata/"+ee.filename, false, false, log.NewNopLogger())
require.Error(t, err, "%s", ee.filename) require.ErrorContains(t, err, ee.errMsg,
require.Contains(t, err.Error(), ee.errMsg,
"Expected error for %s to contain %q but got: %s", ee.filename, ee.errMsg, err) "Expected error for %s to contain %q but got: %s", ee.filename, ee.errMsg, err)
} }
} }

View file

@ -407,7 +407,7 @@ func TestGetDatacenterShouldReturnError(t *testing.T) {
err = d.getDatacenter() err = d.getDatacenter()
// An error should be returned. // An error should be returned.
require.Equal(t, tc.errMessage, err.Error()) require.EqualError(t, err, tc.errMessage)
// Should still be empty. // Should still be empty.
require.Equal(t, "", d.clientDatacenter) require.Equal(t, "", d.clientDatacenter)
} }

View file

@ -95,8 +95,7 @@ func TestRobotSDRefreshHandleError(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
targetGroups, err := d.refresh(context.Background()) targetGroups, err := d.refresh(context.Background())
require.Error(t, err) require.EqualError(t, err, "non 2xx status '401' response during hetzner service discovery with role robot")
require.Equal(t, "non 2xx status '401' response during hetzner service discovery with role robot", err.Error())
require.Empty(t, targetGroups) require.Empty(t, targetGroups)
} }

View file

@ -93,6 +93,5 @@ func TestOpenstackSDHypervisorRefreshWithDoneContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
cancel() cancel()
_, err := hypervisor.refresh(ctx) _, err := hypervisor.refresh(ctx)
require.Error(t, err) require.ErrorContains(t, err, context.Canceled.Error(), "%q doesn't contain %q", err, context.Canceled)
require.Contains(t, err.Error(), context.Canceled.Error(), "%q doesn't contain %q", err, context.Canceled)
} }

View file

@ -134,6 +134,5 @@ func TestOpenstackSDInstanceRefreshWithDoneContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
cancel() cancel()
_, err := hypervisor.refresh(ctx) _, err := hypervisor.refresh(ctx)
require.Error(t, err) require.ErrorContains(t, err, context.Canceled.Error(), "%q doesn't contain %q", err, context.Canceled)
require.Contains(t, err.Error(), context.Canceled.Error(), "%q doesn't contain %q", err, context.Canceled)
} }

View file

@ -21,7 +21,6 @@ import (
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"strconv" "strconv"
"strings"
"testing" "testing"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -182,8 +181,7 @@ func TestTritonSDRefreshNoServer(t *testing.T) {
td, m, _ := newTritonDiscovery(conf) td, m, _ := newTritonDiscovery(conf)
_, err := td.refresh(context.Background()) _, err := td.refresh(context.Background())
require.Error(t, err) require.ErrorContains(t, err, "an error occurred when requesting targets from the discovery endpoint")
require.True(t, strings.Contains(err.Error(), "an error occurred when requesting targets from the discovery endpoint"))
m.Unregister() m.Unregister()
} }
@ -193,8 +191,7 @@ func TestTritonSDRefreshCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
cancel() cancel()
_, err := td.refresh(ctx) _, err := td.refresh(ctx)
require.Error(t, err) require.ErrorContains(t, err, context.Canceled.Error())
require.True(t, strings.Contains(err.Error(), context.Canceled.Error()))
m.Unregister() m.Unregister()
} }

View file

@ -52,16 +52,14 @@ func TestMakeXDSResourceHttpEndpointEmptyServerURLScheme(t *testing.T) {
endpointURL, err := makeXDSResourceHTTPEndpointURL(ProtocolV3, urlMustParse("127.0.0.1"), "monitoring") endpointURL, err := makeXDSResourceHTTPEndpointURL(ProtocolV3, urlMustParse("127.0.0.1"), "monitoring")
require.Empty(t, endpointURL) require.Empty(t, endpointURL)
require.Error(t, err) require.EqualError(t, err, "invalid xDS server URL")
require.Equal(t, "invalid xDS server URL", err.Error())
} }
func TestMakeXDSResourceHttpEndpointEmptyServerURLHost(t *testing.T) { func TestMakeXDSResourceHttpEndpointEmptyServerURLHost(t *testing.T) {
endpointURL, err := makeXDSResourceHTTPEndpointURL(ProtocolV3, urlMustParse("grpc://127.0.0.1"), "monitoring") endpointURL, err := makeXDSResourceHTTPEndpointURL(ProtocolV3, urlMustParse("grpc://127.0.0.1"), "monitoring")
require.Empty(t, endpointURL) require.Empty(t, endpointURL)
require.Error(t, err) require.ErrorContains(t, err, "must be either 'http' or 'https'")
require.Contains(t, err.Error(), "must be either 'http' or 'https'")
} }
func TestMakeXDSResourceHttpEndpoint(t *testing.T) { func TestMakeXDSResourceHttpEndpoint(t *testing.T) {

View file

@ -201,9 +201,8 @@ func TestKumaMadsV1ResourceParserInvalidResources(t *testing.T) {
}} }}
groups, err := kumaMadsV1ResourceParser(resources, KumaMadsV1ResourceTypeURL) groups, err := kumaMadsV1ResourceParser(resources, KumaMadsV1ResourceTypeURL)
require.Nil(t, groups) require.Nil(t, groups)
require.Error(t, err)
require.Contains(t, err.Error(), "cannot parse") require.ErrorContains(t, err, "cannot parse")
} }
func TestNewKumaHTTPDiscovery(t *testing.T) { func TestNewKumaHTTPDiscovery(t *testing.T) {

View file

@ -85,9 +85,8 @@ func TestParseFileFailure(t *testing.T) {
for _, c := range table { for _, c := range table {
_, errs := ParseFile(filepath.Join("testdata", c.filename)) _, errs := ParseFile(filepath.Join("testdata", c.filename))
require.NotNil(t, errs, "Expected error parsing %s but got none", c.filename) require.NotEmpty(t, errs, "Expected error parsing %s but got none", c.filename)
require.Error(t, errs[0]) require.ErrorContainsf(t, errs[0], c.errMsg, "Expected error for %s.", c.filename)
require.Containsf(t, errs[0].Error(), c.errMsg, "Expected error for %s.", c.filename)
} }
} }
@ -259,8 +258,7 @@ func TestError(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
got := tt.error.Error() require.EqualError(t, tt.error, tt.want)
require.Equal(t, tt.want, got)
}) })
} }
} }
@ -308,8 +306,7 @@ func TestWrappedError(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
got := tt.wrappedError.Error() require.EqualError(t, tt.wrappedError, tt.want)
require.Equal(t, tt.want, got)
}) })
} }
} }

View file

@ -98,8 +98,7 @@ func TestNewParser(t *testing.T) {
if tt.err == "" { if tt.err == "" {
require.NoError(t, err) require.NoError(t, err)
} else { } else {
require.Error(t, err) require.ErrorContains(t, err, tt.err)
require.Contains(t, err.Error(), tt.err)
} }
}) })
} }

View file

@ -804,7 +804,7 @@ func TestOpenMetricsParseErrors(t *testing.T) {
for err == nil { for err == nil {
_, err = p.Next() _, err = p.Next()
} }
require.Equal(t, c.err, err.Error(), "test %d: %s", i, c.input) require.EqualError(t, err, c.err, "test %d: %s", i, c.input)
} }
} }
@ -871,11 +871,11 @@ func TestOMNullByteHandling(t *testing.T) {
} }
if c.err == "" { if c.err == "" {
require.Equal(t, io.EOF, err, "test %d", i) require.ErrorIs(t, err, io.EOF, "test %d", i)
continue continue
} }
require.Equal(t, c.err, err.Error(), "test %d", i) require.EqualError(t, err, c.err, "test %d", i)
} }
} }

View file

@ -423,8 +423,7 @@ func TestPromParseErrors(t *testing.T) {
for err == nil { for err == nil {
_, err = p.Next() _, err = p.Next()
} }
require.Error(t, err) require.EqualError(t, err, c.err, "test %d", i)
require.Equal(t, c.err, err.Error(), "test %d", i)
} }
} }
@ -483,8 +482,7 @@ func TestPromNullByteHandling(t *testing.T) {
continue continue
} }
require.Error(t, err) require.EqualError(t, err, c.err, "test %d", i)
require.Equal(t, c.err, err.Error(), "test %d", i)
} }
} }

View file

@ -29,7 +29,7 @@ func TestfuzzParseMetricWithContentTypePanicOnInvalid(t *testing.T) {
} else { } else {
err, ok := p.(error) err, ok := p.(error)
require.True(t, ok) require.True(t, ok)
require.Contains(t, err.Error(), "duplicate parameter name") require.ErrorContains(t, err, "duplicate parameter name")
} }
}() }()

View file

@ -3925,8 +3925,7 @@ func TestParseExpressions(t *testing.T) {
require.Equal(t, expected, expr, "error on input '%s'", test.input) require.Equal(t, expected, expr, "error on input '%s'", test.input)
} else { } else {
require.Error(t, err) require.ErrorContains(t, err, test.errMsg, "unexpected error on input '%s', expected '%s', got '%s'", test.input, test.errMsg, err.Error())
require.Contains(t, err.Error(), test.errMsg, "unexpected error on input '%s', expected '%s', got '%s'", test.input, test.errMsg, err.Error())
var errorList ParseErrors var errorList ParseErrors
ok := errors.As(err, &errorList) ok := errors.As(err, &errorList)
@ -4468,7 +4467,7 @@ func TestRecoverParserError(t *testing.T) {
e := errors.New("custom error") e := errors.New("custom error")
defer func() { defer func() {
require.Equal(t, e.Error(), err.Error()) require.EqualError(t, err, e.Error())
}() }()
defer p.recover(&err) defer p.recover(&err)

View file

@ -441,7 +441,7 @@ func TestScrapePoolTargetLimit(t *testing.T) {
lerr := l.(*testLoop).getForcedError() lerr := l.(*testLoop).getForcedError()
if shouldErr { if shouldErr {
require.Error(t, lerr, "error was expected for %d targets with a limit of %d", targets, limit) require.Error(t, lerr, "error was expected for %d targets with a limit of %d", targets, limit)
require.Equal(t, fmt.Sprintf("target_limit exceeded (number of targets: %d, limit: %d)", targets, limit), lerr.Error()) require.EqualError(t, lerr, fmt.Sprintf("target_limit exceeded (number of targets: %d, limit: %d)", targets, limit))
} else { } else {
require.NoError(t, lerr) require.NoError(t, lerr)
} }
@ -2549,7 +2549,7 @@ func TestTargetScrapeScrapeNotFound(t *testing.T) {
resp, err := ts.scrape(context.Background()) resp, err := ts.scrape(context.Background())
require.NoError(t, err) require.NoError(t, err)
_, err = ts.readResponse(context.Background(), resp, io.Discard) _, err = ts.readResponse(context.Background(), resp, io.Discard)
require.Contains(t, err.Error(), "404", "Expected \"404 NotFound\" error but got: %s", err) require.ErrorContains(t, err, "404", "Expected \"404 NotFound\" error but got: %s", err)
} }
func TestTargetScraperBodySizeLimit(t *testing.T) { func TestTargetScraperBodySizeLimit(t *testing.T) {

View file

@ -173,16 +173,13 @@ func TestFanoutErrors(t *testing.T) {
} }
if tc.err != nil { if tc.err != nil {
require.Error(t, ss.Err()) require.EqualError(t, ss.Err(), tc.err.Error())
require.Equal(t, tc.err.Error(), ss.Err().Error())
} }
if tc.warning != nil { if tc.warning != nil {
require.NotEmpty(t, ss.Warnings(), "warnings expected")
w := ss.Warnings() w := ss.Warnings()
require.Error(t, w.AsErrors()[0]) require.NotEmpty(t, w, "warnings expected")
warn, _ := w.AsStrings("", 0, 0) require.EqualError(t, w.AsErrors()[0], tc.warning.Error())
require.Equal(t, tc.warning.Error(), warn[0])
} }
}) })
t.Run("chunks", func(t *testing.T) { t.Run("chunks", func(t *testing.T) {
@ -200,16 +197,13 @@ func TestFanoutErrors(t *testing.T) {
} }
if tc.err != nil { if tc.err != nil {
require.Error(t, ss.Err()) require.EqualError(t, ss.Err(), tc.err.Error())
require.Equal(t, tc.err.Error(), ss.Err().Error())
} }
if tc.warning != nil { if tc.warning != nil {
require.NotEmpty(t, ss.Warnings(), "warnings expected")
w := ss.Warnings() w := ss.Warnings()
require.Error(t, w.AsErrors()[0]) require.NotEmpty(t, w, "warnings expected")
warn, _ := w.AsStrings("", 0, 0) require.EqualError(t, w.AsErrors()[0], tc.warning.Error())
require.Equal(t, tc.warning.Error(), warn[0])
} }
}) })
} }

View file

@ -86,7 +86,7 @@ func TestChunkedReader_Overflow(t *testing.T) {
_, err = NewChunkedReader(bytes.NewReader(b2), 11, nil).Next() _, err = NewChunkedReader(bytes.NewReader(b2), 11, nil).Next()
require.Error(t, err, "expect exceed limit error") require.Error(t, err, "expect exceed limit error")
require.Equal(t, "chunkedReader: message size exceeded the limit 11 bytes; got: 12 bytes", err.Error()) require.EqualError(t, err, "chunkedReader: message size exceeded the limit 11 bytes; got: 12 bytes")
} }
func TestChunkedReader_CorruptedFrame(t *testing.T) { func TestChunkedReader_CorruptedFrame(t *testing.T) {
@ -102,5 +102,5 @@ func TestChunkedReader_CorruptedFrame(t *testing.T) {
_, err = NewChunkedReader(bytes.NewReader(bs), 20, nil).Next() _, err = NewChunkedReader(bytes.NewReader(bs), 20, nil).Next()
require.Error(t, err, "expected malformed frame") require.Error(t, err, "expected malformed frame")
require.Equal(t, "chunkedReader: corrupted frame; checksum mismatch", err.Error()) require.EqualError(t, err, "chunkedReader: corrupted frame; checksum mismatch")
} }

View file

@ -253,8 +253,7 @@ func TestValidateLabelsAndMetricName(t *testing.T) {
t.Run(test.description, func(t *testing.T) { t.Run(test.description, func(t *testing.T) {
err := validateLabelsAndMetricName(test.input) err := validateLabelsAndMetricName(test.input)
if test.expectedErr != "" { if test.expectedErr != "" {
require.Error(t, err) require.EqualError(t, err, test.expectedErr)
require.Equal(t, test.expectedErr, err.Error())
} else { } else {
require.NoError(t, err) require.NoError(t, err)
} }
@ -551,7 +550,7 @@ func TestNegotiateResponseType(t *testing.T) {
_, err = NegotiateResponseType([]prompb.ReadRequest_ResponseType{20}) _, err = NegotiateResponseType([]prompb.ReadRequest_ResponseType{20})
require.Error(t, err, "expected error due to not supported requested response types") require.Error(t, err, "expected error due to not supported requested response types")
require.Equal(t, "server does not support any of the requested response types: [20]; supported: map[SAMPLES:{} STREAMED_XOR_CHUNKS:{}]", err.Error()) require.EqualError(t, err, "server does not support any of the requested response types: [20]; supported: map[SAMPLES:{} STREAMED_XOR_CHUNKS:{}]")
} }
func TestMergeLabels(t *testing.T) { func TestMergeLabels(t *testing.T) {

View file

@ -192,7 +192,7 @@ func TestCorruptedChunk(t *testing.T) {
// Check open err. // Check open err.
b, err := OpenBlock(nil, blockDir, nil) b, err := OpenBlock(nil, blockDir, nil)
if tc.openErr != nil { if tc.openErr != nil {
require.Equal(t, tc.openErr.Error(), err.Error()) require.EqualError(t, err, tc.openErr.Error())
return return
} }
defer func() { require.NoError(t, b.Close()) }() defer func() { require.NoError(t, b.Close()) }()
@ -206,7 +206,7 @@ func TestCorruptedChunk(t *testing.T) {
require.True(t, set.Next()) require.True(t, set.Next())
it := set.At().Iterator(nil) it := set.At().Iterator(nil)
require.Equal(t, chunkenc.ValNone, it.Next()) require.Equal(t, chunkenc.ValNone, it.Next())
require.Equal(t, tc.iterErr.Error(), it.Err().Error()) require.EqualError(t, it.Err(), tc.iterErr.Error())
}) })
} }
} }

View file

@ -1045,8 +1045,7 @@ func TestCompaction_populateBlock(t *testing.T) {
} }
err = blockPopulator.PopulateBlock(c.ctx, c.metrics, c.logger, c.chunkPool, c.mergeFunc, blocks, meta, iw, nopChunkWriter{}, irPostingsFunc) err = blockPopulator.PopulateBlock(c.ctx, c.metrics, c.logger, c.chunkPool, c.mergeFunc, blocks, meta, iw, nopChunkWriter{}, irPostingsFunc)
if tc.expErr != nil { if tc.expErr != nil {
require.Error(t, err) require.EqualError(t, err, tc.expErr.Error())
require.Equal(t, tc.expErr.Error(), err.Error())
return return
} }
require.NoError(t, err) require.NoError(t, err)

View file

@ -2414,8 +2414,7 @@ func TestAddDuplicateLabelName(t *testing.T) {
add := func(labels labels.Labels, labelName string) { add := func(labels labels.Labels, labelName string) {
app := h.Appender(context.Background()) app := h.Appender(context.Background())
_, err := app.Append(0, labels, 0, 0) _, err := app.Append(0, labels, 0, 0)
require.Error(t, err) require.EqualError(t, err, fmt.Sprintf(`label name "%s" is not unique: invalid sample`, labelName))
require.Equal(t, fmt.Sprintf(`label name "%s" is not unique: invalid sample`, labelName), err.Error())
} }
add(labels.FromStrings("a", "c", "a", "b"), "a") add(labels.FromStrings("a", "c", "a", "b"), "a")

View file

@ -4176,7 +4176,7 @@ func TestExtractQueryOpts(t *testing.T) {
if test.err == nil { if test.err == nil {
require.NoError(t, err) require.NoError(t, err)
} else { } else {
require.Equal(t, test.err.Error(), err.Error()) require.EqualError(t, err, test.err.Error())
} }
}) })
} }