glob_test.go 2.3 KB

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