當前位置: 首頁>>代碼示例>>Golang>>正文


Golang os.Clearenv函數代碼示例

本文整理匯總了Golang中os.Clearenv函數的典型用法代碼示例。如果您正苦於以下問題:Golang Clearenv函數的具體用法?Golang Clearenv怎麽用?Golang Clearenv使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Clearenv函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestSharedCredentialsFilenameFromUserProfile

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")
}
開發者ID:aws,項目名稱:amazon-ssm-agent,代碼行數:30,代碼來源:shared_credentials_integ_test.go

示例2: TestNewConfig

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
}
開發者ID:kaneshin,項目名稱:aws-sdk-go-wrapper,代碼行數:32,代碼來源:auth_test.go

示例3: TestGofigure

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()
}
開發者ID:companieshouse,項目名稱:gofigure,代碼行數:55,代碼來源:gofigure_test.go

示例4: TestNewConfig

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
}
開發者ID:cnry,項目名稱:aws-sdk-go-wrapper,代碼行數:54,代碼來源:auth_test.go

示例5: TestRequestScheme

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)
		}
	}()
}
開發者ID:umisama,項目名稱:kocha,代碼行數:49,代碼來源:request_test.go

示例6: TestCustomDecoderWithPointer

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))
	}
}
開發者ID:Pendoragon,項目名稱:code,代碼行數:27,代碼來源:envconfig_test.go

示例7: main

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())

}
開發者ID:CodyGuo,項目名稱:Go-Cody,代碼行數:31,代碼來源:main.go

示例8: TestAfterRetryRefreshCreds

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)
}
開發者ID:eswdd,項目名稱:bosun,代碼行數:28,代碼來源:handlers_test.go

示例9: Test_ItUnmarhsalsKeysFromEnvironmentalVariablesWithPrefix

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)
}
開發者ID:adrianduke,項目名稱:configr,代碼行數:32,代碼來源:env_vars_test.go

示例10: setupEnv

// 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
}
開發者ID:balagopalraj,項目名稱:clearlinux,代碼行數:27,代碼來源:init.go

示例11: Restore

func (r *EnvRestorer) Restore() {
	os.Clearenv()

	for k, v := range r.env {
		os.Setenv(k, v)
	}
}
開發者ID:jszwedko,項目名稱:ec2-metadatafs,代碼行數:7,代碼來源:parser_test.go

示例12: StartInitialization

// 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()
}
開發者ID:souravbh,項目名稱:lattice-release,代碼行數:34,代碼來源:factory_linux.go

示例13: TestAlternateVarNames

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)
	}
}
開發者ID:blkrs,項目名稱:app-launcher-helper,代碼行數:27,代碼來源:envconfig_test.go

示例14: TestValidateCredentialsHandlerError

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)
}
開發者ID:dockerstack,項目名稱:amazon-ecs-agent,代碼行數:25,代碼來源:handler_functions_test.go

示例15: restoreEnv

// 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])
	}
}
開發者ID:elblivion,項目名稱:s3gof3r,代碼行數:8,代碼來源:auth_test.go


注:本文中的os.Clearenv函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。