Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions testutil/golden.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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) != "" {
Comment thread
abiduke612 marked this conversation as resolved.
if err := os.MkdirAll(filepath.Dir(golden), 0755); err != nil {
t.Fatalf("failed to create fixture directory: %v", err)
}
Expand All @@ -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
Expand All @@ -77,7 +78,8 @@ type options struct {
Suffix string
Extension string

SubDir string
SubDir string
UpdateEnv string
}

type option func(*options)
Expand All @@ -100,6 +102,12 @@ func WithSubDir(subDir string) option {
}
}

func WithUpdateEnv(env string) option {
return func(opts *options) {
opts.UpdateEnv = env
}
}
Comment thread
abiduke612 marked this conversation as resolved.

// golden determines the golden file to use
func golden(t *testing.T, opts *options) (string, error) {
if opts.Extension == "" {
Expand Down
Loading