Hermetic Filesystem With fstest.MapFS
Feed code an in-memory fstest.MapFS so file-reading logic is tested against fixed content, with no temp directories or disk fixtures to clean up.
Code
package main
import (
"fmt"
"io/fs"
"testing/fstest"
)
// 依赖只认 io/fs 抽象,生产传 os.DirFS,测试传 MapFS
func totalSize(root fs.FS) (int64, error) {
var total int64
err := fs.WalkDir(root, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
info, err := d.Info()
if err != nil {
return err
}
total += info.Size()
return nil
})
return total, err
}
func main() {
memory := fstest.MapFS{
"bundle/app.js": {Data: []byte("console.log('hi')")},
"bundle/lib.css": {Data: []byte("body{}")},
"README.md": {Data: []byte("# demo")},
}
size, err := totalSize(memory)
if err != nil {
fmt.Println("walk failed:", err)
return
}
fmt.Println("total bytes:", size)
matches, _ := fs.Glob(memory, "bundle/*")
fmt.Println("bundle files:", matches)
}What the code does
Hermetic Filesystem With fstest.MapFS is built around the functions totalSize and main.
Nothing falls through silently — 3 checkpoints test err != nil on the way through.
Points of care
- The function reports failure by returning
error— callers branch on it before touching other results.
Applying it
Entry signature: func totalSize(root fs.FS) (int64, error)
Running the file prints labeled results such as walk failed:, total bytes:, bundle files: — each operation’s effect is visible in the output.
The sequence totalSize lives in main; running the file triggers it.
Statements that matter most here
if err != nil || d.IsDir() {
return err
}
if err != nil {
return err
}
if err != nil {
fmt.Println("walk failed:", err)
return
}
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How does the code signal failure?
- Through `error` values, not panics — the snippet checks `err != nil` at 3 sites.
- What does Hermetic Filesystem With fstest.MapFS print when run?
- Invoke the file as-is — the `walk failed:`, `total bytes:`, `bundle files:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.