| 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 |
"testing" |
| 11 |
"testing/fstest" |
| 12 |
"time" |
| 13 |
) |
| 14 |
|
| 15 |
var testFsys = fstest.MapFS{ |
| 16 |
"hello.txt": { |
| 17 |
Data: []byte("hello, world"), |
| 18 |
Mode: 0456, |
| 19 |
ModTime: time.Now(), |
| 20 |
Sys: &sysValue, |
| 21 |
}, |
| 22 |
"sub/goodbye.txt": { |
| 23 |
Data: []byte("goodbye, world"), |
| 24 |
Mode: 0456, |
| 25 |
ModTime: time.Now(), |
| 26 |
Sys: &sysValue, |
| 27 |
}, |
| 28 |
} |
| 29 |
|
| 30 |
var sysValue int |
| 31 |
|
| 32 |
type readFileOnly struct{ ReadFileFS } |
| 33 |
|
| 34 |
func (readFileOnly) Open(name string) (File, error) { return nil, ErrNotExist } |
| 35 |
|
| 36 |
type openOnly struct{ FS } |
| 37 |
|
| 38 |
func TestReadFile(t *testing.T) { |
| 39 |
// Test that ReadFile uses the method when present. |
| 40 |
data, err := ReadFile(readFileOnly{testFsys}, "hello.txt") |
| 41 |
if string(data) != "hello, world" || err != nil { |
| 42 |
t.Fatalf(`ReadFile(readFileOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world") |
| 43 |
} |
| 44 |
|
| 45 |
// Test that ReadFile uses Open when the method is not present. |
| 46 |
data, err = ReadFile(openOnly{testFsys}, "hello.txt") |
| 47 |
if string(data) != "hello, world" || err != nil { |
| 48 |
t.Fatalf(`ReadFile(openOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world") |
| 49 |
} |
| 50 |
|
| 51 |
// Test that ReadFile on Sub of . works (sub_test checks non-trivial subs). |
| 52 |
sub, err := Sub(testFsys, ".") |
| 53 |
if err != nil { |
| 54 |
t.Fatal(err) |
| 55 |
} |
| 56 |
data, err = ReadFile(sub, "hello.txt") |
| 57 |
if string(data) != "hello, world" || err != nil { |
| 58 |
t.Fatalf(`ReadFile(sub(.), "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world") |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
func TestReadFilePath(t *testing.T) { |
| 63 |
fsys := os.DirFS(t.TempDir()) |
| 64 |
_, err1 := ReadFile(fsys, "non-existent") |
| 65 |
_, err2 := ReadFile(struct{ FS }{fsys}, "non-existent") |
| 66 |
if s1, s2 := errorPath(err1), errorPath(err2); s1 != s2 { |
| 67 |
t.Fatalf("s1: %s != s2: %s", s1, s2) |
| 68 |
} |
| 69 |
} |