Merge pull request #8034 from hashicorp/dnephin/add-linter-staticcheck-4

ci: enable SA4006 staticcheck check and add ineffassign
This commit is contained in:
Daniel Nephin 2020-06-17 12:16:02 -04:00 committed by GitHub
commit 5afcf5c1bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 96 additions and 90 deletions

View File

@ -5,6 +5,7 @@ linters:
- govet - govet
- unconvert - unconvert
- staticcheck - staticcheck
- ineffassign
issues: issues:
# Disable the default exclude list so that all excludes are explicitly # Disable the default exclude list so that all excludes are explicitly
@ -17,10 +18,6 @@ issues:
- linters: [staticcheck] - linters: [staticcheck]
text: "SA9004:" text: "SA9004:"
# Temp ignore SA4006: this value of `x` is never used
- linters: [staticcheck]
text: "SA4006:"
linters-settings: linters-settings:
gofmt: gofmt:
simplify: true simplify: true

View File

@ -706,18 +706,17 @@ func (a *Agent) setupClientAutoEncryptWatching(rootsReq *structs.DCSpecificReque
// in time. The agent would be stuck in that case because the watches // in time. The agent would be stuck in that case because the watches
// never use the AutoEncrypt.Sign endpoint. // never use the AutoEncrypt.Sign endpoint.
go func() { go func() {
// Check 10sec after cert expires. The agent cache
// should be handling the expiration and renew before
// it.
// If there is no cert, AutoEncryptCertNotAfter returns
// a value in the past which immediately triggers the
// renew, but this case shouldn't happen because at
// this point, auto_encrypt was just being setup
// successfully.
interval := a.tlsConfigurator.AutoEncryptCertNotAfter().Sub(time.Now().Add(10 * time.Second))
autoLogger := a.logger.Named(logging.AutoEncrypt)
for { for {
// Check 10sec after cert expires. The agent cache
// should be handling the expiration and renew before
// it.
// If there is no cert, AutoEncryptCertNotAfter returns
// a value in the past which immediately triggers the
// renew, but this case shouldn't happen because at
// this point, auto_encrypt was just being setup
// successfully.
autoLogger := a.logger.Named(logging.AutoEncrypt)
interval := a.tlsConfigurator.AutoEncryptCertNotAfter().Sub(time.Now().Add(10 * time.Second))
a.logger.Debug("setting up client certificate expiration check on interval", "interval", interval) a.logger.Debug("setting up client certificate expiration check on interval", "interval", interval)
select { select {
case <-a.shutdownCh: case <-a.shutdownCh:

View File

@ -54,33 +54,28 @@ func TestCatalogDatacenters(t *testing.T) {
// Fetch first time // Fetch first time
result, err := typ.Fetch(cache.FetchOptions{}, &structs.DatacentersRequest{}) result, err := typ.Fetch(cache.FetchOptions{}, &structs.DatacentersRequest{})
result2, err := typ.Fetch(cache.FetchOptions{LastResult: &result}, &structs.DatacentersRequest{QueryOptions: structs.QueryOptions{MustRevalidate: true}})
result3, err := typ.Fetch(cache.FetchOptions{LastResult: &result2}, &structs.DatacentersRequest{QueryOptions: structs.QueryOptions{MustRevalidate: true}})
// make sure it was called the right number of times
rpc.AssertExpectations(t)
// make sure the first result was correct
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, result, cache.FetchResult{ require.Equal(t, result, cache.FetchResult{
Value: resp, Value: resp,
Index: 1, Index: 1,
}) })
// validate the second result result2, err := typ.Fetch(cache.FetchOptions{LastResult: &result}, &structs.DatacentersRequest{QueryOptions: structs.QueryOptions{MustRevalidate: true}})
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, result2, cache.FetchResult{ require.Equal(t, result2, cache.FetchResult{
Value: resp2, Value: resp2,
Index: 2, Index: 2,
}) })
// validate the third result result3, err := typ.Fetch(cache.FetchOptions{LastResult: &result2}, &structs.DatacentersRequest{QueryOptions: structs.QueryOptions{MustRevalidate: true}})
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, result3, cache.FetchResult{ require.Equal(t, result3, cache.FetchResult{
Value: resp3, Value: resp3,
Index: 3, Index: 3,
}) })
// make sure it was called the right number of times
rpc.AssertExpectations(t)
} }
func TestDatacenters_badReqType(t *testing.T) { func TestDatacenters_badReqType(t *testing.T) {

View File

@ -76,6 +76,9 @@ func (c *ServiceHTTPChecks) Fetch(opts cache.FetchOptions, req cache.Request) (c
return hash, reply, nil return hash, reply, nil
}, },
) )
if err != nil {
return result, err
}
result.Value = resp result.Value = resp

View File

@ -85,6 +85,7 @@ func TestACLEndpoint_BootstrapTokens(t *testing.T) {
require.True(t, strings.HasPrefix(err.Error(), structs.ACLBootstrapNotAllowedErr.Error())) require.True(t, strings.HasPrefix(err.Error(), structs.ACLBootstrapNotAllowedErr.Error()))
_, resetIdx, err := srv.fsm.State().CanBootstrapACLToken() _, resetIdx, err := srv.fsm.State().CanBootstrapACLToken()
require.NoError(t, err)
resetPath := filepath.Join(dir, "acl-bootstrap-reset") resetPath := filepath.Join(dir, "acl-bootstrap-reset")
require.NoError(t, ioutil.WriteFile(resetPath, []byte(fmt.Sprintf("%d", resetIdx)), 0600)) require.NoError(t, ioutil.WriteFile(resetPath, []byte(fmt.Sprintf("%d", resetIdx)), 0600))
@ -1692,6 +1693,7 @@ func TestACLEndpoint_TokenSet_anon(t *testing.T) {
require.NotEmpty(t, token.SecretID) require.NotEmpty(t, token.SecretID)
tokenResp, err := retrieveTestToken(codec, TestDefaultMasterToken, "dc1", structs.ACLTokenAnonymousID) tokenResp, err := retrieveTestToken(codec, TestDefaultMasterToken, "dc1", structs.ACLTokenAnonymousID)
require.NoError(t, err)
require.Equal(t, len(tokenResp.Token.Policies), 1) require.Equal(t, len(tokenResp.Token.Policies), 1)
require.Equal(t, tokenResp.Token.Policies[0].ID, policy.ID) require.Equal(t, tokenResp.Token.Policies[0].ID, policy.ID)
@ -1900,6 +1902,7 @@ func TestACLEndpoint_TokenDelete_anon(t *testing.T) {
// Make sure the token is still there // Make sure the token is still there
tokenResp, err := retrieveTestToken(codec, TestDefaultMasterToken, "dc1", structs.ACLTokenAnonymousID) tokenResp, err := retrieveTestToken(codec, TestDefaultMasterToken, "dc1", structs.ACLTokenAnonymousID)
require.NoError(t, err)
require.NotNil(t, tokenResp.Token) require.NotNil(t, tokenResp.Token)
} }
@ -2291,6 +2294,7 @@ func TestACLEndpoint_PolicyDelete(t *testing.T) {
// Make sure the policy is gone // Make sure the policy is gone
tokenResp, err := retrieveTestPolicy(codec, TestDefaultMasterToken, "dc1", existingPolicy.ID) tokenResp, err := retrieveTestPolicy(codec, TestDefaultMasterToken, "dc1", existingPolicy.ID)
require.NoError(t, err)
require.Nil(t, tokenResp.Policy) require.Nil(t, tokenResp.Policy)
} }
@ -2903,6 +2907,7 @@ func TestACLEndpoint_RoleDelete(t *testing.T) {
// Make sure the role is gone // Make sure the role is gone
roleResp, err := retrieveTestRole(codec, TestDefaultMasterToken, "dc1", existingRole.ID) roleResp, err := retrieveTestRole(codec, TestDefaultMasterToken, "dc1", existingRole.ID)
require.NoError(t, err)
require.Nil(t, roleResp.Role) require.Nil(t, roleResp.Role)
} }
@ -4395,6 +4400,7 @@ func TestACLEndpoint_Login(t *testing.T) {
structs.BindingRuleBindTypeNode, structs.BindingRuleBindTypeNode,
"${serviceaccount.name}", "${serviceaccount.name}",
) )
require.NoError(t, err)
t.Run("do not provide a token", func(t *testing.T) { t.Run("do not provide a token", func(t *testing.T) {
req := structs.ACLLoginRequest{ req := structs.ACLLoginRequest{

View File

@ -3041,7 +3041,7 @@ func TestACL_filterDatacenterCheckServiceNodes(t *testing.T) {
node_prefix "" { policy = "read" } node_prefix "" { policy = "read" }
`, acl.SyntaxCurrent, nil, nil) `, acl.SyntaxCurrent, nil, nil)
require.NoError(t, err) require.NoError(t, err)
perms, err = acl.NewPolicyAuthorizerWithDefaults(acl.DenyAll(), []*acl.Policy{policy}, nil) _, err = acl.NewPolicyAuthorizerWithDefaults(acl.DenyAll(), []*acl.Policy{policy}, nil)
require.NoError(t, err) require.NoError(t, err)
// Now it should go through. // Now it should go through.

View File

@ -533,6 +533,7 @@ func TestFSM_SnapshotRestore_OSS(t *testing.T) {
// Verify the acl-token-bootstrap index was restored // Verify the acl-token-bootstrap index was restored
canBootstrap, index, err := fsm2.state.CanBootstrapACLToken() canBootstrap, index, err := fsm2.state.CanBootstrapACLToken()
require.NoError(t, err)
require.False(t, canBootstrap) require.False(t, canBootstrap)
require.True(t, index > 0) require.True(t, index > 0)

View File

@ -1,11 +1,11 @@
package consul package consul
import ( import (
"fmt"
"testing" "testing"
"github.com/hashicorp/consul/agent/metadata" "github.com/hashicorp/consul/agent/metadata"
"github.com/hashicorp/raft" "github.com/hashicorp/raft"
"github.com/stretchr/testify/require"
) )
type testAddr struct { type testAddr struct {
@ -46,11 +46,8 @@ func TestServerLookup(t *testing.T) {
lookup.RemoveServer(svr) lookup.RemoveServer(svr)
got, err = lookup.ServerAddr("1") _, err = lookup.ServerAddr("1")
expectedErr := fmt.Errorf("Could not find address for server id 1") require.EqualError(t, err, "Could not find address for server id 1")
if expectedErr.Error() != err.Error() {
t.Fatalf("Unexpected error, got %v wanted %v", err, expectedErr)
}
svr2 := &metadata.Server{ID: "2", Addr: &testAddr{"123.4.5.6"}} svr2 := &metadata.Server{ID: "2", Addr: &testAddr{"123.4.5.6"}}
lookup.RemoveServer(svr2) lookup.RemoveServer(svr2)

View File

@ -795,7 +795,7 @@ func TestStateStore_EnsureNode(t *testing.T) {
if err := s.EnsureNode(3, in2); err != nil { if err := s.EnsureNode(3, in2); err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }
idx, out, err = s.GetNode("node1") _, out, err = s.GetNode("node1")
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }
@ -839,7 +839,8 @@ func TestStateStore_EnsureNode(t *testing.T) {
} }
// Retrieve the node // Retrieve the node
idx, out, err = s.GetNode("node1") _, out, err = s.GetNode("node1")
require.NoError(t, err)
if out != nil { if out != nil {
t.Fatalf("Node should not exist anymore: %q", out) t.Fatalf("Node should not exist anymore: %q", out)
} }
@ -903,7 +904,8 @@ func TestStateStore_EnsureNode(t *testing.T) {
} }
// Retrieve the node // Retrieve the node
idx, out, err = s.GetNode("Node1bis") _, out, err = s.GetNode("Node1bis")
require.NoError(t, err)
if out == nil { if out == nil {
t.Fatalf("Node should exist, but was null") t.Fatalf("Node should exist, but was null")
} }
@ -991,7 +993,7 @@ func TestStateStore_EnsureNode(t *testing.T) {
if err := s.EnsureNode(15, in); err != nil { if err := s.EnsureNode(15, in); err != nil {
t.Fatalf("[DEPRECATED] it should work, err:= %q", err) t.Fatalf("[DEPRECATED] it should work, err:= %q", err)
} }
idx, out, err = s.GetNode("Node1-Renamed2") _, out, err = s.GetNode("Node1-Renamed2")
if err != nil { if err != nil {
t.Fatalf("[DEPRECATED] err: %s", err) t.Fatalf("[DEPRECATED] err: %s", err)
} }
@ -2022,6 +2024,7 @@ func TestStateStore_DeleteService(t *testing.T) {
// Delete the service. // Delete the service.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
_, _, err := s.NodeServices(ws, "node1", nil) _, _, err := s.NodeServices(ws, "node1", nil)
require.NoError(t, err)
if err := s.DeleteService(4, "node1", "service1", nil); err != nil { if err := s.DeleteService(4, "node1", "service1", nil); err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }
@ -3373,7 +3376,7 @@ func TestStateStore_ConnectQueryBlocking(t *testing.T) {
// Run the query // Run the query
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, res, err := s.CheckConnectServiceNodes(ws, tt.svc, nil) _, res, err := s.CheckConnectServiceNodes(ws, tt.svc, nil)
require.NoError(err) require.NoError(err)
require.Len(res, tt.wantBeforeResLen) require.Len(res, tt.wantBeforeResLen)
require.Len(ws, tt.wantBeforeWatchSetSize) require.Len(ws, tt.wantBeforeWatchSetSize)
@ -3392,7 +3395,7 @@ func TestStateStore_ConnectQueryBlocking(t *testing.T) {
// Re-query the same result. Should return the desired index and len // Re-query the same result. Should return the desired index and len
ws = memdb.NewWatchSet() ws = memdb.NewWatchSet()
idx, res, err = s.CheckConnectServiceNodes(ws, tt.svc, nil) idx, res, err := s.CheckConnectServiceNodes(ws, tt.svc, nil)
require.NoError(err) require.NoError(err)
require.Len(res, tt.wantAfterResLen) require.Len(res, tt.wantAfterResLen)
require.Equal(tt.wantAfterIndex, idx) require.Equal(tt.wantAfterIndex, idx)
@ -3465,7 +3468,7 @@ func TestStateStore_CheckServiceNodes(t *testing.T) {
t.Fatalf("bad") t.Fatalf("bad")
} }
ws = memdb.NewWatchSet() ws = memdb.NewWatchSet()
idx, results, err = s.CheckServiceNodes(ws, "service1", nil) idx, _, err = s.CheckServiceNodes(ws, "service1", nil)
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }
@ -3481,7 +3484,7 @@ func TestStateStore_CheckServiceNodes(t *testing.T) {
t.Fatalf("bad") t.Fatalf("bad")
} }
ws = memdb.NewWatchSet() ws = memdb.NewWatchSet()
idx, results, err = s.CheckServiceNodes(ws, "service1", nil) idx, _, err = s.CheckServiceNodes(ws, "service1", nil)
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }
@ -3495,7 +3498,7 @@ func TestStateStore_CheckServiceNodes(t *testing.T) {
t.Fatalf("bad") t.Fatalf("bad")
} }
ws = memdb.NewWatchSet() ws = memdb.NewWatchSet()
idx, results, err = s.CheckServiceNodes(ws, "service1", nil) idx, _, err = s.CheckServiceNodes(ws, "service1", nil)
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }

View File

@ -81,7 +81,7 @@ func TestStateStore_Coordinate_Updates(t *testing.T) {
require.Nil(t, all) require.Nil(t, all)
coordinateWs = memdb.NewWatchSet() coordinateWs = memdb.NewWatchSet()
idx, coords, err = s.Coordinate("node1", coordinateWs) idx, _, err = s.Coordinate("node1", coordinateWs)
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }

View File

@ -429,7 +429,7 @@ func TestStateStore_KVSList(t *testing.T) {
// Delete a key and make sure the index comes from the tombstone. // Delete a key and make sure the index comes from the tombstone.
ws = memdb.NewWatchSet() ws = memdb.NewWatchSet()
idx, _, err = s.KVSList(ws, "foo/bar/baz", nil) _, _, err = s.KVSList(ws, "foo/bar/baz", nil)
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }

View File

@ -2,12 +2,13 @@ package state
import ( import (
"fmt" "fmt"
"github.com/stretchr/testify/assert"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/types" "github.com/hashicorp/consul/types"
@ -543,7 +544,7 @@ func TestStateStore_Session_Invalidate_DeleteNode(t *testing.T) {
// Delete the node and make sure the watch fires. // Delete the node and make sure the watch fires.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, s2, err := s.SessionGet(ws, session.ID, nil) _, _, err := s.SessionGet(ws, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -555,7 +556,7 @@ func TestStateStore_Session_Invalidate_DeleteNode(t *testing.T) {
} }
// Lookup by ID, should be nil. // Lookup by ID, should be nil.
idx, s2, err = s.SessionGet(nil, session.ID, nil) idx, s2, err := s.SessionGet(nil, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -598,7 +599,7 @@ func TestStateStore_Session_Invalidate_DeleteService(t *testing.T) {
// Delete the service and make sure the watch fires. // Delete the service and make sure the watch fires.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, s2, err := s.SessionGet(ws, session.ID, nil) _, _, err := s.SessionGet(ws, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -610,7 +611,7 @@ func TestStateStore_Session_Invalidate_DeleteService(t *testing.T) {
} }
// Lookup by ID, should be nil. // Lookup by ID, should be nil.
idx, s2, err = s.SessionGet(nil, session.ID, nil) idx, s2, err := s.SessionGet(nil, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -648,7 +649,7 @@ func TestStateStore_Session_Invalidate_Critical_Check(t *testing.T) {
// Invalidate the check and make sure the watches fire. // Invalidate the check and make sure the watches fire.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, s2, err := s.SessionGet(ws, session.ID, nil) _, _, err := s.SessionGet(ws, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -661,7 +662,7 @@ func TestStateStore_Session_Invalidate_Critical_Check(t *testing.T) {
} }
// Lookup by ID, should be nil. // Lookup by ID, should be nil.
idx, s2, err = s.SessionGet(nil, session.ID, nil) idx, s2, err := s.SessionGet(nil, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -699,7 +700,7 @@ func TestStateStore_Session_Invalidate_DeleteCheck(t *testing.T) {
// Delete the check and make sure the watches fire. // Delete the check and make sure the watches fire.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, s2, err := s.SessionGet(ws, session.ID, nil) _, _, err := s.SessionGet(ws, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -711,7 +712,7 @@ func TestStateStore_Session_Invalidate_DeleteCheck(t *testing.T) {
} }
// Lookup by ID, should be nil. // Lookup by ID, should be nil.
idx, s2, err = s.SessionGet(nil, session.ID, nil) idx, s2, err := s.SessionGet(nil, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -767,7 +768,7 @@ func TestStateStore_Session_Invalidate_Key_Unlock_Behavior(t *testing.T) {
// Delete the node and make sure the watches fire. // Delete the node and make sure the watches fire.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, s2, err := s.SessionGet(ws, session.ID, nil) _, _, err = s.SessionGet(ws, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -779,7 +780,7 @@ func TestStateStore_Session_Invalidate_Key_Unlock_Behavior(t *testing.T) {
} }
// Lookup by ID, should be nil. // Lookup by ID, should be nil.
idx, s2, err = s.SessionGet(nil, session.ID, nil) idx, s2, err := s.SessionGet(nil, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -849,7 +850,7 @@ func TestStateStore_Session_Invalidate_Key_Delete_Behavior(t *testing.T) {
// Delete the node and make sure the watches fire. // Delete the node and make sure the watches fire.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, s2, err := s.SessionGet(ws, session.ID, nil) _, _, err = s.SessionGet(ws, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -861,7 +862,7 @@ func TestStateStore_Session_Invalidate_Key_Delete_Behavior(t *testing.T) {
} }
// Lookup by ID, should be nil. // Lookup by ID, should be nil.
idx, s2, err = s.SessionGet(nil, session.ID, nil) idx, s2, err := s.SessionGet(nil, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -917,7 +918,7 @@ func TestStateStore_Session_Invalidate_PreparedQuery_Delete(t *testing.T) {
// Invalidate the session and make sure the watches fire. // Invalidate the session and make sure the watches fire.
ws := memdb.NewWatchSet() ws := memdb.NewWatchSet()
idx, s2, err := s.SessionGet(ws, session.ID, nil) _, _, err := s.SessionGet(ws, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -929,7 +930,7 @@ func TestStateStore_Session_Invalidate_PreparedQuery_Delete(t *testing.T) {
} }
// Make sure the session is gone. // Make sure the session is gone.
idx, s2, err = s.SessionGet(nil, session.ID, nil) idx, s2, err := s.SessionGet(nil, session.ID, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }

View File

@ -6,6 +6,7 @@ import (
"github.com/hashicorp/consul/agent/metadata" "github.com/hashicorp/consul/agent/metadata"
"github.com/hashicorp/serf/serf" "github.com/hashicorp/serf/serf"
"github.com/stretchr/testify/require"
) )
func TestServer_Key_params(t *testing.T) { func TestServer_Key_params(t *testing.T) {
@ -136,10 +137,8 @@ func TestIsConsulServer(t *testing.T) {
} }
delete(m.Tags, "role") delete(m.Tags, "role")
ok, parts = metadata.IsConsulServer(m) ok, _ = metadata.IsConsulServer(m)
if ok { require.False(t, ok, "expected to not be a consul server")
t.Fatalf("unexpected ok server")
}
} }
func TestIsConsulServer_Optional(t *testing.T) { func TestIsConsulServer_Optional(t *testing.T) {
@ -209,8 +208,6 @@ func TestIsConsulServer_Optional(t *testing.T) {
} }
delete(m.Tags, "role") delete(m.Tags, "role")
ok, parts = metadata.IsConsulServer(m) ok, _ = metadata.IsConsulServer(m)
if ok { require.False(t, ok, "expected to not be a consul server")
t.Fatalf("unexpected ok server")
}
} }

View File

@ -750,10 +750,8 @@ func (s *state) handleUpdateUpstreams(u cache.UpdateEvent, snap *ConfigSnapshotU
return fmt.Errorf("invalid correlation id %q", u.CorrelationID) return fmt.Errorf("invalid correlation id %q", u.CorrelationID)
} }
m, ok := snap.WatchedUpstreamEndpoints[svc] if _, ok := snap.WatchedUpstreamEndpoints[svc]; !ok {
if !ok { snap.WatchedUpstreamEndpoints[svc] = make(map[string]structs.CheckServiceNodes)
m = make(map[string]structs.CheckServiceNodes)
snap.WatchedUpstreamEndpoints[svc] = m
} }
snap.WatchedUpstreamEndpoints[svc][targetID] = resp.Nodes snap.WatchedUpstreamEndpoints[svc][targetID] = resp.Nodes
@ -767,10 +765,8 @@ func (s *state) handleUpdateUpstreams(u cache.UpdateEvent, snap *ConfigSnapshotU
if !ok { if !ok {
return fmt.Errorf("invalid correlation id %q", u.CorrelationID) return fmt.Errorf("invalid correlation id %q", u.CorrelationID)
} }
m, ok := snap.WatchedGatewayEndpoints[svc] if _, ok = snap.WatchedGatewayEndpoints[svc]; !ok {
if !ok { snap.WatchedGatewayEndpoints[svc] = make(map[string]structs.CheckServiceNodes)
m = make(map[string]structs.CheckServiceNodes)
snap.WatchedGatewayEndpoints[svc] = m
} }
snap.WatchedGatewayEndpoints[svc][dc] = resp.Nodes snap.WatchedGatewayEndpoints[svc][dc] = resp.Nodes
default: default:

View File

@ -487,9 +487,8 @@ func TestSessionCustomTTL(t *testing.T) {
r.Fatalf("err: %v", err) r.Fatalf("err: %v", err)
} }
respObj, ok = obj.(structs.Sessions) respObj, ok = obj.(structs.Sessions)
if len(respObj) != 0 { require.True(r, ok, "unexpected type: %T", obj)
r.Fatalf("session '%s' should have been destroyed", id) require.Len(r, respObj, 0)
}
}) })
} }

View File

@ -165,7 +165,7 @@ func TestHelperProcess(t *testing.T) {
defer os.Exit(0) defer os.Exit(0)
args = args[1:] // strip sentinel value args = args[1:] // strip sentinel value
cmd, args := args[0], args[1:] cmd := args[0]
switch cmd { switch cmd {
case "parent-signal": case "parent-signal":

View File

@ -741,7 +741,7 @@ func TestAPI_AgentService(t *testing.T) {
WaitTime: 100 * time.Millisecond, // Just long enough to be reliably measurable WaitTime: 100 * time.Millisecond, // Just long enough to be reliably measurable
} }
start := time.Now() start := time.Now()
got, qm, err = agent.Service("foo", &opts) _, _, err = agent.Service("foo", &opts)
elapsed := time.Since(start) elapsed := time.Since(start)
require.NoError(err) require.NoError(err)
require.True(elapsed >= opts.WaitTime) require.True(elapsed >= opts.WaitTime)

View File

@ -150,7 +150,7 @@ func TestAPI_ConfigEntries_IngressGateway(t *testing.T) {
require.NotEqual(t, 0, wm.RequestTime) require.NotEqual(t, 0, wm.RequestTime)
// verify deletion // verify deletion
entry, qm, err = config_entries.Get(IngressGateway, "foo", nil) _, _, err = config_entries.Get(IngressGateway, "foo", nil)
require.Error(t, err) require.Error(t, err)
} }
@ -279,6 +279,6 @@ func TestAPI_ConfigEntries_TerminatingGateway(t *testing.T) {
require.NotEqual(t, 0, wm.RequestTime) require.NotEqual(t, 0, wm.RequestTime)
// verify deletion // verify deletion
entry, qm, err = configEntries.Get(TerminatingGateway, "foo", nil) _, _, err = configEntries.Get(TerminatingGateway, "foo", nil)
require.Error(t, err) require.Error(t, err)
} }

View File

@ -83,7 +83,7 @@ func TestAPI_ConfigEntries(t *testing.T) {
require.NotNil(t, wm) require.NotNil(t, wm)
require.NotEqual(t, 0, wm.RequestTime) require.NotEqual(t, 0, wm.RequestTime)
entry, qm, err = config_entries.Get(ProxyDefaults, ProxyConfigGlobal, nil) _, _, err = config_entries.Get(ProxyDefaults, ProxyConfigGlobal, nil)
require.Error(t, err) require.Error(t, err)
}) })
@ -181,7 +181,7 @@ func TestAPI_ConfigEntries(t *testing.T) {
require.NotEqual(t, 0, wm.RequestTime) require.NotEqual(t, 0, wm.RequestTime)
// verify deletion // verify deletion
entry, qm, err = config_entries.Get(ServiceDefaults, "foo", nil) _, _, err = config_entries.Get(ServiceDefaults, "foo", nil)
require.Error(t, err) require.Error(t, err)
}) })
} }

View File

@ -227,6 +227,9 @@ WAIT:
// Determine why the lock failed // Determine why the lock failed
qOpts.WaitIndex = 0 qOpts.WaitIndex = 0
pair, meta, err = kv.Get(l.opts.Key, &qOpts) pair, meta, err = kv.Get(l.opts.Key, &qOpts)
if err != nil {
return nil, err
}
if pair != nil && pair.Session != "" { if pair != nil && pair.Session != "" {
//If the session is not null, this means that a wait can safely happen //If the session is not null, this means that a wait can safely happen
//using a long poll //using a long poll

View File

@ -227,7 +227,7 @@ func TestAPI_SemaphoreBadLimit(t *testing.T) {
s.WaitForSerfCheck(t) s.WaitForSerfCheck(t)
sema, err := c.SemaphorePrefix("test/semaphore", 0) _, err := c.SemaphorePrefix("test/semaphore", 0)
if err == nil { if err == nil {
t.Fatalf("should error, limit must be positive") t.Fatalf("should error, limit must be positive")
} }

View File

@ -2,10 +2,11 @@ package api
import ( import (
"context" "context"
"github.com/stretchr/testify/assert"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
) )
func TestAPI_SessionCreateDestroy(t *testing.T) { func TestAPI_SessionCreateDestroy(t *testing.T) {
@ -411,7 +412,7 @@ func TestAPI_SessionNode(t *testing.T) {
} }
defer session.Destroy(id, nil) defer session.Destroy(id, nil)
info, qm, err := session.Info(id, nil) info, _, err := session.Info(id, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -478,14 +479,14 @@ func TestAPI_SessionNodeChecks(t *testing.T) {
} }
session := c.Session() session := c.Session()
id, _, err := session.Create(&se, nil) _, _, err := session.Create(&se, nil)
if err == nil { if err == nil {
t.Fatalf("should have failed") t.Fatalf("should have failed")
} }
// Empty node check should lead to serf check // Empty node check should lead to serf check
se.NodeChecks = []string{} se.NodeChecks = []string{}
id, _, err = session.Create(&se, nil) id, _, err := session.Create(&se, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -588,7 +589,7 @@ func TestAPI_SessionServiceChecks(t *testing.T) {
} }
session := c.Session() session := c.Session()
id, _, err := session.Create(&se, nil) _, _, err := session.Create(&se, nil)
if err == nil { if err == nil {
t.Fatalf("should have failed") t.Fatalf("should have failed")
} }
@ -624,7 +625,7 @@ func TestAPI_SessionServiceChecks(t *testing.T) {
{"redis:alive", ""}, {"redis:alive", ""},
} }
id, _, err = session.Create(&se, nil) id, _, err := session.Create(&se, nil)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }

View File

@ -180,7 +180,7 @@ func (a *Authenticator) verifyVanillaJWT(ctx context.Context, loginToken string)
// //
// go-sso added support for ed25519 (EdDSA) // go-sso added support for ed25519 (EdDSA)
func parsePublicKeyPEM(data []byte) (interface{}, error) { func parsePublicKeyPEM(data []byte) (interface{}, error) {
block, data := pem.Decode(data) block, _ := pem.Decode(data)
if block != nil { if block != nil {
var rawKey interface{} var rawKey interface{}
var err error var err error

View File

@ -282,6 +282,9 @@ func decodeHCLToMapStructure(source string, target interface{}) error {
Metadata: md, Metadata: md,
Result: target, Result: target,
}) })
if err != nil {
return err
}
return decoder.Decode(&raw) return decoder.Decode(&raw)
} }
@ -305,6 +308,7 @@ func TestHookWeakDecodeFromSlice_DoesNotModifySliceTargetsFromSliceInterface(t *
}) })
require.NoError(t, err) require.NoError(t, err)
err = decoder.Decode(&raw) err = decoder.Decode(&raw)
require.NoError(t, err)
expected := &nested{ expected := &nested{
Slice: []Item{{Name: "first"}}, Slice: []Item{{Name: "first"}},

View File

@ -964,6 +964,7 @@ func TestConfigurator_OutgoingRPCWrapper(t *testing.T) {
require.NotNil(t, wrapper) require.NotNil(t, wrapper)
conn := &net.TCPConn{} conn := &net.TCPConn{}
cWrap, err := wrapper("", conn) cWrap, err := wrapper("", conn)
require.NoError(t, err)
require.Equal(t, conn, cWrap) require.Equal(t, conn, cWrap)
c, err = NewConfigurator(Config{ c, err = NewConfigurator(Config{
@ -975,6 +976,7 @@ func TestConfigurator_OutgoingRPCWrapper(t *testing.T) {
wrapper = c.OutgoingRPCWrapper() wrapper = c.OutgoingRPCWrapper()
require.NotNil(t, wrapper) require.NotNil(t, wrapper)
cWrap, err = wrapper("", conn) cWrap, err = wrapper("", conn)
require.EqualError(t, err, "invalid argument")
require.NotEqual(t, conn, cWrap) require.NotEqual(t, conn, cWrap)
} }
@ -984,6 +986,7 @@ func TestConfigurator_OutgoingALPNRPCWrapper(t *testing.T) {
require.NotNil(t, wrapper) require.NotNil(t, wrapper)
conn := &net.TCPConn{} conn := &net.TCPConn{}
cWrap, err := wrapper("", conn) cWrap, err := wrapper("", conn)
require.NoError(t, err)
require.Equal(t, conn, cWrap) require.Equal(t, conn, cWrap)
c, err = NewConfigurator(Config{ c, err = NewConfigurator(Config{
@ -995,6 +998,7 @@ func TestConfigurator_OutgoingALPNRPCWrapper(t *testing.T) {
wrapper = c.OutgoingRPCWrapper() wrapper = c.OutgoingRPCWrapper()
require.NotNil(t, wrapper) require.NotNil(t, wrapper)
cWrap, err = wrapper("", conn) cWrap, err = wrapper("", conn)
require.EqualError(t, err, "invalid argument")
require.NotEqual(t, conn, cWrap) require.NotEqual(t, conn, cWrap)
} }