Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: use T.TempDir to create temporary test directory #1660

Merged
merged 2 commits into from
Apr 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
| Added subpath functionality to --mount flag
| https://github.com/knative/client/pull/1655[#1655]

| 🐣
| Use `T.TempDir` to create temporary test directory
| https://github.com/knative/client/pull/1660[#1660]

|===
## v1.3.0 (2022-03-08)
[cols="1,10,3", options="header", width="100%"]
Expand Down
8 changes: 2 additions & 6 deletions pkg/kn/commands/completion_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package commands

import (
"fmt"
"io/ioutil"
"os"
"path"
"testing"
Expand Down Expand Up @@ -703,8 +702,6 @@ func TestResourceNameCompletionFuncRevision(t *testing.T) {

func TestResourceNameCompletionFuncGitOps(t *testing.T) {
tempDir := setupTempDir(t)
assert.Assert(t, tempDir != "")
defer os.RemoveAll(tempDir)

completionFunc := ResourceNameCompletionFunc(knParams)

Expand Down Expand Up @@ -1594,11 +1591,10 @@ func getResourceCommandWithTestSubcommand(resource string, addNamespace, addSubc
}

func setupTempDir(t *testing.T) string {
tempDir, err := ioutil.TempDir("", "test-dir")
assert.NilError(t, err)
tempDir := t.TempDir()

svcPath := path.Join(tempDir, "test-ns", "ksvc")
err = os.MkdirAll(svcPath, 0700)
err := os.MkdirAll(svcPath, 0700)
assert.NilError(t, err)

for i, testSvc := range []servingv1.Service{testSvc1, testSvc2, testSvc3} {
Expand Down
16 changes: 6 additions & 10 deletions pkg/kn/commands/namespaced_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,11 @@ func TestGetNamespaceAllNamespacesNotDefined(t *testing.T) {
}

func TestGetNamespaceFallback(t *testing.T) {
tempDir, err := ioutil.TempDir("", "kn-unit-tests")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()

t.Run("MockConfig", func(t *testing.T) {
tempFile := filepath.Join(tempDir, "mock")
err = ioutil.WriteFile(tempFile, []byte(BASIC_KUBECONFIG), test.FileModeReadWrite)
err := ioutil.WriteFile(tempFile, []byte(BASIC_KUBECONFIG), test.FileModeReadWrite)
assert.NilError(t, err)

kp := &KnParams{KubeCfgPath: tempFile}
Expand All @@ -163,7 +161,7 @@ func TestGetNamespaceFallback(t *testing.T) {

t.Run("EmptyConfig", func(t *testing.T) {
tempFile := filepath.Join(tempDir, "empty")
err = ioutil.WriteFile(tempFile, []byte(""), test.FileModeReadWrite)
err := ioutil.WriteFile(tempFile, []byte(""), test.FileModeReadWrite)
assert.NilError(t, err)

kp := &KnParams{KubeCfgPath: tempFile}
Expand All @@ -190,14 +188,12 @@ func TestGetNamespaceFallback(t *testing.T) {
}

func TestCurrentNamespace(t *testing.T) {
tempDir, err := ioutil.TempDir("", "kn-unit-tests")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()

t.Run("EmptyConfig", func(t *testing.T) {
// Invalid kubeconfig
tempFile := filepath.Join(tempDir, "empty")
err = ioutil.WriteFile(tempFile, []byte(""), test.FileModeReadWrite)
err := ioutil.WriteFile(tempFile, []byte(""), test.FileModeReadWrite)
assert.NilError(t, err)

kp := &KnParams{KubeCfgPath: tempFile}
Expand Down Expand Up @@ -234,7 +230,7 @@ func TestCurrentNamespace(t *testing.T) {
t.Run("MockConfig", func(t *testing.T) {
// Fallback to "default" namespace from mock kubeconfig
tempFile := filepath.Join(tempDir, "mock")
err = ioutil.WriteFile(tempFile, []byte(BASIC_KUBECONFIG), test.FileModeReadWrite)
err := ioutil.WriteFile(tempFile, []byte(BASIC_KUBECONFIG), test.FileModeReadWrite)
assert.NilError(t, err)
kp := &KnParams{KubeCfgPath: tempFile}
actual, err := kp.CurrentNamespace()
Expand Down
4 changes: 1 addition & 3 deletions pkg/kn/commands/plugin/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,7 @@ func TestPluginListExtendingBuiltinCommandGroup(t *testing.T) {
// Private

func prepareTestSetup(t *testing.T, args ...interface{}) (string, func()) {
tmpPathDir, err := ioutil.TempDir("", "plugin_list")
assert.NilError(t, err)
tmpPathDir := t.TempDir()

// Prepare configuration to for our test
oldConfig := config.GlobalConfig
Expand All @@ -151,7 +150,6 @@ func prepareTestSetup(t *testing.T, args ...interface{}) (string, func()) {

return tmpPathDir, func() {
config.GlobalConfig = oldConfig
os.RemoveAll(tmpPathDir)
}
}

Expand Down
30 changes: 10 additions & 20 deletions pkg/kn/commands/service/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -894,9 +894,7 @@ func TestServiceCreateFromFile(t *testing.T) {
}

func testWithServiceFiles(t *testing.T, testFunction func(t *testing.T, file string)) {
tempDir, err := ioutil.TempDir("", "kn-file")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()

for _, d := range []struct {
filename string
Expand All @@ -910,7 +908,7 @@ func testWithServiceFiles(t *testing.T, testFunction func(t *testing.T, file str
},
} {
tempFile := filepath.Join(tempDir, d.filename)
err = ioutil.WriteFile(tempFile, []byte(d.content), os.FileMode(0666))
err := ioutil.WriteFile(tempFile, []byte(d.content), os.FileMode(0666))
assert.NilError(t, err)
testFunction(t, tempFile)
}
Expand Down Expand Up @@ -941,14 +939,12 @@ func TestServiceCreateFileError(t *testing.T) {
}

func TestServiceCreateInvalidDataJSON(t *testing.T) {
tempDir, err := ioutil.TempDir("", "kn-file")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()
tempFile := filepath.Join(tempDir, "invalid.json")

// Double curly bracket at the beginning of file
invalidData := strings.Replace(serviceJSON, "{\n", "{{\n", 1)
err = ioutil.WriteFile(tempFile, []byte(invalidData), os.FileMode(0666))
err := ioutil.WriteFile(tempFile, []byte(invalidData), os.FileMode(0666))
assert.NilError(t, err)
_, _, _, err = fakeServiceCreate([]string{"service", "create", "foo", "--filename", tempFile}, false)
assert.Assert(t, util.ContainsAll(err.Error(), "invalid", "character", "'{'", "beginning"))
Expand All @@ -969,14 +965,12 @@ func TestServiceCreateInvalidDataJSON(t *testing.T) {
}

func TestServiceCreateInvalidDataYAML(t *testing.T) {
tempDir, err := ioutil.TempDir("", "kn-file")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()
tempFile := filepath.Join(tempDir, "invalid.yaml")

// Remove dash
invalidData := strings.Replace(serviceYAML, "- image", "image", 1)
err = ioutil.WriteFile(tempFile, []byte(invalidData), os.FileMode(0666))
err := ioutil.WriteFile(tempFile, []byte(invalidData), os.FileMode(0666))
assert.NilError(t, err)
_, _, _, err = fakeServiceCreate([]string{"service", "create", "foo", "--filename", tempFile}, false)
assert.Assert(t, util.ContainsAll(err.Error(), "mapping", "values", "not", "allowed"))
Expand All @@ -997,12 +991,10 @@ func TestServiceCreateInvalidDataYAML(t *testing.T) {
}

func TestServiceCreateFromYAMLWithOverride(t *testing.T) {
tempDir, err := ioutil.TempDir("", "kn-file")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()

tempFile := filepath.Join(tempDir, "service.yaml")
err = ioutil.WriteFile(tempFile, []byte(serviceYAML), os.FileMode(0666))
err := ioutil.WriteFile(tempFile, []byte(serviceYAML), os.FileMode(0666))
assert.NilError(t, err)
// Merge env vars
expectedEnvVars := map[string]string{
Expand Down Expand Up @@ -1077,12 +1069,10 @@ func TestServiceCreateFromYAMLWithOverride(t *testing.T) {
}

func TestServiceCreateFromYAMLWithOverrideError(t *testing.T) {
tempDir, err := ioutil.TempDir("", "kn-file")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()

tempFile := filepath.Join(tempDir, "service.yaml")
err = ioutil.WriteFile(tempFile, []byte(serviceYAML), os.FileMode(0666))
err := ioutil.WriteFile(tempFile, []byte(serviceYAML), os.FileMode(0666))
assert.NilError(t, err)

_, _, _, err = fakeServiceCreate([]string{
Expand Down
21 changes: 7 additions & 14 deletions pkg/kn/commands/service/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ func TestServiceImportFilenameError(t *testing.T) {
}

func TestServiceImportExistError(t *testing.T) {
file, err := generateFile([]byte(exportYAML))
file, err := generateFile(t, []byte(exportYAML))
assert.NilError(t, err)
defer os.RemoveAll(filepath.Dir(file))

client := knclient.NewMockKnServiceClient(t)
r := client.Recorder()
Expand All @@ -60,9 +59,8 @@ func TestServiceImportExistError(t *testing.T) {
}

func TestServiceImport(t *testing.T) {
file, err := generateFile([]byte(exportYAML))
file, err := generateFile(t, []byte(exportYAML))
assert.NilError(t, err)
defer os.RemoveAll(filepath.Dir(file))

client := knclient.NewMockKnServiceClient(t)
r := client.Recorder()
Expand All @@ -80,9 +78,8 @@ func TestServiceImport(t *testing.T) {
}

func TestServiceImportNoWait(t *testing.T) {
file, err := generateFile([]byte(exportYAML))
file, err := generateFile(t, []byte(exportYAML))
assert.NilError(t, err)
defer os.RemoveAll(filepath.Dir(file))

client := knclient.NewMockKnServiceClient(t)
r := client.Recorder()
Expand All @@ -98,9 +95,8 @@ func TestServiceImportNoWait(t *testing.T) {
}

func TestServiceImportWitRevisions(t *testing.T) {
file, err := generateFile([]byte(exportWithRevisionsYAML))
file, err := generateFile(t, []byte(exportWithRevisionsYAML))
assert.NilError(t, err)
defer os.RemoveAll(filepath.Dir(file))

client := knclient.NewMockKnServiceClient(t)
r := client.Recorder()
Expand All @@ -120,14 +116,11 @@ func TestServiceImportWitRevisions(t *testing.T) {
r.Validate()
}

func generateFile(fileContent []byte) (string, error) {
tempDir, err := ioutil.TempDir("", "kn-file")
if err != nil {
return "", err
}
func generateFile(t *testing.T, fileContent []byte) (string, error) {
tempDir := t.TempDir()

tempFile := filepath.Join(tempDir, "import.yaml")
if err = ioutil.WriteFile(tempFile, fileContent, os.FileMode(0666)); err != nil {
if err := ioutil.WriteFile(tempFile, fileContent, os.FileMode(0666)); err != nil {
return "", err
}
return tempFile, nil
Expand Down
6 changes: 2 additions & 4 deletions pkg/kn/commands/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,9 @@ type typeTestCase struct {
func TestGetClientConfig(t *testing.T) {
multiConfigs := fmt.Sprintf("%s%s%s", "/testing/assets/kube-config-01.yml", string(os.PathListSeparator), "/testing/assets/kube-config-02.yml")

tempDir, err := ioutil.TempDir("", "kn-unit-tests")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()
tempFile := filepath.Join(tempDir, "mock")
err = ioutil.WriteFile(tempFile, []byte(BASIC_KUBECONFIG), test.FileModeReadWrite)
err := ioutil.WriteFile(tempFile, []byte(BASIC_KUBECONFIG), test.FileModeReadWrite)
assert.NilError(t, err)

for _, tc := range []typeTestCase{
Expand Down
6 changes: 2 additions & 4 deletions pkg/kn/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,7 @@ sink:
}

func setupConfig(t *testing.T, configContent string) (string, func()) {
tmpDir, err := ioutil.TempDir("", "configContent")
assert.NilError(t, err)
tmpDir := t.TempDir()

// Avoid to be fooled by the things in the the real homedir
oldHome := os.Getenv("HOME")
Expand All @@ -124,7 +123,7 @@ func setupConfig(t *testing.T, configContent string) (string, func()) {
if configContent != "" {
cfgFile = filepath.Join(tmpDir, "config.yaml")
os.Args = []string{"kn", "--config", cfgFile}
err = ioutil.WriteFile(cfgFile, []byte(configContent), 0644)
err := ioutil.WriteFile(cfgFile, []byte(configContent), 0644)
assert.NilError(t, err)
}

Expand All @@ -138,7 +137,6 @@ func setupConfig(t *testing.T, configContent string) (string, func()) {

return cfgFile, func() {
// Cleanup everything
os.RemoveAll(tmpDir)
os.Setenv("HOME", oldHome)
os.Args = backupArgs
bootstrapDefaults = initDefaults()
Expand Down
4 changes: 1 addition & 3 deletions pkg/kn/flags/podspec_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -879,9 +879,7 @@ containers:
assert.NilError(t, err)
assert.Equal(t, len(fromFile.Containers), 2)

tempDir, err := ioutil.TempDir("", "kn-file")
defer os.RemoveAll(tempDir)
assert.NilError(t, err)
tempDir := t.TempDir()
fileName := filepath.Join(tempDir, "container.yaml")
ioutil.WriteFile(fileName, []byte(rawInput), test.FileModeReadWrite)
fromFile, err = decodeContainersFromFile(fileName)
Expand Down
3 changes: 1 addition & 2 deletions pkg/kn/flags/podspec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,7 @@ containers:
"Input:file",
rawInput,
func(data string) string {
tempDir, err := ioutil.TempDir("", "kn-file")
assert.NilError(t, err)
tempDir := t.TempDir()
fileName := filepath.Join(tempDir, "container.yaml")
ioutil.WriteFile(fileName, []byte(data), test.FileModeReadWrite)
return fileName
Expand Down
7 changes: 2 additions & 5 deletions pkg/kn/plugin/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,8 +357,7 @@ func setup(t *testing.T) testContext {
}

func setupWithPathLookup(t *testing.T, lookupInPath bool) testContext {
tmpPathDir, err := ioutil.TempDir("", "plugin_list")
assert.NilError(t, err)
tmpPathDir := t.TempDir()
return testContext{
pluginsDir: tmpPathDir,
pluginManager: NewManager(tmpPathDir, lookupInPath),
Expand Down Expand Up @@ -388,13 +387,11 @@ func executePlugin(plugin Plugin, args []string) (string, error) {

// Prepare a directory and set the path to this directory
func preparePathDirectory(t *testing.T) (string, func()) {
tmpPathDir, err := ioutil.TempDir("", "plugin_path")
assert.NilError(t, err)
tmpPathDir := t.TempDir()

oldPath := os.Getenv("PATH")
os.Setenv("PATH", fmt.Sprintf("%s%c%s", tmpPathDir, os.PathListSeparator, "fast-forward-this-year-plz"))
return tmpPathDir, func() {
os.RemoveAll(tmpPathDir)
os.Setenv("PATH", oldPath)
}
}
Expand Down
15 changes: 4 additions & 11 deletions pkg/serving/v1/gitops_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ package v1

import (
"context"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
Expand All @@ -35,12 +33,9 @@ import (
)

func TestGitOpsOperations(t *testing.T) {
c1TempDir, err := ioutil.TempDir("", "kn-files-cluster1")
assert.NilError(t, err)
c2TempDir, err := ioutil.TempDir("", "kn-files-cluster2")
assert.NilError(t, err)
defer os.RemoveAll(c1TempDir)
defer os.RemoveAll(c2TempDir)
c1TempDir := t.TempDir()
c2TempDir := t.TempDir()

// create clients
fooclient := NewKnServingGitOpsClient("foo-ns", c1TempDir)
bazclient := NewKnServingGitOpsClient("baz-ns", c1TempDir)
Expand Down Expand Up @@ -141,9 +136,7 @@ func TestGitOpsOperations(t *testing.T) {
}

func TestGitOpsSingleFile(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "singlefile")
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
tmpDir := t.TempDir()
// create clients
fooclient := NewKnServingGitOpsClient("", filepath.Join(tmpDir, "test.yaml"))
barclient := NewKnServingGitOpsClient("", filepath.Join(tmpDir, "test.yml"))
Expand Down
Loading