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.

GoData Integrity

Code

gosnippet
42 lines
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

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.