...
Run Format

Source file src/path/filepath/path_test.go

Documentation: path/filepath

     1  // Copyright 2009 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 filepath_test
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"internal/testenv"
    11  	"io/ioutil"
    12  	"os"
    13  	"path/filepath"
    14  	"reflect"
    15  	"runtime"
    16  	"sort"
    17  	"strings"
    18  	"testing"
    19  )
    20  
    21  type PathTest struct {
    22  	path, result string
    23  }
    24  
    25  var cleantests = []PathTest{
    26  	// Already clean
    27  	{"abc", "abc"},
    28  	{"abc/def", "abc/def"},
    29  	{"a/b/c", "a/b/c"},
    30  	{".", "."},
    31  	{"..", ".."},
    32  	{"../..", "../.."},
    33  	{"../../abc", "../../abc"},
    34  	{"/abc", "/abc"},
    35  	{"/", "/"},
    36  
    37  	// Empty is current dir
    38  	{"", "."},
    39  
    40  	// Remove trailing slash
    41  	{"abc/", "abc"},
    42  	{"abc/def/", "abc/def"},
    43  	{"a/b/c/", "a/b/c"},
    44  	{"./", "."},
    45  	{"../", ".."},
    46  	{"../../", "../.."},
    47  	{"/abc/", "/abc"},
    48  
    49  	// Remove doubled slash
    50  	{"abc//def//ghi", "abc/def/ghi"},
    51  	{"//abc", "/abc"},
    52  	{"///abc", "/abc"},
    53  	{"//abc//", "/abc"},
    54  	{"abc//", "abc"},
    55  
    56  	// Remove . elements
    57  	{"abc/./def", "abc/def"},
    58  	{"/./abc/def", "/abc/def"},
    59  	{"abc/.", "abc"},
    60  
    61  	// Remove .. elements
    62  	{"abc/def/ghi/../jkl", "abc/def/jkl"},
    63  	{"abc/def/../ghi/../jkl", "abc/jkl"},
    64  	{"abc/def/..", "abc"},
    65  	{"abc/def/../..", "."},
    66  	{"/abc/def/../..", "/"},
    67  	{"abc/def/../../..", ".."},
    68  	{"/abc/def/../../..", "/"},
    69  	{"abc/def/../../../ghi/jkl/../../../mno", "../../mno"},
    70  	{"/../abc", "/abc"},
    71  
    72  	// Combinations
    73  	{"abc/./../def", "def"},
    74  	{"abc//./../def", "def"},
    75  	{"abc/../../././../def", "../../def"},
    76  }
    77  
    78  var wincleantests = []PathTest{
    79  	{`c:`, `c:.`},
    80  	{`c:\`, `c:\`},
    81  	{`c:\abc`, `c:\abc`},
    82  	{`c:abc\..\..\.\.\..\def`, `c:..\..\def`},
    83  	{`c:\abc\def\..\..`, `c:\`},
    84  	{`c:\..\abc`, `c:\abc`},
    85  	{`c:..\abc`, `c:..\abc`},
    86  	{`\`, `\`},
    87  	{`/`, `\`},
    88  	{`\\i\..\c$`, `\c$`},
    89  	{`\\i\..\i\c$`, `\i\c$`},
    90  	{`\\i\..\I\c$`, `\I\c$`},
    91  	{`\\host\share\foo\..\bar`, `\\host\share\bar`},
    92  	{`//host/share/foo/../baz`, `\\host\share\baz`},
    93  	{`\\a\b\..\c`, `\\a\b\c`},
    94  	{`\\a\b`, `\\a\b`},
    95  }
    96  
    97  func TestClean(t *testing.T) {
    98  	tests := cleantests
    99  	if runtime.GOOS == "windows" {
   100  		for i := range tests {
   101  			tests[i].result = filepath.FromSlash(tests[i].result)
   102  		}
   103  		tests = append(tests, wincleantests...)
   104  	}
   105  	for _, test := range tests {
   106  		if s := filepath.Clean(test.path); s != test.result {
   107  			t.Errorf("Clean(%q) = %q, want %q", test.path, s, test.result)
   108  		}
   109  		if s := filepath.Clean(test.result); s != test.result {
   110  			t.Errorf("Clean(%q) = %q, want %q", test.result, s, test.result)
   111  		}
   112  	}
   113  
   114  	if testing.Short() {
   115  		t.Skip("skipping malloc count in short mode")
   116  	}
   117  	if runtime.GOMAXPROCS(0) > 1 {
   118  		t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")
   119  		return
   120  	}
   121  
   122  	for _, test := range tests {
   123  		allocs := testing.AllocsPerRun(100, func() { filepath.Clean(test.result) })
   124  		if allocs > 0 {
   125  			t.Errorf("Clean(%q): %v allocs, want zero", test.result, allocs)
   126  		}
   127  	}
   128  }
   129  
   130  const sep = filepath.Separator
   131  
   132  var slashtests = []PathTest{
   133  	{"", ""},
   134  	{"/", string(sep)},
   135  	{"/a/b", string([]byte{sep, 'a', sep, 'b'})},
   136  	{"a//b", string([]byte{'a', sep, sep, 'b'})},
   137  }
   138  
   139  func TestFromAndToSlash(t *testing.T) {
   140  	for _, test := range slashtests {
   141  		if s := filepath.FromSlash(test.path); s != test.result {
   142  			t.Errorf("FromSlash(%q) = %q, want %q", test.path, s, test.result)
   143  		}
   144  		if s := filepath.ToSlash(test.result); s != test.path {
   145  			t.Errorf("ToSlash(%q) = %q, want %q", test.result, s, test.path)
   146  		}
   147  	}
   148  }
   149  
   150  type SplitListTest struct {
   151  	list   string
   152  	result []string
   153  }
   154  
   155  const lsep = filepath.ListSeparator
   156  
   157  var splitlisttests = []SplitListTest{
   158  	{"", []string{}},
   159  	{string([]byte{'a', lsep, 'b'}), []string{"a", "b"}},
   160  	{string([]byte{lsep, 'a', lsep, 'b'}), []string{"", "a", "b"}},
   161  }
   162  
   163  var winsplitlisttests = []SplitListTest{
   164  	// quoted
   165  	{`"a"`, []string{`a`}},
   166  
   167  	// semicolon
   168  	{`";"`, []string{`;`}},
   169  	{`"a;b"`, []string{`a;b`}},
   170  	{`";";`, []string{`;`, ``}},
   171  	{`;";"`, []string{``, `;`}},
   172  
   173  	// partially quoted
   174  	{`a";"b`, []string{`a;b`}},
   175  	{`a; ""b`, []string{`a`, ` b`}},
   176  	{`"a;b`, []string{`a;b`}},
   177  	{`""a;b`, []string{`a`, `b`}},
   178  	{`"""a;b`, []string{`a;b`}},
   179  	{`""""a;b`, []string{`a`, `b`}},
   180  	{`a";b`, []string{`a;b`}},
   181  	{`a;b";c`, []string{`a`, `b;c`}},
   182  	{`"a";b";c`, []string{`a`, `b;c`}},
   183  }
   184  
   185  func TestSplitList(t *testing.T) {
   186  	tests := splitlisttests
   187  	if runtime.GOOS == "windows" {
   188  		tests = append(tests, winsplitlisttests...)
   189  	}
   190  	for _, test := range tests {
   191  		if l := filepath.SplitList(test.list); !reflect.DeepEqual(l, test.result) {
   192  			t.Errorf("SplitList(%#q) = %#q, want %#q", test.list, l, test.result)
   193  		}
   194  	}
   195  }
   196  
   197  type SplitTest struct {
   198  	path, dir, file string
   199  }
   200  
   201  var unixsplittests = []SplitTest{
   202  	{"a/b", "a/", "b"},
   203  	{"a/b/", "a/b/", ""},
   204  	{"a/", "a/", ""},
   205  	{"a", "", "a"},
   206  	{"/", "/", ""},
   207  }
   208  
   209  var winsplittests = []SplitTest{
   210  	{`c:`, `c:`, ``},
   211  	{`c:/`, `c:/`, ``},
   212  	{`c:/foo`, `c:/`, `foo`},
   213  	{`c:/foo/bar`, `c:/foo/`, `bar`},
   214  	{`//host/share`, `//host/share`, ``},
   215  	{`//host/share/`, `//host/share/`, ``},
   216  	{`//host/share/foo`, `//host/share/`, `foo`},
   217  	{`\\host\share`, `\\host\share`, ``},
   218  	{`\\host\share\`, `\\host\share\`, ``},
   219  	{`\\host\share\foo`, `\\host\share\`, `foo`},
   220  }
   221  
   222  func TestSplit(t *testing.T) {
   223  	var splittests []SplitTest
   224  	splittests = unixsplittests
   225  	if runtime.GOOS == "windows" {
   226  		splittests = append(splittests, winsplittests...)
   227  	}
   228  	for _, test := range splittests {
   229  		if d, f := filepath.Split(test.path); d != test.dir || f != test.file {
   230  			t.Errorf("Split(%q) = %q, %q, want %q, %q", test.path, d, f, test.dir, test.file)
   231  		}
   232  	}
   233  }
   234  
   235  type JoinTest struct {
   236  	elem []string
   237  	path string
   238  }
   239  
   240  var jointests = []JoinTest{
   241  	// zero parameters
   242  	{[]string{}, ""},
   243  
   244  	// one parameter
   245  	{[]string{""}, ""},
   246  	{[]string{"/"}, "/"},
   247  	{[]string{"a"}, "a"},
   248  
   249  	// two parameters
   250  	{[]string{"a", "b"}, "a/b"},
   251  	{[]string{"a", ""}, "a"},
   252  	{[]string{"", "b"}, "b"},
   253  	{[]string{"/", "a"}, "/a"},
   254  	{[]string{"/", "a/b"}, "/a/b"},
   255  	{[]string{"/", ""}, "/"},
   256  	{[]string{"//", "a"}, "/a"},
   257  	{[]string{"/a", "b"}, "/a/b"},
   258  	{[]string{"a/", "b"}, "a/b"},
   259  	{[]string{"a/", ""}, "a"},
   260  	{[]string{"", ""}, ""},
   261  
   262  	// three parameters
   263  	{[]string{"/", "a", "b"}, "/a/b"},
   264  }
   265  
   266  var winjointests = []JoinTest{
   267  	{[]string{`directory`, `file`}, `directory\file`},
   268  	{[]string{`C:\Windows\`, `System32`}, `C:\Windows\System32`},
   269  	{[]string{`C:\Windows\`, ``}, `C:\Windows`},
   270  	{[]string{`C:\`, `Windows`}, `C:\Windows`},
   271  	{[]string{`C:`, `a`}, `C:a`},
   272  	{[]string{`C:`, `a\b`}, `C:a\b`},
   273  	{[]string{`C:`, `a`, `b`}, `C:a\b`},
   274  	{[]string{`C:.`, `a`}, `C:a`},
   275  	{[]string{`C:a`, `b`}, `C:a\b`},
   276  	{[]string{`C:a`, `b`, `d`}, `C:a\b\d`},
   277  	{[]string{`\\host\share`, `foo`}, `\\host\share\foo`},
   278  	{[]string{`\\host\share\foo`}, `\\host\share\foo`},
   279  	{[]string{`//host/share`, `foo/bar`}, `\\host\share\foo\bar`},
   280  	{[]string{`\`}, `\`},
   281  	{[]string{`\`, ``}, `\`},
   282  	{[]string{`\`, `a`}, `\a`},
   283  	{[]string{`\\`, `a`}, `\a`},
   284  	{[]string{`\`, `a`, `b`}, `\a\b`},
   285  	{[]string{`\\`, `a`, `b`}, `\a\b`},
   286  	{[]string{`\`, `\\a\b`, `c`}, `\a\b\c`},
   287  	{[]string{`\\a`, `b`, `c`}, `\a\b\c`},
   288  	{[]string{`\\a\`, `b`, `c`}, `\a\b\c`},
   289  }
   290  
   291  func TestJoin(t *testing.T) {
   292  	if runtime.GOOS == "windows" {
   293  		jointests = append(jointests, winjointests...)
   294  	}
   295  	for _, test := range jointests {
   296  		expected := filepath.FromSlash(test.path)
   297  		if p := filepath.Join(test.elem...); p != expected {
   298  			t.Errorf("join(%q) = %q, want %q", test.elem, p, expected)
   299  		}
   300  	}
   301  }
   302  
   303  type ExtTest struct {
   304  	path, ext string
   305  }
   306  
   307  var exttests = []ExtTest{
   308  	{"path.go", ".go"},
   309  	{"path.pb.go", ".go"},
   310  	{"a.dir/b", ""},
   311  	{"a.dir/b.go", ".go"},
   312  	{"a.dir/", ""},
   313  }
   314  
   315  func TestExt(t *testing.T) {
   316  	for _, test := range exttests {
   317  		if x := filepath.Ext(test.path); x != test.ext {
   318  			t.Errorf("Ext(%q) = %q, want %q", test.path, x, test.ext)
   319  		}
   320  	}
   321  }
   322  
   323  type Node struct {
   324  	name    string
   325  	entries []*Node // nil if the entry is a file
   326  	mark    int
   327  }
   328  
   329  var tree = &Node{
   330  	"testdata",
   331  	[]*Node{
   332  		{"a", nil, 0},
   333  		{"b", []*Node{}, 0},
   334  		{"c", nil, 0},
   335  		{
   336  			"d",
   337  			[]*Node{
   338  				{"x", nil, 0},
   339  				{"y", []*Node{}, 0},
   340  				{
   341  					"z",
   342  					[]*Node{
   343  						{"u", nil, 0},
   344  						{"v", nil, 0},
   345  					},
   346  					0,
   347  				},
   348  			},
   349  			0,
   350  		},
   351  	},
   352  	0,
   353  }
   354  
   355  func walkTree(n *Node, path string, f func(path string, n *Node)) {
   356  	f(path, n)
   357  	for _, e := range n.entries {
   358  		walkTree(e, filepath.Join(path, e.name), f)
   359  	}
   360  }
   361  
   362  func makeTree(t *testing.T) {
   363  	walkTree(tree, tree.name, func(path string, n *Node) {
   364  		if n.entries == nil {
   365  			fd, err := os.Create(path)
   366  			if err != nil {
   367  				t.Errorf("makeTree: %v", err)
   368  				return
   369  			}
   370  			fd.Close()
   371  		} else {
   372  			os.Mkdir(path, 0770)
   373  		}
   374  	})
   375  }
   376  
   377  func markTree(n *Node) { walkTree(n, "", func(path string, n *Node) { n.mark++ }) }
   378  
   379  func checkMarks(t *testing.T, report bool) {
   380  	walkTree(tree, tree.name, func(path string, n *Node) {
   381  		if n.mark != 1 && report {
   382  			t.Errorf("node %s mark = %d; expected 1", path, n.mark)
   383  		}
   384  		n.mark = 0
   385  	})
   386  }
   387  
   388  // Assumes that each node name is unique. Good enough for a test.
   389  // If clear is true, any incoming error is cleared before return. The errors
   390  // are always accumulated, though.
   391  func mark(info os.FileInfo, err error, errors *[]error, clear bool) error {
   392  	name := info.Name()
   393  	walkTree(tree, tree.name, func(path string, n *Node) {
   394  		if n.name == name {
   395  			n.mark++
   396  		}
   397  	})
   398  	if err != nil {
   399  		*errors = append(*errors, err)
   400  		if clear {
   401  			return nil
   402  		}
   403  		return err
   404  	}
   405  	return nil
   406  }
   407  
   408  func chtmpdir(t *testing.T) (restore func()) {
   409  	oldwd, err := os.Getwd()
   410  	if err != nil {
   411  		t.Fatalf("chtmpdir: %v", err)
   412  	}
   413  	d, err := ioutil.TempDir("", "test")
   414  	if err != nil {
   415  		t.Fatalf("chtmpdir: %v", err)
   416  	}
   417  	if err := os.Chdir(d); err != nil {
   418  		t.Fatalf("chtmpdir: %v", err)
   419  	}
   420  	return func() {
   421  		if err := os.Chdir(oldwd); err != nil {
   422  			t.Fatalf("chtmpdir: %v", err)
   423  		}
   424  		os.RemoveAll(d)
   425  	}
   426  }
   427  
   428  func TestWalk(t *testing.T) {
   429  	if runtime.GOOS == "darwin" {
   430  		switch runtime.GOARCH {
   431  		case "arm", "arm64":
   432  			restore := chtmpdir(t)
   433  			defer restore()
   434  		}
   435  	}
   436  
   437  	tmpDir, err := ioutil.TempDir("", "TestWalk")
   438  	if err != nil {
   439  		t.Fatal("creating temp dir:", err)
   440  	}
   441  	defer os.RemoveAll(tmpDir)
   442  
   443  	origDir, err := os.Getwd()
   444  	if err != nil {
   445  		t.Fatal("finding working dir:", err)
   446  	}
   447  	if err = os.Chdir(tmpDir); err != nil {
   448  		t.Fatal("entering temp dir:", err)
   449  	}
   450  	defer os.Chdir(origDir)
   451  
   452  	makeTree(t)
   453  	errors := make([]error, 0, 10)
   454  	clear := true
   455  	markFn := func(path string, info os.FileInfo, err error) error {
   456  		return mark(info, err, &errors, clear)
   457  	}
   458  	// Expect no errors.
   459  	err = filepath.Walk(tree.name, markFn)
   460  	if err != nil {
   461  		t.Fatalf("no error expected, found: %s", err)
   462  	}
   463  	if len(errors) != 0 {
   464  		t.Fatalf("unexpected errors: %s", errors)
   465  	}
   466  	checkMarks(t, true)
   467  	errors = errors[0:0]
   468  
   469  	// Test permission errors. Only possible if we're not root
   470  	// and only on some file systems (AFS, FAT).  To avoid errors during
   471  	// all.bash on those file systems, skip during go test -short.
   472  	if os.Getuid() > 0 && !testing.Short() {
   473  		// introduce 2 errors: chmod top-level directories to 0
   474  		os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0)
   475  		os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0)
   476  
   477  		// 3) capture errors, expect two.
   478  		// mark respective subtrees manually
   479  		markTree(tree.entries[1])
   480  		markTree(tree.entries[3])
   481  		// correct double-marking of directory itself
   482  		tree.entries[1].mark--
   483  		tree.entries[3].mark--
   484  		err := filepath.Walk(tree.name, markFn)
   485  		if err != nil {
   486  			t.Fatalf("expected no error return from Walk, got %s", err)
   487  		}
   488  		if len(errors) != 2 {
   489  			t.Errorf("expected 2 errors, got %d: %s", len(errors), errors)
   490  		}
   491  		// the inaccessible subtrees were marked manually
   492  		checkMarks(t, true)
   493  		errors = errors[0:0]
   494  
   495  		// 4) capture errors, stop after first error.
   496  		// mark respective subtrees manually
   497  		markTree(tree.entries[1])
   498  		markTree(tree.entries[3])
   499  		// correct double-marking of directory itself
   500  		tree.entries[1].mark--
   501  		tree.entries[3].mark--
   502  		clear = false // error will stop processing
   503  		err = filepath.Walk(tree.name, markFn)
   504  		if err == nil {
   505  			t.Fatalf("expected error return from Walk")
   506  		}
   507  		if len(errors) != 1 {
   508  			t.Errorf("expected 1 error, got %d: %s", len(errors), errors)
   509  		}
   510  		// the inaccessible subtrees were marked manually
   511  		checkMarks(t, false)
   512  		errors = errors[0:0]
   513  
   514  		// restore permissions
   515  		os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0770)
   516  		os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0770)
   517  	}
   518  }
   519  
   520  func touch(t *testing.T, name string) {
   521  	f, err := os.Create(name)
   522  	if err != nil {
   523  		t.Fatal(err)
   524  	}
   525  	if err := f.Close(); err != nil {
   526  		t.Fatal(err)
   527  	}
   528  }
   529  
   530  func TestWalkSkipDirOnFile(t *testing.T) {
   531  	td, err := ioutil.TempDir("", "walktest")
   532  	if err != nil {
   533  		t.Fatal(err)
   534  	}
   535  	defer os.RemoveAll(td)
   536  
   537  	if err := os.MkdirAll(filepath.Join(td, "dir"), 0755); err != nil {
   538  		t.Fatal(err)
   539  	}
   540  	touch(t, filepath.Join(td, "dir/foo1"))
   541  	touch(t, filepath.Join(td, "dir/foo2"))
   542  
   543  	sawFoo2 := false
   544  	walker := func(path string, info os.FileInfo, err error) error {
   545  		if strings.HasSuffix(path, "foo2") {
   546  			sawFoo2 = true
   547  		}
   548  		if strings.HasSuffix(path, "foo1") {
   549  			return filepath.SkipDir
   550  		}
   551  		return nil
   552  	}
   553  
   554  	err = filepath.Walk(td, walker)
   555  	if err != nil {
   556  		t.Fatal(err)
   557  	}
   558  	if sawFoo2 {
   559  		t.Errorf("SkipDir on file foo1 did not block processing of foo2")
   560  	}
   561  
   562  	err = filepath.Walk(filepath.Join(td, "dir"), walker)
   563  	if err != nil {
   564  		t.Fatal(err)
   565  	}
   566  	if sawFoo2 {
   567  		t.Errorf("SkipDir on file foo1 did not block processing of foo2")
   568  	}
   569  }
   570  
   571  func TestWalkFileError(t *testing.T) {
   572  	td, err := ioutil.TempDir("", "walktest")
   573  	if err != nil {
   574  		t.Fatal(err)
   575  	}
   576  	defer os.RemoveAll(td)
   577  
   578  	touch(t, filepath.Join(td, "foo"))
   579  	touch(t, filepath.Join(td, "bar"))
   580  	dir := filepath.Join(td, "dir")
   581  	if err := os.MkdirAll(filepath.Join(td, "dir"), 0755); err != nil {
   582  		t.Fatal(err)
   583  	}
   584  	touch(t, filepath.Join(dir, "baz"))
   585  	touch(t, filepath.Join(dir, "stat-error"))
   586  	defer func() {
   587  		*filepath.LstatP = os.Lstat
   588  	}()
   589  	statErr := errors.New("some stat error")
   590  	*filepath.LstatP = func(path string) (os.FileInfo, error) {
   591  		if strings.HasSuffix(path, "stat-error") {
   592  			return nil, statErr
   593  		}
   594  		return os.Lstat(path)
   595  	}
   596  	got := map[string]error{}
   597  	err = filepath.Walk(td, func(path string, fi os.FileInfo, err error) error {
   598  		rel, _ := filepath.Rel(td, path)
   599  		got[filepath.ToSlash(rel)] = err
   600  		return nil
   601  	})
   602  	if err != nil {
   603  		t.Errorf("Walk error: %v", err)
   604  	}
   605  	want := map[string]error{
   606  		".":              nil,
   607  		"foo":            nil,
   608  		"bar":            nil,
   609  		"dir":            nil,
   610  		"dir/baz":        nil,
   611  		"dir/stat-error": statErr,
   612  	}
   613  	if !reflect.DeepEqual(got, want) {
   614  		t.Errorf("Walked %#v; want %#v", got, want)
   615  	}
   616  }
   617  
   618  var basetests = []PathTest{
   619  	{"", "."},
   620  	{".", "."},
   621  	{"/.", "."},
   622  	{"/", "/"},
   623  	{"////", "/"},
   624  	{"x/", "x"},
   625  	{"abc", "abc"},
   626  	{"abc/def", "def"},
   627  	{"a/b/.x", ".x"},
   628  	{"a/b/c.", "c."},
   629  	{"a/b/c.x", "c.x"},
   630  }
   631  
   632  var winbasetests = []PathTest{
   633  	{`c:\`, `\`},
   634  	{`c:.`, `.`},
   635  	{`c:\a\b`, `b`},
   636  	{`c:a\b`, `b`},
   637  	{`c:a\b\c`, `c`},
   638  	{`\\host\share\`, `\`},
   639  	{`\\host\share\a`, `a`},
   640  	{`\\host\share\a\b`, `b`},
   641  }
   642  
   643  func TestBase(t *testing.T) {
   644  	tests := basetests
   645  	if runtime.GOOS == "windows" {
   646  		// make unix tests work on windows
   647  		for i := range tests {
   648  			tests[i].result = filepath.Clean(tests[i].result)
   649  		}
   650  		// add windows specific tests
   651  		tests = append(tests, winbasetests...)
   652  	}
   653  	for _, test := range tests {
   654  		if s := filepath.Base(test.path); s != test.result {
   655  			t.Errorf("Base(%q) = %q, want %q", test.path, s, test.result)
   656  		}
   657  	}
   658  }
   659  
   660  var dirtests = []PathTest{
   661  	{"", "."},
   662  	{".", "."},
   663  	{"/.", "/"},
   664  	{"/", "/"},
   665  	{"////", "/"},
   666  	{"/foo", "/"},
   667  	{"x/", "x"},
   668  	{"abc", "."},
   669  	{"abc/def", "abc"},
   670  	{"a/b/.x", "a/b"},
   671  	{"a/b/c.", "a/b"},
   672  	{"a/b/c.x", "a/b"},
   673  }
   674  
   675  var windirtests = []PathTest{
   676  	{`c:\`, `c:\`},
   677  	{`c:.`, `c:.`},
   678  	{`c:\a\b`, `c:\a`},
   679  	{`c:a\b`, `c:a`},
   680  	{`c:a\b\c`, `c:a\b`},
   681  	{`\\host\share`, `\\host\share`},
   682  	{`\\host\share\`, `\\host\share\`},
   683  	{`\\host\share\a`, `\\host\share\`},
   684  	{`\\host\share\a\b`, `\\host\share\a`},
   685  }
   686  
   687  func TestDir(t *testing.T) {
   688  	tests := dirtests
   689  	if runtime.GOOS == "windows" {
   690  		// make unix tests work on windows
   691  		for i := range tests {
   692  			tests[i].result = filepath.Clean(tests[i].result)
   693  		}
   694  		// add windows specific tests
   695  		tests = append(tests, windirtests...)
   696  	}
   697  	for _, test := range tests {
   698  		if s := filepath.Dir(test.path); s != test.result {
   699  			t.Errorf("Dir(%q) = %q, want %q", test.path, s, test.result)
   700  		}
   701  	}
   702  }
   703  
   704  type IsAbsTest struct {
   705  	path  string
   706  	isAbs bool
   707  }
   708  
   709  var isabstests = []IsAbsTest{
   710  	{"", false},
   711  	{"/", true},
   712  	{"/usr/bin/gcc", true},
   713  	{"..", false},
   714  	{"/a/../bb", true},
   715  	{".", false},
   716  	{"./", false},
   717  	{"lala", false},
   718  }
   719  
   720  var winisabstests = []IsAbsTest{
   721  	{`C:\`, true},
   722  	{`c\`, false},
   723  	{`c::`, false},
   724  	{`c:`, false},
   725  	{`/`, false},
   726  	{`\`, false},
   727  	{`\Windows`, false},
   728  	{`c:a\b`, false},
   729  	{`c:\a\b`, true},
   730  	{`c:/a/b`, true},
   731  	{`\\host\share\foo`, true},
   732  	{`//host/share/foo/bar`, true},
   733  }
   734  
   735  func TestIsAbs(t *testing.T) {
   736  	var tests []IsAbsTest
   737  	if runtime.GOOS == "windows" {
   738  		tests = append(tests, winisabstests...)
   739  		// All non-windows tests should fail, because they have no volume letter.
   740  		for _, test := range isabstests {
   741  			tests = append(tests, IsAbsTest{test.path, false})
   742  		}
   743  		// All non-windows test should work as intended if prefixed with volume letter.
   744  		for _, test := range isabstests {
   745  			tests = append(tests, IsAbsTest{"c:" + test.path, test.isAbs})
   746  		}
   747  	} else {
   748  		tests = isabstests
   749  	}
   750  
   751  	for _, test := range tests {
   752  		if r := filepath.IsAbs(test.path); r != test.isAbs {
   753  			t.Errorf("IsAbs(%q) = %v, want %v", test.path, r, test.isAbs)
   754  		}
   755  	}
   756  }
   757  
   758  type EvalSymlinksTest struct {
   759  	// If dest is empty, the path is created; otherwise the dest is symlinked to the path.
   760  	path, dest string
   761  }
   762  
   763  var EvalSymlinksTestDirs = []EvalSymlinksTest{
   764  	{"test", ""},
   765  	{"test/dir", ""},
   766  	{"test/dir/link3", "../../"},
   767  	{"test/link1", "../test"},
   768  	{"test/link2", "dir"},
   769  	{"test/linkabs", "/"},
   770  }
   771  
   772  var EvalSymlinksTests = []EvalSymlinksTest{
   773  	{"test", "test"},
   774  	{"test/dir", "test/dir"},
   775  	{"test/dir/../..", "."},
   776  	{"test/link1", "test"},
   777  	{"test/link2", "test/dir"},
   778  	{"test/link1/dir", "test/dir"},
   779  	{"test/link2/..", "test"},
   780  	{"test/dir/link3", "."},
   781  	{"test/link2/link3/test", "test"},
   782  	{"test/linkabs", "/"},
   783  }
   784  
   785  // simpleJoin builds a file name from the directory and path.
   786  // It does not use Join because we don't want ".." to be evaluated.
   787  func simpleJoin(dir, path string) string {
   788  	return dir + string(filepath.Separator) + path
   789  }
   790  
   791  func testEvalSymlinks(t *testing.T, path, want string) {
   792  	have, err := filepath.EvalSymlinks(path)
   793  	if err != nil {
   794  		t.Errorf("EvalSymlinks(%q) error: %v", path, err)
   795  		return
   796  	}
   797  	if filepath.Clean(have) != filepath.Clean(want) {
   798  		t.Errorf("EvalSymlinks(%q) returns %q, want %q", path, have, want)
   799  	}
   800  }
   801  
   802  func testEvalSymlinksAfterChdir(t *testing.T, wd, path, want string) {
   803  	cwd, err := os.Getwd()
   804  	if err != nil {
   805  		t.Fatal(err)
   806  	}
   807  	defer func() {
   808  		err := os.Chdir(cwd)
   809  		if err != nil {
   810  			t.Fatal(err)
   811  		}
   812  	}()
   813  
   814  	err = os.Chdir(wd)
   815  	if err != nil {
   816  		t.Fatal(err)
   817  	}
   818  
   819  	have, err := filepath.EvalSymlinks(path)
   820  	if err != nil {
   821  		t.Errorf("EvalSymlinks(%q) in %q directory error: %v", path, wd, err)
   822  		return
   823  	}
   824  	if filepath.Clean(have) != filepath.Clean(want) {
   825  		t.Errorf("EvalSymlinks(%q) in %q directory returns %q, want %q", path, wd, have, want)
   826  	}
   827  }
   828  
   829  func TestEvalSymlinks(t *testing.T) {
   830  	testenv.MustHaveSymlink(t)
   831  
   832  	tmpDir, err := ioutil.TempDir("", "evalsymlink")
   833  	if err != nil {
   834  		t.Fatal("creating temp dir:", err)
   835  	}
   836  	defer os.RemoveAll(tmpDir)
   837  
   838  	// /tmp may itself be a symlink! Avoid the confusion, although
   839  	// it means trusting the thing we're testing.
   840  	tmpDir, err = filepath.EvalSymlinks(tmpDir)
   841  	if err != nil {
   842  		t.Fatal("eval symlink for tmp dir:", err)
   843  	}
   844  
   845  	// Create the symlink farm using relative paths.
   846  	for _, d := range EvalSymlinksTestDirs {
   847  		var err error
   848  		path := simpleJoin(tmpDir, d.path)
   849  		if d.dest == "" {
   850  			err = os.Mkdir(path, 0755)
   851  		} else {
   852  			err = os.Symlink(d.dest, path)
   853  		}
   854  		if err != nil {
   855  			t.Fatal(err)
   856  		}
   857  	}
   858  
   859  	// Evaluate the symlink farm.
   860  	for _, test := range EvalSymlinksTests {
   861  		path := simpleJoin(tmpDir, test.path)
   862  
   863  		dest := simpleJoin(tmpDir, test.dest)
   864  		if filepath.IsAbs(test.dest) || os.IsPathSeparator(test.dest[0]) {
   865  			dest = test.dest
   866  		}
   867  		testEvalSymlinks(t, path, dest)
   868  
   869  		// test EvalSymlinks(".")
   870  		testEvalSymlinksAfterChdir(t, path, ".", ".")
   871  
   872  		// test EvalSymlinks("C:.") on Windows
   873  		if runtime.GOOS == "windows" {
   874  			volDot := filepath.VolumeName(tmpDir) + "."
   875  			testEvalSymlinksAfterChdir(t, path, volDot, volDot)
   876  		}
   877  
   878  		// test EvalSymlinks(".."+path)
   879  		dotdotPath := simpleJoin("..", test.dest)
   880  		if filepath.IsAbs(test.dest) || os.IsPathSeparator(test.dest[0]) {
   881  			dotdotPath = test.dest
   882  		}
   883  		testEvalSymlinksAfterChdir(t,
   884  			simpleJoin(tmpDir, "test"),
   885  			simpleJoin("..", test.path),
   886  			dotdotPath)
   887  
   888  		// test EvalSymlinks(p) where p is relative path
   889  		testEvalSymlinksAfterChdir(t, tmpDir, test.path, test.dest)
   890  	}
   891  }
   892  
   893  func TestEvalSymlinksIsNotExist(t *testing.T) {
   894  	testenv.MustHaveSymlink(t)
   895  
   896  	defer chtmpdir(t)()
   897  
   898  	_, err := filepath.EvalSymlinks("notexist")
   899  	if !os.IsNotExist(err) {
   900  		t.Errorf("expected the file is not found, got %v\n", err)
   901  	}
   902  
   903  	err = os.Symlink("notexist", "link")
   904  	if err != nil {
   905  		t.Fatal(err)
   906  	}
   907  	defer os.Remove("link")
   908  
   909  	_, err = filepath.EvalSymlinks("link")
   910  	if !os.IsNotExist(err) {
   911  		t.Errorf("expected the file is not found, got %v\n", err)
   912  	}
   913  }
   914  
   915  func TestIssue13582(t *testing.T) {
   916  	testenv.MustHaveSymlink(t)
   917  
   918  	tmpDir, err := ioutil.TempDir("", "issue13582")
   919  	if err != nil {
   920  		t.Fatal(err)
   921  	}
   922  	defer os.RemoveAll(tmpDir)
   923  
   924  	dir := filepath.Join(tmpDir, "dir")
   925  	err = os.Mkdir(dir, 0755)
   926  	if err != nil {
   927  		t.Fatal(err)
   928  	}
   929  	linkToDir := filepath.Join(tmpDir, "link_to_dir")
   930  	err = os.Symlink(dir, linkToDir)
   931  	if err != nil {
   932  		t.Fatal(err)
   933  	}
   934  	file := filepath.Join(linkToDir, "file")
   935  	err = ioutil.WriteFile(file, nil, 0644)
   936  	if err != nil {
   937  		t.Fatal(err)
   938  	}
   939  	link1 := filepath.Join(linkToDir, "link1")
   940  	err = os.Symlink(file, link1)
   941  	if err != nil {
   942  		t.Fatal(err)
   943  	}
   944  	link2 := filepath.Join(linkToDir, "link2")
   945  	err = os.Symlink(link1, link2)
   946  	if err != nil {
   947  		t.Fatal(err)
   948  	}
   949  
   950  	// /tmp may itself be a symlink!
   951  	realTmpDir, err := filepath.EvalSymlinks(tmpDir)
   952  	if err != nil {
   953  		t.Fatal(err)
   954  	}
   955  	realDir := filepath.Join(realTmpDir, "dir")
   956  	realFile := filepath.Join(realDir, "file")
   957  
   958  	tests := []struct {
   959  		path, want string
   960  	}{
   961  		{dir, realDir},
   962  		{linkToDir, realDir},
   963  		{file, realFile},
   964  		{link1, realFile},
   965  		{link2, realFile},
   966  	}
   967  	for i, test := range tests {
   968  		have, err := filepath.EvalSymlinks(test.path)
   969  		if err != nil {
   970  			t.Fatal(err)
   971  		}
   972  		if have != test.want {
   973  			t.Errorf("test#%d: EvalSymlinks(%q) returns %q, want %q", i, test.path, have, test.want)
   974  		}
   975  	}
   976  }
   977  
   978  // Test directories relative to temporary directory.
   979  // The tests are run in absTestDirs[0].
   980  var absTestDirs = []string{
   981  	"a",
   982  	"a/b",
   983  	"a/b/c",
   984  }
   985  
   986  // Test paths relative to temporary directory. $ expands to the directory.
   987  // The tests are run in absTestDirs[0].
   988  // We create absTestDirs first.
   989  var absTests = []string{
   990  	".",
   991  	"b",
   992  	"b/",
   993  	"../a",
   994  	"../a/b",
   995  	"../a/b/./c/../../.././a",
   996  	"../a/b/./c/../../.././a/",
   997  	"$",
   998  	"$/.",
   999  	"$/a/../a/b",
  1000  	"$/a/b/c/../../.././a",
  1001  	"$/a/b/c/../../.././a/",
  1002  }
  1003  
  1004  func TestAbs(t *testing.T) {
  1005  	root, err := ioutil.TempDir("", "TestAbs")
  1006  	if err != nil {
  1007  		t.Fatal("TempDir failed: ", err)
  1008  	}
  1009  	defer os.RemoveAll(root)
  1010  
  1011  	wd, err := os.Getwd()
  1012  	if err != nil {
  1013  		t.Fatal("getwd failed: ", err)
  1014  	}
  1015  	err = os.Chdir(root)
  1016  	if err != nil {
  1017  		t.Fatal("chdir failed: ", err)
  1018  	}
  1019  	defer os.Chdir(wd)
  1020  
  1021  	for _, dir := range absTestDirs {
  1022  		err = os.Mkdir(dir, 0777)
  1023  		if err != nil {
  1024  			t.Fatal("Mkdir failed: ", err)
  1025  		}
  1026  	}
  1027  
  1028  	if runtime.GOOS == "windows" {
  1029  		vol := filepath.VolumeName(root)
  1030  		var extra []string
  1031  		for _, path := range absTests {
  1032  			if strings.Contains(path, "$") {
  1033  				continue
  1034  			}
  1035  			path = vol + path
  1036  			extra = append(extra, path)
  1037  		}
  1038  		absTests = append(absTests, extra...)
  1039  	}
  1040  
  1041  	err = os.Chdir(absTestDirs[0])
  1042  	if err != nil {
  1043  		t.Fatal("chdir failed: ", err)
  1044  	}
  1045  
  1046  	for _, path := range absTests {
  1047  		path = strings.Replace(path, "$", root, -1)
  1048  		info, err := os.Stat(path)
  1049  		if err != nil {
  1050  			t.Errorf("%s: %s", path, err)
  1051  			continue
  1052  		}
  1053  
  1054  		abspath, err := filepath.Abs(path)
  1055  		if err != nil {
  1056  			t.Errorf("Abs(%q) error: %v", path, err)
  1057  			continue
  1058  		}
  1059  		absinfo, err := os.Stat(abspath)
  1060  		if err != nil || !os.SameFile(absinfo, info) {
  1061  			t.Errorf("Abs(%q)=%q, not the same file", path, abspath)
  1062  		}
  1063  		if !filepath.IsAbs(abspath) {
  1064  			t.Errorf("Abs(%q)=%q, not an absolute path", path, abspath)
  1065  		}
  1066  		if filepath.IsAbs(abspath) && abspath != filepath.Clean(abspath) {
  1067  			t.Errorf("Abs(%q)=%q, isn't clean", path, abspath)
  1068  		}
  1069  	}
  1070  }
  1071  
  1072  // Empty path needs to be special-cased on Windows. See golang.org/issue/24441.
  1073  // We test it separately from all other absTests because the empty string is not
  1074  // a valid path, so it can't be used with os.Stat.
  1075  func TestAbsEmptyString(t *testing.T) {
  1076  	root, err := ioutil.TempDir("", "TestAbsEmptyString")
  1077  	if err != nil {
  1078  		t.Fatal("TempDir failed: ", err)
  1079  	}
  1080  	defer os.RemoveAll(root)
  1081  
  1082  	wd, err := os.Getwd()
  1083  	if err != nil {
  1084  		t.Fatal("getwd failed: ", err)
  1085  	}
  1086  	err = os.Chdir(root)
  1087  	if err != nil {
  1088  		t.Fatal("chdir failed: ", err)
  1089  	}
  1090  	defer os.Chdir(wd)
  1091  
  1092  	info, err := os.Stat(root)
  1093  	if err != nil {
  1094  		t.Fatalf("%s: %s", root, err)
  1095  	}
  1096  
  1097  	abspath, err := filepath.Abs("")
  1098  	if err != nil {
  1099  		t.Fatalf(`Abs("") error: %v`, err)
  1100  	}
  1101  	absinfo, err := os.Stat(abspath)
  1102  	if err != nil || !os.SameFile(absinfo, info) {
  1103  		t.Errorf(`Abs("")=%q, not the same file`, abspath)
  1104  	}
  1105  	if !filepath.IsAbs(abspath) {
  1106  		t.Errorf(`Abs("")=%q, not an absolute path`, abspath)
  1107  	}
  1108  	if filepath.IsAbs(abspath) && abspath != filepath.Clean(abspath) {
  1109  		t.Errorf(`Abs("")=%q, isn't clean`, abspath)
  1110  	}
  1111  }
  1112  
  1113  type RelTests struct {
  1114  	root, path, want string
  1115  }
  1116  
  1117  var reltests = []RelTests{
  1118  	{"a/b", "a/b", "."},
  1119  	{"a/b/.", "a/b", "."},
  1120  	{"a/b", "a/b/.", "."},
  1121  	{"./a/b", "a/b", "."},
  1122  	{"a/b", "./a/b", "."},
  1123  	{"ab/cd", "ab/cde", "../cde"},
  1124  	{"ab/cd", "ab/c", "../c"},
  1125  	{"a/b", "a/b/c/d", "c/d"},
  1126  	{"a/b", "a/b/../c", "../c"},
  1127  	{"a/b/../c", "a/b", "../b"},
  1128  	{"a/b/c", "a/c/d", "../../c/d"},
  1129  	{"a/b", "c/d", "../../c/d"},
  1130  	{"a/b/c/d", "a/b", "../.."},
  1131  	{"a/b/c/d", "a/b/", "../.."},
  1132  	{"a/b/c/d/", "a/b", "../.."},
  1133  	{"a/b/c/d/", "a/b/", "../.."},
  1134  	{"../../a/b", "../../a/b/c/d", "c/d"},
  1135  	{"/a/b", "/a/b", "."},
  1136  	{"/a/b/.", "/a/b", "."},
  1137  	{"/a/b", "/a/b/.", "."},
  1138  	{"/ab/cd", "/ab/cde", "../cde"},
  1139  	{"/ab/cd", "/ab/c", "../c"},
  1140  	{"/a/b", "/a/b/c/d", "c/d"},
  1141  	{"/a/b", "/a/b/../c", "../c"},
  1142  	{"/a/b/../c", "/a/b", "../b"},
  1143  	{"/a/b/c", "/a/c/d", "../../c/d"},
  1144  	{"/a/b", "/c/d", "../../c/d"},
  1145  	{"/a/b/c/d", "/a/b", "../.."},
  1146  	{"/a/b/c/d", "/a/b/", "../.."},
  1147  	{"/a/b/c/d/", "/a/b", "../.."},
  1148  	{"/a/b/c/d/", "/a/b/", "../.."},
  1149  	{"/../../a/b", "/../../a/b/c/d", "c/d"},
  1150  	{".", "a/b", "a/b"},
  1151  	{".", "..", ".."},
  1152  
  1153  	// can't do purely lexically
  1154  	{"..", ".", "err"},
  1155  	{"..", "a", "err"},
  1156  	{"../..", "..", "err"},
  1157  	{"a", "/a", "err"},
  1158  	{"/a", "a", "err"},
  1159  }
  1160  
  1161  var winreltests = []RelTests{
  1162  	{`C:a\b\c`, `C:a/b/d`, `..\d`},
  1163  	{`C:\`, `D:\`, `err`},
  1164  	{`C:`, `D:`, `err`},
  1165  	{`C:\Projects`, `c:\projects\src`, `src`},
  1166  	{`C:\Projects`, `c:\projects`, `.`},
  1167  	{`C:\Projects\a\..`, `c:\projects`, `.`},
  1168  }
  1169  
  1170  func TestRel(t *testing.T) {
  1171  	tests := append([]RelTests{}, reltests...)
  1172  	if runtime.GOOS == "windows" {
  1173  		for i := range tests {
  1174  			tests[i].want = filepath.FromSlash(tests[i].want)
  1175  		}
  1176  		tests = append(tests, winreltests...)
  1177  	}
  1178  	for _, test := range tests {
  1179  		got, err := filepath.Rel(test.root, test.path)
  1180  		if test.want == "err" {
  1181  			if err == nil {
  1182  				t.Errorf("Rel(%q, %q)=%q, want error", test.root, test.path, got)
  1183  			}
  1184  			continue
  1185  		}
  1186  		if err != nil {
  1187  			t.Errorf("Rel(%q, %q): want %q, got error: %s", test.root, test.path, test.want, err)
  1188  		}
  1189  		if got != test.want {
  1190  			t.Errorf("Rel(%q, %q)=%q, want %q", test.root, test.path, got, test.want)
  1191  		}
  1192  	}
  1193  }
  1194  
  1195  type VolumeNameTest struct {
  1196  	path string
  1197  	vol  string
  1198  }
  1199  
  1200  var volumenametests = []VolumeNameTest{
  1201  	{`c:/foo/bar`, `c:`},
  1202  	{`c:`, `c:`},
  1203  	{`2:`, ``},
  1204  	{``, ``},
  1205  	{`\\\host`, ``},
  1206  	{`\\\host\`, ``},
  1207  	{`\\\host\share`, ``},
  1208  	{`\\\host\\share`, ``},
  1209  	{`\\host`, ``},
  1210  	{`//host`, ``},
  1211  	{`\\host\`, ``},
  1212  	{`//host/`, ``},
  1213  	{`\\host\share`, `\\host\share`},
  1214  	{`//host/share`, `//host/share`},
  1215  	{`\\host\share\`, `\\host\share`},
  1216  	{`//host/share/`, `//host/share`},
  1217  	{`\\host\share\foo`, `\\host\share`},
  1218  	{`//host/share/foo`, `//host/share`},
  1219  	{`\\host\share\\foo\\\bar\\\\baz`, `\\host\share`},
  1220  	{`//host/share//foo///bar////baz`, `//host/share`},
  1221  	{`\\host\share\foo\..\bar`, `\\host\share`},
  1222  	{`//host/share/foo/../bar`, `//host/share`},
  1223  }
  1224  
  1225  func TestVolumeName(t *testing.T) {
  1226  	if runtime.GOOS != "windows" {
  1227  		return
  1228  	}
  1229  	for _, v := range volumenametests {
  1230  		if vol := filepath.VolumeName(v.path); vol != v.vol {
  1231  			t.Errorf("VolumeName(%q)=%q, want %q", v.path, vol, v.vol)
  1232  		}
  1233  	}
  1234  }
  1235  
  1236  func TestDriveLetterInEvalSymlinks(t *testing.T) {
  1237  	if runtime.GOOS != "windows" {
  1238  		return
  1239  	}
  1240  	wd, _ := os.Getwd()
  1241  	if len(wd) < 3 {
  1242  		t.Errorf("Current directory path %q is too short", wd)
  1243  	}
  1244  	lp := strings.ToLower(wd)
  1245  	up := strings.ToUpper(wd)
  1246  	flp, err := filepath.EvalSymlinks(lp)
  1247  	if err != nil {
  1248  		t.Fatalf("EvalSymlinks(%q) failed: %q", lp, err)
  1249  	}
  1250  	fup, err := filepath.EvalSymlinks(up)
  1251  	if err != nil {
  1252  		t.Fatalf("EvalSymlinks(%q) failed: %q", up, err)
  1253  	}
  1254  	if flp != fup {
  1255  		t.Errorf("Results of EvalSymlinks do not match: %q and %q", flp, fup)
  1256  	}
  1257  }
  1258  
  1259  func TestBug3486(t *testing.T) { // https://golang.org/issue/3486
  1260  	if runtime.GOOS == "darwin" {
  1261  		switch runtime.GOARCH {
  1262  		case "arm", "arm64":
  1263  			t.Skipf("skipping on %s/%s", runtime.GOOS, runtime.GOARCH)
  1264  		}
  1265  	}
  1266  	root, err := filepath.EvalSymlinks(runtime.GOROOT() + "/test")
  1267  	if err != nil {
  1268  		t.Fatal(err)
  1269  	}
  1270  	bugs := filepath.Join(root, "fixedbugs")
  1271  	ken := filepath.Join(root, "ken")
  1272  	seenBugs := false
  1273  	seenKen := false
  1274  	err = filepath.Walk(root, func(pth string, info os.FileInfo, err error) error {
  1275  		if err != nil {
  1276  			t.Fatal(err)
  1277  		}
  1278  
  1279  		switch pth {
  1280  		case bugs:
  1281  			seenBugs = true
  1282  			return filepath.SkipDir
  1283  		case ken:
  1284  			if !seenBugs {
  1285  				t.Fatal("filepath.Walk out of order - ken before fixedbugs")
  1286  			}
  1287  			seenKen = true
  1288  		}
  1289  		return nil
  1290  	})
  1291  	if err != nil {
  1292  		t.Fatal(err)
  1293  	}
  1294  	if !seenKen {
  1295  		t.Fatalf("%q not seen", ken)
  1296  	}
  1297  }
  1298  
  1299  func testWalkSymlink(t *testing.T, mklink func(target, link string) error) {
  1300  	tmpdir, err := ioutil.TempDir("", "testWalkSymlink")
  1301  	if err != nil {
  1302  		t.Fatal(err)
  1303  	}
  1304  	defer os.RemoveAll(tmpdir)
  1305  
  1306  	wd, err := os.Getwd()
  1307  	if err != nil {
  1308  		t.Fatal(err)
  1309  	}
  1310  	defer os.Chdir(wd)
  1311  
  1312  	err = os.Chdir(tmpdir)
  1313  	if err != nil {
  1314  		t.Fatal(err)
  1315  	}
  1316  
  1317  	err = mklink(tmpdir, "link")
  1318  	if err != nil {
  1319  		t.Fatal(err)
  1320  	}
  1321  
  1322  	var visited []string
  1323  	err = filepath.Walk(tmpdir, func(path string, info os.FileInfo, err error) error {
  1324  		if err != nil {
  1325  			t.Fatal(err)
  1326  		}
  1327  		rel, err := filepath.Rel(tmpdir, path)
  1328  		if err != nil {
  1329  			t.Fatal(err)
  1330  		}
  1331  		visited = append(visited, rel)
  1332  		return nil
  1333  	})
  1334  	if err != nil {
  1335  		t.Fatal(err)
  1336  	}
  1337  	sort.Strings(visited)
  1338  	want := []string{".", "link"}
  1339  	if fmt.Sprintf("%q", visited) != fmt.Sprintf("%q", want) {
  1340  		t.Errorf("unexpected paths visited %q, want %q", visited, want)
  1341  	}
  1342  }
  1343  
  1344  func TestWalkSymlink(t *testing.T) {
  1345  	testenv.MustHaveSymlink(t)
  1346  	testWalkSymlink(t, os.Symlink)
  1347  }
  1348  

View as plain text