From 4f03b8fb2530adcbd19133b4981d11655e97fa29 Mon Sep 17 00:00:00 2001 From: Anton Troshin Date: Tue, 7 Jan 2025 19:48:33 -0600 Subject: [PATCH] adjust golangci-lint settings and fix lint issues Signed-off-by: Anton Troshin --- .golangci.yml | 40 +++++++++---------- cmd/dashboard.go | 2 +- cmd/mtls.go | 2 +- cmd/renew_certificate.go | 6 +-- cmd/run.go | 10 ++--- pkg/kubernetes/annotator_test.go | 3 +- pkg/kubernetes/components_test.go | 4 +- pkg/kubernetes/configurations_test.go | 4 +- pkg/kubernetes/kubernetes.go | 16 ++++---- pkg/kubernetes/pods_test.go | 8 ++-- pkg/kubernetes/portforward.go | 3 +- pkg/kubernetes/renew_certificate.go | 10 ++--- pkg/kubernetes/run.go | 2 +- pkg/kubernetes/status.go | 1 - pkg/kubernetes/status_test.go | 32 +++++++-------- pkg/kubernetes/uninstall.go | 2 +- pkg/kubernetes/upgrade.go | 20 +++++----- pkg/rundata/rundata.go | 2 +- pkg/runexec/runexec.go | 8 ++-- pkg/runexec/runexec_test.go | 24 +++++------ pkg/runfileconfig/run_file_config_parser.go | 5 +-- .../run_file_config_parser_test.go | 12 +++--- pkg/standalone/container.go | 3 -- pkg/standalone/dashboard_test.go | 8 ++-- pkg/standalone/list.go | 2 +- pkg/standalone/publish.go | 4 +- pkg/standalone/publish_test.go | 2 +- pkg/standalone/run.go | 20 +++++----- pkg/standalone/standalone.go | 15 ++++--- pkg/standalone/standalone_test.go | 5 +-- pkg/version/version.go | 9 +++-- pkg/version/version_test.go | 4 +- tests/e2e/common/common.go | 10 ++--- utils/utils_test.go | 10 ----- 34 files changed, 143 insertions(+), 165 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b0b805b93..a7aafd438 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -4,7 +4,7 @@ run: concurrency: 4 # timeout for analysis, e.g. 30s, 5m, default is 1m - deadline: 10m + timeout: 10m # exit code when at least one issue was found, default is 1 issues-exit-code: 1 @@ -16,28 +16,22 @@ run: #build-tags: # - mytag +issues: # which dirs to skip: they won't be analyzed; # can use regexp here: generated.*, regexp is applied on full path; # default value is empty list, but next dirs are always skipped independently # from this option's value: # third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs: + exclude-dirs: - ^pkg.*client.*clientset.*versioned.* - ^pkg.*client.*informers.*externalversions.* - pkg.*mod.*k8s.io.* - # which files to skip: they will be analyzed, but issues from them - # won't be reported. Default value is empty list, but there is - # no need to include all autogenerated files, we confidently recognize - # autogenerated files. If it's not please let us know. - skip-files: [] - # - ".*\\.my\\.go$" - # - lib/bad.go - # output configuration options output: # colored-line-number|line-number|json|tab|checkstyle, default is "colored-line-number" - format: tab + formats: + - format: tab # print lines of code with issue, default is true print-issued-lines: true @@ -71,9 +65,6 @@ linters-settings: statements: 40 govet: - # report about shadowed variables - check-shadowing: true - # settings per analyzer settings: printf: # analyzer name, run `go tool vet help` to see all analyzers @@ -82,13 +73,18 @@ linters-settings: - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + - github.com/dapr/cli/pkg/print.FailureStatusEvent + - github.com/dapr/cli/pkg/print.SuccessStatusEvent + - github.com/dapr/cli/pkg/print.WarningStatusEvent + - github.com/dapr/cli/pkg/print.InfoStatusEvent + - github.com/dapr/cli/pkg/print.StatusEvent + - github.com/dapr/cli/pkg/print.Spinner # enable or disable analyzers by name enable: - atomicalign - enable-all: false - disable: - shadow + enable-all: false disable-all: false revive: # linting errors below this confidence will be ignored, default is 0.8 @@ -106,9 +102,6 @@ linters-settings: gocognit: # minimal code complexity to report, 30 by default (but we recommend 10-20) min-complexity: 10 - maligned: - # print struct with more effective memory layout or not, false by default - suggest-new: true dupl: # tokens count to trigger issue, 150 by default threshold: 100 @@ -141,7 +134,7 @@ linters-settings: # XXX: if you enable this setting, unused will report a lot of false-positives in text editors: # if it's called for subdir of a project it can't find funcs usages. All text editor integrations # with golangci-lint call it on a directory with the changed file. - check-exported: false + exported-fields-are-used: false unparam: # Inspect exported functions, default is false. Set to true if no external program/library imports your code. # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: @@ -216,6 +209,10 @@ linters-settings: # Allow case blocks to end with a whitespace. # Allow declarations (var) to be cuddled. allow-cuddle-declarations: false + testifylint: + disable: + - require-error + linters: fast: false @@ -274,4 +271,5 @@ linters: - exportloopref - execinquery - err113 - - fatcontext \ No newline at end of file + - fatcontext + - forbidigo diff --git a/cmd/dashboard.go b/cmd/dashboard.go index d75be1b42..ae86efcb2 100644 --- a/cmd/dashboard.go +++ b/cmd/dashboard.go @@ -182,7 +182,7 @@ dapr dashboard -k -p 0 // url for dashboard after port forwarding. webURL := fmt.Sprintf("http://%s", net.JoinHostPort(dashboardHost, fmt.Sprint(portForward.LocalPort))) //nolint: perfsprint - print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Dapr dashboard found in namespace:\t%s", foundNamespace)) + print.InfoStatusEvent(os.Stdout, "Dapr dashboard found in namespace:\t"+foundNamespace) print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Dapr dashboard available at:\t%s\n", webURL)) err = browser.OpenURL(webURL) diff --git a/cmd/mtls.go b/cmd/mtls.go index de7f06a4e..20afcb313 100644 --- a/cmd/mtls.go +++ b/cmd/mtls.go @@ -67,7 +67,7 @@ dapr mtls export -o ./certs } dir, _ := filepath.Abs(exportPath) - print.SuccessStatusEvent(os.Stdout, fmt.Sprintf("Trust certs successfully exported to %s", dir)) + print.SuccessStatusEvent(os.Stdout, "Trust certs successfully exported to "+dir) }, PostRun: func(cmd *cobra.Command, args []string) { kubernetes.CheckForCertExpiry() diff --git a/cmd/renew_certificate.go b/cmd/renew_certificate.go index e3274aeb7..5c5e28191 100644 --- a/cmd/renew_certificate.go +++ b/cmd/renew_certificate.go @@ -103,7 +103,7 @@ dapr mtls renew-cert -k --valid-until --restart print.InfoStatusEvent(os.Stdout, "Using password file to generate root certificate") err = kubernetes.RenewCertificate(kubernetes.RenewCertificateParams{ RootPrivateKeyFilePath: privateKey, - ValidUntil: time.Hour * time.Duration(validUntil*24), + ValidUntil: time.Hour * time.Duration(validUntil*24), //nolint:gosec Timeout: timeout, ImageVariant: imageVariant, }) @@ -113,7 +113,7 @@ dapr mtls renew-cert -k --valid-until --restart } else { print.InfoStatusEvent(os.Stdout, "generating fresh certificates") err = kubernetes.RenewCertificate(kubernetes.RenewCertificateParams{ - ValidUntil: time.Hour * time.Duration(validUntil*24), + ValidUntil: time.Hour * time.Duration(validUntil*24), //nolint:gosec Timeout: timeout, ImageVariant: imageVariant, }) @@ -129,7 +129,7 @@ dapr mtls renew-cert -k --valid-until --restart logErrorAndExit(err) } print.SuccessStatusEvent(os.Stdout, - fmt.Sprintf("Certificate rotation is successful! Your new certicate is valid through %s", expiry.Format(time.RFC1123))) + "Certificate rotation is successful! Your new certicate is valid through "+expiry.Format(time.RFC1123)) if restartDaprServices { restartControlPlaneService() diff --git a/cmd/run.go b/cmd/run.go index 45247cd09..1bbe65c9d 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -319,14 +319,14 @@ dapr run --run-file /path/to/directory -k stdErrPipe, pipeErr := output.AppCMD.StderrPipe() if pipeErr != nil { - print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Error creating stderr for App: %s", err.Error())) + print.FailureStatusEvent(os.Stderr, "Error creating stderr for App: "+err.Error()) appRunning <- false return } stdOutPipe, pipeErr := output.AppCMD.StdoutPipe() if pipeErr != nil { - print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Error creating stdout for App: %s", err.Error())) + print.FailureStatusEvent(os.Stderr, "Error creating stdout for App: "+err.Error()) appRunning <- false return } @@ -335,13 +335,13 @@ dapr run --run-file /path/to/directory -k outScanner := bufio.NewScanner(stdOutPipe) go func() { for errScanner.Scan() { - fmt.Println(print.Blue(fmt.Sprintf("== APP == %s", errScanner.Text()))) + fmt.Println(print.Blue("== APP == " + errScanner.Text())) } }() go func() { for outScanner.Scan() { - fmt.Println(print.Blue(fmt.Sprintf("== APP == %s", outScanner.Text()))) + fmt.Println(print.Blue("== APP == " + outScanner.Text())) } }() @@ -395,7 +395,7 @@ dapr run --run-file /path/to/directory -k } appCommand := strings.Join(args, " ") - print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Updating metadata for app command: %s", appCommand)) + print.InfoStatusEvent(os.Stdout, "Updating metadata for app command: "+appCommand) err = metadata.Put(output.DaprHTTPPort, "appCommand", appCommand, output.AppID, unixDomainSocket) if err != nil { print.WarningStatusEvent(os.Stdout, "Could not update sidecar metadata for appCommand: %s", err.Error()) diff --git a/pkg/kubernetes/annotator_test.go b/pkg/kubernetes/annotator_test.go index e038fc79a..a61bf7386 100644 --- a/pkg/kubernetes/annotator_test.go +++ b/pkg/kubernetes/annotator_test.go @@ -292,7 +292,6 @@ func TestAnnotate(t *testing.T) { var out bytes.Buffer in := []io.Reader{inputFile} for i, annotation := range tt.annotations { - annotation := annotation annotator := NewK8sAnnotator(K8sAnnotatorConfig{ TargetResource: &annotation.targetResource, TargetNamespace: &annotation.targetNamespace, @@ -334,7 +333,7 @@ func TestAnnotate(t *testing.T) { for i := range expectedDocs { if tt.printOutput { - t.Logf(outDocs[i]) + t.Logf(outDocs[i]) //nolint:govet } assert.YAMLEq(t, expectedDocs[i], outDocs[i]) } diff --git a/pkg/kubernetes/components_test.go b/pkg/kubernetes/components_test.go index 3714afb18..1568a9a8d 100644 --- a/pkg/kubernetes/components_test.go +++ b/pkg/kubernetes/components_test.go @@ -15,7 +15,7 @@ package kubernetes import ( "bytes" - "fmt" + "errors" "testing" "github.com/stretchr/testify/assert" @@ -242,7 +242,7 @@ func TestComponents(t *testing.T) { err := writeComponents(&buff, func() (*v1alpha1.ComponentList, error) { if len(tc.errString) > 0 { - return nil, fmt.Errorf(tc.errString) + return nil, errors.New(tc.errString) } return &v1alpha1.ComponentList{Items: tc.k8sConfig}, nil diff --git a/pkg/kubernetes/configurations_test.go b/pkg/kubernetes/configurations_test.go index 93a4c6b59..a48d655bb 100644 --- a/pkg/kubernetes/configurations_test.go +++ b/pkg/kubernetes/configurations_test.go @@ -15,7 +15,7 @@ package kubernetes import ( "bytes" - "fmt" + "errors" "testing" "github.com/stretchr/testify/assert" @@ -221,7 +221,7 @@ func TestConfigurations(t *testing.T) { err := writeConfigurations(&buff, func() (*v1alpha1.ConfigurationList, error) { if len(tc.errString) > 0 { - return nil, fmt.Errorf(tc.errString) + return nil, errors.New(tc.errString) } return &v1alpha1.ConfigurationList{Items: tc.k8sConfig}, nil diff --git a/pkg/kubernetes/kubernetes.go b/pkg/kubernetes/kubernetes.go index 54f79a578..80ae0c2fc 100644 --- a/pkg/kubernetes/kubernetes.go +++ b/pkg/kubernetes/kubernetes.go @@ -249,10 +249,10 @@ func daprChartValues(config InitConfiguration, version string) (map[string]inter helmVals := []string{ fmt.Sprintf("global.ha.enabled=%t", config.EnableHA), fmt.Sprintf("global.mtls.enabled=%t", config.EnableMTLS), - fmt.Sprintf("global.tag=%s", utils.GetVariantVersion(version, config.ImageVariant)), + "global.tag=" + utils.GetVariantVersion(version, config.ImageVariant), } if len(config.ImageRegistryURI) != 0 { - helmVals = append(helmVals, fmt.Sprintf("global.registry=%s", config.ImageRegistryURI)) + helmVals = append(helmVals, "global.registry="+config.ImageRegistryURI) } helmVals = append(helmVals, config.Args...) @@ -265,9 +265,9 @@ func daprChartValues(config InitConfiguration, version string) (map[string]inter if err != nil { return nil, err } - helmVals = append(helmVals, fmt.Sprintf("dapr_sentry.tls.root.certPEM=%s", string(rootCertBytes)), - fmt.Sprintf("dapr_sentry.tls.issuer.certPEM=%s", string(issuerCertBytes)), - fmt.Sprintf("dapr_sentry.tls.issuer.keyPEM=%s", string(issuerKeyBytes)), + helmVals = append(helmVals, "dapr_sentry.tls.root.certPEM="+string(rootCertBytes), + "dapr_sentry.tls.issuer.certPEM="+string(issuerCertBytes), + "dapr_sentry.tls.issuer.keyPEM="+string(issuerKeyBytes), ) } @@ -301,7 +301,7 @@ func install(releaseName, releaseVersion, helmRepo string, config InitConfigurat } if releaseName == daprReleaseName { - err = applyCRDs(fmt.Sprintf("v%s", version)) + err = applyCRDs("v" + version) if err != nil { return err } @@ -311,7 +311,7 @@ func install(releaseName, releaseVersion, helmRepo string, config InitConfigurat installClient.ReleaseName = releaseName installClient.Namespace = config.Namespace installClient.Wait = config.Wait - installClient.Timeout = time.Duration(config.Timeout) * time.Second + installClient.Timeout = time.Duration(config.Timeout) * time.Second //nolint:gosec values, err := daprChartValues(config, version) if err != nil { @@ -340,7 +340,7 @@ func installThirdParty(releaseName, chartName, releaseVersion, helmRepo string, installClient.ReleaseName = releaseName installClient.Namespace = thirdPartyDevNamespace installClient.Wait = config.Wait - installClient.Timeout = time.Duration(config.Timeout) * time.Second + installClient.Timeout = time.Duration(config.Timeout) * time.Second //nolint:gosec values := map[string]interface{}{} diff --git a/pkg/kubernetes/pods_test.go b/pkg/kubernetes/pods_test.go index fe5314047..0e7ffbed1 100644 --- a/pkg/kubernetes/pods_test.go +++ b/pkg/kubernetes/pods_test.go @@ -28,9 +28,9 @@ func TestListPodsInterface(t *testing.T) { output, err := ListPodsInterface(k8s, map[string]string{ "test": "test", }) - assert.Nil(t, err, "unexpected error") + assert.NoError(t, err, "unexpected error") assert.NotNil(t, output, "Expected empty list") - assert.Equal(t, 0, len(output.Items), "Expected length 0") + assert.Empty(t, output.Items, "Expected length 0") }) t.Run("one matching pod", func(t *testing.T) { k8s := fake.NewSimpleClientset((&v1.Pod{ @@ -46,9 +46,9 @@ func TestListPodsInterface(t *testing.T) { output, err := ListPodsInterface(k8s, map[string]string{ "test": "test", }) - assert.Nil(t, err, "unexpected error") + assert.NoError(t, err, "unexpected error") assert.NotNil(t, output, "Expected non empty list") - assert.Equal(t, 1, len(output.Items), "Expected length 0") + assert.Len(t, output.Items, 1, "Expected length 0") assert.Equal(t, "test", output.Items[0].Name, "expected name to match") assert.Equal(t, "test", output.Items[0].Namespace, "expected namespace to match") }) diff --git a/pkg/kubernetes/portforward.go b/pkg/kubernetes/portforward.go index 484b39e1a..67dac72a9 100644 --- a/pkg/kubernetes/portforward.go +++ b/pkg/kubernetes/portforward.go @@ -14,6 +14,7 @@ limitations under the License. package kubernetes import ( + "errors" "fmt" "io" "net/http" @@ -133,7 +134,7 @@ func (pf *PortForward) Init() error { return fmt.Errorf("can not get the local and remote ports: %w", err) } if len(ports) == 0 { - return fmt.Errorf("can not get the local and remote ports: error getting ports length") + return errors.New("can not get the local and remote ports: error getting ports length") } pf.LocalPort = int(ports[0].Local) diff --git a/pkg/kubernetes/renew_certificate.go b/pkg/kubernetes/renew_certificate.go index 28dd49e77..106d7313d 100644 --- a/pkg/kubernetes/renew_certificate.go +++ b/pkg/kubernetes/renew_certificate.go @@ -121,7 +121,7 @@ func renewCertificate(rootCert, issuerCert, issuerKey []byte, timeout uint, imag // Reuse the existing helm configuration values i.e. tags, registry, etc. upgradeClient.ReuseValues = true upgradeClient.Wait = true - upgradeClient.Timeout = time.Duration(timeout) * time.Second + upgradeClient.Timeout = time.Duration(timeout) * time.Second //nolint:gosec upgradeClient.Namespace = status[0].Namespace // Override the helm configuration values with the new certificates. @@ -146,12 +146,12 @@ func createHelmParamsForNewCertificates(ca, issuerCert, issuerKey string) (map[s args := []string{} if ca != "" && issuerCert != "" && issuerKey != "" { - args = append(args, fmt.Sprintf("dapr_sentry.tls.root.certPEM=%s", ca), - fmt.Sprintf("dapr_sentry.tls.issuer.certPEM=%s", issuerCert), - fmt.Sprintf("dapr_sentry.tls.issuer.keyPEM=%s", issuerKey), + args = append(args, "dapr_sentry.tls.root.certPEM="+ca, + "dapr_sentry.tls.issuer.certPEM="+issuerCert, + "dapr_sentry.tls.issuer.keyPEM="+issuerKey, ) } else { - return nil, fmt.Errorf("parameters not found") + return nil, errors.New("parameters not found") } for _, v := range args { diff --git a/pkg/kubernetes/run.go b/pkg/kubernetes/run.go index b8869916e..5297e4b76 100644 --- a/pkg/kubernetes/run.go +++ b/pkg/kubernetes/run.go @@ -317,7 +317,7 @@ func createDeploymentConfig(client versioned.Interface, app runfileconfig.App) d if app.AppPort != 0 { dep.Spec.Template.Spec.Containers[0].Ports = []corev1.ContainerPort{ { - ContainerPort: int32(app.AppPort), + ContainerPort: int32(app.AppPort), //nolint:gosec }, } } diff --git a/pkg/kubernetes/status.go b/pkg/kubernetes/status.go index 3d364c6ee..7061927a5 100644 --- a/pkg/kubernetes/status.go +++ b/pkg/kubernetes/status.go @@ -65,7 +65,6 @@ func NewStatusClient() (*StatusClient, error) { // List status for Dapr resources. func (s *StatusClient) Status() ([]StatusOutput, error) { - //nolint client := s.client if client == nil { return nil, errors.New("kubernetes client not initialized") diff --git a/pkg/kubernetes/status_test.go b/pkg/kubernetes/status_test.go index a2f2778ab..10883a831 100644 --- a/pkg/kubernetes/status_test.go +++ b/pkg/kubernetes/status_test.go @@ -83,7 +83,7 @@ func TestStatus(t *testing.T) { if err != nil { t.Fatalf("%s status should not raise an error", err.Error()) } - assert.Equal(t, 0, len(status), "Expected status to be empty list") + assert.Empty(t, status, "Expected status to be empty list") }) t.Run("one status waiting", func(t *testing.T) { @@ -102,8 +102,8 @@ func TestStatus(t *testing.T) { } k8s := newTestSimpleK8s(newDaprControlPlanePod(pd)) status, err := k8s.Status() - assert.Nil(t, err, "status should not raise an error") - assert.Equal(t, 1, len(status), "Expected status to be non-empty list") + assert.NoError(t, err, "status should not raise an error") + assert.Len(t, status, 1, "Expected status to be non-empty list") stat := status[0] assert.Equal(t, "dapr-dashboard", stat.Name, "expected name to match") assert.Equal(t, "dapr-system", stat.Namespace, "expected namespace to match") @@ -131,8 +131,8 @@ func TestStatus(t *testing.T) { } k8s := newTestSimpleK8s(newDaprControlPlanePod(pd)) status, err := k8s.Status() - assert.Nil(t, err, "status should not raise an error") - assert.Equal(t, 1, len(status), "Expected status to be non-empty list") + assert.NoError(t, err, "status should not raise an error") + assert.Len(t, status, 1, "Expected status to be non-empty list") stat := status[0] assert.Equal(t, "dapr-dashboard", stat.Name, "expected name to match") assert.Equal(t, "dapr-system", stat.Namespace, "expected namespace to match") @@ -140,7 +140,7 @@ func TestStatus(t *testing.T) { assert.Equal(t, "0.0.1", stat.Version, "expected version to match") assert.Equal(t, 1, stat.Replicas, "expected replicas to match") assert.Equal(t, "True", stat.Healthy, "expected health to match") - assert.Equal(t, stat.Status, "Running", "expected running status") + assert.Equal(t, "Running", stat.Status, "expected running status") }) t.Run("one status terminated", func(t *testing.T) { @@ -160,8 +160,8 @@ func TestStatus(t *testing.T) { k8s := newTestSimpleK8s(newDaprControlPlanePod(pd)) status, err := k8s.Status() - assert.Nil(t, err, "status should not raise an error") - assert.Equal(t, 1, len(status), "Expected status to be non-empty list") + assert.NoError(t, err, "status should not raise an error") + assert.Len(t, status, 1, "Expected status to be non-empty list") stat := status[0] assert.Equal(t, "dapr-dashboard", stat.Name, "expected name to match") assert.Equal(t, "dapr-system", stat.Namespace, "expected namespace to match") @@ -169,7 +169,7 @@ func TestStatus(t *testing.T) { assert.Equal(t, "0.0.1", stat.Version, "expected version to match") assert.Equal(t, 1, stat.Replicas, "expected replicas to match") assert.Equal(t, "False", stat.Healthy, "expected health to match") - assert.Equal(t, stat.Status, "Terminated", "expected terminated status") + assert.Equal(t, "Terminated", stat.Status, "expected terminated status") }) t.Run("one status pending", func(t *testing.T) { @@ -193,8 +193,8 @@ func TestStatus(t *testing.T) { k8s := newTestSimpleK8s(pod) status, err := k8s.Status() - assert.Nil(t, err, "status should not raise an error") - assert.Equal(t, 1, len(status), "Expected status to be non-empty list") + assert.NoError(t, err, "status should not raise an error") + assert.Len(t, status, 1, "Expected status to be non-empty list") stat := status[0] assert.Equal(t, "dapr-dashboard", stat.Name, "expected name to match") assert.Equal(t, "dapr-system", stat.Namespace, "expected namespace to match") @@ -202,13 +202,13 @@ func TestStatus(t *testing.T) { assert.Equal(t, "0.0.1", stat.Version, "expected version to match") assert.Equal(t, 1, stat.Replicas, "expected replicas to match") assert.Equal(t, "False", stat.Healthy, "expected health to match") - assert.Equal(t, stat.Status, "Pending", "expected pending status") + assert.Equal(t, "Pending", stat.Status, "expected pending status") }) t.Run("one status empty client", func(t *testing.T) { k8s := &StatusClient{} status, err := k8s.Status() - assert.NotNil(t, err, "status should raise an error") + assert.Error(t, err, "status should raise an error") assert.Equal(t, "kubernetes client not initialized", err.Error(), "expected errors to match") assert.Nil(t, status, "expected nil for status") }) @@ -263,7 +263,7 @@ func TestControlPlaneServices(t *testing.T) { k8s := newTestSimpleK8s(runtimeObj...) status, err := k8s.Status() - assert.Nil(t, err, "status should not raise an error") + assert.NoError(t, err, "status should not raise an error") assert.Equal(t, len(expectedReplicas), len(status), "Expected status to be empty list") @@ -305,8 +305,8 @@ func TestControlPlaneVersion(t *testing.T) { pd.imageURI = tc.imageURI k8s := newTestSimpleK8s(newDaprControlPlanePod(pd)) status, err := k8s.Status() - assert.Nil(t, err, "status should not raise an error") - assert.Equal(t, 1, len(status), "Expected status to be non-empty list") + assert.NoError(t, err, "status should not raise an error") + assert.Len(t, status, 1, "Expected status to be non-empty list") stat := status[0] assert.Equal(t, tc.expectedVersion, stat.Version, "expected version to match") } diff --git a/pkg/kubernetes/uninstall.go b/pkg/kubernetes/uninstall.go index 1ab874dd0..7f1a1555b 100644 --- a/pkg/kubernetes/uninstall.go +++ b/pkg/kubernetes/uninstall.go @@ -41,7 +41,7 @@ func Uninstall(namespace string, uninstallAll bool, uninstallDev bool, timeout u } uninstallClient := helm.NewUninstall(config) - uninstallClient.Timeout = time.Duration(timeout) * time.Second + uninstallClient.Timeout = time.Duration(timeout) * time.Second //nolint:gosec // Uninstall Dashboard as a best effort. // Chart versions < 1.11 for Dapr will delete dashboard as part of the main chart. diff --git a/pkg/kubernetes/upgrade.go b/pkg/kubernetes/upgrade.go index c9ad41a2c..eab2b341c 100644 --- a/pkg/kubernetes/upgrade.go +++ b/pkg/kubernetes/upgrade.go @@ -111,7 +111,7 @@ func Upgrade(conf UpgradeConfig) error { if !hasDashboardInDaprChart && willHaveDashboardInDaprChart && dashboardExists { print.InfoStatusEvent(os.Stdout, "Dashboard being uninstalled prior to Dapr control plane upgrade...") uninstallClient := helm.NewUninstall(helmConf) - uninstallClient.Timeout = time.Duration(conf.Timeout) * time.Second + uninstallClient.Timeout = time.Duration(conf.Timeout) * time.Second //nolint:gosec _, err = uninstallClient.Run(dashboardReleaseName) if err != nil { @@ -157,7 +157,7 @@ func Upgrade(conf UpgradeConfig) error { } if !isDowngrade(conf.RuntimeVersion, daprVersion) { - err = applyCRDs(fmt.Sprintf("v%s", conf.RuntimeVersion)) + err = applyCRDs("v" + conf.RuntimeVersion) if err != nil { return fmt.Errorf("unable to apply CRDs: %w", err) } @@ -240,7 +240,7 @@ func helmUpgrade(client *helm.Upgrade, name string, chart *chart.Chart, vals map // create a totally new helm client, this ensures that we fetch a fresh openapi schema from the server on each attempt. client, _, err = newUpgradeClient(client.Namespace, UpgradeConfig{ - Timeout: uint(client.Timeout), + Timeout: uint(client.Timeout), //nolint:gosec }) if err != nil { return nil, fmt.Errorf("unable to create helm client: %w", err) @@ -267,7 +267,7 @@ func applyCRDs(version string) error { url := fmt.Sprintf("https://raw.githubusercontent.com/dapr/dapr/%s/charts/dapr/crds/%s.yaml", version, crd) resp, _ := http.Get(url) //nolint:gosec - if resp != nil && resp.StatusCode == 200 { + if resp != nil && resp.StatusCode == http.StatusOK { defer resp.Body.Close() _, err := utils.RunCmdAndWait("kubectl", "apply", "-f", url) @@ -286,18 +286,18 @@ func upgradeChartValues(ca, issuerCert, issuerKey string, haMode, mtls bool, con if err != nil { return nil, err } - globalVals = append(globalVals, fmt.Sprintf("global.tag=%s", utils.GetVariantVersion(conf.RuntimeVersion, conf.ImageVariant))) + globalVals = append(globalVals, "global.tag="+utils.GetVariantVersion(conf.RuntimeVersion, conf.ImageVariant)) if mtls && ca != "" && issuerCert != "" && issuerKey != "" { - globalVals = append(globalVals, fmt.Sprintf("dapr_sentry.tls.root.certPEM=%s", ca), - fmt.Sprintf("dapr_sentry.tls.issuer.certPEM=%s", issuerCert), - fmt.Sprintf("dapr_sentry.tls.issuer.keyPEM=%s", issuerKey), + globalVals = append(globalVals, "dapr_sentry.tls.root.certPEM="+ca, + "dapr_sentry.tls.issuer.certPEM="+issuerCert, + "dapr_sentry.tls.issuer.keyPEM="+issuerKey, ) } else { globalVals = append(globalVals, "global.mtls.enabled=false") } if len(conf.ImageRegistryURI) != 0 { - globalVals = append(globalVals, fmt.Sprintf("global.registry=%s", conf.ImageRegistryURI)) + globalVals = append(globalVals, "global.registry="+conf.ImageRegistryURI) } if haMode { globalVals = append(globalVals, "global.ha.enabled=true") @@ -334,7 +334,7 @@ func newUpgradeClient(namespace string, cfg UpgradeConfig) (*helm.Upgrade, *helm client.Namespace = namespace client.CleanupOnFail = true client.Wait = true - client.Timeout = time.Duration(cfg.Timeout) * time.Second + client.Timeout = time.Duration(cfg.Timeout) * time.Second //nolint:gosec return client, helmCfg, nil } diff --git a/pkg/rundata/rundata.go b/pkg/rundata/rundata.go index 3b4e80dcc..93bcf0a34 100644 --- a/pkg/rundata/rundata.go +++ b/pkg/rundata/rundata.go @@ -69,7 +69,7 @@ func tryGetRunDataLock() (*lockfile.Lockfile, error) { return nil, err } - for i := 0; i < 10; i++ { + for range 10 { err = lockFile.TryLock() // Error handling is essential, as we only try to get the lock. diff --git a/pkg/runexec/runexec.go b/pkg/runexec/runexec.go index 4eab89153..908680ffb 100644 --- a/pkg/runexec/runexec.go +++ b/pkg/runexec/runexec.go @@ -14,7 +14,7 @@ limitations under the License. package runexec import ( - "fmt" + "errors" "io" "os" "os/exec" @@ -86,7 +86,7 @@ func (c *CmdProcess) WithOutputWriter(w io.Writer) { // SetStdout should be called after WithOutputWriter. func (c *CmdProcess) SetStdout() error { if c.Command == nil { - return fmt.Errorf("command is nil") + return errors.New("command is nil") } c.Command.Stdout = c.OutputWriter return nil @@ -99,7 +99,7 @@ func (c *CmdProcess) WithErrorWriter(w io.Writer) { // SetStdErr should be called after WithErrorWriter. func (c *CmdProcess) SetStderr() error { if c.Command == nil { - return fmt.Errorf("command is nil") + return errors.New("command is nil") } c.Command.Stderr = c.ErrorWriter return nil @@ -108,7 +108,7 @@ func (c *CmdProcess) SetStderr() error { func NewOutput(config *standalone.RunConfig) (*RunOutput, error) { // set default values from RunConfig struct's tag. config.SetDefaultFromSchema() - //nolint + err := config.Validate() if err != nil { return nil, err diff --git a/pkg/runexec/runexec_test.go b/pkg/runexec/runexec_test.go index 377124e62..8b24a2fc3 100644 --- a/pkg/runexec/runexec_test.go +++ b/pkg/runexec/runexec_test.go @@ -80,10 +80,10 @@ func setupRun(t *testing.T) { componentsDir := standalone.GetDaprComponentsPath(myDaprPath) configFile := standalone.GetDaprConfigPath(myDaprPath) err = os.MkdirAll(componentsDir, 0o700) - assert.Equal(t, nil, err, "Unable to setup components dir before running test") + assert.NoError(t, err, "Unable to setup components dir before running test") file, err := os.Create(configFile) file.Close() - assert.Equal(t, nil, err, "Unable to create config file before running test") + assert.NoError(t, err, "Unable to create config file before running test") } func tearDownRun(t *testing.T) { @@ -94,9 +94,9 @@ func tearDownRun(t *testing.T) { configFile := standalone.GetDaprConfigPath(myDaprPath) err = os.RemoveAll(componentsDir) - assert.Equal(t, nil, err, "Unable to delete default components dir after running test") + assert.NoError(t, err, "Unable to delete default components dir after running test") err = os.Remove(configFile) - assert.Equal(t, nil, err, "Unable to delete default config file after running test") + assert.NoError(t, err, "Unable to delete default config file after running test") } func assertCommonArgs(t *testing.T, basicConfig *standalone.RunConfig, output *RunOutput) { @@ -301,10 +301,10 @@ func TestRun(t *testing.T) { basicConfig.SetDefaultFromSchema() assert.Equal(t, -1, basicConfig.AppPort) - assert.True(t, basicConfig.HTTPPort == -1) - assert.True(t, basicConfig.GRPCPort == -1) - assert.True(t, basicConfig.MetricsPort == -1) - assert.True(t, basicConfig.ProfilePort == -1) + assert.Equal(t, -1, basicConfig.HTTPPort) + assert.Equal(t, -1, basicConfig.GRPCPort) + assert.Equal(t, -1, basicConfig.MetricsPort) + assert.Equal(t, -1, basicConfig.ProfilePort) assert.True(t, basicConfig.EnableProfiling) assert.Equal(t, -1, basicConfig.MaxConcurrency) assert.Equal(t, -1, basicConfig.MaxRequestBodySize) @@ -316,10 +316,10 @@ func TestRun(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 0, basicConfig.AppPort) - assert.True(t, basicConfig.HTTPPort > 0) - assert.True(t, basicConfig.GRPCPort > 0) - assert.True(t, basicConfig.MetricsPort > 0) - assert.True(t, basicConfig.ProfilePort > 0) + assert.Positive(t, basicConfig.HTTPPort) + assert.Positive(t, basicConfig.GRPCPort) + assert.Positive(t, basicConfig.MetricsPort) + assert.Positive(t, basicConfig.ProfilePort) assert.True(t, basicConfig.EnableProfiling) assert.Equal(t, -1, basicConfig.MaxConcurrency) assert.Equal(t, -1, basicConfig.MaxRequestBodySize) diff --git a/pkg/runfileconfig/run_file_config_parser.go b/pkg/runfileconfig/run_file_config_parser.go index c5a857b3e..126334674 100644 --- a/pkg/runfileconfig/run_file_config_parser.go +++ b/pkg/runfileconfig/run_file_config_parser.go @@ -72,7 +72,7 @@ func (a *RunFileConfig) validateRunConfig(runFilePath string) error { a.Common.ResourcesPaths = append(a.Common.ResourcesPaths, a.Common.ResourcesPath) } - for i := 0; i < len(a.Apps); i++ { + for i := range len(a.Apps) { if a.Apps[i].AppDirPath == "" { return errors.New("required field 'appDirPath' not found in the provided app config file") } @@ -223,9 +223,6 @@ func (a *RunFileConfig) resolvePathToAbsAndValidate(baseDir string, paths ...*st return err } absPath := utils.GetAbsPath(baseDir, *path) - if err != nil { - return err - } *path = absPath if err = utils.ValidateFilePath(*path); err != nil { return err diff --git a/pkg/runfileconfig/run_file_config_parser_test.go b/pkg/runfileconfig/run_file_config_parser_test.go index b2df4dd17..dc0a648ba 100644 --- a/pkg/runfileconfig/run_file_config_parser_test.go +++ b/pkg/runfileconfig/run_file_config_parser_test.go @@ -45,7 +45,7 @@ func TestRunConfigFile(t *testing.T) { err := appsRunConfig.parseAppsConfig(validRunFilePath) assert.NoError(t, err) - assert.Equal(t, 2, len(appsRunConfig.Apps)) + assert.Len(t, appsRunConfig.Apps, 2) assert.Equal(t, 1, appsRunConfig.Version) assert.NotEmpty(t, appsRunConfig.Common.ResourcesPath) @@ -64,7 +64,7 @@ func TestRunConfigFile(t *testing.T) { apps, err := config.GetApps(validRunFilePath) assert.NoError(t, err) - assert.Equal(t, 2, len(apps)) + assert.Len(t, apps, 2) assert.Equal(t, "webapp", apps[0].AppID) assert.Equal(t, "backend", apps[1].AppID) assert.Equal(t, "HTTP", apps[0].AppProtocol) @@ -90,8 +90,8 @@ func TestRunConfigFile(t *testing.T) { assert.Equal(t, filepath.Join(apps[1].AppDirPath, ".dapr", "resources"), apps[1].ResourcesPaths[0]) // test merged envs from common and app sections. - assert.Equal(t, 2, len(apps[0].Env)) - assert.Equal(t, 2, len(apps[1].Env)) + assert.Len(t, apps[0].Env, 2) + assert.Len(t, apps[1].Env, 2) assert.Contains(t, apps[0].Env, "DEBUG") assert.Contains(t, apps[0].Env, "tty") assert.Contains(t, apps[1].Env, "DEBUG") @@ -233,7 +233,7 @@ func TestRunConfigFile(t *testing.T) { config := RunFileConfig{} apps, err := config.GetApps(runFileForLogDestination) assert.NoError(t, err) - assert.Equal(t, 6, len(apps)) + assert.Len(t, apps, 6) assert.Equal(t, "file", apps[0].DaprdLogDestination.String()) assert.Equal(t, "fileAndConsole", apps[0].AppLogDestination.String()) @@ -346,7 +346,7 @@ func TestMultiResourcePathsResolution(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.expectedNoOfResources, len(config.Apps[tc.appIndex].ResourcesPaths)) + assert.Len(t, config.Apps[tc.appIndex].ResourcesPaths, tc.expectedNoOfResources) var rsrcFound bool for _, resourcePath := range config.Apps[tc.appIndex].ResourcesPaths { if rsrcFound = strings.Contains(resourcePath, tc.expectedResourcesPathsContains); rsrcFound { diff --git a/pkg/standalone/container.go b/pkg/standalone/container.go index e6371c187..545f7300a 100644 --- a/pkg/standalone/container.go +++ b/pkg/standalone/container.go @@ -85,7 +85,6 @@ func confirmContainerIsRunningOrExists(containerName string, isRunning bool, run // If 'docker ps' failed due to some reason. if err != nil { - //nolint return false, fmt.Errorf("unable to confirm whether %s is running or exists. error\n%v", containerName, err.Error()) } // 'docker ps' worked fine, but the response did not have the container name. @@ -100,7 +99,6 @@ func confirmContainerIsRunningOrExists(containerName string, isRunning bool, run } func isContainerRunError(err error) bool { - //nolint if exitError, ok := err.(*exec.ExitError); ok { exitCode := exitError.ExitCode() return exitCode == 125 @@ -109,7 +107,6 @@ func isContainerRunError(err error) bool { } func parseContainerRuntimeError(component string, err error) error { - //nolint if exitError, ok := err.(*exec.ExitError); ok { exitCode := exitError.ExitCode() if exitCode == 125 { // see https://github.com/moby/moby/pull/14012 diff --git a/pkg/standalone/dashboard_test.go b/pkg/standalone/dashboard_test.go index 3499b1058..5302d71e7 100644 --- a/pkg/standalone/dashboard_test.go +++ b/pkg/standalone/dashboard_test.go @@ -26,8 +26,8 @@ func TestDashboardRun(t *testing.T) { assert.NoError(t, err) assert.Contains(t, cmd.Args[0], "dashboard") - assert.Equal(t, cmd.Args[1], "--port") - assert.Equal(t, cmd.Args[2], "9090") + assert.Equal(t, "--port", cmd.Args[1]) + assert.Equal(t, "9090", cmd.Args[2]) }) t.Run("start dashboard on random free port", func(t *testing.T) { @@ -35,7 +35,7 @@ func TestDashboardRun(t *testing.T) { assert.NoError(t, err) assert.Contains(t, cmd.Args[0], "dashboard") - assert.Equal(t, cmd.Args[1], "--port") - assert.NotEqual(t, cmd.Args[2], "0") + assert.Equal(t, "--port", cmd.Args[1]) + assert.NotEqual(t, "0", cmd.Args[2]) }) } diff --git a/pkg/standalone/list.go b/pkg/standalone/list.go index 342d67301..1a9d20624 100644 --- a/pkg/standalone/list.go +++ b/pkg/standalone/list.go @@ -66,7 +66,7 @@ func List() ([]ListOutput, error) { for _, proc := range processes { executable := strings.ToLower(proc.Executable()) if (executable == "daprd") || (executable == "daprd.exe") { - procDetails, err := process.NewProcess(int32(proc.Pid())) + procDetails, err := process.NewProcess(int32(proc.Pid())) //nolint:gosec if err != nil { continue } diff --git a/pkg/standalone/publish.go b/pkg/standalone/publish.go index 30ae646fe..e2cb1a352 100644 --- a/pkg/standalone/publish.go +++ b/pkg/standalone/publish.go @@ -94,7 +94,7 @@ func (s *Standalone) Publish(publishAppID, pubsubName, topic string, payload []b } func getDaprInstance(list []ListOutput, publishAppID string) (ListOutput, error) { - for i := 0; i < len(list); i++ { + for i := range list { if list[i].AppID == publishAppID { return list[i], nil } @@ -112,7 +112,7 @@ func getQueryParams(metadata map[string]interface{}) string { } // Prefix with "?" and remove the last "&". if queryParams != "" { - queryParams = fmt.Sprintf("?%s", queryParams[:len(queryParams)-1]) + queryParams = "?" + queryParams[:len(queryParams)-1] } return queryParams } diff --git a/pkg/standalone/publish_test.go b/pkg/standalone/publish_test.go index dbb0a1e65..a9d5e41e9 100644 --- a/pkg/standalone/publish_test.go +++ b/pkg/standalone/publish_test.go @@ -212,7 +212,7 @@ func TestGetQueryParams(t *testing.T) { queryParams := getQueryParams(tc.metadata) if queryParams != "" { - assert.True(t, queryParams[0] == '?', "expected query params to start with '?'") + assert.Equal(t, '?', queryParams[0], "expected query params to start with '?'") queryParams = queryParams[1:] } diff --git a/pkg/standalone/run.go b/pkg/standalone/run.go index 3a4b4163c..57781e4b5 100644 --- a/pkg/standalone/run.go +++ b/pkg/standalone/run.go @@ -129,9 +129,9 @@ func (config *RunConfig) validatePlacementHostAddr() error { } if indx := strings.Index(placementHostAddr, ":"); indx == -1 { if runtime.GOOS == daprWindowsOS { - placementHostAddr = fmt.Sprintf("%s:6050", placementHostAddr) + placementHostAddr += ":6050" } else { - placementHostAddr = fmt.Sprintf("%s:50005", placementHostAddr) + placementHostAddr += ":50005" } } config.PlacementHostAddr = placementHostAddr @@ -146,9 +146,9 @@ func (config *RunConfig) validateSchedulerHostAddr() error { if indx := strings.Index(schedulerHostAddr, ":"); indx == -1 { if runtime.GOOS == daprWindowsOS { - schedulerHostAddr = fmt.Sprintf("%s:6060", schedulerHostAddr) + schedulerHostAddr += ":6060" } else { - schedulerHostAddr = fmt.Sprintf("%s:50006", schedulerHostAddr) + schedulerHostAddr += ":50006" } } @@ -290,7 +290,7 @@ func (meta *DaprMeta) portExists(port int) bool { if port <= 0 { return false } - //nolint + _, ok := meta.ExistingPorts[port] if ok { return true @@ -347,7 +347,7 @@ func (config *RunConfig) getArgs() []string { // Recursive function to get all the args from the config struct. // This is needed because the config struct has embedded struct. func getArgsFromSchema(schema reflect.Value, args []string) []string { - for i := 0; i < schema.NumField(); i++ { + for i := range schema.NumField() { valueField := schema.Field(i).Interface() typeField := schema.Type().Field(i) key := typeField.Tag.Get("arg") @@ -389,7 +389,7 @@ func (config *RunConfig) SetDefaultFromSchema() { } func (config *RunConfig) setDefaultFromSchemaRecursive(schema reflect.Value) { - for i := 0; i < schema.NumField(); i++ { + for i := range schema.NumField() { valueField := schema.Field(i) typeField := schema.Type().Field(i) if typeField.Type.Kind() == reflect.Struct { @@ -415,7 +415,7 @@ func (config *RunConfig) getEnv() []string { // Handle values from config that have an "env" tag. schema := reflect.ValueOf(*config) - for i := 0; i < schema.NumField(); i++ { + for i := range schema.NumField() { valueField := schema.Field(i).Interface() typeField := schema.Type().Field(i) key := typeField.Tag.Get("env") @@ -475,7 +475,7 @@ func (config *RunConfig) getAppProtocol() string { func (config *RunConfig) GetEnv() map[string]string { env := map[string]string{} schema := reflect.ValueOf(*config) - for i := 0; i < schema.NumField(); i++ { + for i := range schema.NumField() { valueField := schema.Field(i).Interface() typeField := schema.Type().Field(i) key := typeField.Tag.Get("env") @@ -499,7 +499,7 @@ func (config *RunConfig) GetEnv() map[string]string { func (config *RunConfig) GetAnnotations() map[string]string { annotations := map[string]string{} schema := reflect.ValueOf(*config) - for i := 0; i < schema.NumField(); i++ { + for i := range schema.NumField() { valueField := schema.Field(i).Interface() typeField := schema.Type().Field(i) key := typeField.Tag.Get("annotation") diff --git a/pkg/standalone/standalone.go b/pkg/standalone/standalone.go index 8dcca112d..b7300eea3 100644 --- a/pkg/standalone/standalone.go +++ b/pkg/standalone/standalone.go @@ -888,7 +888,7 @@ func createSlimConfiguration(wg *sync.WaitGroup, errorChan chan<- error, info in func makeDefaultComponentsDir(installDir string) error { // Make default components directory. componentsDir := GetDaprComponentsPath(installDir) - //nolint + _, err := os.Stat(componentsDir) if os.IsNotExist(err) { errDir := os.MkdirAll(componentsDir, 0o755) @@ -955,7 +955,7 @@ func unzip(r *zip.Reader, targetDir string, binaryFilePrefix string) (string, er return "", err } - if strings.HasSuffix(fpath, fmt.Sprintf("%s.exe", binaryFilePrefix)) { + if strings.HasSuffix(fpath, binaryFilePrefix+".exe") { foundBinary = fpath } @@ -1013,7 +1013,6 @@ func untar(reader io.Reader, targetDir string, binaryFilePrefix string) (string, foundBinary := "" for { header, err := tr.Next() - //nolint if err == io.EOF { break } else if err != nil { @@ -1036,7 +1035,7 @@ func untar(reader io.Reader, targetDir string, binaryFilePrefix string) (string, continue } - f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)) + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)) //nolint:gosec if err != nil { return "", err } @@ -1085,14 +1084,14 @@ func moveFileToPath(filepath string, installLocation string) (string, error) { if !strings.Contains(strings.ToLower(p), strings.ToLower(destDir)) { destDir = utils.SanitizeDir(destDir) - pathCmd := "[System.Environment]::SetEnvironmentVariable('Path',[System.Environment]::GetEnvironmentVariable('Path','user') + '" + fmt.Sprintf(";%s", destDir) + "', 'user')" + pathCmd := "[System.Environment]::SetEnvironmentVariable('Path',[System.Environment]::GetEnvironmentVariable('Path','user') + '" + ";" + destDir + "', 'user')" _, err := utils.RunCmdAndWait("powershell", pathCmd) if err != nil { return "", err } } - return fmt.Sprintf("%s\\daprd.exe", destDir), nil + return destDir + "\\daprd.exe", nil } if strings.HasPrefix(fileName, daprRuntimeFilePrefix) && installLocation != "" { @@ -1117,7 +1116,7 @@ func createRedisStateStore(redisHost string, componentsPath string) error { redisStore.Spec.Metadata = []componentMetadataItem{ { Name: "redisHost", - Value: fmt.Sprintf("%s:6379", redisHost), + Value: redisHost + ":6379", }, { Name: "redisPassword", @@ -1152,7 +1151,7 @@ func createRedisPubSub(redisHost string, componentsPath string) error { redisPubSub.Spec.Metadata = []componentMetadataItem{ { Name: "redisHost", - Value: fmt.Sprintf("%s:6379", redisHost), + Value: redisHost + ":6379", }, { Name: "redisPassword", diff --git a/pkg/standalone/standalone_test.go b/pkg/standalone/standalone_test.go index 7f8ae5c0c..98b8a7cd5 100644 --- a/pkg/standalone/standalone_test.go +++ b/pkg/standalone/standalone_test.go @@ -98,7 +98,6 @@ func TestResolveImageWithGHCR(t *testing.T) { } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() got, err := resolveImageURI(test.args) @@ -144,7 +143,6 @@ func TestResolveImageWithDockerHub(t *testing.T) { } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() got, err := resolveImageURI(test.args) @@ -190,7 +188,6 @@ func TestResolveImageWithPrivateRegistry(t *testing.T) { } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() got, err := resolveImageURI(test.args) @@ -329,7 +326,7 @@ func TestInitLogActualContainerRuntimeName(t *testing.T) { } err := Init(latestVersion, latestVersion, "", false, "", "", test.containerRuntime, "", "", nil) - assert.NotNil(t, err) + assert.Error(t, err) assert.Contains(t, err.Error(), test.containerRuntime) }) } diff --git a/pkg/version/version.go b/pkg/version/version.go index 22aa2e75a..4c0254e9a 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -15,6 +15,7 @@ package version import ( "encoding/json" + "errors" "fmt" "io" "net/http" @@ -112,7 +113,7 @@ func GetLatestReleaseGithub(githubURL string) (string, error) { } if len(githubRepoReleases) == 0 { - return "", fmt.Errorf("no releases") + return "", errors.New("no releases") } defaultVersion, _ := version.NewVersion("0.0.0") @@ -135,7 +136,7 @@ func GetLatestReleaseGithub(githubURL string) (string, error) { } if latestVersion.Equal(defaultVersion) { - return "", fmt.Errorf("no releases") + return "", errors.New("no releases") } return latestVersion.String(), nil @@ -151,7 +152,7 @@ func GetLatestReleaseHelmChart(helmChartURL string) (string, error) { return "", err } if len(helmChartReleases.Entries.Dapr) == 0 { - return "", fmt.Errorf("no releases") + return "", errors.New("no releases") } for _, release := range helmChartReleases.Entries.Dapr { @@ -166,6 +167,6 @@ func GetLatestReleaseHelmChart(helmChartURL string) (string, error) { return release.Version, nil } - return "", fmt.Errorf("no releases") + return "", errors.New("no releases") }) } diff --git a/pkg/version/version_test.go b/pkg/version/version_test.go index 24cb69b93..5e9e37755 100644 --- a/pkg/version/version_test.go +++ b/pkg/version/version_test.go @@ -225,7 +225,7 @@ func TestGetVersionsGithub(t *testing.T) { for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { - version, err := GetLatestReleaseGithub(fmt.Sprintf("http://localhost:12345%s", tc.Path)) + version, err := GetLatestReleaseGithub("http://localhost:12345" + tc.Path) assert.Equal(t, tc.ExpectedVer, version) if tc.ExpectedErr != "" { assert.EqualError(t, err, tc.ExpectedErr) @@ -334,7 +334,7 @@ entries: for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { - version, err := GetLatestReleaseHelmChart(fmt.Sprintf("http://localhost:12346%s", tc.Path)) + version, err := GetLatestReleaseHelmChart("http://localhost:12346" + tc.Path) assert.Equal(t, tc.ExpectedVer, version) if tc.ExpectedErr != "" { assert.EqualError(t, err, tc.ExpectedErr) diff --git a/tests/e2e/common/common.go b/tests/e2e/common/common.go index a10fba8c0..9f7557682 100644 --- a/tests/e2e/common/common.go +++ b/tests/e2e/common/common.go @@ -906,7 +906,7 @@ func componentsTestOnUninstall(opts TestOptions) func(t *testing.T) { lines := strings.Split(output, "\n") // An extra empty line is there in output. - require.Equal(t, 3, len(lines), "expected header and warning message of the output to remain") + require.Len(t, lines, 3, "expected header and warning message of the output to remain") } } @@ -936,7 +936,7 @@ func httpEndpointsTestOnUninstall(opts TestOptions) func(t *testing.T) { lines := strings.Split(output, "\n") // An extra empty line is there in output. - require.Equal(t, 2, len(lines), "expected kubernetes response message to remain") + require.Len(t, lines, 2, "expected kubernetes response message to remain") } } } @@ -959,7 +959,7 @@ func componentOutputCheck(t *testing.T, opts TestOptions, output string) { } if opts.UninstallAll { - assert.Equal(t, 2, len(lines), "expected at 0 components and 2 output lines") + assert.Len(t, lines, 2, "expected at 0 components and 2 output lines") return } @@ -969,9 +969,9 @@ func componentOutputCheck(t *testing.T, opts TestOptions, output string) { // default, test statestore. // default pubsub. // 3 components. - assert.Equal(t, 3, len(lines), "expected 3 components") + assert.Len(t, lines, 3, "expected 3 components") } else { - assert.Equal(t, 2, len(lines), "expected 2 components") // default and test namespace components. + assert.Len(t, lines, 2, "expected 2 components") // default and test namespace components. // for fresh cluster only one component yaml has been applied. testNsFields := strings.Fields(lines[0]) diff --git a/utils/utils_test.go b/utils/utils_test.go index d89ea4d0a..95a0d7ec1 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -76,7 +76,6 @@ func TestContainerRuntimeUtils(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() actualValid := IsValidContainerRuntime(tc.input) @@ -120,7 +119,6 @@ func TestContains(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() actualValid := Contains(tc.input, tc.expected) @@ -165,7 +163,6 @@ func TestGetVersionAndImageVariant(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() version, imageVariant := GetVersionAndImageVariant(tc.input) @@ -202,7 +199,6 @@ func TestValidateFilePaths(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() actual := ValidateFilePath(tc.input) @@ -244,7 +240,6 @@ func TestGetAbsPath(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() actual := GetAbsPath(baseDir, tc.input) @@ -302,7 +297,6 @@ func TestResolveHomeDir(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { if tc.skipWindows && runtime.GOOS == "windows" { t.Skip("Skipping test on Windows") @@ -335,7 +329,6 @@ func TestReadFile(t *testing.T) { }, } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() _, actual := ReadFile(tc.input) @@ -398,7 +391,6 @@ func TestFindFileInDir(t *testing.T) { }, } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() filePath, err := FindFileInDir(tc.input, "dapr.yaml") @@ -480,7 +472,6 @@ func TestPrintDetail(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() var buf bytes.Buffer @@ -552,7 +543,6 @@ func TestSanitizeDir(t *testing.T) { } for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() actual := SanitizeDir(tc.input)