forked from juju/testing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosenv.go
114 lines (102 loc) · 2.51 KB
/
osenv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Copyright 2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package testing
import (
"os"
"runtime"
"strings"
gc "gopkg.in/check.v1"
)
// OsEnvSuite isolates the tests from the underlaying system environment.
// Environment variables are reset in SetUpTest and restored in TearDownTest.
type OsEnvSuite struct {
oldEnvironment map[string]string
}
// windowsVariables is a whitelist of windows environment variables
// that will be retained if found. Some of these variables are needed
// by standard go packages (such as os.TempDir()), as well as powershell
var windowsVariables = []string{
"ALLUSERSPROFILE",
"APPDATA",
"CommonProgramFiles",
"CommonProgramFiles(x86)",
"CommonProgramW6432",
"COMPUTERNAME",
"ComSpec",
"FP_NO_HOST_CHECK",
"HOMEDRIVE",
"HOMEPATH",
"LOCALAPPDATA",
"LOGONSERVER",
"NUMBER_OF_PROCESSORS",
"OS",
"Path",
"PATHEXT",
"PROCESSOR_ARCHITECTURE",
"PROCESSOR_IDENTIFIER",
"PROCESSOR_LEVEL",
"PROCESSOR_REVISION",
"ProgramData",
"ProgramFiles",
"ProgramFiles(x86)",
"ProgramW6432",
"PROMPT",
"PSModulePath",
"PUBLIC",
"SESSIONNAME",
"SystemDrive",
"SystemRoot",
"TEMP",
"TMP",
"USERDOMAIN",
"USERDOMAIN_ROAMINGPROFILE",
"USERNAME",
"USERPROFILE",
"windir",
}
// testingVariables is a whitelist of environment variables
// used to control Juju tests, that will be retained if found.
var testingVariables = []string{
"JUJU_MONGOD",
}
func (s *OsEnvSuite) setEnviron() {
var envList []string
switch runtime.GOOS {
case "windows":
envList = windowsVariables
default:
envList = []string{}
}
envList = append(envList, testingVariables...)
for _, envVar := range envList {
if value, ok := s.oldEnvironment[envVar]; ok {
os.Setenv(envVar, value)
}
}
}
// osDependendClearenv will clear the environment, and based on platform, will repopulate
// with whitelisted values previously saved in s.oldEnvironment
func (s *OsEnvSuite) osDependendClearenv() {
os.Clearenv()
// Currently, this will only do something if we are running on windows
s.setEnviron()
}
func (s *OsEnvSuite) SetUpSuite(c *gc.C) {
s.oldEnvironment = make(map[string]string)
for _, envvar := range os.Environ() {
parts := strings.SplitN(envvar, "=", 2)
s.oldEnvironment[parts[0]] = parts[1]
}
s.osDependendClearenv()
}
func (s *OsEnvSuite) TearDownSuite(c *gc.C) {
os.Clearenv()
for name, value := range s.oldEnvironment {
os.Setenv(name, value)
}
}
func (s *OsEnvSuite) SetUpTest(c *gc.C) {
s.osDependendClearenv()
}
func (s *OsEnvSuite) TearDownTest(c *gc.C) {
}