| 1 | |
| 2 | |
| 3 | |
| 4 | package envutil |
| 5 | |
| 6 | import ( |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "testing" |
| 10 | |
| 11 | "gotest.tools/v3/assert" |
| 12 | ) |
| 13 | |
| 14 | func TestAppendDirsToPath(t *testing.T) { |
| 15 | sep := string(filepath.ListSeparator) |
| 16 | existingDir := t.TempDir() |
| 17 | missingDir := filepath.Join(existingDir, "does-not-exist") |
| 18 | existingFile := filepath.Join(existingDir, "file.txt") |
| 19 | assert.NilError(t, os.WriteFile(existingFile, []byte("x"), 0o644)) |
| 20 | dummyCurrentPath := filepath.Join("dummy1", "dummy2") |
| 21 | |
| 22 | testCases := []struct { |
| 23 | name string |
| 24 | originalPATH string |
| 25 | dirs []string |
| 26 | expected string |
| 27 | }{ |
| 28 | { |
| 29 | name: "existing directory is appended", |
| 30 | originalPATH: dummyCurrentPath, |
| 31 | dirs: []string{existingDir}, |
| 32 | expected: dummyCurrentPath + sep + existingDir, |
| 33 | }, |
| 34 | { |
| 35 | name: "missing directory is not appended.", |
| 36 | originalPATH: dummyCurrentPath, |
| 37 | dirs: []string{missingDir}, |
| 38 | expected: dummyCurrentPath, |
| 39 | }, |
| 40 | { |
| 41 | name: "file is not appended", |
| 42 | originalPATH: dummyCurrentPath, |
| 43 | dirs: []string{existingFile}, |
| 44 | expected: dummyCurrentPath, |
| 45 | }, |
| 46 | { |
| 47 | name: "directory already in pathEnv is not appended again", |
| 48 | originalPATH: dummyCurrentPath + sep + existingDir, |
| 49 | dirs: []string{existingDir}, |
| 50 | expected: dummyCurrentPath + sep + existingDir, |
| 51 | }, |
| 52 | } |
| 53 | |
| 54 | for _, test := range testCases { |
| 55 | t.Run(test.name, func(t *testing.T) { |
| 56 | got := AppendDirsToPath(test.originalPATH, test.dirs) |
| 57 | assert.Equal(t, got, test.expected) |
| 58 | }) |
| 59 | } |
| 60 | } |