github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/src/pkg/os/exec/lp_windows_test.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package exec 6 7 import ( 8 "fmt" 9 "io" 10 "io/ioutil" 11 "os" 12 "path/filepath" 13 "strconv" 14 "strings" 15 "testing" 16 "text/template" 17 ) 18 19 type lookPathTest struct { 20 PATH string 21 PATHEXT string 22 files []string 23 searchFor string 24 fails bool // test is expected to fail 25 } 26 27 // PrefixPATH returns p.PATH with every element prefixed by prefix. 28 func (t lookPathTest) PrefixPATH(prefix string) string { 29 a := strings.SplitN(t.PATH, ";", -1) 30 for i := range a { 31 a[i] = filepath.Join(prefix, a[i]) 32 } 33 return strings.Join(a, ";") 34 } 35 36 var lookPathTests = []lookPathTest{ 37 { 38 PATHEXT: `.COM;.EXE;.BAT`, 39 PATH: `p1;p2`, 40 files: []string{`p1\a.exe`, `p2\a.exe`, `p2\a`}, 41 searchFor: `a`, 42 }, 43 { 44 PATHEXT: `.COM;.EXE;.BAT`, 45 PATH: `p1.dir;p2.dir`, 46 files: []string{`p1.dir\a`, `p2.dir\a.exe`}, 47 searchFor: `a`, 48 }, 49 { 50 PATHEXT: `.COM;.EXE;.BAT`, 51 PATH: `p1;p2`, 52 files: []string{`p1\a.exe`, `p2\a.exe`}, 53 searchFor: `a.exe`, 54 }, 55 { 56 PATHEXT: `.COM;.EXE;.BAT`, 57 PATH: `p1;p2`, 58 files: []string{`p1\a.exe`, `p2\b.exe`}, 59 searchFor: `b`, 60 }, 61 { 62 PATHEXT: `.COM;.EXE;.BAT`, 63 PATH: `p1;p2`, 64 files: []string{`p1\b`, `p2\a`}, 65 searchFor: `a`, 66 fails: true, // TODO(brainman): do not know why this fails 67 }, 68 // If the command name specifies a path, the shell searches 69 // the specified path for an executable file matching 70 // the command name. If a match is found, the external 71 // command (the executable file) executes. 72 { 73 PATHEXT: `.COM;.EXE;.BAT`, 74 PATH: `p1;p2`, 75 files: []string{`p1\a.exe`, `p2\a.exe`}, 76 searchFor: `p2\a`, 77 }, 78 // If the command name specifies a path, the shell searches 79 // the specified path for an executable file matching the command 80 // name. ... If no match is found, the shell reports an error 81 // and command processing completes. 82 { 83 PATHEXT: `.COM;.EXE;.BAT`, 84 PATH: `p1;p2`, 85 files: []string{`p1\b.exe`, `p2\a.exe`}, 86 searchFor: `p2\b`, 87 fails: true, 88 }, 89 // If the command name does not specify a path, the shell 90 // searches the current directory for an executable file 91 // matching the command name. If a match is found, the external 92 // command (the executable file) executes. 93 { 94 PATHEXT: `.COM;.EXE;.BAT`, 95 PATH: `p1;p2`, 96 files: []string{`a`, `p1\a.exe`, `p2\a.exe`}, 97 searchFor: `a`, 98 }, 99 // The shell now searches each directory specified by the 100 // PATH environment variable, in the order listed, for an 101 // executable file matching the command name. If a match 102 // is found, the external command (the executable file) executes. 103 { 104 PATHEXT: `.COM;.EXE;.BAT`, 105 PATH: `p1;p2`, 106 files: []string{`p1\a.exe`, `p2\a.exe`}, 107 searchFor: `a`, 108 }, 109 // The shell now searches each directory specified by the 110 // PATH environment variable, in the order listed, for an 111 // executable file matching the command name. If no match 112 // is found, the shell reports an error and command processing 113 // completes. 114 { 115 PATHEXT: `.COM;.EXE;.BAT`, 116 PATH: `p1;p2`, 117 files: []string{`p1\a.exe`, `p2\a.exe`}, 118 searchFor: `b`, 119 fails: true, 120 }, 121 // If the command name includes a file extension, the shell 122 // searches each directory for the exact file name specified 123 // by the command name. 124 { 125 PATHEXT: `.COM;.EXE;.BAT`, 126 PATH: `p1;p2`, 127 files: []string{`p1\a.exe`, `p2\a.exe`}, 128 searchFor: `a.exe`, 129 }, 130 { 131 PATHEXT: `.COM;.EXE;.BAT`, 132 PATH: `p1;p2`, 133 files: []string{`p1\a.exe`, `p2\a.exe`}, 134 searchFor: `a.com`, 135 fails: true, // includes extension and not exact file name match 136 }, 137 { 138 PATHEXT: `.COM;.EXE;.BAT`, 139 PATH: `p1`, 140 files: []string{`p1\a.exe.exe`}, 141 searchFor: `a.exe`, 142 }, 143 { 144 PATHEXT: `.COM;.BAT`, 145 PATH: `p1;p2`, 146 files: []string{`p1\a.exe`, `p2\a.exe`}, 147 searchFor: `a.exe`, 148 }, 149 // If the command name does not include a file extension, the shell 150 // adds the extensions listed in the PATHEXT environment variable, 151 // one by one, and searches the directory for that file name. Note 152 // that the shell tries all possible file extensions in a specific 153 // directory before moving on to search the next directory 154 // (if there is one). 155 { 156 PATHEXT: `.COM;.EXE`, 157 PATH: `p1;p2`, 158 files: []string{`p1\a.bat`, `p2\a.exe`}, 159 searchFor: `a`, 160 }, 161 { 162 PATHEXT: `.COM;.EXE;.BAT`, 163 PATH: `p1;p2`, 164 files: []string{`p1\a.bat`, `p2\a.exe`}, 165 searchFor: `a`, 166 }, 167 { 168 PATHEXT: `.COM;.EXE;.BAT`, 169 PATH: `p1;p2`, 170 files: []string{`p1\a.bat`, `p1\a.exe`, `p2\a.bat`, `p2\a.exe`}, 171 searchFor: `a`, 172 }, 173 { 174 PATHEXT: `.COM`, 175 PATH: `p1;p2`, 176 files: []string{`p1\a.bat`, `p2\a.exe`}, 177 searchFor: `a`, 178 fails: true, // tried all extensions in PATHEXT, but none matches 179 }, 180 } 181 182 func updateEnv(env []string, name, value string) []string { 183 for i, e := range env { 184 if strings.HasPrefix(strings.ToUpper(e), name+"=") { 185 env[i] = name + "=" + value 186 return env 187 } 188 } 189 return append(env, name+"="+value) 190 } 191 192 func installExe(t *testing.T, dest, src string) { 193 fsrc, err := os.Open(src) 194 if err != nil { 195 t.Fatal("os.Open failed: ", err) 196 } 197 defer fsrc.Close() 198 fdest, err := os.Create(dest) 199 if err != nil { 200 t.Fatal("os.Create failed: ", err) 201 } 202 defer fdest.Close() 203 _, err = io.Copy(fdest, fsrc) 204 if err != nil { 205 t.Fatal("io.Copy failed: ", err) 206 } 207 } 208 209 func installBat(t *testing.T, dest string) { 210 f, err := os.Create(dest) 211 if err != nil { 212 t.Fatalf("failed to create batch file: %v", err) 213 } 214 defer f.Close() 215 fmt.Fprintf(f, "@echo %s\n", dest) 216 } 217 218 func installProg(t *testing.T, dest, srcExe string) { 219 err := os.MkdirAll(filepath.Dir(dest), 0700) 220 if err != nil { 221 t.Fatal("os.MkdirAll failed: ", err) 222 } 223 if strings.ToLower(filepath.Ext(dest)) == ".bat" { 224 installBat(t, dest) 225 return 226 } 227 installExe(t, dest, srcExe) 228 } 229 230 func runProg(t *testing.T, test lookPathTest, env []string, dir string, args ...string) (string, error) { 231 cmd := Command(args[0], args[1:]...) 232 cmd.Env = env 233 cmd.Dir = dir 234 args[0] = filepath.Base(args[0]) 235 cmdText := fmt.Sprintf("%q command", strings.Join(args, " ")) 236 out, err := cmd.CombinedOutput() 237 if (err != nil) != test.fails { 238 if test.fails { 239 t.Fatalf("test=%+v: %s succeeded, but expected to fail", test, cmdText) 240 } 241 t.Fatalf("test=%+v: %s failed, but expected to succeed: %v - %v", test, cmdText, err, string(out)) 242 } 243 if err != nil { 244 return "", fmt.Errorf("test=%+v: %s failed: %v - %v", test, cmdText, err, string(out)) 245 } 246 // normalise program output 247 p := string(out) 248 // trim terminating \r and \n that batch file outputs 249 for len(p) > 0 && (p[len(p)-1] == '\n' || p[len(p)-1] == '\r') { 250 p = p[:len(p)-1] 251 } 252 if !filepath.IsAbs(p) { 253 return p, nil 254 } 255 if p[:len(dir)] != dir { 256 t.Fatalf("test=%+v: %s output is wrong: %q must have %q prefix", test, cmdText, p, dir) 257 } 258 return p[len(dir)+1:], nil 259 } 260 261 func testLookPath(t *testing.T, test lookPathTest, tmpdir, lookpathExe, printpathExe string) { 262 // Create files listed in test.files in tmp directory. 263 for i := range test.files { 264 installProg(t, filepath.Join(tmpdir, test.files[i]), printpathExe) 265 } 266 // Create environment with test.PATH and test.PATHEXT set. 267 env := os.Environ() 268 env = updateEnv(env, "PATH", test.PrefixPATH(tmpdir)) 269 env = updateEnv(env, "PATHEXT", test.PATHEXT) 270 // Run "cmd.exe /c test.searchFor" with new environment and 271 // work directory set. All candidates are copies of printpath.exe. 272 // These will output their program paths when run. 273 should, errCmd := runProg(t, test, env, tmpdir, "cmd", "/c", test.searchFor) 274 // Run the lookpath program with new environment and work directory set. 275 have, errLP := runProg(t, test, env, tmpdir, lookpathExe, test.searchFor) 276 // Compare results. 277 if errCmd == nil && errLP == nil { 278 // both succeeded 279 if should != have { 280 // t.Fatalf("test=%+v failed: expected to find %v, but found %v", test, should, have) 281 t.Fatalf("test=%+v failed: expected to find %q, but found %q", test, should, have) 282 } 283 return 284 } 285 if errCmd != nil && errLP != nil { 286 // both failed -> continue 287 return 288 } 289 if errCmd != nil { 290 t.Fatal(errCmd) 291 } 292 if errLP != nil { 293 t.Fatal(errLP) 294 } 295 } 296 297 func buildExe(t *testing.T, templ, dir, name string) string { 298 srcname := name + ".go" 299 f, err := os.Create(filepath.Join(dir, srcname)) 300 if err != nil { 301 t.Fatalf("failed to create source: %v", err) 302 } 303 err = template.Must(template.New("template").Parse(templ)).Execute(f, nil) 304 f.Close() 305 if err != nil { 306 t.Fatalf("failed to execute template: %v", err) 307 } 308 outname := name + ".exe" 309 cmd := Command("go", "build", "-o", outname, srcname) 310 cmd.Dir = dir 311 out, err := cmd.CombinedOutput() 312 if err != nil { 313 t.Fatalf("failed to build executable: %v - %v", err, string(out)) 314 } 315 return filepath.Join(dir, outname) 316 } 317 318 func TestLookPath(t *testing.T) { 319 tmp, err := ioutil.TempDir("", "TestLookPath") 320 if err != nil { 321 t.Fatal("TempDir failed: ", err) 322 } 323 defer os.RemoveAll(tmp) 324 325 // Create a Go program that uses LookPath to find executable passed as command line parameter. 326 lookpathExe := buildExe(t, lookpathSrc, tmp, "lookpath") 327 328 // Create a Go program that prints its own path. 329 printpathExe := buildExe(t, printpathSrc, tmp, "printpath") 330 331 // Run all tests. 332 for i, test := range lookPathTests { 333 dir := filepath.Join(tmp, "d"+strconv.Itoa(i)) 334 err := os.Mkdir(dir, 0700) 335 if err != nil { 336 t.Fatal("Mkdir failed: ", err) 337 } 338 testLookPath(t, test, dir, lookpathExe, printpathExe) 339 } 340 } 341 342 const lookpathSrc = ` 343 package main 344 345 import ( 346 "fmt" 347 "os" 348 "os/exec" 349 ) 350 351 func main() { 352 p, err := exec.LookPath(os.Args[1]) 353 if err != nil { 354 fmt.Printf("LookPath failed: %v\n", err) 355 os.Exit(1) 356 } 357 fmt.Print(p) 358 } 359 ` 360 361 const printpathSrc = ` 362 package main 363 364 import ( 365 "fmt" 366 "os" 367 "syscall" 368 "unicode/utf16" 369 "unsafe" 370 ) 371 372 func getMyName() (string, error) { 373 var sysproc = syscall.MustLoadDLL("kernel32.dll").MustFindProc("GetModuleFileNameW") 374 b := make([]uint16, syscall.MAX_PATH) 375 r, _, err := sysproc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))) 376 n := uint32(r) 377 if n == 0 { 378 return "", err 379 } 380 return string(utf16.Decode(b[0:n])), nil 381 } 382 383 func main() { 384 path, err := getMyName() 385 if err != nil { 386 fmt.Printf("getMyName failed: %v\n", err) 387 os.Exit(1) 388 } 389 fmt.Print(path) 390 } 391 `