summaryrefslogtreecommitdiffstats
path: root/src/io/fs/sub_test.go
blob: 451b0efb02f1856b4cf1c4f31f2b1879dfc97170 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fs_test

import (
	. "io/fs"
	"testing"
)

type subOnly struct{ SubFS }

func (subOnly) Open(name string) (File, error) { return nil, ErrNotExist }

func TestSub(t *testing.T) {
	check := func(desc string, sub FS, err error) {
		t.Helper()
		if err != nil {
			t.Errorf("Sub(sub): %v", err)
			return
		}
		data, err := ReadFile(sub, "goodbye.txt")
		if string(data) != "goodbye, world" || err != nil {
			t.Errorf(`ReadFile(%s, "goodbye.txt" = %q, %v, want %q, nil`, desc, string(data), err, "goodbye, world")
		}

		dirs, err := ReadDir(sub, ".")
		if err != nil || len(dirs) != 1 || dirs[0].Name() != "goodbye.txt" {
			var names []string
			for _, d := range dirs {
				names = append(names, d.Name())
			}
			t.Errorf(`ReadDir(%s, ".") = %v, %v, want %v, nil`, desc, names, err, []string{"goodbye.txt"})
		}
	}

	// Test that Sub uses the method when present.
	sub, err := Sub(subOnly{testFsys}, "sub")
	check("subOnly", sub, err)

	// Test that Sub uses Open when the method is not present.
	sub, err = Sub(openOnly{testFsys}, "sub")
	check("openOnly", sub, err)

	_, err = sub.Open("nonexist")
	if err == nil {
		t.Fatal("Open(nonexist): succeeded")
	}
	pe, ok := err.(*PathError)
	if !ok {
		t.Fatalf("Open(nonexist): error is %T, want *PathError", err)
	}
	if pe.Path != "nonexist" {
		t.Fatalf("Open(nonexist): err.Path = %q, want %q", pe.Path, "nonexist")
	}
}