1
2
3
4
5 package fstest
6
7 import (
8 "errors"
9 "internal/testenv"
10 "io/fs"
11 "os"
12 "path/filepath"
13 "slices"
14 "strings"
15 "testing"
16 )
17
18 func TestSymlink(t *testing.T) {
19 testenv.MustHaveSymlink(t)
20
21 tmp := t.TempDir()
22 tmpfs := os.DirFS(tmp)
23
24 if err := os.WriteFile(filepath.Join(tmp, "hello"), []byte("hello, world\n"), 0644); err != nil {
25 t.Fatal(err)
26 }
27
28 if err := os.Symlink(filepath.Join(tmp, "hello"), filepath.Join(tmp, "hello.link")); err != nil {
29 t.Fatal(err)
30 }
31
32 if err := TestFS(tmpfs, "hello", "hello.link"); err != nil {
33 t.Fatal(err)
34 }
35 }
36
37 func TestDash(t *testing.T) {
38 m := MapFS{
39 "a-b/a": {Data: []byte("a-b/a")},
40 }
41 if err := TestFS(m, "a-b/a"); err != nil {
42 t.Error(err)
43 }
44 }
45
46 type shuffledFS MapFS
47
48 func (fsys shuffledFS) Open(name string) (fs.File, error) {
49 f, err := MapFS(fsys).Open(name)
50 if err != nil {
51 return nil, err
52 }
53 return &shuffledFile{File: f}, nil
54 }
55
56 type shuffledFile struct{ fs.File }
57
58 func (f *shuffledFile) ReadDir(n int) ([]fs.DirEntry, error) {
59 dirents, err := f.File.(fs.ReadDirFile).ReadDir(n)
60
61
62
63
64
65 slices.SortFunc(dirents, func(a, b fs.DirEntry) int {
66 return strings.Compare(b.Name(), a.Name())
67 })
68 return dirents, err
69 }
70
71 func TestShuffledFS(t *testing.T) {
72 fsys := shuffledFS{
73 "tmp/one": {Data: []byte("1")},
74 "tmp/two": {Data: []byte("2")},
75 "tmp/three": {Data: []byte("3")},
76 }
77 if err := TestFS(fsys, "tmp/one", "tmp/two", "tmp/three"); err != nil {
78 t.Error(err)
79 }
80 }
81
82
83 type failPermFS struct{}
84
85 func (f failPermFS) Open(name string) (fs.File, error) {
86 if !fs.ValidPath(name) {
87 return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrInvalid}
88 }
89 return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrPermission}
90 }
91
92 func TestTestFSWrappedErrors(t *testing.T) {
93 err := TestFS(failPermFS{})
94 if err == nil {
95 t.Fatal("error expected")
96 }
97 t.Logf("Error (expecting wrapped fs.ErrPermission):\n%v", err)
98
99 if !errors.Is(err, fs.ErrPermission) {
100 t.Errorf("error should be a wrapped ErrPermission: %#v", err)
101 }
102
103
104
105 var errs interface{ Unwrap() []error }
106 if !errors.As(err, &errs) {
107 t.Errorf("caller should be able to extract the errors as a list: %#v", err)
108 } else {
109 for _, err := range errs.Unwrap() {
110
111
112 if !errors.Is(err, fs.ErrPermission) {
113 t.Errorf("unexpected error: %v", err)
114 }
115 }
116 }
117 }
118
View as plain text