Use revive instead of golint (#4555)

* Use revive instead of golint

Signed-off-by: pigletfly <wangbing.adam@gmail.com>

* Fixed test

Signed-off-by: Alessandro (Ale) Segala <43508+ItalyPaleAle@users.noreply.github.com>

Co-authored-by: Alessandro (Ale) Segala <43508+ItalyPaleAle@users.noreply.github.com>
Co-authored-by: Yaron Schneider <schneider.yaron@live.com>
Co-authored-by: Artur Souza <artursouza.ms@outlook.com>
This commit is contained in:
authored and GitHub committed 2022-05-05 14:02:43 -07:00
1 parent f471c46a27
commit ade2935597
54 files changed
+161 -133

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
runs-on: ${{ matrix.os }}
env:
GOVER: 1.17
GOLANGCILINT_VER: v1.31
GOLANGCILINT_VER: v1.45.2
GOOS: ${{ matrix.target_os }}
GOARCH: ${{ matrix.target_arch }}
GOPROXY: https://proxy.golang.org
+27 -1
View File
@@ -129,7 +129,7 @@ linters-settings:
# Correct spellings using locale preferences for US or UK.
# Default is to use a neutral variety of English.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
locale: default
# locale: default
ignore-words:
- someword
lll:
@@ -247,6 +247,32 @@ linters:
- exhaustive
- noctx
- gci
- golint
- tparallel
- paralleltest
- wrapcheck
- tagliatelle
- ireturn
- exhaustivestruct
- errchkjson
- contextcheck
- gomoddirectives
- godot
- cyclop
- varnamelen
- gosec
- errorlint
- forcetypeassert
- ifshort
- maintidx
- nilnil
- predeclared
- tenv
- thelper
- wastedassign
- containedctx
- gosimple
- forbidigo
issues:
exclude:
# staticcheck
+1 -1
View File
@@ -25,7 +25,7 @@ import (
)
// ErrActorDisposed is the error when runtime tries to hold the lock of the disposed actor.
var ErrActorDisposed error = errors.New("actor is already disposed")
var ErrActorDisposed = errors.New("actor is already disposed")
// actor represents single actor object and maintains its turn-based concurrency.
type actor struct {
+1 -1
View File
@@ -20,7 +20,7 @@ import (
"go.uber.org/atomic"
)
var ErrMaxStackDepthExceeded error = errors.New("Maximum stack depth exceeded")
var ErrMaxStackDepthExceeded = errors.New("Maximum stack depth exceeded")
type ActorLock struct {
methodLock *sync.Mutex
+7 -4
View File
@@ -150,7 +150,8 @@ func NewActors(
tracingSpec configuration.TracingSpec,
features []configuration.FeatureSpec,
resiliency resiliency.Provider,
stateStoreName string) Actors {
stateStoreName string,
) Actors {
var transactionalStore state.TransactionalStore
if stateStore != nil {
features := stateStore.Features()
@@ -344,7 +345,8 @@ func (a *actorsRuntime) callRemoteActorWithRetry(
numRetries int,
backoffInterval time.Duration,
fn func(ctx context.Context, targetAddress, targetID string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error),
targetAddress, targetID string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
targetAddress, targetID string, req *invokev1.InvokeMethodRequest,
) (*invokev1.InvokeMethodResponse, error) {
for i := 0; i < numRetries; i++ {
resp, err := fn(ctx, targetAddress, targetID, req)
if err == nil {
@@ -445,7 +447,8 @@ func (a *actorsRuntime) callLocalActor(ctx context.Context, req *invokev1.Invoke
func (a *actorsRuntime) callRemoteActor(
ctx context.Context,
targetAddress, targetID string,
req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
req *invokev1.InvokeMethodRequest,
) (*invokev1.InvokeMethodResponse, error) {
conn, err := a.grpcConnectionFn(context.TODO(), targetAddress, targetID, a.config.Namespace, false, false, false)
if err != nil {
return nil, err
@@ -960,7 +963,7 @@ func (m *ActorMetadata) calculateEtag(partitionID uint32) *string {
func (m *ActorMetadata) removeReminderFromPartition(reminderRefs []actorReminderReference, actorType, actorID, reminderName string) ([]Reminder, string, *string) {
// First, we find the partition
var partitionID uint32 = 0
var partitionID uint32
if m.RemindersMetadata.PartitionCount > 0 {
for _, reminderRef := range reminderRefs {
if reminderRef.reminder.ActorType == actorType && reminderRef.reminder.ActorID == actorID && reminderRef.reminder.Name == reminderName {
-1
View File
@@ -250,7 +250,6 @@ func (f *FailingActors) Init() error {
}
func (f *FailingActors) Stop() {
}
func (f *FailingActors) GetState(ctx context.Context, req *GetStateRequest) (*StateResponse, error) {
+2 -1
View File
@@ -118,7 +118,8 @@ func NewActorPlacement(
serverAddr []string, clientCert *dapr_credentials.CertChain,
appID, runtimeHostName string, actorTypes []string,
appHealthFn func() bool,
afterTableUpdateFn func()) *ActorPlacement {
afterTableUpdateFn func(),
) *ActorPlacement {
return &ActorPlacement{
actorTypes: actorTypes,
appID: appID,
+1 -1
View File
@@ -335,7 +335,7 @@ func (s *testServer) ReportDaprStatus(srv placementv1pb.Placement_ReportDaprStat
return nil
} else if err != nil {
s.recvError = err
return nil
return err
}
s.recvCount.Inc()
s.lastHost = req
+1 -1
View File
@@ -14,7 +14,7 @@ import (
const configPrefix = "."
func writeTempConfig(path, content string) error {
return os.WriteFile(filepath.Join(configPrefix, path), []byte(content), fs.FileMode(0644))
return os.WriteFile(filepath.Join(configPrefix, path), []byte(content), fs.FileMode(0o644))
}
func TestLoadComponentsFromFile(t *testing.T) {
+1 -1
View File
@@ -308,7 +308,7 @@ func sortAndValidateSecretsConfiguration(conf *Configuration) error {
// IsSecretAllowed Check if the secret is allowed to be accessed.
func (c SecretsScope) IsSecretAllowed(key string) bool {
// By default, set allow access for the secret store.
var access string = AllowAccess
access := AllowAccess
// Check and set deny access.
if strings.EqualFold(c.DefaultAccess, DenyAccess) {
access = DenyAccess
+2 -2
View File
@@ -12,7 +12,7 @@ import (
func GetServerOptions(certChain *CertChain) ([]grpc.ServerOption, error) {
opts := []grpc.ServerOption{}
if certChain == nil {
return opts, nil
return nil, nil
}
cp := x509.NewCertPool()
@@ -20,7 +20,7 @@ func GetServerOptions(certChain *CertChain) ([]grpc.ServerOption, error) {
cert, err := tls.X509KeyPair(certChain.Cert, certChain.Key)
if err != nil {
return opts, nil
return nil, err
}
// nolint:gosec
+2 -4
View File
@@ -24,10 +24,8 @@ func TestServerOptions(t *testing.T) {
Cert: []byte(nil),
Key: []byte(nil),
}
opts, err := GetServerOptions(chain)
assert.Nil(t, err)
assert.NotNil(t, opts)
assert.Len(t, opts, 0)
_, err := GetServerOptions(chain)
assert.Error(t, err)
})
}
+1 -1
View File
@@ -129,7 +129,7 @@ func UpdateSpanStatusFromHTTPStatus(span *trace.Span, code int) {
// https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md#status
func traceStatusFromHTTPCode(httpCode int) trace.Status {
var code codes.Code = codes.Unknown
code := codes.Unknown
switch httpCode {
case http.StatusUnauthorized:
code = codes.Unauthenticated
+2 -1
View File
@@ -143,7 +143,8 @@ func NewAPI(
accessControlList *config.AccessControlList,
appProtocol string,
getComponentsFn func() []components_v1alpha.Component,
shutdown func()) API {
shutdown func(),
) API {
transactionalStateStores := map[string]state.TransactionalStore{}
for key, store := range stateStores {
if state.FeatureTransactional.IsPresent(store.Features()) {
+1
View File
@@ -3161,6 +3161,7 @@ func (c fakeStateStore) BulkGet(req []state.GetRequest) (bool, []state.BulkGetRe
}
func (c fakeStateStore) Init(metadata state.Metadata) error {
//nolint:staticcheck
c.counter = 0
return nil
}
+2 -1
View File
@@ -118,7 +118,8 @@ const (
)
func (i *injector) getPodPatchOperations(ar *v1.AdmissionReview,
namespace, image, imagePullPolicy string, kubeClient kubernetes.Interface, daprClient scheme.Interface) ([]PatchOperation, error) {
namespace, image, imagePullPolicy string, kubeClient kubernetes.Interface, daprClient scheme.Interface,
) ([]PatchOperation, error) {
req := ar.Request
var pod corev1.Pod
if err := json.Unmarshal(req.Object.Raw, &pod); err != nil {
+4 -2
View File
@@ -80,7 +80,8 @@ func NewDirectMessaging(
appChannel channel.AppChannel,
clientConnFn messageClientConnection,
resolver nr.Resolver,
tracingSpec config.TracingSpec, maxRequestBodySize int, proxy Proxy, readBufferSize int, streamRequestBody bool) DirectMessaging {
tracingSpec config.TracingSpec, maxRequestBodySize int, proxy Proxy, readBufferSize int, streamRequestBody bool,
) DirectMessaging {
hAddr, _ := utils.GetHostAddress()
hName, _ := os.Hostname()
@@ -142,7 +143,8 @@ func (d *directMessaging) invokeWithRetry(
backoffInterval time.Duration,
app remoteApp,
fn func(ctx context.Context, appID, namespace, appAddress string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error),
req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
req *invokev1.InvokeMethodRequest,
) (*invokev1.InvokeMethodResponse, error) {
for i := 0; i < numRetries; i++ {
resp, err := fn(ctx, app.id, app.namespace, app.address, req)
if err == nil {
+2 -2
View File
@@ -81,7 +81,7 @@ func (p *proxy) intercept(ctx context.Context, fullName string) (context.Context
appID := v[0]
if p.remoteAppFn == nil {
return ctx, nil, errors.Errorf("failed to proxy request: proxy not initialized. daprd startup may be incomplete.")
return ctx, nil, errors.Errorf("failed to proxy request: proxy not initialized. daprd startup may be incomplete")
}
target, isLocal, err := p.isLocalInternal(appID)
@@ -128,7 +128,7 @@ func (p *proxy) IsLocal(appID string) (bool, error) {
func (p *proxy) isLocalInternal(appID string) (remoteApp, bool, error) {
if p.remoteAppFn == nil {
return remoteApp{}, false, errors.Errorf("failed to proxy request: proxy not initialized. daprd startup may be incomplete.")
return remoteApp{}, false, errors.Errorf("failed to proxy request: proxy not initialized. daprd startup may be incomplete")
}
target, err := p.remoteAppFn(appID)
+4 -2
View File
@@ -51,7 +51,8 @@ func (o *Options) MetricsPort() uint64 {
// AttachCmdFlags attaches metrics options to command flags.
func (o *Options) AttachCmdFlags(
stringVar func(p *string, name string, value string, usage string),
boolVar func(p *bool, name string, value bool, usage string)) {
boolVar func(p *bool, name string, value bool, usage string),
) {
stringVar(
&o.Port,
"metrics-port",
@@ -66,7 +67,8 @@ func (o *Options) AttachCmdFlags(
// AttachCmdFlag attaches single metrics option to command flags.
func (o *Options) AttachCmdFlag(
stringVar func(p *string, name string, value string, usage string)) {
stringVar func(p *string, name string, value string, usage string),
) {
stringVar(
&o.Port,
"metrics-port",
+2 -1
View File
@@ -326,7 +326,8 @@ type chanGracefully struct {
}
func initChanGracefully(ch chan *componentsapi.Component) (
c *chanGracefully) {
c *chanGracefully,
) {
return &chanGracefully{
ch: ch,
isClosed: false,
+1 -1
View File
@@ -21,7 +21,7 @@ import (
"github.com/pkg/errors"
)
const defaultDirPermission = 0755
const defaultDirPermission = 0o755
func ensureDir(dirName string) error {
info, err := os.Stat(dirName)
+1 -1
View File
@@ -32,7 +32,7 @@ func TestEnsureDir(t *testing.T) {
})
t.Run("ensure the existing directory", func(t *testing.T) {
err := os.Mkdir(testDir, 0700)
err := os.Mkdir(testDir, 0o700)
assert.NoError(t, err)
err = ensureDir(testDir)
assert.NoError(t, err)
+1 -1
View File
@@ -132,7 +132,7 @@ func TestPolicyRetry(t *testing.T) {
fn := func(ctx context.Context) error {
if called < maxCalls {
called++
return errors.Errorf("Called (%d) vs Max (%d)!", called, maxCalls)
return errors.Errorf("Called (%d) vs Max (%d)", called, maxCalls)
}
return nil
}
+2 -1
View File
@@ -83,7 +83,8 @@ func NewRuntimeConfig(
id string, placementAddresses []string,
controlPlaneAddress, allowedOrigins, globalConfig, componentsPath, appProtocol, mode string,
httpPort, internalGRPCPort, apiGRPCPort int, apiListenAddresses []string, publicPort *int, appPort, profilePort int,
enableProfiling bool, maxConcurrency int, mtlsEnabled bool, sentryAddress string, appSSL bool, maxRequestBodySize int, unixDomainSocket string, readBufferSize int, streamRequestBody bool, gracefulShutdownDuration time.Duration, enableAPILogging bool) *Config {
enableProfiling bool, maxConcurrency int, mtlsEnabled bool, sentryAddress string, appSSL bool, maxRequestBodySize int, unixDomainSocket string, readBufferSize int, streamRequestBody bool, gracefulShutdownDuration time.Duration, enableAPILogging bool,
) *Config {
return &Config{
ID: id,
HTTPPort: httpPort,
+3 -3
View File
@@ -110,12 +110,12 @@ func testDeclarativeSubscriptionV2() subscriptionsapi_v2alpha1.Subscription {
func writeSubscriptionToDisk(subscription interface{}, filePath string) {
b, _ := yaml.Marshal(subscription)
os.WriteFile(filePath, b, 0600)
os.WriteFile(filePath, b, 0o600)
}
func TestDeclarativeSubscriptionsV1(t *testing.T) {
dir := filepath.Join(".", "components")
os.Mkdir(dir, 0777)
os.Mkdir(dir, 0o777)
defer os.RemoveAll(dir)
t.Run("load single valid subscription", func(t *testing.T) {
@@ -180,7 +180,7 @@ func TestDeclarativeSubscriptionsV1(t *testing.T) {
func TestDeclarativeSubscriptionsV2(t *testing.T) {
dir := filepath.Join(".", "componentsV2")
os.Mkdir(dir, 0777)
os.Mkdir(dir, 0o777)
defer os.RemoveAll(dir)
t.Run("load single valid subscription", func(t *testing.T) {
+4 -4
View File
@@ -21,10 +21,10 @@ import (
)
var (
timeoutSeconds int = 60
requestTimeoutMillis int = 500
periodMillis int = 100
urlFormat string = "http://localhost:%s/v1.0/healthz/outbound"
timeoutSeconds = 60
requestTimeoutMillis = 500
periodMillis = 100
urlFormat = "http://localhost:%s/v1.0/healthz/outbound"
)
func waitUntilDaprOutboundReady(daprHTTPPort string) {
+3 -3
View File
@@ -80,9 +80,9 @@ func getTestCertAuth() CertificateAuthority {
}
func writeTestCredentialsToDisk() {
os.WriteFile("ca.crt", []byte(rootCert), 0644)
os.WriteFile("issuer.crt", []byte(issuerCert), 0644)
os.WriteFile("issuer.key", []byte(issuerKey), 0644)
os.WriteFile("ca.crt", []byte(rootCert), 0o644)
os.WriteFile("issuer.crt", []byte(issuerCert), 0o644)
os.WriteFile("issuer.key", []byte(issuerKey), 0o644)
}
func cleanupCredentials() {
+3 -3
View File
@@ -81,17 +81,17 @@ func CredentialsExist(conf config.SentryConfig) (bool, error) {
/* #nosec. */
func storeSelfhosted(rootCertPem, issuerCertPem, issuerKeyPem []byte, rootCertPath, issuerCertPath, issuerKeyPath string) error {
err := os.WriteFile(rootCertPath, rootCertPem, 0644)
err := os.WriteFile(rootCertPath, rootCertPem, 0o644)
if err != nil {
return errors.Wrapf(err, "failed saving file to %s", rootCertPath)
}
err = os.WriteFile(issuerCertPath, issuerCertPem, 0644)
err = os.WriteFile(issuerCertPath, issuerCertPem, 0o644)
if err != nil {
return errors.Wrapf(err, "failed saving file to %s", issuerCertPath)
}
err = os.WriteFile(issuerKeyPath, issuerKeyPem, 0644)
err = os.WriteFile(issuerKeyPath, issuerKeyPem, 0o644)
if err != nil {
return errors.Wrapf(err, "failed saving file to %s", issuerKeyPath)
}
+2 -1
View File
@@ -117,7 +117,8 @@ func GenerateRootCertCSR(org, cn string, publicKey interface{}, ttl, skew time.D
// GenerateCSRCertificate returns an x509 Certificate from a CSR, signing cert, public key, signing private key and duration.
func GenerateCSRCertificate(csr *x509.CertificateRequest, subject string, identityBundle *identity.Bundle, signingCert *x509.Certificate, publicKey interface{}, signingKey crypto.PrivateKey,
ttl, skew time.Duration, isCA bool) ([]byte, error) {
ttl, skew time.Duration, isCA bool,
) ([]byte, error) {
cert, err := generateBaseCert(ttl, skew, publicKey)
if err != nil {
return nil, errors.Wrap(err, "error generating csr certificate")
+1 -1
View File
@@ -52,4 +52,4 @@ func (f *FailingDirectMessaging) Invoke(ctx context.Context, targetAppID string,
return &v1.InvokeMethodResponse{}, err
}
return v1.NewInvokeMethodResponse(200, "OK", nil), nil
}
}
+1 -1
View File
@@ -44,4 +44,4 @@ func (f *FailingStatestore) Query(req *state.QueryRequest) (*state.QueryResponse
return nil, err
}
return &state.QueryResponse{}, nil
}
}
+1 -1
View File
@@ -192,4 +192,4 @@ func (f *FailingStatestore) Set(req *state.SetRequest) error {
func (f *FailingStatestore) Close() error {
return nil
}
}
+2 -2
View File
@@ -113,7 +113,7 @@ func (f *FailingConfigurationStore) Subscribe(ctx context.Context, req *configur
handler(ctx, &configuration.UpdateEvent{
Items: []*configuration.Item{
{
Key: req.Metadata["key"],
Key: req.Metadata["key"],
Value: "testConfig",
},
},
@@ -126,4 +126,4 @@ func (f *FailingConfigurationStore) Subscribe(ctx context.Context, req *configur
func (f *FailingConfigurationStore) Unsubscribe(ctx context.Context, req *configuration.UnsubscribeRequest) error {
return f.Failure.PerformFailure(req.ID)
}
}
+4 -2
View File
@@ -68,8 +68,10 @@ var daprConfigResponse = daprConfig{
drainRebalancedActors,
}
var actorLogs = []actorLogEntry{}
var actorLogsMutex = &sync.Mutex{}
var (
actorLogs = []actorLogEntry{}
actorLogsMutex = &sync.Mutex{}
)
var actors sync.Map
+7 -5
View File
@@ -116,10 +116,12 @@ type TempTransactionalDelete struct {
Key string `json:"key"`
}
var actorLogs = []actorLogEntry{}
var actorLogsMutex = &sync.Mutex{}
var registeredActorType = getActorType()
var actors sync.Map
var (
actorLogs = []actorLogEntry{}
actorLogsMutex = &sync.Mutex{}
registeredActorType = getActorType()
actors sync.Map
)
var envOverride sync.Map
@@ -208,7 +210,7 @@ func logsHandler(w http.ResponseWriter, r *http.Request) {
}
func configHandler(w http.ResponseWriter, r *http.Request) {
var daprConfigResponse = daprConfig{
daprConfigResponse := daprConfig{
[]string{getActorType()},
actorIdleTimeout,
actorScanInterval,
@@ -98,7 +98,7 @@ func (s *ActorService) onHealthz(w http.ResponseWriter, r *http.Request) {
}
func (s *ActorService) router() http.Handler {
var r = chi.NewRouter()
r := chi.NewRouter()
r.Get("/dapr/config", s.onConfig)
r.Get("/healthz", s.onHealthz)
+2 -3
View File
@@ -17,7 +17,6 @@ import (
actor_cl "actorload/pkg/actor/client"
cl "actorload/pkg/actor/client"
http_client "actorload/pkg/actor/client/http"
"errors"
"flag"
"fmt"
@@ -112,7 +111,7 @@ type actorLoadTestOptions struct {
}
func generatePayload(length int) []byte {
var chs = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
chs := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
payload := make([]byte, length)
for i := range payload {
@@ -123,7 +122,7 @@ func generatePayload(length int) []byte {
}
func activateRandomActors(client actor_cl.ActorClient, actorType string, maxActor int) []string {
var activatedActors = []string{}
activatedActors := []string{}
for i := 0; i < maxActor; i++ {
actorID := strings.Replace(uuid.New().String(), "-", "", -1)
log.Infof("Request to activate %s.%s actor", actorType, actorID)
@@ -80,7 +80,8 @@ func (t *TelemetryClient) RecordLoadRequestCount(actorType, actorID string, elap
label.String("hostname", t.hostname),
label.Int("code", code),
label.Bool("success", code == 200),
label.String("actor", fmt.Sprintf("%s.%s", actorType, actorID))},
label.String("actor", fmt.Sprintf("%s.%s", actorType, actorID)),
},
t.reqCounter.Measurement(1))
t.reqLatency.Record(
@@ -90,5 +91,4 @@ func (t *TelemetryClient) RecordLoadRequestCount(actorType, actorID string, elap
label.Int("code", code),
label.Bool("success", code == 200),
label.String("actor", fmt.Sprintf("%s.%s", actorType, actorID)))
}
+1 -1
View File
@@ -75,7 +75,7 @@ func (m *messageBuffer) fail(failedMessage string) bool {
return false
}
var messages messageBuffer = messageBuffer{
var messages = messageBuffer{
lock: &sync.RWMutex{},
successMessages: []string{},
}
@@ -15,9 +15,10 @@ package main
import (
"context"
"log"
"github.com/dapr/go-sdk/service/common"
daprd "github.com/dapr/go-sdk/service/grpc"
"log"
)
func main() {
-4
View File
@@ -160,7 +160,6 @@ func performPublishHTTP(topic string, jsonValue []byte, contentType string, meta
log.Printf("Publishing using url %s and body '%s'", url, jsonValue)
resp, err := http.Post(url, contentType, bytes.NewBuffer(jsonValue))
if err != nil {
if resp != nil {
return resp.StatusCode, err
@@ -185,7 +184,6 @@ func performPublishGRPC(topic string, jsonValue []byte, contentType string, meta
Metadata: metadata,
}
_, err := grpcClient.PublishEvent(context.Background(), req)
if err != nil {
log.Printf("Publish failed: %s", err.Error())
@@ -251,14 +249,12 @@ func callMethodGRPC(appName, method string) ([]byte, error) {
func callMethodHTTP(appName, method string) ([]byte, error) {
url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/%s", daprPortHTTP, appName, method)
resp, err := http.Post(url, "application/json", bytes.NewBuffer([]byte{})) //nolint: gosec
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
+1 -1
View File
@@ -226,7 +226,7 @@ func (s *server) OnTopicEvent(ctx context.Context, in *pb.TopicEventRequest) (*p
// Return success with DROP status to drop message
return &pb.TopicEventResponse{
Status: pb.TopicEventResponse_DROP,
}, nil
}, err
}
// Raw data does not have content-type, so it is handled as-is.
-1
View File
@@ -505,7 +505,6 @@ func TestInvokeService(w http.ResponseWriter, r *http.Request) {
return
}
}
}
func TestInvokeActorMethod(w http.ResponseWriter, r *http.Request) {
+4 -4
View File
@@ -85,7 +85,7 @@ func get(key, store string) (*map[string]string, int, error) {
log.Printf("Found secret for key %s: %s", key, body)
var state = map[string]string{}
state := map[string]string{}
if len(body) == 0 {
return nil, http.StatusOK, nil
}
@@ -103,7 +103,7 @@ func getAll(secrets []daprSecret) ([]daprSecret, int, error) {
statusCode := http.StatusOK
log.Printf("Processing get request for %d states.", len(secrets))
var output = make([]daprSecret, 0, len(secrets))
output := make([]daprSecret, 0, len(secrets))
for _, secret := range secrets {
value, sc, err := get(secret.Key, secret.Store)
if err != nil {
@@ -140,8 +140,8 @@ func handler(w http.ResponseWriter, r *http.Request) {
return
}
var res = requestResponse{}
var uri = r.URL.RequestURI()
res := requestResponse{}
uri := r.URL.RequestURI()
var secrets []daprSecret
var statusCode int
+2 -12
View File
@@ -233,7 +233,6 @@ func invokeService(remoteApp, method string) (appResponse, int, error) {
func invokeServiceWithBody(remoteApp, method string, data []byte) (appResponse, int, error) {
resp, err := invokeServiceWithBodyHeader(remoteApp, method, data, map[string]string{})
if err != nil {
return appResponse{}, resp.StatusCode, err
}
@@ -421,7 +420,6 @@ func requestHTTPToHTTP(w http.ResponseWriter, r *http.Request, send func(remoteA
}
resp, err := send(commandBody.RemoteApp, "retrieve_request_object", b, headers)
if err != nil {
fmt.Printf("response had error %s\n", err)
onHTTPCallFailed(w, 0, err)
@@ -508,7 +506,6 @@ func testV1RequestHTTPToGRPC(w http.ResponseWriter, r *http.Request) {
b,
headers,
)
if err != nil {
fmt.Printf("response had error %s\n", err)
onHTTPCallFailed(w, 0, err)
@@ -597,7 +594,6 @@ func testV1RequestGRPCToGRPC(w http.ResponseWriter, r *http.Request) {
grpc.Header(&header), // will retrieve header
grpc.Trailer(&trailer), // will retrieve trailer
)
if err != nil {
fmt.Printf("response had error %s\n", err)
onHTTPCallFailed(w, 0, err)
@@ -691,7 +687,6 @@ func testV1RequestGRPCToHTTP(w http.ResponseWriter, r *http.Request) {
req,
grpc.Header(&header), // will retrieve header
)
if err != nil {
fmt.Printf("response had error %s\n", err)
onHTTPCallFailed(w, 0, err)
@@ -754,9 +749,8 @@ func grpcToGrpcTest(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s calling with message %s\n", commandBody.Method, string(b))
var req = constructRequest(commandBody.RemoteApp, commandBody.Method, "", b)
req := constructRequest(commandBody.RemoteApp, commandBody.Method, "", b)
resp, err := daprClient.InvokeService(context.Background(), req)
if err != nil {
logAndSetResponse(w, http.StatusInternalServerError, "grpc call failed with "+err.Error())
return
@@ -813,7 +807,6 @@ func httpToGrpcTest(w http.ResponseWriter, r *http.Request) {
fmt.Printf("httpToGrpcTest calling with message %s\n", string(b))
resp, statusCode, err := invokeServiceWithBody(commandBody.RemoteApp, "httpToGrpcTest", b)
if err != nil {
fmt.Printf("response had error %s\n", err)
onHTTPCallFailed(w, statusCode, err)
@@ -990,7 +983,7 @@ func grpcToHTTPTest(w http.ResponseWriter, r *http.Request) {
body := resp.Data.GetValue()
fmt.Printf("resp was %s\n", string(body))
//var responseMessage string
// var responseMessage string
var appResp appResponse
err = json.Unmarshal(body, &appResp)
if err != nil {
@@ -1146,7 +1139,6 @@ func parseErrorServiceCall(w http.ResponseWriter, r *http.Request) {
}
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
onSerializationFailed(w, err)
return
@@ -1273,7 +1265,6 @@ func logAndSetResponse(w http.ResponseWriter, statusCode int, message string) {
// HTTPPost is a helper to make POST request call to url
func HTTPPost(url string, data []byte) ([]byte, error) {
resp, err := httpClient.Post(sanitizeHTTPURL(url), jsonContentType, bytes.NewBuffer(data)) //nolint
if err != nil {
return nil, err
}
@@ -1284,7 +1275,6 @@ func HTTPPost(url string, data []byte) ([]byte, error) {
// Wraps GET calls
func HTTPGet(url string) ([]byte, error) {
resp, err := httpClient.Get(sanitizeHTTPURL(url)) //nolint
if err != nil {
return nil, err
}
+1 -1
View File
@@ -78,7 +78,7 @@ func (s *server) grpcTestHandler(data []byte) ([]byte, error) {
func (s *server) retrieveRequestObject(ctx context.Context) ([]byte, error) {
md, _ := metadata.FromIncomingContext(ctx)
var requestMD = map[string][]string{}
requestMD := map[string][]string{}
for k, vals := range md {
requestMD[k] = vals
fmt.Printf("incoming md: %s %q", k, vals)
+7 -9
View File
@@ -191,10 +191,9 @@ func parseState(key string, body []byte) (*appState, error) {
func getAll(states []daprState, statestore string, meta map[string]string) ([]daprState, error) {
log.Printf("Processing get request for %d states.", len(states))
var output = make([]daprState, 0, len(states))
output := make([]daprState, 0, len(states))
for _, state := range states {
value, err := get(state.Key, statestore, meta)
if err != nil {
return nil, err
}
@@ -213,7 +212,7 @@ func getAll(states []daprState, statestore string, meta map[string]string) ([]da
func getBulk(states []daprState, statestore string) ([]daprState, error) {
log.Printf("Processing get bulk request for %d states.", len(states))
var output = make([]daprState, 0, len(states))
output := make([]daprState, 0, len(states))
url, err := createBulkStateURL(statestore)
if err != nil {
@@ -300,7 +299,6 @@ func deleteAll(states []daprState, statestore string, meta map[string]string) er
for _, state := range states {
err := delete(state.Key, statestore, meta)
if err != nil {
return err
}
@@ -370,7 +368,7 @@ func executeQuery(query []byte, statestore string, meta map[string]string) ([]da
}
log.Printf("Query returned %d results", len(qres.Results))
var output = make([]daprState, 0, len(qres.Results))
output := make([]daprState, 0, len(qres.Results))
for _, item := range qres.Results {
output = append(output, daprState{
Key: item.Key,
@@ -440,9 +438,9 @@ func httpHandler(w http.ResponseWriter, r *http.Request) {
var req *requestResponse
var data []byte
var err error
var res = requestResponse{}
var uri = r.URL.RequestURI()
var statusCode = http.StatusOK
res := requestResponse{}
uri := r.URL.RequestURI()
statusCode := http.StatusOK
res.StartTime = epoch()
@@ -522,7 +520,7 @@ func grpcHandler(w http.ResponseWriter, r *http.Request) {
var err error
var res requestResponse
res.StartTime = epoch()
var statusCode = http.StatusOK
statusCode := http.StatusOK
cmd := mux.Vars(r)["command"]
statestore := mux.Vars(r)["statestore"]
@@ -198,8 +198,8 @@ func TestActorReminder(t *testing.T) {
expectedEnvPartitionCount := "0"
mustCheckLogs := true
for i := 0; i < numActors; i++ {
//externalURL = tr.Platform.AcquireAppExternalURL(appName)
//require.NotEmpty(t, externalURL, "external URL must not be empty!")
// externalURL = tr.Platform.AcquireAppExternalURL(appName)
// require.NotEmpty(t, externalURL, "external URL must not be empty!")
rateLimit.Take()
actorID := fmt.Sprintf(actorIDPartitionTemplate, i+1000)
@@ -270,7 +270,6 @@ func TestActorReminder(t *testing.T) {
return fmt.Errorf("invalid status code %d while registering reminder for actorID %s", httpStatusCode, actorID)
}
return nil
}, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 10))
require.NoError(t, err)
+4 -2
View File
@@ -35,8 +35,10 @@ const (
numHealthChecks = 60 // Number of get calls before starting tests.
)
var tr *runner.TestRunner
var apps []kube.AppDescription
var (
tr *runner.TestRunner
apps []kube.AppDescription
)
func healthCheckApp(t *testing.T, externalURL string, numHealthChecks int) {
t.Logf("Starting health check for %s\n", externalURL)
+2 -1
View File
@@ -338,7 +338,8 @@ func validateMessagesReceivedBySubscriber(t *testing.T, publisherExternalURL str
}
func validateMessagesReceivedBySubscriberOrError(
t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages receivedMessagesResponse) error {
t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages receivedMessagesResponse,
) error {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
@@ -445,11 +445,11 @@ func TestHeaders(t *testing.T) {
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
var trailerHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
trailerHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
json.Unmarshal([]byte(actualHeaders["trailers"]), &trailerHeaders)
@@ -512,10 +512,10 @@ func TestHeaders(t *testing.T) {
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
@@ -562,10 +562,10 @@ func TestHeaders(t *testing.T) {
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
@@ -649,11 +649,11 @@ func TestHeaders(t *testing.T) {
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
var trailerHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
trailerHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
json.Unmarshal([]byte(actualHeaders["trailers"]), &trailerHeaders)
@@ -712,10 +712,10 @@ func TestHeaders(t *testing.T) {
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
@@ -746,10 +746,10 @@ func TestHeaders(t *testing.T) {
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
@@ -793,10 +793,10 @@ func verifyHTTPToHTTPTracing(t *testing.T, url string, expectedTraceID string) {
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
@@ -828,10 +828,10 @@ func verifyHTTPToHTTP(t *testing.T, hostIP string, hostname string, url string,
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
var actualHeaders = map[string]string{}
actualHeaders := map[string]string{}
json.Unmarshal([]byte(appResp.Message), &actualHeaders)
var requestHeaders = map[string][]string{}
var responseHeaders = map[string][]string{}
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders["request"]), &requestHeaders)
json.Unmarshal([]byte(actualHeaders["response"]), &responseHeaders)
+1 -1
View File
@@ -454,7 +454,7 @@ func TestStateTransactionApps(t *testing.T) {
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
var transactionTests = []struct {
transactionTests := []struct {
protocol string
in testStateTransactionCase
}{
+2 -1
View File
@@ -76,7 +76,8 @@ type TestRunner struct {
// NewTestRunner returns TestRunner instance for e2e test.
func NewTestRunner(id string, apps []kube.AppDescription,
comps []kube.ComponentDescription,
initApps []kube.AppDescription) *TestRunner {
initApps []kube.AppDescription,
) *TestRunner {
return &TestRunner{
id: id,
components: comps,
+1
View File
@@ -1,3 +1,4 @@
//go:build tools
// +build tools
/*