github.com/k8snetworkplumbingwg/sriov-network-operator@v1.2.1-0.20240408194816-2d2e5a45d453/test/util/fakefilesystem/fakefilesystem.go (about)

     1  package fakefilesystem
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path"
     7  )
     8  
     9  // FS allows to setup isolated fake files structure used for the tests.
    10  type FS struct {
    11  	Dirs     []string
    12  	Files    map[string][]byte
    13  	Symlinks map[string]string
    14  }
    15  
    16  // Use function creates entire files structure and returns a function to tear it down.
    17  // Example usage:
    18  //
    19  // ```
    20  // rootDir, fakeFsClean, err := defer fs.Use()
    21  // if err != nil { ... }
    22  // defer fakeFsClean()
    23  // ````
    24  func (f *FS) Use() (string, func(), error) {
    25  	// create the new fake fs root dir in /tmp/sriov...
    26  	rootDir, err := os.MkdirTemp("", "sriov-operator")
    27  	if err != nil {
    28  		return "", nil, fmt.Errorf("error creating fake root dir: %w", err)
    29  	}
    30  
    31  	for _, dir := range f.Dirs {
    32  		err := os.MkdirAll(path.Join(rootDir, dir), 0755)
    33  		if err != nil {
    34  			return "", nil, fmt.Errorf("error creating fake directory: %w", err)
    35  		}
    36  	}
    37  
    38  	for filename, body := range f.Files {
    39  		err := os.WriteFile(path.Join(rootDir, filename), body, 0600)
    40  		if err != nil {
    41  			return "", nil, fmt.Errorf("error creating fake file: %w", err)
    42  		}
    43  	}
    44  
    45  	for link, target := range f.Symlinks {
    46  		err = os.Symlink(target, path.Join(rootDir, link))
    47  		if err != nil {
    48  			return "", nil, fmt.Errorf("error creating fake symlink: %w", err)
    49  		}
    50  	}
    51  
    52  	return rootDir, func() {
    53  		// remove temporary fake fs
    54  		err := os.RemoveAll(rootDir)
    55  		if err != nil {
    56  			panic(fmt.Errorf("error tearing down fake filesystem: %w", err))
    57  		}
    58  	}, nil
    59  }