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