...

Source file src/io/fs/readdir_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  	"os"
		10  	"testing"
		11  	"testing/fstest"
		12  	"time"
		13  )
		14  
		15  type readDirOnly struct{ ReadDirFS }
		16  
		17  func (readDirOnly) Open(name string) (File, error) { return nil, ErrNotExist }
		18  
		19  func TestReadDir(t *testing.T) {
		20  	check := func(desc string, dirs []DirEntry, err error) {
		21  		t.Helper()
		22  		if err != nil || len(dirs) != 2 || dirs[0].Name() != "hello.txt" || dirs[1].Name() != "sub" {
		23  			var names []string
		24  			for _, d := range dirs {
		25  				names = append(names, d.Name())
		26  			}
		27  			t.Errorf("ReadDir(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt", "sub"})
		28  		}
		29  	}
		30  
		31  	// Test that ReadDir uses the method when present.
		32  	dirs, err := ReadDir(readDirOnly{testFsys}, ".")
		33  	check("readDirOnly", dirs, err)
		34  
		35  	// Test that ReadDir uses Open when the method is not present.
		36  	dirs, err = ReadDir(openOnly{testFsys}, ".")
		37  	check("openOnly", dirs, err)
		38  
		39  	// Test that ReadDir on Sub of . works (sub_test checks non-trivial subs).
		40  	sub, err := Sub(testFsys, ".")
		41  	if err != nil {
		42  		t.Fatal(err)
		43  	}
		44  	dirs, err = ReadDir(sub, ".")
		45  	check("sub(.)", dirs, err)
		46  }
		47  
		48  func TestFileInfoToDirEntry(t *testing.T) {
		49  	testFs := fstest.MapFS{
		50  		"notadir.txt": {
		51  			Data:		[]byte("hello, world"),
		52  			Mode:		0,
		53  			ModTime: time.Now(),
		54  			Sys:		 &sysValue,
		55  		},
		56  		"adir": {
		57  			Data:		nil,
		58  			Mode:		os.ModeDir,
		59  			ModTime: time.Now(),
		60  			Sys:		 &sysValue,
		61  		},
		62  	}
		63  
		64  	tests := []struct {
		65  		path		 string
		66  		wantMode FileMode
		67  		wantDir	bool
		68  	}{
		69  		{path: "notadir.txt", wantMode: 0, wantDir: false},
		70  		{path: "adir", wantMode: os.ModeDir, wantDir: true},
		71  	}
		72  
		73  	for _, test := range tests {
		74  		test := test
		75  		t.Run(test.path, func(t *testing.T) {
		76  			fi, err := Stat(testFs, test.path)
		77  			if err != nil {
		78  				t.Fatal(err)
		79  			}
		80  
		81  			dirEntry := FileInfoToDirEntry(fi)
		82  			if g, w := dirEntry.Type(), test.wantMode; g != w {
		83  				t.Errorf("FileMode mismatch: got=%v, want=%v", g, w)
		84  			}
		85  			if g, w := dirEntry.Name(), test.path; g != w {
		86  				t.Errorf("Name mismatch: got=%v, want=%v", g, w)
		87  			}
		88  			if g, w := dirEntry.IsDir(), test.wantDir; g != w {
		89  				t.Errorf("IsDir mismatch: got=%v, want=%v", g, w)
		90  			}
		91  		})
		92  	}
		93  }
		94  

View as plain text