...

Source file src/io/fs/sub_test.go

Documentation: io/fs

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

View as plain text