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