os: implement and smoketest os.Clearenv

This commit is contained in:
Dan Kegel
2021-12-11 11:53:02 -08:00
committed by Ron Evans
parent e4f2b9c003
commit 51fc78c100
4 changed files with 49 additions and 0 deletions
+5
View File
@@ -25,6 +25,11 @@ func Unsetenv(key string) error {
return nil
}
// Clearenv deletes all environment variables.
func Clearenv() {
syscall.Clearenv()
}
func LookupEnv(key string) (string, bool) {
return syscall.Getenv(key)
}
+28
View File
@@ -46,6 +46,34 @@ func TestUnsetenv(t *testing.T) {
}
}
func TestClearenv(t *testing.T) {
const testKey = "GO_TEST_CLEARENV"
const testValue = "1"
// reset env
defer func(origEnv []string) {
for _, pair := range origEnv {
// Environment variables on Windows can begin with =
// https://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
i := strings.Index(pair[1:], "=") + 1
if err := Setenv(pair[:i], pair[i+1:]); err != nil {
t.Errorf("Setenv(%q, %q) failed during reset: %v", pair[:i], pair[i+1:], err)
}
}
}(Environ())
if err := Setenv(testKey, testValue); err != nil {
t.Fatalf("Setenv(%q, %q) failed: %v", testKey, testValue, err)
}
if _, ok := LookupEnv(testKey); !ok {
t.Errorf("Setenv(%q, %q) didn't set $%s", testKey, testValue, testKey)
}
Clearenv()
if val, ok := LookupEnv(testKey); ok {
t.Errorf("Clearenv() didn't clear $%s, remained with value %q", testKey, val)
}
}
func TestLookupEnv(t *testing.T) {
const smallpox = "SMALLPOX" // No one has smallpox.
value, ok := LookupEnv(smallpox) // Should not exist.