|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +// TestAddToPath tests basic functionality of AddToPath. |
| 9 | +func TestAddToPath(t *testing.T) { |
| 10 | + tests := []struct { |
| 11 | + name string |
| 12 | + initialPath string |
| 13 | + pathToAdd string |
| 14 | + expected string |
| 15 | + }{ |
| 16 | + { |
| 17 | + name: "Add new path to existing PATH", |
| 18 | + initialPath: "/usr/bin" + pathSeparator + "/usr/local/bin", |
| 19 | + pathToAdd: "/opt/bin", |
| 20 | + expected: "/usr/bin" + pathSeparator + "/usr/local/bin" + pathSeparator + "/opt/bin", |
| 21 | + }, |
| 22 | + { |
| 23 | + name: "Path already exists in PATH", |
| 24 | + initialPath: "/usr/bin" + pathSeparator + "/usr/local/bin" + pathSeparator + "/opt/bin", |
| 25 | + pathToAdd: "/usr/bin", |
| 26 | + expected: "/usr/bin" + pathSeparator + "/usr/local/bin" + pathSeparator + "/opt/bin", |
| 27 | + }, |
| 28 | + { |
| 29 | + name: "Path exists as substring but not as the exact match", |
| 30 | + initialPath: "/usr/bin" + pathSeparator + "/usr/local/bin", |
| 31 | + pathToAdd: "/usr", |
| 32 | + expected: "/usr/bin" + pathSeparator + "/usr/local/bin" + pathSeparator + "/usr", |
| 33 | + }, |
| 34 | + // A zero-length (null) directory name in the value of PATH indicates the current directory. |
| 35 | + // Examples: PATH="", PATH=/usr/bin:, PATH=/usr/bin::/usr/local/bin |
| 36 | + { |
| 37 | + name: "Add path to empty PATH", |
| 38 | + initialPath: "", |
| 39 | + pathToAdd: "/usr/bin", |
| 40 | + expected: pathSeparator + "/usr/bin", |
| 41 | + }, |
| 42 | + { |
| 43 | + name: "Add empty path", |
| 44 | + initialPath: "/usr/bin", |
| 45 | + pathToAdd: "", |
| 46 | + expected: "/usr/bin" + pathSeparator, |
| 47 | + }, |
| 48 | + { |
| 49 | + name: "Single empty path exists in the middle of non-empty PATH", |
| 50 | + initialPath: "/usr/bin" + pathSeparator + pathSeparator + "/usr/local/bin", |
| 51 | + pathToAdd: "", |
| 52 | + expected: "/usr/bin" + pathSeparator + pathSeparator + "/usr/local/bin", |
| 53 | + }, |
| 54 | + { |
| 55 | + name: "Single empty path exists at the end of in non-empty PATH", |
| 56 | + initialPath: "/usr/bin" + pathSeparator, |
| 57 | + pathToAdd: "", |
| 58 | + expected: "/usr/bin" + pathSeparator, |
| 59 | + }, |
| 60 | + } |
| 61 | + |
| 62 | + for _, tt := range tests { |
| 63 | + t.Run(tt.name, func(t *testing.T) { |
| 64 | + // Use t.Setenv instead of os.Setenv() to restore the original PATH automatically. |
| 65 | + t.Setenv("PATH", tt.initialPath) |
| 66 | + err := AddToPath(tt.pathToAdd) |
| 67 | + if err != nil { |
| 68 | + t.Errorf("Expected no error from AddToPath() but got: %v", err) |
| 69 | + } |
| 70 | + |
| 71 | + newPath := os.Getenv("PATH") |
| 72 | + if newPath != tt.expected { |
| 73 | + t.Errorf("Expected PATH to be %q, but got %q", tt.expected, newPath) |
| 74 | + } |
| 75 | + }) |
| 76 | + } |
| 77 | +} |
0 commit comments