func TestSharedCredentialsFilenameFromUserProfile(t *testing.T) { // Test setup os.Clearenv() // Test os.Setenv("HOME", "") os.Setenv("USERPROFILE", "") _, err1 := filename() assert.Error(t, err1, "Expect error when no HOME or USERPROFILE set") os.Clearenv() os.Setenv("USERPROFILE", "") os.Setenv("HOME", "hometest") file2, err2 := filename() assert.Nil(t, err2, "Expect no error when HOME is set") assert.Equal(t, "hometest/.aws/credentials", file2, "HOME dir does not match") os.Clearenv() os.Setenv("USERPROFILE", "usertest") os.Setenv("HOME", "") file3, err3 := filename() assert.Nil(t, err3, "Expect no error when USERPROFILE is set") assert.Equal(t, "usertest/.aws/credentials", file3, "HOME dir does not match") }
func TestNewConfig(t *testing.T) { os.Clearenv() conf := NewConfig("region") assert.NotNil(t, conf) assert.Equal(t, "region", conf.Region) assert.NotNil(t, conf.Credentials) creds, err := conf.Credentials.Get() assert.NotNil(t, err) auth = nil // from env setTestEnv() conf = NewConfig("region") assert.NotNil(t, conf) assert.Equal(t, "region", conf.Region) assert.NotNil(t, conf.Credentials) creds, err = conf.Credentials.Get() assert.Nil(t, err) assert.NotNil(t, creds) // from cache os.Clearenv() conf = NewConfig("region") assert.NotNil(t, conf) creds, err = conf.Credentials.Get() assert.Nil(t, err) assert.NotNil(t, creds) auth = nil }
func TestGofigure(t *testing.T) { Convey("Gofigure should set field values", t, func() { os.Clearenv() os.Args = []string{"gofigure", "-bind-addr", "abcdef"} var cfg MyConfigFoo err := Gofigure(&cfg) So(err, ShouldBeNil) So(cfg, ShouldNotBeNil) So(cfg.BindAddr, ShouldEqual, "abcdef") }) Convey("Gofigure should set multiple field values", t, func() { os.Clearenv() os.Args = []string{"gofigure", "-remote-addr", "foo", "-local-addr", "bar"} var cfg2 MyConfigBar err := Gofigure(&cfg2) So(err, ShouldBeNil) So(cfg2, ShouldNotBeNil) So(cfg2.RemoteAddr, ShouldEqual, "foo") So(cfg2.LocalAddr, ShouldEqual, "bar") }) Convey("Gofigure should support environment variables", t, func() { os.Clearenv() os.Args = []string{"gofigure"} os.Setenv("FOO_BIND_ADDR", "bindaddr") var cfg MyConfigFoo err := Gofigure(&cfg) So(err, ShouldBeNil) So(cfg, ShouldNotBeNil) So(cfg.BindAddr, ShouldEqual, "bindaddr") }) Convey("Gofigure should preserve order", t, func() { os.Clearenv() os.Args = []string{"gofigure", "-bind-addr", "abc"} os.Setenv("FOO_BIND_ADDR", "def") var cfg MyConfigFoo err := Gofigure(&cfg) So(err, ShouldBeNil) So(cfg, ShouldNotBeNil) So(cfg.BindAddr, ShouldEqual, "abc") os.Clearenv() os.Args = []string{"gofigure", "-remote-addr", "abc"} os.Setenv("BAR_REMOTE_ADDR", "def") var cfg2 MyConfigBar err = Gofigure(&cfg2) So(err, ShouldBeNil) So(cfg2, ShouldNotBeNil) So(cfg2.RemoteAddr, ShouldEqual, "def") }) clear() }
func TestNewConfig(t *testing.T) { assert := assert.New(t) os.Clearenv() Clear() var conf Config var awsConf *AWS.Config conf = NewConfig("region", "") awsConf = conf.Config assert.NotNil(awsConf) assert.Equal("region", awsConf.Region) assert.Empty(awsConf.Endpoint) assert.NotNil(awsConf.Credentials) creds, err := awsConf.Credentials.Get() assert.NotNil(err) // with endpoint Clear() conf = NewConfig("region", "endpoint") awsConf = conf.Config assert.NotNil(awsConf) assert.Equal("region", awsConf.Region) assert.Equal("endpoint", awsConf.Endpoint) assert.NotNil(awsConf.Credentials) creds, err = awsConf.Credentials.Get() assert.NotNil(err) // from env Clear() setTestEnv() conf = NewConfig("region", "") awsConf = conf.Config assert.NotNil(awsConf) assert.Equal("region", awsConf.Region) assert.NotNil(awsConf.Credentials) creds, err = awsConf.Credentials.Get() assert.Nil(err) assert.NotNil(creds) // from cache os.Clearenv() conf = NewConfig("region", "") awsConf = conf.Config assert.NotNil(awsConf) creds, err = awsConf.Credentials.Get() assert.Nil(err) assert.NotNil(creds) auth = nil }
func TestRequestScheme(t *testing.T) { req := &Request{} func() { os.Setenv("HTTPS", "on") defer os.Clearenv() actual := req.Scheme() expected := "https" if !reflect.DeepEqual(actual, expected) { t.Errorf("Expect %v, but %v", expected, actual) } }() func() { os.Setenv("HTTP_X_FORWARDED_SSL", "on") defer os.Clearenv() actual := req.Scheme() expected := "https" if !reflect.DeepEqual(actual, expected) { t.Errorf("Expect %v, but %v", expected, actual) } }() func() { os.Setenv("HTTP_X_FORWARDED_SCHEME", "file") defer os.Clearenv() actual := req.Scheme() expected := "file" if !reflect.DeepEqual(actual, expected) { t.Errorf("Expect %v, but %v", expected, actual) } }() func() { os.Setenv("HTTP_X_FORWARDED_PROTO", "gopher") defer os.Clearenv() actual := req.Scheme() expected := "gopher" if !reflect.DeepEqual(actual, expected) { t.Errorf("Expect %v, but %v", expected, actual) } os.Setenv("HTTP_X_FORWARDED_PROTO", "https, http, file") actual = req.Scheme() expected = "https" if !reflect.DeepEqual(actual, expected) { t.Errorf("Expect %v, but %v", expected, actual) } }() }
func TestCustomDecoderWithPointer(t *testing.T) { s := struct { Foo string Bar *bracketed }{} // Decode would panic when b is nil, so make sure it // has an initial value to replace. var b bracketed = "initial_value" s.Bar = &b os.Clearenv() os.Setenv("ENV_CONFIG_FOO", "foo") os.Setenv("ENV_CONFIG_BAR", "bar") if err := Process("env_config", &s); err != nil { t.Error(err.Error()) } if s.Foo != "foo" { t.Errorf("foo: expected 'foo', got %q", s.Foo) } if string(*s.Bar) != "[bar]" { t.Errorf("bar: expected '[bar]', got %q", string(*s.Bar)) } }
func main() { // 获取系统名字 fmt.Println(os.Hostname()) // 获取系统内存 fmt.Println(os.Getpagesize()) // 获取系统环境变量 for index, env := range os.Environ() { fmt.Println(index, " : ", env) } // 获取指定key的环境变量,环境变量不区分大小写 fmt.Println("当前系统目录为:", os.Getenv("windir")) // 设置环境变量 fmt.Println("cody的环境变量为:", os.Getenv("cody")) os.Setenv("Cody", "guo") fmt.Println("cody的环境变量为:", os.Getenv("cody")) // 删除所有环境变量 os.Clearenv() fmt.Println(os.Environ()) // 如果存在os.Exit()就不会执行defer // defer fmt.Println("我在退出吗?") // os.Exit(0) fmt.Println("程序已退出,不打印了...") fmt.Println(os.Getuid(), os.Getgid()) fmt.Println(os.Getgroups()) fmt.Println(os.Getpid(), os.Getppid()) fmt.Println(os.TempDir()) }
func TestAfterRetryRefreshCreds(t *testing.T) { os.Clearenv() credProvider := &mockCredsProvider{} svc := service.New(&aws.Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: aws.Int(1)}) svc.Handlers.Clear() svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) { r.Error = awserr.New("UnknownError", "", nil) r.HTTPResponse = &http.Response{StatusCode: 400} }) svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) { r.Error = awserr.New("ExpiredTokenException", "", nil) }) svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired") assert.False(t, credProvider.retrieveCalled) req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) req.Send() assert.True(t, svc.Config.Credentials.IsExpired()) assert.False(t, credProvider.retrieveCalled) _, err := svc.Config.Credentials.Get() assert.NoError(t, err) assert.True(t, credProvider.retrieveCalled) }
func Test_ItUnmarhsalsKeysFromEnvironmentalVariablesWithPrefix(t *testing.T) { prefix := "configr" keySplitter := configr.NewKeySplitter(".") envVars := NewEnvVars(prefix) configrKeys := []string{ "t2.t21", "t1", "t4.t41.t411.t4111", "t3.t31.t311", "t5", "t6", } expectedKeyValues := map[string]interface{}{ "t1": "1", "t2.t21": "2", "t3.t31.t311": "3.0", "t4.t41.t411.t4111": "true", "t5": "", } os.Clearenv() for key, value := range expectedKeyValues { os.Setenv(toEnvVarKey(prefix, key, keySplitter), value.(string)) } actual, err := envVars.Unmarshal(configrKeys, keySplitter) assert.Nil(t, err) assert.Equal(t, expectedKeyValues, actual) }
// Clear environment pollution introduced by lxc-start func setupEnv(args *InitArgs) error { // Get env var env []string content, err := ioutil.ReadFile(".dockerenv") if err != nil { return fmt.Errorf("Unable to load environment variables: %v", err) } if err := json.Unmarshal(content, &env); err != nil { return fmt.Errorf("Unable to unmarshal environment variables: %v", err) } // Propagate the plugin-specific container env variable env = append(env, "container="+os.Getenv("container")) args.Env = env os.Clearenv() for _, kv := range args.Env { parts := strings.SplitN(kv, "=", 2) if len(parts) == 1 { parts = append(parts, "") } os.Setenv(parts[0], parts[1]) } return nil }
func (r *EnvRestorer) Restore() { os.Clearenv() for k, v := range r.env { os.Setenv(k, v) } }
// StartInitialization loads a container by opening the pipe fd from the parent to read the configuration and state // This is a low level implementation detail of the reexec and should not be consumed externally func (l *LinuxFactory) StartInitialization() (err error) { pipefd, err := strconv.Atoi(os.Getenv("_LIBCONTAINER_INITPIPE")) if err != nil { return err } var ( pipe = os.NewFile(uintptr(pipefd), "pipe") it = initType(os.Getenv("_LIBCONTAINER_INITTYPE")) ) // clear the current process's environment to clean any libcontainer // specific env vars. os.Clearenv() defer func() { // if we have an error during the initialization of the container's init then send it back to the // parent process in the form of an initError. if err != nil { // ensure that any data sent from the parent is consumed so it doesn't // receive ECONNRESET when the child writes to the pipe. ioutil.ReadAll(pipe) if err := json.NewEncoder(pipe).Encode(newSystemError(err)); err != nil { panic(err) } } // ensure that this pipe is always closed pipe.Close() }() i, err := newContainerInit(it, pipe) if err != nil { return err } return i.Init() }
func TestAlternateVarNames(t *testing.T) { var s Specification os.Clearenv() os.Setenv("ENV_CONFIG_MULTI_WORD_VAR", "foo") os.Setenv("ENV_CONFIG_MULTI_WORD_VAR_WITH_ALT", "bar") os.Setenv("ENV_CONFIG_MULTI_WORD_VAR_WITH_LOWER_CASE_ALT", "baz") if err := Process("env_config", &s); err != nil { t.Error(err.Error()) } // Setting the alt version of the var in the environment has no effect if // the struct tag is not supplied if s.MultiWordVar != "" { t.Errorf("expected %q, got %q", "", s.MultiWordVar) } // Setting the alt version of the var in the environment correctly sets // the value if the struct tag IS supplied if s.MultiWordVarWithAlt != "bar" { t.Errorf("expected %q, got %q", "bar", s.MultiWordVarWithAlt) } // Alt value is not case sensitive and is treated as all uppercase if s.MultiWordVarWithLowerCaseAlt != "baz" { t.Errorf("expected %q, got %q", "baz", s.MultiWordVarWithLowerCaseAlt) } }
func TestValidateCredentialsHandlerError(t *testing.T) { os.Clearenv() creds, _ := ProfileCreds("example.ini", "missing", 10*time.Minute) svc := NewService(&Config{Credentials: creds}) svc.Handlers.Clear() svc.Handlers.Validate.PushBack(ValidateCredentialsHandler) req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) err := req.Build() assert.Error(t, err) assert.Equal(t, ErrMissingCredentials, err) // Now try without any credentials object at all svc = NewService(nil) svc.Handlers.Clear() svc.Handlers.Validate.PushBack(ValidateCredentialsHandler) req = NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) err = req.Build() assert.Error(t, err) assert.Equal(t, ErrMissingCredentials, err) }
// restore environment after each test func (s *authT) restoreEnv() { os.Clearenv() for _, kv := range s.env { l := strings.SplitN(kv, "=", 2) os.Setenv(l[0], l[1]) } }
func TestIsMaster(t *testing.T) { origEnv := make([]string, len(os.Environ())) copy(origEnv, os.Environ()) for _, v := range []struct { env string expect bool }{ {miyabi.FDEnvKey, false}, {"UNKNOWN_KEY", true}, } { func() { defer func() { os.Clearenv() for _, v := range origEnv { env := strings.SplitN(v, "=", 2) os.Setenv(env[0], env[1]) } }() if err := os.Setenv(v.env, "1"); err != nil { t.Error(err) return } actual := miyabi.IsMaster() expect := v.expect if !reflect.DeepEqual(actual, expect) { t.Errorf(`IsMaster() with %v=1 => %#v; want %#v`, v.env, actual, expect) } }() } }
func TestMySQL(t *testing.T) { os.Clearenv() os.Setenv("T_MYSQL_USER", "foo") os.Setenv("T_MYSQL_PASSWORD", "bar") os.Setenv("T_MYSQL_HOST", "h") os.Setenv("T_MYSQL_PORT", "p") os.Setenv("T_MYSQL_DB_NAME", "n") os.Setenv("T_MYSQL_LOCATION", "l") AppName = "t" mysql := ReadMySQL() if mysql == nil { t.Fatal("Expect *MySQL Type was nil") } _, err := mysql.DB() if err != nil { t.Fatal("Expect nil was %v", err) } mysqlStr := "foo:bar@tcp(h:p)/n?loc=l&parseTime=true" if mysql.String() != mysqlStr { t.Fatalf("Expect %v was %v", mysqlStr, mysql.String()) } }
func TestArrayField(t *testing.T) { Convey("String array should work", t, func() { os.Clearenv() os.Args = []string{ "gofigure", "-array-string-field", "foo", "-array-string-field", "bar", } var cfg MyConfigFull err := Gofigure(&cfg) So(err, ShouldBeNil) So(cfg, ShouldNotBeNil) So(cfg.ArrayStringField, ShouldNotBeNil) So(len(cfg.ArrayStringField), ShouldEqual, 2) So(cfg.ArrayStringField, ShouldResemble, []string{"foo", "bar"}) }) Convey("Int array should work", t, func() { os.Args = []string{ "gofigure", "-array-int-field", "1", "-array-int-field", "2", } var cfg MyConfigFull err := Gofigure(&cfg) So(err, ShouldBeNil) So(cfg, ShouldNotBeNil) So(cfg.ArrayIntField, ShouldNotBeNil) So(len(cfg.ArrayIntField), ShouldEqual, 2) So(cfg.ArrayIntField, ShouldResemble, []int{1, 2}) }) clear() }
func (s *S) TestSharedAuthNoCredentialsFile(c *C) { os.Clearenv() os.Setenv("AWS_PROFILE", "foo") os.Setenv("HOME", "/tmp") _, err := aws.SharedAuth() c.Assert(err, ErrorMatches, "Couldn't parse AWS credentials file") }
func newTestUserStore() (*UserStore, error) { os.Clearenv() os.Setenv("DB_URL", "rethinkdb://localhost:28015/test") os.Setenv("DB_POOLSIZE", "5") return NewUserStore() }
func restoreEnv(env []string) { os.Clearenv() for _, kvp := range env { kv := strings.SplitN(kvp, "=", 2) os.Setenv(kv[0], kv[1]) } }
// Resets os.Args and the default flag set. func resetForTesting(args ...string) { os.Clearenv() EnvPrefix = "" os.Args = append([]string{"cmd"}, args...) flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) }
func TestProcess(t *testing.T) { var s Specification os.Clearenv() os.Setenv("ENV_CONFIG_DEBUG", "true") os.Setenv("ENV_CONFIG_PORT", "8080") os.Setenv("ENV_CONFIG_RATE", "0.5") os.Setenv("ENV_CONFIG_USER", "Kelsey") os.Setenv("SERVICE_HOST", "127.0.0.1") err := Process("env_config", &s) if err != nil { t.Error(err.Error()) } if s.NoPrefixWithAlt != "127.0.0.1" { t.Errorf("expected %v, got %v", "127.0.0.1", s.NoPrefixWithAlt) } if !s.Debug { t.Errorf("expected %v, got %v", true, s.Debug) } if s.Port != 8080 { t.Errorf("expected %d, got %v", 8080, s.Port) } if s.Rate != 0.5 { t.Errorf("expected %f, got %v", 0.5, s.Rate) } if s.User != "Kelsey" { t.Errorf("expected %s, got %s", "Kelsey", s.User) } }
func TestNoPrefix(t *testing.T) { var s Specification os.Clearenv() os.Setenv("DEBUG", "true") os.Setenv("PORT", "8080") os.Setenv("RATE", "0.5") os.Setenv("USER", "Kelsey") os.Setenv("SERVICE_HOST", "127.0.0.1") os.Setenv("REQUIREDVAR", "foo") err := Process("", &s) if err != nil { t.Error(err.Error()) } if s.NoPrefixWithAlt != "127.0.0.1" { t.Errorf("expected %v, got %v", "127.0.0.1", s.NoPrefixWithAlt) } if !s.Debug { t.Errorf("expected %v, got %v", true, s.Debug) } if s.Port != 8080 { t.Errorf("expected %d, got %v", 8080, s.Port) } if s.Rate != 0.5 { t.Errorf("expected %f, got %v", 0.5, s.Rate) } if s.User != "Kelsey" { t.Errorf("expected %s, got %s", "Kelsey", s.User) } if s.RequiredVar != "foo" { t.Errorf("expected %s, got %s", "foo", s.RequiredVar) } }
func (s *S) TearDownTest(c *C) { os.Clearenv() for _, kv := range s.environ { l := strings.SplitN(kv, "=", 2) os.Setenv(l[0], l[1]) } }
func TestPopulate(t *testing.T) { var ( fs = flag.NewFlagSet("testing", flag.ExitOnError) foo = fs.String("foo", "", "") bar = fs.String("bar", "", "") baz = fs.String("baz", "", "") ) fs.Parse([]string{"-foo=foo", "-baz=baz"}) os.Clearenv() os.Setenv("DOORMAN_BAR", "bar") os.Setenv("DOORMAN_BAZ", "baz from env") if err := Populate(fs, "DOORMAN"); err != nil { t.Fatal(err) } if got, want := *foo, "foo"; got != want { t.Errorf("foo=%q; want %q", got, want) } if got, want := *bar, "bar"; got != want { t.Errorf("bar=%q; want %q", got, want) } if got, want := *baz, "baz"; got != want { t.Errorf("baz=%q; want %q", got, want) } }
func (s *MySuite) TestEnvPropertyIsNotSet(c *C) { os.Clearenv() actual := isPropertySet("foo") c.Assert(actual, Equals, false) }
func TestAfterRetryRefreshCreds(t *testing.T) { os.Clearenv() credProvider := &mockCredsProvider{} svc := NewService(&Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: 1}) svc.Handlers.Clear() svc.Handlers.ValidateResponse.PushBack(func(r *Request) { r.Error = &APIError{Code: "UnknownError"} r.HTTPResponse = &http.Response{StatusCode: 400} }) svc.Handlers.UnmarshalError.PushBack(func(r *Request) { r.Error = &APIError{Code: "ExpiredTokenException"} }) svc.Handlers.AfterRetry.PushBack(func(r *Request) { AfterRetryHandler(r) }) assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired") assert.False(t, credProvider.retreiveCalled) req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) req.Send() assert.True(t, svc.Config.Credentials.IsExpired()) assert.False(t, credProvider.retreiveCalled) _, err := svc.Config.Credentials.Get() assert.NoError(t, err) assert.True(t, credProvider.retreiveCalled) }
// StartInitialization loads a container by opening the pipe fd from the parent to read the configuration and state // This is a low level implementation detail of the reexec and should not be consumed externally func (l *LinuxFactory) StartInitialization() (err error) { fdStr := os.Getenv("_LIBCONTAINER_INITPIPE") pipefd, err := strconv.Atoi(fdStr) if err != nil { return fmt.Errorf("error converting env var _LIBCONTAINER_INITPIPE(%q) to an int: %s", fdStr, err) } var ( pipe = os.NewFile(uintptr(pipefd), "pipe") it = initType(os.Getenv("_LIBCONTAINER_INITTYPE")) ) defer pipe.Close() // clear the current process's environment to clean any libcontainer // specific env vars. os.Clearenv() i, err := newContainerInit(it, pipe) if err != nil { l.sendError(nil, pipe, err) return err } if err := i.Init(); err != nil { if !isExecError(err) { l.sendError(i, pipe, err) } return err } return nil }
func TestCredentialsNotSet(t *testing.T) { os.Clearenv() _, err := new(EnvironmentCredentialProvider).Credentials() if err == nil { t.Fail() } }