fix new lint errors

pull/19447/head
Steven Powell 2024-08-14 10:31:53 -07:00
parent e126545ff6
commit d8c94a6ad6
25 changed files with 137 additions and 75 deletions

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"fmt"
"log" "log"
v1 "k8s.io/api/admissionregistration/v1" v1 "k8s.io/api/admissionregistration/v1"
@ -59,7 +58,7 @@ func apiServerCert(clientset *kubernetes.Clientset) []byte {
pem, ok := c.Data["requestheader-client-ca-file"] pem, ok := c.Data["requestheader-client-ca-file"]
if !ok { if !ok {
klog.Fatalf(fmt.Sprintf("cannot find the ca.crt in the configmap, configMap.Data is %#v", c.Data)) klog.Fatalf("cannot find the ca.crt in the configmap, configMap.Data is %#v", c.Data)
} }
klog.Info("client-ca-file=", pem) klog.Info("client-ca-file=", pem)
return []byte(pem) return []byte(pem)

View File

@ -241,7 +241,7 @@ func warnInvalidProfiles(invalidProfiles []*config.Profile) {
out.ErrT(style.Tip, "You can delete them using the following command(s): ") out.ErrT(style.Tip, "You can delete them using the following command(s): ")
for _, p := range invalidProfiles { for _, p := range invalidProfiles {
out.Err(fmt.Sprintf("\t $ minikube delete -p %s \n", p.Name)) out.Errf("\t $ minikube delete -p %s \n", p.Name)
} }
} }

View File

@ -36,7 +36,7 @@ func AskForYesNoConfirmation(s string, posResponses, negResponses []string) bool
reader := bufio.NewReader(os.Stdin) reader := bufio.NewReader(os.Stdin)
for { for {
out.String("%s [y/n]: ", s) out.Stringf("%s [y/n]: ", s)
response, err := reader.ReadString('\n') response, err := reader.ReadString('\n')
if err != nil { if err != nil {
@ -78,7 +78,7 @@ func AskForStaticValueOptional(s string) string {
} }
func getStaticValue(reader *bufio.Reader, s string) string { func getStaticValue(reader *bufio.Reader, s string) string {
out.String("%s", s) out.String(s)
response, err := reader.ReadString('\n') response, err := reader.ReadString('\n')
if err != nil { if err != nil {

View File

@ -642,7 +642,7 @@ func killProcess(path string) error {
// if multiple errors were encountered, combine them into a single error // if multiple errors were encountered, combine them into a single error
out.Styled(style.Failure, "Multiple errors encountered:") out.Styled(style.Failure, "Multiple errors encountered:")
for _, e := range errs { for _, e := range errs {
out.Err("%v\n", e) out.Errf("%v\n", e)
} }
return errors.New("multiple errors encountered while closing mount processes") return errors.New("multiple errors encountered while closing mount processes")
} }

View File

@ -314,7 +314,7 @@ var buildImageCmd = &cobra.Command{
if runtime.GOOS == "windows" && strings.Contains(dockerFile, "\\") { if runtime.GOOS == "windows" && strings.Contains(dockerFile, "\\") {
// if dockerFile is a DOS path, translate it into UNIX path // if dockerFile is a DOS path, translate it into UNIX path
// because we are going to build this image in UNIX environment // because we are going to build this image in UNIX environment
out.String("minikube detects that you are using DOS-style path %s. minikube will convert it to UNIX-style by replacing all \\ to /", dockerFile) out.Stringf("minikube detects that you are using DOS-style path %s. minikube will convert it to UNIX-style by replacing all \\ to /", dockerFile)
dockerFile = strings.ReplaceAll(dockerFile, "\\", "/") dockerFile = strings.ReplaceAll(dockerFile, "\\", "/")
} }
if err := machine.BuildImage(img, dockerFile, tag, push, buildEnv, buildOpt, []*config.Profile{profile}, allNodes, nodeName); err != nil { if err := machine.BuildImage(img, dockerFile, tag, push, buildEnv, buildOpt, []*config.Profile{profile}, allNodes, nodeName); err != nil {

View File

@ -147,7 +147,7 @@ You may select another namespace by using 'minikube service {{.service}} -n <nam
data = append(data, []string{svc.Namespace, svc.Name, servicePortNames, serviceURLs}) data = append(data, []string{svc.Namespace, svc.Name, servicePortNames, serviceURLs})
if serviceURLMode && !driver.NeedsPortForward(co.Config.Driver) { if serviceURLMode && !driver.NeedsPortForward(co.Config.Driver) {
out.String(fmt.Sprintf("%s\n", serviceURLs)) out.Stringf("%s\n", serviceURLs)
} }
} }
// check whether there are running pods for this service // check whether there are running pods for this service
@ -229,7 +229,7 @@ func startKicServiceTunnel(services service.URLs, configName, driverName string)
service.PrintServiceList(os.Stdout, data) service.PrintServiceList(os.Stdout, data)
} else { } else {
for _, row := range data { for _, row := range data {
out.String(fmt.Sprintf("%s\n", row[3])) out.Stringf("%s\n", row[3])
} }
} }
@ -286,12 +286,12 @@ func openURLs(urls [][]string) {
_, err := url.Parse(u[3]) _, err := url.Parse(u[3])
if err != nil { if err != nil {
klog.Warningf("failed to parse url %q: %v (will not open)", u[3], err) klog.Warningf("failed to parse url %q: %v (will not open)", u[3], err)
out.String(fmt.Sprintf("%s\n", u)) out.Stringf("%s\n", u)
continue continue
} }
if serviceURLMode { if serviceURLMode {
out.String(fmt.Sprintf("%s\n", u)) out.Stringf("%s\n", u)
continue continue
} }

View File

@ -100,7 +100,7 @@ func TestSetAndSave(t *testing.T) {
// enable // enable
if err := SetAndSave(profile, "dashboard", "true"); err != nil { if err := SetAndSave(profile, "dashboard", "true"); err != nil {
t.Errorf("Disable returned unexpected error: " + err.Error()) t.Errorf("Disable returned unexpected error: %v", err)
} }
c, err := config.DefaultLoader.LoadConfigFromFile(profile) c, err := config.DefaultLoader.LoadConfigFromFile(profile)
@ -113,7 +113,7 @@ func TestSetAndSave(t *testing.T) {
// disable // disable
if err := SetAndSave(profile, "dashboard", "false"); err != nil { if err := SetAndSave(profile, "dashboard", "false"); err != nil {
t.Errorf("Disable returned unexpected error: " + err.Error()) t.Errorf("Disable returned unexpected error: %v", err)
} }
c, err = config.DefaultLoader.LoadConfigFromFile(profile) c, err = config.DefaultLoader.LoadConfigFromFile(profile)

View File

@ -17,6 +17,7 @@ limitations under the License.
package addons package addons
import ( import (
"errors"
"fmt" "fmt"
"strconv" "strconv"
@ -53,7 +54,7 @@ func isRuntimeContainerd(cc *config.ClusterConfig, _, _ string) error {
} }
_, ok := r.(*cruntime.Containerd) _, ok := r.(*cruntime.Containerd)
if !ok { if !ok {
return fmt.Errorf(containerdOnlyAddonMsg) return errors.New(containerdOnlyAddonMsg)
} }
return nil return nil
} }

View File

@ -19,6 +19,7 @@ package kverify
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
@ -95,7 +96,7 @@ func waitPodCondition(cs *kubernetes.Clientset, name, namespace string, conditio
// return immediately: status == core.ConditionUnknown // return immediately: status == core.ConditionUnknown
if status == core.ConditionUnknown { if status == core.ConditionUnknown {
klog.Info(reason) klog.Info(reason)
return false, fmt.Errorf(reason) return false, errors.New(reason)
} }
// reduce log spam // reduce log spam
if time.Since(lap) > (2 * time.Second) { if time.Since(lap) > (2 * time.Second) {

View File

@ -58,7 +58,7 @@ func WaitForSystemPods(r cruntime.Manager, bs bootstrapper.Bootstrapper, cfg con
klog.Infof("%d kube-system pods found", len(pods.Items)) klog.Infof("%d kube-system pods found", len(pods.Items))
for _, pod := range pods.Items { for _, pod := range pods.Items {
klog.Infof(podStatusMsg(pod)) klog.Info(podStatusMsg(pod))
} }
if len(pods.Items) < 2 { if len(pods.Items) < 2 {
@ -86,7 +86,7 @@ func ExpectAppsRunning(cs *kubernetes.Clientset, expected []string) error {
klog.Infof("%d kube-system pods found", len(pods.Items)) klog.Infof("%d kube-system pods found", len(pods.Items))
for _, pod := range pods.Items { for _, pod := range pods.Items {
klog.Infof(podStatusMsg(pod)) klog.Info(podStatusMsg(pod))
if pod.Status.Phase != core.PodRunning { if pod.Status.Phase != core.PodRunning {
continue continue

View File

@ -100,7 +100,7 @@ func ISO(urls []string, skipChecksum bool) (string, error) {
msg.WriteString(fmt.Sprintf(" %s: %s\n", u, err)) msg.WriteString(fmt.Sprintf(" %s: %s\n", u, err))
} }
return "", fmt.Errorf(msg.String()) return "", errors.New(msg.String())
} }
// downloadISO downloads an ISO URL // downloadISO downloads an ISO URL

View File

@ -70,7 +70,7 @@ func Message(r reason.Kind, format string, args ...out.V) {
// Code will exit with a code // Code will exit with a code
func Code(code int) { func Code(code int) {
if shell { if shell {
out.Output(os.Stdout, fmt.Sprintf("false exit code %d\n", code)) out.Outputf(os.Stdout, "false exit code %d\n", code)
} }
os.Exit(code) os.Exit(code)
} }

View File

@ -762,21 +762,21 @@ func ListImages(profile *config.Profile, format string) error {
klog.Warningf("Error marshalling images list: %v", err.Error()) klog.Warningf("Error marshalling images list: %v", err.Error())
return nil return nil
} }
fmt.Printf(string(json) + "\n") fmt.Printf("%s\n", string(json))
case "yaml": case "yaml":
yaml, err := yaml.Marshal(uniqueImages) yaml, err := yaml.Marshal(uniqueImages)
if err != nil { if err != nil {
klog.Warningf("Error marshalling images list: %v", err.Error()) klog.Warningf("Error marshalling images list: %v", err.Error())
return nil return nil
} }
fmt.Printf(string(yaml) + "\n") fmt.Printf("%s\n", string(yaml))
default: default:
res := []string{} res := []string{}
for _, item := range uniqueImages { for _, item := range uniqueImages {
res = append(res, item.RepoTags...) res = append(res, item.RepoTags...)
} }
sort.Sort(sort.Reverse(sort.StringSlice(res))) sort.Sort(sort.Reverse(sort.StringSlice(res)))
fmt.Printf(strings.Join(res, "\n") + "\n") fmt.Printf("%s\n", strings.Join(res, "\n"))
} }
return nil return nil

View File

@ -191,7 +191,7 @@ func (api *LocalClient) Create(h *host.Host) error {
// CA cert and client cert should be generated atomically, otherwise might cause bad certificate error. // CA cert and client cert should be generated atomically, otherwise might cause bad certificate error.
lockErr := api.flock.LockWithTimeout(time.Second * 5) lockErr := api.flock.LockWithTimeout(time.Second * 5)
if lockErr != nil { if lockErr != nil {
return fmt.Errorf("failed to acquire bootstrap client lock: %v " + lockErr.Error()) return fmt.Errorf("failed to acquire bootstrap client lock: %v", lockErr)
} }
defer func() { defer func() {
lockErr = api.flock.Unlock() lockErr = api.flock.Unlock()

View File

@ -17,7 +17,6 @@ limitations under the License.
package machine package machine
import ( import (
"fmt"
"os/exec" "os/exec"
"path" "path"
"strings" "strings"
@ -173,7 +172,7 @@ func backup(h host.Host, files []string) error {
} }
} }
if len(errs) > 0 { if len(errs) > 0 {
return errors.Errorf(fmt.Sprintf("%v", errs)) return errors.Errorf("%v", errs)
} }
return nil return nil
} }
@ -208,7 +207,7 @@ func restore(h host.Host) error {
} }
} }
if len(errs) > 0 { if len(errs) > 0 {
return errors.Errorf(fmt.Sprintf("%v", errs)) return errors.Errorf("%v", errs)
} }
return nil return nil
} }

View File

@ -632,7 +632,7 @@ func setupKubeconfig(h host.Host, cc config.ClusterConfig, n config.Node, cluste
exit.Message(reason.DrvCPEndpoint, fmt.Sprintf("failed to construct cluster server address: %v", err), out.V{"profileArg": fmt.Sprintf("--profile=%s", clusterName)}) exit.Message(reason.DrvCPEndpoint, fmt.Sprintf("failed to construct cluster server address: %v", err), out.V{"profileArg": fmt.Sprintf("--profile=%s", clusterName)})
} }
} }
addr := fmt.Sprintf("https://" + net.JoinHostPort(host, strconv.Itoa(port))) addr := fmt.Sprintf("https://%s", net.JoinHostPort(host, strconv.Itoa(port)))
if cc.KubernetesConfig.APIServerName != constants.APIServerName { if cc.KubernetesConfig.APIServerName != constants.APIServerName {
addr = strings.ReplaceAll(addr, host, cc.KubernetesConfig.APIServerName) addr = strings.ReplaceAll(addr, host, cc.KubernetesConfig.APIServerName)

View File

@ -122,7 +122,7 @@ func TestLatestVersionFromURLCorrect(t *testing.T) {
latestVersion, err := latestVersionFromURL(server.URL) latestVersion, err := latestVersionFromURL(server.URL)
if err != nil { if err != nil {
t.Fatalf(err.Error()) t.Fatal(err.Error())
} }
expectedVersion, _ := semver.Make(versionFromURL) expectedVersion, _ := semver.Make(versionFromURL)
if latestVersion.Compare(expectedVersion) != 0 { if latestVersion.Compare(expectedVersion) != 0 {

View File

@ -126,12 +126,12 @@ func boxedCommon(printFunc func(format string, a ...interface{}), cfg box.Config
// Boxed writes a stylized and templated message in a box to stdout using the default style config // Boxed writes a stylized and templated message in a box to stdout using the default style config
func Boxed(format string, a ...V) { func Boxed(format string, a ...V) {
boxedCommon(String, defaultBoxCfg, "", format, a...) boxedCommon(Stringf, defaultBoxCfg, "", format, a...)
} }
// BoxedErr writes a stylized and templated message in a box to stderr using the default style config // BoxedErr writes a stylized and templated message in a box to stderr using the default style config
func BoxedErr(format string, a ...V) { func BoxedErr(format string, a ...V) {
boxedCommon(Err, defaultBoxCfg, "", format, a...) boxedCommon(Errf, defaultBoxCfg, "", format, a...)
} }
// BoxedWithConfig writes a templated message in a box with customized style config to stdout // BoxedWithConfig writes a templated message in a box with customized style config to stdout
@ -141,7 +141,7 @@ func BoxedWithConfig(cfg box.Config, st style.Enum, title string, text string, a
} }
// need to make sure no newlines are in the title otherwise box-cli-maker panics // need to make sure no newlines are in the title otherwise box-cli-maker panics
title = strings.ReplaceAll(title, "\n", "") title = strings.ReplaceAll(title, "\n", "")
boxedCommon(String, cfg, title, text, a...) boxedCommon(Stringf, cfg, title, text, a...)
} }
// Sprintf is used for returning the string (doesn't write anything) // Sprintf is used for returning the string (doesn't write anything)
@ -159,8 +159,32 @@ func Infof(format string, a ...V) {
String(outStyled) String(outStyled)
} }
// String writes a basic string to stdout
func String(s string) {
// Flush log buffer so that output order makes sense
klog.Flush()
defer klog.Flush()
if silent || JSON {
klog.Info(s)
return
}
if outFile == nil {
klog.Warningf("[unset outFile]: %s", s)
return
}
klog.Info(s)
// if spin is active from a previous step, it will stop spinner displaying
if spin.Active() {
spin.Stop()
}
Output(outFile, s)
}
// String writes a basic formatted string to stdout // String writes a basic formatted string to stdout
func String(format string, a ...interface{}) { func Stringf(format string, a ...interface{}) {
// Flush log buffer so that output order makes sense // Flush log buffer so that output order makes sense
klog.Flush() klog.Flush()
defer klog.Flush() defer klog.Flush()
@ -180,11 +204,18 @@ func String(format string, a ...interface{}) {
spin.Stop() spin.Stop()
} }
Output(outFile, format, a...) Outputf(outFile, format, a...)
} }
// Output writes a basic formatted string // Output writes a basic string
func Output(file fdWriter, format string, a ...interface{}) { func Output(file fdWriter, s string) {
if _, err := fmt.Fprint(file, s); err != nil {
klog.Errorf("Fprint failed: %v", err)
}
}
// Outputf writes a basic formatted string
func Outputf(file fdWriter, format string, a ...interface{}) {
_, err := fmt.Fprintf(file, format, a...) _, err := fmt.Fprintf(file, format, a...)
if err != nil { if err != nil {
klog.Errorf("Fprintf failed: %v", err) klog.Errorf("Fprintf failed: %v", err)
@ -192,28 +223,28 @@ func Output(file fdWriter, format string, a ...interface{}) {
} }
// spinnerString writes a basic formatted string to stdout with spinner character // spinnerString writes a basic formatted string to stdout with spinner character
func spinnerString(format string, a ...interface{}) { func spinnerString(s string) {
// Flush log buffer so that output order makes sense // Flush log buffer so that output order makes sense
klog.Flush() klog.Flush()
if outFile == nil { if outFile == nil {
klog.Warningf("[unset outFile]: %s", fmt.Sprintf(format, a...)) klog.Warningf("[unset outFile]: %s", s)
return return
} }
klog.Infof(format, a...) klog.Info(s)
// if spin is active from a previous step, it will stop spinner displaying // if spin is active from a previous step, it will stop spinner displaying
if spin.Active() { if spin.Active() {
spin.Stop() spin.Stop()
} }
Output(outFile, format, a...) Output(outFile, s)
// Start spinning at the end of the printed line // Start spinning at the end of the printed line
spin.Start() spin.Start()
} }
// Ln writes a basic formatted string with a newline to stdout // Ln writes a basic formatted string with a newline to stdout
func Ln(format string, a ...interface{}) { func Ln(format string, a ...interface{}) {
String(format+"\n", a...) Stringf(format+"\n", a...)
} }
// ErrT writes a stylized and templated error message to stderr // ErrT writes a stylized and templated error message to stderr
@ -222,8 +253,31 @@ func ErrT(st style.Enum, format string, a ...V) {
Err(errStyled) Err(errStyled)
} }
// Err writes a basic formatted string to stderr // Err writes a basic string to stderr
func Err(format string, a ...interface{}) { func Err(s string) {
if JSON {
register.PrintError(s)
klog.Warning(s)
return
}
register.RecordError(s)
if errFile == nil {
klog.Errorf("[unset errFile]: %s", s)
return
}
klog.Warning(s)
// if spin is active from a previous step, it will stop spinner displaying
if spin.Active() {
spin.Stop()
}
Output(errFile, s)
}
// Errf writes a basic formatted string to stderr
func Errf(format string, a ...interface{}) {
if JSON { if JSON {
register.PrintError(format) register.PrintError(format)
klog.Warningf(format, a...) klog.Warningf(format, a...)
@ -242,12 +296,12 @@ func Err(format string, a ...interface{}) {
if spin.Active() { if spin.Active() {
spin.Stop() spin.Stop()
} }
Output(errFile, format, a...) Outputf(errFile, format, a...)
} }
// ErrLn writes a basic formatted string with a newline to stderr // ErrLn writes a basic formatted string with a newline to stderr
func ErrLn(format string, a ...interface{}) { func ErrLn(format string, a ...interface{}) {
Err(format+"\n", a...) Errf(format+"\n", a...)
} }
// SuccessT is a shortcut for writing a templated success message to stdout // SuccessT is a shortcut for writing a templated success message to stdout
@ -361,7 +415,7 @@ func LogEntries(msg string, err error, entries map[string][]string) {
// displayError prints the error and displays the standard minikube error messaging // displayError prints the error and displays the standard minikube error messaging
func displayError(msg string, err error) { func displayError(msg string, err error) {
klog.Warningf(fmt.Sprintf("%s: %v", msg, err)) klog.Warningf("%s: %v", msg, err)
if JSON { if JSON {
ErrT(style.Fatal, "{{.msg}}: {{.err}}", V{"msg": translate.T(msg), "err": err}) ErrT(style.Fatal, "{{.msg}}: {{.err}}", V{"msg": translate.T(msg), "err": err})
return return
@ -452,12 +506,6 @@ func applyTmpl(format string, a ...V) string {
// Return quotes back to normal // Return quotes back to normal
out = html.UnescapeString(out) out = html.UnescapeString(out)
// escape any outstanding '%' signs so that they don't get interpreted
// as a formatting directive down the line
out = strings.ReplaceAll(out, "%", "%%")
// avoid doubling up in case this function is called multiple times
out = strings.ReplaceAll(out, "%%%%", "%%")
return out return out
} }

View File

@ -33,7 +33,7 @@ import (
"k8s.io/minikube/pkg/minikube/translate" "k8s.io/minikube/pkg/minikube/translate"
) )
func TestOutT(t *testing.T) { func TestStep(t *testing.T) {
// Set the system locale to Arabic and define a dummy translation file. // Set the system locale to Arabic and define a dummy translation file.
translate.SetPreferredLanguage(language.Arabic) translate.SetPreferredLanguage(language.Arabic)
@ -70,14 +70,14 @@ func TestOutT(t *testing.T) {
want = tc.want want = tc.want
} }
if got != want { if got != want {
t.Errorf("OutStyle() = %q (%d runes), want %q (%d runes)", got, len(got), want, len(want)) t.Errorf("Step() = %q (%d runes), want %q (%d runes)", got, len(got), want, len(want))
} }
}) })
} }
} }
} }
func TestOut(t *testing.T) { func TestString(t *testing.T) {
t.Setenv(OverrideEnv, "") t.Setenv(OverrideEnv, "")
testCases := []struct { testCases := []struct {
@ -97,11 +97,11 @@ func TestOut(t *testing.T) {
if tc.arg == nil { if tc.arg == nil {
String(tc.format) String(tc.format)
} else { } else {
String(tc.format, tc.arg) Stringf(tc.format, tc.arg)
} }
got := f.String() got := f.String()
if got != tc.want { if got != tc.want {
t.Errorf("Out(%s, %s) = %q, want %q", tc.format, tc.arg, got, tc.want) t.Errorf("String(%s, %s) = %q, want %q", tc.format, tc.arg, got, tc.want)
} }
}) })
} }
@ -111,13 +111,27 @@ func TestErr(t *testing.T) {
t.Setenv(OverrideEnv, "0") t.Setenv(OverrideEnv, "0")
f := tests.NewFakeFile() f := tests.NewFakeFile()
SetErrFile(f) SetErrFile(f)
Err("xyz123 %s\n", "%s%%%d") Err("xyz123\n")
Ln("unrelated message")
got := f.String()
want := "xyz123\n"
if got != want {
t.Errorf("Err() = %q, want %q", got, want)
}
}
func TestErrf(t *testing.T) {
t.Setenv(OverrideEnv, "0")
f := tests.NewFakeFile()
SetErrFile(f)
Errf("xyz123 %s\n", "%s%%%d")
Ln("unrelated message") Ln("unrelated message")
got := f.String() got := f.String()
want := "xyz123 %s%%%d\n" want := "xyz123 %s%%%d\n"
if got != want { if got != want {
t.Errorf("Err() = %q, want %q", got, want) t.Errorf("Errf() = %q, want %q", got, want)
} }
} }

View File

@ -17,7 +17,7 @@ limitations under the License.
package reason package reason
import ( import (
"fmt" "errors"
"testing" "testing"
) )
@ -68,7 +68,7 @@ VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component MachineWrap,
} }
for _, tc := range tests { for _, tc := range tests {
t.Run(tc.want, func(t *testing.T) { t.Run(tc.want, func(t *testing.T) {
got := MatchKnownIssue(Kind{}, fmt.Errorf(tc.err), tc.os) got := MatchKnownIssue(Kind{}, errors.New(tc.err), tc.os)
if got == nil { if got == nil {
if tc.want != "" { if tc.want != "" {
t.Errorf("FromError(%q)=nil, want %s", tc.err, tc.want) t.Errorf("FromError(%q)=nil, want %s", tc.err, tc.want)

View File

@ -230,13 +230,13 @@ func TestGetStoragev1(t *testing.T) {
} }
configFile, err := os.CreateTemp("/tmp", "") configFile, err := os.CreateTemp("/tmp", "")
if err != nil { if err != nil {
t.Fatalf(err.Error()) t.Fatal(err.Error())
} }
defer os.Remove(configFile.Name()) defer os.Remove(configFile.Name())
for _, test := range tests { for _, test := range tests {
t.Run(test.description, func(t *testing.T) { t.Run(test.description, func(t *testing.T) {
if err := setK8SConfig(t, test.config, configFile.Name()); err != nil { if err := setK8SConfig(t, test.config, configFile.Name()); err != nil {
t.Fatalf(err.Error()) t.Fatal(err.Error())
} }
// context name is hardcoded by mockK8sConfig // context name is hardcoded by mockK8sConfig

View File

@ -17,7 +17,7 @@ limitations under the License.
package tests package tests
import ( import (
"fmt" "errors"
"github.com/docker/machine/libmachine/drivers" "github.com/docker/machine/libmachine/drivers"
) )
@ -49,7 +49,7 @@ func (m MockHost) RunSSHCommand(cmd string) (string, error) {
return output, nil return output, nil
} }
if m.Error != "" { if m.Error != "" {
return "", fmt.Errorf(m.Error) return "", errors.New(m.Error)
} }
return "", nil return "", nil
} }

View File

@ -100,7 +100,7 @@ func (t *tunnel) cleanup() *Status {
err := t.router.Cleanup(t.status.TunnelID.Route) err := t.router.Cleanup(t.status.TunnelID.Route)
if err != nil { if err != nil {
t.status.RouteError = errors.Errorf("error cleaning up route: %v", err) t.status.RouteError = errors.Errorf("error cleaning up route: %v", err)
klog.V(3).Infof(t.status.RouteError.Error()) klog.V(3).Info(t.status.RouteError.Error())
} else { } else {
err = t.registry.Remove(t.status.TunnelID.Route) err = t.registry.Remove(t.status.TunnelID.Route)
if err != nil { if err != nil {
@ -211,7 +211,7 @@ func setupBridge(t *tunnel) {
command = exec.Command("sudo", "ifconfig", "bridge100", "deletem", member) command = exec.Command("sudo", "ifconfig", "bridge100", "deletem", member)
klog.Infof("About to run command: %s\n", command.Args) klog.Infof("About to run command: %s\n", command.Args)
response, err = command.CombinedOutput() response, err = command.CombinedOutput()
klog.Infof(string(response)) klog.Info(string(response))
if err != nil { if err != nil {
t.status.RouteError = fmt.Errorf("couldn't remove member %s: %s", member, err) t.status.RouteError = fmt.Errorf("couldn't remove member %s: %s", member, err)
return return
@ -220,7 +220,7 @@ func setupBridge(t *tunnel) {
command = exec.Command("sudo", "ifconfig", "bridge100", "addm", member) command = exec.Command("sudo", "ifconfig", "bridge100", "addm", member)
klog.Infof("About to run command: %s\n", command.Args) klog.Infof("About to run command: %s\n", command.Args)
response, err = command.CombinedOutput() response, err = command.CombinedOutput()
klog.Infof(string(response)) klog.Info(string(response))
if err != nil { if err != nil {
t.status.RouteError = fmt.Errorf("couldn't re-add member %s: %s", member, err) t.status.RouteError = fmt.Errorf("couldn't re-add member %s: %s", member, err)
return return

View File

@ -140,17 +140,17 @@ func validateHADeployApp(ctx context.Context, t *testing.T, profile string) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "kubectl", "-p", profile, "--", "get", "pods", "-o", "jsonpath='{.items[*].status.podIP}'")) rr, err := Run(t, exec.CommandContext(ctx, Target(), "kubectl", "-p", profile, "--", "get", "pods", "-o", "jsonpath='{.items[*].status.podIP}'"))
if err != nil { if err != nil {
err := fmt.Errorf("failed to retrieve Pod IPs (may be temporary): %v", err) err := fmt.Errorf("failed to retrieve Pod IPs (may be temporary): %v", err)
t.Logf(err.Error()) t.Log(err.Error())
return err return err
} }
podIPs := strings.Split(strings.Trim(rr.Stdout.String(), "'"), " ") podIPs := strings.Split(strings.Trim(rr.Stdout.String(), "'"), " ")
if len(podIPs) != 3 { if len(podIPs) != 3 {
err := fmt.Errorf("expected 3 Pod IPs but got %d (may be temporary), output: %q", len(podIPs), rr.Output()) err := fmt.Errorf("expected 3 Pod IPs but got %d (may be temporary), output: %q", len(podIPs), rr.Output())
t.Logf(err.Error()) t.Log(err.Error())
return err return err
} else if podIPs[0] == podIPs[1] || podIPs[0] == podIPs[2] || podIPs[1] == podIPs[2] { } else if podIPs[0] == podIPs[1] || podIPs[0] == podIPs[2] || podIPs[1] == podIPs[2] {
err := fmt.Errorf("expected 3 different pod IPs but got %s and %s (may be temporary), output: %q", podIPs[0], podIPs[1], rr.Output()) err := fmt.Errorf("expected 3 different pod IPs but got %s and %s (may be temporary), output: %q", podIPs[0], podIPs[1], rr.Output())
t.Logf(err.Error()) t.Log(err.Error())
return err return err
} }
return nil return nil
@ -419,7 +419,7 @@ func validateHARestartSecondaryNode(ctx context.Context, t *testing.T, profile s
// start stopped node(s) back up // start stopped node(s) back up
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "start", SecondNodeName, "-v=7", "--alsologtostderr")) rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "start", SecondNodeName, "-v=7", "--alsologtostderr"))
if err != nil { if err != nil {
t.Logf(rr.Stderr.String()) t.Log(rr.Stderr.String())
t.Errorf("secondary control-plane node start returned an error. args %q: %v", rr.Command(), err) t.Errorf("secondary control-plane node start returned an error. args %q: %v", rr.Command(), err)
} }

View File

@ -281,7 +281,7 @@ func validateStartNodeAfterStop(ctx context.Context, t *testing.T, profile strin
// Start the node back up // Start the node back up
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "start", ThirdNodeName, "-v=7", "--alsologtostderr")) rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "start", ThirdNodeName, "-v=7", "--alsologtostderr"))
if err != nil { if err != nil {
t.Logf(rr.Stderr.String()) t.Log(rr.Stderr.String())
t.Errorf("node start returned an error. args %q: %v", rr.Command(), err) t.Errorf("node start returned an error. args %q: %v", rr.Command(), err)
} }
@ -505,17 +505,17 @@ func validateDeployAppToMultiNode(ctx context.Context, t *testing.T, profile str
rr, err := Run(t, exec.CommandContext(ctx, Target(), "kubectl", "-p", profile, "--", "get", "pods", "-o", "jsonpath='{.items[*].status.podIP}'")) rr, err := Run(t, exec.CommandContext(ctx, Target(), "kubectl", "-p", profile, "--", "get", "pods", "-o", "jsonpath='{.items[*].status.podIP}'"))
if err != nil { if err != nil {
err := fmt.Errorf("failed to retrieve Pod IPs (may be temporary): %v", err) err := fmt.Errorf("failed to retrieve Pod IPs (may be temporary): %v", err)
t.Logf(err.Error()) t.Log(err.Error())
return err return err
} }
podIPs := strings.Split(strings.Trim(rr.Stdout.String(), "'"), " ") podIPs := strings.Split(strings.Trim(rr.Stdout.String(), "'"), " ")
if len(podIPs) != 2 { if len(podIPs) != 2 {
err := fmt.Errorf("expected 2 Pod IPs but got %d (may be temporary), output: %q", len(podIPs), rr.Output()) err := fmt.Errorf("expected 2 Pod IPs but got %d (may be temporary), output: %q", len(podIPs), rr.Output())
t.Logf(err.Error()) t.Log(err.Error())
return err return err
} else if podIPs[0] == podIPs[1] { } else if podIPs[0] == podIPs[1] {
err := fmt.Errorf("expected 2 different pod IPs but got %s and %s (may be temporary), output: %q", podIPs[0], podIPs[1], rr.Output()) err := fmt.Errorf("expected 2 different pod IPs but got %s and %s (may be temporary), output: %q", podIPs[0], podIPs[1], rr.Output())
t.Logf(err.Error()) t.Log(err.Error())
return err return err
} }
return nil return nil