github.com/AndrienkoAleksandr/go@v0.0.19/src/testing/fstest/testfs_test.go (about)

     1  // Copyright 2021 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 fstest
     6  
     7  import (
     8  	"internal/testenv"
     9  	"io/fs"
    10  	"os"
    11  	"path/filepath"
    12  	"sort"
    13  	"testing"
    14  )
    15  
    16  func TestSymlink(t *testing.T) {
    17  	testenv.MustHaveSymlink(t)
    18  
    19  	tmp := t.TempDir()
    20  	tmpfs := os.DirFS(tmp)
    21  
    22  	if err := os.WriteFile(filepath.Join(tmp, "hello"), []byte("hello, world\n"), 0644); err != nil {
    23  		t.Fatal(err)
    24  	}
    25  
    26  	if err := os.Symlink(filepath.Join(tmp, "hello"), filepath.Join(tmp, "hello.link")); err != nil {
    27  		t.Fatal(err)
    28  	}
    29  
    30  	if err := TestFS(tmpfs, "hello", "hello.link"); err != nil {
    31  		t.Fatal(err)
    32  	}
    33  }
    34  
    35  func TestDash(t *testing.T) {
    36  	m := MapFS{
    37  		"a-b/a": {Data: []byte("a-b/a")},
    38  	}
    39  	if err := TestFS(m, "a-b/a"); err != nil {
    40  		t.Error(err)
    41  	}
    42  }
    43  
    44  type shuffledFS MapFS
    45  
    46  func (fsys shuffledFS) Open(name string) (fs.File, error) {
    47  	f, err := MapFS(fsys).Open(name)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	return &shuffledFile{File: f}, nil
    52  }
    53  
    54  type shuffledFile struct{ fs.File }
    55  
    56  func (f *shuffledFile) ReadDir(n int) ([]fs.DirEntry, error) {
    57  	dirents, err := f.File.(fs.ReadDirFile).ReadDir(n)
    58  	// Shuffle in a deterministic way, all we care about is making sure that the
    59  	// list of directory entries is not is the lexicographic order.
    60  	//
    61  	// We do this to make sure that the TestFS test suite is not affected by the
    62  	// order of directory entries.
    63  	sort.Slice(dirents, func(i, j int) bool {
    64  		return dirents[i].Name() > dirents[j].Name()
    65  	})
    66  	return dirents, err
    67  }
    68  
    69  func TestShuffledFS(t *testing.T) {
    70  	fsys := shuffledFS{
    71  		"tmp/one":   {Data: []byte("1")},
    72  		"tmp/two":   {Data: []byte("2")},
    73  		"tmp/three": {Data: []byte("3")},
    74  	}
    75  	if err := TestFS(fsys, "tmp/one", "tmp/two", "tmp/three"); err != nil {
    76  		t.Error(err)
    77  	}
    78  }