github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/uefivars/vartest/test.go (about)

     1  // Copyright 2020 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  //
     5  // SPDX-License-Identifier: BSD-3-Clause
     6  //
     7  
     8  // Package vartest contains utility functions for testing uefivars and
     9  // subpackages. It is unlikely to be useful outside of testing.
    10  package vartest
    11  
    12  import (
    13  	"archive/zip"
    14  	"io"
    15  	"io/ioutil"
    16  	"os"
    17  	fp "path/filepath"
    18  )
    19  
    20  // Extracts testdata zip for use as efivars in tests. Used in uefivars and subpackages.
    21  func SetupVarZip(path string) (efiVarDir string, cleanup func(), err error) {
    22  	efiVarDir, err = ioutil.TempDir("", "gotest-uefivars")
    23  	if err != nil {
    24  		return
    25  	}
    26  	defer func() {
    27  		if err != nil {
    28  			os.RemoveAll(efiVarDir)
    29  		}
    30  	}()
    31  	z, err := zip.OpenReader(path)
    32  	if err != nil {
    33  		return
    34  	}
    35  	defer z.Close()
    36  	for _, zf := range z.File {
    37  		fname := fp.Join(efiVarDir, zf.Name)
    38  		if zf.FileInfo().IsDir() {
    39  			err = os.MkdirAll(fname, zf.FileInfo().Mode())
    40  			if err != nil {
    41  				return
    42  			}
    43  		} else {
    44  			var fo *os.File
    45  			fo, err = os.Create(fname)
    46  			if err != nil {
    47  				return
    48  			}
    49  			var fi io.ReadCloser
    50  			fi, err = zf.Open()
    51  			if err != nil {
    52  				return
    53  			}
    54  			_, err = io.Copy(fo, fi)
    55  			if err != nil {
    56  				return
    57  			}
    58  			fo.Close()
    59  		}
    60  	}
    61  	cleanup = func() { os.RemoveAll(efiVarDir) }
    62  	return
    63  }