github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/io/fs/readdir_test.go (about) 1 // Copyright 2020 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 fs_test 6 7 import ( 8 "errors" 9 . "io/fs" 10 "os" 11 "testing" 12 "testing/fstest" 13 "time" 14 ) 15 16 type readDirOnly struct{ ReadDirFS } 17 18 func (readDirOnly) Open(name string) (File, error) { return nil, ErrNotExist } 19 20 func TestReadDir(t *testing.T) { 21 check := func(desc string, dirs []DirEntry, err error) { 22 t.Helper() 23 if err != nil || len(dirs) != 2 || dirs[0].Name() != "hello.txt" || dirs[1].Name() != "sub" { 24 var names []string 25 for _, d := range dirs { 26 names = append(names, d.Name()) 27 } 28 t.Errorf("ReadDir(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt", "sub"}) 29 } 30 } 31 32 // Test that ReadDir uses the method when present. 33 dirs, err := ReadDir(readDirOnly{testFsys}, ".") 34 check("readDirOnly", dirs, err) 35 36 // Test that ReadDir uses Open when the method is not present. 37 dirs, err = ReadDir(openOnly{testFsys}, ".") 38 check("openOnly", dirs, err) 39 40 // Test that ReadDir on Sub of . works (sub_test checks non-trivial subs). 41 sub, err := Sub(testFsys, ".") 42 if err != nil { 43 t.Fatal(err) 44 } 45 dirs, err = ReadDir(sub, ".") 46 check("sub(.)", dirs, err) 47 } 48 49 func TestFileInfoToDirEntry(t *testing.T) { 50 testFs := fstest.MapFS{ 51 "notadir.txt": { 52 Data: []byte("hello, world"), 53 Mode: 0, 54 ModTime: time.Now(), 55 Sys: &sysValue, 56 }, 57 "adir": { 58 Data: nil, 59 Mode: os.ModeDir, 60 ModTime: time.Now(), 61 Sys: &sysValue, 62 }, 63 } 64 65 tests := []struct { 66 path string 67 wantMode FileMode 68 wantDir bool 69 }{ 70 {path: "notadir.txt", wantMode: 0, wantDir: false}, 71 {path: "adir", wantMode: os.ModeDir, wantDir: true}, 72 } 73 74 for _, test := range tests { 75 test := test 76 t.Run(test.path, func(t *testing.T) { 77 fi, err := Stat(testFs, test.path) 78 if err != nil { 79 t.Fatal(err) 80 } 81 82 dirEntry := FileInfoToDirEntry(fi) 83 if g, w := dirEntry.Type(), test.wantMode; g != w { 84 t.Errorf("FileMode mismatch: got=%v, want=%v", g, w) 85 } 86 if g, w := dirEntry.Name(), test.path; g != w { 87 t.Errorf("Name mismatch: got=%v, want=%v", g, w) 88 } 89 if g, w := dirEntry.IsDir(), test.wantDir; g != w { 90 t.Errorf("IsDir mismatch: got=%v, want=%v", g, w) 91 } 92 }) 93 } 94 } 95 96 func errorPath(err error) string { 97 var perr *PathError 98 if !errors.As(err, &perr) { 99 return "" 100 } 101 return perr.Path 102 } 103 104 func TestReadDirPath(t *testing.T) { 105 fsys := os.DirFS(t.TempDir()) 106 _, err1 := ReadDir(fsys, "non-existent") 107 _, err2 := ReadDir(struct{ FS }{fsys}, "non-existent") 108 if s1, s2 := errorPath(err1), errorPath(err2); s1 != s2 { 109 t.Fatalf("s1: %s != s2: %s", s1, s2) 110 } 111 }