2023-03-28 22:48:58 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
2023-08-11 13:12:13 +00:00
|
|
|
// SPDX-License-Identifier: BUSL-1.1
|
2023-03-28 22:48:58 +00:00
|
|
|
|
2021-01-15 23:28:32 +00:00
|
|
|
package golden
|
|
|
|
|
|
|
|
import (
|
|
|
|
"flag"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
|
|
|
// update allows golden files to be updated based on the current output.
|
|
|
|
var update = flag.Bool("update", false, "update golden files")
|
|
|
|
|
|
|
|
// Get reads the expected value from the file at filename and returns the value.
|
|
|
|
// filename is relative to the ./testdata directory.
|
|
|
|
//
|
|
|
|
// If the `-update` flag is used with `go test`, the golden file will be updated
|
|
|
|
// to the value of actual.
|
|
|
|
func Get(t *testing.T, actual, filename string) string {
|
|
|
|
t.Helper()
|
2024-03-14 16:59:06 +00:00
|
|
|
return string(GetBytes(t, []byte(actual), filename))
|
2023-09-12 01:17:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetBytes reads the expected value from the file at filename and returns the
|
|
|
|
// value as a byte array. filename is relative to the ./testdata directory.
|
|
|
|
//
|
|
|
|
// If the `-update` flag is used with `go test`, the golden file will be updated
|
|
|
|
// to the value of actual.
|
2024-03-14 16:59:06 +00:00
|
|
|
func GetBytes(t *testing.T, actual []byte, filename string) []byte {
|
2023-09-12 01:17:56 +00:00
|
|
|
t.Helper()
|
2021-01-15 23:28:32 +00:00
|
|
|
|
|
|
|
path := filepath.Join("testdata", filename)
|
|
|
|
if *update {
|
|
|
|
if dir := filepath.Dir(path); dir != "." {
|
|
|
|
require.NoError(t, os.MkdirAll(dir, 0755))
|
|
|
|
}
|
2024-03-14 16:59:06 +00:00
|
|
|
err := os.WriteFile(path, actual, 0644)
|
2021-01-15 23:28:32 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
}
|
|
|
|
|
2023-10-24 15:33:23 +00:00
|
|
|
return GetBytesAtFilePath(t, path)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetBytes reads the expected value from the file at filepath and returns the
|
|
|
|
// value as a byte array. filepath is relative to the ./testdata directory.
|
|
|
|
func GetBytesAtFilePath(t *testing.T, filepath string) []byte {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
expected, err := os.ReadFile(filepath)
|
2021-01-15 23:28:32 +00:00
|
|
|
require.NoError(t, err)
|
2023-09-12 01:17:56 +00:00
|
|
|
return expected
|
2021-01-15 23:28:32 +00:00
|
|
|
}
|