Files
magpie/internal/agent/statkind_test.go
T
yetone e3ab7f3bf7 agent: isDir, isFile and Taken make no os.FileInfo on unix
Detection asks isDir, isFile and Taken of about a thousand paths on each
of the window's 15s /api/drift asks. os.Stat made an os.FileInfo on the
heap for each, a fifth of what forty asks allocated with real accounts.
statKind calls syscall.Stat into a Stat_t on the stack (retrying EINTR,
following links as os.Stat does); only the path made a C string is
left. Windows keeps os.Stat (statkind_other.go).

Run:
- TestStatKindAnswersWithoutAFileInfo: folder, file, gone, a path under
  a file, "" and a link to a folder answer as os.Stat did; two looks
  take 2 allocations. Broken by hand (statKind through os.Stat): red, 4.
- go test ./internal/agent on mote; go vet ./internal/agent for darwin,
  windows and linux.
- Real accounts (sandbox HOME on mote, 40 /api/drift asks), paired:
  os.Stat's allocations 4.6 and 4.1 MB before (t24), 1.0 and 1.5 MB
  after (t25); totals 25.0 and 22.6 MB before, 18.4 and 22.0 MB after.
2026-11-10 06:00:10 +08:00

47 lines
1.2 KiB
Go

package agent
import (
"os"
"path/filepath"
"runtime"
"testing"
)
// isDir, isFile and Taken answer as os.Stat would, and on unix make no
// os.FileInfo: detection asks them of some thousand paths a drift ask.
func TestStatKindAnswersWithoutAFileInfo(t *testing.T) {
d := t.TempDir()
f := filepath.Join(d, "f")
if err := os.WriteFile(f, nil, 0o644); err != nil {
t.Fatal(err)
}
link := filepath.Join(d, "to-dir")
linked := os.Symlink(d, link) == nil
gone := filepath.Join(d, "gone")
for _, c := range []struct {
p string
dir, file bool
taken bool
}{
{d, true, false, false},
{f, false, true, true},
{gone, false, false, false},
{filepath.Join(f, "under"), false, false, true},
{"", false, false, false},
} {
if isDir(c.p) != c.dir || isFile(c.p) != c.file || Taken(c.p) != c.taken {
t.Errorf("%q: isDir %v isFile %v Taken %v", c.p, isDir(c.p), isFile(c.p), Taken(c.p))
}
}
if linked && !isDir(link) {
t.Error("a link to a folder is a folder, as os.Stat follows it")
}
if runtime.GOOS == "windows" {
return
}
// the path made a C string is all there is to it
if n := testing.AllocsPerRun(50, func() { isDir(d); isFile(f) }); n > 2 {
t.Fatalf("%v allocations for two looks", n)
}
}