diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml index 7e8974b60..914cddca1 100644 --- a/.github/workflows/validate.yaml +++ b/.github/workflows/validate.yaml @@ -7,7 +7,7 @@ on: env: GO_VERSION: '1.21' - GOLANGCI_LINT_VERSION: v1.54.1 + GOLANGCI_LINT_VERSION: v1.55.2 MISSSPELL_VERSION: v0.4.0 IN_DOCKER: "" diff --git a/.golangci.yml b/.golangci.yml index ba3ce50a3..246fea4fa 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -151,6 +151,19 @@ linters-settings: - github.com/mailgun/minheap - github.com/mailgun/multibuf - github.com/jaguilar/vt100 + testifylint: + enable: + - bool-compare + - compares + - empty + - error-is-as + - error-nil + - expected-actual + - float-compare + - len + - suite-dont-use-pkg + - suite-extra-assert-call + - suite-thelper linters: enable-all: true diff --git a/.semaphore/semaphore.yml b/.semaphore/semaphore.yml index ccc703dae..a4a01946f 100644 --- a/.semaphore/semaphore.yml +++ b/.semaphore/semaphore.yml @@ -25,7 +25,7 @@ global_job_config: - export "PATH=${GOPATH}/bin:${PATH}" - mkdir -vp "${SEMAPHORE_GIT_DIR}" "${GOPATH}/bin" - export GOPROXY=https://proxy.golang.org,direct - - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "${GOPATH}/bin" v1.54.1 + - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "${GOPATH}/bin" v1.55.2 - curl -sSfL https://gist.githubusercontent.com/traefiker/6d7ac019c11d011e4f131bb2cca8900e/raw/goreleaser.sh | bash -s -- -b "${GOPATH}/bin" - checkout - cache restore traefik-$(checksum go.sum) diff --git a/build.Dockerfile b/build.Dockerfile index aa5d63693..587424c38 100644 --- a/build.Dockerfile +++ b/build.Dockerfile @@ -13,7 +13,7 @@ RUN mkdir -p /usr/local/bin \ | tar -xzC /usr/local/bin --transform 's#^.+/##x' # Download golangci-lint binary to bin folder in $GOPATH -RUN curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | bash -s -- -b $GOPATH/bin v1.54.1 +RUN curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | bash -s -- -b $GOPATH/bin v1.55.2 # Download misspell binary to bin folder in $GOPATH RUN curl -sfL https://raw.githubusercontent.com/golangci/misspell/master/install-misspell.sh | bash -s -- -b $GOPATH/bin v0.4.0 diff --git a/integration/access_log_test.go b/integration/access_log_test.go index 1f25a9471..5a65beb9e 100644 --- a/integration/access_log_test.go +++ b/integration/access_log_test.go @@ -3,6 +3,7 @@ package integration import ( "crypto/md5" "crypto/rand" + "encoding/hex" "encoding/json" "fmt" "io" @@ -265,7 +266,8 @@ func getMD5(data string) string { if _, err := digest.Write([]byte(data)); err != nil { log.WithoutContext().Error(err) } - return fmt.Sprintf("%x", digest.Sum(nil)) + + return hex.EncodeToString(digest.Sum(nil)) } func getCnonce() string { @@ -273,7 +275,8 @@ func getCnonce() string { if _, err := io.ReadFull(rand.Reader, b); err != nil { log.WithoutContext().Error(err) } - return fmt.Sprintf("%x", b)[:16] + + return hex.EncodeToString(b)[:16] } func getDigestAuthorization(digestParts map[string]string) string { diff --git a/integration/grpc_test.go b/integration/grpc_test.go index ab1c7f899..6493d1f04 100644 --- a/integration/grpc_test.go +++ b/integration/grpc_test.go @@ -42,7 +42,7 @@ func (s *GRPCSuite) SetUpSuite(c *check.C) { } func (s *myserver) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) { - return &helloworld.HelloReply{Message: "Hello " + in.Name}, nil + return &helloworld.HelloReply{Message: "Hello " + in.GetName()}, nil } func (s *myserver) StreamExample(in *helloworld.StreamExampleRequest, server helloworld.Greeter_StreamExampleServer) error { @@ -121,7 +121,7 @@ func callHelloClientGRPC(name string, secure bool) (string, error) { if err != nil { return "", err } - return r.Message, nil + return r.GetMessage(), nil } func callStreamExampleClientGRPC() (helloworld.Greeter_StreamExampleClient, func() error, error) { @@ -351,7 +351,7 @@ func (s *GRPCSuite) TestGRPCBuffer(c *check.C) { go func() { tr, err := client.Recv() c.Assert(err, check.IsNil) - c.Assert(len(tr.Data), check.Equals, 512) + c.Assert(len(tr.GetData()), check.Equals, 512) received <- true }() @@ -414,7 +414,7 @@ func (s *GRPCSuite) TestGRPCBufferWithFlushInterval(c *check.C) { go func() { tr, err := client.Recv() c.Assert(err, check.IsNil) - c.Assert(len(tr.Data), check.Equals, 512) + c.Assert(len(tr.GetData()), check.Equals, 512) received <- true }() diff --git a/pkg/api/handler_entrypoint_test.go b/pkg/api/handler_entrypoint_test.go index a3c31e583..114724b40 100644 --- a/pkg/api/handler_entrypoint_test.go +++ b/pkg/api/handler_entrypoint_test.go @@ -212,7 +212,7 @@ func TestHandler_EntryPoints(t *testing.T) { return } - assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) diff --git a/pkg/api/handler_http_test.go b/pkg/api/handler_http_test.go index f6137f202..b186a2d15 100644 --- a/pkg/api/handler_http_test.go +++ b/pkg/api/handler_http_test.go @@ -873,7 +873,7 @@ func TestHandler_HTTP(t *testing.T) { return } - assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) diff --git a/pkg/api/handler_overview_test.go b/pkg/api/handler_overview_test.go index 6dee89a72..428687e69 100644 --- a/pkg/api/handler_overview_test.go +++ b/pkg/api/handler_overview_test.go @@ -291,7 +291,7 @@ func TestHandler_Overview(t *testing.T) { return } - assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) diff --git a/pkg/api/handler_tcp_test.go b/pkg/api/handler_tcp_test.go index 3e14921fb..d15ec1cdf 100644 --- a/pkg/api/handler_tcp_test.go +++ b/pkg/api/handler_tcp_test.go @@ -750,7 +750,7 @@ func TestHandler_TCP(t *testing.T) { return } - assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) diff --git a/pkg/api/handler_test.go b/pkg/api/handler_test.go index 1dd55ebdb..7bca3921a 100644 --- a/pkg/api/handler_test.go +++ b/pkg/api/handler_test.go @@ -143,7 +143,7 @@ func TestHandler_RawData(t *testing.T) { require.NoError(t, err) assert.Equal(t, test.expected.statusCode, resp.StatusCode) - assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) diff --git a/pkg/api/handler_udp_test.go b/pkg/api/handler_udp_test.go index 4a5c0116f..b091f8e1d 100644 --- a/pkg/api/handler_udp_test.go +++ b/pkg/api/handler_udp_test.go @@ -510,7 +510,7 @@ func TestHandler_UDP(t *testing.T) { return } - assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") + assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) diff --git a/pkg/healthcheck/healthcheck_test.go b/pkg/healthcheck/healthcheck_test.go index 4c30f8f31..5b1ba2f39 100644 --- a/pkg/healthcheck/healthcheck_test.go +++ b/pkg/healthcheck/healthcheck_test.go @@ -21,6 +21,8 @@ const ( healthCheckTimeout = 100 * time.Millisecond ) +const delta float64 = 1e-10 + type testHandler struct { done func() healthSequence []int @@ -149,7 +151,7 @@ func TestSetBackendsConfiguration(t *testing.T) { assert.Equal(t, test.expectedNumRemovedServers, lb.numRemovedServers, "removed servers") assert.Equal(t, test.expectedNumUpsertedServers, lb.numUpsertedServers, "upserted servers") - assert.Equal(t, test.expectedGaugeValue, collectingMetrics.GaugeValue, "ServerUp Gauge") + assert.InDelta(t, test.expectedGaugeValue, collectingMetrics.GaugeValue, delta, "ServerUp Gauge") }) } } @@ -402,7 +404,7 @@ func TestBalancers_Servers(t *testing.T) { want, err := url.Parse("http://foo.com") require.NoError(t, err) - assert.Equal(t, 1, len(balancers.Servers())) + assert.Len(t, balancers.Servers(), 1) assert.Equal(t, want, balancers.Servers()[0]) } @@ -421,10 +423,10 @@ func TestBalancers_UpsertServer(t *testing.T) { err = balancers.UpsertServer(want) require.NoError(t, err) - assert.Equal(t, 1, len(balancer1.Servers())) + assert.Len(t, balancer1.Servers(), 1) assert.Equal(t, want, balancer1.Servers()[0]) - assert.Equal(t, 1, len(balancer2.Servers())) + assert.Len(t, balancer2.Servers(), 1) assert.Equal(t, want, balancer2.Servers()[0]) } @@ -449,8 +451,8 @@ func TestBalancers_RemoveServer(t *testing.T) { err = balancers.RemoveServer(server) require.NoError(t, err) - assert.Equal(t, 0, len(balancer1.Servers())) - assert.Equal(t, 0, len(balancer2.Servers())) + assert.Empty(t, balancer1.Servers()) + assert.Empty(t, balancer2.Servers()) } type testLoadBalancer struct { @@ -541,23 +543,23 @@ func TestLBStatusUpdater(t *testing.T) { assert.NoError(t, err) err = lbsu.UpsertServer(newServer, roundrobin.Weight(1)) assert.NoError(t, err) - assert.Equal(t, len(lbsu.Servers()), 1) - assert.Equal(t, len(lbsu.BalancerHandler.(*testLoadBalancer).Options()), 1) + assert.Len(t, lbsu.Servers(), 1) + assert.Len(t, lbsu.BalancerHandler.(*testLoadBalancer).Options(), 1) statuses := svInfo.GetAllStatus() - assert.Equal(t, len(statuses), 1) + assert.Len(t, statuses, 1) for k, v := range statuses { - assert.Equal(t, k, newServer.String()) - assert.Equal(t, v, serverUp) + assert.Equal(t, newServer.String(), k) + assert.Equal(t, serverUp, v) break } err = lbsu.RemoveServer(newServer) assert.NoError(t, err) - assert.Equal(t, len(lbsu.Servers()), 0) + assert.Empty(t, lbsu.Servers()) statuses = svInfo.GetAllStatus() - assert.Equal(t, len(statuses), 1) + assert.Len(t, statuses, 1) for k, v := range statuses { - assert.Equal(t, k, newServer.String()) - assert.Equal(t, v, serverDown) + assert.Equal(t, newServer.String(), k) + assert.Equal(t, serverDown, v) break } } diff --git a/pkg/log/log.go b/pkg/log/log.go index 999a5e1fd..d71c28d71 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -18,7 +18,7 @@ const ( // Logger the Traefik logger. type Logger interface { logrus.FieldLogger - WriterLevel(logrus.Level) *io.PipeWriter + WriterLevel(level logrus.Level) *io.PipeWriter } var ( diff --git a/pkg/metrics/prometheus_test.go b/pkg/metrics/prometheus_test.go index e347e1e5c..33b6ba80d 100644 --- a/pkg/metrics/prometheus_test.go +++ b/pkg/metrics/prometheus_test.go @@ -427,12 +427,12 @@ func TestPrometheus(t *testing.T) { return } - for _, label := range family.Metric[0].Label { - val, ok := test.labels[*label.Name] + for _, label := range family.GetMetric()[0].GetLabel() { + val, ok := test.labels[label.GetName()] if !ok { - t.Errorf("%q metric contains unexpected label %q", test.name, *label.Name) - } else if val != *label.Value { - t.Errorf("label %q in metric %q has wrong value %q, expected %q", *label.Name, test.name, *label.Value, val) + t.Errorf("%q metric contains unexpected label %q", test.name, label.GetName()) + } else if val != label.GetValue() { + t.Errorf("label %q in metric %q has wrong value %q, expected %q", label.GetName(), test.name, label.GetValue(), val) } } test.assert(family) @@ -683,7 +683,7 @@ func findMetricByLabelNamesValues(family *dto.MetricFamily, labelNamesValues ... return nil } - for _, metric := range family.Metric { + for _, metric := range family.GetMetric() { if hasMetricAllLabelPairs(metric, labelNamesValues...) { return metric } @@ -703,7 +703,7 @@ func hasMetricAllLabelPairs(metric *dto.Metric, labelNamesValues ...string) bool } func hasMetricLabelPair(metric *dto.Metric, labelName, labelValue string) bool { - for _, labelPair := range metric.Label { + for _, labelPair := range metric.GetLabel() { if labelPair.GetName() == labelName && labelPair.GetValue() == labelValue { return true } @@ -720,12 +720,12 @@ func assertCounterValue(t *testing.T, want float64, family *dto.MetricFamily, la t.Error("metric must not be nil") return } - if metric.Counter == nil { + if metric.GetCounter() == nil { t.Errorf("metric %s must be a counter", family.GetName()) return } - if cv := metric.Counter.GetValue(); cv != want { + if cv := metric.GetCounter().GetValue(); cv != want { t.Errorf("metric %s has value %v, want %v", family.GetName(), cv, want) } } @@ -734,7 +734,7 @@ func buildCounterAssert(t *testing.T, metricName string, expectedValue int) func t.Helper() return func(family *dto.MetricFamily) { - if cv := int(family.Metric[0].Counter.GetValue()); cv != expectedValue { + if cv := int(family.GetMetric()[0].GetCounter().GetValue()); cv != expectedValue { t.Errorf("metric %s has value %d, want %d", metricName, cv, expectedValue) } } @@ -744,7 +744,7 @@ func buildGreaterThanCounterAssert(t *testing.T, metricName string, expectedMinV t.Helper() return func(family *dto.MetricFamily) { - if cv := int(family.Metric[0].Counter.GetValue()); cv < expectedMinValue { + if cv := int(family.GetMetric()[0].GetCounter().GetValue()); cv < expectedMinValue { t.Errorf("metric %s has value %d, want at least %d", metricName, cv, expectedMinValue) } } @@ -754,7 +754,7 @@ func buildHistogramAssert(t *testing.T, metricName string, expectedSampleCount i t.Helper() return func(family *dto.MetricFamily) { - if sc := int(family.Metric[0].Histogram.GetSampleCount()); sc != expectedSampleCount { + if sc := int(family.GetMetric()[0].GetHistogram().GetSampleCount()); sc != expectedSampleCount { t.Errorf("metric %s has sample count value %d, want %d", metricName, sc, expectedSampleCount) } } @@ -764,7 +764,7 @@ func buildGaugeAssert(t *testing.T, metricName string, expectedValue int) func(f t.Helper() return func(family *dto.MetricFamily) { - if gv := int(family.Metric[0].Gauge.GetValue()); gv != expectedValue { + if gv := int(family.GetMetric()[0].GetGauge().GetValue()); gv != expectedValue { t.Errorf("metric %s has value %d, want %d", metricName, gv, expectedValue) } } @@ -774,7 +774,7 @@ func buildTimestampAssert(t *testing.T, metricName string) func(family *dto.Metr t.Helper() return func(family *dto.MetricFamily) { - if ts := time.Unix(int64(family.Metric[0].Gauge.GetValue()), 0); time.Since(ts) > time.Minute { + if ts := time.Unix(int64(family.GetMetric()[0].GetGauge().GetValue()), 0); time.Since(ts) > time.Minute { t.Errorf("metric %s has wrong timestamp %v", metricName, ts) } } diff --git a/pkg/middlewares/accesslog/logger_test.go b/pkg/middlewares/accesslog/logger_test.go index 80bda1530..fec509e32 100644 --- a/pkg/middlewares/accesslog/logger_test.go +++ b/pkg/middlewares/accesslog/logger_test.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "regexp" + "strconv" "strings" "testing" "time" @@ -321,7 +322,7 @@ func TestLoggerJSON(t *testing.T) { ServiceURL: assertString(testServiceName), ClientUsername: assertString(testUsername), ClientHost: assertString(testHostname), - ClientPort: assertString(fmt.Sprintf("%d", testPort)), + ClientPort: assertString(strconv.Itoa(testPort)), ClientAddr: assertString(fmt.Sprintf("%s:%d", testHostname, testPort)), "level": assertString("info"), "msg": assertString(""), @@ -361,7 +362,7 @@ func TestLoggerJSON(t *testing.T) { ServiceURL: assertString(testServiceName), ClientUsername: assertString(testUsername), ClientHost: assertString(testHostname), - ClientPort: assertString(fmt.Sprintf("%d", testPort)), + ClientPort: assertString(strconv.Itoa(testPort)), ClientAddr: assertString(fmt.Sprintf("%s:%d", testHostname, testPort)), "level": assertString("info"), "msg": assertString(""), diff --git a/pkg/middlewares/auth/digest_auth_request_test.go b/pkg/middlewares/auth/digest_auth_request_test.go index 7101016c8..95916d36f 100644 --- a/pkg/middlewares/auth/digest_auth_request_test.go +++ b/pkg/middlewares/auth/digest_auth_request_test.go @@ -137,5 +137,5 @@ func (r *digestRequest) makeAuthorization(req *http.Request, parts map[string]st func generateRandom(n int) string { b := make([]byte, 8) _, _ = io.ReadFull(rand.Reader, b) - return fmt.Sprintf("%x", b)[:n] + return hex.EncodeToString(b)[:n] } diff --git a/pkg/middlewares/capture/capture_test.go b/pkg/middlewares/capture/capture_test.go index f8652e423..776dd74d8 100644 --- a/pkg/middlewares/capture/capture_test.go +++ b/pkg/middlewares/capture/capture_test.go @@ -165,7 +165,7 @@ func runBenchmark(b *testing.B, size int, req *http.Request, handler http.Handle b.Fatalf("Expected 200 but got %d", code) } - assert.Equal(b, size, len(recorder.Body.String())) + assert.Len(b, recorder.Body.String(), size) } func generateBytes(length int) []byte { diff --git a/pkg/middlewares/compress/compress_test.go b/pkg/middlewares/compress/compress_test.go index 4a1fd2196..10f07fda0 100644 --- a/pkg/middlewares/compress/compress_test.go +++ b/pkg/middlewares/compress/compress_test.go @@ -424,7 +424,7 @@ func Test1xxResponses(t *testing.T) { req.Header.Add(acceptEncodingHeader, gzipValue) res, err := frontendClient.Do(req) - assert.Nil(t, err) + assert.NoError(t, err) defer res.Body.Close() diff --git a/pkg/middlewares/customerrors/custom_errors_test.go b/pkg/middlewares/customerrors/custom_errors_test.go index 84e3579b7..2b5f5d9a2 100644 --- a/pkg/middlewares/customerrors/custom_errors_test.go +++ b/pkg/middlewares/customerrors/custom_errors_test.go @@ -253,7 +253,7 @@ func Test1xxResponses(t *testing.T) { req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, server.URL, nil) res, err := frontendClient.Do(req) - assert.Nil(t, err) + assert.NoError(t, err) defer res.Body.Close() diff --git a/pkg/middlewares/headers/headers_test.go b/pkg/middlewares/headers/headers_test.go index c345efd60..ceef014dd 100644 --- a/pkg/middlewares/headers/headers_test.go +++ b/pkg/middlewares/headers/headers_test.go @@ -182,7 +182,7 @@ func Test1xxResponses(t *testing.T) { req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, server.URL, nil) res, err := frontendClient.Do(req) - assert.Nil(t, err) + assert.NoError(t, err) defer res.Body.Close() diff --git a/pkg/middlewares/pipelining/pipelining_test.go b/pkg/middlewares/pipelining/pipelining_test.go index 181fcb328..80a03d2d6 100644 --- a/pkg/middlewares/pipelining/pipelining_test.go +++ b/pkg/middlewares/pipelining/pipelining_test.go @@ -134,7 +134,7 @@ func Test1xxResponses(t *testing.T) { req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, server.URL, nil) res, err := frontendClient.Do(req) - assert.Nil(t, err) + assert.NoError(t, err) defer res.Body.Close() diff --git a/pkg/middlewares/ratelimiter/rate_limiter_test.go b/pkg/middlewares/ratelimiter/rate_limiter_test.go index 670561774..51a077819 100644 --- a/pkg/middlewares/ratelimiter/rate_limiter_test.go +++ b/pkg/middlewares/ratelimiter/rate_limiter_test.go @@ -18,6 +18,8 @@ import ( "golang.org/x/time/rate" ) +const delta float64 = 1e-10 + func TestNewRateLimiter(t *testing.T) { testCases := []struct { desc string @@ -131,7 +133,7 @@ func TestNewRateLimiter(t *testing.T) { assert.Equal(t, test.requestHeader, hd) } if test.expectedRTL != 0 { - assert.Equal(t, test.expectedRTL, rtl.rate) + assert.InDelta(t, float64(test.expectedRTL), float64(rtl.rate), delta) } }) } diff --git a/pkg/middlewares/retry/retry_test.go b/pkg/middlewares/retry/retry_test.go index 75ef5831b..8da95f8e1 100644 --- a/pkg/middlewares/retry/retry_test.go +++ b/pkg/middlewares/retry/retry_test.go @@ -373,7 +373,7 @@ func Test1xxResponses(t *testing.T) { req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, server.URL, nil) res, err := frontendClient.Do(req) - assert.Nil(t, err) + assert.NoError(t, err) defer res.Body.Close() diff --git a/pkg/middlewares/tracing/forwarder_test.go b/pkg/middlewares/tracing/forwarder_test.go index 1253412d3..6eab47432 100644 --- a/pkg/middlewares/tracing/forwarder_test.go +++ b/pkg/middlewares/tracing/forwarder_test.go @@ -123,7 +123,7 @@ func TestNewForwarder(t *testing.T) { tags := span.Tags assert.Equal(t, test.expected.Tags, tags) - assert.True(t, len(test.expected.OperationName) <= test.spanNameLimit, + assert.LessOrEqual(t, len(test.expected.OperationName), test.spanNameLimit, "the len of the operation name %q [len: %d] doesn't respect limit %d", test.expected.OperationName, len(test.expected.OperationName), test.spanNameLimit) assert.Equal(t, test.expected.OperationName, span.OpName) diff --git a/pkg/muxer/tcp/mux_test.go b/pkg/muxer/tcp/mux_test.go index f33398ef5..827d295b1 100644 --- a/pkg/muxer/tcp/mux_test.go +++ b/pkg/muxer/tcp/mux_test.go @@ -548,7 +548,7 @@ func Test_addTCPRoute(t *testing.T) { matchingHandler.ServeTCP(conn) n, ok := conn.call[msg] - assert.Equal(t, n, 1) + assert.Equal(t, 1, n) assert.True(t, ok) }) } diff --git a/pkg/plugins/client.go b/pkg/plugins/client.go index 4fcdd1ab4..4e0540be2 100644 --- a/pkg/plugins/client.go +++ b/pkg/plugins/client.go @@ -4,6 +4,7 @@ import ( zipa "archive/zip" "context" "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -423,5 +424,5 @@ func computeHash(filepath string) (string, error) { sum := hash.Sum(nil) - return fmt.Sprintf("%x", sum), nil + return hex.EncodeToString(sum), nil } diff --git a/pkg/provider/acme/provider.go b/pkg/provider/acme/provider.go index 20b1aa343..451ee83b1 100644 --- a/pkg/provider/acme/provider.go +++ b/pkg/provider/acme/provider.go @@ -30,6 +30,8 @@ import ( "github.com/traefik/traefik/v2/pkg/version" ) +const resolverSuffix = ".acme" + // ocspMustStaple enables OCSP stapling as from https://github.com/go-acme/lego/issues/270. var ocspMustStaple = false @@ -131,7 +133,7 @@ func (p *Provider) ListenConfiguration(config dynamic.Configuration) { // Init for compatibility reason the BaseProvider implements an empty Init. func (p *Provider) Init() error { - ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+".acme")) + ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+resolverSuffix)) logger := log.FromContext(ctx) if len(p.Configuration.Storage) == 0 { @@ -195,7 +197,7 @@ func (p *Provider) ThrottleDuration() time.Duration { // using the given Configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { ctx := log.With(context.Background(), - log.Str(log.ProviderName, p.ResolverName+".acme"), + log.Str(log.ProviderName, p.ResolverName+resolverSuffix), log.Str("ACME CA", p.Configuration.CAServer)) p.pool = pool @@ -236,7 +238,7 @@ func (p *Provider) getClient() (*lego.Client, error) { p.clientMutex.Lock() defer p.clientMutex.Unlock() - ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+".acme")) + ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+resolverSuffix)) logger := log.FromContext(ctx) if p.client != nil { @@ -406,7 +408,7 @@ func (p *Provider) resolveDomains(ctx context.Context, domains []string, tlsStor } func (p *Provider) watchNewDomains(ctx context.Context) { - ctx = log.With(ctx, log.Str(log.ProviderName, p.ResolverName+".acme")) + ctx = log.With(ctx, log.Str(log.ProviderName, p.ResolverName+resolverSuffix)) p.pool.GoCtx(func(ctxPool context.Context) { for { select { @@ -765,7 +767,7 @@ func deleteUnnecessaryDomains(ctx context.Context, domains []types.Domain) []typ func (p *Provider) buildMessage() dynamic.Message { conf := dynamic.Message{ - ProviderName: p.ResolverName + ".acme", + ProviderName: p.ResolverName + resolverSuffix, Configuration: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, diff --git a/pkg/provider/acme/provider_test.go b/pkg/provider/acme/provider_test.go index 3cd024c77..2a55de2c9 100644 --- a/pkg/provider/acme/provider_test.go +++ b/pkg/provider/acme/provider_test.go @@ -580,7 +580,7 @@ func TestInitAccount(t *testing.T) { acmeProvider := Provider{account: test.account, Configuration: &Configuration{Email: test.email, KeyType: test.keyType}} actualAccount, err := acmeProvider.initAccount(context.Background()) - assert.Nil(t, err, "Init account in error") + assert.NoError(t, err, "Init account in error") assert.Equal(t, test.expectedAccount.Email, actualAccount.Email, "unexpected email account") assert.Equal(t, test.expectedAccount.KeyType, actualAccount.KeyType, "unexpected keyType account") }) diff --git a/pkg/provider/acme/store.go b/pkg/provider/acme/store.go index 6fe899574..986510525 100644 --- a/pkg/provider/acme/store.go +++ b/pkg/provider/acme/store.go @@ -8,8 +8,8 @@ type StoredData struct { // Store is a generic interface that represents a storage. type Store interface { - GetAccount(string) (*Account, error) - SaveAccount(string, *Account) error - GetCertificates(string) ([]*CertAndStore, error) - SaveCertificates(string, []*CertAndStore) error + GetAccount(resolverName string) (*Account, error) + SaveAccount(resolverName string, account *Account) error + GetCertificates(resolverName string) ([]*CertAndStore, error) + SaveCertificates(resolverName string, certificates []*CertAndStore) error } diff --git a/pkg/provider/file/file_test.go b/pkg/provider/file/file_test.go index 20d74d2d9..cf40d7032 100644 --- a/pkg/provider/file/file_test.go +++ b/pkg/provider/file/file_test.go @@ -145,10 +145,10 @@ func TestProvideWithWatch(t *testing.T) { require.NotNil(t, conf.Configuration.HTTP) numServices := len(conf.Configuration.HTTP.Services) + len(conf.Configuration.TCP.Services) + len(conf.Configuration.UDP.Services) numRouters := len(conf.Configuration.HTTP.Routers) + len(conf.Configuration.TCP.Routers) + len(conf.Configuration.UDP.Routers) - assert.Equal(t, numServices, 0) - assert.Equal(t, numRouters, 0) + assert.Equal(t, 0, numServices) + assert.Equal(t, 0, numRouters) require.NotNil(t, conf.Configuration.TLS) - assert.Len(t, conf.Configuration.TLS.Certificates, 0) + assert.Empty(t, conf.Configuration.TLS.Certificates) case <-timeout: t.Errorf("timeout while waiting for config") } diff --git a/pkg/provider/http/http_test.go b/pkg/provider/http/http_test.go index 19759c8b7..d63a3cacc 100644 --- a/pkg/provider/http/http_test.go +++ b/pkg/provider/http/http_test.go @@ -251,5 +251,5 @@ func TestProvider_ProvideConfigurationOnlyOnceIfUnchanged(t *testing.T) { time.Sleep(time.Second) - assert.Equal(t, 1, len(configurationChan)) + assert.Len(t, configurationChan, 1) } diff --git a/pkg/provider/kubernetes/crd/kubernetes_test.go b/pkg/provider/kubernetes/crd/kubernetes_test.go index e9620c122..389b9a659 100644 --- a/pkg/provider/kubernetes/crd/kubernetes_test.go +++ b/pkg/provider/kubernetes/crd/kubernetes_test.go @@ -6551,7 +6551,7 @@ func TestCreateBasicAuthCredentials(t *testing.T) { username = components[0] hashedPassword = components[1] - assert.Equal(t, username, "test2") - assert.Equal(t, hashedPassword, "$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0") + assert.Equal(t, "test2", username) + assert.Equal(t, "$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0", hashedPassword) assert.True(t, auth.CheckSecret("test2", hashedPassword)) } diff --git a/pkg/provider/kubernetes/gateway/kubernetes_test.go b/pkg/provider/kubernetes/gateway/kubernetes_test.go index 2f13d0d9f..6fdfd82f0 100644 --- a/pkg/provider/kubernetes/gateway/kubernetes_test.go +++ b/pkg/provider/kubernetes/gateway/kubernetes_test.go @@ -5204,7 +5204,7 @@ func Test_getAllowedRoutes(t *testing.T) { return } - require.Len(t, conditions, 0) + require.Empty(t, conditions) assert.Equal(t, test.wantKinds, got) }) } diff --git a/pkg/provider/kubernetes/ingress/convert.go b/pkg/provider/kubernetes/ingress/convert.go index b0274d660..25bfa6dc8 100644 --- a/pkg/provider/kubernetes/ingress/convert.go +++ b/pkg/provider/kubernetes/ingress/convert.go @@ -13,7 +13,7 @@ type marshaler interface { } type unmarshaler interface { - Unmarshal([]byte) error + Unmarshal(data []byte) error } type LoadBalancerIngress interface { diff --git a/pkg/provider/kubernetes/ingress/kubernetes.go b/pkg/provider/kubernetes/ingress/kubernetes.go index 8e5105a4e..7b43ead4f 100644 --- a/pkg/provider/kubernetes/ingress/kubernetes.go +++ b/pkg/provider/kubernetes/ingress/kubernetes.go @@ -319,7 +319,7 @@ func (p *Provider) loadConfigurationFromIngresses(ctx context.Context, client Cl portString := pa.Backend.Service.Port.Name if len(pa.Backend.Service.Port.Name) == 0 { - portString = fmt.Sprint(pa.Backend.Service.Port.Number) + portString = strconv.Itoa(int(pa.Backend.Service.Port.Number)) } serviceName := provider.Normalize(ingress.Namespace + "-" + pa.Backend.Service.Name + "-" + portString) diff --git a/pkg/server/configurationwatcher_test.go b/pkg/server/configurationwatcher_test.go index da8d39c4d..c65e6acf6 100644 --- a/pkg/server/configurationwatcher_test.go +++ b/pkg/server/configurationwatcher_test.go @@ -265,7 +265,7 @@ func TestListenProvidersThrottleProviderConfigReload(t *testing.T) { providerAggregator := aggregator.ProviderAggregator{} err := providerAggregator.AddProvider(pvd) - assert.Nil(t, err) + assert.NoError(t, err) watcher := NewConfigurationWatcher(routinesPool, providerAggregator, []string{}, "") @@ -340,7 +340,7 @@ func TestListenProvidersSkipsSameConfigurationForProvider(t *testing.T) { // give some time so that the configuration can be processed time.Sleep(100 * time.Millisecond) - assert.Equal(t, configurationReloads, 1, "Same configuration should not be published multiple times") + assert.Equal(t, 1, configurationReloads, "Same configuration should not be published multiple times") } func TestListenProvidersDoesNotSkipFlappingConfiguration(t *testing.T) { @@ -447,7 +447,7 @@ func TestListenProvidersIgnoreSameConfig(t *testing.T) { providerAggregator := aggregator.ProviderAggregator{} err := providerAggregator.AddProvider(pvd) - assert.Nil(t, err) + assert.NoError(t, err) watcher := NewConfigurationWatcher(routinesPool, providerAggregator, []string{"defaultEP"}, "") @@ -589,7 +589,7 @@ func TestListenProvidersIgnoreIntermediateConfigs(t *testing.T) { providerAggregator := aggregator.ProviderAggregator{} err := providerAggregator.AddProvider(pvd) - assert.Nil(t, err) + assert.NoError(t, err) watcher := NewConfigurationWatcher(routinesPool, providerAggregator, []string{"defaultEP"}, "") diff --git a/pkg/server/router/tcp/router_test.go b/pkg/server/router/tcp/router_test.go index 64753a0ea..9937da973 100644 --- a/pkg/server/router/tcp/router_test.go +++ b/pkg/server/router/tcp/router_test.go @@ -618,12 +618,12 @@ func Test_Routing(t *testing.T) { err := check.checkRouter(epListener.Addr().String(), timeout) if check.expectedError != "" { - require.NotNil(t, err, check.desc) + require.Error(t, err, check.desc) assert.Contains(t, err.Error(), check.expectedError, check.desc) continue } - assert.Nil(t, err, check.desc) + assert.NoError(t, err, check.desc) } epListener.Close() diff --git a/pkg/server/server_entrypoint_tcp.go b/pkg/server/server_entrypoint_tcp.go index a3f389605..b33c955ee 100644 --- a/pkg/server/server_entrypoint_tcp.go +++ b/pkg/server/server_entrypoint_tcp.go @@ -499,7 +499,7 @@ func (c *connectionTracker) Close() { } type stoppable interface { - Shutdown(context.Context) error + Shutdown(ctx context.Context) error Close() error } diff --git a/pkg/server/service/loadbalancer/mirror/mirror_test.go b/pkg/server/service/loadbalancer/mirror/mirror_test.go index eda49a960..430baac8f 100644 --- a/pkg/server/service/loadbalancer/mirror/mirror_test.go +++ b/pkg/server/service/loadbalancer/mirror/mirror_test.go @@ -98,7 +98,7 @@ func TestHijack(t *testing.T) { var mirrorRequest bool err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { hijacker, ok := rw.(http.Hijacker) - assert.Equal(t, true, ok) + assert.True(t, ok) _, _, err := hijacker.Hijack() assert.Error(t, err) @@ -109,7 +109,7 @@ func TestHijack(t *testing.T) { mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) pool.Stop() - assert.Equal(t, true, mirrorRequest) + assert.True(t, mirrorRequest) } func TestFlush(t *testing.T) { @@ -122,7 +122,7 @@ func TestFlush(t *testing.T) { var mirrorRequest bool err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { hijacker, ok := rw.(http.Flusher) - assert.Equal(t, true, ok) + assert.True(t, ok) hijacker.Flush() @@ -133,7 +133,7 @@ func TestFlush(t *testing.T) { mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) pool.Stop() - assert.Equal(t, true, mirrorRequest) + assert.True(t, mirrorRequest) } func TestMirroringWithBody(t *testing.T) { @@ -233,7 +233,7 @@ func TestCloneRequest(t *testing.T) { _, expectedBytes, err := newReusableRequest(req, 2) assert.Error(t, err) - assert.Equal(t, bb[:3], expectedBytes) + assert.Equal(t, expectedBytes, bb[:3]) }) t.Run("valid case with maxBodySize", func(t *testing.T) { @@ -258,7 +258,7 @@ func TestCloneRequest(t *testing.T) { rr, expectedBytes, err := newReusableRequest(req, 20) assert.NoError(t, err) assert.Nil(t, expectedBytes) - assert.Len(t, rr.body, 0) + assert.Empty(t, rr.body) }) t.Run("no request given", func(t *testing.T) { diff --git a/pkg/server/service/proxy_websocket_test.go b/pkg/server/service/proxy_websocket_test.go index 84e6a1aef..108133c37 100644 --- a/pkg/server/service/proxy_websocket_test.go +++ b/pkg/server/service/proxy_websocket_test.go @@ -56,7 +56,7 @@ func TestWebSocketTCPClose(t *testing.T) { serverErr := <-errChan var wsErr *gorillawebsocket.CloseError - require.True(t, errors.As(serverErr, &wsErr)) + require.ErrorAs(t, serverErr, &wsErr) assert.Equal(t, 1006, wsErr.Code) } diff --git a/pkg/server/service/service_test.go b/pkg/server/service/service_test.go index 617b3569a..0ff7e86ae 100644 --- a/pkg/server/service/service_test.go +++ b/pkg/server/service/service_test.go @@ -417,7 +417,7 @@ func Test1xxResponses(t *testing.T) { }, } handler, err := sm.getLoadBalancerServiceHandler(context.Background(), "foobar", config) - assert.Nil(t, err) + assert.NoError(t, err) frontend := httptest.NewServer(handler) t.Cleanup(frontend.Close) @@ -463,7 +463,7 @@ func Test1xxResponses(t *testing.T) { req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, frontend.URL, nil) res, err := frontendClient.Do(req) - assert.Nil(t, err) + assert.NoError(t, err) defer res.Body.Close() diff --git a/pkg/tls/tlsmanager_test.go b/pkg/tls/tlsmanager_test.go index 08acf04a2..983ab2401 100644 --- a/pkg/tls/tlsmanager_test.go +++ b/pkg/tls/tlsmanager_test.go @@ -173,7 +173,7 @@ func TestManager_Get(t *testing.T) { } require.NoError(t, err) - assert.Equal(t, config.MinVersion, test.expectedMinVersion) + assert.Equal(t, test.expectedMinVersion, config.MinVersion) }) } } @@ -317,10 +317,10 @@ func TestClientAuth(t *testing.T) { if test.expectedRawSubject != nil { subjects := config.ClientCAs.Subjects() assert.Len(t, subjects, 1) - assert.Equal(t, subjects[0], test.expectedRawSubject) + assert.Equal(t, test.expectedRawSubject, subjects[0]) } - assert.Equal(t, config.ClientAuth, test.expectedClientAuth) + assert.Equal(t, test.expectedClientAuth, config.ClientAuth) }) } } @@ -330,9 +330,9 @@ func TestManager_Get_DefaultValues(t *testing.T) { // Ensures we won't break things for Traefik users when updating Go config, _ := tlsManager.Get("default", "default") - assert.Equal(t, config.MinVersion, uint16(tls.VersionTLS12)) - assert.Equal(t, config.NextProtos, []string{"h2", "http/1.1", "acme-tls/1"}) - assert.Equal(t, config.CipherSuites, []uint16{ + assert.Equal(t, uint16(tls.VersionTLS12), config.MinVersion) + assert.Equal(t, []string{"h2", "http/1.1", "acme-tls/1"}, config.NextProtos) + assert.Equal(t, []uint16{ tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, tls.TLS_RSA_WITH_AES_128_GCM_SHA256, @@ -350,5 +350,5 @@ func TestManager_Get_DefaultValues(t *testing.T) { tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, - }) + }, config.CipherSuites) } diff --git a/pkg/tracing/operation_name.go b/pkg/tracing/operation_name.go index e6194e31e..5bf339896 100644 --- a/pkg/tracing/operation_name.go +++ b/pkg/tracing/operation_name.go @@ -2,7 +2,7 @@ package tracing import ( "crypto/sha256" - "fmt" + "encoding/hex" "strings" "github.com/traefik/traefik/v2/pkg/log" @@ -61,5 +61,5 @@ func computeHash(name string) string { log.WithoutContext().WithField("OperationName", name).Errorf("Failed to create Span name hash for %s: %v", name, err) } - return fmt.Sprintf("%x", hash.Sum(nil))[:TraceNameHashLength] + return hex.EncodeToString(hash.Sum(nil))[:TraceNameHashLength] } diff --git a/pkg/tracing/operation_name_test.go b/pkg/tracing/operation_name_test.go index dd9542c67..daae56806 100644 --- a/pkg/tracing/operation_name_test.go +++ b/pkg/tracing/operation_name_test.go @@ -129,7 +129,7 @@ func TestTruncateString(t *testing.T) { actual := truncateString(test.text, test.limit) assert.Equal(t, test.expected, actual) - assert.True(t, len(actual) <= test.limit) + assert.LessOrEqual(t, len(actual), test.limit) }) } } diff --git a/pkg/udp/conn_test.go b/pkg/udp/conn_test.go index 6351e3309..44e748474 100644 --- a/pkg/udp/conn_test.go +++ b/pkg/udp/conn_test.go @@ -220,10 +220,10 @@ func testTimeout(t *testing.T, withRead bool) { time.Sleep(10 * time.Millisecond) - assert.Equal(t, 10, len(ln.conns)) + assert.Len(t, ln.conns, 10) time.Sleep(ln.timeout + time.Second) - assert.Equal(t, 0, len(ln.conns)) + assert.Empty(t, ln.conns) } func TestShutdown(t *testing.T) {