safe_path_test.go
1 package tools 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 ) 8 9 func TestExpandHome(t *testing.T) { 10 home, err := os.UserHomeDir() 11 if err != nil { 12 t.Fatalf("cannot get home dir: %v", err) 13 } 14 15 tests := []struct { 16 input string 17 want string 18 }{ 19 {"", ""}, 20 {"/absolute/path", "/absolute/path"}, 21 {"relative/path", "relative/path"}, 22 {"~", home}, 23 {"~/Desktop/file.txt", filepath.Join(home, "Desktop/file.txt")}, 24 {"~/", filepath.Join(home, "")}, 25 {"~user/foo", "~user/foo"}, // ~user expansion not supported, returned as-is 26 } 27 28 for _, tt := range tests { 29 got := ExpandHome(tt.input) 30 if got != tt.want { 31 t.Errorf("ExpandHome(%q) = %q, want %q", tt.input, got, tt.want) 32 } 33 } 34 } 35 36 func TestIsPathUnderCWD_WithTilde(t *testing.T) { 37 // ~ paths should not be considered under CWD (unless CWD is home) 38 home, _ := os.UserHomeDir() 39 cwd, _ := os.Getwd() 40 41 // ~/Desktop is only under CWD if CWD is home and Desktop is a subdir 42 result := isPathUnderCWD("~/Desktop") 43 if cwd == home { 44 if !result { 45 t.Error("~/Desktop should be under CWD when CWD is home") 46 } 47 } else { 48 if result { 49 t.Error("~/Desktop should NOT be under CWD when CWD is not home") 50 } 51 } 52 }