...

Source file src/sigs.k8s.io/cli-utils/pkg/testutil/test-filesystem.go

Documentation: sigs.k8s.io/cli-utils/pkg/testutil

     1  // Copyright 2020 The Kubernetes Authors.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package testutil
     5  
     6  import (
     7  	"os"
     8  	"path/filepath"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  // TestFilesystem creates directories and files for testing
    15  type TestFilesystem struct {
    16  	// root is the tmp directory
    17  	root string
    18  }
    19  
    20  // Setupd creates directories in the test filesystem, returning
    21  // the TestFilesystem.
    22  func Setup(t *testing.T, dirs ...string) TestFilesystem {
    23  	tempDir := "" // Use the default temp directory
    24  	d, err := os.MkdirTemp(tempDir, "test-filesystem")
    25  	if !assert.NoError(t, err) {
    26  		assert.FailNow(t, err.Error())
    27  	}
    28  	err = os.Chdir(d)
    29  	if !assert.NoError(t, err) {
    30  		assert.FailNow(t, err.Error())
    31  	}
    32  	for _, s := range dirs {
    33  		err = os.MkdirAll(s, 0700)
    34  		if !assert.NoError(t, err) {
    35  			assert.FailNow(t, err.Error())
    36  		}
    37  	}
    38  	return TestFilesystem{root: d}
    39  }
    40  
    41  // GetRootDir returns the path to the root of the
    42  // test filesystem.
    43  func (tf TestFilesystem) GetRootDir() string {
    44  	return tf.root
    45  }
    46  
    47  // WriteFile writes a file in the test filesystem at relative "path"
    48  // containing the bytes "value".
    49  func (tf TestFilesystem) WriteFile(t *testing.T, path string, value []byte) {
    50  	err := os.MkdirAll(filepath.Dir(filepath.Join(tf.root, path)), 0700)
    51  	if !assert.NoError(t, err) {
    52  		assert.FailNow(t, err.Error())
    53  	}
    54  	err = os.WriteFile(filepath.Join(tf.root, path), value, 0600)
    55  	if !assert.NoError(t, err) {
    56  		assert.FailNow(t, err.Error())
    57  	}
    58  }
    59  
    60  // Clean deletes the test filesystem.
    61  func (tf TestFilesystem) Clean() {
    62  	os.RemoveAll(tf.root)
    63  }
    64  

View as plain text