本文整理匯總了Golang中os.Unsetenv函數的典型用法代碼示例。如果您正苦於以下問題:Golang Unsetenv函數的具體用法?Golang Unsetenv怎麽用?Golang Unsetenv使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Unsetenv函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: composeUp
// composeUp converts given json to yaml, saves to a file on the host and
// uses `docker-compose up -d` to create the containers.
func composeUp(d driver.DistroDriver, json map[string]interface{}) error {
if len(json) == 0 {
log.Println("docker-compose config not specified, noop")
return nil
}
// Convert json to yaml
yaml, err := yaml.Marshal(json)
if err != nil {
return fmt.Errorf("error converting to compose.yml: %v", err)
}
if err := os.MkdirAll(composeYmlDir, 0777); err != nil {
return fmt.Errorf("failed creating %s: %v", composeYmlDir, err)
}
log.Printf("Using compose yaml:>>>>>\n%s\n<<<<<", string(yaml))
ymlPath := filepath.Join(composeYmlDir, composeYml)
if err := ioutil.WriteFile(ymlPath, yaml, 0666); err != nil {
return fmt.Errorf("error writing %s: %v", ymlPath, err)
}
// set timeout for docker-compose -> docker-engine interactions.
// When downloading large images, docker-compose intermittently times out
// (gh#docker/compose/issues/2186).
os.Setenv("COMPOSE_HTTP_TIMEOUT", fmt.Sprintf("%d", composeTimeoutSecs)) // versions <= 1.4.2
os.Setenv("DOCKER_CLIENT_TIMEOUT", fmt.Sprintf("%d", composeTimeoutSecs)) // version >= 1.5.0
defer os.Unsetenv("COMPOSE_HTTP_TIMEOUT")
defer os.Unsetenv("DOCKER_CLIENT_TIMEOUT")
return executil.ExecPipeToFds(executil.Fds{Out: ioutil.Discard}, composeBinPath(d), "-p", composeProject, "-f", ymlPath, "up", "-d")
}
示例2: main
func main(cfg *config.CloudConfig) error {
os.Unsetenv("_LIBCONTAINER_INITPIPE")
os.Unsetenv("_LIBCONTAINER_INITPID")
if err := system.ParentDeathSignal(syscall.SIGKILL).Set(); err != nil {
return err
}
if err := os.Remove("/var/run/docker.pid"); err != nil && !os.IsNotExist(err) {
return err
}
dockerCfg := cfg.Rancher.Docker
args := dockerCfg.FullArgs()
log.Debugf("User Docker args: %v", args)
if dockerCfg.TLS {
log.Debug("Generating TLS certs if needed")
if err := control.Generate(true, "/etc/docker/tls", []string{"localhost"}); err != nil {
return err
}
}
prog := findProgram("docker-init", "dockerlaunch", "docker")
if strings.Contains(prog, "dockerlaunch") {
args = append([]string{prog, "docker"}, args...)
} else {
args = append([]string{prog}, args...)
}
log.Infof("Running %v", args)
return syscall.Exec(args[0], args, dockerCfg.AppendEnv())
}
示例3: TestNewCliParamsFromEnvVarsWithRegionSpecifiedAsEnvVariable
func TestNewCliParamsFromEnvVarsWithRegionSpecifiedAsEnvVariable(t *testing.T) {
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalContext := cli.NewContext(nil, globalSet, nil)
context := cli.NewContext(nil, nil, globalContext)
rdwr := &mockReadWriter{}
os.Setenv("AWS_REGION", "us-west-1")
os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
os.Setenv("AWS_SECRET_KEY", "SECRET")
defer func() {
os.Unsetenv("AWS_REGION")
os.Unsetenv("AWS_ACCESS_KEY")
os.Unsetenv("AWS_SECRET_KEY")
}()
params, err := NewCliParams(context, rdwr)
if err != nil {
t.Errorf("Unexpected error when region is specified using environment variable AWS_REGION: ", err)
}
paramsRegion := aws.StringValue(params.Config.Region)
if "us-west-1" != paramsRegion {
t.Errorf("Unexpected region set, expected: us-west-1, got: %s", paramsRegion)
}
}
示例4: TestShellToContainerWithUnit
func (s *S) TestShellToContainerWithUnit(c *check.C) {
guesser := cmdtest.FakeGuesser{Name: "myapp"}
server := httptest.NewServer(buildHandler([]byte("hello my friend\nglad to see you here\n")))
defer server.Close()
target := "http://" + server.Listener.Addr().String()
os.Setenv("TSURU_TARGET", target)
defer os.Unsetenv("TSURU_TARGET")
os.Setenv("TSURU_TOKEN", "abc123")
defer os.Unsetenv("TSURU_TOKEN")
var stdout, stderr, stdin bytes.Buffer
context := Context{
Args: []string{"containerid"},
Stdout: &stdout,
Stderr: &stderr,
Stdin: &stdin,
}
var command ShellToContainerCmd
command.GuessingCommand = GuessingCommand{G: &guesser}
err := command.Flags().Parse(true, []string{"-a", "myapp"})
c.Assert(err, check.IsNil)
mngr := NewManager("admin", "0.1", "admin-ver", &stdout, &stderr, nil, nil)
client := NewClient(http.DefaultClient, &context, mngr)
err = command.Run(&context, client)
c.Assert(err, check.IsNil)
c.Assert(stdout.String(), check.Equals, "hello my friend\nglad to see you here\n")
}
示例5: TestRuntime
// TestRuntime tests stuff from runtime.go
func TestRuntime(t *testing.T) {
Convey("The Runtime configuration tests, ", t, func() {
envvars := []string{"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_STORAGE_BUCKET_NAME", "REDIS_URL"}
for i := range envvars {
envvar := envvars[i]
Convey(fmt.Sprintf("Without %s", envvar), func() {
curVal := os.Getenv(envvar)
os.Unsetenv(envvar)
So(func() { CheckEnvVars() }, ShouldPanic)
os.Setenv(envvar, curVal)
})
}
Convey("Without MAX_CPUS", func() {
envvar := "MAX_CPUS"
curVal := os.Getenv(envvar)
os.Unsetenv(envvar)
So(func() { ConfigureRuntime() }, ShouldNotPanic)
os.Setenv(envvar, curVal)
})
invalidLogLevels := []string{"D3BUG", ""}
for i := range invalidLogLevels {
envvar := "LOG_LEVEL"
envval := invalidLogLevels[i]
Convey(fmt.Sprintf("With %s to %s", envvar, envval), func() {
curVal := os.Getenv(envvar)
os.Setenv(envvar, envval)
So(func() { ConfigureLogger() }, ShouldNotPanic)
os.Setenv(envvar, curVal)
})
}
})
}
示例6: TestPopulateContext
func TestPopulateContext(t *testing.T) {
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalContext := cli.NewContext(nil, globalSet, nil)
cliContext := cli.NewContext(nil, nil, globalContext)
ecsContext := &ecscompose.Context{}
// Create a temprorary directory for the dummy ecs config
tempDirName, err := ioutil.TempDir("", "test")
if err != nil {
t.Fatal("Error while creating the dummy ecs config directory")
}
defer os.Remove(tempDirName)
os.Setenv("HOME", tempDirName)
os.Setenv("AWS_REGION", "us-east-1")
os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
os.Setenv("AWS_SECRET_KEY", "secret")
defer func() {
os.Unsetenv("AWS_REGION")
os.Unsetenv("AWS_ACCESS_KEY")
os.Unsetenv("AWS_SECRET_KEY")
os.Unsetenv("HOME")
}()
projectFactory := projectFactory{}
err = projectFactory.populateContext(ecsContext, cliContext)
if err != nil {
t.Fatal("Error while populating the context")
}
if ecsContext.ECSParams == nil {
t.Error("ECS Params was expected to be set for ecsContext but was nil")
}
}
示例7: unsetEnv
// unsetEnv unsets enviornment variables for testing a "clean slate" with no
// credentials in the environment
func unsetEnv(t *testing.T) func() {
// Grab any existing AWS keys and preserve. In some tests we'll unset these, so
// we need to have them and restore them after
e := getEnv()
if err := os.Unsetenv("AWS_ACCESS_KEY_ID"); err != nil {
t.Fatalf("Error unsetting env var AWS_ACCESS_KEY_ID: %s", err)
}
if err := os.Unsetenv("AWS_SECRET_ACCESS_KEY"); err != nil {
t.Fatalf("Error unsetting env var AWS_SECRET_ACCESS_KEY: %s", err)
}
if err := os.Unsetenv("AWS_SESSION_TOKEN"); err != nil {
t.Fatalf("Error unsetting env var AWS_SESSION_TOKEN: %s", err)
}
return func() {
// re-set all the envs we unset above
if err := os.Setenv("AWS_ACCESS_KEY_ID", e.Key); err != nil {
t.Fatalf("Error resetting env var AWS_ACCESS_KEY_ID: %s", err)
}
if err := os.Setenv("AWS_SECRET_ACCESS_KEY", e.Secret); err != nil {
t.Fatalf("Error resetting env var AWS_SECRET_ACCESS_KEY: %s", err)
}
if err := os.Setenv("AWS_SESSION_TOKEN", e.Token); err != nil {
t.Fatalf("Error resetting env var AWS_SESSION_TOKEN: %s", err)
}
}
}
示例8: Test0Steps3WorkflowsCircularDependency
// Test - Bitrise Validate workflow
// Workflow contains before and after workflow, and no one contains steps, but circular wofklow dependecy exist, which should fail
func Test0Steps3WorkflowsCircularDependency(t *testing.T) {
require.NoError(t, os.Setenv("BITRISE_BUILD_STATUS", "0"))
defer func() { require.NoError(t, os.Unsetenv("BITRISE_BUILD_STATUS")) }()
require.NoError(t, os.Setenv("STEPLIB_BUILD_STATUS", "0"))
defer func() { require.NoError(t, os.Unsetenv("STEPLIB_BUILD_STATUS")) }()
beforeWorkflow := models.WorkflowModel{
BeforeRun: []string{"target"},
}
afterWorkflow := models.WorkflowModel{}
workflow := models.WorkflowModel{
BeforeRun: []string{"before"},
AfterRun: []string{"after"},
}
config := models.BitriseDataModel{
FormatVersion: "1.0.0",
DefaultStepLibSource: "https://github.com/bitrise-io/bitrise-steplib.git",
Workflows: map[string]models.WorkflowModel{
"target": workflow,
"before": beforeWorkflow,
"after": afterWorkflow,
},
}
_, err := config.Validate()
require.Error(t, err)
require.Equal(t, "0", os.Getenv("BITRISE_BUILD_STATUS"))
require.Equal(t, "0", os.Getenv("STEPLIB_BUILD_STATUS"))
}
示例9: TestToServiceConfigWhenUsingEnvVariables
func TestToServiceConfigWhenUsingEnvVariables(t *testing.T) {
ecsConfig := NewCliConfig(clusterName)
ecsConfig.Region = region
os.Setenv("AWS_ACCESS_KEY_ID", envAwsAccessKey)
os.Setenv("AWS_SECRET_ACCESS_KEY", envAwsSecretKey)
// Clear env variables as they persist past the individual test boundary
defer func() {
os.Unsetenv("AWS_ACCESS_KEY_ID")
os.Unsetenv("AWS_SECRET_ACCESS_KEY")
os.Unsetenv("AWS_ACCESS_KEY")
os.Unsetenv("AWS_SECRET_KEY")
}()
awsConfig, _ := ecsConfig.ToServiceConfig()
resolvedCredentials, err := awsConfig.Credentials.Get()
if err != nil {
t.Error("Error fetching credentials from the chain provider")
}
if envAwsAccessKey != resolvedCredentials.AccessKeyID {
t.Errorf("Invalid access key set. Expected [%s]. Got [%s]", envAwsAccessKey, resolvedCredentials.AccessKeyID)
}
if envAwsSecretKey != resolvedCredentials.SecretAccessKey {
t.Errorf("Invalid secret key set. Expected [%s]. Got [%s]", envAwsSecretKey, resolvedCredentials.SecretAccessKey)
}
}
示例10: init
func init() {
if runtime.GOOS == "darwin" {
// remove DYLD_LIBRARY_PATH and LD_LIBRARY_PATH as they break VBoxManage on OSX
os.Unsetenv("DYLD_LIBRARY_PATH")
os.Unsetenv("LD_LIBRARY_PATH")
}
}
示例11: TestEnvVarOverride
func TestEnvVarOverride(t *testing.T) {
defer func() {
loadedTemplates = make(map[string]*template.Template)
os.Unsetenv(defaultTemplateDirectoryEnvVar)
}()
// first check that we fail with the wrong directory
os.Setenv(defaultTemplateDirectoryEnvVar, filepath.Join("nosuchdir"))
_, err := loadPageTemplate("error")
if err == nil {
t.Fatalf("Load with OS env directory %v", os.Getenv(defaultTemplateDirectoryEnvVar))
}
// now reset to the tests directory and try a test load
os.Setenv(defaultTemplateDirectoryEnvVar, "tests")
_, err = loadPageTemplate("test")
if err != nil {
t.Fatalf("Failed to load test template: %v", err)
}
// now unset the environment to use the default
os.Unsetenv(defaultTemplateDirectoryEnvVar)
_, err = loadPageTemplate("error")
if err != nil {
t.Fatalf("Failed to load error template: %v", err)
}
}
示例12: TestEnv
func TestEnv(t *testing.T) {
os.Setenv("STR", "helloworld")
os.Setenv("NUM", "42")
os.Setenv("BOOL", "true")
//config
type Config struct {
Str string
Num int
Bool bool
}
c := &Config{}
//flag example parse
if err := New(c).UseEnv().Process([]string{}); err != nil {
t.Fatal(err)
}
os.Unsetenv("STR")
os.Unsetenv("NUM")
os.Unsetenv("BOOL")
//check config is filled
check(t, c.Str, `helloworld`)
check(t, c.Num, 42)
check(t, c.Bool, true)
}
示例13: TestEnvConvert
func TestEnvConvert(t *testing.T) {
os.Setenv("TEST_PRUXY_1", "abc.com=127.0.0.1:8081,127.0.0.1:8082")
os.Setenv("TEST_PRUXY_2", "abc.com/abc/123=127.0.0.1")
defer os.Unsetenv("TEST_PRUXY_1")
defer os.Unsetenv("TEST_PRUXY_2")
p, _ := NewEnv("TEST_PRUXY_")
convertFunc := p.DefaultRequestConverter()
var convertTests = []struct {
in string
out string
}{
{"http://abc.com/a/b/", "http://127.0.0.1:8081/a/b/"},
{"http://abc.com/a/b", "http://127.0.0.1:8082/a/b"},
{"http://abc.com/abc/123/456/hi", "http://127.0.0.1/456/hi"},
}
for i, tt := range convertTests {
in, _ := http.NewRequest("GET", tt.in, nil)
out := copyRequest(in)
convertFunc(in, out)
if out.URL.String() != tt.out {
t.Errorf("%d expected %s, got %s", i, tt.out, out.URL.String())
}
}
}
示例14: TestShellToContainerWithUnit
func (s *S) TestShellToContainerWithUnit(c *check.C) {
transport := cmdtest.ConditionalTransport{
Transport: cmdtest.Transport{
Message: "",
Status: http.StatusOK,
},
CondFunc: func(req *http.Request) bool {
return req.Method == "GET" && req.URL.Path == "/apps/myapp"
},
}
guesser := cmdtest.FakeGuesser{Name: "myapp"}
server := httptest.NewServer(buildHandler([]byte("hello my friend\nglad to see you here\n")))
defer server.Close()
target := "http://" + server.Listener.Addr().String()
os.Setenv("TSURU_TARGET", target)
defer os.Unsetenv("TSURU_TARGET")
os.Setenv("TSURU_TOKEN", "abc123")
defer os.Unsetenv("TSURU_TOKEN")
var stdout, stderr, stdin bytes.Buffer
context := Context{
Args: []string{"containerid"},
Stdout: &stdout,
Stderr: &stderr,
Stdin: &stdin,
}
var command ShellToContainerCmd
command.GuessingCommand = GuessingCommand{G: &guesser}
err := command.Flags().Parse(true, []string{"-a", "myapp"})
c.Assert(err, check.IsNil)
mngr := NewManager("admin", "0.1", "admin-ver", &stdout, &stderr, nil, nil)
client := NewClient(&http.Client{Transport: &transport}, &context, mngr)
err = command.Run(&context, client)
c.Assert(err, check.IsNil)
c.Assert(stdout.String(), check.Equals, "hello my friend\nglad to see you here\n")
}
示例15: TestShellToContainerCmdConnectionRefused
func (s *S) TestShellToContainerCmdConnectionRefused(c *check.C) {
var buf bytes.Buffer
transport := cmdtest.ConditionalTransport{
Transport: cmdtest.Transport{
Message: "",
Status: http.StatusOK,
},
CondFunc: func(req *http.Request) bool {
return req.Method == "GET" && req.URL.Path == "/apps/cmd"
},
}
server := httptest.NewServer(nil)
addr := server.Listener.Addr().String()
server.Close()
os.Setenv("TSURU_TARGET", "http://"+addr)
defer os.Unsetenv("TSURU_TARGET")
os.Setenv("TSURU_TOKEN", "abc123")
defer os.Unsetenv("TSURU_TOKEN")
context := Context{
Args: []string{"af3332d"},
Stdout: &buf,
Stderr: &buf,
Stdin: &buf,
}
mngr := NewManager("admin", "0.1", "admin-ver", &buf, &buf, nil, nil)
client := NewClient(&http.Client{Transport: &transport}, &context, mngr)
var command ShellToContainerCmd
err := command.Run(&context, client)
c.Assert(err, check.NotNil)
}