File size: 1,864 Bytes
de452ad | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 | // 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"
"os"
"testing"
"testing/fstest"
"time"
)
var testFsys = fstest.MapFS{
"hello.txt": {
Data: []byte("hello, world"),
Mode: 0456,
ModTime: time.Now(),
Sys: &sysValue,
},
"sub/goodbye.txt": {
Data: []byte("goodbye, world"),
Mode: 0456,
ModTime: time.Now(),
Sys: &sysValue,
},
}
var sysValue int
type readFileOnly struct{ ReadFileFS }
func (readFileOnly) Open(name string) (File, error) { return nil, ErrNotExist }
type openOnly struct{ FS }
func TestReadFile(t *testing.T) {
// Test that ReadFile uses the method when present.
data, err := ReadFile(readFileOnly{testFsys}, "hello.txt")
if string(data) != "hello, world" || err != nil {
t.Fatalf(`ReadFile(readFileOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
}
// Test that ReadFile uses Open when the method is not present.
data, err = ReadFile(openOnly{testFsys}, "hello.txt")
if string(data) != "hello, world" || err != nil {
t.Fatalf(`ReadFile(openOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
}
// Test that ReadFile on Sub of . works (sub_test checks non-trivial subs).
sub, err := Sub(testFsys, ".")
if err != nil {
t.Fatal(err)
}
data, err = ReadFile(sub, "hello.txt")
if string(data) != "hello, world" || err != nil {
t.Fatalf(`ReadFile(sub(.), "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
}
}
func TestReadFilePath(t *testing.T) {
fsys := os.DirFS(t.TempDir())
_, err1 := ReadFile(fsys, "non-existent")
_, err2 := ReadFile(struct{ FS }{fsys}, "non-existent")
if s1, s2 := errorPath(err1), errorPath(err2); s1 != s2 {
t.Fatalf("s1: %s != s2: %s", s1, s2)
}
}
|