github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/io/fs/glob_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 . "io/fs" 9 "os" 10 "path" 11 "testing" 12 ) 13 14 var globTests = []struct { 15 fs FS 16 pattern, result string 17 }{ 18 {os.DirFS("."), "glob.go", "glob.go"}, 19 {os.DirFS("."), "gl?b.go", "glob.go"}, 20 {os.DirFS("."), "*", "glob.go"}, 21 {os.DirFS(".."), "*/glob.go", "fs/glob.go"}, 22 } 23 24 func TestGlob(t *testing.T) { 25 for _, tt := range globTests { 26 matches, err := Glob(tt.fs, tt.pattern) 27 if err != nil { 28 t.Errorf("Glob error for %q: %s", tt.pattern, err) 29 continue 30 } 31 if !contains(matches, tt.result) { 32 t.Errorf("Glob(%#q) = %#v want %v", tt.pattern, matches, tt.result) 33 } 34 } 35 for _, pattern := range []string{"no_match", "../*/no_match"} { 36 matches, err := Glob(os.DirFS("."), pattern) 37 if err != nil { 38 t.Errorf("Glob error for %q: %s", pattern, err) 39 continue 40 } 41 if len(matches) != 0 { 42 t.Errorf("Glob(%#q) = %#v want []", pattern, matches) 43 } 44 } 45 } 46 47 func TestGlobError(t *testing.T) { 48 bad := []string{`[]`, `nonexist/[]`} 49 for _, pattern := range bad { 50 _, err := Glob(os.DirFS("."), pattern) 51 if err != path.ErrBadPattern { 52 t.Errorf("Glob(fs, %#q) returned err=%v, want path.ErrBadPattern", pattern, err) 53 } 54 } 55 } 56 57 // contains reports whether vector contains the string s. 58 func contains(vector []string, s string) bool { 59 for _, elem := range vector { 60 if elem == s { 61 return true 62 } 63 } 64 return false 65 } 66 67 type globOnly struct{ GlobFS } 68 69 func (globOnly) Open(name string) (File, error) { return nil, ErrNotExist } 70 71 func TestGlobMethod(t *testing.T) { 72 check := func(desc string, names []string, err error) { 73 t.Helper() 74 if err != nil || len(names) != 1 || names[0] != "hello.txt" { 75 t.Errorf("Glob(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt"}) 76 } 77 } 78 79 // Test that ReadDir uses the method when present. 80 names, err := Glob(globOnly{testFsys}, "*.txt") 81 check("readDirOnly", names, err) 82 83 // Test that ReadDir uses Open when the method is not present. 84 names, err = Glob(openOnly{testFsys}, "*.txt") 85 check("openOnly", names, err) 86 }