Skip to content

Commit 643c6b3

Browse files
hirochachachaalexbrainman
authored andcommitted
path/filepath: make TestToNorm robust
The old code leaves garbages in a temporary directory because it cannot remove the current working directory on windows. The new code changes the directory before calling os.Remove. Furthermore, the old code assumes that ioutil.TempDir (os.TempDir) doesn't return a relative path nor an UNC path. If it isn't the case, the new code calls t.Fatal earlier for preventing ambiguous errors. Finally, the old code reassigns the variable which is used by the defer function. It could cause unexpected results, so avoid that. Change-Id: I5fc3902059ecaf18dc1341ecc4979d1206034cd7 Reviewed-on: https://go-review.googlesource.com/31790 TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Alex Brainman <[email protected]>
1 parent 02c1d8a commit 643c6b3

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

src/path/filepath/path_windows_test.go

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -352,38 +352,47 @@ func TestToNorm(t *testing.T) {
352352
{`{{tmp}}\test`, `FOO\BAR`, `foo\bar`},
353353
}
354354

355-
cwd, err := os.Getwd()
355+
tmp, err := ioutil.TempDir("", "testToNorm")
356356
if err != nil {
357357
t.Fatal(err)
358358
}
359359
defer func() {
360-
err := os.Chdir(cwd)
360+
err := os.RemoveAll(tmp)
361361
if err != nil {
362362
t.Fatal(err)
363363
}
364364
}()
365365

366-
tmp, err := ioutil.TempDir("", "testToNorm")
366+
// ioutil.TempDir might return "non-canonical" name.
367+
ctmp, err := filepath.EvalSymlinks(tmp)
367368
if err != nil {
368369
t.Fatal(err)
369370
}
370-
defer os.RemoveAll(tmp)
371371

372-
// ioutil.TempDir might return "non-canonical" name.
373-
tmp, err = filepath.EvalSymlinks(tmp)
372+
err = os.MkdirAll(strings.Replace(testPath, "{{tmp}}", ctmp, -1), 0777)
374373
if err != nil {
375374
t.Fatal(err)
376375
}
377376

378-
err = os.MkdirAll(strings.Replace(testPath, "{{tmp}}", tmp, -1), 0777)
377+
cwd, err := os.Getwd()
379378
if err != nil {
380379
t.Fatal(err)
381380
}
381+
defer func() {
382+
err := os.Chdir(cwd)
383+
if err != nil {
384+
t.Fatal(err)
385+
}
386+
}()
387+
388+
tmpVol := filepath.VolumeName(ctmp)
389+
if len(tmpVol) != 2 {
390+
t.Fatalf("unexpected temp volume name %q", tmpVol)
391+
}
382392

383-
tmpVol := filepath.VolumeName(tmp)
384-
tmpNoVol := tmp[len(tmpVol):]
393+
tmpNoVol := ctmp[len(tmpVol):]
385394

386-
replacer := strings.NewReplacer("{{tmp}}", tmp, "{{tmpvol}}", tmpVol, "{{tmpnovol}}", tmpNoVol)
395+
replacer := strings.NewReplacer("{{tmp}}", ctmp, "{{tmpvol}}", tmpVol, "{{tmpnovol}}", tmpNoVol)
387396

388397
for _, test := range testsDir {
389398
wd := replacer.Replace(test.wd)

0 commit comments

Comments
 (0)