sub_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. "testing"
  8. )
  9. type subOnly struct{ SubFS }
  10. func (subOnly) Open(name string) (File, error) { return nil, ErrNotExist }
  11. func TestSub(t *testing.T) {
  12. check := func(desc string, sub FS, err error) {
  13. t.Helper()
  14. if err != nil {
  15. t.Errorf("Sub(sub): %v", err)
  16. return
  17. }
  18. data, err := ReadFile(sub, "goodbye.txt")
  19. if string(data) != "goodbye, world" || err != nil {
  20. t.Errorf(`ReadFile(%s, "goodbye.txt" = %q, %v, want %q, nil`, desc, string(data), err, "goodbye, world")
  21. }
  22. dirs, err := ReadDir(sub, ".")
  23. if err != nil || len(dirs) != 1 || dirs[0].Name() != "goodbye.txt" {
  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{"goodbye.txt"})
  29. }
  30. }
  31. // Test that Sub uses the method when present.
  32. sub, err := Sub(subOnly{testFsys}, "sub")
  33. check("subOnly", sub, err)
  34. // Test that Sub uses Open when the method is not present.
  35. sub, err = Sub(openOnly{testFsys}, "sub")
  36. check("openOnly", sub, err)
  37. _, err = sub.Open("nonexist")
  38. if err == nil {
  39. t.Fatal("Open(nonexist): succeeded")
  40. }
  41. pe, ok := err.(*PathError)
  42. if !ok {
  43. t.Fatalf("Open(nonexist): error is %T, want *PathError", err)
  44. }
  45. if pe.Path != "nonexist" {
  46. t.Fatalf("Open(nonexist): err.Path = %q, want %q", pe.Path, "nonexist")
  47. }
  48. }