tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/engine/fs/fstest/fstest.go (about)

     1  package fstest
     2  
     3  import (
     4  	"io/fs"
     5  	"path/filepath"
     6  	"testing"
     7  
     8  	"tractor.dev/toolkit-go/engine/fs/fsutil"
     9  )
    10  
    11  func must(t *testing.T, err error) {
    12  	t.Helper()
    13  	if err != nil {
    14  		t.Fatal(err)
    15  	}
    16  }
    17  
    18  func ReadFS(t *testing.T, fsys fs.FS) map[string]string {
    19  	fsmap := map[string]string{}
    20  	must(t, fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
    21  		if err != nil {
    22  			return err
    23  		}
    24  
    25  		if d.IsDir() {
    26  			fsmap[path+"/"] = ""
    27  			return nil
    28  		}
    29  		b, err := fs.ReadFile(fsys, path)
    30  		if err != nil {
    31  			return err
    32  		}
    33  		fsmap[path] = string(b)
    34  		return nil
    35  	}))
    36  	return fsmap
    37  }
    38  
    39  func CheckFS(t *testing.T, fsys fs.FS, expect map[string]string) {
    40  	fsmap := ReadFS(t, fsys)
    41  	for path, contents := range expect {
    42  		c, ok := fsmap[path]
    43  		if !ok {
    44  			t.Fatal("path not found:", path)
    45  		}
    46  		if c != contents {
    47  			t.Fatalf("unexpected contents for %s: got %#v, want %#v", path, c, contents)
    48  		}
    49  	}
    50  }
    51  
    52  func WriteFS(t *testing.T, fsys fs.FS, fsmap map[string]string) {
    53  	for path, contents := range fsmap {
    54  		must(t, fsutil.MkdirAll(fsys, filepath.Dir(path), 0755))
    55  		must(t, fsutil.WriteFile(fsys, path, []byte(contents), 0644))
    56  	}
    57  }