cleanup unused code and fix t.Fatal usage in goroutine in testing (#11694)

This commit is contained in:
Mayo 2021-09-30 19:33:14 +08:00 committed by GitHub
parent 39a9727c8b
commit 0bd0339c0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 91 additions and 91 deletions

View File

@ -2,7 +2,6 @@ package command
import (
"context"
"errors"
"flag"
"fmt"
"io"
@ -336,6 +335,7 @@ func (c *AgentCommand) Run(args []string) int {
// TemplateServer that periodically listen for ctx.Done() to fire and shut
// down accordingly.
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
var method auth.AuthMethod
var sinks []*sink.SinkConfig
@ -880,7 +880,7 @@ func verifyRequestHeader(handler http.Handler) http.Handler {
if val, ok := r.Header[consts.RequestHeaderName]; !ok || len(val) != 1 || val[0] != "true" {
logical.RespondError(w,
http.StatusPreconditionFailed,
errors.New(fmt.Sprintf("missing '%s' header", consts.RequestHeaderName)))
fmt.Errorf("missing '%s' header", consts.RequestHeaderName))
return
}
@ -927,7 +927,7 @@ func (c *AgentCommand) setBoolFlag(f *FlagSets, configVal bool, fVar *BoolVar) {
case flagEnvSet:
// Use value from env var
*fVar.Target = flagEnvValue != ""
case configVal == true:
case configVal:
// Use value from config
*fVar.Target = configVal
default:

View File

@ -1618,10 +1618,10 @@ func TestAgent_Cache_Retry(t *testing.T) {
t.Run(tcname, func(t *testing.T) {
h.failCount = 2
cacheConfig := fmt.Sprintf(`
cacheConfig := `
cache {
}
`)
`
listenAddr := "127.0.0.1:18123"
listenConfig := fmt.Sprintf(`
listener "tcp" {

View File

@ -74,10 +74,12 @@ func TestAppRole_Integ_ConcurrentLogins(t *testing.T) {
"secret_id": secretID,
})
if err != nil {
t.Fatal(err)
t.Error(err)
return
}
if secret.Auth.ClientToken == "" {
t.Fatalf("expected a successful login")
t.Error("expected a successful login")
return
}
}()

View File

@ -99,7 +99,7 @@ func (c *AuditListCommand) Run(args []string) int {
switch Format(c.UI) {
case "table":
if len(audits) == 0 {
c.UI.Output(fmt.Sprintf("No audit devices are enabled."))
c.UI.Output("No audit devices are enabled.")
return 2
}

View File

@ -27,14 +27,14 @@ func Test_BoolPtr(t *testing.T) {
require.True(t, boolPtr.Get())
var boolPtrFalseDefault BoolPtr
value = newBoolPtrValue(new(bool), &boolPtrFalseDefault, false)
_ = newBoolPtrValue(new(bool), &boolPtrFalseDefault, false)
require.True(t, boolPtrFalseDefault.IsSet())
require.False(t, boolPtrFalseDefault.Get())
var boolPtrTrueDefault BoolPtr
defTrue := true
value = newBoolPtrValue(&defTrue, &boolPtrTrueDefault, false)
_ = newBoolPtrValue(&defTrue, &boolPtrTrueDefault, false)
require.True(t, boolPtrTrueDefault.IsSet())
require.True(t, boolPtrTrueDefault.Get())

View File

@ -261,13 +261,13 @@ func humanDuration(d time.Duration) string {
// humanDurationInt prints the given int as if it were a time.Duration number
// of seconds.
func humanDurationInt(i interface{}) interface{} {
switch i.(type) {
switch i := i.(type) {
case int:
return humanDuration(time.Duration(i.(int)) * time.Second)
return humanDuration(time.Duration(i) * time.Second)
case int64:
return humanDuration(time.Duration(i.(int64)) * time.Second)
return humanDuration(time.Duration(i) * time.Second)
case json.Number:
if i, err := i.(json.Number).Int64(); err == nil {
if i, err := i.Int64(); err == nil {
return humanDuration(time.Duration(i) * time.Second)
}
}

View File

@ -150,7 +150,7 @@ func TestTruncateToSeconds(t *testing.T) {
for _, tc := range cases {
tc := tc
t.Run(fmt.Sprintf("%s", tc.d), func(t *testing.T) {
t.Run(tc.d.String(), func(t *testing.T) {
t.Parallel()
act := truncateToSeconds(tc.d)

View File

@ -31,9 +31,9 @@ func OutputSecret(ui cli.Ui, secret *api.Secret) int {
}
func OutputList(ui cli.Ui, data interface{}) int {
switch data.(type) {
switch data := data.(type) {
case *api.Secret:
secret := data.(*api.Secret)
secret := data
return outputWithFormat(ui, secret, secret.Data["keys"])
default:
return outputWithFormat(ui, nil, data)
@ -73,9 +73,9 @@ var Formatters = map[string]Formatter{
}
func Format(ui cli.Ui) string {
switch ui.(type) {
switch ui := ui.(type) {
case *VaultUI:
return ui.(*VaultUI).format
return ui.format
}
format := os.Getenv(EnvVaultFormat)
@ -158,7 +158,7 @@ func formatServer(srv *api.AutopilotServer) string {
buffer.WriteString(fmt.Sprintf(" Last Index: %d\n", srv.LastIndex))
if len(srv.Meta) > 0 {
buffer.WriteString(fmt.Sprintf(" Meta\n"))
buffer.WriteString(" Meta\n")
var outputs []mapOutput
for k, v := range srv.Meta {
outputs = append(outputs, mapOutput{key: k, value: fmt.Sprintf(" %q: %q\n", k, v)})
@ -218,7 +218,7 @@ func (t TableFormatter) Format(data interface{}) ([]byte, error) {
}
func (t TableFormatter) Output(ui cli.Ui, secret *api.Secret, data interface{}) error {
switch data.(type) {
switch data := data.(type) {
case *api.Secret:
return t.OutputSecret(ui, secret)
case []interface{}:
@ -226,7 +226,7 @@ func (t TableFormatter) Output(ui cli.Ui, secret *api.Secret, data interface{})
case []string:
return t.OutputList(ui, nil, data)
case map[string]interface{}:
return t.OutputMap(ui, data.(map[string]interface{}))
return t.OutputMap(ui, data)
case SealStatusOutput:
return t.OutputSealStatusStruct(ui, nil, data)
default:
@ -319,10 +319,10 @@ func (t TableFormatter) OutputSealStatusStruct(ui cli.Ui, secret *api.Secret, da
func (t TableFormatter) OutputList(ui cli.Ui, secret *api.Secret, data interface{}) error {
t.printWarnings(ui, secret)
switch data.(type) {
switch data := data.(type) {
case []interface{}:
case []string:
ui.Output(tableOutput(data.([]string), nil))
ui.Output(tableOutput(data, nil))
return nil
default:
return errors.New("error: table formatter cannot output list for this data type")

View File

@ -111,7 +111,7 @@ func (c *KVPatchCommand) Run(args []string) int {
}
if !v2 {
c.UI.Error(fmt.Sprintf("K/V engine mount must be version 2 for patch support"))
c.UI.Error("K/V engine mount must be version 2 for patch support")
return 2
}

View File

@ -88,7 +88,7 @@ func (c *KVRollbackCommand) Run(args []string) int {
c.UI.Error(fmt.Sprintf("Invalid number of arguments (expected 1, got %d)", len(args)))
return 1
case version == nil:
c.UI.Error(fmt.Sprintf("Version flag must be specified"))
c.UI.Error("Version flag must be specified")
return 1
case c.flagVersion <= 0:
c.UI.Error(fmt.Sprintf("Invalid value %d for the version flag", c.flagVersion))
@ -111,7 +111,7 @@ func (c *KVRollbackCommand) Run(args []string) int {
}
if !v2 {
c.UI.Error(fmt.Sprintf("K/V engine mount must be version 2 for rollback support"))
c.UI.Error("K/V engine mount must be version 2 for rollback support")
return 2
}
@ -193,12 +193,12 @@ func (c *KVRollbackCommand) Run(args []string) int {
// Verify it hasn't been deleted
if meta["deletion_time"] != nil && meta["deletion_time"].(string) != "" {
c.UI.Error(fmt.Sprintf("Cannot roll back to a version that has been deleted"))
c.UI.Error("Cannot roll back to a version that has been deleted")
return 2
}
if meta["destroyed"] != nil && meta["destroyed"].(bool) {
c.UI.Error(fmt.Sprintf("Cannot roll back to a version that has been destroyed"))
c.UI.Error("Cannot roll back to a version that has been destroyed")
return 2
}

View File

@ -26,7 +26,7 @@ func retryKVCommand(t *testing.T, client *api.Client, args []string) (code int,
// Loop until return message does not indicate upgrade, or timeout.
timeout := time.After(20 * time.Second)
for true {
for {
ui, cmd := testKVPutCommand(t)
cmd.client = client
code = cmd.Run(args)

View File

@ -78,11 +78,9 @@ func TestMonitorCommand_Run(t *testing.T) {
atomic.StoreInt64(&code, int64(cmd.Run(tc.args)))
}()
select {
case <-time.After(3 * time.Second):
stopCh <- struct{}{}
close(shutdownCh)
}
<-time.After(3 * time.Second)
stopCh <- struct{}{}
close(shutdownCh)
if atomic.LoadInt64(&code) != tc.code {
t.Errorf("expected %d to be %d", code, tc.code)

View File

@ -83,7 +83,7 @@ func (c *NamespaceListCommand) Run(args []string) int {
}
if secret == nil {
c.UI.Error(fmt.Sprintf("No namespaces found"))
c.UI.Error("No namespaces found")
return 2
}
@ -97,7 +97,7 @@ func (c *NamespaceListCommand) Run(args []string) int {
}
if !ok {
c.UI.Error(fmt.Sprintf("No entries found"))
c.UI.Error("No entries found")
return 2
}

View File

@ -404,13 +404,13 @@ func (c *OperatorRekeyCommand) provide(client *api.Client, key string) int {
var started bool
var nonce string
switch status.(type) {
switch status := status.(type) {
case *api.RekeyStatusResponse:
stat := status.(*api.RekeyStatusResponse)
stat := status
started = stat.Started
nonce = stat.Nonce
case *api.RekeyVerificationStatusResponse:
stat := status.(*api.RekeyVerificationStatusResponse)
stat := status
started = stat.Started
nonce = stat.Nonce
default:
@ -489,12 +489,12 @@ func (c *OperatorRekeyCommand) provide(client *api.Client, key string) int {
var complete bool
var mightContainUnsealKeys bool
switch resp.(type) {
switch resp := resp.(type) {
case *api.RekeyUpdateResponse:
complete = resp.(*api.RekeyUpdateResponse).Complete
complete = resp.Complete
mightContainUnsealKeys = true
case *api.RekeyVerificationUpdateResponse:
complete = resp.(*api.RekeyVerificationUpdateResponse).Complete
complete = resp.Complete
default:
c.UI.Error("Unknown update response type")
return 1
@ -608,9 +608,9 @@ func (c *OperatorRekeyCommand) printStatus(in interface{}) int {
out := []string{}
out = append(out, "Key | Value")
switch in.(type) {
switch in := in.(type) {
case *api.RekeyStatusResponse:
status := in.(*api.RekeyStatusResponse)
status := in
out = append(out, fmt.Sprintf("Nonce | %s", status.Nonce))
out = append(out, fmt.Sprintf("Started | %t", status.Started))
if status.Started {
@ -631,7 +631,7 @@ func (c *OperatorRekeyCommand) printStatus(in interface{}) int {
out = append(out, fmt.Sprintf("Backup | %t", status.Backup))
}
case *api.RekeyVerificationStatusResponse:
status := in.(*api.RekeyVerificationStatusResponse)
status := in
out = append(out, fmt.Sprintf("Started | %t", status.Started))
out = append(out, fmt.Sprintf("New Shares | %d", status.N))
out = append(out, fmt.Sprintf("New Threshold | %d", status.T))

View File

@ -121,9 +121,9 @@ func parseDecryptAndTestUnsealKeys(t *testing.T,
testFunc := func(bkeys map[string][]string) {
var re *regexp.Regexp
if fingerprints {
re, err = regexp.Compile("\\s*Key\\s+\\d+\\s+fingerprint:\\s+([0-9a-fA-F]+);\\s+value:\\s+(.*)")
re, err = regexp.Compile(`\s*Key\s+\d+\s+fingerprint:\s+([0-9a-fA-F]+);\s+value:\s+(.*)`)
} else {
re, err = regexp.Compile("\\s*Key\\s+\\d+:\\s+(.*)")
re, err = regexp.Compile(`\s*Key\s+\d+:\s+(.*)`)
}
if err != nil {
t.Fatalf("Error compiling regex: %s", err)

View File

@ -24,7 +24,6 @@ import (
systemd "github.com/coreos/go-systemd/daemon"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-hclog"
log "github.com/hashicorp/go-hclog"
wrapping "github.com/hashicorp/go-kms-wrapping"
aeadwrapper "github.com/hashicorp/go-kms-wrapping/wrappers/aead"
"github.com/hashicorp/go-multierror"
@ -51,6 +50,7 @@ import (
vaultseal "github.com/hashicorp/vault/vault/seal"
"github.com/mitchellh/cli"
"github.com/mitchellh/go-testing-interface"
"github.com/pkg/errors"
"github.com/posener/complete"
"go.uber.org/atomic"
"golang.org/x/net/http/httpproxy"
@ -96,7 +96,7 @@ type ServerCommand struct {
logOutput io.Writer
gatedWriter *gatedwriter.Writer
logger log.InterceptLogger
logger hclog.InterceptLogger
cleanupGuard sync.Once
@ -106,7 +106,7 @@ type ServerCommand struct {
reloadedCh chan (struct{}) // for tests
licenseReloadedCh chan (error) // for tests
allLoggers []log.Logger
allLoggers []hclog.Logger
// new stuff
flagConfigs []string
@ -450,7 +450,7 @@ func (c *ServerCommand) runRecoveryMode() int {
return 1
}
c.logger = log.NewInterceptLogger(&log.LoggerOptions{
c.logger = hclog.NewInterceptLogger(&hclog.LoggerOptions{
Output: c.gatedWriter,
Level: level,
// Note that if logFormat is either unspecified or standard, then
@ -725,7 +725,6 @@ func (c *ServerCommand) runRecoveryMode() int {
}
}
return 0
}
func logProxyEnvironmentVariables(logger hclog.Logger) {
@ -760,15 +759,15 @@ func (c *ServerCommand) adjustLogLevel(config *server.Config, logLevelWasNotSet
logLevelString = configLogLevel
switch configLogLevel {
case "trace":
c.logger.SetLevel(log.Trace)
c.logger.SetLevel(hclog.Trace)
case "debug":
c.logger.SetLevel(log.Debug)
c.logger.SetLevel(hclog.Debug)
case "notice", "info", "":
c.logger.SetLevel(log.Info)
c.logger.SetLevel(hclog.Info)
case "warn", "warning":
c.logger.SetLevel(log.Warn)
c.logger.SetLevel(hclog.Warn)
case "err", "error":
c.logger.SetLevel(log.Error)
c.logger.SetLevel(hclog.Error)
default:
return "", fmt.Errorf("unknown log level: %s", config.LogLevel)
}
@ -776,7 +775,7 @@ func (c *ServerCommand) adjustLogLevel(config *server.Config, logLevelWasNotSet
return logLevelString, nil
}
func (c *ServerCommand) processLogLevelAndFormat(config *server.Config) (log.Level, string, bool, logging.LogFormat, error) {
func (c *ServerCommand) processLogLevelAndFormat(config *server.Config) (hclog.Level, string, bool, logging.LogFormat, error) {
// Create a logger. We wrap it in a gated writer so that it doesn't
// start logging too early.
c.logOutput = os.Stderr
@ -784,7 +783,7 @@ func (c *ServerCommand) processLogLevelAndFormat(config *server.Config) (log.Lev
c.logOutput = os.Stdout
}
c.gatedWriter = gatedwriter.NewWriter(c.logOutput)
var level log.Level
var level hclog.Level
var logLevelWasNotSet bool
logFormat := logging.UnspecifiedFormat
logLevelString := c.flagLogLevel
@ -793,17 +792,17 @@ func (c *ServerCommand) processLogLevelAndFormat(config *server.Config) (log.Lev
case notSetValue, "":
logLevelWasNotSet = true
logLevelString = "info"
level = log.Info
level = hclog.Info
case "trace":
level = log.Trace
level = hclog.Trace
case "debug":
level = log.Debug
level = hclog.Debug
case "notice", "info":
level = log.Info
level = hclog.Info
case "warn", "warning":
level = log.Warn
level = hclog.Warn
case "err", "error":
level = log.Error
level = hclog.Error
default:
return level, logLevelString, logLevelWasNotSet, logFormat, fmt.Errorf("unknown log level: %s", c.flagLogLevel)
}
@ -833,14 +832,14 @@ type quiescenceSink struct {
t *time.Timer
}
func (q quiescenceSink) Accept(name string, level log.Level, msg string, args ...interface{}) {
func (q quiescenceSink) Accept(name string, level hclog.Level, msg string, args ...interface{}) {
q.t.Reset(100 * time.Millisecond)
}
func (c *ServerCommand) setupStorage(config *server.Config) (physical.Backend, error) {
// Ensure that a backend is provided
if config.Storage == nil {
return nil, fmt.Errorf("A storage backend must be specified")
return nil, errors.New("A storage backend must be specified")
}
// Initialize the backend
@ -866,7 +865,7 @@ func (c *ServerCommand) setupStorage(config *server.Config) (physical.Backend, e
config.ClusterAddr = envCA
}
if len(config.ClusterAddr) == 0 {
return nil, fmt.Errorf("Cluster address must be set when using raft storage")
return nil, errors.New("Cluster address must be set when using raft storage")
}
}
@ -1097,13 +1096,13 @@ func (c *ServerCommand) Run(args []string) int {
config.LogFormat = logFormat.String()
if c.flagDevThreeNode || c.flagDevFourCluster {
c.logger = log.NewInterceptLogger(&log.LoggerOptions{
c.logger = hclog.NewInterceptLogger(&hclog.LoggerOptions{
Mutex: &sync.Mutex{},
Output: c.gatedWriter,
Level: log.Trace,
Level: hclog.Trace,
})
} else {
c.logger = log.NewInterceptLogger(&log.LoggerOptions{
c.logger = hclog.NewInterceptLogger(&hclog.LoggerOptions{
Output: c.gatedWriter,
Level: level,
// Note that if logFormat is either unspecified or standard, then
@ -1115,7 +1114,7 @@ func (c *ServerCommand) Run(args []string) int {
// Ensure logging is flushed if initialization fails
defer c.flushLog()
c.allLoggers = []log.Logger{c.logger}
c.allLoggers = []hclog.Logger{c.logger}
logLevelStr, err := c.adjustLogLevel(config, logLevelWasNotSet)
if err != nil {
@ -1233,7 +1232,7 @@ func (c *ServerCommand) Run(args []string) int {
}
if barrierSeal == nil {
c.UI.Error(fmt.Sprintf("Could not create barrier seal! Most likely proper Seal configuration information was not set, but no error was generated."))
c.UI.Error("Could not create barrier seal! Most likely proper Seal configuration information was not set, but no error was generated.")
return 1
}
@ -1519,7 +1518,7 @@ func (c *ServerCommand) Run(args []string) int {
// Check for new log level
var config *server.Config
var level log.Level
var level hclog.Level
for _, path := range c.flagConfigs {
current, err := server.LoadConfig(path)
if err != nil {
@ -1546,15 +1545,15 @@ func (c *ServerCommand) Run(args []string) int {
configLogLevel := strings.ToLower(strings.TrimSpace(config.LogLevel))
switch configLogLevel {
case "trace":
level = log.Trace
level = hclog.Trace
case "debug":
level = log.Debug
level = hclog.Debug
case "notice", "info", "":
level = log.Info
level = hclog.Info
case "warn", "warning":
level = log.Warn
level = hclog.Warn
case "err", "error":
level = log.Error
level = hclog.Error
default:
c.logger.Error("unknown log level found on reload", "level", config.LogLevel)
goto RUNRELOADFUNCS
@ -1673,7 +1672,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig
if leaderCount == 0 {
buf := make([]byte, 1<<16)
runtime.Stack(buf, true)
return nil, fmt.Errorf("failed to get active status after five seconds; call stack is\n%s\n", buf)
return nil, fmt.Errorf("failed to get active status after five seconds; call stack is\n%s", buf)
}
time.Sleep(1 * time.Second)
isLeader, _, _, err = core.Leader()
@ -1714,7 +1713,7 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig
req.ID = "dev-revoke-init-root"
req.Path = "auth/token/revoke-self"
req.Data = nil
resp, err = core.HandleRequest(ctx, req)
_, err = core.HandleRequest(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to revoke initial root token: %w", err)
}
@ -1852,7 +1851,7 @@ func (c *ServerCommand) enableThreeNodeDevCluster(base *vault.CoreConfig, info m
req.ID = "dev-revoke-init-root"
req.Path = "auth/token/revoke-self"
req.Data = nil
resp, err = testCluster.Cores[0].HandleRequest(ctx, req)
_, err = testCluster.Cores[0].HandleRequest(ctx, req)
if err != nil {
c.UI.Output(fmt.Sprintf("failed to revoke initial root token: %s", err))
return 1
@ -2696,7 +2695,7 @@ func SetStorageMigration(b physical.Backend, active bool) error {
}
type grpclogFaker struct {
logger log.Logger
logger hclog.Logger
log bool
}

View File

@ -15,7 +15,8 @@ func testListenerImpl(t *testing.T, ln net.Listener, connFn testListenerConnFn,
go func() {
server, err := ln.Accept()
if err != nil {
t.Fatalf("err: %s", err)
t.Errorf("err: %s", err)
return
}
if certName != "" {
tlsConn := server.(*tls.Conn)

View File

@ -71,7 +71,7 @@ func (c *TokenCapabilitiesCommand) Run(args []string) int {
args = f.Args()
switch len(args) {
case 0:
c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1-2, got 0)"))
c.UI.Error("Not enough arguments (expected 1-2, got 0)")
return 1
case 1:
path = args[0]
@ -99,7 +99,7 @@ func (c *TokenCapabilitiesCommand) Run(args []string) int {
return 2
}
if capabilities == nil {
c.UI.Error(fmt.Sprintf("No capabilities found"))
c.UI.Error("No capabilities found")
return 1
}

View File

@ -90,11 +90,11 @@ func RawField(secret *api.Secret, field string) interface{} {
// PrintRawField prints raw field from the secret.
func PrintRawField(ui cli.Ui, data interface{}, field string) int {
var val interface{}
switch data.(type) {
switch data := data.(type) {
case *api.Secret:
val = RawField(data.(*api.Secret), field)
val = RawField(data, field)
case map[string]interface{}:
val = data.(map[string]interface{})[field]
val = data[field]
}
if val == nil {

View File

@ -782,7 +782,7 @@ func (f *FSM) SetNoopRestore(enabled bool) {
func (f *FSM) Restore(r io.ReadCloser) error {
defer metrics.MeasureSince([]string{"raft_storage", "fsm", "restore_snapshot"}, time.Now())
if f.noopRestore == true {
if f.noopRestore {
return nil
}