1 // Copyright (c) 2014-2015 The Notify Authors. All rights reserved.
2 // Use of this source code is governed by the MIT license that can be
3 // found in the LICENSE file.
16 func tmpfile(s string) (string, error) {
17 f, err := ioutil.TempFile(filepath.Split(s))
21 if err = nonil(f.Sync(), f.Close()); err != nil {
27 func symlink(src, dst string) (string, error) {
28 name, err := tmpfile(dst)
32 if err = nonil(os.Remove(name), os.Symlink(src, name)); err != nil {
38 func removeall(s ...string) {
44 func TestCanonical(t *testing.T) {
47 t.Fatalf("os.Getwd()=%v", err)
49 wdsym, err := symlink(wd, "")
51 t.Fatalf(`symlink(%q, "")=%v`, wd, err)
53 td := filepath.Join(wd, "testdata")
54 tdsym, err := symlink(td, td)
56 t.Errorf("symlink(%q, %q)=%v", td, td, nonil(err, os.Remove(wdsym)))
58 defer removeall(wdsym, tdsym)
59 vfstxt := filepath.Join(td, "vfs.txt")
60 cases := [...]caseCanonical{
63 {filepath.Join(wdsym, "notify.go"), filepath.Join(wd, "notify.go")},
64 {filepath.Join(tdsym, "vfs.txt"), vfstxt},
65 {filepath.Join(wdsym, filepath.Base(tdsym), "vfs.txt"), vfstxt},
67 testCanonical(t, cases[:])
70 func TestCanonicalCircular(t *testing.T) {
71 tmp1, err := tmpfile("circular")
75 tmp2, err := tmpfile("circular")
77 t.Fatal(nonil(err, os.Remove(tmp1)))
79 defer removeall(tmp1, tmp2)
80 // Symlink tmp1 -> tmp2.
81 if err = nonil(os.Remove(tmp1), os.Symlink(tmp2, tmp1)); err != nil {
84 // Symlnik tmp2 -> tmp1.
85 if err = nonil(os.Remove(tmp2), os.Symlink(tmp1, tmp2)); err != nil {
88 if _, err = canonical(tmp1); err == nil {
89 t.Fatalf("want canonical(%q)!=nil", tmp1)
91 if _, ok := err.(*os.PathError); !ok {
92 t.Fatalf("want canonical(%q)=os.PathError; got %T", tmp1, err)
97 func TestCanonical_RelativeSymlink(t *testing.T) {
98 dir, err := ioutil.TempDir(wd, "")
100 t.Fatalf("TempDir()=%v", err)
103 path = filepath.Join(dir, filepath.FromSlash("a/b/c/d/e/f"))
104 realpath = filepath.Join(dir, filepath.FromSlash("a/b/x/y/z/d/e/f"))
105 rel = filepath.FromSlash("x/y/z/../z/../z")
106 chdir = filepath.Join(dir, filepath.FromSlash("a/b"))
108 defer os.RemoveAll(dir)
109 if err = os.MkdirAll(realpath, 0755); err != nil {
110 t.Fatalf("MkdirAll()=%v", err)
112 if err := os.Chdir(chdir); err != nil {
113 t.Fatalf("Chdir()=%v", err)
115 if err := nonil(os.Symlink(rel, "c"), os.Chdir(wd)); err != nil {
116 t.Fatalf("Symlink()=%v", err)
118 got, err := canonical(path)
120 t.Fatalf("canonical(%s)=%v", path, err)
123 t.Fatalf("want canonical()=%s; got %s", realpath, got)