Lint fixes (#3526)

Signed-off-by: Anton Troshin <anton@diagrid.io>
Co-authored-by: Bernd Verst <4535280+berndverst@users.noreply.github.com>
This commit is contained in:
Anton Troshin 2024-09-05 16:46:48 -05:00 committed by GitHub
parent 75dcdef8c9
commit facd5088cd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
140 changed files with 456 additions and 463 deletions

View File

@ -261,6 +261,11 @@ linters-settings:
allow-case-traling-whitespace: true
# Allow declarations (var) to be cuddled.
allow-cuddle-declarations: false
testifylint:
disable:
- float-compare
- negative-positive
- go-require
linters:
fast: false
@ -317,3 +322,5 @@ linters:
- goconst
- tagalign
- inamedparam
- canonicalheader
- fatcontext

View File

@ -116,7 +116,7 @@ test:
################################################################################
.PHONY: lint
lint: verify-linter-installed verify-linter-version
$(GOLANGCI_LINT) run --timeout=20m
$(GOLANGCI_LINT) run --timeout=20m --max-same-issues 0 --max-issues-per-linter 0
################################################################################
# Target: modtidy-all #

View File

@ -3,7 +3,7 @@ package sls
import (
"context"
"encoding/json"
"fmt"
"errors"
"reflect"
"time"
@ -61,16 +61,16 @@ func NewAliCloudSlsLogstorage(logger logger.Logger) bindings.OutputBinding {
func (s *AliCloudSlsLogstorage) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
// verify the metadata property
if logProject := req.Metadata["project"]; logProject == "" {
return nil, fmt.Errorf("SLS binding error: project property not supplied")
return nil, errors.New("SLS binding error: project property not supplied")
}
if logstore := req.Metadata["logstore"]; logstore == "" {
return nil, fmt.Errorf("SLS binding error: logstore property not supplied")
return nil, errors.New("SLS binding error: logstore property not supplied")
}
if topic := req.Metadata["topic"]; topic == "" {
return nil, fmt.Errorf("SLS binding error: topic property not supplied")
return nil, errors.New("SLS binding error: topic property not supplied")
}
if source := req.Metadata["source"]; source == "" {
return nil, fmt.Errorf("SLS binding error: source property not supplied")
return nil, errors.New("SLS binding error: source property not supplied")
}
log, err := s.parseLog(req)

View File

@ -271,7 +271,6 @@ func (s *AliCloudTableStore) create(req *bindings.InvokeRequest, resp *bindings.
}
_, err = s.client.PutRow(putRequest)
if err != nil {
return err
}
@ -302,7 +301,6 @@ func (s *AliCloudTableStore) delete(req *bindings.InvokeRequest, resp *bindings.
change.SetCondition(tablestore.RowExistenceExpectation_IGNORE) //nolint:nosnakecase
deleteReq := &tablestore.DeleteRowRequest{DeleteRowChange: change}
_, err = s.client.DeleteRow(deleteReq)
if err != nil {
return err
}

View File

@ -301,7 +301,6 @@ func (a *AWSKinesis) registerConsumer(ctx context.Context, streamARN *string) (*
ConsumerName: &a.metadata.ConsumerName,
StreamARN: streamARN,
})
if err != nil {
return nil, err
}

View File

@ -313,7 +313,7 @@ func (s *AWSS3) get(ctx context.Context, req *bindings.InvokeRequest) (*bindings
if err != nil {
var awsErr awserr.Error
if errors.As(err, &awsErr) && awsErr.Code() == s3.ErrCodeNoSuchKey {
return nil, fmt.Errorf("object not found")
return nil, errors.New("object not found")
}
return nil, fmt.Errorf("s3 binding error: error downloading S3 object: %w", err)
}
@ -348,7 +348,7 @@ func (s *AWSS3) delete(ctx context.Context, req *bindings.InvokeRequest) (*bindi
if err != nil {
var awsErr awserr.Error
if errors.As(err, &awsErr) && awsErr.Code() == s3.ErrCodeNoSuchKey {
return nil, fmt.Errorf("object not found")
return nil, errors.New("object not found")
}
return nil, fmt.Errorf("s3 binding error: delete operation failed: %w", err)
}

View File

@ -15,6 +15,7 @@ package ses
import (
"context"
"errors"
"fmt"
"reflect"
"strconv"
@ -92,13 +93,13 @@ func (a *AWSSES) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bind
metadata := a.metadata.mergeWithRequestMetadata(req)
if metadata.EmailFrom == "" {
return nil, fmt.Errorf("SES binding error: emailFrom property not supplied in configuration- or request-metadata")
return nil, errors.New("SES binding error: emailFrom property not supplied in configuration- or request-metadata")
}
if metadata.EmailTo == "" {
return nil, fmt.Errorf("SES binding error: emailTo property not supplied in configuration- or request-metadata")
return nil, errors.New("SES binding error: emailTo property not supplied in configuration- or request-metadata")
}
if metadata.Subject == "" {
return nil, fmt.Errorf("SES binding error: subject property not supplied in configuration- or request-metadata")
return nil, errors.New("SES binding error: subject property not supplied in configuration- or request-metadata")
}
body, err := strconv.Unquote(string(req.Data))

View File

@ -154,7 +154,6 @@ func (a *AzureBlobStorage) create(ctx context.Context, req *bindings.InvokeReque
blockBlobClient := a.containerClient.NewBlockBlobClient(blobName)
_, err = blockBlobClient.UploadBuffer(ctx, req.Data, &uploadOptions)
if err != nil {
return nil, fmt.Errorf("error uploading az blob: %w", err)
}
@ -192,7 +191,7 @@ func (a *AzureBlobStorage) get(ctx context.Context, req *bindings.InvokeRequest)
blobDownloadResponse, err := blockBlobClient.DownloadStream(ctx, &downloadOptions)
if err != nil {
if bloberror.HasCode(err, bloberror.BlobNotFound) {
return nil, fmt.Errorf("blob not found")
return nil, errors.New("blob not found")
}
return nil, fmt.Errorf("error downloading az blob: %w", err)
}
@ -261,7 +260,7 @@ func (a *AzureBlobStorage) delete(ctx context.Context, req *bindings.InvokeReque
_, err := blockBlobClient.Delete(ctx, &deleteOptions)
if bloberror.HasCode(err, bloberror.BlobNotFound) {
return nil, fmt.Errorf("blob not found")
return nil, errors.New("blob not found")
}
return nil, err

View File

@ -16,6 +16,7 @@ package cosmosdb
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
@ -158,7 +159,7 @@ func (c *CosmosDB) getPartitionKeyValue(key string, obj interface{}) (string, er
}
val, ok := valI.(string)
if !ok {
return "", fmt.Errorf("partition key is not a string")
return "", errors.New("partition key is not a string")
}
if val == "" {
@ -172,7 +173,7 @@ func (c *CosmosDB) lookup(m map[string]interface{}, ks []string) (val interface{
var ok bool
if len(ks) == 0 {
return nil, fmt.Errorf("needs at least one key")
return nil, errors.New("needs at least one key")
}
if val, ok = m[ks[0]]; !ok {

View File

@ -156,7 +156,7 @@ func (s *SignalR) parseMetadata(md map[string]string) (err error) {
s.accessKey = connectionValue[i+1:]
case "AuthType":
if connectionValue[i+1:] != "aad" {
return fmt.Errorf("invalid value for AuthType in the connection string; only 'aad' is supported")
return errors.New("invalid value for AuthType in the connection string; only 'aad' is supported")
}
useAAD = true
case "ClientId", "ClientSecret", "TenantId":
@ -171,14 +171,14 @@ func (s *SignalR) parseMetadata(md map[string]string) (err error) {
}
}
} else if len(connectionValue) != 0 {
return fmt.Errorf("the connection string is invalid or malformed")
return errors.New("the connection string is invalid or malformed")
}
}
// Check here because if we use a connection string, we'd have an explicit "AuthType=aad" option
// We would otherwise catch this issue later, but here we can be more explicit with the error
if s.accessKey == "" && !useAAD {
return fmt.Errorf("missing AccessKey in the connection string")
return errors.New("missing AccessKey in the connection string")
}
}
@ -198,7 +198,7 @@ func (s *SignalR) parseMetadata(md map[string]string) (err error) {
// Check for required values
if s.endpoint == "" {
return fmt.Errorf("missing endpoint in the metadata or connection string")
return errors.New("missing endpoint in the metadata or connection string")
}
return nil
@ -333,7 +333,7 @@ func (s *SignalR) GetAadClientAccessToken(ctx context.Context, hub string, user
u := fmt.Sprintf("%s/api/hubs/%s/:generateToken?api-version=%s", s.endpoint, hub, apiVersion)
if user != "" {
u += fmt.Sprintf("&userId=%s", url.QueryEscape(user))
u += "&userId=" + url.QueryEscape(user)
}
body, err := s.sendRequestToSignalR(ctx, u, aadToken, nil)

View File

@ -394,7 +394,6 @@ func TestWriteShouldSucceed(t *testing.T) {
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
httpTransport.reset()
s.hub = tt.hubInMetadata

View File

@ -220,7 +220,7 @@ func (d *AzureQueueHelper) Read(ctx context.Context, consumer *consumer) error {
}
return nil
} else {
return fmt.Errorf("could not delete message from queue: message ID or pop receipt is nil")
return errors.New("could not delete message from queue: message ID or pop receipt is nil")
}
}

View File

@ -65,7 +65,7 @@ func (ct *Binding) Init(_ context.Context, metadata bindings.Metadata) error {
baseURLdomain := fmt.Sprintf("%s.%s.commercetools.com", commercetoolsM.Region, commercetoolsM.Provider)
authURL := fmt.Sprintf("https://auth.%s/oauth/token", baseURLdomain)
apiURL := fmt.Sprintf("https://api.%s", baseURLdomain)
apiURL := "https://api." + baseURLdomain
// Create the new client. When an empty value is passed it will use the CTP_*
// environment variables to get the value. The HTTPClient arg is optional,

View File

@ -76,7 +76,7 @@ func (b *Binding) Init(ctx context.Context, meta bindings.Metadata) error {
return err
}
if m.Schedule == "" {
return fmt.Errorf("schedule not set")
return errors.New("schedule not set")
}
_, err = b.parser.Parse(m.Schedule)
if err != nil {

View File

@ -109,7 +109,7 @@ func TestCronRead(t *testing.T) {
return nil, nil
})
// Check if cron triggers 5 times in 5 seconds
for i := int32(0); i < expectedCount; i++ {
for range expectedCount {
// Add time to mock clock in 1 second intervals using loop to allow cron go routine to run
clk.Step(time.Second)
runtime.Gosched()
@ -143,7 +143,7 @@ func TestCronReadWithContextCancellation(t *testing.T) {
return nil, nil
})
// Check if cron triggers only 5 times in 10 seconds since context should be cancelled after 5 triggers
for i := 0; i < 10; i++ {
for range 10 {
// Add time to mock clock in 1 second intervals using loop to allow cron go routine to run
clk.Step(time.Second)
runtime.Gosched()

View File

@ -220,7 +220,7 @@ func (g *GCPStorage) get(ctx context.Context, req *bindings.InvokeRequest) (*bin
if val, ok := req.Metadata[metadataKey]; ok && val != "" {
key = val
} else {
return nil, fmt.Errorf("gcp bucket binding error: can't read key value")
return nil, errors.New("gcp bucket binding error: can't read key value")
}
var rc io.ReadCloser
@ -256,7 +256,7 @@ func (g *GCPStorage) delete(ctx context.Context, req *bindings.InvokeRequest) (*
if val, ok := req.Metadata[metadataKey]; ok && val != "" {
key = val
} else {
return nil, fmt.Errorf("gcp bucketgcp bucket binding error: can't read key value")
return nil, errors.New("gcp bucketgcp bucket binding error: can't read key value")
}
object := g.client.Bucket(g.metadata.Bucket).Object(key)
@ -355,7 +355,7 @@ func (g *GCPStorage) sign(ctx context.Context, req *bindings.InvokeRequest) (*bi
if val, ok := req.Metadata[metadataKey]; ok && val != "" {
key = val
} else {
return nil, fmt.Errorf("gcp bucket binding error: can't read key value")
return nil, errors.New("gcp bucket binding error: can't read key value")
}
if metadata.SignTTL == "" {

View File

@ -16,6 +16,7 @@ package graphql
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
@ -73,7 +74,7 @@ func (gql *GraphQL) Init(_ context.Context, meta bindings.Metadata) error {
}
if m.Endpoint == "" {
return fmt.Errorf("GraphQL Error: Missing GraphQL URL")
return errors.New("GraphQL Error: Missing GraphQL URL")
}
// Connect to GraphQL Server
@ -101,11 +102,11 @@ func (gql *GraphQL) Operations() []bindings.OperationKind {
// Invoke handles all invoke operations.
func (gql *GraphQL) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
if req == nil {
return nil, fmt.Errorf("GraphQL Error: Invoke request required")
return nil, errors.New("GraphQL Error: Invoke request required")
}
if req.Metadata == nil {
return nil, fmt.Errorf("GraphQL Error: Metadata required")
return nil, errors.New("GraphQL Error: Metadata required")
}
gql.logger.Debugf("operation: %v", req.Operation)

View File

@ -354,7 +354,7 @@ func (h *HTTPSource) Invoke(parentCtx context.Context, req *bindings.InvokeReque
}
// Create an error for non-200 status codes unless suppressed.
if errorIfNot2XX && resp.StatusCode/100 != 2 {
if errorIfNot2XX && resp.StatusCode/100 != 2 { //nolint:usestdlibvars
err = fmt.Errorf("received status code %d", resp.StatusCode)
}

View File

@ -330,7 +330,7 @@ func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h.Path = req.URL.Path
if strings.TrimPrefix(h.Path, "/") == "large" {
// Write 5KB
for i := 0; i < 1<<10; i++ {
for range 1 << 10 {
fmt.Fprint(w, "12345")
}
return

View File

@ -104,16 +104,16 @@ func (o *HuaweiOBS) parseMetadata(meta bindings.Metadata) (*obsMetadata, error)
}
if m.Bucket == "" {
return nil, fmt.Errorf("missing obs bucket name")
return nil, errors.New("missing obs bucket name")
}
if m.Endpoint == "" {
return nil, fmt.Errorf("missing obs endpoint")
return nil, errors.New("missing obs endpoint")
}
if m.AccessKey == "" {
return nil, fmt.Errorf("missing the huawei access key")
return nil, errors.New("missing the huawei access key")
}
if m.SecretKey == "" {
return nil, fmt.Errorf("missing the huawei secret key")
return nil, errors.New("missing the huawei secret key")
}
o.logger.Debugf("Huawei OBS metadata=[%s]", m)
@ -212,7 +212,7 @@ func (o *HuaweiOBS) get(ctx context.Context, req *bindings.InvokeRequest) (*bind
if val, ok := req.Metadata[metadataKey]; ok && val != "" {
key = val
} else {
return nil, fmt.Errorf("obs binding error: can't read key value")
return nil, errors.New("obs binding error: can't read key value")
}
input := &obs.GetObjectInput{}
@ -252,7 +252,7 @@ func (o *HuaweiOBS) delete(ctx context.Context, req *bindings.InvokeRequest) (*b
if val, ok := req.Metadata[metadataKey]; ok && val != "" {
key = val
} else {
return nil, fmt.Errorf("obs binding error: can't read key value")
return nil, errors.New("obs binding error: can't read key value")
}
input := &obs.DeleteObjectInput{}

View File

@ -17,7 +17,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"testing"
@ -105,7 +104,7 @@ func TestInit(t *testing.T) {
}
err := obs.Init(context.Background(), m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("missing obs bucket name"))
assert.Equal(t, err, errors.New("missing obs bucket name"))
})
t.Run("Init with missing access key", func(t *testing.T) {
m := bindings.Metadata{}
@ -116,7 +115,7 @@ func TestInit(t *testing.T) {
}
err := obs.Init(context.Background(), m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("missing the huawei access key"))
assert.Equal(t, err, errors.New("missing the huawei access key"))
})
t.Run("Init with missing secret key", func(t *testing.T) {
m := bindings.Metadata{}
@ -127,7 +126,7 @@ func TestInit(t *testing.T) {
}
err := obs.Init(context.Background(), m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("missing the huawei secret key"))
assert.Equal(t, err, errors.New("missing the huawei secret key"))
})
t.Run("Init with missing endpoint", func(t *testing.T) {
m := bindings.Metadata{}
@ -138,7 +137,7 @@ func TestInit(t *testing.T) {
}
err := obs.Init(context.Background(), m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("missing obs endpoint"))
assert.Equal(t, err, errors.New("missing obs endpoint"))
})
}
@ -249,7 +248,7 @@ func TestCreateOperation(t *testing.T) {
mo := &HuaweiOBS{
service: &MockHuaweiOBSService{
PutObjectFn: func(ctx context.Context, input *obs.PutObjectInput) (output *obs.PutObjectOutput, err error) {
return nil, fmt.Errorf("error while creating object")
return nil, errors.New("error while creating object")
},
},
logger: logger.NewLogger("test"),
@ -341,7 +340,7 @@ func TestUploadOperation(t *testing.T) {
mo := &HuaweiOBS{
service: &MockHuaweiOBSService{
PutFileFn: func(ctx context.Context, input *obs.PutFileInput) (output *obs.PutObjectOutput, err error) {
return nil, fmt.Errorf("error while creating object")
return nil, errors.New("error while creating object")
},
},
logger: logger.NewLogger("test"),
@ -417,7 +416,7 @@ func TestGetOperation(t *testing.T) {
mo := &HuaweiOBS{
service: &MockHuaweiOBSService{
GetObjectFn: func(ctx context.Context, input *obs.GetObjectInput) (output *obs.GetObjectOutput, err error) {
return nil, fmt.Errorf("error while getting object")
return nil, errors.New("error while getting object")
},
},
logger: logger.NewLogger("test"),
@ -525,7 +524,7 @@ func TestDeleteOperation(t *testing.T) {
mo := &HuaweiOBS{
service: &MockHuaweiOBSService{
DeleteObjectFn: func(ctx context.Context, input *obs.DeleteObjectInput) (output *obs.DeleteObjectOutput, err error) {
return nil, fmt.Errorf("error while deleting object")
return nil, errors.New("error while deleting object")
},
},
logger: logger.NewLogger("test"),
@ -580,7 +579,7 @@ func TestListOperation(t *testing.T) {
mo := &HuaweiOBS{
service: &MockHuaweiOBSService{
ListObjectsFn: func(ctx context.Context, input *obs.ListObjectsInput) (output *obs.ListObjectsOutput, err error) {
return nil, fmt.Errorf("error while listing objects")
return nil, errors.New("error while listing objects")
},
},
logger: logger.NewLogger("test"),

View File

@ -15,7 +15,7 @@ package bindings
import (
"context"
"fmt"
"errors"
"io"
"github.com/dapr/components-contrib/health"
@ -43,6 +43,6 @@ func PingInpBinding(ctx context.Context, inputBinding InputBinding) error {
if inputBindingWithPing, ok := inputBinding.(health.Pinger); ok {
return inputBindingWithPing.Ping(ctx)
} else {
return fmt.Errorf("ping is not implemented by this input binding")
return errors.New("ping is not implemented by this input binding")
}
}

View File

@ -1,7 +1,7 @@
package kubemq
import (
"fmt"
"errors"
"strconv"
"strings"
@ -27,15 +27,15 @@ func parseAddress(address string) (string, int, error) {
var err error
hostPort := strings.Split(address, ":")
if len(hostPort) != 2 {
return "", 0, fmt.Errorf("invalid kubemq address, address format is invalid")
return "", 0, errors.New("invalid kubemq address, address format is invalid")
}
host = hostPort[0]
if len(host) == 0 {
return "", 0, fmt.Errorf("invalid kubemq address, host is empty")
return "", 0, errors.New("invalid kubemq address, host is empty")
}
port, err = strconv.Atoi(hostPort[1])
if err != nil {
return "", 0, fmt.Errorf("invalid kubemq address, port is invalid")
return "", 0, errors.New("invalid kubemq address, port is invalid")
}
return host, port, nil
}
@ -64,19 +64,19 @@ func createOptions(md bindings.Metadata) (*options, error) {
return nil, err
}
} else {
return nil, fmt.Errorf("invalid kubemq address, address is empty")
return nil, errors.New("invalid kubemq address, address is empty")
}
if result.Channel == "" {
return nil, fmt.Errorf("invalid kubemq channel, channel is empty")
return nil, errors.New("invalid kubemq channel, channel is empty")
}
if result.PollMaxItems < 1 {
return nil, fmt.Errorf("invalid kubemq pollMaxItems value, value must be greater than 0")
return nil, errors.New("invalid kubemq pollMaxItems value, value must be greater than 0")
}
if result.PollTimeoutSeconds < 1 {
return nil, fmt.Errorf("invalid kubemq pollTimeoutSeconds value, value must be greater than 0")
return nil, errors.New("invalid kubemq pollTimeoutSeconds value, value must be greater than 0")
}
return result, nil

View File

@ -95,7 +95,7 @@ func (m *MQTT) getProducer() (mqtt.Client, error) {
}
// mqtt broker allows only one connection at a given time from a clientID.
producerClientID := fmt.Sprintf("%s-producer", m.metadata.ClientID)
producerClientID := m.metadata.ClientID + "-producer"
p, err := m.connect(producerClientID, false)
if err != nil {
return nil, err
@ -170,7 +170,7 @@ func (m *MQTT) Read(ctx context.Context, handler bindings.Handler) error {
m.readHandler = handler
// mqtt broker allows only one connection at a given time from a clientID
consumerClientID := fmt.Sprintf("%s-consumer", m.metadata.ClientID)
consumerClientID := m.metadata.ClientID + "-consumer"
// Establish the connection
// This will also create the subscription in the OnConnect handler

View File

@ -114,7 +114,7 @@ func (m *Mysql) Init(ctx context.Context, md bindings.Metadata) error {
}
if meta.URL == "" {
return fmt.Errorf("missing MySql connection string")
return errors.New("missing MySql connection string")
}
m.db, err = initDB(meta.URL, meta.PemPath)
@ -281,7 +281,7 @@ func initDB(url, pemPath string) (*sql.DB, error) {
ok := rootCertPool.AppendCertsFromPEM(pem)
if !ok {
return nil, fmt.Errorf("failed to append PEM")
return nil, errors.New("failed to append PEM")
}
err = mysql.RegisterTLSConfig("custom", &tls.Config{

View File

@ -91,7 +91,7 @@ func TestMysqlIntegration(t *testing.T) {
})
t.Run("Invoke insert", func(t *testing.T) {
for i := 0; i < 10; i++ {
for i := range 10 {
res, err := b.Invoke(context.Background(), &bindings.InvokeRequest{
Operation: execOperation,
Metadata: map[string]string{
@ -106,7 +106,7 @@ func TestMysqlIntegration(t *testing.T) {
t.Run("Invoke update", func(t *testing.T) {
date := time.Now().Add(time.Hour)
for i := 0; i < 10; i++ {
for i := range 10 {
res, err := b.Invoke(context.Background(), &bindings.InvokeRequest{
Operation: execOperation,
Metadata: map[string]string{
@ -122,7 +122,7 @@ func TestMysqlIntegration(t *testing.T) {
t.Run("Invoke update with parameters", func(t *testing.T) {
date := time.Now().Add(2 * time.Hour)
for i := 0; i < 10; i++ {
for i := range 10 {
res, err := b.Invoke(context.Background(), &bindings.InvokeRequest{
Operation: execOperation,
Metadata: map[string]string{

View File

@ -15,7 +15,7 @@ package bindings
import (
"context"
"fmt"
"errors"
"github.com/dapr/components-contrib/health"
"github.com/dapr/components-contrib/metadata"
@ -35,6 +35,6 @@ func PingOutBinding(ctx context.Context, outputBinding OutputBinding) error {
if outputBindingWithPing, ok := outputBinding.(health.Pinger); ok {
return outputBindingWithPing.Ping(ctx)
} else {
return fmt.Errorf("ping is not implemented by this output binding")
return errors.New("ping is not implemented by this output binding")
}
}

View File

@ -87,7 +87,7 @@ func TestPostgresIntegration(t *testing.T) {
})
t.Run("Invoke insert", func(t *testing.T) {
for i := 0; i < 10; i++ {
for i := range 10 {
req.Metadata[commandSQLKey] = fmt.Sprintf(testInsert, i, i, time.Now().Format(time.RFC3339))
res, err := b.Invoke(ctx, req)
assertResponse(t, res, err)
@ -95,7 +95,7 @@ func TestPostgresIntegration(t *testing.T) {
})
t.Run("Invoke update", func(t *testing.T) {
for i := 0; i < 10; i++ {
for i := range 10 {
req.Metadata[commandSQLKey] = fmt.Sprintf(testUpdate, time.Now().Format(time.RFC3339), i)
res, err := b.Invoke(ctx, req)
assertResponse(t, res, err)

View File

@ -104,7 +104,7 @@ func (p *Postmark) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bi
email.From = req.Metadata["emailFrom"]
}
if len(email.From) == 0 {
return nil, fmt.Errorf("error Postmark from email not supplied")
return nil, errors.New("error Postmark from email not supplied")
}
// Build email to address, this is required
@ -115,7 +115,7 @@ func (p *Postmark) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bi
email.To = req.Metadata["emailTo"]
}
if len(email.To) == 0 {
return nil, fmt.Errorf("error Postmark to email not supplied")
return nil, errors.New("error Postmark to email not supplied")
}
// Build email subject, this is required
@ -126,7 +126,7 @@ func (p *Postmark) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bi
email.Subject = req.Metadata["subject"]
}
if len(email.Subject) == 0 {
return nil, fmt.Errorf("error Postmark subject not supplied")
return nil, errors.New("error Postmark subject not supplied")
}
// Build email cc address, this is optional

View File

@ -89,7 +89,7 @@ func (a *RocketMQ) Read(ctx context.Context, handler bindings.Handler) error {
}
if len(a.settings.Topics) == 0 {
return fmt.Errorf("binding-rocketmq error: must configure topics")
return errors.New("binding-rocketmq error: must configure topics")
}
for _, topicStr := range a.settings.Topics {

View File

@ -55,7 +55,7 @@ func TestInputBindingRead(t *testing.T) { //nolint:paralleltest
require.NoError(t, err)
time.Sleep(10 * time.Second)
for i := 0; i < 30; i++ {
for range 30 {
if atomic.LoadInt32(&count) > 0 {
break
}

View File

@ -88,13 +88,13 @@ func (s *Mailer) Invoke(_ context.Context, req *bindings.InvokeRequest) (*bindin
return nil, err
}
if metadata.EmailFrom == "" {
return nil, fmt.Errorf("smtp binding error: emailFrom property not supplied in configuration- or request-metadata")
return nil, errors.New("smtp binding error: emailFrom property not supplied in configuration- or request-metadata")
}
if metadata.EmailTo == "" {
return nil, fmt.Errorf("smtp binding error: emailTo property not supplied in configuration- or request-metadata")
return nil, errors.New("smtp binding error: emailTo property not supplied in configuration- or request-metadata")
}
if metadata.Subject == "" {
return nil, fmt.Errorf("smtp binding error: subject property not supplied in configuration- or request-metadata")
return nil, errors.New("smtp binding error: subject property not supplied in configuration- or request-metadata")
}
// Compose message
@ -168,7 +168,6 @@ func (s *Mailer) parseMetadata(meta bindings.Metadata) (Metadata, error) {
}
err = smtpMeta.parsePriority(meta.Properties["priority"])
if err != nil {
return smtpMeta, err
}

View File

@ -136,7 +136,7 @@ func (sg *SendGrid) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*b
fromAddress = mail.NewEmail(fromName, req.Metadata["emailFrom"])
}
if fromAddress == nil {
return nil, fmt.Errorf("error SendGrid from email not supplied")
return nil, errors.New("error SendGrid from email not supplied")
}
// Build email to address, this is required
@ -160,7 +160,7 @@ func (sg *SendGrid) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*b
toAddress = mail.NewEmail(toName, req.Metadata["emailTo"])
}
if toAddress == nil {
return nil, fmt.Errorf("error SendGrid to email not supplied")
return nil, errors.New("error SendGrid to email not supplied")
}
// Build email subject, this is required
@ -172,7 +172,7 @@ func (sg *SendGrid) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*b
subject = req.Metadata["subject"]
}
if subject == "" {
return nil, fmt.Errorf("error SendGrid subject not supplied")
return nil, errors.New("error SendGrid subject not supplied")
}
// Build email cc address, this is optional

View File

@ -16,6 +16,7 @@ package wasm
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"reflect"
@ -91,7 +92,7 @@ func (out *outputBinding) Init(ctx context.Context, metadata bindings.Metadata)
if _, found := imports[modeWasiHTTP]; found {
if out.meta.StrictSandbox {
_ = out.runtime.Close(context.Background())
return fmt.Errorf("can not instantiate wasi-http with strict sandbox")
return errors.New("can not instantiate wasi-http with strict sandbox")
}
err = wasi_http.MakeWasiHTTP().Instantiate(ctx, out.runtime)
}

View File

@ -172,7 +172,7 @@ func Test_Invoke(t *testing.T) {
if tc.expectedErr == "" {
// execute twice to prove idempotency
for i := 0; i < 2; i++ {
for range 2 {
resp, outputErr := output.Invoke(reqCtx, tc.request)
require.NoError(t, outputErr)
require.Equal(t, tc.expectedData, string(resp.Data))
@ -258,7 +258,7 @@ func Test_InvokeHttp(t *testing.T) {
if tc.expectedErr == "" {
// execute twice to prove idempotency
for i := 0; i < 2; i++ {
for range 2 {
resp, outputErr := output.Invoke(reqCtx, tc.request)
require.NoError(t, outputErr)
require.Equal(t, tc.expectedData, string(resp.Data))
@ -292,7 +292,7 @@ func TestEnsureConcurrency(t *testing.T) {
// Wasm is running in goroutine, use wait group to ensure all goroutines are finished
wg := sync.WaitGroup{}
// 100 is enough to trigger concurrency, and wasm should be executed run fast enough to not consuming too much time
for i := 0; i < 100; i++ {
for i := range 100 {
wg.Add(1)
go func(i int) {
request := &bindings.InvokeRequest{

View File

@ -104,7 +104,7 @@ func (z *ZeebeJobWorker) Init(ctx context.Context, metadata bindings.Metadata) e
func (z *ZeebeJobWorker) Read(ctx context.Context, handler bindings.Handler) error {
if z.closed.Load() {
return fmt.Errorf("binding is closed")
return errors.New("binding is closed")
}
var retryBackOff *time.Duration

View File

@ -124,7 +124,7 @@ func (opts *AWSIAMAuthOptions) GetAccessToken(ctx context.Context) (string, erro
return authenticationToken, nil
case err != nil:
return "", fmt.Errorf("failed to load default AWS authentication configuration")
return "", errors.New("failed to load default AWS authentication configuration")
}
authenticationToken, err = auth.BuildAuthToken(

View File

@ -234,7 +234,7 @@ func (s EnvironmentSettings) GetTokenCredential() (azcore.TokenCredential, error
break
} else {
// If authMethod is "none", we don't add any provider and return an error
return nil, fmt.Errorf("all Azure auth methods have been disabled with auth method 'None'")
return nil, errors.New("all Azure auth methods have been disabled with auth method 'None'")
}
}
}
@ -412,7 +412,7 @@ func (c CertConfig) decodePEM(data []byte) (certificate *x509.Certificate, priva
parsedKey any
ok bool
)
for i := 0; i < 2; i++ {
for range 2 {
block, data = pem.Decode(data)
if block == nil {
break

View File

@ -190,7 +190,7 @@ func ValidIdentifier(v string) bool {
// Loop through the string as byte slice as we only care about ASCII characters
b := []byte(v)
for i := 0; i < len(b); i++ {
for i := range len(b) {
if (b[i] >= '0' && b[i] <= '9') ||
(b[i] >= 'a' && b[i] <= 'z') ||
(b[i] >= 'A' && b[i] <= 'Z') ||

View File

@ -51,10 +51,10 @@ func (m *SQLServerAuthMetadata) Validate(meta map[string]string) (err error) {
return errors.New("missing connection string")
}
if !IsValidSQLName(m.DatabaseName) {
return fmt.Errorf("invalid database name, accepted characters are (A-Z, a-z, 0-9, _)")
return errors.New("invalid database name, accepted characters are (A-Z, a-z, 0-9, _)")
}
if !IsValidSQLName(m.SchemaName) {
return fmt.Errorf("invalid schema name, accepted characters are (A-Z, a-z, 0-9, _)")
return errors.New("invalid schema name, accepted characters are (A-Z, a-z, 0-9, _)")
}
// If using Azure AD

View File

@ -109,7 +109,7 @@ func (opts *ContainerClientOpts) GetContainerURL(azEnvSettings azauth.Environmen
if opts.customEndpoint != "" {
u, err = url.Parse(fmt.Sprintf("%s/%s/%s", opts.customEndpoint, opts.AccountName, opts.ContainerName))
if err != nil {
return nil, fmt.Errorf("failed to get container's URL with custom endpoint")
return nil, errors.New("failed to get container's URL with custom endpoint")
}
} else {
u = opts.getAzureBlobStorageContainerURL(azEnvSettings)

View File

@ -15,7 +15,7 @@ package blobstorage
import (
b64 "encoding/base64"
"fmt"
"errors"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
@ -56,7 +56,7 @@ func CreateBlobHTTPHeadersFromRequest(meta map[string]string, contentType *strin
if val, ok := meta[caseMap[contentMD5Key]]; ok && val != "" {
sDec, err := b64.StdEncoding.DecodeString(val)
if err != nil || len(sDec) != 16 {
return blob.HTTPHeaders{}, fmt.Errorf("the MD5 value specified in Content MD5 is invalid, MD5 value must be 128 bits and base64 encoded")
return blob.HTTPHeaders{}, errors.New("the MD5 value specified in Content MD5 is invalid, MD5 value must be 128 bits and base64 encoded")
}
blobHTTPHeaders.BlobContentMD5 = sDec
delete(meta, caseMap[contentMD5Key])
@ -88,7 +88,7 @@ func SanitizeMetadata(log logger.Logger, metadata map[string]string) map[string]
// Keep only letters and digits
n := 0
newKey := make([]byte, len(key))
for i := 0; i < len(key); i++ {
for i := range len(key) {
if (key[i] >= 'A' && key[i] <= 'Z') ||
(key[i] >= 'a' && key[i] <= 'z') ||
(key[i] >= '0' && key[i] <= '9') {
@ -106,7 +106,7 @@ func SanitizeMetadata(log logger.Logger, metadata map[string]string) map[string]
// Remove all non-ascii characters
n = 0
newVal := make([]byte, len(val))
for i := 0; i < len(val); i++ {
for i := range len(val) {
if val[i] > 127 || val[i] == 0 {
continue
}

View File

@ -115,7 +115,7 @@ func (aeh *AzureEventHubs) Init(metadata map[string]string) error {
aeh.backOffConfig.MaxRetries = 3
err = retry.DecodeConfigWithPrefix(&aeh.backOffConfig, metadata, "backOff")
if err != nil {
return fmt.Errorf("failed to decode backoff configuration")
return errors.New("failed to decode backoff configuration")
}
return nil
@ -365,15 +365,13 @@ func (aeh *AzureEventHubs) processEvents(subscribeCtx context.Context, partition
// Loop to receive messages
var (
ctx context.Context
cancel context.CancelFunc
events []*azeventhubs.ReceivedEventData
err error
)
counter := 0
for {
// Maximum duration to wait till bulk message is sent to app is `maxBulkSubAwaitDurationMs`
ctx, cancel = context.WithTimeout(subscribeCtx, time.Duration(config.MaxBulkSubAwaitDurationMs)*time.Millisecond)
ctx, cancel := context.WithTimeout(subscribeCtx, time.Duration(config.MaxBulkSubAwaitDurationMs)*time.Millisecond)
// Receive events with batchsize of `maxBulkSubCount`
events, err = partitionClient.ReceiveEvents(ctx, config.MaxBulkSubCount, nil)
cancel()

View File

@ -185,7 +185,7 @@ func (c *Client) CloseAllSenders(log logger.Logger) {
<-workersCh
}(k, t)
}
for i := 0; i < cap(workersCh); i++ {
for range cap(workersCh) {
// Wait for all workers to be done
workersCh <- true
}

View File

@ -76,7 +76,6 @@ func TestAddMessageAttributesToMetadata(t *testing.T) {
}
for _, tc := range testCases {
tc := tc
for mType, mMap := range metadataMap {
t.Run(fmt.Sprintf("%s, metadata is %s", tc.name, mType), func(t *testing.T) {
actual := addMessageAttributesToMetadata(mMap, &tc.ASBMessage)

View File

@ -331,7 +331,7 @@ func (s *Subscription) doRenewLocks(ctx context.Context, receiver *MessageReceiv
err error
errored int
)
for i := 0; i < len(msgs); i++ {
for range len(msgs) {
// This is a nop if the received error is nil
if multierr.AppendInto(&err, <-errCh) {
errored++
@ -548,7 +548,7 @@ func (s *Subscription) CompleteMessage(ctx context.Context, receiver Receiver, m
func (s *Subscription) addActiveMessage(m *azservicebus.ReceivedMessage) error {
if m.SequenceNumber == nil {
return fmt.Errorf("message sequence number is nil")
return errors.New("message sequence number is nil")
}
var logSuffix string

View File

@ -20,6 +20,7 @@ import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"mime/multipart"
@ -188,7 +189,7 @@ func (w *Base) getWorkersSubdomain() (string, error) {
}
if data.Result.Subdomain == "" {
return "", fmt.Errorf("response does not contain a value for 'subdomain'")
return "", errors.New("response does not contain a value for 'subdomain'")
}
return data.Result.Subdomain, nil

View File

@ -43,7 +43,7 @@ func updatePasswordAuthInfo(config *sarama.Config, metadata *KafkaMetadata, sasl
func updateMTLSAuthInfo(config *sarama.Config, metadata *KafkaMetadata) error {
if metadata.TLSDisable {
return fmt.Errorf("kafka: cannot configure mTLS authentication when TLSDisable is 'true'")
return errors.New("kafka: cannot configure mTLS authentication when TLSDisable is 'true'")
}
cert, err := tls.X509KeyPair([]byte(metadata.TLSClientCert), []byte(metadata.TLSClientKey))
if err != nil {

View File

@ -280,7 +280,7 @@ func (k *Kafka) DeserializeValue(message *sarama.ConsumerMessage, config Subscri
return nil, err
}
if len(message.Value) < 5 {
return nil, fmt.Errorf("value is too short")
return nil, errors.New("value is too short")
}
schemaID := binary.BigEndian.Uint32(message.Value[1:5])
schema, err := srClient.GetSchema(int(schemaID))

View File

@ -18,6 +18,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"net/http"
"time"
@ -58,7 +59,7 @@ func (ts *OAuthTokenSource) addCa(caPem string) error {
block, _ := pem.Decode(pemBytes)
if block == nil || block.Type != "CERTIFICATE" {
return fmt.Errorf("PEM data not valid or not of a valid type (CERTIFICATE)")
return errors.New("PEM data not valid or not of a valid type (CERTIFICATE)")
}
caCert, err := x509.ParseCertificate(block.Bytes)
@ -109,7 +110,7 @@ func (ts *OAuthTokenSource) Token() (*sarama.AccessToken, error) {
}
if ts.TokenEndpoint.TokenURL == "" || ts.ClientID == "" || ts.ClientSecret == "" {
return nil, fmt.Errorf("cannot generate token, OAuthTokenSource not fully configured")
return nil, errors.New("cannot generate token, OAuthTokenSource not fully configured")
}
oidcCfg := ccred.Config{ClientID: ts.ClientID, ClientSecret: ts.ClientSecret, Scopes: ts.Scopes, TokenURL: ts.TokenEndpoint.TokenURL, AuthStyle: ts.TokenEndpoint.AuthStyle}

View File

@ -503,7 +503,7 @@ func Test_Subscribe(t *testing.T) {
}
ctx, cancel := context.WithCancel(context.Background())
for i := 0; i < 100; i++ {
for i := range 100 {
go func(i int) {
k.Subscribe(ctx, SubscriptionHandlerConfig{}, strconv.Itoa(i))
}(i)

View File

@ -365,7 +365,7 @@ func GetServerVersion(c RedisClient) (string, error) {
return strings.TrimSpace(strings.Split(row, ":")[1]), nil
}
}
return "", fmt.Errorf("could not find redis_version in redis info response")
return "", errors.New("could not find redis_version in redis info response")
}
// GetConnectedSlaves returns the number of slaves connected to the Redis master.

View File

@ -107,7 +107,7 @@ func (m Migrations) EnsureMetadataTable(ctx context.Context) (err error) {
// Add an "IF NOT EXISTS" in case another Dapr sidecar is creating the same table at the same time
// In the next step we'll acquire a lock so there won't be issues with concurrency
// Note that this query can fail with error `23505` on constraint `pg_type_typname_nsp_index` if ran in parallel; we will just retry that up to 3 times
for i := 0; i < 3; i++ {
for range 3 {
_, err = m.DB.Exec(ctx, fmt.Sprintf(
`CREATE TABLE IF NOT EXISTS %s (
key text NOT NULL PRIMARY KEY,

View File

@ -158,7 +158,7 @@ func TestMigration(t *testing.T) {
const parallel = 5
errs := make(chan error, parallel)
hasLogs := atomic.Uint32{}
for i := 0; i < parallel; i++ {
for i := range parallel {
go func(i int) {
// Collect logs
collectLog := logger.NewLogger("concurrent-" + strconv.Itoa(i))
@ -188,7 +188,7 @@ func TestMigration(t *testing.T) {
}(i)
}
for i := 0; i < parallel; i++ {
for range parallel {
select {
case err := <-errs:
assert.NoError(t, err) //nolint:testifylint
@ -213,7 +213,7 @@ func getUniqueDBSchema(t *testing.T) string {
b := make([]byte, 4)
_, err := io.ReadFull(rand.Reader, b)
require.NoError(t, err)
return fmt.Sprintf("m%s", hex.EncodeToString(b))
return "m%s" + hex.EncodeToString(b)
}
func assertTableExists(t *testing.T, db *sql.DB, schema, table string) {

View File

@ -219,7 +219,7 @@ func (r *ConfigurationStore) getLabelFromMetadata(metadata map[string]string) *s
func (r *ConfigurationStore) Subscribe(ctx context.Context, req *configuration.SubscribeRequest, handler configuration.UpdateHandler) (string, error) {
sentinelKey := r.getSentinelKeyFromMetadata(req.Metadata)
if sentinelKey == "" {
return "", fmt.Errorf("sentinel key is not provided in metadata")
return "", errors.New("sentinel key is not provided in metadata")
}
uuid, err := uuid.NewRandom()
if err != nil {

View File

@ -246,7 +246,7 @@ func TestInit(t *testing.T) {
}
func TestParseMetadata(t *testing.T) {
t.Run(fmt.Sprintf("parse metadata with %s", host), func(t *testing.T) {
t.Run("parse metadata with "+host, func(t *testing.T) {
testProperties := make(map[string]string)
testProperties[host] = "testHost"
testProperties[maxRetries] = "3"
@ -279,7 +279,7 @@ func TestParseMetadata(t *testing.T) {
assert.Equal(t, want.RequestTimeout, m.RequestTimeout)
})
t.Run(fmt.Sprintf("parse metadata with %s", connectionString), func(t *testing.T) {
t.Run("parse metadata with "+connectionString, func(t *testing.T) {
testProperties := make(map[string]string)
testProperties[connectionString] = "testConnectionString"
testProperties[maxRetries] = "3"

View File

@ -14,6 +14,7 @@ limitations under the License.
package postgres
import (
"errors"
"fmt"
"time"
@ -53,7 +54,7 @@ func (m *metadata) InitWithMetadata(meta map[string]string) error {
// Validate and sanitize input
if m.ConfigTable == "" {
return fmt.Errorf("missing postgreSQL configuration table name")
return errors.New("missing postgreSQL configuration table name")
}
if len(m.ConfigTable) > maxIdentifierLength {
return fmt.Errorf("table name is too long - tableName : '%s'. max allowed field length is %d", m.ConfigTable, maxIdentifierLength)

View File

@ -156,7 +156,7 @@ func TestPubKeyCacheGetKey(t *testing.T) {
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
for range 10 {
go func() {
defer wg.Done()
result, err := cache.GetKey(context.Background(), "key")

View File

@ -85,7 +85,7 @@ func (r *StandaloneRedisLock) TryLock(ctx context.Context, req *lock.TryLockRequ
// Set a key if doesn't exist with an expiration time
nxval, err := r.client.SetNX(ctx, req.ResourceID, req.LockOwner, time.Second*time.Duration(req.ExpiryInSeconds))
if nxval == nil {
return &lock.TryLockResponse{}, fmt.Errorf("setNX returned a nil response")
return &lock.TryLockResponse{}, errors.New("setNX returned a nil response")
}
if err != nil {

View File

@ -219,7 +219,7 @@ func GetMetadataInfoFromStructType(t reflect.Type, metadataMap *MetadataMap, com
*metadataMap = MetadataMap{}
}
for i := 0; i < t.NumField(); i++ {
for i := range t.NumField() {
currentField := t.Field(i)
// fields that are not exported cannot be set via the mapstructure metadata decoding mechanism
if !currentField.IsExported() {

View File

@ -56,7 +56,7 @@ func TestRequestHandlerWithFlowRules(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "http://localhost:5001/v1.0/nodeapp/healthz", nil)
counter := &counter{}
for i := 0; i < 100; i++ {
for range 100 {
w := httptest.NewRecorder()
handler(http.HandlerFunc(counter.handle)).ServeHTTP(w, r)
}
@ -126,7 +126,6 @@ func TestLoadRules(t *testing.T) {
}
for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
sentinel, _ := NewMiddleware(nil).(*Middleware)
err := sentinel.loadSentinelRules(&c.meta)

View File

@ -91,11 +91,11 @@ var benches = map[string]struct {
httputils.RespondWithErrorAndMessage(w, http.StatusInternalServerError, body)
}
if path := r.URL.Path; path != "/v1.0/hello" {
body := fmt.Sprintf("Expected wasm to rewrite path: %s", path)
body := "Expected wasm to rewrite path: " + path
httputils.RespondWithErrorAndMessage(w, http.StatusInternalServerError, body)
}
if query := r.URL.RawQuery; query != "name=teddy" {
body := fmt.Sprintf("Expected wasm to retain query: %s", query)
body := "Expected wasm to retain query: " + query
httputils.RespondWithErrorAndMessage(w, http.StatusInternalServerError, body)
}
w.Header().Set("Content-Type", "text/plain")

View File

@ -97,7 +97,7 @@ func Test_EndToEnd(t *testing.T) {
guest: guestWasm[guestWasmOutput],
test: func(t *testing.T, handler http.Handler, log *bytes.Buffer) {
// Service more requests than one to ensure pooling works properly.
for i := 0; i < 3; i++ {
for range 3 {
r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)

View File

@ -140,7 +140,7 @@ func mapChecks(config []*AgentServiceCheck) []*consul.AgentServiceCheck {
mapped := []*consul.AgentServiceCheck{}
for i := 0; i < len(config); i++ {
for i := range len(config) {
mapped = append(mapped, mapCheck(config[i]))
}
@ -211,7 +211,7 @@ func mapAdvancedRegistration(config *AgentServiceRegistration) *consul.AgentServ
mapped.Checks = config.Checks
for i := 0; i < len(config.Paths); i++ {
for i := range len(config.Paths) {
tmp := consul.ExposePath{
ListenerPort: config.Paths[i].ListenerPort,
Path: config.Paths[i].Path,
@ -232,7 +232,7 @@ func mapAdvancedRegistration(config *AgentServiceRegistration) *consul.AgentServ
mapped := []consul.Upstream{}
for i := 0; i < len(config); i++ {
for i := range len(config) {
tmp := consul.Upstream{
DestinationType: consul.UpstreamDestType(config[i].DestinationType),
DestinationNamespace: config[i].DestinationNamespace,
@ -273,7 +273,7 @@ func mapAdvancedRegistration(config *AgentServiceRegistration) *consul.AgentServ
mapped := consul.AgentServiceChecks{}
for i := 0; i < len(config); i++ {
for i := range len(config) {
mapped = append(mapped, mapCheck(config[i]))
}

View File

@ -420,7 +420,7 @@ func getRegistrationConfig(cfg configSpec, props map[string]string) (*consul.Age
cfg.Checks = []*consul.AgentServiceCheck{
{
Name: "Dapr Health Status",
CheckID: fmt.Sprintf("daprHealth:%s", id),
CheckID: "daprHealth:" + id,
Interval: "15s",
HTTP: fmt.Sprintf("http://%s/v1.0/healthz?appid=%s", net.JoinHostPort(host, httpPort), appID),
},

View File

@ -15,6 +15,7 @@ package consul
import (
"context"
"errors"
"fmt"
"net"
"strconv"
@ -246,7 +247,6 @@ func TestInit(t *testing.T) {
}
for _, tt := range tests {
tt := tt
t.Run(tt.testName, func(t *testing.T) {
tt.test(t, tt.metadata)
})
@ -589,7 +589,7 @@ func TestResolveID(t *testing.T) {
LastIndex: 0,
}
err := fmt.Errorf("oh no")
err := errors.New("oh no")
serviceEntries := []*consul.ServiceEntry{
{
@ -909,7 +909,7 @@ func TestResolveID(t *testing.T) {
total1 := 0
total2 := 0
for i := 0; i < 100; i++ {
for range 100 {
addr, _ := resolver.ResolveID(context.Background(), req)
if addr == "10.3.245.137:50005" {
@ -1026,7 +1026,6 @@ func TestResolveID(t *testing.T) {
}
for _, tt := range tests {
tt := tt
t.Run(tt.testName, func(t *testing.T) {
tt.test(t, tt.req)
})
@ -1111,7 +1110,6 @@ func TestClose(t *testing.T) {
}
for _, tt := range tests {
tt := tt
t.Run(tt.testName, func(t *testing.T) {
t.Parallel()
tt.test(t, tt.metadata)
@ -1265,7 +1263,6 @@ func TestRegistry(t *testing.T) {
}
for _, tt := range tests {
tt := tt
t.Run(tt.testName, func(t *testing.T) {
t.Parallel()
tt.test(t)
@ -1356,7 +1353,6 @@ func TestParseConfig(t *testing.T) {
}
for _, tt := range tests {
tt := tt
t.Run(tt.testName, func(t *testing.T) {
actual, err := parseConfig(tt.input)
@ -1727,7 +1723,6 @@ func TestGetConfig(t *testing.T) {
}
for _, tt := range tests {
tt := tt
t.Run(tt.testName, func(t *testing.T) {
tt.test(t, tt.metadata)
})
@ -2015,7 +2010,7 @@ func TestMapConfig(t *testing.T) {
compareRegistration(t, expected.AdvancedRegistration, actual.AdvancedRegistration)
compareClientConfig(t, expected.Client, actual.Client)
for i := 0; i < len(expected.Checks); i++ {
for i := range len(expected.Checks) {
compareCheck(t, expected.Checks[i], actual.Checks[i])
}
@ -2102,7 +2097,7 @@ func compareRegistration(t *testing.T, expected *AgentServiceRegistration, actua
compareCheck(t, expected.Check, actual.Check)
for i := 0; i < len(expected.Checks); i++ {
for i := range len(expected.Checks) {
compareCheck(t, expected.Checks[i], actual.Checks[i])
}
@ -2113,7 +2108,7 @@ func compareRegistration(t *testing.T, expected *AgentServiceRegistration, actua
assert.Equal(t, expected.Proxy.LocalServicePort, actual.Proxy.LocalServicePort)
assert.Equal(t, expected.Proxy.Config, actual.Proxy.Config)
for i := 0; i < len(expected.Proxy.Upstreams); i++ {
for i := range len(expected.Proxy.Upstreams) {
assert.Equal(t, string(expected.Proxy.Upstreams[i].DestinationType), string(actual.Proxy.Upstreams[i].DestinationType))
assert.Equal(t, expected.Proxy.Upstreams[i].DestinationNamespace, actual.Proxy.Upstreams[i].DestinationNamespace)
assert.Equal(t, expected.Proxy.Upstreams[i].DestinationName, actual.Proxy.Upstreams[i].DestinationName)
@ -2128,7 +2123,7 @@ func compareRegistration(t *testing.T, expected *AgentServiceRegistration, actua
assert.Equal(t, expected.Proxy.Expose.Checks, actual.Proxy.Expose.Checks)
for i := 0; i < len(expected.Proxy.Expose.Paths); i++ {
for i := range len(expected.Proxy.Expose.Paths) {
assert.Equal(t, expected.Proxy.Expose.Paths[i].ListenerPort, actual.Proxy.Expose.Paths[i].ListenerPort)
assert.Equal(t, expected.Proxy.Expose.Paths[i].LocalPathPort, actual.Proxy.Expose.Paths[i].LocalPathPort)
assert.Equal(t, expected.Proxy.Expose.Paths[i].ParsedFromCheck, actual.Proxy.Expose.Paths[i].ParsedFromCheck)
@ -2192,7 +2187,7 @@ func getInstanceInfoWithoutKey(removeKey string) nr.Instance {
}
func waitTillTrueOrTimeout(d time.Duration, condition func() bool) {
for i := 0; i < 100; i++ {
for range 100 {
if condition() {
return
}

View File

@ -298,7 +298,7 @@ watchLoop:
// generate set of keys
serviceKeys := make(map[string]any)
for i := 0; i < len(services); i++ {
for i := range len(services) {
serviceKeys[services[i]] = nil
}

View File

@ -299,14 +299,14 @@ func (m *Resolver) getZeroconfResolver() (resolver *zeroconf.Resolver, err error
zeroconf.SelectIPTraffic(zeroconf.IPv4),
zeroconf.SelectIPTraffic(zeroconf.IPv6),
}
for i := 0; i < len(opts); i++ {
for i := range len(opts) {
resolver, err = zeroconf.NewResolver(opts[i])
if err == nil {
break
}
}
if err != nil {
return nil, fmt.Errorf("failed to initialize resolver after attempting IPv4+IPv6, IPv4-only, and IPv6-only")
return nil, errors.New("failed to initialize resolver after attempting IPv4+IPv6, IPv4-only, and IPv6-only")
}
return resolver, nil
}

View File

@ -142,7 +142,7 @@ func TestResolver(t *testing.T) {
// assert
require.NoError(t, err)
assert.Equal(t, fmt.Sprintf("%s:1234", localhost), pt)
assert.Equal(t, localhost+":1234", pt)
}
func TestResolverClose(t *testing.T) {
@ -163,7 +163,7 @@ func TestResolverClose(t *testing.T) {
// assert
require.NoError(t, err)
assert.Equal(t, fmt.Sprintf("%s:1234", localhost), pt)
assert.Equal(t, localhost+":1234", pt)
// act again
err = resolver.Close()
@ -217,7 +217,7 @@ func TestResolverMultipleInstances(t *testing.T) {
// instance A and instance B and we see them each atleast m times.
instanceACount := atomic.Uint32{}
instanceBCount := atomic.Uint32{}
for i := 0; i < 100; i++ {
for range 100 {
addr, err := resolver.ResolveID(context.Background(), request)
require.NoError(t, err)
require.Contains(t, []string{instanceAPQDN, instanceBPQDN}, addr)
@ -294,14 +294,14 @@ func ResolverConcurrencySubsriberClear(t *testing.T) {
request := nr.ResolveRequest{ID: "testAppID"}
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
pt, err := resolver.ResolveID(context.Background(), request)
require.NoError(t, err)
require.Equal(t, fmt.Sprintf("%s:1234", localhost), pt)
require.Equal(t, localhost+":1234", pt)
}()
}
@ -354,7 +354,7 @@ func ResolverConcurrencyFound(t *testing.T) {
// act...
wg := sync.WaitGroup{}
for i := 0; i < numConcurrency; i++ {
for i := range numConcurrency {
wg.Add(1)
go func(i int) {
defer wg.Done()
@ -401,7 +401,7 @@ func ResolverConcurrencyNotFound(t *testing.T) {
// act...
wg := sync.WaitGroup{}
for i := 0; i < numConcurrency; i++ {
for i := range numConcurrency {
idx := i
wg.Add(1)
go func() {
@ -509,7 +509,7 @@ func TestAddressListAddExisitingAddress(t *testing.T) {
// assert
require.Len(t, addressList.addresses, 2)
require.Greater(t, deltaSec, 0) // Ensures expiry has been extended for existing address.
require.Positive(t, deltaSec, 0) // Ensures expiry has been extended for existing address.
}
func TestAddressListNext(t *testing.T) {

View File

@ -102,7 +102,7 @@ func TestSqliteNameResolver(t *testing.T) {
require.Equal(t, tc.expectOne, res)
}
} else {
for i := 0; i < 20; i++ {
for i := range 20 {
res, err := nr.ResolveID(context.Background(), nameresolution.ResolveRequest{ID: tc.appID})
require.NoErrorf(t, err, "Error on iteration %d", i)
require.Contains(t, tc.expectAny, res)

View File

@ -61,7 +61,7 @@ type snsSqsMetadata struct {
func maskLeft(s string) string {
rs := []rune(s)
for i := 0; i < len(rs)-4; i++ {
for i := range len(rs) - 4 {
rs[i] = 'X'
}
return string(rs)

View File

@ -414,7 +414,7 @@ func (s *snsSqs) getSnsSqsSubscriptionArn(parentCtx context.Context, topicArn st
}
}
return "", fmt.Errorf("sns sqs subscription not found for topic arn")
return "", errors.New("sns sqs subscription not found for topic arn")
}
func (s *snsSqs) getOrCreateSnsSqsSubscription(ctx context.Context, queueArn, topicArn string) (subscriptionArn string, err error) {
@ -552,7 +552,7 @@ func (s *snsSqs) callHandler(ctx context.Context, message *sqs.Message, queueInf
)
if handler, loadOK = s.subscriptionManager.GetSubscriptionTopicHandler(sanitizedTopic); loadOK {
if len(handler.requestTopic) == 0 {
return fmt.Errorf("handler topic name is missing")
return errors.New("handler topic name is missing")
}
} else {
return fmt.Errorf("handler for (sanitized) topic: %s was not found", sanitizedTopic)

View File

@ -335,7 +335,7 @@ func Test_replaceNameToAWSSanitizedExistingFifoName_NonMax(t *testing.T) {
s := `0123456789`
v := nameToAWSSanitizedName(s, true)
r.EqualValues(len(s)+len(".fifo"), len(v))
r.Len(v, len(s)+len(".fifo"))
r.Equal("0123456789.fifo", v)
}

View File

@ -256,7 +256,7 @@ func (a *azureServiceBus) connectAndReceive(ctx context.Context, req pubsub.Subs
func (a *azureServiceBus) connectAndReceiveWithSessions(ctx context.Context, req pubsub.SubscribeRequest, sub *impl.Subscription, handlerFn impl.HandlerFn, onFirstSuccess func(), maxConcurrentSessions int) {
sessionsChan := make(chan struct{}, maxConcurrentSessions)
for i := 0; i < maxConcurrentSessions; i++ {
for range maxConcurrentSessions {
sessionsChan <- struct{}{}
}

View File

@ -213,7 +213,7 @@ func TestCreateCloudEventsEnvelopeExpiration(t *testing.T) {
ApplyMetadata(envelope, []Feature{FeatureMessageTTL}, map[string]string{
"ttlInSeconds": "10000",
})
assert.Equal(t, nil, envelope[ExpirationField])
assert.Nil(t, envelope[ExpirationField])
assert.False(t, HasExpired(envelope))
})
@ -376,7 +376,7 @@ func TestCreateFromCloudEventsProtobufPayload(t *testing.T) {
contenttypes := []string{contribContenttype.CloudEventProtobufContentType, contribContenttype.ProtobufContentType}
for i := 0; i < len(contenttypes); i++ {
for i := range len(contenttypes) {
envelope := NewCloudEventsEnvelope("", "", "", "", "", "",
contenttypes[i], ceProtoBytes, "trace", "")

View File

@ -320,7 +320,7 @@ func BuildSubscriptionID(consumerID, topic string) string {
func (g *GCPPubSub) handleSubscriptionMessages(parentCtx context.Context, topic *gcppubsub.Topic, sub *gcppubsub.Subscription, handler pubsub.Handler) error {
// Limit the number of attempted reconnects we make.
reconnAttempts := make(chan struct{}, g.metadata.MaxReconnectionAttempts)
for i := 0; i < g.metadata.MaxReconnectionAttempts; i++ {
for range g.metadata.MaxReconnectionAttempts {
reconnAttempts <- struct{}{}
}

View File

@ -76,7 +76,7 @@ func (a *bus) Subscribe(ctx context.Context, req pubsub.SubscribeRequest, handle
// For this component we allow built-in retries because it is backed by memory
retryHandler := func(data []byte) {
for i := 0; i < 10; i++ {
for range 10 {
handleErr := handler(ctx, &pubsub.NewMessage{Data: data, Topic: req.Topic, Metadata: req.Metadata})
if handleErr == nil {
break

View File

@ -14,6 +14,7 @@ limitations under the License.
package jetstream
import (
"errors"
"fmt"
"time"
@ -70,23 +71,23 @@ func parseMetadata(psm pubsub.Metadata) (metadata, error) {
}
if m.NatsURL == "" {
return metadata{}, fmt.Errorf("missing nats URL")
return metadata{}, errors.New("missing nats URL")
}
if m.Jwt != "" && m.SeedKey == "" {
return metadata{}, fmt.Errorf("missing seed key")
return metadata{}, errors.New("missing seed key")
}
if m.Jwt == "" && m.SeedKey != "" {
return metadata{}, fmt.Errorf("missing jwt")
return metadata{}, errors.New("missing jwt")
}
if m.TLSClientCert != "" && m.TLSClientKey == "" {
return metadata{}, fmt.Errorf("missing tls client key")
return metadata{}, errors.New("missing tls client key")
}
if m.TLSClientCert == "" && m.TLSClientKey != "" {
return metadata{}, fmt.Errorf("missing tls client cert")
return metadata{}, errors.New("missing tls client cert")
}
if m.Name == "" {

View File

@ -3,6 +3,7 @@ package kubemq
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
@ -104,7 +105,7 @@ func (k *kubeMQEvents) Publish(req *pubsub.PublishRequest) error {
return err
}
if req.Topic == "" {
return fmt.Errorf("kubemq pub/sub error: topic is required")
return errors.New("kubemq pub/sub error: topic is required")
}
metadata := ""
if req.Metadata != nil {

View File

@ -2,7 +2,7 @@ package kubemq
import (
"context"
"fmt"
"errors"
"testing"
"time"
@ -111,7 +111,7 @@ func Test_kubeMQEvents_Publish(t *testing.T) {
Topic: "some-topic",
},
resultError: nil,
publishErr: fmt.Errorf("some error"),
publishErr: errors.New("some error"),
wantErr: true,
},
}
@ -175,7 +175,7 @@ func Test_kubeMQEvents_Subscribe(t *testing.T) {
subscribeHandler: func(ctx context.Context, msg *pubsub.NewMessage) error {
return nil
},
subscribeError: fmt.Errorf("some error"),
subscribeError: errors.New("some error"),
wantErr: true,
},
}

View File

@ -3,6 +3,7 @@ package kubemq
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
@ -108,7 +109,7 @@ func (k *kubeMQEventStore) Publish(req *pubsub.PublishRequest) error {
return err
}
if req.Topic == "" {
return fmt.Errorf("kubemq pub/sub error: topic is required")
return errors.New("kubemq pub/sub error: topic is required")
}
k.logger.Debugf("kubemq pub/sub: publishing message to %s", req.Topic)
metadata := ""
@ -143,7 +144,7 @@ func (k *kubeMQEventStore) Publish(req *pubsub.PublishRequest) error {
return res.Err
}
case <-time.After(k.waitForResultTimeout):
return fmt.Errorf("kubemq pub/sub error: timeout waiting for response")
return errors.New("kubemq pub/sub error: timeout waiting for response")
}
return nil
}

View File

@ -2,7 +2,7 @@ package kubemq
import (
"context"
"fmt"
"errors"
"testing"
"time"
@ -114,7 +114,7 @@ func Test_kubeMQEventsStore_Publish(t *testing.T) {
Data: []byte("data"),
Topic: "some-topic",
},
resultError: fmt.Errorf("some error"),
resultError: errors.New("some error"),
wantErr: true,
},
{
@ -134,7 +134,7 @@ func Test_kubeMQEventsStore_Publish(t *testing.T) {
Topic: "some-topic",
},
resultError: nil,
publishErr: fmt.Errorf("some error"),
publishErr: errors.New("some error"),
wantErr: true,
},
}
@ -198,7 +198,7 @@ func Test_kubeMQkubeMQEventsStore_Subscribe(t *testing.T) {
subscribeHandler: func(ctx context.Context, msg *pubsub.NewMessage) error {
return nil
},
subscribeError: fmt.Errorf("some error"),
subscribeError: errors.New("some error"),
wantErr: true,
},
}

View File

@ -1,7 +1,7 @@
package kubemq
import (
"fmt"
"errors"
"strconv"
"strings"
@ -26,15 +26,15 @@ func parseAddress(address string) (string, int, error) {
var err error
hostPort := strings.Split(address, ":")
if len(hostPort) != 2 {
return "", 0, fmt.Errorf("invalid kubeMQ address, address format is invalid")
return "", 0, errors.New("invalid kubeMQ address, address format is invalid")
}
host = hostPort[0]
if len(host) == 0 {
return "", 0, fmt.Errorf("invalid kubeMQ address, host is empty")
return "", 0, errors.New("invalid kubeMQ address, host is empty")
}
port, err = strconv.Atoi(hostPort[1])
if err != nil {
return "", 0, fmt.Errorf("invalid kubeMQ address, port is invalid")
return "", 0, errors.New("invalid kubeMQ address, port is invalid")
}
return host, port, nil
}
@ -56,7 +56,7 @@ func createMetadata(pubSubMetadata pubsub.Metadata) (*kubemqMetadata, error) {
return nil, err
}
} else {
return nil, fmt.Errorf("invalid kubeMQ address, address is empty")
return nil, errors.New("invalid kubeMQ address, address is empty")
}
return result, nil
}

View File

@ -459,7 +459,7 @@ func buildRegexForTopic(topicName string) string {
if strings.ContainsAny(topicName, "#+") {
regexStr = "^"
// It's ok to iterate over bytes here (rather than codepoints) because all characters we're looking for are always single-byte
for i := 0; i < len(topicName); i++ {
for i := range len(topicName) {
// Wildcard chars must either be at the beginning of the string or must follow a /
okPos = (i == 0 || topicName[i-1] == '/')
if topicName[i] == '#' && okPos {

View File

@ -15,7 +15,7 @@ package pubsub
import (
"context"
"fmt"
"errors"
"github.com/dapr/components-contrib/health"
"github.com/dapr/components-contrib/metadata"
@ -72,6 +72,6 @@ func Ping(ctx context.Context, pubsub PubSub) error {
if pubsubWithPing, ok := pubsub.(health.Pinger); ok {
return pubsubWithPing.Ping(ctx)
} else {
return fmt.Errorf("ping is not implemented by this pubsub")
return errors.New("ping is not implemented by this pubsub")
}
}

View File

@ -212,7 +212,7 @@ func (p *Pulsar) Init(ctx context.Context, metadata pubsub.Metadata) error {
}
})
if err != nil {
return fmt.Errorf("could not initialize pulsar lru cache for publisher")
return errors.New("could not initialize pulsar lru cache for publisher")
}
p.cache = c
defer p.cache.Purge()
@ -318,7 +318,6 @@ func parsePublishMetadata(req *pubsub.PublishRequest, schema schemaMetadata) (
case jsonProtocol:
var obj interface{}
err = json.Unmarshal(req.Data, &obj)
if err != nil {
return nil, err
}
@ -332,7 +331,6 @@ func parsePublishMetadata(req *pubsub.PublishRequest, schema schemaMetadata) (
}
err = avro.Unmarshal(avroSchema, req.Data, &obj)
if err != nil {
return nil, err
}

View File

@ -104,7 +104,7 @@ func TestCreateMetadata(t *testing.T) {
invalidDeliveryModes := []string{"3", "10", "-1"}
for _, deliveryMode := range invalidDeliveryModes {
t.Run(fmt.Sprintf("deliveryMode value=%s", deliveryMode), func(t *testing.T) {
t.Run("deliveryMode value="+deliveryMode, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{
@ -317,7 +317,7 @@ func TestCreateMetadata(t *testing.T) {
})
for _, tt := range booleanFlagTests {
t.Run(fmt.Sprintf("autoAck value=%s", tt.in), func(t *testing.T) {
t.Run("autoAck value="+tt.in, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{
@ -337,7 +337,7 @@ func TestCreateMetadata(t *testing.T) {
}
for _, tt := range booleanFlagTests {
t.Run(fmt.Sprintf("requeueInFailure value=%s", tt.in), func(t *testing.T) {
t.Run("requeueInFailure value="+tt.in, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{
@ -357,7 +357,7 @@ func TestCreateMetadata(t *testing.T) {
}
for _, tt := range booleanFlagTests {
t.Run(fmt.Sprintf("deleteWhenUnused value=%s", tt.in), func(t *testing.T) {
t.Run("deleteWhenUnused value="+tt.in, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{
@ -377,7 +377,7 @@ func TestCreateMetadata(t *testing.T) {
}
for _, tt := range booleanFlagTests {
t.Run(fmt.Sprintf("durable value=%s", tt.in), func(t *testing.T) {
t.Run("durable value="+tt.in, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{
@ -397,7 +397,7 @@ func TestCreateMetadata(t *testing.T) {
}
for _, tt := range booleanFlagTests {
t.Run(fmt.Sprintf("publisherConfirm value=%s", tt.in), func(t *testing.T) {
t.Run("publisherConfirm value="+tt.in, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{
@ -417,7 +417,7 @@ func TestCreateMetadata(t *testing.T) {
}
for _, tt := range booleanFlagTests {
t.Run(fmt.Sprintf("enableDeadLetter value=%s", tt.in), func(t *testing.T) {
t.Run("enableDeadLetter value="+tt.in, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{
@ -438,7 +438,7 @@ func TestCreateMetadata(t *testing.T) {
validExchangeKind := []string{amqp.ExchangeDirect, amqp.ExchangeTopic, amqp.ExchangeFanout, amqp.ExchangeHeaders}
for _, exchangeKind := range validExchangeKind {
t.Run(fmt.Sprintf("exchangeKind value=%s", exchangeKind), func(t *testing.T) {
t.Run("exchangeKind value="+exchangeKind, func(t *testing.T) {
fakeProperties := getFakeProperties()
fakeMetaData := pubsub.Metadata{

View File

@ -134,7 +134,6 @@ func dial(protocol, uri, clientName string, heartBeat time.Duration, tlsCfg *tls
}
}
conn, err = amqp.DialConfig(uri, cfg)
if err != nil {
return nil, nil, err
}
@ -272,7 +271,7 @@ func (r *rabbitMQ) publishSync(ctx context.Context, req *pubsub.PublishRequest)
// Blocks until the server confirms
ok := confirm.Wait()
if !ok {
err = fmt.Errorf("did not receive confirmation of publishing")
err = errors.New("did not receive confirmation of publishing")
r.logger.Errorf("%s publishing to %s failed: %v", logMessagePrefix, req.Topic, err)
}
}
@ -482,7 +481,7 @@ func (r *rabbitMQ) prepareSubscription(channel rabbitMQChannelBroker, req pubsub
metadataRoutingKey = val
}
routingKeys := strings.Split(metadataRoutingKey, ",")
for i := 0; i < len(routingKeys); i++ {
for i := range len(routingKeys) {
routingKey := routingKeys[i]
r.logger.Debugf("%s binding queue '%s' to exchange '%s' with routing key '%s'", logMessagePrefix, q.Name, req.Topic, routingKey)
err = channel.QueueBind(q.Name, routingKey, req.Topic, false, nil)
@ -521,7 +520,6 @@ func (r *rabbitMQ) subscribeForever(ctx context.Context, req pubsub.SubscribeReq
)
for {
channel, connectionCount, q, err = r.ensureSubscription(req, queueName)
if err != nil {
errFuncName = "ensureSubscription"
break

View File

@ -86,7 +86,7 @@ func (r *redisStreams) Init(ctx context.Context, metadata pubsub.Metadata) error
}
r.queue = make(chan redisMessageWrapper, int(r.clientSettings.QueueDepth))
for i := uint(0); i < r.clientSettings.Concurrency; i++ {
for range r.clientSettings.Concurrency {
r.wg.Add(1)
go func() {
defer r.wg.Done()

View File

@ -130,7 +130,6 @@ func (a *amqpPubSub) Publish(ctx context.Context, req *pubsub.PublishRequest) er
a.logger.Errorf("Unable to create link to %s", req.Topic, err)
} else {
err = sender.Send(ctx, m, nil)
// If the publish operation has failed, attempt to republish a maximum number of times
// before giving up
if err != nil {
@ -139,7 +138,6 @@ func (a *amqpPubSub) Publish(ctx context.Context, req *pubsub.PublishRequest) er
// Send message
err = sender.Send(ctx, m, nil)
if err != nil {
a.logger.Warnf("Failed to publish a message to the broker", err)
}

View File

@ -65,7 +65,7 @@ func ConvertTLSPropertiesToTLSConfig(properties TLSProperties) (*tls.Config, err
if properties.CACert != "" {
tlsConfig.RootCAs = x509.NewCertPool()
if ok := tlsConfig.RootCAs.AppendCertsFromPEM([]byte(properties.CACert)); !ok {
return tlsConfig, fmt.Errorf("unable to load CA certificate")
return tlsConfig, errors.New("unable to load CA certificate")
}
}

View File

@ -15,7 +15,7 @@ package parameterstore
import (
"context"
"fmt"
"errors"
"testing"
oos "github.com/alibabacloud-go/oos-20190601/client"
@ -62,11 +62,11 @@ func (m *mockedParameterStore) GetSecretParametersByPathWithOptions(request *oos
type mockedParameterStoreReturnError struct{}
func (m *mockedParameterStoreReturnError) GetSecretParameterWithOptions(request *oos.GetSecretParameterRequest, runtime *util.RuntimeOptions) (*oos.GetSecretParameterResponse, error) {
return nil, fmt.Errorf("mocked error")
return nil, errors.New("mocked error")
}
func (m *mockedParameterStoreReturnError) GetSecretParametersByPathWithOptions(request *oos.GetSecretParametersByPathRequest, runtime *util.RuntimeOptions) (*oos.GetSecretParametersByPathResponse, error) {
return nil, fmt.Errorf("mocked error")
return nil, errors.New("mocked error")
}
func TestInit(t *testing.T) {

View File

@ -16,6 +16,7 @@ package parameterstore
import (
"context"
"errors"
"fmt"
"strings"
"testing"
@ -73,7 +74,7 @@ func TestInit(t *testing.T) {
s.(*ssmSecretStore).client = &mockedSSM{
GetParameterFn: func(ctx context.Context, input *ssm.GetParameterInput, option ...request.Option) (*ssm.GetParameterOutput, error) {
// Simulate a failure that resembles what AWS SSM would return
return nil, fmt.Errorf("wrong-credentials")
return nil, errors.New("wrong-credentials")
},
}
@ -173,7 +174,7 @@ func TestGetSecret(t *testing.T) {
s := ssmSecretStore{
client: &mockedSSM{
GetParameterFn: func(ctx context.Context, input *ssm.GetParameterInput, option ...request.Option) (*ssm.GetParameterOutput, error) {
return nil, fmt.Errorf("failed due to any reason")
return nil, errors.New("failed due to any reason")
},
},
}
@ -272,7 +273,7 @@ func TestGetBulkSecrets(t *testing.T) {
}}, nil
},
GetParameterFn: func(ctx context.Context, input *ssm.GetParameterInput, option ...request.Option) (*ssm.GetParameterOutput, error) {
return nil, fmt.Errorf("failed due to any reason")
return nil, errors.New("failed due to any reason")
},
},
}
@ -287,7 +288,7 @@ func TestGetBulkSecrets(t *testing.T) {
s := ssmSecretStore{
client: &mockedSSM{
DescribeParametersFn: func(context.Context, *ssm.DescribeParametersInput, ...request.Option) (*ssm.DescribeParametersOutput, error) {
return nil, fmt.Errorf("failed due to any reason")
return nil, errors.New("failed due to any reason")
},
},
}

View File

@ -16,7 +16,7 @@ package secretmanager
import (
"context"
"fmt"
"errors"
"testing"
"github.com/aws/aws-sdk-go/aws/request"
@ -141,7 +141,7 @@ func TestGetSecret(t *testing.T) {
s := smSecretStore{
client: &mockedSM{
GetSecretValueFn: func(ctx context.Context, input *secretsmanager.GetSecretValueInput, option ...request.Option) (*secretsmanager.GetSecretValueOutput, error) {
return nil, fmt.Errorf("failed due to any reason")
return nil, errors.New("failed due to any reason")
},
},
}

View File

@ -16,6 +16,7 @@ package secretmanager
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
@ -103,11 +104,11 @@ func (s *Store) GetSecret(ctx context.Context, req secretstores.GetSecretRequest
res := secretstores.GetSecretResponse{Data: nil}
if s.client == nil {
return res, fmt.Errorf("client is not initialized")
return res, errors.New("client is not initialized")
}
if req.Name == "" {
return res, fmt.Errorf("missing secret name in request")
return res, errors.New("missing secret name in request")
}
secretName := fmt.Sprintf("projects/%s/secrets/%s", s.ProjectID, req.Name)
@ -131,11 +132,11 @@ func (s *Store) BulkGetSecret(ctx context.Context, req secretstores.BulkGetSecre
response := map[string]map[string]string{}
if s.client == nil {
return secretstores.BulkGetSecretResponse{Data: nil}, fmt.Errorf("client is not initialized")
return secretstores.BulkGetSecretResponse{Data: nil}, errors.New("client is not initialized")
}
request := &secretmanagerpb.ListSecretsRequest{
Parent: fmt.Sprintf("projects/%s", s.ProjectID),
Parent: "projects/" + s.ProjectID,
}
it := s.client.ListSecrets(ctx, request)
@ -183,16 +184,16 @@ func (s *Store) parseSecretManagerMetadata(metadataRaw secretstores.Metadata) (*
}
if meta.Type == "" {
return nil, fmt.Errorf("missing property `type` in metadata")
return nil, errors.New("missing property `type` in metadata")
}
if meta.ProjectID == "" {
return nil, fmt.Errorf("missing property `project_id` in metadata")
return nil, errors.New("missing property `project_id` in metadata")
}
if meta.PrivateKey == "" {
return nil, fmt.Errorf("missing property `private_key` in metadata")
return nil, errors.New("missing property `private_key` in metadata")
}
if meta.ClientEmail == "" {
return nil, fmt.Errorf("missing property `client_email` in metadata")
return nil, errors.New("missing property `client_email` in metadata")
}
return &meta, nil

View File

@ -15,7 +15,7 @@ package secretmanager
import (
"context"
"fmt"
"errors"
"testing"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
@ -71,7 +71,7 @@ func TestInit(t *testing.T) {
err := sm.Init(ctx, m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("failed to setup secretmanager client: google: could not parse key: private key should be a PEM or plain PKCS1 or PKCS8; parse error: asn1: syntax error: truncated tag or length"))
assert.Equal(t, err, errors.New("failed to setup secretmanager client: google: could not parse key: private key should be a PEM or plain PKCS1 or PKCS8; parse error: asn1: syntax error: truncated tag or length"))
})
t.Run("Init with missing `type` metadata", func(t *testing.T) {
@ -80,7 +80,7 @@ func TestInit(t *testing.T) {
}
err := sm.Init(ctx, m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("missing property `type` in metadata"))
assert.Equal(t, err, errors.New("missing property `type` in metadata"))
})
t.Run("Init with missing `project_id` metadata", func(t *testing.T) {
@ -89,7 +89,7 @@ func TestInit(t *testing.T) {
}
err := sm.Init(ctx, m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("missing property `project_id` in metadata"))
assert.Equal(t, err, errors.New("missing property `project_id` in metadata"))
})
}
@ -100,7 +100,7 @@ func TestGetSecret(t *testing.T) {
t.Run("Get Secret - without Init", func(t *testing.T) {
v, err := sm.GetSecret(context.Background(), secretstores.GetSecretRequest{Name: "test"})
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("client is not initialized"))
assert.Equal(t, err, errors.New("client is not initialized"))
assert.Equal(t, secretstores.GetSecretResponse{Data: nil}, v)
})
@ -154,7 +154,7 @@ func TestBulkGetSecret(t *testing.T) {
t.Run("Bulk Get Secret - without Init", func(t *testing.T) {
v, err := sm.BulkGetSecret(context.Background(), secretstores.BulkGetSecretRequest{})
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("client is not initialized"))
assert.Equal(t, err, errors.New("client is not initialized"))
assert.Equal(t, secretstores.BulkGetSecretResponse{Data: nil}, v)
})

View File

@ -400,12 +400,12 @@ func (v *vaultSecretStore) isSecretPath(key string) bool {
func (v *vaultSecretStore) initVaultToken() error {
// Test that at least one of them are set if not return error
if v.vaultToken == "" && v.vaultTokenMountPath == "" {
return fmt.Errorf("token mount path and token not set")
return errors.New("token mount path and token not set")
}
// Test that both are not set. If so return error
if v.vaultToken != "" && v.vaultTokenMountPath != "" {
return fmt.Errorf("token mount path and token both set")
return errors.New("token mount path and token both set")
}
if v.vaultToken != "" {
@ -464,7 +464,7 @@ func (v *vaultSecretStore) getRootCAsPools(vaultCAPem string, vaultCAPath string
certPool := x509.NewCertPool()
cert := []byte(vaultCAPem)
if ok := certPool.AppendCertsFromPEM(cert); !ok {
return nil, fmt.Errorf("couldn't read PEM")
return nil, errors.New("couldn't read PEM")
}
return certPool, nil
@ -505,7 +505,7 @@ func readCertificateFile(certPool *x509.CertPool, path string) error {
}
if ok := certPool.AppendCertsFromPEM(pemFile); !ok {
return fmt.Errorf("couldn't read PEM")
return errors.New("couldn't read PEM")
}
return nil

View File

@ -15,7 +15,7 @@ package csms
import (
"context"
"fmt"
"errors"
"testing"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/csms/v1/model"
@ -72,17 +72,17 @@ func (m *mockedCsmsSecretStoreReturnError) ListSecrets(request *model.ListSecret
}
func (m *mockedCsmsSecretStoreReturnError) ShowSecretVersion(request *model.ShowSecretVersionRequest) (*model.ShowSecretVersionResponse, error) {
return nil, fmt.Errorf("mocked error")
return nil, errors.New("mocked error")
}
type mockedCsmsSecretStoreBothReturnError struct{}
func (m *mockedCsmsSecretStoreBothReturnError) ListSecrets(request *model.ListSecretsRequest) (*model.ListSecretsResponse, error) {
return nil, fmt.Errorf("mocked error")
return nil, errors.New("mocked error")
}
func (m *mockedCsmsSecretStoreBothReturnError) ShowSecretVersion(request *model.ShowSecretVersionRequest) (*model.ShowSecretVersionResponse, error) {
return nil, fmt.Errorf("mocked error")
return nil, errors.New("mocked error")
}
func TestGetSecret(t *testing.T) {

View File

@ -196,7 +196,7 @@ func (j *localSecretStore) visitPrimitive(context string) error {
}
func (j *localSecretStore) visitArray(array []interface{}) error {
for i := 0; i < len(array); i++ {
for i := range len(array) {
j.enterContext(strconv.Itoa(i))
err := j.visitProperty(array[i])
if err != nil {
@ -244,7 +244,7 @@ func (j *localSecretStore) getLocalSecretStoreMetadata(spec secretstores.Metadat
}
if meta.SecretsFile == "" {
return nil, fmt.Errorf("missing local secrets file in metadata")
return nil, errors.New("missing local secrets file in metadata")
}
return &meta, nil

View File

@ -17,6 +17,7 @@ package file
import (
"context"
"encoding/json"
"errors"
"fmt"
"testing"
@ -52,7 +53,7 @@ func TestInit(t *testing.T) {
}
err := s.Init(context.Background(), m)
require.Error(t, err)
assert.Equal(t, err, fmt.Errorf("missing local secrets file in metadata"))
assert.Equal(t, err, errors.New("missing local secrets file in metadata"))
})
}

Some files were not shown because too many files have changed in this diff Show More