|
1 | 1 | package main |
2 | 2 |
|
3 | | -import "testing" |
| 3 | +import ( |
| 4 | + "github.com/stretchr/testify/require" |
| 5 | + "testing" |
| 6 | + //"fmt" |
| 7 | + "os" |
| 8 | +) |
| 9 | + |
| 10 | +func TestCanSetEnvironmentVariables(t *testing.T) { |
| 11 | + // backup env variables before the test if any was set |
| 12 | + backup := backupEnvironment() |
| 13 | + |
| 14 | + os.Unsetenv("HELLO") |
| 15 | + |
| 16 | + env := make(Environment) |
| 17 | + env["HELLO"] = EnvValue{"hello", false} |
| 18 | + |
| 19 | + setEnvironmentVariables(env) |
| 20 | + |
| 21 | + value, present := os.LookupEnv("HELLO") |
| 22 | + require.Equal(t, true, present) |
| 23 | + require.Equal(t, "hello", value) |
| 24 | + |
| 25 | + // restore backup variables |
| 26 | + restoreEnvironmentFromTheBackup(backup) |
| 27 | +} |
| 28 | + |
| 29 | +func TestCanRemoveEnvironmentVariables(t *testing.T) { |
| 30 | + // backup env variables before the test if any was set |
| 31 | + backup := backupEnvironment() |
| 32 | + |
| 33 | + os.Setenv("HELLO", "hello") |
| 34 | + |
| 35 | + env := make(Environment) |
| 36 | + env["HELLO"] = EnvValue{"hello", true} |
| 37 | + |
| 38 | + setEnvironmentVariables(env) |
| 39 | + _, present := os.LookupEnv("HELLO") |
| 40 | + require.Equal(t, false, present) |
| 41 | + |
| 42 | + // restore backup variables |
| 43 | + restoreEnvironmentFromTheBackup(backup) |
| 44 | +} |
4 | 45 |
|
5 | 46 | func TestRunCmd(t *testing.T) { |
6 | | - // Place your code here |
| 47 | + cmd := make([]string, 2) |
| 48 | + cmd[0] = "testdata/echo.sh" |
| 49 | + cmd[1] = "arg1" |
| 50 | + code := RunCmd(cmd, getAllValues()) |
| 51 | + require.Equal(t, 0, code) |
| 52 | +} |
| 53 | + |
| 54 | +func backupEnvironment() map[string]string { |
| 55 | + var testEnvNames = []string{"HELLO", "BAR", "FOO", "UNSET", "ADDED", "EMPTY"} |
| 56 | + result := make(map[string]string) |
| 57 | + |
| 58 | + for _, name := range testEnvNames { |
| 59 | + value, present := os.LookupEnv(name) |
| 60 | + if present == true { |
| 61 | + result[name] = value |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return result |
| 66 | +} |
| 67 | + |
| 68 | +func restoreEnvironmentFromTheBackup(env map[string]string) { |
| 69 | + for name, value := range env { |
| 70 | + os.Setenv(name, value) |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +func getAllValues() Environment { |
| 75 | + result := make(Environment) |
| 76 | + result["HELLO"] = EnvValue{"hello", false} |
| 77 | + result["BAR"] = EnvValue{"bar", false} |
| 78 | + result["FOO"] = EnvValue{"foo", false} |
| 79 | + result["UNSET"] = EnvValue{"unset", false} |
| 80 | + result["ADDED"] = EnvValue{"added", false} |
| 81 | + result["EMPTY"] = EnvValue{"empty", false} |
| 82 | + |
| 83 | + return result |
7 | 84 | } |
0 commit comments