diff --git a/testutil/golden.go b/testutil/golden.go index 66e2a6c..2f31e0b 100644 --- a/testutil/golden.go +++ b/testutil/golden.go @@ -22,13 +22,14 @@ func CompareFileWithFixture(t *testing.T, outputFile string, opts ...option) { } // CompareWithFixture will compare output with a test fixture and allows to automatically update them -// by setting the UPDATE env var. +// by setting the UPDATE env var (configurable via WithUpdateEnv, defaulting to "UPDATE"). // If output is not a []byte or string, it will get serialized as yaml prior to the comparison. // The fixtures are stored in $PWD/testdata/prefix${testName}.yaml func CompareWithFixture(t *testing.T, output interface{}, opts ...option) string { t.Helper() options := &options{ Extension: ".yaml", + UpdateEnv: "UPDATE", } for _, opt := range opts { opt(options) @@ -52,7 +53,7 @@ func CompareWithFixture(t *testing.T, output interface{}, opts ...option) string if err != nil { t.Fatalf("failed to get absolute path to testdata file: %v", err) } - if os.Getenv("UPDATE") != "" { + if os.Getenv(options.UpdateEnv) != "" { if err := os.MkdirAll(filepath.Dir(golden), 0755); err != nil { t.Fatalf("failed to create fixture directory: %v", err) } @@ -66,7 +67,7 @@ func CompareWithFixture(t *testing.T, output interface{}, opts ...option) string } if diff := cmp.Diff(string(expected), string(serializedOutput)); diff != "" { - t.Errorf("got diff between expected and actual result:\nfile: %s\ndiff:\n%s\n\nIf this is expected, re-run the test with `UPDATE=true go test ./...` to update the fixtures.", golden, diff) + t.Errorf("got diff between expected and actual result:\nfile: %s\ndiff:\n%s\n\nIf this is expected, re-run the test with `%s=1 go test ./...` to update the fixtures.", golden, diff, options.UpdateEnv) } return golden @@ -77,7 +78,8 @@ type options struct { Suffix string Extension string - SubDir string + SubDir string + UpdateEnv string } type option func(*options) @@ -100,6 +102,12 @@ func WithSubDir(subDir string) option { } } +func WithUpdateEnv(env string) option { + return func(opts *options) { + opts.UpdateEnv = env + } +} + // golden determines the golden file to use func golden(t *testing.T, opts *options) (string, error) { if opts.Extension == "" {