github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/testutil/must.go (about)

     1  package testutil
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"path/filepath"
     7  )
     8  
     9  // MustPipe calls os.Pipe. It panics if an error occurs.
    10  func MustPipe() (*os.File, *os.File) {
    11  	r, w, err := os.Pipe()
    12  	Must(err)
    13  	return r, w
    14  }
    15  
    16  // MustReadAllAndClose reads all bytes and closes the ReadCloser. It panics if
    17  // an error occurs.
    18  func MustReadAllAndClose(r io.ReadCloser) []byte {
    19  	bs, err := io.ReadAll(r)
    20  	Must(err)
    21  	Must(r.Close())
    22  	return bs
    23  }
    24  
    25  // MustMkdirAll calls os.MkdirAll for each argument. It panics if an error
    26  // occurs.
    27  func MustMkdirAll(names ...string) {
    28  	for _, name := range names {
    29  		Must(os.MkdirAll(name, 0700))
    30  	}
    31  }
    32  
    33  // MustCreateEmpty creates empty file, after creating all ancestor directories
    34  // that don't exist. It panics if an error occurs.
    35  func MustCreateEmpty(names ...string) {
    36  	for _, name := range names {
    37  		Must(os.MkdirAll(filepath.Dir(name), 0700))
    38  		file, err := os.Create(name)
    39  		Must(err)
    40  		Must(file.Close())
    41  	}
    42  }
    43  
    44  // MustWriteFile writes data to a file, after creating all ancestor directories
    45  // that don't exist. It panics if an error occurs.
    46  func MustWriteFile(filename, data string) {
    47  	Must(os.MkdirAll(filepath.Dir(filename), 0700))
    48  	Must(os.WriteFile(filename, []byte(data), 0600))
    49  }
    50  
    51  // MustChdir calls os.Chdir and panics if it fails.
    52  func MustChdir(dir string) {
    53  	Must(os.Chdir(dir))
    54  }
    55  
    56  // Must panics if the error value is not nil. It is typically used like this:
    57  //
    58  //   testutil.Must(someFunction(...))
    59  //
    60  // Where someFunction returns a single error value. This is useful with
    61  // functions like os.Mkdir to succinctly ensure the test fails to proceed if an
    62  // operation required for the test setup results in an error.
    63  func Must(err error) {
    64  	if err != nil {
    65  		panic(err)
    66  	}
    67  }