diff --git a/.golangci.yml b/.golangci.yml index 156dd0509..a9b13c35f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -30,6 +30,7 @@ linters: - thelper - unused - usestdlibvars + - usetesting exclusions: generated: lax diff --git a/internal/test/ensure/ensure.go b/internal/test/ensure/ensure.go index c131e6da5..a72f48c2d 100644 --- a/internal/test/ensure/ensure.go +++ b/internal/test/ensure/ensure.go @@ -29,12 +29,12 @@ import ( func HelmHome(t *testing.T) { t.Helper() base := t.TempDir() - os.Setenv(xdg.CacheHomeEnvVar, base) - os.Setenv(xdg.ConfigHomeEnvVar, base) - os.Setenv(xdg.DataHomeEnvVar, base) - os.Setenv(helmpath.CacheHomeEnvVar, "") - os.Setenv(helmpath.ConfigHomeEnvVar, "") - os.Setenv(helmpath.DataHomeEnvVar, "") + t.Setenv(xdg.CacheHomeEnvVar, base) + t.Setenv(xdg.ConfigHomeEnvVar, base) + t.Setenv(xdg.DataHomeEnvVar, base) + t.Setenv(helmpath.CacheHomeEnvVar, "") + t.Setenv(helmpath.ConfigHomeEnvVar, "") + t.Setenv(helmpath.DataHomeEnvVar, "") } // TempFile ensures a temp file for unit testing purposes. @@ -49,7 +49,7 @@ func TempFile(t *testing.T, name string, data []byte) string { t.Helper() path := t.TempDir() filename := filepath.Join(path, name) - if err := os.WriteFile(filename, data, 0755); err != nil { + if err := os.WriteFile(filename, data, 0o755); err != nil { t.Fatal(err) } return path diff --git a/pkg/action/install_test.go b/pkg/action/install_test.go index dabd57b22..7a88d82b5 100644 --- a/pkg/action/install_test.go +++ b/pkg/action/install_test.go @@ -131,7 +131,7 @@ func TestInstallRelease(t *testing.T) { instAction := installAction(t) vals := map[string]interface{}{} - ctx, done := context.WithCancel(context.Background()) + ctx, done := context.WithCancel(t.Context()) res, err := instAction.RunWithContext(ctx, buildChart(), vals) if err != nil { t.Fatalf("Failed install: %s", err) @@ -557,7 +557,7 @@ func TestInstallRelease_Wait_Interrupted(t *testing.T) { instAction.WaitStrategy = kube.StatusWatcherStrategy vals := map[string]interface{}{} - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) time.AfterFunc(time.Second, cancel) goroutines := runtime.NumGoroutine() @@ -641,7 +641,7 @@ func TestInstallRelease_Atomic_Interrupted(t *testing.T) { instAction.Atomic = true vals := map[string]interface{}{} - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) time.AfterFunc(time.Second, cancel) goroutines := runtime.NumGoroutine() diff --git a/pkg/action/upgrade_test.go b/pkg/action/upgrade_test.go index 4476bc44d..e20955560 100644 --- a/pkg/action/upgrade_test.go +++ b/pkg/action/upgrade_test.go @@ -57,7 +57,7 @@ func TestUpgradeRelease_Success(t *testing.T) { upAction.WaitStrategy = kube.StatusWatcherStrategy vals := map[string]interface{}{} - ctx, done := context.WithCancel(context.Background()) + ctx, done := context.WithCancel(t.Context()) res, err := upAction.RunWithContext(ctx, rel.Name, buildChart(), vals) done() req.NoError(err) @@ -384,7 +384,6 @@ func TestUpgradeRelease_Pending(t *testing.T) { } func TestUpgradeRelease_Interrupted_Wait(t *testing.T) { - is := assert.New(t) req := require.New(t) @@ -400,8 +399,7 @@ func TestUpgradeRelease_Interrupted_Wait(t *testing.T) { upAction.WaitStrategy = kube.StatusWatcherStrategy vals := map[string]interface{}{} - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) + ctx, cancel := context.WithCancel(t.Context()) time.AfterFunc(time.Second, cancel) res, err := upAction.RunWithContext(ctx, rel.Name, buildChart(), vals) @@ -409,11 +407,9 @@ func TestUpgradeRelease_Interrupted_Wait(t *testing.T) { req.Error(err) is.Contains(res.Info.Description, "Upgrade \"interrupted-release\" failed: context canceled") is.Equal(res.Info.Status, release.StatusFailed) - } func TestUpgradeRelease_Interrupted_Atomic(t *testing.T) { - is := assert.New(t) req := require.New(t) @@ -429,8 +425,7 @@ func TestUpgradeRelease_Interrupted_Atomic(t *testing.T) { upAction.Atomic = true vals := map[string]interface{}{} - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) + ctx, cancel := context.WithCancel(t.Context()) time.AfterFunc(time.Second, cancel) res, err := upAction.RunWithContext(ctx, rel.Name, buildChart(), vals) @@ -446,7 +441,7 @@ func TestUpgradeRelease_Interrupted_Atomic(t *testing.T) { } func TestMergeCustomLabels(t *testing.T) { - var tests = [][3]map[string]string{ + tests := [][3]map[string]string{ {nil, nil, map[string]string{}}, {map[string]string{}, map[string]string{}, map[string]string{}}, {map[string]string{"k1": "v1", "k2": "v2"}, nil, map[string]string{"k1": "v1", "k2": "v2"}}, @@ -551,7 +546,7 @@ func TestUpgradeRelease_DryRun(t *testing.T) { upAction.DryRun = true vals := map[string]interface{}{} - ctx, done := context.WithCancel(context.Background()) + ctx, done := context.WithCancel(t.Context()) res, err := upAction.RunWithContext(ctx, rel.Name, buildChart(withSampleSecret()), vals) done() req.NoError(err) @@ -567,7 +562,7 @@ func TestUpgradeRelease_DryRun(t *testing.T) { upAction.HideSecret = true vals = map[string]interface{}{} - ctx, done = context.WithCancel(context.Background()) + ctx, done = context.WithCancel(t.Context()) res, err = upAction.RunWithContext(ctx, rel.Name, buildChart(withSampleSecret()), vals) done() req.NoError(err) @@ -583,7 +578,7 @@ func TestUpgradeRelease_DryRun(t *testing.T) { upAction.DryRun = false vals = map[string]interface{}{} - ctx, done = context.WithCancel(context.Background()) + ctx, done = context.WithCancel(t.Context()) _, err = upAction.RunWithContext(ctx, rel.Name, buildChart(withSampleSecret()), vals) done() req.Error(err) diff --git a/pkg/cli/environment_test.go b/pkg/cli/environment_test.go index 8a3b87936..52326eeff 100644 --- a/pkg/cli/environment_test.go +++ b/pkg/cli/environment_test.go @@ -38,7 +38,6 @@ func TestSetNamespace(t *testing.T) { if settings.namespace != "testns" { t.Errorf("Expected namespace testns, got %s", settings.namespace) } - } func TestEnvSettings(t *testing.T) { @@ -126,7 +125,7 @@ func TestEnvSettings(t *testing.T) { defer resetEnv()() for k, v := range tt.envvars { - os.Setenv(k, v) + t.Setenv(k, v) } flags := pflag.NewFlagSet("testing", pflag.ContinueOnError) @@ -233,10 +232,7 @@ func TestEnvOrBool(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.env != "" { - t.Cleanup(func() { - os.Unsetenv(tt.env) - }) - os.Setenv(tt.env, tt.val) + t.Setenv(tt.env, tt.val) } actual := envBoolOr(tt.env, tt.def) if actual != tt.expected { diff --git a/pkg/cmd/create_test.go b/pkg/cmd/create_test.go index 26eabbfc3..103cd3bc0 100644 --- a/pkg/cmd/create_test.go +++ b/pkg/cmd/create_test.go @@ -33,7 +33,7 @@ func TestCreateCmd(t *testing.T) { ensure.HelmHome(t) cname := "testchart" dir := t.TempDir() - defer testChdir(t, dir)() + defer t.Chdir(dir) // Run a create if _, _, err := executeActionCommand("create " + cname); err != nil { @@ -64,19 +64,19 @@ func TestCreateStarterCmd(t *testing.T) { ensure.HelmHome(t) cname := "testchart" defer resetEnv()() - os.MkdirAll(helmpath.CachePath(), 0755) - defer testChdir(t, helmpath.CachePath())() + os.MkdirAll(helmpath.CachePath(), 0o755) + defer t.Chdir(helmpath.CachePath()) // Create a starter. starterchart := helmpath.DataPath("starters") - os.MkdirAll(starterchart, 0755) + os.MkdirAll(starterchart, 0o755) if dest, err := chartutil.Create("starterchart", starterchart); err != nil { t.Fatalf("Could not create chart: %s", err) } else { t.Logf("Created %s", dest) } tplpath := filepath.Join(starterchart, "starterchart", "templates", "foo.tpl") - if err := os.WriteFile(tplpath, []byte("test"), 0644); err != nil { + if err := os.WriteFile(tplpath, []byte("test"), 0o644); err != nil { t.Fatalf("Could not write template: %s", err) } @@ -122,7 +122,6 @@ func TestCreateStarterCmd(t *testing.T) { if !found { t.Error("Did not find foo.tpl") } - } func TestCreateStarterAbsoluteCmd(t *testing.T) { @@ -132,19 +131,19 @@ func TestCreateStarterAbsoluteCmd(t *testing.T) { // Create a starter. starterchart := helmpath.DataPath("starters") - os.MkdirAll(starterchart, 0755) + os.MkdirAll(starterchart, 0o755) if dest, err := chartutil.Create("starterchart", starterchart); err != nil { t.Fatalf("Could not create chart: %s", err) } else { t.Logf("Created %s", dest) } tplpath := filepath.Join(starterchart, "starterchart", "templates", "foo.tpl") - if err := os.WriteFile(tplpath, []byte("test"), 0644); err != nil { + if err := os.WriteFile(tplpath, []byte("test"), 0o644); err != nil { t.Fatalf("Could not write template: %s", err) } - os.MkdirAll(helmpath.CachePath(), 0755) - defer testChdir(t, helmpath.CachePath())() + os.MkdirAll(helmpath.CachePath(), 0o755) + defer t.Chdir(helmpath.CachePath()) starterChartPath := filepath.Join(starterchart, "starterchart") diff --git a/pkg/cmd/helpers_test.go b/pkg/cmd/helpers_test.go index b48f802b5..5d71fecad 100644 --- a/pkg/cmd/helpers_test.go +++ b/pkg/cmd/helpers_test.go @@ -149,15 +149,3 @@ func resetEnv() func() { settings = cli.New() } } - -func testChdir(t *testing.T, dir string) func() { - t.Helper() - old, err := os.Getwd() - if err != nil { - t.Fatal(err) - } - if err := os.Chdir(dir); err != nil { - t.Fatal(err) - } - return func() { os.Chdir(old) } -} diff --git a/pkg/cmd/package_test.go b/pkg/cmd/package_test.go index 54358fc12..b17684aa6 100644 --- a/pkg/cmd/package_test.go +++ b/pkg/cmd/package_test.go @@ -111,9 +111,9 @@ func TestPackage(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cachePath := t.TempDir() - defer testChdir(t, cachePath)() + defer t.Chdir(cachePath) - if err := os.MkdirAll("toot", 0777); err != nil { + if err := os.MkdirAll("toot", 0o777); err != nil { t.Fatal(err) } diff --git a/pkg/cmd/plugin_test.go b/pkg/cmd/plugin_test.go index bc0f7de48..74f7a276a 100644 --- a/pkg/cmd/plugin_test.go +++ b/pkg/cmd/plugin_test.go @@ -79,7 +79,6 @@ func TestManuallyProcessArgs(t *testing.T) { t.Errorf("expected unknown flag %d to be %q, got %q", i, expectUnknown[i], k) } } - } func TestLoadPlugins(t *testing.T) { @@ -327,7 +326,6 @@ func checkCommand(t *testing.T, plugins []*cobra.Command, tests []staticCompleti } func TestPluginDynamicCompletion(t *testing.T) { - tests := []cmdTestCase{{ name: "completion for plugin", cmd: "__complete args ''", @@ -364,7 +362,7 @@ func TestLoadPlugins_HelmNoPlugins(t *testing.T) { settings.PluginsDirectory = "testdata/helmhome/helm/plugins" settings.RepositoryConfig = "testdata/helmhome/helm/repository" - os.Setenv("HELM_NO_PLUGINS", "1") + t.Setenv("HELM_NO_PLUGINS", "1") out := bytes.NewBuffer(nil) cmd := &cobra.Command{} @@ -377,7 +375,6 @@ func TestLoadPlugins_HelmNoPlugins(t *testing.T) { } func TestPluginCmdsCompletion(t *testing.T) { - tests := []cmdTestCase{{ name: "completion for plugin update", cmd: "__complete plugin update ''", diff --git a/pkg/cmd/repo_add_test.go b/pkg/cmd/repo_add_test.go index cfa610611..aa6c4eaad 100644 --- a/pkg/cmd/repo_add_test.go +++ b/pkg/cmd/repo_add_test.go @@ -50,7 +50,7 @@ func TestRepoAddCmd(t *testing.T) { defer srv2.Stop() tmpdir := filepath.Join(t.TempDir(), "path-component.yaml/data") - if err := os.MkdirAll(tmpdir, 0777); err != nil { + if err := os.MkdirAll(tmpdir, 0o777); err != nil { t.Fatal(err) } repoFile := filepath.Join(tmpdir, "repositories.yaml") @@ -99,7 +99,7 @@ func TestRepoAdd(t *testing.T) { forceUpdate: false, repoFile: repoFile, } - os.Setenv(xdg.CacheHomeEnvVar, rootDir) + t.Setenv(xdg.CacheHomeEnvVar, rootDir) if err := o.run(io.Discard); err != nil { t.Error(err) @@ -153,7 +153,7 @@ func TestRepoAddCheckLegalName(t *testing.T) { forceUpdate: false, repoFile: repoFile, } - os.Setenv(xdg.CacheHomeEnvVar, rootDir) + t.Setenv(xdg.CacheHomeEnvVar, rootDir) wantErrorMsg := fmt.Sprintf("repository name (%s) contains '/', please specify a different name without '/'", testRepoName) diff --git a/pkg/cmd/root_test.go b/pkg/cmd/root_test.go index 9521a5aa2..84e3d9ed2 100644 --- a/pkg/cmd/root_test.go +++ b/pkg/cmd/root_test.go @@ -80,7 +80,7 @@ func TestRootCmd(t *testing.T) { ensure.HelmHome(t) for k, v := range tt.envvars { - os.Setenv(k, v) + t.Setenv(k, v) } if _, _, err := executeActionCommand(tt.args); err != nil { diff --git a/pkg/gates/gates_test.go b/pkg/gates/gates_test.go index 6bdd17ed6..4d77199e6 100644 --- a/pkg/gates/gates_test.go +++ b/pkg/gates/gates_test.go @@ -23,14 +23,13 @@ import ( const name string = "HELM_EXPERIMENTAL_FEATURE" func TestIsEnabled(t *testing.T) { - os.Unsetenv(name) g := Gate(name) if g.IsEnabled() { t.Errorf("feature gate shows as available, but the environment variable %s was not set", name) } - os.Setenv(name, "1") + t.Setenv(name, "1") if !g.IsEnabled() { t.Errorf("feature gate shows as disabled, but the environment variable %s was set", name) diff --git a/pkg/helmpath/home_unix_test.go b/pkg/helmpath/home_unix_test.go index 6e4189bc9..a64c9bcd6 100644 --- a/pkg/helmpath/home_unix_test.go +++ b/pkg/helmpath/home_unix_test.go @@ -16,7 +16,6 @@ package helmpath import ( - "os" "runtime" "testing" @@ -24,9 +23,9 @@ import ( ) func TestHelmHome(t *testing.T) { - os.Setenv(xdg.CacheHomeEnvVar, "/cache") - os.Setenv(xdg.ConfigHomeEnvVar, "/config") - os.Setenv(xdg.DataHomeEnvVar, "/data") + t.Setenv(xdg.CacheHomeEnvVar, "/cache") + t.Setenv(xdg.ConfigHomeEnvVar, "/config") + t.Setenv(xdg.DataHomeEnvVar, "/data") isEq := func(t *testing.T, got, expected string) { t.Helper() if expected != got { @@ -40,7 +39,7 @@ func TestHelmHome(t *testing.T) { isEq(t, DataPath(), "/data/helm") // test to see if lazy-loading environment variables at runtime works - os.Setenv(xdg.CacheHomeEnvVar, "/cache2") + t.Setenv(xdg.CacheHomeEnvVar, "/cache2") isEq(t, CachePath(), "/cache2/helm") } diff --git a/pkg/helmpath/lazypath_unix_test.go b/pkg/helmpath/lazypath_unix_test.go index 534735d10..4b0f2429b 100644 --- a/pkg/helmpath/lazypath_unix_test.go +++ b/pkg/helmpath/lazypath_unix_test.go @@ -16,7 +16,6 @@ package helmpath import ( - "os" "path/filepath" "testing" @@ -32,15 +31,13 @@ const ( ) func TestDataPath(t *testing.T) { - os.Unsetenv(xdg.DataHomeEnvVar) - expected := filepath.Join(homedir.HomeDir(), ".local", "share", appName, testFile) if lazy.dataPath(testFile) != expected { t.Errorf("expected '%s', got '%s'", expected, lazy.dataPath(testFile)) } - os.Setenv(xdg.DataHomeEnvVar, "/tmp") + t.Setenv(xdg.DataHomeEnvVar, "/tmp") expected = filepath.Join("/tmp", appName, testFile) @@ -50,15 +47,13 @@ func TestDataPath(t *testing.T) { } func TestConfigPath(t *testing.T) { - os.Unsetenv(xdg.ConfigHomeEnvVar) - expected := filepath.Join(homedir.HomeDir(), ".config", appName, testFile) if lazy.configPath(testFile) != expected { t.Errorf("expected '%s', got '%s'", expected, lazy.configPath(testFile)) } - os.Setenv(xdg.ConfigHomeEnvVar, "/tmp") + t.Setenv(xdg.ConfigHomeEnvVar, "/tmp") expected = filepath.Join("/tmp", appName, testFile) @@ -68,15 +63,13 @@ func TestConfigPath(t *testing.T) { } func TestCachePath(t *testing.T) { - os.Unsetenv(xdg.CacheHomeEnvVar) - expected := filepath.Join(homedir.HomeDir(), ".cache", appName, testFile) if lazy.cachePath(testFile) != expected { t.Errorf("expected '%s', got '%s'", expected, lazy.cachePath(testFile)) } - os.Setenv(xdg.CacheHomeEnvVar, "/tmp") + t.Setenv(xdg.CacheHomeEnvVar, "/tmp") expected = filepath.Join("/tmp", appName, testFile) diff --git a/pkg/kube/ready_test.go b/pkg/kube/ready_test.go index 9d1dfd272..db0d02cbe 100644 --- a/pkg/kube/ready_test.go +++ b/pkg/kube/ready_test.go @@ -60,7 +60,7 @@ func Test_ReadyChecker_IsReady_Pod(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.Pod{}, Name: "foo", Namespace: defaultNamespace}, }, pod: newPodWithCondition("foo", corev1.ConditionTrue), @@ -75,7 +75,7 @@ func Test_ReadyChecker_IsReady_Pod(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.Pod{}, Name: "foo", Namespace: defaultNamespace}, }, pod: newPodWithCondition("bar", corev1.ConditionTrue), @@ -90,7 +90,7 @@ func Test_ReadyChecker_IsReady_Pod(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.CoreV1().Pods(defaultNamespace).Create(context.TODO(), tt.pod, metav1.CreateOptions{}); err != nil { + if _, err := c.client.CoreV1().Pods(defaultNamespace).Create(t.Context(), tt.pod, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create Pod error: %v", err) return } @@ -132,7 +132,7 @@ func Test_ReadyChecker_IsReady_Job(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &batchv1.Job{}, Name: "foo", Namespace: defaultNamespace}, }, job: newJob("bar", 1, intToInt32(1), 1, 0), @@ -147,7 +147,7 @@ func Test_ReadyChecker_IsReady_Job(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &batchv1.Job{}, Name: "foo", Namespace: defaultNamespace}, }, job: newJob("foo", 1, intToInt32(1), 1, 0), @@ -162,7 +162,7 @@ func Test_ReadyChecker_IsReady_Job(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.BatchV1().Jobs(defaultNamespace).Create(context.TODO(), tt.job, metav1.CreateOptions{}); err != nil { + if _, err := c.client.BatchV1().Jobs(defaultNamespace).Create(t.Context(), tt.job, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create Job error: %v", err) return } @@ -204,7 +204,7 @@ func Test_ReadyChecker_IsReady_Deployment(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.Deployment{}, Name: "foo", Namespace: defaultNamespace}, }, replicaSet: newReplicaSet("foo", 0, 0, true), @@ -220,7 +220,7 @@ func Test_ReadyChecker_IsReady_Deployment(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.Deployment{}, Name: "foo", Namespace: defaultNamespace}, }, replicaSet: newReplicaSet("foo", 0, 0, true), @@ -236,11 +236,11 @@ func Test_ReadyChecker_IsReady_Deployment(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.AppsV1().Deployments(defaultNamespace).Create(context.TODO(), tt.deployment, metav1.CreateOptions{}); err != nil { + if _, err := c.client.AppsV1().Deployments(defaultNamespace).Create(t.Context(), tt.deployment, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create Deployment error: %v", err) return } - if _, err := c.client.AppsV1().ReplicaSets(defaultNamespace).Create(context.TODO(), tt.replicaSet, metav1.CreateOptions{}); err != nil { + if _, err := c.client.AppsV1().ReplicaSets(defaultNamespace).Create(t.Context(), tt.replicaSet, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create ReplicaSet error: %v", err) return } @@ -281,7 +281,7 @@ func Test_ReadyChecker_IsReady_PersistentVolumeClaim(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.PersistentVolumeClaim{}, Name: "foo", Namespace: defaultNamespace}, }, pvc: newPersistentVolumeClaim("foo", corev1.ClaimPending), @@ -296,7 +296,7 @@ func Test_ReadyChecker_IsReady_PersistentVolumeClaim(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.PersistentVolumeClaim{}, Name: "foo", Namespace: defaultNamespace}, }, pvc: newPersistentVolumeClaim("bar", corev1.ClaimPending), @@ -311,7 +311,7 @@ func Test_ReadyChecker_IsReady_PersistentVolumeClaim(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.CoreV1().PersistentVolumeClaims(defaultNamespace).Create(context.TODO(), tt.pvc, metav1.CreateOptions{}); err != nil { + if _, err := c.client.CoreV1().PersistentVolumeClaims(defaultNamespace).Create(t.Context(), tt.pvc, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create PersistentVolumeClaim error: %v", err) return } @@ -352,7 +352,7 @@ func Test_ReadyChecker_IsReady_Service(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.Service{}, Name: "foo", Namespace: defaultNamespace}, }, svc: newService("foo", corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, ClusterIP: ""}), @@ -367,7 +367,7 @@ func Test_ReadyChecker_IsReady_Service(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.Service{}, Name: "foo", Namespace: defaultNamespace}, }, svc: newService("bar", corev1.ServiceSpec{Type: corev1.ServiceTypeExternalName, ClusterIP: ""}), @@ -382,7 +382,7 @@ func Test_ReadyChecker_IsReady_Service(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.CoreV1().Services(defaultNamespace).Create(context.TODO(), tt.svc, metav1.CreateOptions{}); err != nil { + if _, err := c.client.CoreV1().Services(defaultNamespace).Create(t.Context(), tt.svc, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create Service error: %v", err) return } @@ -423,7 +423,7 @@ func Test_ReadyChecker_IsReady_DaemonSet(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.DaemonSet{}, Name: "foo", Namespace: defaultNamespace}, }, ds: newDaemonSet("foo", 0, 0, 1, 0, true), @@ -438,7 +438,7 @@ func Test_ReadyChecker_IsReady_DaemonSet(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.DaemonSet{}, Name: "foo", Namespace: defaultNamespace}, }, ds: newDaemonSet("bar", 0, 1, 1, 1, true), @@ -453,7 +453,7 @@ func Test_ReadyChecker_IsReady_DaemonSet(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.AppsV1().DaemonSets(defaultNamespace).Create(context.TODO(), tt.ds, metav1.CreateOptions{}); err != nil { + if _, err := c.client.AppsV1().DaemonSets(defaultNamespace).Create(t.Context(), tt.ds, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create DaemonSet error: %v", err) return } @@ -494,7 +494,7 @@ func Test_ReadyChecker_IsReady_StatefulSet(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.StatefulSet{}, Name: "foo", Namespace: defaultNamespace}, }, ss: newStatefulSet("foo", 1, 0, 0, 1, true), @@ -509,7 +509,7 @@ func Test_ReadyChecker_IsReady_StatefulSet(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.StatefulSet{}, Name: "foo", Namespace: defaultNamespace}, }, ss: newStatefulSet("bar", 1, 0, 1, 1, true), @@ -524,7 +524,7 @@ func Test_ReadyChecker_IsReady_StatefulSet(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.AppsV1().StatefulSets(defaultNamespace).Create(context.TODO(), tt.ss, metav1.CreateOptions{}); err != nil { + if _, err := c.client.AppsV1().StatefulSets(defaultNamespace).Create(t.Context(), tt.ss, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create StatefulSet error: %v", err) return } @@ -565,7 +565,7 @@ func Test_ReadyChecker_IsReady_ReplicationController(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.ReplicationController{}, Name: "foo", Namespace: defaultNamespace}, }, rc: newReplicationController("foo", false), @@ -580,7 +580,7 @@ func Test_ReadyChecker_IsReady_ReplicationController(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.ReplicationController{}, Name: "foo", Namespace: defaultNamespace}, }, rc: newReplicationController("bar", false), @@ -595,7 +595,7 @@ func Test_ReadyChecker_IsReady_ReplicationController(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &corev1.ReplicationController{}, Name: "foo", Namespace: defaultNamespace}, }, rc: newReplicationController("foo", true), @@ -610,7 +610,7 @@ func Test_ReadyChecker_IsReady_ReplicationController(t *testing.T) { checkJobs: tt.fields.checkJobs, pausedAsReady: tt.fields.pausedAsReady, } - if _, err := c.client.CoreV1().ReplicationControllers(defaultNamespace).Create(context.TODO(), tt.rc, metav1.CreateOptions{}); err != nil { + if _, err := c.client.CoreV1().ReplicationControllers(defaultNamespace).Create(t.Context(), tt.rc, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create ReplicationController error: %v", err) return } @@ -651,7 +651,7 @@ func Test_ReadyChecker_IsReady_ReplicaSet(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.ReplicaSet{}, Name: "foo", Namespace: defaultNamespace}, }, rs: newReplicaSet("foo", 1, 1, true), @@ -666,7 +666,7 @@ func Test_ReadyChecker_IsReady_ReplicaSet(t *testing.T) { pausedAsReady: false, }, args: args{ - ctx: context.TODO(), + ctx: t.Context(), resource: &resource.Info{Object: &appsv1.ReplicaSet{}, Name: "foo", Namespace: defaultNamespace}, }, rs: newReplicaSet("bar", 1, 1, false), @@ -1014,12 +1014,12 @@ func Test_ReadyChecker_podsReadyForObject(t *testing.T) { t.Run(tt.name, func(t *testing.T) { c := NewReadyChecker(fake.NewClientset()) for _, pod := range tt.existPods { - if _, err := c.client.CoreV1().Pods(defaultNamespace).Create(context.TODO(), &pod, metav1.CreateOptions{}); err != nil { + if _, err := c.client.CoreV1().Pods(defaultNamespace).Create(t.Context(), &pod, metav1.CreateOptions{}); err != nil { t.Errorf("Failed to create Pod error: %v", err) return } } - got, err := c.podsReadyForObject(context.TODO(), tt.args.namespace, tt.args.obj) + got, err := c.podsReadyForObject(t.Context(), tt.args.namespace, tt.args.obj) if (err != nil) != tt.wantErr { t.Errorf("podsReadyForObject() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/pkg/plugin/installer/base_test.go b/pkg/plugin/installer/base_test.go index f4dd6d6be..732ac7927 100644 --- a/pkg/plugin/installer/base_test.go +++ b/pkg/plugin/installer/base_test.go @@ -14,7 +14,6 @@ limitations under the License. package installer // import "helm.sh/helm/v4/pkg/plugin/installer" import ( - "os" "testing" ) @@ -37,12 +36,11 @@ func TestPath(t *testing.T) { for _, tt := range tests { - os.Setenv("HELM_PLUGINS", tt.helmPluginsDir) + t.Setenv("HELM_PLUGINS", tt.helmPluginsDir) baseIns := newBase(tt.source) baseInsPath := baseIns.Path() if baseInsPath != tt.expectPath { t.Errorf("expected name %s, got %s", tt.expectPath, baseInsPath) } - os.Unsetenv("HELM_PLUGINS") } } diff --git a/pkg/postrender/exec_test.go b/pkg/postrender/exec_test.go index 2b091cc12..a10ad2cc4 100644 --- a/pkg/postrender/exec_test.go +++ b/pkg/postrender/exec_test.go @@ -60,11 +60,7 @@ func TestGetFullPath(t *testing.T) { t.Run("binary in PATH resolves correctly", func(t *testing.T) { testpath := setupTestingScript(t) - realPath := os.Getenv("PATH") - os.Setenv("PATH", filepath.Dir(testpath)) - defer func() { - os.Setenv("PATH", realPath) - }() + t.Setenv("PATH", filepath.Dir(testpath)) fullPath, err := getFullPath(filepath.Base(testpath)) is.NoError(err) @@ -183,7 +179,7 @@ func setupTestingScript(t *testing.T) (filepath string) { t.Fatalf("unable to write tempfile for testing: %s", err) } - err = f.Chmod(0755) + err = f.Chmod(0o755) if err != nil { t.Fatalf("unable to make tempfile executable for testing: %s", err) } diff --git a/pkg/provenance/sign_test.go b/pkg/provenance/sign_test.go index 69a6dad5b..9a60fd19c 100644 --- a/pkg/provenance/sign_test.go +++ b/pkg/provenance/sign_test.go @@ -276,7 +276,7 @@ func TestDecodeSignature(t *testing.T) { t.Fatal(err) } - f, err := os.CreateTemp("", "helm-test-sig-") + f, err := os.CreateTemp(t.TempDir(), "helm-test-sig-") if err != nil { t.Fatal(err) } diff --git a/pkg/registry/client_test.go b/pkg/registry/client_test.go index 8fc392336..2ffd691c2 100644 --- a/pkg/registry/client_test.go +++ b/pkg/registry/client_test.go @@ -17,7 +17,6 @@ limitations under the License. package registry import ( - "context" "io" "testing" @@ -31,7 +30,7 @@ import ( func TestTagManifestTransformsReferences(t *testing.T) { memStore := memory.New() client := &Client{out: io.Discard} - ctx := context.Background() + ctx := t.Context() refWithPlus := "test-registry.io/charts/test:1.0.0+metadata" expectedRef := "test-registry.io/charts/test:1.0.0_metadata" // + becomes _ diff --git a/pkg/repo/chartrepo_test.go b/pkg/repo/chartrepo_test.go index bc15560c9..05e034dd8 100644 --- a/pkg/repo/chartrepo_test.go +++ b/pkg/repo/chartrepo_test.go @@ -70,7 +70,7 @@ func TestIndexCustomSchemeDownload(t *testing.T) { } repo.CachePath = t.TempDir() - tempIndexFile, err := os.CreateTemp("", "test-repo") + tempIndexFile, err := os.CreateTemp(t.TempDir(), "test-repo") if err != nil { t.Fatalf("Failed to create temp index file: %v", err) } diff --git a/pkg/repo/repo_test.go b/pkg/repo/repo_test.go index c2087ebbe..bdaa61eda 100644 --- a/pkg/repo/repo_test.go +++ b/pkg/repo/repo_test.go @@ -197,7 +197,7 @@ func TestWriteFile(t *testing.T) { }, ) - file, err := os.CreateTemp("", "helm-repo") + file, err := os.CreateTemp(t.TempDir(), "helm-repo") if err != nil { t.Errorf("failed to create test-file (%v)", err) } diff --git a/pkg/repo/repotest/server.go b/pkg/repo/repotest/server.go index b366572d8..ea9d5290c 100644 --- a/pkg/repo/repotest/server.go +++ b/pkg/repo/repotest/server.go @@ -16,7 +16,6 @@ limitations under the License. package repotest import ( - "context" "crypto/tls" "fmt" "net/http" @@ -91,10 +90,7 @@ type Server struct { // The temp dir will be removed by testing package automatically when test finished. func NewTempServer(t *testing.T, options ...ServerOption) *Server { t.Helper() - docrootTempDir, err := os.MkdirTemp("", "helm-repotest-") - if err != nil { - t.Fatal(err) - } + docrootTempDir := t.TempDir() srv := newServer(t, docrootTempDir, options...) @@ -173,7 +169,7 @@ func NewOCIServer(t *testing.T, dir string) (*OCIServer, error) { t.Fatal("error generating bcrypt password for test htpasswd file") } htpasswdPath := filepath.Join(dir, testHtpasswdFileBasename) - err = os.WriteFile(htpasswdPath, []byte(fmt.Sprintf("%s:%s\n", testUsername, string(pwBytes))), 0644) + err = os.WriteFile(htpasswdPath, []byte(fmt.Sprintf("%s:%s\n", testUsername, string(pwBytes))), 0o644) if err != nil { t.Fatalf("error creating test htpasswd file") } @@ -197,7 +193,7 @@ func NewOCIServer(t *testing.T, dir string) (*OCIServer, error) { registryURL := fmt.Sprintf("localhost:%d", port) - r, err := registry.NewRegistry(context.Background(), config) + r, err := registry.NewRegistry(t.Context(), config) if err != nil { t.Fatal(err) } @@ -331,7 +327,7 @@ func (s *Server) CopyCharts(origin string) ([]string, error) { if err != nil { return []string{}, err } - if err := os.WriteFile(newname, data, 0644); err != nil { + if err := os.WriteFile(newname, data, 0o644); err != nil { return []string{}, err } copied[i] = newname @@ -355,7 +351,7 @@ func (s *Server) CreateIndex() error { } ifile := filepath.Join(s.docroot, "index.yaml") - return os.WriteFile(ifile, d, 0644) + return os.WriteFile(ifile, d, 0o644) } func (s *Server) start() { @@ -407,5 +403,5 @@ func setTestingRepository(url, fname string) error { Name: "test", URL: url, }) - return r.WriteFile(fname, 0640) + return r.WriteFile(fname, 0o640) }