test: add fstree helper to build, snapshot and diff directory trees

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 22:57:11 +03:00
parent 05da3c0d30
commit ffcc8f5806
2 changed files with 386 additions and 0 deletions

View file

@ -0,0 +1,320 @@
// Package fstree builds, snapshots and compares directory trees in tests.
//
// spec := fstree.Spec{
// fstree.File("a.txt", "hello"),
// fstree.Dir("ro").WithMode(0o555),
// fstree.File("ro/b.bin", "").WithSize(1 << 20),
// fstree.Symlink("link", "a.txt"),
// }
// fstree.Build(t, src, spec)
// ... copy src -> dst ...
// fstree.Equal(t, fstree.Snapshot(t, src), fstree.Snapshot(t, dst), fstree.Opts{Mode: true, Links: true})
package fstree
import (
"bytes"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"sort"
"strings"
"syscall"
"testing"
"time"
)
// Kind of a tree node.
type Kind int
const (
KindFile Kind = iota
KindDir
KindSymlink
KindFIFO
KindOther
)
func (k Kind) String() string {
switch k {
case KindFile:
return "file"
case KindDir:
return "dir"
case KindSymlink:
return "symlink"
case KindFIFO:
return "fifo"
}
return "other"
}
// Entry describes one node to create. Path is slash-separated and relative
// to the root passed to Build.
type Entry struct {
Path string
Kind Kind
Content []byte
// Size, when > 0 and Content is empty, fills the file with a
// deterministic pattern of that many bytes.
Size int64
// Mode is the permission bits; 0 means 0644 for files/FIFOs, 0755 for dirs.
Mode fs.FileMode
// MTime is applied after the whole tree is built; zero leaves it alone
// (and means "don't care" when the spec is used as an expectation).
MTime time.Time
Target string // symlink target
}
// File, Dir, Symlink and FIFO construct entries.
func File(p, content string) Entry { return Entry{Path: p, Kind: KindFile, Content: []byte(content)} }
func Dir(p string) Entry { return Entry{Path: p, Kind: KindDir} }
func Symlink(p, target string) Entry {
return Entry{Path: p, Kind: KindSymlink, Target: target}
}
func FIFO(p string) Entry { return Entry{Path: p, Kind: KindFIFO} }
// WithMode, WithMTime and WithSize return a modified copy.
func (e Entry) WithMode(m fs.FileMode) Entry { e.Mode = m; return e }
func (e Entry) WithMTime(t time.Time) Entry { e.MTime = t; return e }
func (e Entry) WithSize(n int64) Entry { e.Size = n; return e }
func (e Entry) WithContent(b []byte) Entry { e.Content = b; return e }
// Spec is a list of entries; parents are created implicitly (0755).
type Spec []Entry
func (e Entry) data() []byte {
if len(e.Content) > 0 || e.Size <= 0 {
return e.Content
}
b := make([]byte, e.Size)
for i := range b {
b[i] = byte(i % 251)
}
return b
}
func (e Entry) perm() fs.FileMode {
if e.Mode != 0 {
return e.Mode.Perm()
}
if e.Kind == KindDir {
return 0o755
}
return 0o644
}
// Build creates spec under root (which must exist). Directory modes and all
// mtimes are applied after every node exists, deepest first, so a 0555
// directory can still be populated. A Cleanup restores write permission on
// directories so t.TempDir removal works.
func Build(t testing.TB, root string, spec Spec) {
t.Helper()
sorted := append(Spec(nil), spec...)
sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path })
var dirs []string
t.Cleanup(func() {
for _, d := range dirs {
os.Chmod(d, 0o755)
}
})
for _, e := range sorted {
p := filepath.Join(root, filepath.FromSlash(e.Path))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatalf("fstree: %v", err)
}
var err error
switch e.Kind {
case KindFile:
err = os.WriteFile(p, e.data(), 0o600)
if err == nil {
err = os.Chmod(p, e.perm())
}
case KindDir:
err = os.MkdirAll(p, 0o755)
dirs = append(dirs, p)
case KindSymlink:
err = os.Symlink(e.Target, p)
case KindFIFO:
err = syscall.Mkfifo(p, 0o600)
if err == nil {
err = os.Chmod(p, e.perm())
}
default:
err = fmt.Errorf("unsupported kind %v", e.Kind)
}
if err != nil {
t.Fatalf("fstree: build %s: %v", e.Path, err)
}
}
// Deepest first so setting a parent's mtime/mode comes last.
for i := len(sorted) - 1; i >= 0; i-- {
e := sorted[i]
p := filepath.Join(root, filepath.FromSlash(e.Path))
if !e.MTime.IsZero() && e.Kind != KindSymlink {
if err := os.Chtimes(p, e.MTime, e.MTime); err != nil {
t.Fatalf("fstree: chtimes %s: %v", e.Path, err)
}
}
if e.Kind == KindDir {
if err := os.Chmod(p, e.perm()); err != nil {
t.Fatalf("fstree: chmod %s: %v", e.Path, err)
}
}
}
}
// Node is one entry of a snapshot.
type Node struct {
Kind Kind
Mode fs.FileMode // permission bits; 0 in an expectation means "don't care"
Data []byte // file content
MTime time.Time // zero in an expectation means "don't care"
Target string // symlink target
}
// Tree maps slash-separated relative paths to nodes (root excluded).
type Tree map[string]Node
// FromSpec turns a spec into the tree Build would produce, for use as an
// expectation. Implicit parent directories are included with mode 0755.
func FromSpec(spec Spec) Tree {
tr := Tree{}
for _, e := range spec {
for d := path.Dir(e.Path); d != "." && d != "/"; d = path.Dir(d) {
if _, ok := tr[d]; !ok {
tr[d] = Node{Kind: KindDir, Mode: 0o755}
}
}
n := Node{Kind: e.Kind, Mode: e.perm(), MTime: e.MTime}
switch e.Kind {
case KindFile:
n.Data = e.data()
case KindSymlink:
n.Mode, n.MTime, n.Target = 0, time.Time{}, e.Target
}
tr[e.Path] = n
}
return tr
}
// Snapshot reads the tree under root without following symlinks.
func Snapshot(t testing.TB, root string) Tree {
t.Helper()
tr := Tree{}
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if p == root {
return nil
}
rel, _ := filepath.Rel(root, p)
rel = filepath.ToSlash(rel)
info, err := d.Info()
if err != nil {
return err
}
n := Node{Mode: info.Mode().Perm(), MTime: info.ModTime()}
switch m := info.Mode(); {
case m.IsRegular():
n.Kind = KindFile
b, err := os.ReadFile(p)
if err != nil {
return err
}
n.Data = b
case m.IsDir():
n.Kind = KindDir
case m&fs.ModeSymlink != 0:
n.Kind = KindSymlink
n.Target, err = os.Readlink(p)
if err != nil {
return err
}
case m&fs.ModeNamedPipe != 0:
n.Kind = KindFIFO
default:
n.Kind = KindOther
}
tr[rel] = n
return nil
})
if err != nil {
t.Fatalf("fstree: snapshot %s: %v", root, err)
}
return tr
}
// Opts selects what Equal compares besides kind and file content.
type Opts struct {
Mode bool // permission bits (skipped where want.Mode == 0)
MTime bool // mtime at 1 s granularity (skipped where want.MTime is zero); dirs included
Links bool // compare symlinks and their targets; false ignores symlinks on both sides
}
// Diff returns human-readable differences between want and got, sorted.
func Diff(want, got Tree, o Opts) []string {
var out []string
keys := map[string]bool{}
for k := range want {
keys[k] = true
}
for k := range got {
keys[k] = true
}
sorted := make([]string, 0, len(keys))
for k := range keys {
sorted = append(sorted, k)
}
sort.Strings(sorted)
for _, k := range sorted {
w, wok := want[k]
g, gok := got[k]
if !o.Links && ((wok && w.Kind == KindSymlink) || (gok && g.Kind == KindSymlink)) {
continue
}
switch {
case !gok:
out = append(out, fmt.Sprintf("missing %s %s", w.Kind, k))
continue
case !wok:
out = append(out, fmt.Sprintf("unexpected %s %s", g.Kind, k))
continue
}
if w.Kind != g.Kind {
out = append(out, fmt.Sprintf("%s: kind want %s, got %s", k, w.Kind, g.Kind))
continue
}
if w.Kind == KindFile && !bytes.Equal(w.Data, g.Data) {
out = append(out, fmt.Sprintf("%s: content want %s, got %s", k, short(w.Data), short(g.Data)))
}
if w.Kind == KindSymlink && w.Target != g.Target {
out = append(out, fmt.Sprintf("%s: link target want %q, got %q", k, w.Target, g.Target))
}
if o.Mode && w.Kind != KindSymlink && w.Mode != 0 && w.Mode != g.Mode {
out = append(out, fmt.Sprintf("%s: mode want %04o, got %04o", k, w.Mode, g.Mode))
}
if o.MTime && w.Kind != KindSymlink && !w.MTime.IsZero() &&
!w.MTime.Truncate(time.Second).Equal(g.MTime.Truncate(time.Second)) {
out = append(out, fmt.Sprintf("%s: mtime want %s, got %s", k, w.MTime.Format(time.RFC3339), g.MTime.Format(time.RFC3339)))
}
}
return out
}
// Equal fails t with a readable diff if the trees differ.
func Equal(t testing.TB, want, got Tree, o Opts) {
t.Helper()
if d := Diff(want, got, o); len(d) > 0 {
t.Errorf("fstree: trees differ (%d):\n %s", len(d), strings.Join(d, "\n "))
}
}
func short(b []byte) string {
if len(b) <= 32 {
return fmt.Sprintf("%q", b)
}
return fmt.Sprintf("%d bytes %q...", len(b), b[:16])
}

View file

@ -0,0 +1,66 @@
package fstree
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestFstreeRoundTrip(t *testing.T) {
old := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC)
spec := Spec{
File("a.txt", "hello").WithMTime(old),
File("bin/run.sh", "#!/bin/sh\n").WithMode(0o755),
Dir("ro").WithMode(0o555).WithMTime(old),
File("ro/inside.bin", "").WithSize(100000),
Symlink("link", "a.txt"),
Symlink("broken", "/nonexistent/zzz"),
FIFO("pipe"),
Dir("empty"),
}
root := t.TempDir()
Build(t, root, spec)
st, err := os.Stat(filepath.Join(root, "ro"))
if err != nil || st.Mode().Perm() != 0o555 {
t.Fatalf("ro dir: %v %v", st, err)
}
got := Snapshot(t, root)
if got["ro/inside.bin"].Kind != KindFile || len(got["ro/inside.bin"].Data) != 100000 {
t.Fatalf("sized file not built: %+v", got["ro/inside.bin"].Kind)
}
Equal(t, FromSpec(spec), got, Opts{Mode: true, MTime: true, Links: true})
// A second build of the same spec is equal, including mode and mtime.
root2 := t.TempDir()
Build(t, root2, spec)
Equal(t, got, Snapshot(t, root2), Opts{Mode: true, Links: true})
}
func TestFstreeDiffReportsDifferences(t *testing.T) {
want := FromSpec(Spec{
File("a", "x"),
File("b", "y").WithMode(0o600),
Symlink("l", "a"),
Dir("d"),
})
got := FromSpec(Spec{
File("a", "z"),
File("b", "y").WithMode(0o644),
Symlink("l", "b"),
File("d", ""),
File("extra", ""),
})
d := Diff(want, got, Opts{Mode: true, Links: true})
joined := strings.Join(d, "\n")
for _, s := range []string{"a: content", "b: mode want 0600, got 0644", "l: link target", "d: kind want dir, got file", "unexpected file extra"} {
if !strings.Contains(joined, s) {
t.Errorf("diff lacks %q:\n%s", s, joined)
}
}
if d := Diff(want, got, Opts{}); strings.Contains(strings.Join(d, "\n"), "link target") {
t.Errorf("Links=false must ignore symlinks: %v", d)
}
}