github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/internal/test/golden.go (about)

     1  package test
     2  
     3  import (
     4  	"io/fs"
     5  	"os"
     6  	"path/filepath"
     7  	"strconv"
     8  	"testing"
     9  )
    10  
    11  // Update indicates whether golden files should be updated.
    12  var Update, _ = strconv.ParseBool(os.Getenv("UPDATE_GOLDEN")) //nolint:gochecknoglobals
    13  
    14  type PathFilter func(path string) bool
    15  
    16  // Ignore returns a PathFilter that ignores files matching the given globs.
    17  func Ignore(globs ...string) PathFilter {
    18  	return func(path string) bool {
    19  		for _, glob := range globs {
    20  			if ok, _ := filepath.Match(glob, filepath.Base(path)); ok {
    21  				return false
    22  			}
    23  			if ok, _ := filepath.Match(glob, path); ok {
    24  				return false
    25  			}
    26  		}
    27  		return true
    28  	}
    29  }
    30  
    31  // Golden compares the result directory to the golden directory and updates the
    32  // golden directory if the UPDATE_GOLDEN environment variable is set.
    33  func Golden(t *testing.T, golden, result string, filter ...PathFilter) {
    34  	t.Helper()
    35  
    36  	if !Update {
    37  		return
    38  	}
    39  
    40  	t.Cleanup(func() {
    41  		if err := os.RemoveAll(golden); err != nil {
    42  			t.Fatal("failed to remove golden files:", err)
    43  		}
    44  
    45  		from := os.DirFS(result)
    46  		err := fs.WalkDir(from, ".", func(path string, d fs.DirEntry, err error) error {
    47  			if err != nil || d.IsDir() {
    48  				return err
    49  			}
    50  
    51  			for _, f := range filter {
    52  				if !f(path) {
    53  					return nil
    54  				}
    55  			}
    56  
    57  			if err = os.MkdirAll(filepath.Join(golden, filepath.Dir(path)), 0o755); err != nil {
    58  				return err
    59  			}
    60  			if err = os.Rename(filepath.Join(result, path), filepath.Join(golden, path)); err != nil {
    61  				return err
    62  			}
    63  			return nil
    64  		})
    65  		if err != nil {
    66  			t.Fatal("failed to update golden files:", err)
    67  		}
    68  	})
    69  }