Testing cleanup (#1272)

* chore: replace WithEnvVar -> t.Setenv()

Signed-off-by: Matej Vasek <mvasek@redhat.com>

* chore: replace defer with t.Cleanup()

Signed-off-by: Matej Vasek <mvasek@redhat.com>

* chore: remove unused function

Signed-off-by: Matej Vasek <mvasek@redhat.com>

* fix: os.Hostname -> os.UserHomeDir

Signed-off-by: Matej Vasek <mvasek@redhat.com>

Signed-off-by: Matej Vasek <mvasek@redhat.com>
This commit is contained in:
Matej Vasek 2022-09-22 15:12:12 +02:00 committed by GitHub
parent 2988f0c06b
commit 56b56a5559
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 69 additions and 145 deletions

View File

@ -7,7 +7,6 @@ import (
pack "github.com/buildpacks/pack/pkg/client"
fn "knative.dev/kn-plugin-func"
"knative.dev/kn-plugin-func/builders"
. "knative.dev/kn-plugin-func/testing"
)
// Test_BuilderImageDefault ensures that a Function bing built which does not
@ -64,7 +63,7 @@ func Test_BuilderImageConfigurable(t *testing.T) {
// Test_BuildEnvs ensures that build environment variables are interpolated and
// provided in Build Options
func Test_BuildEnvs(t *testing.T) {
defer WithEnvVar(t, "INTERPOLATE_ME", "interpolated")()
t.Setenv("INTERPOLATE_ME", "interpolated")
var (
envName = "NAME"
envValue = "{{ env:INTERPOLATE_ME }}"

View File

@ -66,7 +66,7 @@ func TestClient_InstantiationCreatesRepositoriesPath(t *testing.T) {
}
// Instruct the system to use the above test root directory as the home dir.
defer WithEnvVar(t, "XDG_CONFIG_HOME", rootAbs)()
t.Setenv("XDG_CONFIG_HOME", rootAbs)
// The expected full path to the repositories should be:
expected := filepath.Join(rootAbs, "func", "repositories")

View File

@ -91,7 +91,7 @@ func TestCreateConfig_RepositoriesPath(t *testing.T) {
// Update XDG_CONFIG_HOME to point to some arbitrary location.
xdgConfigHome := t.TempDir()
defer WithEnvVar(t, "XDG_CONFIG_HOME", xdgConfigHome)()
t.Setenv("XDG_CONFIG_HOME", xdgConfigHome)
// The expected full path is XDG_CONFIG_HOME/func/repositories
expected := filepath.Join(xdgConfigHome, "func", "repositories")

View File

@ -246,7 +246,7 @@ func TestDeploy_BuilderPersists(t *testing.T) {
}
func testBuilderPersists(cmdFn commandConstructor, t *testing.T) {
defer WithEnvVar(t, "KUBECONFIG", fmt.Sprintf("%s/testdata/kubeconfig_deploy_namespace", cwd()))()
t.Setenv("KUBECONFIG", fmt.Sprintf("%s/testdata/kubeconfig_deploy_namespace", cwd()))
t.Helper()
root, rm := Mktemp(t)
@ -575,7 +575,7 @@ func Test_ImageWithDigestErrors(t *testing.T) {
},
}
defer WithEnvVar(t, "KUBECONFIG", fmt.Sprintf("%s/testdata/kubeconfig_deploy_namespace", cwd()))()
t.Setenv("KUBECONFIG", fmt.Sprintf("%s/testdata/kubeconfig_deploy_namespace", cwd()))
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@ -682,9 +682,9 @@ func Test_namespace(t *testing.T) {
// if running with an active kubeconfig
if test.context {
defer WithEnvVar(t, "KUBECONFIG", contextPath)()
t.Setenv("KUBECONFIG", contextPath)
} else {
defer WithEnvVar(t, "KUBECONFIG", cwd())()
t.Setenv("KUBECONFIG", cwd())
}
// Creat a funcction which may be already deployed
@ -860,7 +860,7 @@ func TestDeploy_GitURLBranch(t *testing.T) {
// active kubernetes context is used for the namespace if available.
func TestDeploy_NamespaceDefaults(t *testing.T) {
// Set kube context to test context
defer WithEnvVar(t, "KUBECONFIG", filepath.Join(cwd(), "testdata", "kubeconfig_deploy_namespace"))()
t.Setenv("KUBECONFIG", filepath.Join(cwd(), "testdata", "kubeconfig_deploy_namespace"))
// from a temp directory
root, rm := Mktemp(t)
@ -970,7 +970,7 @@ func TestDeploy_NamespaceUpdateWarning(t *testing.T) {
// not instructed otherwise.
func TestDeploy_NamespaceRedeployWarning(t *testing.T) {
// Change profile to one whose current profile is 'test-ns-deploy'
defer WithEnvVar(t, "KUBECONFIG", filepath.Join(cwd(), "testdata", "kubeconfig_deploy_namespace"))()
t.Setenv("KUBECONFIG", filepath.Join(cwd(), "testdata", "kubeconfig_deploy_namespace"))
// From within a temp directory
root, rm := Mktemp(t)

View File

@ -4,15 +4,14 @@ import (
"testing"
fn "knative.dev/kn-plugin-func"
. "knative.dev/kn-plugin-func/testing"
)
// TestLanguages_Default ensures that the default behavior of listing
// all supported languages is to print a plain text list of all the builtin
// language runtimes.
func TestLanguages_Default(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())() // ignore user-added
buf := piped(t) // gather output
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // ignore user-added
buf := piped(t) // gather output
cmd := NewLanguagesCmd(NewClientFactory(func() *fn.Client {
return fn.New()
}))
@ -36,8 +35,8 @@ typescript`
// TestLanguages_JSON ensures that listing languages in --json format returns
// builtin languages as a JSON array.
func TestLanguages_JSON(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())() // ignore user-added
buf := piped(t) // gather output
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // ignore user-added
buf := piped(t) // gather output
cmd := NewLanguagesCmd(NewClientFactory(func() *fn.Client {
return fn.New()
}))

View File

@ -13,7 +13,7 @@ import (
// set of repositories by name for builtin repositories, by explicitly
// setting the repositories path to a new path which includes no others.
func TestRepository_List(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cmd := NewRepositoryListCmd(NewClient)
cmd.SetArgs([]string{}) // Do not use test command args
@ -35,7 +35,7 @@ func TestRepository_List(t *testing.T) {
// arguments, respects the repositories path flag, and the expected name is echoed
// upon subsequent 'list'.
func TestRepository_Add(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var (
add = NewRepositoryAddCmd(NewClient)
list = NewRepositoryListCmd(NewClient)
@ -73,7 +73,7 @@ func TestRepository_Add(t *testing.T) {
// positional arguments, respects the repositories path flag, and the name is
// reflected as having been reanamed upon subsequent 'list'.
func TestRepository_Rename(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var (
add = NewRepositoryAddCmd(NewClient)
rename = NewRepositoryRenameCmd(NewClient)
@ -119,7 +119,7 @@ func TestRepository_Rename(t *testing.T) {
// its argument, respects the repositorieis flag, and the entry is removed upon
// subsequent 'list'.
func TestRepository_Remove(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var (
add = NewRepositoryAddCmd(NewClient)
remove = NewRepositoryRemoveCmd(NewClient)

View File

@ -7,14 +7,13 @@ import (
"gotest.tools/v3/assert"
fn "knative.dev/kn-plugin-func"
. "knative.dev/kn-plugin-func/testing"
)
// TestTemplates_Default ensures that the default behavior is listing all
// templates for all language runtimes.
func TestTemplates_Default(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())() // ignore user-added
buf := piped(t) // gather output
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // ignore user-added
buf := piped(t) // gather output
cmd := NewTemplatesCmd(NewClientFactory(func() *fn.Client {
return fn.New()
}))
@ -46,8 +45,8 @@ typescript http`
// TestTemplates_JSON ensures that listing templates respects the --json
// output format.
func TestTemplates_JSON(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())() // ignore user-added
buf := piped(t) // gather output
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // ignore user-added
buf := piped(t) // gather output
cmd := NewTemplatesCmd(NewClientFactory(func() *fn.Client {
return fn.New()
}))
@ -105,7 +104,7 @@ func TestTemplates_JSON(t *testing.T) {
// TestTemplates_ByLanguage ensures that the output is correctly filtered
// by language runtime when provided.
func TestTemplates_ByLanguage(t *testing.T) {
defer WithEnvVar(t, "XDG_CONFIG_HOME", t.TempDir())() // ignore user-added
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // ignore user-added
cmd := NewTemplatesCmd(NewClientFactory(func() *fn.Client {
return fn.New()
}))

View File

@ -310,7 +310,7 @@ const (
type Credentials = docker.Credentials
func TestNewCredentialsProvider(t *testing.T) {
defer withCleanHome(t)()
withCleanHome(t)
helperWithQuayIO := newInMemoryHelper()
@ -413,7 +413,7 @@ func TestNewCredentialsProvider(t *testing.T) {
defer cleanUpConfigs(t)
if tt.args.setUpEnv != nil {
defer tt.args.setUpEnv(t)()
tt.args.setUpEnv(t)
}
credentialsProvider := creds.NewCredentialsProvider(
@ -450,10 +450,10 @@ func TestNewCredentialsProviderEmptyCreds(t *testing.T) {
}
func TestCredentialsProviderSavingFromUserInput(t *testing.T) {
defer withCleanHome(t)()
withCleanHome(t)
helper := newInMemoryHelper()
defer setUpMockHelper("docker-credential-mock", helper)(t)()
setUpMockHelper("docker-credential-mock", helper)(t)
var pwdCbkInvocations int
pwdCbk := func(r string) (Credentials, error) {
@ -531,7 +531,7 @@ func TestCredentialsProviderSavingFromUserInput(t *testing.T) {
}
func cleanUpConfigs(t *testing.T) {
home, err := os.Hostname()
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
@ -541,9 +541,9 @@ func cleanUpConfigs(t *testing.T) {
os.RemoveAll(filepath.Join(home, ".docker"))
}
type setUpEnv = func(t *testing.T) func()
type setUpEnv = func(t *testing.T)
func withPopulatedDockerAuthConfig(t *testing.T) func() {
func withPopulatedDockerAuthConfig(t *testing.T) {
t.Helper()
home, err := os.UserHomeDir()
if err != nil {
@ -555,6 +555,7 @@ func withPopulatedDockerAuthConfig(t *testing.T) func() {
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.RemoveAll(dockerConfigDir) })
configJSON := `{
"auths": {
@ -569,14 +570,9 @@ func withPopulatedDockerAuthConfig(t *testing.T) func() {
if err != nil {
t.Fatal(err)
}
return func() {
os.RemoveAll(dockerConfigDir)
}
}
func withPopulatedFuncAuthConfig(t *testing.T) func() {
func withPopulatedFuncAuthConfig(t *testing.T) {
t.Helper()
var err error
@ -587,6 +583,8 @@ func withPopulatedFuncAuthConfig(t *testing.T) func() {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.RemoveAll(authConfig) })
authJSON := `{
"auths": {
"docker.io": { "auth": "%s" },
@ -601,9 +599,6 @@ func withPopulatedFuncAuthConfig(t *testing.T) func() {
if err != nil {
t.Fatal(err)
}
return func() {
os.RemoveAll(fn.ConfigPath())
}
}
func pwdCbkThatShallNotBeCalled(t *testing.T) creds.CredentialsCallback {
@ -649,33 +644,17 @@ func correctVerifyCbk(ctx context.Context, image string, credentials Credentials
return creds.ErrUnauthorized
}
func withCleanHome(t *testing.T) func() {
func withCleanHome(t *testing.T) {
t.Helper()
homeName := "HOME"
if runtime.GOOS == "windows" {
homeName = "USERPROFILE"
}
tmpHome := t.TempDir()
oldHome, hadHome := os.LookupEnv(homeName)
os.Setenv(homeName, tmpHome)
oldXDGConfigHome, hadXDGConfigHome := os.LookupEnv("XDG_CONFIG_HOME")
t.Setenv(homeName, tmpHome)
if runtime.GOOS == "linux" {
os.Setenv("XDG_CONFIG_HOME", filepath.Join(tmpHome, ".config"))
}
return func() {
if hadHome {
os.Setenv(homeName, oldHome)
} else {
os.Unsetenv(homeName)
}
if hadXDGConfigHome {
os.Setenv("XDG_CONFIG_HOME", oldXDGConfigHome)
} else {
os.Unsetenv("XDG_CONFIG_HOME")
}
t.Setenv("XDG_CONFIG_HOME", filepath.Join(tmpHome, ".config"))
}
}
@ -807,23 +786,20 @@ func main() {
// The executable behaves like docker credential helper (https://github.com/docker/docker-credential-helpers).
//
// The content of the store presented by the executable is backed by the helper parameter.
func setUpMockHelper(helperName string, helper credentials.Helper) func(t *testing.T) func() {
var cleanUps []func()
return func(t *testing.T) func() {
func setUpMockHelper(helperName string, helper credentials.Helper) func(t *testing.T) {
return func(t *testing.T) {
cleanUps = append(cleanUps, WithExecutable(t, helperName, helperGoSrc))
WithExecutable(t, helperName, helperGoSrc)
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatal(err)
}
cleanUps = append(cleanUps, func() {
_ = listener.Close()
})
t.Cleanup(func() { _ = listener.Close() })
baseURL := fmt.Sprintf("http://%s", listener.Addr().String())
cleanUps = append(cleanUps, WithEnvVar(t, "HELPER_BASE_URL", baseURL))
t.Setenv("HELPER_BASE_URL", baseURL)
server := http.Server{Handler: handlerForCredHelper(t, helper)}
servErrChan := make(chan error)
@ -831,7 +807,7 @@ func setUpMockHelper(helperName string, helper credentials.Helper) func(t *testi
servErrChan <- server.Serve(listener)
}()
cleanUps = append(cleanUps, func() {
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_ = server.Shutdown(ctx)
@ -840,28 +816,15 @@ func setUpMockHelper(helperName string, helper credentials.Helper) func(t *testi
t.Fatal(e)
}
})
return func() {
for i := len(cleanUps) - 1; i <= 0; i-- {
cleanUps[i]()
}
}
}
}
// combines multiple setUp routines into one setUp routine
func all(fns ...setUpEnv) setUpEnv {
return func(t *testing.T) func() {
return func(t *testing.T) {
t.Helper()
var cleanUps []func()
for _, fn := range fns {
cleanUps = append(cleanUps, fn(t))
}
return func() {
for i := len(cleanUps) - 1; i >= 0; i-- {
cleanUps[i]()
}
fn(t)
}
}
}

View File

@ -17,8 +17,8 @@ func TestNewDockerClientWithAutomaticPodmanSuccess(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*1)
defer cancel()
defer WithExecutable(t, "podman", mockPodmanSrc)()
defer WithEnvVar(t, "DOCKER_HOST", "")()
WithExecutable(t, "podman", mockPodmanSrc)
t.Setenv("DOCKER_HOST", "")
dockerClient, dockerHostToMount, err := docker.NewClient("unix:///var/run/nonexistent.sock")
if err != nil {
@ -39,8 +39,8 @@ func TestNewDockerClientWithAutomaticPodmanSuccess(t *testing.T) {
func TestNewDockerClientWithAutomaticPodmanFail(t *testing.T) {
src := `package main;import ("os";"fmt");func main(){fmt.Println("something went wrong");os.Exit(1);}`
defer WithExecutable(t, "podman", src)()
defer WithEnvVar(t, "DOCKER_HOST", "")()
WithExecutable(t, "podman", src)
t.Setenv("DOCKER_HOST", "")
_, _, err := docker.NewClient("unix:///var/run/nonexistent.sock")
if err == nil {

View File

@ -39,8 +39,8 @@ func TestNewDockerClientWithPodmanMachine(t *testing.T) {
goSrc := fmt.Sprintf("package main; import \"fmt\"; func main() { fmt.Println(%q); }", out)
defer WithEnvVar(t, "DOCKER_HOST", "")()
defer WithExecutable(t, "podman", goSrc)()
t.Setenv("DOCKER_HOST", "")
WithExecutable(t, "podman", goSrc)
dockerClient, dockerHostInRemote, err := docker.NewClient("")
if err != nil {

View File

@ -20,11 +20,9 @@ import (
"testing"
"time"
"knative.dev/kn-plugin-func/docker"
. "knative.dev/kn-plugin-func/testing"
"github.com/docker/docker/client"
"golang.org/x/crypto/ssh"
"knative.dev/kn-plugin-func/docker"
)
func TestNewDockerClientWithSSH(t *testing.T) {
@ -38,7 +36,7 @@ func TestNewDockerClientWithSSH(t *testing.T) {
defer withKnowHosts(t, sshConf.address, sshConf.pubHostKey)()
defer WithEnvVar(t, "DOCKER_HOST", fmt.Sprintf("ssh://user:pwd@%s", sshConf.address))()
t.Setenv("DOCKER_HOST", fmt.Sprintf("ssh://user:pwd@%s", sshConf.address))
dockerClient, dockerHostInRemote, err := docker.NewClient(client.DefaultDockerHost)
if err != nil {

View File

@ -11,10 +11,8 @@ import (
"testing"
"time"
"knative.dev/kn-plugin-func/docker"
. "knative.dev/kn-plugin-func/testing"
"github.com/docker/docker/client"
"knative.dev/kn-plugin-func/docker"
)
// Test that we are creating client in accordance
@ -33,7 +31,7 @@ func TestNewClient(t *testing.T) {
defer startMockDaemonUnix(t, sock)()
defer WithEnvVar(t, "DOCKER_HOST", dockerHost)()
t.Setenv("DOCKER_HOST", dockerHost)
dockerClient, dockerHostInRemote, err := docker.NewClient(client.DefaultDockerHost)
if err != nil {
@ -77,7 +75,7 @@ func TestNewClient_DockerHost(t *testing.T) {
t.Skip("Windows cannot handle Unix sockets")
}
defer WithEnvVar(t, "DOCKER_HOST", tt.dockerHostEnvVar)()
t.Setenv("DOCKER_HOST", tt.dockerHostEnvVar)
_, host, err := docker.NewClient(client.DefaultDockerHost)
if err != nil {
t.Fatal(err)

View File

@ -9,8 +9,6 @@ import (
winio "github.com/Microsoft/go-winio"
"github.com/docker/docker/client"
"knative.dev/kn-plugin-func/docker"
. "knative.dev/kn-plugin-func/testing"
)
func TestNewClientWinPipe(t *testing.T) {
@ -18,7 +16,7 @@ func TestNewClientWinPipe(t *testing.T) {
const testNPipe = "test-npipe"
defer startMockDaemonWinPipe(t, testNPipe)()
defer WithEnvVar(t, "DOCKER_HOST", fmt.Sprintf("npipe:////./pipe/%s", testNPipe))()
t.Setenv("DOCKER_HOST", fmt.Sprintf("npipe:////./pipe/%s", testNPipe))
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*1)
defer cancel()

View File

@ -5,8 +5,6 @@ package function
import (
"testing"
. "knative.dev/kn-plugin-func/testing"
)
func Test_validateLabels(t *testing.T) {
@ -29,10 +27,10 @@ func Test_validateLabels(t *testing.T) {
valueLocalEnvIncorrect2 := "{{ MY_ENV }}"
valueLocalEnvIncorrect3 := "{{env:MY_ENV}}foo"
defer WithEnvVar(t, "BAD_EXAMPLE", ":invalid")()
t.Setenv("BAD_EXAMPLE", ":invalid")
valueLocalEnvIncorrect4 := "{{env:BAD_EXAMPLE}}"
defer WithEnvVar(t, "GOOD_EXAMPLE", "valid")()
t.Setenv("GOOD_EXAMPLE", "valid")
valueLocalEnv4 := "{{env:GOOD_EXAMPLE}}"
tests := []struct {

View File

@ -93,7 +93,7 @@ func TestFunction_NameDefault(t *testing.T) {
// TODO: What use case does a nil pointer in the Env struct serve? Add it
// explicitly here ore get rid of the nils.
func Test_Interpolate(t *testing.T) {
defer WithEnvVar(t, "INTERPOLATE", "interpolated")()
t.Setenv("INTERPOLATE", "interpolated")
cases := []struct {
Value string
Expected string

View File

@ -8,7 +8,6 @@ import (
"testing"
fnlabels "knative.dev/kn-plugin-func/k8s/labels"
. "knative.dev/kn-plugin-func/testing"
)
func TestFunction_ImageWithDigest(t *testing.T) {
@ -93,10 +92,10 @@ func Test_LabelsMap(t *testing.T) {
value1 := "value1"
value2 := "value2"
defer WithEnvVar(t, "BAD_EXAMPLE", ":invalid")()
t.Setenv("BAD_EXAMPLE", ":invalid")
valueLocalEnvIncorrect4 := "{{env:BAD_EXAMPLE}}"
defer WithEnvVar(t, "GOOD_EXAMPLE", "valid")()
t.Setenv("GOOD_EXAMPLE", "valid")
valueLocalEnv4 := "{{env:GOOD_EXAMPLE}}"
tests := []struct {

View File

@ -5,11 +5,10 @@ import (
"testing"
"knative.dev/kn-plugin-func/k8s"
. "knative.dev/kn-plugin-func/testing"
)
func TestListConfigMapsNamesIfConnectedWrongKubeconfig(t *testing.T) {
defer WithEnvVar(t, "KUBECONFIG", "/tmp/non-existent.config")()
t.Setenv("KUBECONFIG", "/tmp/non-existent.config")
_, err := k8s.ListConfigMapsNamesIfConnected(context.Background(), "")
if err != nil {
t.Fatal(err)
@ -17,7 +16,7 @@ func TestListConfigMapsNamesIfConnectedWrongKubeconfig(t *testing.T) {
}
func TestListConfigMapsNamesIfConnectedWrongKubernentesMaster(t *testing.T) {
defer WithEnvVar(t, "KUBERNETES_MASTER", "/tmp/non-existent.config")()
t.Setenv("KUBERNETES_MASTER", "/tmp/non-existent.config")
_, err := k8s.ListConfigMapsNamesIfConnected(context.Background(), "")
if err != nil {
t.Fatal(err)

View File

@ -5,11 +5,10 @@ import (
"testing"
"knative.dev/kn-plugin-func/k8s"
. "knative.dev/kn-plugin-func/testing"
)
func TestListSecretsNamesIfConnectedWrongKubeconfig(t *testing.T) {
defer WithEnvVar(t, "KUBECONFIG", "/tmp/non-existent.config")()
t.Setenv("KUBECONFIG", "/tmp/non-existent.config")
_, err := k8s.ListSecretsNamesIfConnected(context.Background(), "")
if err != nil {
t.Fatal(err)
@ -17,7 +16,7 @@ func TestListSecretsNamesIfConnectedWrongKubeconfig(t *testing.T) {
}
func TestListSecretsNamesIfConnectedWrongKubernentesMaster(t *testing.T) {
defer WithEnvVar(t, "KUBERNETES_MASTER", "/tmp/non-existent.config")()
t.Setenv("KUBERNETES_MASTER", "/tmp/non-existent.config")
_, err := k8s.ListSecretsNamesIfConnected(context.Background(), "")
if err != nil {
t.Fatal(err)

View File

@ -10,7 +10,6 @@ import (
corev1 "k8s.io/api/core/v1"
fn "knative.dev/kn-plugin-func"
. "knative.dev/kn-plugin-func/testing"
)
// Test_DefaultNamespace ensures that if there is an active kubeconfig,
@ -19,7 +18,7 @@ import (
func Test_DefaultNamespace(t *testing.T) {
// Update Kubeconfig to indicate the currently active namespace is:
// "test-ns-deploy"
defer WithEnvVar(t, "KUBECONFIG", fmt.Sprintf("%s/testdata/test_default_namespace", cwd()))()
t.Setenv("KUBECONFIG", fmt.Sprintf("%s/testdata/test_default_namespace", cwd()))
if DefaultNamespace() != "test-ns-deploy" {
t.Fatalf("expected 'test-ns-deploy', got '%v'", DefaultNamespace())

View File

@ -28,7 +28,6 @@ import (
fn "knative.dev/kn-plugin-func"
"knative.dev/kn-plugin-func/builders"
"knative.dev/kn-plugin-func/s2i"
. "knative.dev/kn-plugin-func/testing"
)
// Test_BuildImages ensures that supported runtimes returns builder image
@ -173,7 +172,7 @@ func Test_BuilderVerbose(t *testing.T) {
// are interpolated and passed to the S2I build implementation in the final
// build config.
func Test_BuildEnvs(t *testing.T) {
defer WithEnvVar(t, "INTERPOLATE_ME", "interpolated")()
t.Setenv("INTERPOLATE_ME", "interpolated")
var (
envName = "NAME"
envValue = "{{ env:INTERPOLATE_ME }}"

View File

@ -146,34 +146,15 @@ func TestRepoURI(name string, t *testing.T) string {
return fmt.Sprintf(`http://%s/%s.git`, hostPort, name)
}
// WithEnvVar sets an environment variable
// and returns deferrable function that restores previous value of the environment variable.
// TODO: replace with t.Setenv when we upgrade to go.1.17
func WithEnvVar(t *testing.T, name, value string) func() {
t.Helper()
oldDh, hadDh := os.LookupEnv(name)
err := os.Setenv(name, value)
if err != nil {
t.Fatal(err)
}
return func() {
if hadDh {
_ = os.Setenv(name, oldDh)
} else {
_ = os.Unsetenv(name)
}
}
}
// WithExecutable creates an executable of the given name and source in a temp
// directory which is then added to PATH. Returned is a deferrable which will
// clean up both the script and PATH.
func WithExecutable(t *testing.T, name, goSrc string) func() {
func WithExecutable(t *testing.T, name, goSrc string) {
var err error
binDir := t.TempDir()
newPath := binDir + string(os.PathListSeparator) + os.Getenv("PATH")
cleanUpPath := WithEnvVar(t, "PATH", newPath)
t.Setenv("PATH", newPath)
goSrcPath := filepath.Join(binDir, fmt.Sprintf("%s.go", name))
@ -204,10 +185,6 @@ go.exe run GO_SCRIPT_PATH %*
if err != nil {
t.Fatal(err)
}
return func() {
cleanUpPath()
}
}
// RunGitServer starts serving git HTTP server and returns its address including port