1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

test: use T.Setenv to set env vars in tests

This commit replaces `os.Setenv` with `t.Setenv` in tests. The
environment variable is automatically restored to its original value
when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.Setenv
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2022-04-23 17:01:58 +08:00
parent e78f6f9c68
commit 36049a04d2
No known key found for this signature in database
GPG key ID: DAEBBD2E34C111E6
10 changed files with 39 additions and 153 deletions

View file

@ -6,7 +6,6 @@ import (
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"os"
"runtime" "runtime"
"strings" "strings"
"testing" "testing"
@ -189,7 +188,7 @@ func TestNewClientWithOpsFromEnvSetsDefaultVersion(t *testing.T) {
assert.Check(t, is.Equal(client.ClientVersion(), api.DefaultVersion)) assert.Check(t, is.Equal(client.ClientVersion(), api.DefaultVersion))
const expected = "1.22" const expected = "1.22"
_ = os.Setenv("DOCKER_API_VERSION", expected) t.Setenv("DOCKER_API_VERSION", expected)
client, err = NewClientWithOpts(FromEnv) client, err = NewClientWithOpts(FromEnv)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -1654,8 +1654,7 @@ func BenchmarkUnwrapEvents(b *testing.B) {
func TestNewAWSLogsClientCredentialEndpointDetect(t *testing.T) { func TestNewAWSLogsClientCredentialEndpointDetect(t *testing.T) {
// required for the cloudwatchlogs client // required for the cloudwatchlogs client
os.Setenv("AWS_REGION", "us-west-2") t.Setenv("AWS_REGION", "us-west-2")
defer os.Unsetenv("AWS_REGION")
credsResp := `{ credsResp := `{
"AccessKeyId" : "test-access-key-id", "AccessKeyId" : "test-access-key-id",
@ -1694,17 +1693,13 @@ func TestNewAWSLogsClientCredentialEndpointDetect(t *testing.T) {
func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) { func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) {
// required for the cloudwatchlogs client // required for the cloudwatchlogs client
os.Setenv("AWS_REGION", "us-west-2") t.Setenv("AWS_REGION", "us-west-2")
defer os.Unsetenv("AWS_REGION")
expectedAccessKeyID := "test-access-key-id" expectedAccessKeyID := "test-access-key-id"
expectedSecretAccessKey := "test-secret-access-key" expectedSecretAccessKey := "test-secret-access-key"
os.Setenv("AWS_ACCESS_KEY_ID", expectedAccessKeyID) t.Setenv("AWS_ACCESS_KEY_ID", expectedAccessKeyID)
defer os.Unsetenv("AWS_ACCESS_KEY_ID") t.Setenv("AWS_SECRET_ACCESS_KEY", expectedSecretAccessKey)
os.Setenv("AWS_SECRET_ACCESS_KEY", expectedSecretAccessKey)
defer os.Unsetenv("AWS_SECRET_ACCESS_KEY")
info := logger.Info{ info := logger.Info{
Config: map[string]string{}, Config: map[string]string{},
@ -1724,8 +1719,7 @@ func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) {
func TestNewAWSLogsClientCredentialSharedFile(t *testing.T) { func TestNewAWSLogsClientCredentialSharedFile(t *testing.T) {
// required for the cloudwatchlogs client // required for the cloudwatchlogs client
os.Setenv("AWS_REGION", "us-west-2") t.Setenv("AWS_REGION", "us-west-2")
defer os.Unsetenv("AWS_REGION")
expectedAccessKeyID := "test-access-key-id" expectedAccessKeyID := "test-access-key-id"
expectedSecretAccessKey := "test-secret-access-key" expectedSecretAccessKey := "test-secret-access-key"
@ -1750,8 +1744,7 @@ func TestNewAWSLogsClientCredentialSharedFile(t *testing.T) {
os.Unsetenv("AWS_ACCESS_KEY_ID") os.Unsetenv("AWS_ACCESS_KEY_ID")
os.Unsetenv("AWS_SECRET_ACCESS_KEY") os.Unsetenv("AWS_SECRET_ACCESS_KEY")
os.Setenv("AWS_SHARED_CREDENTIALS_FILE", tmpfile.Name()) t.Setenv("AWS_SHARED_CREDENTIALS_FILE", tmpfile.Name())
defer os.Unsetenv("AWS_SHARED_CREDENTIALS_FILE")
info := logger.Info{ info := logger.Info{
Config: map[string]string{}, Config: map[string]string{},

View file

@ -5,7 +5,6 @@ import (
"context" "context"
"fmt" "fmt"
"net/http" "net/http"
"os"
"runtime" "runtime"
"testing" "testing"
"time" "time"
@ -807,9 +806,7 @@ func TestRawFormatWithoutTag(t *testing.T) {
// Verify that we will send messages in batches with default batching parameters, // Verify that we will send messages in batches with default batching parameters,
// but change frequency to be sure that numOfRequests will match expected 17 requests // but change frequency to be sure that numOfRequests will match expected 17 requests
func TestBatching(t *testing.T) { func TestBatching(t *testing.T) {
if err := os.Setenv(envVarPostMessagesFrequency, "10h"); err != nil { t.Setenv(envVarPostMessagesFrequency, "10h")
t.Fatal(err)
}
hec := NewHTTPEventCollectorMock(t) hec := NewHTTPEventCollectorMock(t)
@ -865,17 +862,11 @@ func TestBatching(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := os.Setenv(envVarPostMessagesFrequency, ""); err != nil {
t.Fatal(err)
}
} }
// Verify that test is using time to fire events not rare than specified frequency // Verify that test is using time to fire events not rare than specified frequency
func TestFrequency(t *testing.T) { func TestFrequency(t *testing.T) {
if err := os.Setenv(envVarPostMessagesFrequency, "5ms"); err != nil { t.Setenv(envVarPostMessagesFrequency, "5ms")
t.Fatal(err)
}
hec := NewHTTPEventCollectorMock(t) hec := NewHTTPEventCollectorMock(t)
@ -938,30 +929,15 @@ func TestFrequency(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := os.Setenv(envVarPostMessagesFrequency, ""); err != nil {
t.Fatal(err)
}
} }
// Simulate behavior similar to first version of Splunk Logging Driver, when we were sending one message // Simulate behavior similar to first version of Splunk Logging Driver, when we were sending one message
// per request // per request
func TestOneMessagePerRequest(t *testing.T) { func TestOneMessagePerRequest(t *testing.T) {
if err := os.Setenv(envVarPostMessagesFrequency, "10h"); err != nil { t.Setenv(envVarPostMessagesFrequency, "10h")
t.Fatal(err) t.Setenv(envVarPostMessagesBatchSize, "1")
} t.Setenv(envVarBufferMaximum, "1")
t.Setenv(envVarStreamChannelSize, "0")
if err := os.Setenv(envVarPostMessagesBatchSize, "1"); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarBufferMaximum, "1"); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarStreamChannelSize, "0"); err != nil {
t.Fatal(err)
}
hec := NewHTTPEventCollectorMock(t) hec := NewHTTPEventCollectorMock(t)
@ -1017,22 +993,6 @@ func TestOneMessagePerRequest(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := os.Setenv(envVarPostMessagesFrequency, ""); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarPostMessagesBatchSize, ""); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarBufferMaximum, ""); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarStreamChannelSize, ""); err != nil {
t.Fatal(err)
}
} }
// Driver should not be created when HEC is unresponsive // Driver should not be created when HEC is unresponsive
@ -1136,17 +1096,9 @@ func TestSkipVerify(t *testing.T) {
// Verify logic for when we filled whole buffer // Verify logic for when we filled whole buffer
func TestBufferMaximum(t *testing.T) { func TestBufferMaximum(t *testing.T) {
if err := os.Setenv(envVarPostMessagesBatchSize, "2"); err != nil { t.Setenv(envVarPostMessagesBatchSize, "2")
t.Fatal(err) t.Setenv(envVarBufferMaximum, "10")
} t.Setenv(envVarStreamChannelSize, "0")
if err := os.Setenv(envVarBufferMaximum, "10"); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarStreamChannelSize, "0"); err != nil {
t.Fatal(err)
}
hec := NewHTTPEventCollectorMock(t) hec := NewHTTPEventCollectorMock(t)
hec.simulateErr(true) hec.simulateErr(true)
@ -1209,33 +1161,13 @@ func TestBufferMaximum(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := os.Setenv(envVarPostMessagesBatchSize, ""); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarBufferMaximum, ""); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarStreamChannelSize, ""); err != nil {
t.Fatal(err)
}
} }
// Verify that we are not blocking close when HEC is down for the whole time // Verify that we are not blocking close when HEC is down for the whole time
func TestServerAlwaysDown(t *testing.T) { func TestServerAlwaysDown(t *testing.T) {
if err := os.Setenv(envVarPostMessagesBatchSize, "2"); err != nil { t.Setenv(envVarPostMessagesBatchSize, "2")
t.Fatal(err) t.Setenv(envVarBufferMaximum, "4")
} t.Setenv(envVarStreamChannelSize, "0")
if err := os.Setenv(envVarBufferMaximum, "4"); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarStreamChannelSize, "0"); err != nil {
t.Fatal(err)
}
hec := NewHTTPEventCollectorMock(t) hec := NewHTTPEventCollectorMock(t)
hec.simulateServerError = true hec.simulateServerError = true
@ -1281,18 +1213,6 @@ func TestServerAlwaysDown(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := os.Setenv(envVarPostMessagesBatchSize, ""); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarBufferMaximum, ""); err != nil {
t.Fatal(err)
}
if err := os.Setenv(envVarStreamChannelSize, ""); err != nil {
t.Fatal(err)
}
} }
// Cannot send messages after we close driver // Cannot send messages after we close driver

View file

@ -5009,16 +5009,14 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *
} }
func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *testing.T) { func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *testing.T) {
osPath := os.Getenv("PATH")
defer os.Setenv("PATH", osPath)
workingDir, err := os.Getwd() workingDir, err := os.Getwd()
assert.NilError(c, err) assert.NilError(c, err)
absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
assert.NilError(c, err) assert.NilError(c, err)
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
os.Setenv("PATH", testPath) osPath := os.Getenv("PATH")
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
c.Setenv("PATH", testPath)
repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)

View file

@ -1693,12 +1693,7 @@ func (s *DockerDaemonSuite) TestDaemonStartWithDefaultTLSHost(c *testing.T) {
"--tlskey", "fixtures/https/server-key.pem") "--tlskey", "fixtures/https/server-key.pem")
// The client with --tlsverify should also use default host localhost:2376 // The client with --tlsverify should also use default host localhost:2376
tmpHost := os.Getenv("DOCKER_HOST") c.Setenv("DOCKER_HOST", "")
defer func() {
os.Setenv("DOCKER_HOST", tmpHost)
}()
os.Setenv("DOCKER_HOST", "")
out, _ := dockerCmd( out, _ := dockerCmd(
c, c,

View file

@ -15,16 +15,14 @@ import (
func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *testing.T) { func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *testing.T) {
s.d.StartWithBusybox(c) s.d.StartWithBusybox(c)
osPath := os.Getenv("PATH")
defer os.Setenv("PATH", osPath)
workingDir, err := os.Getwd() workingDir, err := os.Getwd()
assert.NilError(c, err) assert.NilError(c, err)
absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
assert.NilError(c, err) assert.NilError(c, err)
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
os.Setenv("PATH", testPath) osPath := os.Getenv("PATH")
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
c.Setenv("PATH", testPath)
repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
@ -65,16 +63,14 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *testing.
// #23100 // #23100
func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithWrongHostnamesStored(c *testing.T) { func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithWrongHostnamesStored(c *testing.T) {
osPath := os.Getenv("PATH")
defer os.Setenv("PATH", osPath)
workingDir, err := os.Getwd() workingDir, err := os.Getwd()
assert.NilError(c, err) assert.NilError(c, err)
absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
assert.NilError(c, err) assert.NilError(c, err)
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
os.Setenv("PATH", testPath) osPath := os.Getenv("PATH")
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
c.Setenv("PATH", testPath)
cmd := exec.Command("docker-credential-shell-test", "store") cmd := exec.Command("docker-credential-shell-test", "store")
stdin := bytes.NewReader([]byte(fmt.Sprintf(`{"ServerURL": "https://%s", "Username": "%s", "Secret": "%s"}`, privateRegistryURL, s.reg.Username(), s.reg.Password()))) stdin := bytes.NewReader([]byte(fmt.Sprintf(`{"ServerURL": "https://%s", "Username": "%s", "Secret": "%s"}`, privateRegistryURL, s.reg.Username(), s.reg.Password())))

View file

@ -367,16 +367,14 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *testing.T) {
// #23100 // #23100
func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithScheme(c *testing.T) { func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithScheme(c *testing.T) {
osPath := os.Getenv("PATH")
defer os.Setenv("PATH", osPath)
workingDir, err := os.Getwd() workingDir, err := os.Getwd()
assert.NilError(c, err) assert.NilError(c, err)
absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
assert.NilError(c, err) assert.NilError(c, err)
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
os.Setenv("PATH", testPath) osPath := os.Getenv("PATH")
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
c.Setenv("PATH", testPath)
repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
@ -411,16 +409,14 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithSchem
} }
func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *testing.T) { func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *testing.T) {
osPath := os.Getenv("PATH")
defer os.Setenv("PATH", osPath)
workingDir, err := os.Getwd() workingDir, err := os.Getwd()
assert.NilError(c, err) assert.NilError(c, err)
absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
assert.NilError(c, err) assert.NilError(c, err)
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
os.Setenv("PATH", testPath) osPath := os.Getenv("PATH")
testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
c.Setenv("PATH", testPath)
repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)

View file

@ -243,8 +243,6 @@ func (s *DockerSuite) TestRunAttachDetachFromConfig(c *testing.T) {
keyA := []byte{97} keyA := []byte{97}
// Setup config // Setup config
homeKey := homedir.Key()
homeVal := homedir.Get()
tmpDir, err := os.MkdirTemp("", "fake-home") tmpDir, err := os.MkdirTemp("", "fake-home")
assert.NilError(c, err) assert.NilError(c, err)
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
@ -253,8 +251,7 @@ func (s *DockerSuite) TestRunAttachDetachFromConfig(c *testing.T) {
os.Mkdir(dotDocker, 0600) os.Mkdir(dotDocker, 0600)
tmpCfg := filepath.Join(dotDocker, "config.json") tmpCfg := filepath.Join(dotDocker, "config.json")
defer func() { os.Setenv(homeKey, homeVal) }() c.Setenv(homedir.Key(), tmpDir)
os.Setenv(homeKey, tmpDir)
data := `{ data := `{
"detachKeys": "ctrl-a,a" "detachKeys": "ctrl-a,a"
@ -326,8 +323,6 @@ func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) {
keyA := []byte{97} keyA := []byte{97}
// Setup config // Setup config
homeKey := homedir.Key()
homeVal := homedir.Get()
tmpDir, err := os.MkdirTemp("", "fake-home") tmpDir, err := os.MkdirTemp("", "fake-home")
assert.NilError(c, err) assert.NilError(c, err)
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
@ -336,8 +331,7 @@ func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) {
os.Mkdir(dotDocker, 0600) os.Mkdir(dotDocker, 0600)
tmpCfg := filepath.Join(dotDocker, "config.json") tmpCfg := filepath.Join(dotDocker, "config.json")
defer func() { os.Setenv(homeKey, homeVal) }() c.Setenv(homedir.Key(), tmpDir)
os.Setenv(homeKey, tmpDir)
data := `{ data := `{
"detachKeys": "ctrl-e,e" "detachKeys": "ctrl-e,e"

View file

@ -1372,8 +1372,7 @@ func TestDisablePigz(t *testing.T) {
t.Log("Test will not check full path when Pigz not installed") t.Log("Test will not check full path when Pigz not installed")
} }
os.Setenv("MOBY_DISABLE_PIGZ", "true") t.Setenv("MOBY_DISABLE_PIGZ", "true")
defer os.Unsetenv("MOBY_DISABLE_PIGZ")
r := testDecompressStream(t, "gz", "gzip -f") r := testDecompressStream(t, "gz", "gzip -f")
// For the bufio pool // For the bufio pool

View file

@ -3,7 +3,6 @@ package jsonmessage // import "github.com/docker/docker/pkg/jsonmessage"
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"os"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -268,8 +267,7 @@ func TestDisplayJSONMessagesStream(t *testing.T) {
// Use $TERM which is unlikely to exist, forcing DisplayJSONMessageStream to // Use $TERM which is unlikely to exist, forcing DisplayJSONMessageStream to
// (hopefully) use &noTermInfo. // (hopefully) use &noTermInfo.
origTerm := os.Getenv("TERM") t.Setenv("TERM", "xyzzy-non-existent-terminfo")
os.Setenv("TERM", "xyzzy-non-existent-terminfo")
for jsonMessage, expectedMessages := range messages { for jsonMessage, expectedMessages := range messages {
data := bytes.NewBuffer([]byte{}) data := bytes.NewBuffer([]byte{})
@ -294,6 +292,4 @@ func TestDisplayJSONMessagesStream(t *testing.T) {
t.Fatalf("\nExpected %q\n got %q", expectedMessages[1], data.String()) t.Fatalf("\nExpected %q\n got %q", expectedMessages[1], data.String())
} }
} }
os.Setenv("TERM", origTerm)
} }